mcalc_builder.py 24 KB

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