mcalc_builder.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. """
  2. @package modules::mcalc_builder
  3. @brief Map calculator, GUI wrapper for r.mapcalc
  4. Classes:
  5. - mcalc_builder::MapCalcFrame
  6. (C) 2008, 2011-2013 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Michael Barton, Arizona State University
  10. @author Martin Landa <landa.martin gmail.com>
  11. @author Tim Michelsen (load/save expression)
  12. """
  13. import os
  14. import re
  15. import wx
  16. import grass.script as grass
  17. from core import globalvar
  18. from core.gcmd import GError, RunCommand
  19. from core.giface import StandaloneGrassInterface
  20. from gui_core.gselect import Select
  21. from gui_core.forms import GUI
  22. from gui_core.widgets import IntegerValidator
  23. from gui_core.wrap import Button, ClearButton, CloseButton, TextCtrl, \
  24. StaticText, StaticBox
  25. from core.settings import UserSettings
  26. class MapCalcFrame(wx.Frame):
  27. """Mapcalc Frame class. Calculator-style window to create and run
  28. r(3).mapcalc statements.
  29. """
  30. def __init__(self, parent, giface, cmd, id=wx.ID_ANY,
  31. style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
  32. self.parent = parent
  33. self._giface = giface
  34. if self.parent:
  35. self.log = self.parent.GetLogWindow()
  36. else:
  37. self.log = None
  38. # grass command
  39. self.cmd = cmd
  40. if self.cmd == 'r.mapcalc':
  41. self.rast3d = False
  42. title = _('Raster Map Calculator')
  43. if self.cmd == 'r3.mapcalc':
  44. self.rast3d = True
  45. title = _('3D Raster Map Calculator')
  46. wx.Frame.__init__(self, parent, id=id, title=title, **kwargs)
  47. self.SetIcon(
  48. wx.Icon(
  49. os.path.join(
  50. globalvar.ICONDIR,
  51. 'grass.ico'),
  52. wx.BITMAP_TYPE_ICO))
  53. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  54. self.CreateStatusBar()
  55. #
  56. # variables
  57. #
  58. self.heading = _('mapcalc statement')
  59. self.funct_dict = {
  60. 'abs(x)': 'abs()',
  61. 'acos(x)': 'acos()',
  62. 'asin(x)': 'asin()',
  63. 'atan(x)': 'atan()',
  64. 'atan(x,y)': 'atan( , )',
  65. 'cos(x)': 'cos()',
  66. 'double(x)': 'double()',
  67. 'eval([x,y,...,]z)': 'eval()',
  68. 'exp(x)': 'exp()',
  69. 'exp(x,y)': 'exp( , )',
  70. 'float(x)': 'float()',
  71. 'graph(x,x1,y1[x2,y2..])': 'graph( , , )',
  72. 'if(x)': 'if()',
  73. 'if(x,a)': 'if( , )',
  74. 'if(x,a,b)': 'if( , , )',
  75. 'if(x,a,b,c)': 'if( , , , )',
  76. 'int(x)': 'int()',
  77. 'isnull(x)': 'isnull()',
  78. 'log(x)': 'log(',
  79. 'log(x,b)': 'log( , )',
  80. 'max(x,y[,z...])': 'max( , )',
  81. 'median(x,y[,z...])': 'median( , )',
  82. 'min(x,y[,z...])': 'min( , )',
  83. 'mode(x,y[,z...])': 'mode( , )',
  84. 'nmax(x,y[,z...])': 'nmax( , )',
  85. 'nmedian(x,y[,z...])': 'nmedian( , )',
  86. 'nmin(x,y[,z...])': 'nmin( , )',
  87. 'nmode(x,y[,z...])': 'nmode( , )',
  88. 'not(x)': 'not()',
  89. 'pow(x,y)': 'pow( , )',
  90. 'rand(a,b)': 'rand( , )',
  91. 'round(x)': 'round()',
  92. 'round(x,y)': 'round( , )',
  93. 'round(x,y,z)': 'round( , , )',
  94. 'sin(x)': 'sin()',
  95. 'sqrt(x)': 'sqrt()',
  96. 'tan(x)': 'tan()',
  97. 'xor(x,y)': 'xor( , )',
  98. 'row()': 'row()',
  99. 'col()': 'col()',
  100. 'nrows()': 'nrows()',
  101. 'ncols()': 'ncols()',
  102. 'x()': 'x()',
  103. 'y()': 'y()',
  104. 'ewres()': 'ewres()',
  105. 'nsres()': 'nsres()',
  106. 'area()': 'area()',
  107. 'null()': 'null()'
  108. }
  109. if self.rast3d:
  110. self.funct_dict['z()'] = 'z()'
  111. self.funct_dict['tbres()'] = 'tbres()'
  112. element = 'raster_3d'
  113. else:
  114. element = 'cell'
  115. # characters which can be in raster map name but the map name must be
  116. # then quoted
  117. self.charactersToQuote = '+-&!<>%~?^|'
  118. # stores last typed map name in Select widget to distinguish typing
  119. # from selection
  120. self.lastMapName = ''
  121. self.operatorBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  122. label=" %s " % _('Operators'))
  123. self.outputBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  124. label=" %s " % _('Output'))
  125. self.operandBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  126. label=" %s " % _('Operands'))
  127. self.expressBox = StaticBox(parent=self.panel, id=wx.ID_ANY,
  128. label=" %s " % _('Expression'))
  129. #
  130. # Buttons
  131. #
  132. self.btn_clear = ClearButton(parent=self.panel)
  133. self.btn_help = Button(parent=self.panel, id=wx.ID_HELP)
  134. self.btn_run = Button(
  135. parent=self.panel,
  136. id=wx.ID_ANY,
  137. label=_("&Run"))
  138. self.btn_run.SetDefault()
  139. self.btn_close = CloseButton(parent=self.panel)
  140. self.btn_save = Button(parent=self.panel, id=wx.ID_SAVE)
  141. self.btn_save.SetToolTip(_('Save expression to file'))
  142. self.btn_load = Button(parent=self.panel, id=wx.ID_ANY,
  143. label=_("&Load"))
  144. self.btn_load.SetToolTip(_('Load expression from file'))
  145. self.btn_copy = Button(
  146. parent=self.panel, id=wx.ID_ANY, label=_("Copy"))
  147. self.btn_copy.SetToolTip(
  148. _("Copy the current command string to the clipboard"))
  149. self.btn = dict()
  150. self.btn['pow'] = Button(parent=self.panel, id=wx.ID_ANY, label="^")
  151. self.btn['pow'].SetToolTip(_('exponent'))
  152. self.btn['div'] = Button(parent=self.panel, id=wx.ID_ANY, label="/")
  153. self.btn['div'].SetToolTip(_('divide'))
  154. self.btn['add'] = Button(parent=self.panel, id=wx.ID_ANY, label="+")
  155. self.btn['add'].SetToolTip(_('add'))
  156. self.btn['minus'] = Button(
  157. parent=self.panel, id=wx.ID_ANY, label="-")
  158. self.btn['minus'].SetToolTip(_('subtract'))
  159. self.btn['mod'] = Button(parent=self.panel, id=wx.ID_ANY, label="%")
  160. self.btn['mod'].SetToolTip(_('modulus'))
  161. self.btn['mult'] = Button(
  162. parent=self.panel, id=wx.ID_ANY, label="*")
  163. self.btn['mult'].SetToolTip(_('multiply'))
  164. self.btn['parenl'] = Button(
  165. parent=self.panel, id=wx.ID_ANY, label="(")
  166. self.btn['parenr'] = Button(
  167. parent=self.panel, id=wx.ID_ANY, label=")")
  168. self.btn['lshift'] = Button(
  169. parent=self.panel, id=wx.ID_ANY, label="<<")
  170. self.btn['lshift'].SetToolTip(_('left shift'))
  171. self.btn['rshift'] = Button(
  172. parent=self.panel, id=wx.ID_ANY, label=">>")
  173. self.btn['rshift'].SetToolTip(_('right shift'))
  174. self.btn['rshiftu'] = Button(
  175. parent=self.panel, id=wx.ID_ANY, label=">>>")
  176. self.btn['rshiftu'].SetToolTip(_('right shift (unsigned)'))
  177. self.btn['gt'] = Button(parent=self.panel, id=wx.ID_ANY, label=">")
  178. self.btn['gt'].SetToolTip(_('greater than'))
  179. self.btn['gteq'] = Button(
  180. parent=self.panel, id=wx.ID_ANY, label=">=")
  181. self.btn['gteq'].SetToolTip(_('greater than or equal to'))
  182. self.btn['lt'] = Button(parent=self.panel, id=wx.ID_ANY, label="<")
  183. self.btn['lt'].SetToolTip(_('less than'))
  184. self.btn['lteq'] = Button(
  185. parent=self.panel, id=wx.ID_ANY, label="<=")
  186. self.btn['lteq'].SetToolTip(_('less than or equal to'))
  187. self.btn['eq'] = Button(parent=self.panel, id=wx.ID_ANY, label="==")
  188. self.btn['eq'].SetToolTip(_('equal to'))
  189. self.btn['noteq'] = Button(
  190. parent=self.panel, id=wx.ID_ANY, label="!=")
  191. self.btn['noteq'].SetToolTip(_('not equal to'))
  192. self.btn['compl'] = Button(
  193. parent=self.panel, id=wx.ID_ANY, label="~")
  194. self.btn['compl'].SetToolTip(_('one\'s complement'))
  195. self.btn['not'] = Button(parent=self.panel, id=wx.ID_ANY, label="!")
  196. self.btn['not'].SetToolTip(_('NOT'))
  197. self.btn['andbit'] = Button(
  198. parent=self.panel, id=wx.ID_ANY, label='&&')
  199. self.btn['andbit'].SetToolTip(_('bitwise AND'))
  200. self.btn['orbit'] = Button(
  201. parent=self.panel, id=wx.ID_ANY, label="|")
  202. self.btn['orbit'].SetToolTip(_('bitwise OR'))
  203. self.btn['and'] = Button(
  204. parent=self.panel, id=wx.ID_ANY, label="&&&&")
  205. self.btn['and'].SetToolTip(_('logical AND'))
  206. self.btn['andnull'] = Button(
  207. parent=self.panel, id=wx.ID_ANY, label="&&&&&&")
  208. self.btn['andnull'].SetToolTip(_('logical AND (ignores NULLs)'))
  209. self.btn['or'] = Button(parent=self.panel, id=wx.ID_ANY, label="||")
  210. self.btn['or'].SetToolTip(_('logical OR'))
  211. self.btn['ornull'] = Button(
  212. parent=self.panel, id=wx.ID_ANY, label="|||")
  213. self.btn['ornull'].SetToolTip(_('logical OR (ignores NULLs)'))
  214. self.btn['cond'] = Button(
  215. parent=self.panel,
  216. id=wx.ID_ANY,
  217. label="a ? b : c")
  218. self.btn['cond'].SetToolTip(_('conditional'))
  219. #
  220. # Text area
  221. #
  222. self.text_mcalc = TextCtrl(
  223. parent=self.panel, id=wx.ID_ANY, size=(-1, 100),
  224. style=wx.TE_MULTILINE)
  225. wx.CallAfter(self.text_mcalc.SetFocus)
  226. #
  227. # Map and function insertion text and ComboBoxes
  228. self.newmaplabel = StaticText(parent=self.panel, id=wx.ID_ANY)
  229. if self.rast3d:
  230. self.newmaplabel.SetLabel(
  231. _('Name for new 3D raster map to create'))
  232. else:
  233. self.newmaplabel.SetLabel(_('Name for new raster map to create'))
  234. # As we can write only to current mapset, names should not be fully qualified
  235. # to not confuse end user about writing in other mapset
  236. self.newmaptxt = Select(
  237. parent=self.panel, id=wx.ID_ANY, size=(
  238. 250, -1), type=element, multiple=False,
  239. fullyQualified=False)
  240. self.mapsellabel = StaticText(parent=self.panel, id=wx.ID_ANY)
  241. if self.rast3d:
  242. self.mapsellabel.SetLabel(_('Insert existing 3D raster map'))
  243. else:
  244. self.mapsellabel.SetLabel(_('Insert existing raster map'))
  245. self.mapselect = Select(
  246. parent=self.panel, id=wx.ID_ANY, size=(
  247. 250, -1), type=element, multiple=False)
  248. self.functlabel = StaticText(parent=self.panel, id=wx.ID_ANY,
  249. label=_('Insert mapcalc function'))
  250. self.function = wx.ComboBox(
  251. parent=self.panel, id=wx.ID_ANY, size=(250, -1),
  252. choices=sorted(self.funct_dict.keys()),
  253. style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.TE_PROCESS_ENTER)
  254. self.overwrite = wx.CheckBox(
  255. parent=self.panel, id=wx.ID_ANY,
  256. label=_("Allow output files to overwrite existing files"))
  257. self.overwrite.SetValue(
  258. UserSettings.Get(
  259. group='cmd',
  260. key='overwrite',
  261. subkey='enabled'))
  262. self.randomSeed = wx.CheckBox(
  263. parent=self.panel,
  264. label=_("Generate random seed for rand()"))
  265. self.randomSeedStaticText = StaticText(
  266. parent=self.panel, label=_("Seed:"))
  267. self.randomSeedText = TextCtrl(parent=self.panel, size=(100, -1),
  268. validator=IntegerValidator())
  269. self.randomSeedText.SetToolTip(
  270. _("Integer seed for rand() function"))
  271. self.randomSeed.SetValue(True)
  272. self.randomSeedStaticText.Disable()
  273. self.randomSeedText.Disable()
  274. self.addbox = wx.CheckBox(
  275. parent=self.panel,
  276. label=_('Add created raster map into layer tree'),
  277. style=wx.NO_BORDER)
  278. self.addbox.SetValue(
  279. UserSettings.Get(
  280. group='cmd',
  281. key='addNewLayer',
  282. subkey='enabled'))
  283. if not self.parent or self.parent.GetName() != 'LayerManager':
  284. self.addbox.Hide()
  285. #
  286. # Bindings
  287. #
  288. for btn in self.btn.keys():
  289. self.btn[btn].Bind(wx.EVT_BUTTON, self.AddMark)
  290. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  291. self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
  292. self.btn_run.Bind(wx.EVT_BUTTON, self.OnMCalcRun)
  293. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  294. self.btn_save.Bind(wx.EVT_BUTTON, self.OnSaveExpression)
  295. self.btn_load.Bind(wx.EVT_BUTTON, self.OnLoadExpression)
  296. self.btn_copy.Bind(wx.EVT_BUTTON, self.OnCopyCommand)
  297. self.mapselect.Bind(wx.EVT_TEXT, self.OnSelect)
  298. self.function.Bind(wx.EVT_COMBOBOX, self._return_funct)
  299. self.function.Bind(wx.EVT_TEXT_ENTER, self.OnSelect)
  300. self.newmaptxt.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  301. self.text_mcalc.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  302. self.overwrite.Bind(wx.EVT_CHECKBOX, self.OnUpdateStatusBar)
  303. self.randomSeed.Bind(wx.EVT_CHECKBOX, self.OnUpdateStatusBar)
  304. self.randomSeed.Bind(wx.EVT_CHECKBOX, self.OnSeedFlag)
  305. self.randomSeedText.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  306. # bind closing to ESC
  307. self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_CANCEL)
  308. accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CANCEL)]
  309. accelTable = wx.AcceleratorTable(accelTableList)
  310. self.SetAcceleratorTable(accelTable)
  311. self._layout()
  312. self.SetMinSize(self.panel.GetBestSize())
  313. # workaround for http://trac.wxwidgets.org/ticket/13628
  314. self.SetSize(self.panel.GetBestSize())
  315. def _return_funct(self, event):
  316. i = event.GetString()
  317. self._addSomething(self.funct_dict[i])
  318. # reset
  319. win = self.FindWindowById(event.GetId())
  320. win.SetValue('')
  321. def _layout(self):
  322. sizer = wx.BoxSizer(wx.VERTICAL)
  323. controlSizer = wx.BoxSizer(wx.HORIZONTAL)
  324. operatorSizer = wx.StaticBoxSizer(self.operatorBox, wx.HORIZONTAL)
  325. outOpeSizer = wx.BoxSizer(wx.VERTICAL)
  326. buttonSizer1 = wx.GridBagSizer(5, 1)
  327. buttonSizer1.Add(self.btn['add'], pos=(0, 0))
  328. buttonSizer1.Add(self.btn['minus'], pos=(0, 1))
  329. buttonSizer1.Add(self.btn['mod'], pos=(5, 0))
  330. buttonSizer1.Add(self.btn['mult'], pos=(1, 0))
  331. buttonSizer1.Add(self.btn['div'], pos=(1, 1))
  332. buttonSizer1.Add(self.btn['pow'], pos=(5, 1))
  333. buttonSizer1.Add(self.btn['gt'], pos=(2, 0))
  334. buttonSizer1.Add(self.btn['gteq'], pos=(2, 1))
  335. buttonSizer1.Add(self.btn['eq'], pos=(4, 0))
  336. buttonSizer1.Add(self.btn['lt'], pos=(3, 0))
  337. buttonSizer1.Add(self.btn['lteq'], pos=(3, 1))
  338. buttonSizer1.Add(self.btn['noteq'], pos=(4, 1))
  339. buttonSizer2 = wx.GridBagSizer(5, 1)
  340. buttonSizer2.Add(self.btn['and'], pos=(0, 0))
  341. buttonSizer2.Add(self.btn['andbit'], pos=(1, 0))
  342. buttonSizer2.Add(self.btn['andnull'], pos=(2, 0))
  343. buttonSizer2.Add(self.btn['or'], pos=(0, 1))
  344. buttonSizer2.Add(self.btn['orbit'], pos=(1, 1))
  345. buttonSizer2.Add(self.btn['ornull'], pos=(2, 1))
  346. buttonSizer2.Add(self.btn['lshift'], pos=(3, 0))
  347. buttonSizer2.Add(self.btn['rshift'], pos=(3, 1))
  348. buttonSizer2.Add(self.btn['rshiftu'], pos=(4, 0))
  349. buttonSizer2.Add(self.btn['cond'], pos=(5, 0))
  350. buttonSizer2.Add(self.btn['compl'], pos=(5, 1))
  351. buttonSizer2.Add(self.btn['not'], pos=(4, 1))
  352. outputSizer = wx.StaticBoxSizer(self.outputBox, wx.VERTICAL)
  353. outputSizer.Add(self.newmaplabel,
  354. flag=wx.ALIGN_CENTER | wx.TOP, border=5)
  355. outputSizer.Add(self.newmaptxt,
  356. flag=wx.EXPAND | wx.ALL, border=5)
  357. operandSizer = wx.StaticBoxSizer(self.operandBox, wx.HORIZONTAL)
  358. buttonSizer3 = wx.GridBagSizer(7, 1)
  359. buttonSizer3.Add(self.functlabel, pos=(0, 0),
  360. span=(1, 2), flag=wx.ALIGN_CENTER | wx.EXPAND)
  361. buttonSizer3.Add(self.function, pos=(1, 0),
  362. span=(1, 2))
  363. buttonSizer3.Add(self.mapsellabel, pos=(2, 0),
  364. span=(1, 2), flag=wx.ALIGN_CENTER)
  365. buttonSizer3.Add(self.mapselect, pos=(3, 0),
  366. span=(1, 2))
  367. threebutton = wx.GridBagSizer(1, 2)
  368. threebutton.Add(self.btn['parenl'], pos=(0, 0),
  369. span=(1, 1), flag=wx.ALIGN_LEFT)
  370. threebutton.Add(self.btn['parenr'], pos=(0, 1),
  371. span=(1, 1), flag=wx.ALIGN_CENTER)
  372. threebutton.Add(self.btn_clear, pos=(0, 2),
  373. span=(1, 1), flag=wx.ALIGN_RIGHT)
  374. buttonSizer3.Add(threebutton, pos=(4, 0),
  375. span=(1, 1), flag=wx.ALIGN_CENTER)
  376. buttonSizer4 = wx.BoxSizer(wx.HORIZONTAL)
  377. buttonSizer4.Add(self.btn_load,
  378. flag=wx.ALL, border=5)
  379. buttonSizer4.Add(self.btn_save,
  380. flag=wx.ALL, border=5)
  381. buttonSizer4.Add(self.btn_copy,
  382. flag=wx.ALL, border=5)
  383. buttonSizer4.AddSpacer(30)
  384. buttonSizer4.Add(self.btn_help,
  385. flag=wx.ALL, border=5)
  386. buttonSizer4.Add(self.btn_run,
  387. flag=wx.ALL, border=5)
  388. buttonSizer4.Add(self.btn_close,
  389. flag=wx.ALL, border=5)
  390. operatorSizer.Add(buttonSizer1, proportion=0,
  391. flag=wx.ALL | wx.EXPAND, border=5)
  392. operatorSizer.Add(
  393. buttonSizer2,
  394. proportion=0,
  395. flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
  396. border=5)
  397. operandSizer.Add(buttonSizer3, proportion=0,
  398. flag=wx.ALL, border=5)
  399. controlSizer.Add(operatorSizer, proportion=1,
  400. flag=wx.RIGHT | wx.EXPAND, border=5)
  401. outOpeSizer.Add(outputSizer, proportion=0,
  402. flag=wx.EXPAND)
  403. outOpeSizer.Add(operandSizer, proportion=1,
  404. flag=wx.EXPAND | wx.TOP, border=5)
  405. controlSizer.Add(outOpeSizer, proportion=0,
  406. flag=wx.EXPAND)
  407. expressSizer = wx.StaticBoxSizer(self.expressBox, wx.HORIZONTAL)
  408. expressSizer.Add(self.text_mcalc, proportion=1,
  409. flag=wx.EXPAND)
  410. sizer.Add(controlSizer, proportion=0,
  411. flag=wx.EXPAND | wx.ALL,
  412. border=5)
  413. sizer.Add(expressSizer, proportion=1,
  414. flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
  415. border=5)
  416. sizer.Add(buttonSizer4, proportion=0,
  417. flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
  418. randomSizer = wx.BoxSizer(wx.HORIZONTAL)
  419. randomSizer.Add(self.randomSeed, proportion=0,
  420. flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=20)
  421. randomSizer.Add(self.randomSeedStaticText, proportion=0,
  422. flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=5)
  423. randomSizer.Add(self.randomSeedText, proportion=0)
  424. sizer.Add(randomSizer, proportion=0,
  425. flag=wx.LEFT | wx.RIGHT,
  426. border=5)
  427. sizer.Add(self.overwrite, proportion=0,
  428. flag=wx.LEFT | wx.RIGHT,
  429. border=5)
  430. if self.addbox.IsShown():
  431. sizer.Add(self.addbox, proportion=0,
  432. flag=wx.LEFT | wx.RIGHT,
  433. border=5)
  434. self.panel.SetAutoLayout(True)
  435. self.panel.SetSizer(sizer)
  436. sizer.Fit(self.panel)
  437. self.Layout()
  438. def AddMark(self, event):
  439. """Sends operators to insertion method
  440. """
  441. if event.GetId() == self.btn['compl'].GetId():
  442. mark = "~"
  443. elif event.GetId() == self.btn['not'].GetId():
  444. mark = "!"
  445. elif event.GetId() == self.btn['pow'].GetId():
  446. mark = "^"
  447. elif event.GetId() == self.btn['div'].GetId():
  448. mark = "/"
  449. elif event.GetId() == self.btn['add'].GetId():
  450. mark = "+"
  451. elif event.GetId() == self.btn['minus'].GetId():
  452. mark = "-"
  453. elif event.GetId() == self.btn['mod'].GetId():
  454. mark = "%"
  455. elif event.GetId() == self.btn['mult'].GetId():
  456. mark = "*"
  457. elif event.GetId() == self.btn['lshift'].GetId():
  458. mark = "<<"
  459. elif event.GetId() == self.btn['rshift'].GetId():
  460. mark = ">>"
  461. elif event.GetId() == self.btn['rshiftu'].GetId():
  462. mark = ">>>"
  463. elif event.GetId() == self.btn['gt'].GetId():
  464. mark = ">"
  465. elif event.GetId() == self.btn['gteq'].GetId():
  466. mark = ">="
  467. elif event.GetId() == self.btn['lt'].GetId():
  468. mark = "<"
  469. elif event.GetId() == self.btn['lteq'].GetId():
  470. mark = "<="
  471. elif event.GetId() == self.btn['eq'].GetId():
  472. mark = "=="
  473. elif event.GetId() == self.btn['noteq'].GetId():
  474. mark = "!="
  475. elif event.GetId() == self.btn['andbit'].GetId():
  476. mark = "&"
  477. elif event.GetId() == self.btn['orbit'].GetId():
  478. mark = "|"
  479. elif event.GetId() == self.btn['or'].GetId():
  480. mark = "||"
  481. elif event.GetId() == self.btn['ornull'].GetId():
  482. mark = "|||"
  483. elif event.GetId() == self.btn['and'].GetId():
  484. mark = "&&"
  485. elif event.GetId() == self.btn['andnull'].GetId():
  486. mark = "&&&"
  487. elif event.GetId() == self.btn['cond'].GetId():
  488. mark = " ? : "
  489. elif event.GetId() == self.btn['parenl'].GetId():
  490. mark = "("
  491. elif event.GetId() == self.btn['parenr'].GetId():
  492. mark = ")"
  493. self._addSomething(mark)
  494. # unused
  495. # def OnSelectTextEvt(self, event):
  496. # """Checks if user is typing or the event was emited by map selection.
  497. # Prevents from changing focus.
  498. # """
  499. # item = self.mapselect.GetValue().strip()
  500. # if not (abs(len(item) - len(self.lastMapName)) == 1 and \
  501. # self.lastMapName in item or item in self.lastMapName):
  502. # self.OnSelect(event)
  503. # self.lastMapName = item
  504. def OnSelect(self, event):
  505. """Gets raster map or function selection and send it to
  506. insertion method.
  507. Checks for characters which can be in raster map name but
  508. the raster map name must be then quoted.
  509. """
  510. win = self.FindWindowById(event.GetId())
  511. item = win.GetValue().strip()
  512. if any((char in item) for char in self.charactersToQuote):
  513. item = '"' + item + '"'
  514. self._addSomething(item)
  515. win.ChangeValue('') # reset
  516. # Map selector likes to keep focus. Set it back to expression input area
  517. wx.CallAfter(self.text_mcalc.SetFocus)
  518. def OnUpdateStatusBar(self, event):
  519. """Update statusbar text"""
  520. command = self._getCommand()
  521. self.SetStatusText(command)
  522. event.Skip()
  523. def OnSeedFlag(self, event):
  524. checked = self.randomSeed.IsChecked()
  525. self.randomSeedText.Enable(not checked)
  526. self.randomSeedStaticText.Enable(not checked)
  527. event.Skip()
  528. def _getCommand(self):
  529. """Returns entire command as string."""
  530. expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
  531. cmd = 'r.mapcalc'
  532. if self.rast3d:
  533. cmd = 'r3.mapcalc'
  534. overwrite = ''
  535. if self.overwrite.IsChecked():
  536. overwrite = ' --overwrite'
  537. seed_flag = seed = ''
  538. if re.search(pattern="rand *\(.+\)", string=expr):
  539. if self.randomSeed.IsChecked():
  540. seed_flag = ' -s'
  541. else:
  542. seed = " seed={val}".format(
  543. val=self.randomSeedText.GetValue().strip())
  544. return ('{cmd} expression="{new} = {expr}"{seed}{seed_flag}{overwrite}'
  545. .format(cmd=cmd, expr=expr, new=self.newmaptxt.GetValue(),
  546. seed_flag=seed_flag, seed=seed, overwrite=overwrite))
  547. def _addSomething(self, what):
  548. """Inserts operators, map names, and functions into text area
  549. """
  550. mcalcstr = self.text_mcalc.GetValue()
  551. position = self.text_mcalc.GetInsertionPoint()
  552. newmcalcstr = mcalcstr[:position]
  553. position_offset = 0
  554. try:
  555. if newmcalcstr[-1] != ' ':
  556. newmcalcstr += ' '
  557. position_offset += 1
  558. except:
  559. pass
  560. newmcalcstr += what
  561. # Do not add extra space if there is already one
  562. try:
  563. if newmcalcstr[-1] != ' ' and mcalcstr[position] != ' ':
  564. newmcalcstr += ' '
  565. except:
  566. newmcalcstr += ' '
  567. newmcalcstr += mcalcstr[position:]
  568. self.text_mcalc.SetValue(newmcalcstr)
  569. if len(what) > 0:
  570. match = re.search(pattern="\(.*\)", string=what)
  571. if match:
  572. position_offset += match.start() + 1
  573. else:
  574. position_offset += len(what)
  575. try:
  576. if newmcalcstr[position + position_offset] == ' ':
  577. position_offset += 1
  578. except:
  579. pass
  580. self.text_mcalc.SetInsertionPoint(position + position_offset)
  581. self.text_mcalc.Update()
  582. self.text_mcalc.SetFocus()
  583. def OnMCalcRun(self, event):
  584. """Builds and runs r.mapcalc statement
  585. """
  586. name = self.newmaptxt.GetValue().strip()
  587. if not name:
  588. GError(parent=self,
  589. message=_("You must enter the name of "
  590. "a new raster map to create."))
  591. return
  592. if not(name[0] == '"' and name[-1] == '"') and any((char in name)
  593. for char in self.charactersToQuote):
  594. name = '"' + name + '"'
  595. expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
  596. if not expr:
  597. GError(parent=self,
  598. message=_("You must enter an expression "
  599. "to create a new raster map."))
  600. return
  601. seed_flag = seed = None
  602. if re.search(pattern="rand *\(.+\)", string=expr):
  603. if self.randomSeed.IsChecked():
  604. seed_flag = '-s'
  605. else:
  606. seed = self.randomSeedText.GetValue().strip()
  607. if self.log:
  608. cmd = [self.cmd]
  609. if seed_flag:
  610. cmd.append('-s')
  611. if seed:
  612. cmd.append("seed={val}".format(val=seed))
  613. if self.overwrite.IsChecked():
  614. cmd.append('--overwrite')
  615. cmd.append(str('expression=%s = %s' % (name, expr)))
  616. self.log.RunCmd(cmd, onDone=self.OnDone)
  617. self.parent.Raise()
  618. else:
  619. if self.overwrite.IsChecked():
  620. overwrite = True
  621. else:
  622. overwrite = False
  623. params = dict(expression="%s=%s" % (name, expr),
  624. overwrite=overwrite)
  625. if seed_flag:
  626. params['flags'] = 's'
  627. if seed:
  628. params['seed'] = seed
  629. RunCommand(self.cmd,
  630. **params)
  631. def OnDone(self, event):
  632. """Add create map to the layer tree
  633. Sends the mapCreated signal from the grass interface.
  634. """
  635. if event.returncode != 0:
  636. return
  637. name = self.newmaptxt.GetValue().strip(
  638. ' "') + '@' + grass.gisenv()['MAPSET']
  639. ltype = 'raster'
  640. if self.rast3d:
  641. ltype = 'raster_3d'
  642. self._giface.mapCreated.emit(
  643. name=name, ltype=ltype, add=self.addbox.IsChecked())
  644. gisenv = grass.gisenv()
  645. self._giface.grassdbChanged.emit(grassdb=gisenv['GISDBASE'],
  646. location=gisenv['LOCATION_NAME'],
  647. mapset=gisenv['MAPSET'],
  648. action='new',
  649. map=name.split('@')[0],
  650. element=ltype)
  651. def OnSaveExpression(self, event):
  652. """Saves expression to file
  653. """
  654. mctxt = self.newmaptxt.GetValue() + ' = ' + self.text_mcalc.GetValue() + os.linesep
  655. # dialog
  656. dlg = wx.FileDialog(
  657. parent=self,
  658. message=_("Choose a file name to save the expression"),
  659. wildcard=_("Expression file (*)|*"),
  660. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  661. if dlg.ShowModal() == wx.ID_OK:
  662. path = dlg.GetPath()
  663. if not path:
  664. dlg.Destroy()
  665. return
  666. try:
  667. fobj = open(path, 'w')
  668. fobj.write(mctxt)
  669. finally:
  670. fobj.close()
  671. dlg.Destroy()
  672. def OnLoadExpression(self, event):
  673. """Load expression from file
  674. """
  675. dlg = wx.FileDialog(
  676. parent=self,
  677. message=_("Choose a file name to load the expression"),
  678. wildcard=_("Expression file (*)|*"),
  679. style=wx.FD_OPEN)
  680. if dlg.ShowModal() == wx.ID_OK:
  681. path = dlg.GetPath()
  682. if not path:
  683. dlg.Destroy()
  684. return
  685. try:
  686. fobj = open(path, 'r')
  687. mctxt = fobj.read()
  688. finally:
  689. fobj.close()
  690. try:
  691. result, exp = mctxt.split('=', 1)
  692. except ValueError:
  693. result = ''
  694. exp = mctxt
  695. self.newmaptxt.SetValue(result.strip())
  696. self.text_mcalc.SetValue(exp.strip())
  697. self.text_mcalc.SetFocus()
  698. self.text_mcalc.SetInsertionPointEnd()
  699. dlg.Destroy()
  700. def OnCopyCommand(self, event):
  701. command = self._getCommand()
  702. cmddata = wx.TextDataObject()
  703. cmddata.SetText(command)
  704. if wx.TheClipboard.Open():
  705. wx.TheClipboard.SetData(cmddata)
  706. wx.TheClipboard.Close()
  707. self.SetStatusText(
  708. _("'{cmd}' copied to clipboard").format(
  709. cmd=command))
  710. def OnClear(self, event):
  711. """Clears text area
  712. """
  713. self.text_mcalc.SetValue('')
  714. def OnHelp(self, event):
  715. """Launches r.mapcalc help
  716. """
  717. RunCommand('g.manual', parent=self, entry=self.cmd)
  718. def OnClose(self, event):
  719. """Close window"""
  720. self.Destroy()
  721. if __name__ == "__main__":
  722. app = wx.App(0)
  723. frame = MapCalcFrame(
  724. parent=None,
  725. cmd='r.mapcalc',
  726. giface=StandaloneGrassInterface())
  727. frame.Show()
  728. app.MainLoop()