mcalc_builder.py 29 KB

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