mcalc_builder.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 sys
  15. import re
  16. import wx
  17. import grass.script as grass
  18. if __name__ == "__main__":
  19. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  20. if gui_wx_path not in sys.path:
  21. sys.path.append(gui_wx_path)
  22. from core import globalvar
  23. from core.gcmd import GError, RunCommand
  24. from core.giface import StandaloneGrassInterface
  25. from core.utils import _
  26. from gui_core.gselect import Select
  27. from gui_core.forms import GUI
  28. from core.settings import UserSettings
  29. class MapCalcFrame(wx.Frame):
  30. """!Mapcalc Frame class. Calculator-style window to create and run
  31. r(3).mapcalc statements.
  32. """
  33. def __init__(self, parent, giface, cmd, id = wx.ID_ANY,
  34. style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
  35. self.parent = parent
  36. self._giface = giface
  37. if self.parent:
  38. self.log = self.parent.GetLogWindow()
  39. else:
  40. self.log = None
  41. # grass command
  42. self.cmd = cmd
  43. if self.cmd == 'r.mapcalc':
  44. self.rast3d = False
  45. title = _('GRASS GIS Raster Map Calculator')
  46. if self.cmd == 'r3.mapcalc':
  47. self.rast3d = True
  48. title = _('GRASS GIS 3D Raster Map Calculator')
  49. wx.Frame.__init__(self, parent, id = id, title = title, **kwargs)
  50. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  51. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  52. self.CreateStatusBar()
  53. #
  54. # variables
  55. #
  56. self.heading = _('mapcalc statement')
  57. self.funct_dict = {
  58. 'abs(x)':'abs()',
  59. 'acos(x)':'acos()',
  60. 'asin(x)':'asin()',
  61. 'atan(x)':'atan()',
  62. 'atan(x,y)':'atan( , )',
  63. 'cos(x)':'cos()',
  64. 'double(x)':'double()',
  65. 'eval([x,y,...,]z)':'eval()',
  66. 'exp(x)':'exp()',
  67. 'exp(x,y)':'exp( , )',
  68. 'float(x)':'float()',
  69. 'graph(x,x1,y1[x2,y2..])':'graph( , , )',
  70. 'if(x)':'if()',
  71. 'if(x,a)':'if( , )',
  72. 'if(x,a,b)':'if( , , )',
  73. 'if(x,a,b,c)':'if( , , , )',
  74. 'int(x)':'int()',
  75. 'isnull(x)':'isnull()',
  76. 'log(x)':'log(',
  77. 'log(x,b)':'log( , )',
  78. 'max(x,y[,z...])':'max( , )',
  79. 'median(x,y[,z...])':'median( , )',
  80. 'min(x,y[,z...])':'min( , )',
  81. 'mode(x,y[,z...])':'mode( , )',
  82. 'not(x)':'not()',
  83. 'pow(x,y)':'pow( , )',
  84. 'rand(a,b)':'rand( , )',
  85. 'round(x)':'round()',
  86. 'sin(x)':'sin()',
  87. 'sqrt(x)':'sqrt()',
  88. 'tan(x)':'tan()',
  89. 'xor(x,y)':'xor( , )',
  90. 'row()':'row()',
  91. 'col()':'col()',
  92. 'x()':'x()',
  93. 'y()':'y()',
  94. 'ewres()':'ewres()',
  95. 'nsres()':'nsres()',
  96. 'null()':'null()'
  97. }
  98. if self.rast3d:
  99. self.funct_dict['z()'] = 'z()'
  100. self.funct_dict['tbres()'] = 'tbres()'
  101. element = 'rast3d'
  102. else:
  103. element = 'cell'
  104. # characters which can be in raster map name but the map name must be then quoted
  105. self.charactersToQuote = '+-&!<>%~?^|'
  106. # stores last typed map name in Select widget to distinguish typing from selection
  107. self.lastMapName = ''
  108. self.operatorBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  109. label=" %s " % _('Operators'))
  110. self.outputBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  111. label=" %s " % _('Output'))
  112. self.operandBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  113. label=" %s " % _('Operands'))
  114. self.expressBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  115. label=" %s " % _('Expression'))
  116. #
  117. # Buttons
  118. #
  119. self.btn_clear = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
  120. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  121. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("&Run"))
  122. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  123. self.btn_run.SetDefault()
  124. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  125. self.btn_save = wx.Button(parent = self.panel, id = wx.ID_SAVE)
  126. self.btn_save.SetToolTipString(_('Save expression to file'))
  127. self.btn_load = wx.Button(parent = self.panel, id = wx.ID_ANY,
  128. label = _("&Load"))
  129. self.btn_load.SetToolTipString(_('Load expression from file'))
  130. self.btn = dict()
  131. self.btn['pow'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "^")
  132. self.btn['pow'].SetToolTipString(_('exponent'))
  133. self.btn['div'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "/")
  134. self.btn['div'].SetToolTipString(_('divide'))
  135. self.btn['add'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "+")
  136. self.btn['add'].SetToolTipString(_('add'))
  137. self.btn['minus'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "-")
  138. self.btn['minus'].SetToolTipString(_('subtract'))
  139. self.btn['mod'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "%")
  140. self.btn['mod'].SetToolTipString(_('modulus'))
  141. self.btn['mult'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "*")
  142. self.btn['mult'].SetToolTipString(_('multiply'))
  143. self.btn['parenl'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "(")
  144. self.btn['parenr'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ")")
  145. self.btn['lshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<<")
  146. self.btn['lshift'].SetToolTipString(_('left shift'))
  147. self.btn['rshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>")
  148. self.btn['rshift'].SetToolTipString(_('right shift'))
  149. self.btn['rshiftu'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>>")
  150. self.btn['rshiftu'].SetToolTipString(_('right shift (unsigned)'))
  151. self.btn['gt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">")
  152. self.btn['gt'].SetToolTipString(_('greater than'))
  153. self.btn['gteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">=")
  154. self.btn['gteq'].SetToolTipString(_('greater than or equal to'))
  155. self.btn['lt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<")
  156. self.btn['lt'].SetToolTipString(_('less than'))
  157. self.btn['lteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<=")
  158. self.btn['lteq'].SetToolTipString(_('less than or equal to'))
  159. self.btn['eq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "==")
  160. self.btn['eq'].SetToolTipString(_('equal to'))
  161. self.btn['noteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!=")
  162. self.btn['noteq'].SetToolTipString(_('not equal to'))
  163. self.btn['compl'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "~")
  164. self.btn['compl'].SetToolTipString(_('one\'s complement'))
  165. self.btn['not'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!")
  166. self.btn['not'].SetToolTipString(_('NOT'))
  167. self.btn['andbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = '&&')
  168. self.btn['andbit'].SetToolTipString(_('bitwise AND'))
  169. self.btn['orbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|")
  170. self.btn['orbit'].SetToolTipString(_('bitwise OR'))
  171. self.btn['and'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&")
  172. self.btn['and'].SetToolTipString(_('logical AND'))
  173. self.btn['andnull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&&&")
  174. self.btn['andnull'].SetToolTipString(_('logical AND (ignores NULLs)'))
  175. self.btn['or'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "||")
  176. self.btn['or'].SetToolTipString(_('logical OR'))
  177. self.btn['ornull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|||")
  178. self.btn['ornull'].SetToolTipString(_('logical OR (ignores NULLs)'))
  179. self.btn['cond'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "a ? b : c")
  180. self.btn['cond'].SetToolTipString(_('conditional'))
  181. #
  182. # Text area
  183. #
  184. self.text_mcalc = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (-1, 75),
  185. style = wx.TE_MULTILINE)
  186. wx.CallAfter(self.text_mcalc.SetFocus)
  187. #
  188. # Map and function insertion text and ComboBoxes
  189. self.newmaplabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY)
  190. if self.rast3d:
  191. self.newmaplabel.SetLabel(_('Name for new 3D raster map to create'))
  192. else:
  193. self.newmaplabel.SetLabel(_('Name for new raster map to create'))
  194. self.newmaptxt = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size=(250, -1))
  195. self.mapsellabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY)
  196. if self.rast3d:
  197. self.mapsellabel.SetLabel(_('Insert existing 3D raster map'))
  198. else:
  199. self.mapsellabel.SetLabel(_('Insert existing raster map'))
  200. self.mapselect = Select(parent = self.panel, id = wx.ID_ANY, size = (250, -1),
  201. type = element, multiple = False)
  202. self.functlabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  203. label = _('Insert mapcalc function'))
  204. self.function = wx.ComboBox(parent = self.panel, id = wx.ID_ANY,
  205. size = (250, -1), choices = sorted(self.funct_dict.keys()),
  206. style = wx.CB_DROPDOWN |
  207. wx.CB_READONLY | wx.TE_PROCESS_ENTER)
  208. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  209. label=_("Allow output files to overwrite existing files"))
  210. self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  211. self.addbox = wx.CheckBox(parent=self.panel,
  212. label=_('Add created raster map into layer tree'), style = wx.NO_BORDER)
  213. self.addbox.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  214. if not self.parent or self.parent.GetName() != 'LayerManager':
  215. self.addbox.Hide()
  216. #
  217. # Bindings
  218. #
  219. for btn in self.btn.keys():
  220. self.btn[btn].Bind(wx.EVT_BUTTON, self.AddMark)
  221. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  222. self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
  223. self.btn_run.Bind(wx.EVT_BUTTON, self.OnMCalcRun)
  224. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  225. self.btn_save.Bind(wx.EVT_BUTTON, self.OnSaveExpression)
  226. self.btn_load.Bind(wx.EVT_BUTTON, self.OnLoadExpression)
  227. # self.mapselect.Bind(wx.EVT_TEXT, self.OnSelectTextEvt)
  228. self.mapselect.Bind(wx.EVT_TEXT, self.OnSelect)
  229. self.function.Bind(wx.EVT_COMBOBOX, self._return_funct)
  230. self.function.Bind(wx.EVT_TEXT_ENTER, self.OnSelect)
  231. self.newmaptxt.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  232. self.text_mcalc.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  233. self._layout()
  234. self.SetMinSize(self.GetBestSize())
  235. def _return_funct(self,event):
  236. i = event.GetString()
  237. self._addSomething(self.funct_dict[i])
  238. # reset
  239. win = self.FindWindowById(event.GetId())
  240. win.SetValue('')
  241. def _layout(self):
  242. sizer = wx.BoxSizer(wx.VERTICAL)
  243. controlSizer = wx.BoxSizer(wx.HORIZONTAL)
  244. operatorSizer = wx.StaticBoxSizer(self.operatorBox, wx.HORIZONTAL)
  245. outOpeSizer = wx.BoxSizer(wx.VERTICAL)
  246. buttonSizer1 = wx.GridBagSizer(5, 1)
  247. buttonSizer1.Add(item = self.btn['add'], pos = (0,0))
  248. buttonSizer1.Add(item = self.btn['minus'], pos = (0,1))
  249. buttonSizer1.Add(item = self.btn['mod'], pos = (5,0))
  250. buttonSizer1.Add(item = self.btn['mult'], pos = (1,0))
  251. buttonSizer1.Add(item = self.btn['div'], pos = (1,1))
  252. buttonSizer1.Add(item = self.btn['pow'], pos = (5,1))
  253. buttonSizer1.Add(item = self.btn['gt'], pos = (2,0))
  254. buttonSizer1.Add(item = self.btn['gteq'], pos = (2,1))
  255. buttonSizer1.Add(item = self.btn['eq'], pos = (4,0))
  256. buttonSizer1.Add(item = self.btn['lt'], pos = (3,0))
  257. buttonSizer1.Add(item = self.btn['lteq'], pos = (3,1))
  258. buttonSizer1.Add(item = self.btn['noteq'], pos = (4,1))
  259. buttonSizer2 = wx.GridBagSizer(5, 1)
  260. buttonSizer2.Add(item = self.btn['and'], pos = (0,0))
  261. buttonSizer2.Add(item = self.btn['andbit'], pos = (1,0))
  262. buttonSizer2.Add(item = self.btn['andnull'], pos = (2,0))
  263. buttonSizer2.Add(item = self.btn['or'], pos = (0,1))
  264. buttonSizer2.Add(item = self.btn['orbit'], pos = (1,1))
  265. buttonSizer2.Add(item = self.btn['ornull'], pos = (2,1))
  266. buttonSizer2.Add(item = self.btn['lshift'], pos = (3,0))
  267. buttonSizer2.Add(item = self.btn['rshift'], pos = (3,1))
  268. buttonSizer2.Add(item = self.btn['rshiftu'], pos = (4,0))
  269. buttonSizer2.Add(item = self.btn['cond'], pos = (5,0))
  270. buttonSizer2.Add(item = self.btn['compl'], pos = (5,1))
  271. buttonSizer2.Add(item = self.btn['not'], pos = (4,1))
  272. outputSizer = wx.StaticBoxSizer(self.outputBox, wx.VERTICAL)
  273. outputSizer.Add(item = self.newmaplabel,
  274. flag = wx.ALIGN_CENTER | wx.BOTTOM | wx.TOP, border = 5)
  275. outputSizer.Add(item = self.newmaptxt,
  276. flag = wx.EXPAND)
  277. operandSizer = wx.StaticBoxSizer(self.operandBox, wx.HORIZONTAL)
  278. buttonSizer3 = wx.GridBagSizer(7, 1)
  279. buttonSizer3.Add(item = self.functlabel, pos = (0,0),
  280. span = (1,2), flag = wx.ALIGN_CENTER)
  281. buttonSizer3.Add(item = self.function, pos = (1,0),
  282. span = (1,2))
  283. buttonSizer3.Add(item = self.mapsellabel, pos = (2,0),
  284. span = (1,2), flag = wx.ALIGN_CENTER)
  285. buttonSizer3.Add(item = self.mapselect, pos = (3,0),
  286. span = (1,2))
  287. threebutton = wx.GridBagSizer(1, 2)
  288. threebutton.Add(item = self.btn['parenl'], pos = (0,0),
  289. span = (1,1), flag = wx.ALIGN_LEFT)
  290. threebutton.Add(item = self.btn['parenr'], pos = (0,1),
  291. span = (1,1), flag = wx.ALIGN_CENTER)
  292. threebutton.Add(item = self.btn_clear, pos = (0,2),
  293. span = (1,1), flag = wx.ALIGN_RIGHT)
  294. buttonSizer3.Add(item = threebutton, pos = (4,0),
  295. span = (1,1), flag = wx.ALIGN_CENTER)
  296. buttonSizer4 = wx.BoxSizer(wx.HORIZONTAL)
  297. buttonSizer4.Add(item = self.btn_load,
  298. flag = wx.ALL, border = 5)
  299. buttonSizer4.Add(item = self.btn_save,
  300. flag = wx.ALL, border = 5)
  301. buttonSizer4.AddSpacer(30)
  302. buttonSizer4.Add(item = self.btn_help,
  303. flag = wx.ALL, border = 5)
  304. buttonSizer4.Add(item = self.btn_run,
  305. flag = wx.ALL, border = 5)
  306. buttonSizer4.Add(item = self.btn_close,
  307. flag = wx.ALL, border = 5)
  308. operatorSizer.Add(item = buttonSizer1, proportion = 0,
  309. flag = wx.ALL | wx.EXPAND, border = 5)
  310. operatorSizer.Add(item = buttonSizer2, proportion = 0,
  311. flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND, border = 5)
  312. operandSizer.Add(item = buttonSizer3, proportion = 0,
  313. flag = wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  314. controlSizer.Add(item = operatorSizer, proportion = 1,
  315. flag = wx.RIGHT | wx.EXPAND, border = 5)
  316. outOpeSizer.Add(item = outputSizer, proportion = 0,
  317. flag = wx.EXPAND)
  318. outOpeSizer.Add(item = operandSizer, proportion = 1,
  319. flag = wx.EXPAND | wx.TOP, border = 5)
  320. controlSizer.Add(item = outOpeSizer, proportion = 0,
  321. flag = wx.EXPAND)
  322. expressSizer = wx.StaticBoxSizer(self.expressBox, wx.HORIZONTAL)
  323. expressSizer.Add(item = self.text_mcalc, proportion = 1,
  324. flag = wx.EXPAND)
  325. sizer.Add(item = controlSizer, proportion = 0,
  326. flag = wx.EXPAND | wx.ALL,
  327. border = 5)
  328. sizer.Add(item = expressSizer, proportion = 1,
  329. flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
  330. border = 5)
  331. sizer.Add(item = buttonSizer4, proportion = 0,
  332. flag = wx.ALIGN_RIGHT | wx.ALL, border = 3)
  333. sizer.Add(item = self.overwrite, proportion = 0,
  334. flag = wx.LEFT | wx.RIGHT,
  335. border = 5)
  336. if self.addbox.IsShown():
  337. sizer.Add(item = self.addbox, proportion = 0,
  338. flag = wx.LEFT | wx.RIGHT,
  339. border = 5)
  340. self.panel.SetAutoLayout(True)
  341. self.panel.SetSizer(sizer)
  342. sizer.Fit(self.panel)
  343. self.Layout()
  344. def AddMark(self,event):
  345. """!Sends operators to insertion method
  346. """
  347. if event.GetId() == self.btn['compl'].GetId(): mark = "~"
  348. elif event.GetId() == self.btn['not'].GetId(): mark = "!"
  349. elif event.GetId() == self.btn['pow'].GetId(): mark = "^"
  350. elif event.GetId() == self.btn['div'].GetId(): mark = "/"
  351. elif event.GetId() == self.btn['add'].GetId(): mark = "+"
  352. elif event.GetId() == self.btn['minus'].GetId(): mark = "-"
  353. elif event.GetId() == self.btn['mod'].GetId(): mark = "%"
  354. elif event.GetId() == self.btn['mult'].GetId(): mark = "*"
  355. elif event.GetId() == self.btn['lshift'].GetId(): mark = "<<"
  356. elif event.GetId() == self.btn['rshift'].GetId(): mark = ">>"
  357. elif event.GetId() == self.btn['rshiftu'].GetId(): mark = ">>>"
  358. elif event.GetId() == self.btn['gt'].GetId(): mark = ">"
  359. elif event.GetId() == self.btn['gteq'].GetId(): mark = ">="
  360. elif event.GetId() == self.btn['lt'].GetId(): mark = "<"
  361. elif event.GetId() == self.btn['lteq'].GetId(): mark = "<="
  362. elif event.GetId() == self.btn['eq'].GetId(): mark = "=="
  363. elif event.GetId() == self.btn['noteq'].GetId(): mark = "!="
  364. elif event.GetId() == self.btn['andbit'].GetId(): mark = "&"
  365. elif event.GetId() == self.btn['orbit'].GetId(): mark = "|"
  366. elif event.GetId() == self.btn['or'].GetId(): mark = "||"
  367. elif event.GetId() == self.btn['ornull'].GetId(): mark = "|||"
  368. elif event.GetId() == self.btn['and'].GetId(): mark = "&&"
  369. elif event.GetId() == self.btn['andnull'].GetId(): mark = "&&&"
  370. elif event.GetId() == self.btn['cond'].GetId(): mark = " ? : "
  371. elif event.GetId() == self.btn['parenl'].GetId(): mark = "("
  372. elif event.GetId() == self.btn['parenr'].GetId(): mark = ")"
  373. self._addSomething(mark)
  374. ### unused
  375. # def OnSelectTextEvt(self, event):
  376. # """!Checks if user is typing or the event was emited by map selection.
  377. # Prevents from changing focus.
  378. # """
  379. # item = self.mapselect.GetValue().strip()
  380. # if not (abs(len(item) - len(self.lastMapName)) == 1 and \
  381. # self.lastMapName in item or item in self.lastMapName):
  382. # self.OnSelect(event)
  383. # self.lastMapName = item
  384. def OnSelect(self, event):
  385. """!Gets raster map or function selection and send it to
  386. insertion method.
  387. Checks for characters which can be in raster map name but
  388. the raster map name must be then quoted.
  389. """
  390. win = self.FindWindowById(event.GetId())
  391. item = event.GetString().strip()
  392. if any((char in item) for char in self.charactersToQuote):
  393. item = '"' + item + '"'
  394. self._addSomething(item)
  395. win.ChangeValue('') # reset
  396. def OnUpdateStatusBar(self, event):
  397. """!Update statusbar text"""
  398. expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
  399. cmd = 'r.mapcalc'
  400. if self.rast3d:
  401. cmd = 'r3.mapcalc'
  402. self.SetStatusText("{cmd} '{new} = {expr}'".format(cmd=cmd, expr=expr,
  403. new=self.newmaptxt.GetValue()))
  404. event.Skip()
  405. def _addSomething(self, what):
  406. """!Inserts operators, map names, and functions into text area
  407. """
  408. mcalcstr = self.text_mcalc.GetValue()
  409. position = self.text_mcalc.GetInsertionPoint()
  410. newmcalcstr = mcalcstr[:position]
  411. position_offset = 0
  412. try:
  413. if newmcalcstr[-1] != ' ':
  414. newmcalcstr += ' '
  415. position_offset += 1
  416. except:
  417. pass
  418. newmcalcstr += what + ' ' + mcalcstr[position:]
  419. self.text_mcalc.SetValue(newmcalcstr)
  420. if len(what) > 0:
  421. match = re.search(pattern="\(.*\)", string=what)
  422. if match:
  423. position_offset += match.start() + 1
  424. else:
  425. position_offset += len(what)
  426. self.text_mcalc.SetInsertionPoint(position + position_offset)
  427. self.text_mcalc.Update()
  428. self.text_mcalc.SetFocus()
  429. def OnMCalcRun(self,event):
  430. """!Builds and runs r.mapcalc statement
  431. """
  432. name = self.newmaptxt.GetValue().strip()
  433. if not name:
  434. GError(parent = self,
  435. message = _("You must enter the name of "
  436. "a new raster map to create."))
  437. return
  438. if not (name[0] == '"' and name[-1] == '"') and any((char in name) for char in self.charactersToQuote):
  439. name = '"' + name + '"'
  440. expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
  441. if not expr:
  442. GError(parent = self,
  443. message = _("You must enter an expression "
  444. "to create a new raster map."))
  445. return
  446. if self.log:
  447. cmd = [self.cmd, str('expression=%s = %s' % (name, expr))]
  448. if self.overwrite.IsChecked():
  449. cmd.append('--overwrite')
  450. self.log.RunCmd(cmd, onDone = self.OnDone)
  451. self.parent.Raise()
  452. else:
  453. if self.overwrite.IsChecked():
  454. overwrite = True
  455. else:
  456. overwrite = False
  457. RunCommand(self.cmd,
  458. expression = "%s=%s" % (name, expr),
  459. overwrite = overwrite)
  460. def OnDone(self, cmd, returncode):
  461. """!Add create map to the layer tree
  462. Sends the mapCreated signal from the grass interface.
  463. """
  464. if returncode != 0:
  465. return
  466. name = self.newmaptxt.GetValue().strip(' "') + '@' + grass.gisenv()['MAPSET']
  467. ltype = 'rast'
  468. if self.rast3d:
  469. ltype = 'rast3d'
  470. self._giface.mapCreated.emit(name=name, ltype=ltype, add=self.addbox.IsChecked())
  471. def OnSaveExpression(self, event):
  472. """!Saves expression to file
  473. """
  474. mctxt = self.newmaptxt.GetValue() + ' = ' + self.text_mcalc.GetValue() + os.linesep
  475. #dialog
  476. dlg = wx.FileDialog(parent = self,
  477. message = _("Choose a file name to save the expression"),
  478. wildcard = _("Expression file (*)|*"),
  479. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  480. if dlg.ShowModal() == wx.ID_OK:
  481. path = dlg.GetPath()
  482. if not path:
  483. dlg.Destroy()
  484. return
  485. try:
  486. fobj = open(path, 'w')
  487. fobj.write(mctxt)
  488. finally:
  489. fobj.close()
  490. dlg.Destroy()
  491. def OnLoadExpression(self, event):
  492. """!Load expression from file
  493. """
  494. dlg = wx.FileDialog(parent = self,
  495. message = _("Choose a file name to load the expression"),
  496. wildcard = _("Expression file (*)|*"),
  497. style = wx.OPEN)
  498. if dlg.ShowModal() == wx.ID_OK:
  499. path = dlg.GetPath()
  500. if not path:
  501. dlg.Destroy()
  502. return
  503. try:
  504. fobj = open(path,'r')
  505. mctxt = fobj.read()
  506. finally:
  507. fobj.close()
  508. try:
  509. result, exp = mctxt.split('=', 1)
  510. except ValueError:
  511. result = ''
  512. exp = mctxt
  513. self.newmaptxt.SetValue(result.strip())
  514. self.text_mcalc.SetValue(exp.strip())
  515. self.text_mcalc.SetFocus()
  516. self.text_mcalc.SetInsertionPointEnd()
  517. dlg.Destroy()
  518. def OnClear(self, event):
  519. """!Clears text area
  520. """
  521. self.text_mcalc.SetValue('')
  522. def OnHelp(self, event):
  523. """!Launches r.mapcalc help
  524. """
  525. RunCommand('g.manual', parent = self, entry = self.cmd)
  526. def OnClose(self,event):
  527. """!Close window"""
  528. self.Destroy()
  529. if __name__ == "__main__":
  530. app = wx.App(0)
  531. frame = MapCalcFrame(parent = None, cmd = 'r.mapcalc', giface = StandaloneGrassInterface())
  532. frame.Show()
  533. app.MainLoop()