Ticket #669: mcalc_builder.py

File mcalc_builder.py, 25.0 KB (added by timmie, 14 years ago)

mcalc_builde mods

Line 
1"""!
2@package mcalc_builder.py
3
4@brief Map calculator, wrapper for r.mapcalc
5
6Classes:
7 - MapCalcFrame
8
9(C) 2008, 2010 by the GRASS Development Team
10
11This program is free software under the GNU General Public License
12(>=v2). Read the file COPYING that comes with GRASS for details.
13
14@author Michael Barton, Arizona State University
15@author Martin Landa <landa.martin gmail.com>
16"""
17#TDOD: load expression functionaliy
18#TODO: add to layer tree
19
20import os
21import sys
22import time
23
24import globalvar
25if not os.getenv("GRASS_WXBUNDLED"):
26 globalvar.CheckForWx()
27import wx
28import wx.aui
29
30import gcmd
31import gselect
32import gdialogs
33import menuform
34try:
35 import subprocess
36except:
37 sys.path.append(os.path.join(globalvar.ETCWXDIR, "compat"))
38 import subprocess
39from preferences import globalSettings as UserSettings
40
41class MapCalcFrame(wx.Frame):
42 """!Mapcalc Frame class. Calculator-style window to create and run
43 r(3).mapcalc statements
44 """
45 def __init__(self, parent, cmd, id = wx.ID_ANY,
46 style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
47 self.parent = parent
48 if self.parent:
49 self.log = self.parent.GetLogWindow()
50 else:
51 self.log = None
52
53 # grass command
54 self.cmd = cmd
55
56 if self.cmd == 'r.mapcalc':
57 self.rast3d = False
58 title = _('GRASS GIS Raster Map Calculator')
59 if self.cmd == 'r3.mapcalc':
60 self.rast3d = True
61 title = _('GRASS GIS 3D Raster Map Calculator')
62
63 wx.Frame.__init__(self, parent, id = id, title = title, **kwargs)
64 self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
65
66 self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
67
68 #
69 # variables
70 #
71 self.heading = _('mapcalc statement')
72 self.funct_list = [
73 'abs(x)',
74 'acos(x)',
75 'asin(x)',
76 'atan(x)',
77 'atan(x,y)',
78 'cos(x)',
79 'double(x)',
80 'eval([x,y,...,]z)',
81 'exp(x)',
82 'exp(x,y)',
83 'float(x)',
84 'graph(x,x1,y1[x2,y2..])',
85 'if(x)',
86 'if(x,a)',
87 'if(x,a,b)',
88 'if(x,a,b,c)',
89 'int(x)',
90 'isnull(x)',
91 'log(x)',
92 'log(x,b)',
93 'max(x,y[,z...])',
94 'median(x,y[,z...])',
95 'min(x,y[,z...])',
96 'mode(x,y[,z...])',
97 'not(x)',
98 'pow(x,y)',
99 'rand(a,b)',
100 'round(x)',
101 'sin(x)',
102 'sqrt(x)',
103 'tan(x)',
104 'xor(x,y)',
105 'row()',
106 'col()',
107 'x()',
108 'y()',
109 'ewres()',
110 'nsres()',
111 'null()'
112 ]
113
114 if self.rast3d:
115 indx = self.funct_list.index('y()') +1
116 self.funct_list.insert(indx, 'z()')
117 indx = self.funct_list.index('nsres()') +1
118 self.funct_list.insert(indx, 'tbres()')
119 maplabel = _('3D raster map')
120 element = 'rast3d'
121 else:
122 maplabel = _('raster map')
123 element = 'cell'
124
125 self.operatorBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
126 label=" %s " % _('Operators'))
127 self.operandBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
128 label=" %s " % _('Operands'))
129 self.expressBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
130 label=" %s " % _('Expression'))
131
132 #
133 # Buttons
134 #
135 self.btn_clear = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
136 self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
137 self.btn_run = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("&Run"))
138 self.btn_run.SetDefault()
139 self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
140 self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
141 label = _("Command dialog"))
142 self.btn_cmd.SetToolTipString(_('Open %s dialog') % self.cmd)
143 self.btn_save = wx.Button(parent = self.panel, id = wx.ID_ANY,
144 label = _("Save"))
145 self.btn_load = wx.Button(parent = self.panel, id = wx.ID_ANY,
146 label = _("Load"))
147 self.btn_load.SetToolTipString(_('Load %s from file') % _('Expression'))
148
149
150
151 self.btn = dict()
152 self.btn['pow'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "^")
153 self.btn['pow'].SetToolTipString(_('exponent'))
154 self.btn['div'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "/")
155 self.btn['div'].SetToolTipString(_('divide'))
156 self.btn['add'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "+")
157 self.btn['add'].SetToolTipString(_('add'))
158 self.btn['minus'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "-")
159 self.btn['minus'].SetToolTipString(_('subtract'))
160 self.btn['mod'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "%")
161 self.btn['mod'].SetToolTipString(_('modulus'))
162 self.btn['mult'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "*")
163 self.btn['mult'].SetToolTipString(_('multiply'))
164
165 self.btn['paren'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "( )")
166
167 self.btn['lshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<<")
168 self.btn['lshift'].SetToolTipString(_('left shift'))
169 self.btn['rshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>")
170 self.btn['rshift'].SetToolTipString(_('right shift'))
171 self.btn['rshiftu'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>>")
172 self.btn['rshiftu'].SetToolTipString(_('right shift (unsigned)'))
173 self.btn['gt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">")
174 self.btn['gt'].SetToolTipString(_('greater than'))
175 self.btn['gteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">=")
176 self.btn['gteq'].SetToolTipString(_('greater than or equal to'))
177 self.btn['lt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<")
178 self.btn['lt'].SetToolTipString(_('less than'))
179 self.btn['lteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<=")
180 self.btn['lteq'].SetToolTipString(_('less than or equal to'))
181 self.btn['eq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "==")
182 self.btn['eq'].SetToolTipString(_('equal to'))
183 self.btn['noteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!=")
184 self.btn['noteq'].SetToolTipString(_('not equal to'))
185
186 self.btn['compl'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "~")
187 self.btn['compl'].SetToolTipString(_('one\'s complement'))
188 self.btn['not'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!")
189 self.btn['not'].SetToolTipString(_('NOT'))
190 self.btn['andbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = '&&')
191 self.btn['andbit'].SetToolTipString(_('bitwise AND'))
192 self.btn['orbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|")
193 self.btn['orbit'].SetToolTipString(_('bitwise OR'))
194 self.btn['and'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&")
195 self.btn['and'].SetToolTipString(_('logical AND'))
196 self.btn['andnull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&&&")
197 self.btn['andnull'].SetToolTipString(_('logical AND (ignores NULLs)'))
198 self.btn['or'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "||")
199 self.btn['or'].SetToolTipString(_('logical OR'))
200 self.btn['ornull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|||")
201 self.btn['ornull'].SetToolTipString(_('logical OR (ignores NULLs)'))
202 self.btn['cond'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "a ? b : c")
203 self.btn['cond'].SetToolTipString(_('conditional'))
204
205 #
206 # Text area
207 #
208 self.text_mcalc = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (-1, 75),
209 style = wx.TE_MULTILINE)
210 wx.CallAfter(self.text_mcalc.SetFocus)
211
212 #
213 # Map and function insertion text and ComboBoxes
214 self.newmaplabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
215 label= _('Name for new %s to create') % maplabel)
216 self.newmaptxt = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size=(250, -1))
217 self.mapsellabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
218 label = _('Insert existing %s') % maplabel)
219 self.mapselect = gselect.Select(parent = self.panel, id = wx.ID_ANY, size = (250, -1),
220 type = element, multiple = False)
221 self.functlabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
222 label = _('Insert mapcalc function'))
223 self.function = wx.ComboBox(parent = self.panel, id = wx.ID_ANY,
224 size = (250, -1), choices = self.funct_list,
225 style = wx.CB_DROPDOWN |
226 wx.CB_READONLY | wx.TE_PROCESS_ENTER)
227
228 self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
229 label=_("Allow output files to overwrite existing files"))
230 self.addbox = wx.CheckBox(parent = self.panel,
231 label = _('Add created map into layer tree'), style = wx.NO_BORDER)
232 self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
233
234 #
235 # Bindings
236 #
237 for btn in self.btn.keys():
238 self.btn[btn].Bind(wx.EVT_BUTTON, self.AddMark)
239
240 self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
241 self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
242 self.btn_run.Bind(wx.EVT_BUTTON, self.OnMCalcRun)
243 self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
244 self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
245 self.btn_save.Bind(wx.EVT_BUTTON, self.OnSaveDialog)
246 self.btn_load.Bind(wx.EVT_BUTTON, self.OnLoadDialog)
247 self.mapselect.Bind(wx.EVT_TEXT, self.OnSelect)
248 self.function.Bind(wx.EVT_COMBOBOX, self.OnSelect)
249 self.function.Bind(wx.EVT_TEXT_ENTER, self.OnSelect)
250
251 self._layout()
252
253 self.SetMinSize(self.GetBestSize())
254
255 def _layout(self):
256 sizer = wx.BoxSizer(wx.VERTICAL)
257
258 controlSizer = wx.BoxSizer(wx.HORIZONTAL)
259 operatorSizer = wx.StaticBoxSizer(self.operatorBox, wx.HORIZONTAL)
260
261 buttonSizer1 = wx.GridBagSizer(5, 1)
262 buttonSizer1.Add(item = self.btn['add'], pos = (0,0))
263 buttonSizer1.Add(item = self.btn['minus'], pos = (0,1))
264 buttonSizer1.Add(item = self.btn['mod'], pos = (5,0))
265 buttonSizer1.Add(item = self.btn['mult'], pos = (1,0))
266 buttonSizer1.Add(item = self.btn['div'], pos = (1,1))
267 buttonSizer1.Add(item = self.btn['pow'], pos = (5,1))
268 buttonSizer1.Add(item = self.btn['gt'], pos = (2,0))
269 buttonSizer1.Add(item = self.btn['gteq'], pos = (2,1))
270 buttonSizer1.Add(item = self.btn['eq'], pos = (4,0))
271 buttonSizer1.Add(item = self.btn['lt'], pos = (3,0))
272 buttonSizer1.Add(item = self.btn['lteq'], pos = (3,1))
273 buttonSizer1.Add(item = self.btn['noteq'], pos = (4,1))
274
275 buttonSizer2 = wx.GridBagSizer(5, 1)
276 buttonSizer2.Add(item = self.btn['and'], pos = (0,0))
277 buttonSizer2.Add(item = self.btn['andbit'], pos = (1,0))
278 buttonSizer2.Add(item = self.btn['andnull'], pos = (2,0))
279 buttonSizer2.Add(item = self.btn['or'], pos = (0,1))
280 buttonSizer2.Add(item = self.btn['orbit'], pos = (1,1))
281 buttonSizer2.Add(item = self.btn['ornull'], pos = (2,1))
282 buttonSizer2.Add(item = self.btn['lshift'], pos = (3,0))
283 buttonSizer2.Add(item = self.btn['rshift'], pos = (3,1))
284 buttonSizer2.Add(item = self.btn['rshiftu'], pos = (4,0))
285 buttonSizer2.Add(item = self.btn['cond'], pos = (5,0))
286 buttonSizer2.Add(item = self.btn['compl'], pos = (5,1))
287 buttonSizer2.Add(item = self.btn['not'], pos = (4,1))
288
289 operandSizer = wx.StaticBoxSizer(self.operandBox, wx.HORIZONTAL)
290
291 buttonSizer3 = wx.GridBagSizer(7, 1)
292
293 buttonSizer3.Add(item = self.newmaplabel, pos = (0, 0),
294 span = (1, 2), flag = wx.ALIGN_CENTER)
295 buttonSizer3.Add(item = self.newmaptxt, pos = (1, 0),
296 span = (1, 2))
297 buttonSizer3.Add(item = self.mapsellabel, pos = (2, 0),
298 span = (1, 2), flag = wx.ALIGN_CENTER)
299 buttonSizer3.Add(item = self.mapselect, pos = (3, 0),
300 span = (1, 2))
301 buttonSizer3.Add(item = self.functlabel, pos = (4, 0),
302 span = (1, 2), flag = wx.ALIGN_CENTER)
303 buttonSizer3.Add(item = self.function, pos = (5, 0),
304 span = (1, 2))
305 buttonSizer3.Add(item = self.btn['paren'], pos = (6, 0),
306 flag = wx.ALIGN_LEFT)
307 buttonSizer3.Add(item = self.btn_clear, pos = (6, 1),
308 flag = wx.ALIGN_RIGHT)
309
310 buttonSizer4 = wx.BoxSizer(wx.HORIZONTAL)
311 buttonSizer4.Add(item = self.btn_cmd,
312 flag = wx.ALL, border = 5)
313 buttonSizer4.Add(item = self.btn_close,
314 flag = wx.ALL, border = 5)
315 buttonSizer4.Add(item = self.btn_save,
316 flag = wx.ALL, border = 5)
317 buttonSizer4.Add(item = self.btn_load,
318 flag = wx.ALL, border = 5)
319 buttonSizer4.Add(item = self.btn_run,
320 flag = wx.ALL, border = 5)
321 buttonSizer4.Add(item = self.btn_help,
322 flag = wx.ALL, border = 5)
323
324 operatorSizer.Add(item = buttonSizer1, proportion = 0,
325 flag = wx.ALL | wx.EXPAND, border = 5)
326 operatorSizer.Add(item = buttonSizer2, proportion = 0,
327 flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND, border = 5)
328
329 operandSizer.Add(item = buttonSizer3, proportion = 0,
330 flag = wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
331
332 controlSizer.Add(item = operatorSizer, proportion = 1,
333 flag = wx.RIGHT, border = 5)
334 controlSizer.Add(item = operandSizer, proportion = 0,
335 flag = wx.EXPAND)
336
337 expressSizer = wx.StaticBoxSizer(self.expressBox, wx.HORIZONTAL)
338 expressSizer.Add(item = self.text_mcalc, proportion = 1,
339 flag = wx.EXPAND)
340
341 sizer.Add(item = controlSizer, proportion = 0,
342 flag = wx.EXPAND | wx.ALL,
343 border = 5)
344 sizer.Add(item = expressSizer, proportion = 1,
345 flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
346 border = 5)
347 sizer.Add(item = self.overwrite, proportion = 0,
348 flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
349 border = 5)
350 sizer.Add(item = self.addbox, proportion = 0,
351 flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
352 border = 5)
353 #~ sizer.Add(item=self.addbox, proportion=0,
354 #~ flag=wx.EXPAND | wx.ALL, border=1)
355 sizer.Add(item = buttonSizer4, proportion = 0,
356 flag = wx.ALL | wx.ALIGN_RIGHT, border = 1)
357
358 self.panel.SetAutoLayout(True)
359 self.panel.SetSizer(sizer)
360 sizer.Fit(self.panel)
361
362 self.Fit()
363 self.Layout()
364
365 #~ self.addbox = wx.CheckBox(parent = self.panel,
366 #~ label = _('Add created map into layer tree'), style = wx.NO_BORDER)
367 disableAdd=False
368 if disableAdd:
369 self.addbox.SetValue(True)
370 self.addbox.Enable(False)
371 else:
372 self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
373
374
375 def AddMark(self,event):
376 """!Sends operators to insertion method
377 """
378 if event.GetId() == self.btn['compl'].GetId(): mark = "~"
379 elif event.GetId() == self.btn['not'].GetId(): mark = "!"
380 elif event.GetId() == self.btn['pow'].GetId(): mark = "^"
381 elif event.GetId() == self.btn['div'].GetId(): mark = "/"
382 elif event.GetId() == self.btn['add'].GetId(): mark = "+"
383 elif event.GetId() == self.btn['minus'].GetId(): mark = "-"
384 elif event.GetId() == self.btn['mod'].GetId(): mark = "%"
385 elif event.GetId() == self.btn['mult'].GetId(): mark = "*"
386 elif event.GetId() == self.btn['lshift'].GetId(): mark = "<<"
387 elif event.GetId() == self.btn['rshift'].GetId(): mark = ">>"
388 elif event.GetId() == self.btn['rshiftu'].GetId(): mark = ">>>"
389 elif event.GetId() == self.btn['gt'].GetId(): mark = ">"
390 elif event.GetId() == self.btn['gteq'].GetId(): mark = ">="
391 elif event.GetId() == self.btn['lt'].GetId(): mark = "<"
392 elif event.GetId() == self.btn['lteq'].GetId(): mark = "<="
393 elif event.GetId() == self.btn['eq'].GetId(): mark = "=="
394 elif event.GetId() == self.btn['noteq'].GetId(): mark = "!="
395 elif event.GetId() == self.btn['andbit'].GetId(): mark = "&"
396 elif event.GetId() == self.btn['orbit'].GetId(): mark = "|"
397 elif event.GetId() == self.btn['or'].GetId(): mark = "||"
398 elif event.GetId() == self.btn['ornull'].GetId(): mark = "|||"
399 elif event.GetId() == self.btn['and'].GetId(): mark = "&&"
400 elif event.GetId() == self.btn['andnull'].GetId(): mark = "&&&"
401 elif event.GetId() == self.btn['cond'].GetId(): mark = " ? : "
402 elif event.GetId() == self.btn['paren'].GetId(): mark = "( )"
403 self._addSomething(mark)
404
405 def OnSelect(self, event):
406 """!Gets raster map or function selection and send it to
407 insertion method
408 """
409 item = event.GetString()
410 self._addSomething(item)
411
412 def _addSomething(self, what):
413 """!Inserts operators, map names, and functions into text area
414 """
415 self.text_mcalc.SetFocus()
416 mcalcstr = self.text_mcalc.GetValue()
417 position = self.text_mcalc.GetInsertionPoint()
418
419 newmcalcstr = mcalcstr[:position]
420
421 position_offset = 0
422 try:
423 if newmcalcstr[-1] != ' ':
424 newmcalcstr += ' '
425 position_offset += 1
426 except:
427 pass
428
429 newmcalcstr += what
430 position_offset += len(what)
431 newmcalcstr += ' ' + mcalcstr[position:]
432
433 self.text_mcalc.SetValue(newmcalcstr)
434 if what == '()':
435 position_offset -= 1
436 self.text_mcalc.SetInsertionPoint(position + position_offset)
437 self.text_mcalc.Update()
438
439 def OnMCalcRun(self,event):
440 """!Builds and runs r.mapcalc statement
441 """
442 name = self.newmaptxt.GetValue().strip()
443 if not name:
444 gcmd.GError(parent = self,
445 message = _("You must enter the name of a new map to create"))
446 return
447
448 if not self.text_mcalc.GetValue().strip():
449 gcmd.GError(parent = self,
450 message = _("You must enter a mapcalc statement to create a new map"))
451 return
452
453 mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
454 mctxt = mctxt.replace(" " , "")
455
456 if self.log:
457 cmd = [self.cmd, str('expression=%s = %s' % (name, mctxt))]
458 if self.overwrite.IsChecked():
459 cmd.append('--overwrite')
460 self.log.RunCmd(cmd)
461 self.parent.Raise()
462 else:
463 if self.overwrite.IsChecked():
464 overwrite = True
465 else:
466 overwrite = False
467 gcmd.RunCommand(self.cmd,
468 expression = "%s=%s" % (name, mctxt),
469 overwrite = overwrite)
470
471 #~ if not self.addbox.IsChecked():
472 #~ return
473 #~
474 #~ maptree = self.parent.curr_page.maptree
475 #~
476 #~ layer, output = self.list.GetLayers()[self.commandId]
477 #~
478 #~ if '@' not in output:
479 #~ name = output + '@' + grass.gisenv()['MAPSET']
480 #~ else:
481 #~ name = output
482 #~ # add imported layers into layer tree
483 #~ cmd = ['d.rast', 'map=%s' % name]
484 #~ if UserSettings.Get(group='cmd', key='rasterOpaque', subkey='enabled'):
485 #~ cmd.append('-n')
486 #~ item = maptree.AddLayer(ltype='raster', lname=name, lcmd=cmd)
487#~
488 #~ maptree.mapdisplay.MapWindow.ZoomToMap()
489
490 def OnClear(self, event):
491 """!Clears text area
492 """
493 self.text_mcalc.SetValue('')
494
495 def OnHelp(self, event):
496 """!Launches r.mapcalc help
497 """
498 gcmd.RunCommand('g.manual', parent = self, entry = self.cmd)
499
500 def OnClose(self,event):
501 """!Close window"""
502 self.Destroy()
503
504 def OnSaveDialog(self, event):
505 """saves expresseion to file
506 """
507
508 mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
509 mctxt = mctxt.replace(" " , "")
510
511 #dialog
512 filetype = "Expression file (*.exp)|*.exp|Text file (*.txt)|*.txt"
513 ltype = [{ 'ext' : 'exp', 'type' : -1 },
514 { 'ext' : 'tif', 'type' : wx.BITMAP_TYPE_TIF }]
515
516 # get filename
517 dlg = wx.FileDialog(parent = self,
518 message = _("Choose a file name to save the expression"),
519 wildcard = filetype,
520 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
521 if dlg.ShowModal() == wx.ID_OK:
522 path = dlg.GetPath()
523 if not path:
524 dlg.Destroy()
525 return
526
527 base, ext = os.path.splitext(path)
528 fileType = ltype[dlg.GetFilterIndex()]['type']
529 #extType = ltype[dlg.GetFilterIndex()]['ext']
530 suffix = '_mcalc'
531 extType = 'exp'
532
533 if ext != extType:
534 path = base + suffix + '.' + extType
535
536 fobj = open(path,'w')
537 fobj.write(mctxt)
538 fobj.close()
539 #self.MapWindow.SaveToFile(path, fileType,
540 # width, height)
541
542 dlg.Destroy()
543
544
545
546 def OnLoadDialog(self, event):
547 """load expresseion from file
548 """
549
550 #mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
551 #mctxt = mctxt.replace(" " , "")
552
553 #dialog
554 filetype = "Expression file (*.exp)|*.exp|Text file (*.txt)|*.txt"
555 ltype = [{ 'ext' : 'exp', 'type' : -1 },
556 { 'ext' : 'tif', 'type' : wx.BITMAP_TYPE_TIF }]
557
558 # get filename
559 dlg = wx.FileDialog(parent = self,
560 message = _("Choose a file name to load the expression"),
561 wildcard = filetype,
562 style=wx.OPEN)
563 if dlg.ShowModal() == wx.ID_OK:
564 path = dlg.GetPath()
565 print path
566 if not path:
567 dlg.Destroy()
568 return
569
570 base, ext = os.path.splitext(path)
571 fileType = ltype[dlg.GetFilterIndex()]['type']
572 #extType = ltype[dlg.GetFilterIndex()]['ext']
573 suffix = '_mcalc'
574 extType = 'exp'
575
576 #if ext != extType:
577 # path = base + suffix + '.' + extType
578
579 fobj = open(path,'r')
580 mctxt = fobj.read()
581 fobj.close()
582 print mctxt
583 self.text_mcalc.SetValue(mctxt)
584 self.text_mcalc.Update()
585 #self.MapWindow.SaveToFile(path, fileType,
586 # width, height)
587
588 dlg.Destroy()
589
590
591
592
593 def OnCmdDialog(self, event):
594 """!Shows command dialog"""
595 name = self.newmaptxt.GetValue().strip()
596 mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
597 mctxt = mctxt.replace(" " , "")
598 expr = name
599 if expr:
600 expr += '='
601 expr += mctxt
602
603 menuform.GUI().ParseCommand(cmd = [self.cmd, 'expression=' + expr],
604 parentframe = self)
605
606if __name__ == "__main__":
607 app = wx.App(0)
608 frame = MapCalcFrame(None, cmd = 'r.mapcalc')
609 frame.Show()
610 app.MainLoop()
611