mcalc_builder.py 27 KB

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