mcalc_builder.py 26 KB

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