mcalc_builder.py 30 KB

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