mcalc_builder.py 26 KB

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