mcalc_builder.py 25 KB

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