gmodeler.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. """!
  2. @package gmodeler.py
  3. @brief Graphical modeler to create edit, and manage models
  4. Classes:
  5. - ModelFrame
  6. - ModelCanvas
  7. - ModelAction
  8. - ModelSearchDialog
  9. - ModelData
  10. - ModelDataDialog
  11. - ProcessModelFile
  12. - WriteModelFile
  13. (C) 2010 by the GRASS Development Team
  14. This program is free software under the GNU General Public License
  15. (>=v2). Read the file COPYING that comes with GRASS for details.
  16. @author Martin Landa <landa.martin gmail.com>
  17. """
  18. import os
  19. import sys
  20. import shlex
  21. import time
  22. import traceback
  23. try:
  24. import xml.etree.ElementTree as etree
  25. except ImportError:
  26. import elementtree.ElementTree as etree # Python <= 2.4
  27. import globalvar
  28. if not os.getenv("GRASS_WXBUNDLED"):
  29. globalvar.CheckForWx()
  30. import wx
  31. import wx.lib.ogl as ogl
  32. import wx.lib.flatnotebook as FN
  33. import menu
  34. import menudata
  35. import toolbars
  36. import menuform
  37. import prompt
  38. import utils
  39. import goutput
  40. import gselect
  41. from debug import Debug
  42. from gcmd import GMessage
  43. from gdialogs import ElementDialog
  44. from grass.script import core as grass
  45. class ModelFrame(wx.Frame):
  46. def __init__(self, parent, id = wx.ID_ANY, title = _("Graphical modeler (under development)"), **kwargs):
  47. """!Graphical modeler main window
  48. @param parent parent window
  49. @param id window id
  50. @param title window title
  51. @param kwargs wx.Frames' arguments
  52. """
  53. self.parent = parent
  54. self.searchDialog = None # module search dialog
  55. self.actions = list() # list of recorded actions
  56. self.data = list() # list of recorded data items
  57. self.baseTitle = title
  58. self.modelFile = None # loaded model
  59. self.modelChanged = False
  60. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  61. self.SetName("Modeler")
  62. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  63. self.menubar = menu.Menu(parent = self, data = menudata.ModelerData())
  64. self.SetMenuBar(self.menubar)
  65. self.toolbar = toolbars.ModelToolbar(parent = self)
  66. self.SetToolBar(self.toolbar)
  67. self.statusbar = self.CreateStatusBar(number = 1)
  68. self.notebook = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
  69. style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
  70. FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON)
  71. self.canvas = ModelCanvas(self)
  72. self.canvas.SetBackgroundColour(wx.WHITE)
  73. self.goutput = goutput.GMConsole(parent = self, pageid = 1)
  74. self.modelPage = self.notebook.AddPage(self.canvas, text=_('Model'))
  75. self.commandPage = self.notebook.AddPage(self.goutput, text=_('Command output'))
  76. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  77. self._layout()
  78. self.SetMinSize((350, 200))
  79. self.SetSize((640, 480))
  80. def _layout(self):
  81. """!Do layout"""
  82. sizer = wx.BoxSizer(wx.VERTICAL)
  83. sizer.Add(item = self.notebook, proportion = 1,
  84. flag = wx.EXPAND)
  85. self.SetAutoLayout(True)
  86. self.SetSizer(sizer)
  87. sizer.Fit(self)
  88. self.Layout()
  89. def _addEvent(self, item):
  90. """!Add event to item"""
  91. evthandler = ModelEvtHandler(self.statusbar,
  92. self)
  93. evthandler.SetShape(item)
  94. evthandler.SetPreviousHandler(item.GetEventHandler())
  95. item.SetEventHandler(evthandler)
  96. def ModelChanged(self):
  97. """!Update window title"""
  98. if not self.modelChanged:
  99. self.modelChanged = True
  100. if self.modelFile:
  101. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile) + '*')
  102. def OnCloseWindow(self, event):
  103. """!Close window"""
  104. self.Destroy()
  105. def OnModelNew(self, event):
  106. """!Create new model"""
  107. pass
  108. def OnModelOpen(self, event):
  109. """!Load model from file"""
  110. filename = ''
  111. dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
  112. defaultDir = os.getcwd(),
  113. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  114. if dlg.ShowModal() == wx.ID_OK:
  115. filename = dlg.GetPath()
  116. if not filename:
  117. return
  118. Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
  119. # close current model
  120. ### self.OnModelClose()
  121. self.LoadModelFile(filename)
  122. self.modelFile = filename
  123. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  124. self.SetStatusText(_('%d actions loaded into model') % len(self.actions), 0)
  125. def OnModelSave(self, event):
  126. """!Save model to file"""
  127. if self.modelFile:
  128. dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
  129. "Do you want to overwrite this file?") % \
  130. self.modelFile,
  131. caption=_("Save model"),
  132. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  133. if dlg.ShowModal() == wx.ID_NO:
  134. dlg.Destroy()
  135. else:
  136. Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
  137. self.WriteModelFile(self.modelFile)
  138. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  139. else:
  140. self.OnModelSaveAs(None)
  141. def OnModelSaveAs(self, event):
  142. """!Create model to file as"""
  143. filename = ''
  144. dlg = wx.FileDialog(parent = self,
  145. message = _("Choose file to save current model"),
  146. defaultDir = os.getcwd(),
  147. wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
  148. style=wx.FD_SAVE)
  149. if dlg.ShowModal() == wx.ID_OK:
  150. filename = dlg.GetPath()
  151. if not filename:
  152. return
  153. # check for extension
  154. if filename[-4:] != ".gxm":
  155. filename += ".gxm"
  156. if os.path.exists(filename):
  157. dlg = wx.MessageDialog(parent = self,
  158. message=_("Model file <%s> already exists. "
  159. "Do you want to overwrite this file?") % filename,
  160. caption=_("File already exists"),
  161. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  162. if dlg.ShowModal() != wx.ID_YES:
  163. dlg.Destroy()
  164. return
  165. Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
  166. self.WriteModelFile(filename)
  167. self.modelFile = filename
  168. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  169. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  170. def OnModelClose(self, event):
  171. """!Close model file"""
  172. Debug.msg(4, "ModelFrame.OnModelClose(): file=%s" % self.modelFile)
  173. self.modelFile = None
  174. self.SetTitle(self.baseTitle)
  175. self.canvas.GetDiagram().DeleteAllShapes()
  176. self.actions = list()
  177. self.data = list()
  178. self.canvas.Refresh()
  179. def OnRunModel(self, event):
  180. """!Run entire model"""
  181. if len(self.actions) < 1:
  182. GMessage(parent = self,
  183. message = _('Model is empty. Nothing to run.'),
  184. msgType = 'info')
  185. return
  186. errList = self._validateModel()
  187. if errList:
  188. dlg = wx.MessageDialog(parent = self,
  189. message = _('Model is not valid. Do you want to '
  190. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  191. caption=_("Run model?"),
  192. style = wx.YES_NO | wx.NO_DEFAULT |
  193. wx.ICON_QUESTION | wx.CENTRE)
  194. ret = dlg.ShowModal()
  195. if ret != wx.ID_YES:
  196. return
  197. for action in self.actions:
  198. self.SetStatusText(_('Running model...'), 0)
  199. self.goutput.RunCmd(command = action.GetLog(string = False),
  200. onDone = self.OnDone)
  201. def OnDone(self, returncode):
  202. """!Computation finished"""
  203. self.SetStatusText('', 0)
  204. def OnValidateModel(self, event, showMsg = True):
  205. """!Validate entire model"""
  206. if len(self.actions) < 1:
  207. GMessage(parent = self,
  208. message = _('Model is empty. Nothing to validate.'),
  209. msgType = 'info')
  210. return
  211. errList = self._validateModel()
  212. if errList:
  213. GMessage(parent = self,
  214. message = _('Model is not valid.\n\n%s') % '\n'.join(errList),
  215. msgType = 'warning')
  216. else:
  217. GMessage(parent = self,
  218. message = _('Model is valid.'),
  219. msgType = 'info')
  220. def _validateModel(self):
  221. """!Validate model"""
  222. self.SetStatusText(_('Validating model...'), 0)
  223. errList = list()
  224. for action in self.actions:
  225. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  226. show = None)
  227. errList += task.getCmdError()
  228. self.SetStatusText('', 0)
  229. return errList
  230. def OnRemoveItem(self, event):
  231. """!Remove item from model"""
  232. pass
  233. def OnAddAction(self, event):
  234. """!Add action to model"""
  235. if self.searchDialog is None:
  236. self.searchDialog = ModelSearchDialog(self)
  237. self.searchDialog.CentreOnParent()
  238. else:
  239. self.searchDialog.Reset()
  240. if self.searchDialog.ShowModal() == wx.ID_CANCEL:
  241. self.searchDialog.Hide()
  242. return
  243. cmd = self.searchDialog.GetCmd()
  244. self.searchDialog.Hide()
  245. self.ModelChanged()
  246. # add action to canvas
  247. width, height = self.canvas.GetSize()
  248. action = ModelAction(self, cmd = cmd, x = width/2, y = height/2)
  249. self.canvas.diagram.AddShape(action)
  250. action.Show(True)
  251. self._addEvent(action)
  252. self.actions.append(action)
  253. self.canvas.Refresh()
  254. time.sleep(.1)
  255. # show properties dialog
  256. win = action.GetPropDialog()
  257. if not win:
  258. module = menuform.GUI().ParseCommand(action.GetLog(string = False),
  259. completed = (self.GetOptData, action, None),
  260. parentframe = self, show = True)
  261. elif not win.IsShown():
  262. win.Show()
  263. if win:
  264. win.Raise()
  265. def OnAddData(self, event):
  266. """!Add data item to model"""
  267. # add action to canvas
  268. width, height = self.canvas.GetSize()
  269. data = ModelData(self, x = width/2, y = height/2)
  270. self.canvas.diagram.AddShape(data)
  271. data.Show(True)
  272. self._addEvent(data)
  273. self.data.append(data)
  274. self.canvas.Refresh()
  275. def OnHelp(self, event):
  276. """!Display manual page"""
  277. grass.run_command('g.manual',
  278. entry = 'wxGUI.Modeler')
  279. def OnAbout(self, event):
  280. """!Display About window"""
  281. info = wx.AboutDialogInfo()
  282. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  283. info.SetName(_('wxGUI Graphical Modeler'))
  284. info.SetWebSite('http://grass.osgeo.org')
  285. info.SetDescription(_('(C) 2010 by the GRASS Development Team\n\n'
  286. 'This program is free software under the GNU General Public License'
  287. '(>=v2). Read the file COPYING that comes with GRASS for details.'))
  288. wx.AboutBox(info)
  289. def GetOptData(self, dcmd, layer, params, propwin):
  290. """!Process action data"""
  291. layer.SetProperties(dcmd, params, propwin)
  292. if params: # add data items
  293. width, height = self.canvas.GetSize()
  294. x = [width/2 + 200, width/2 - 200]
  295. for p in params['params']:
  296. if p.get('value', None) and \
  297. p.get('prompt', '') in ('raster', 'vector', 'raster3d'):
  298. # create data item
  299. data = ModelData(self, name = p.get('name', ''),
  300. value = p.get('value', ''),
  301. prompt = p.get('prompt', ''),
  302. x = x.pop(), y = height/2)
  303. self.canvas.diagram.AddShape(data)
  304. data.Show(True)
  305. self._addEvent(data)
  306. self.data.append(data)
  307. if p.get('age', 'old') == 'old':
  308. self._addLine(data, layer)
  309. data.AddAction(layer, direction = 'from')
  310. else:
  311. self._addLine(layer, data)
  312. data.AddAction(layer, direction = 'to')
  313. self.canvas.Refresh()
  314. self.SetStatusText(layer.GetLog(), 0)
  315. def _addLine(self, fromShape, toShape):
  316. """!Add connection
  317. @param fromShape from
  318. @param toShape to
  319. """
  320. line = ogl.LineShape()
  321. line.SetCanvas(self)
  322. line.SetPen(wx.BLACK_PEN)
  323. line.SetBrush(wx.BLACK_BRUSH)
  324. line.AddArrow(ogl.ARROW_ARROW)
  325. line.MakeLineControlPoints(2)
  326. fromShape.AddLine(line, toShape)
  327. self.canvas.diagram.AddShape(line)
  328. line.Show(True)
  329. def LoadModelFile(self, filename):
  330. """!Load model definition stored in GRASS Model XML file (gxm)
  331. @todo Validate against DTD
  332. Raise exception on error.
  333. """
  334. ### dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  335. # parse workspace file
  336. try:
  337. gxmXml = ProcessModelFile(etree.parse(filename))
  338. except:
  339. GMessage(parent = self,
  340. message = _("Reading model file <%s> failed.\n"
  341. "Invalid file, unable to parse XML document.") % filename)
  342. return
  343. self.modelFile = filename
  344. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  345. busy = wx.BusyInfo(message=_("Please wait, loading model..."),
  346. parent=self)
  347. wx.Yield()
  348. # load actions
  349. for action in gxmXml.actions:
  350. actionShape = ModelAction(parent = self,
  351. x = action['pos'][0],
  352. y = action['pos'][1],
  353. width = action['size'][0],
  354. height = action['size'][1],
  355. cmd = action['cmd'])
  356. self.canvas.diagram.AddShape(actionShape)
  357. actionShape.Show(True)
  358. self._addEvent(actionShape)
  359. self.actions.append(actionShape)
  360. # load data & connections
  361. for data in gxmXml.data:
  362. dataShape = ModelData(parent = self,
  363. x = data['pos'][0],
  364. y = data['pos'][1],
  365. width = data['size'][0],
  366. height = data['size'][1],
  367. name = data['name'],
  368. prompt = data['prompt'],
  369. value = data['value'])
  370. self.canvas.diagram.AddShape(dataShape)
  371. dataShape.Show(True)
  372. self._addEvent(dataShape)
  373. self.data.append(dataShape)
  374. actionShape = self.actions[0]
  375. if data['from'] is True:
  376. self._addLine(dataShape, actionShape)
  377. dataShape.AddAction(actionShape, direction = 'from')
  378. elif data['from'] is False:
  379. self._addLine(actionShape, dataShape)
  380. dataShape.AddAction(actionShape, direction = 'to')
  381. self.canvas.Refresh(True)
  382. def WriteModelFile(self, filename):
  383. """!Save model to model file
  384. @return True on success
  385. @return False on failure
  386. """
  387. try:
  388. file = open(filename, "w")
  389. except IOError:
  390. wx.MessageBox(parent = self,
  391. message = _("Unable to open file <%s> for writing.") % filename,
  392. caption = _("Error"),
  393. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  394. return False
  395. try:
  396. WriteModelFile(fd = file, actions = self.actions, data = self.data)
  397. except StandardError:
  398. file.close()
  399. GMessage(parent = self,
  400. message = _("Writing current settings to model file failed."))
  401. return False
  402. file.close()
  403. return True
  404. class ModelCanvas(ogl.ShapeCanvas):
  405. """!Canvas where model is drawn"""
  406. def __init__(self, parent):
  407. ogl.OGLInitialize()
  408. ogl.ShapeCanvas.__init__(self, parent)
  409. self.diagram = ogl.Diagram()
  410. self.SetDiagram(self.diagram)
  411. self.diagram.SetCanvas(self)
  412. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  413. class ModelAction(ogl.RectangleShape):
  414. """!Action class (GRASS module)"""
  415. def __init__(self, parent, x, y, cmd = None, width = 100, height = 50):
  416. self.parent = parent
  417. self.cmd = cmd
  418. self.params = None
  419. self.propWin = None
  420. ogl.RectangleShape.__init__(self, width, height)
  421. # self.Draggable(True)
  422. self.SetCanvas(self.parent)
  423. self.SetX(x)
  424. self.SetY(y)
  425. self.SetPen(wx.BLACK_PEN)
  426. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  427. if self.cmd and len(self.cmd) > 0:
  428. self.AddText(self.cmd[0])
  429. else:
  430. self.AddText('<<module>>')
  431. def SetProperties(self, dcmd, params, propwin):
  432. """!Record properties dialog"""
  433. self.cmd = dcmd
  434. self.params = params
  435. self.propWin = propwin
  436. def GetPropDialog(self):
  437. """!Get properties dialog"""
  438. return self.propWin
  439. def GetLog(self, string = True):
  440. """!Get logging info"""
  441. if string:
  442. if self.cmd is None:
  443. return ''
  444. else:
  445. return ' '.join(self.cmd)
  446. return self.cmd
  447. def GetName(self):
  448. """!Get name"""
  449. if self.cmd and len(self.cmd) > 0:
  450. return self.cmd[0]
  451. return _('unknown')
  452. def GetParams(self):
  453. """!Get dictionary of parameters"""
  454. return self.params
  455. def SetParams(self, params, cmd):
  456. """!Set dictionary of parameters"""
  457. self.params = params
  458. self.cmd = cmd
  459. class ModelData(ogl.EllipseShape):
  460. """!Data item class"""
  461. def __init__(self, parent, x, y, name = '', value = '', prompt = '', width = 175, height = 50):
  462. self.parent = parent
  463. self.name = name
  464. self.value = value
  465. self.prompt = prompt
  466. self.propWin = None
  467. self.actions = { 'from' : list(), 'to' : list() }
  468. ogl.EllipseShape.__init__(self, width, height)
  469. # self.Draggable(True)
  470. self.SetCanvas(self.parent)
  471. self.SetX(x)
  472. self.SetY(y)
  473. self.SetPen(wx.BLACK_PEN)
  474. if self.prompt == 'raster':
  475. self.SetBrush(wx.Brush(wx.Colour(215, 215, 248)))
  476. elif self.prompt == 'vector':
  477. self.SetBrush(wx.Brush(wx.Colour(248, 215, 215)))
  478. else:
  479. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  480. if name:
  481. self.AddText(name)
  482. self.AddText(value)
  483. else:
  484. self.AddText(_('unknown'))
  485. def GetLog(self, string = True):
  486. """!Get logging info"""
  487. if self.name:
  488. return self.name + '=' + self.value + ' (' + self.prompt + ')'
  489. else:
  490. return _('unknown')
  491. def GetName(self):
  492. """!Get name"""
  493. return self.name
  494. def GetPrompt(self):
  495. """!Get prompt"""
  496. return self.prompt
  497. def GetValue(self):
  498. """!Get value"""
  499. return self.value
  500. def SetValue(self, value):
  501. """!Set value"""
  502. self.value = value
  503. self.ClearText()
  504. self.AddText(self.name)
  505. self.AddText(self.value)
  506. for direction in ('from', 'to'):
  507. for action in self.actions[direction]:
  508. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  509. show = None)
  510. task.set_param(self.name, self.value)
  511. action.SetParams(params = task.get_options(),
  512. cmd = task.getCmd(ignoreErrors = True))
  513. def GetActions(self, direction):
  514. """!Get related actions
  515. @param direction direction - 'from' or 'to'
  516. """
  517. return self.actions[direction]
  518. def AddAction(self, action, direction):
  519. """!Record related actions
  520. @param action action to be recoreded
  521. @param direction direction of relation
  522. """
  523. self.actions[direction].append(action)
  524. def GetPropDialog(self):
  525. """!Get properties dialog"""
  526. return self.propWin
  527. def SetPropDialog(self, win):
  528. """!Get properties dialog"""
  529. self.propWin = win
  530. class ModelDataDialog(ElementDialog):
  531. """!Data item properties dialog"""
  532. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Data properties"),
  533. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  534. self.parent = parent
  535. self.shape = shape
  536. prompt = shape.GetPrompt()
  537. if prompt == 'raster':
  538. label = _('Name of raster map:')
  539. elif prompt == 'vector':
  540. label = _('Name of vector map:')
  541. else:
  542. label = _('Name of element:')
  543. ElementDialog.__init__(self, parent, title, label = label)
  544. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY,
  545. size = globalvar.DIALOG_GSELECT_SIZE,
  546. type = prompt)
  547. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  548. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  549. self.PostInit()
  550. self._layout()
  551. self.SetMinSize(self.GetSize())
  552. def _layout(self):
  553. """!Do layout"""
  554. self.dataSizer.Add(self.element, proportion=0,
  555. flag=wx.EXPAND | wx.ALL, border=1)
  556. self.panel.SetSizer(self.sizer)
  557. self.sizer.Fit(self)
  558. def OnOK(self, event):
  559. """!Ok pressed"""
  560. self.shape.SetValue(self.GetElement())
  561. self.parent.canvas.Refresh()
  562. self.parent.SetStatusText('', 0)
  563. self.OnCancel(event)
  564. def OnCancel(self, event):
  565. """!Cancel pressed"""
  566. self.shape.SetPropDialog(None)
  567. self.Destroy()
  568. class ModelEvtHandler(ogl.ShapeEvtHandler):
  569. """!Model event handler class"""
  570. def __init__(self, log, frame):
  571. ogl.ShapeEvtHandler.__init__(self)
  572. self.log = log
  573. self.frame = frame
  574. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  575. """!Left mouse button pressed -> select item & update statusbar"""
  576. shape = self.GetShape()
  577. canvas = shape.GetCanvas()
  578. dc = wx.ClientDC(canvas)
  579. canvas.PrepareDC(dc)
  580. if shape.Selected():
  581. shape.Select(False, dc)
  582. else:
  583. redraw = False
  584. shapeList = canvas.GetDiagram().GetShapeList()
  585. toUnselect = list()
  586. for s in shapeList:
  587. if s.Selected():
  588. toUnselect.append(s)
  589. shape.Select(True, dc)
  590. for s in toUnselect:
  591. s.Select(False, dc)
  592. canvas.Refresh(False)
  593. self.log.SetStatusText(shape.GetLog(), 0)
  594. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  595. """!Left mouse button pressed (double-click) -> show properties"""
  596. self.OnProperties()
  597. def OnProperties(self, event = None):
  598. """!Show properties dialog"""
  599. self.frame.ModelChanged()
  600. shape = self.GetShape()
  601. win = shape.GetPropDialog()
  602. if not win:
  603. if isinstance(shape, ModelAction):
  604. module = menuform.GUI().ParseCommand(shape.cmd,
  605. completed = (self.frame.GetOptData, shape, None),
  606. parentframe = self.frame, show = True)
  607. elif isinstance(shape, ModelData):
  608. dlg = ModelDataDialog(parent = self.frame, shape = shape)
  609. shape.SetPropDialog(dlg)
  610. dlg.CentreOnParent()
  611. dlg.Show()
  612. elif win and not win.IsShown():
  613. win.Show()
  614. if win:
  615. win.Raise()
  616. def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
  617. """!Drag shape"""
  618. self.frame.ModelChanged()
  619. if self._previousHandler:
  620. self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
  621. def OnRightClick(self, x, y, keys = 0, attachment = 0):
  622. """!Right click -> pop-up menu"""
  623. if not hasattr (self, "popupID1"):
  624. self.popupID1 = wx.NewId()
  625. self.popupID2 = wx.NewId()
  626. popupMenu = wx.Menu()
  627. popupMenu.Append(self.popupID1, text=_('Remove'))
  628. self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  629. popupMenu.AppendSeparator()
  630. popupMenu.Append(self.popupID2, text=_('Properties'))
  631. self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID2)
  632. self.frame.PopupMenu(popupMenu)
  633. popupMenu.Destroy()
  634. def OnRemove(self, event):
  635. """!Remove shape"""
  636. shape = self.GetShape()
  637. self.frame.canvas.GetDiagram().RemoveShape(shape)
  638. self.frame.canvas.Refresh()
  639. class ModelSearchDialog(wx.Dialog):
  640. def __init__(self, parent, id = wx.ID_ANY, title = _("Find GRASS module"),
  641. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  642. """!Graphical modeler module search window
  643. @param parent parent window
  644. @param id window id
  645. @param title window title
  646. @param kwargs wx.Dialogs' arguments
  647. """
  648. self.parent = parent
  649. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  650. self.SetName("ModelerDialog")
  651. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  652. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  653. self.searchBy = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  654. choices = [_("description"),
  655. _("keywords")])
  656. self.search = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  657. value = "", size = (-1, 25))
  658. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  659. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  660. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  661. self.btnOk.SetDefault()
  662. self._layout()
  663. def _layout(self):
  664. btnSizer = wx.StdDialogButtonSizer()
  665. btnSizer.AddButton(self.btnCancel)
  666. btnSizer.AddButton(self.btnOk)
  667. btnSizer.Realize()
  668. bodyBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  669. label=" %s " % _("Find GRASS module"))
  670. bodySizer = wx.StaticBoxSizer(bodyBox, wx.VERTICAL)
  671. searchSizer = wx.BoxSizer(wx.HORIZONTAL)
  672. searchSizer.Add(item = self.searchBy,
  673. proportion = 0, flag = wx.LEFT, border = 3)
  674. searchSizer.Add(item = self.search,
  675. proportion = 1, flag = wx.LEFT | wx.EXPAND, border = 3)
  676. bodySizer.Add(item=searchSizer, proportion=0,
  677. flag=wx.EXPAND | wx.ALL, border=1)
  678. bodySizer.Add(item=self.cmd_prompt, proportion=1,
  679. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  680. mainSizer = wx.BoxSizer(wx.VERTICAL)
  681. mainSizer.Add(item=bodySizer, proportion=1,
  682. flag=wx.EXPAND | wx.ALL, border=5)
  683. mainSizer.Add(item=btnSizer, proportion=0,
  684. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  685. self.panel.SetSizer(mainSizer)
  686. mainSizer.Fit(self.panel)
  687. def GetPanel(self):
  688. """!Get dialog panel"""
  689. return self.panel
  690. def GetCmd(self):
  691. """!Get command"""
  692. line = self.cmd_prompt.GetCurLine()[0].strip()
  693. if len(line) == 0:
  694. list()
  695. try:
  696. cmd = shlex.split(str(line))
  697. except UnicodeError:
  698. cmd = shlex.split(utils.EncodeString((line)))
  699. return cmd
  700. def OnOk(self, event):
  701. self.btnOk.SetFocus()
  702. def Reset(self):
  703. """!Reset dialog"""
  704. self.searchBy.SetSelection(0)
  705. self.search.SetValue('')
  706. self.cmd_prompt.OnCmdErase(None)
  707. class ProcessModelFile:
  708. """!Process GRASS model file (gxm)"""
  709. def __init__(self, tree):
  710. """!A ElementTree handler for the GXM XML file, as defined in
  711. grass-gxm.dtd.
  712. """
  713. self.tree = tree
  714. self.root = self.tree.getroot()
  715. # list of actions, data
  716. self.actions = list()
  717. self.data = list()
  718. self._processActions()
  719. self._processData()
  720. def _filterValue(self, value):
  721. """!Filter value
  722. @param value
  723. """
  724. value = value.replace('&lt;', '<')
  725. value = value.replace('&gt;', '>')
  726. return value
  727. def _getNodeText(self, node, tag, default = ''):
  728. """!Get node text"""
  729. p = node.find(tag)
  730. if p is not None:
  731. return utils.normalize_whitespace(p.text)
  732. return default
  733. def _processActions(self):
  734. """!Process model file"""
  735. for action in self.root.findall('action'):
  736. pos, size = self._getDim(action)
  737. task = action.find('task')
  738. if task:
  739. cmd = self._processTask(task)
  740. else:
  741. cmd = None
  742. self.actions.append({ 'pos' : pos,
  743. 'size': size,
  744. 'cmd' : cmd })
  745. def _getDim(self, node):
  746. """!Get position and size of shape"""
  747. pos = size = None
  748. posAttr = node.get('pos', None)
  749. if posAttr:
  750. posVal = map(int, posAttr.split(','))
  751. try:
  752. pos = (posVal[0], posVal[1])
  753. except:
  754. pos = None
  755. sizeAttr = node.get('size', None)
  756. if sizeAttr:
  757. sizeVal = map(int, sizeAttr.split(','))
  758. try:
  759. size = (sizeVal[0], sizeVal[1])
  760. except:
  761. size = None
  762. return pos, size
  763. def _processData(self):
  764. """!Process model file"""
  765. for data in self.root.findall('data'):
  766. pos, size = self._getDim(data)
  767. param = data.find('parameter')
  768. name = prompt = value = None
  769. if param is not None:
  770. name = param.get('name', None)
  771. prompt = param.get('prompt', None)
  772. value = self._filterValue(self._getNodeText(param, 'value'))
  773. action = data.find('action')
  774. aId = fromDir = None
  775. if action is not None:
  776. aId = int(action.get('id', None))
  777. if action.get('dir', 'to') == 'to':
  778. fromDir = False
  779. else:
  780. fromDir = True
  781. self.data.append({ 'pos' : pos,
  782. 'size': size,
  783. 'name' : name,
  784. 'prompt' : prompt,
  785. 'value' : value,
  786. 'id' : aId,
  787. 'from' : fromDir })
  788. def _processTask(self, node):
  789. """!Process task"""
  790. cmd = list()
  791. name = node.get('name', None)
  792. if not name:
  793. return cmd
  794. cmd.append(name)
  795. # flags
  796. for p in node.findall('flag'):
  797. flag = p.get('name', '')
  798. if len(flag) > 1:
  799. cmd.append('--' + flag)
  800. else:
  801. cmd.append('-' + flag)
  802. # parameters
  803. for p in node.findall('parameter'):
  804. cmd.append('%s=%s' % (p.get('name', ''),
  805. self._filterValue(self._getNodeText(p, 'value'))))
  806. return cmd
  807. class WriteModelFile:
  808. """!Generic class for writing model file"""
  809. def __init__(self, fd, actions, data):
  810. self.fd = fd
  811. self.actions = actions
  812. self.data = data
  813. self.indent = 0
  814. self._header()
  815. self._actions()
  816. self._data()
  817. self._footer()
  818. def _filterValue(self, value):
  819. """!Make value XML-valid"""
  820. value = value.replace('<', '&lt;')
  821. value = value.replace('>', '&gt;')
  822. return value
  823. def _header(self):
  824. """!Write header"""
  825. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  826. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  827. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  828. def _footer(self):
  829. """!Write footer"""
  830. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  831. def _actions(self):
  832. """!Write actions"""
  833. id = 1
  834. self.indent += 4
  835. for action in self.actions:
  836. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  837. (' ' * self.indent, id, action.GetName(), action.GetX(), action.GetY(),
  838. action.GetWidth(), action.GetHeight()))
  839. self.indent += 4
  840. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  841. self.indent += 4
  842. for key, val in action.GetParams().iteritems():
  843. if key == 'flags':
  844. for f in val:
  845. if f.get('value', False):
  846. self.fd.write('%s<flag name="%s" />\n' %
  847. (' ' * self.indent, f.get('name', '')))
  848. else: # parameter
  849. for p in val:
  850. if not p.get('value', ''):
  851. continue
  852. self.fd.write('%s<parameter name="%s">\n' %
  853. (' ' * self.indent, p.get('name', '')))
  854. self.indent += 4
  855. self.fd.write('%s<value>%s</value>\n' %
  856. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  857. self.indent -= 4
  858. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  859. self.indent -= 4
  860. self.fd.write('%s</task>\n' % (' ' * self.indent))
  861. self.indent -= 4
  862. self.fd.write('%s</action>\n' % (' ' * self.indent))
  863. id += 1
  864. self.indent -= 4
  865. def _data(self):
  866. """!Write data"""
  867. self.indent += 4
  868. for data in self.data:
  869. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  870. (' ' * self.indent, data.GetX(), data.GetY(),
  871. data.GetWidth(), data.GetHeight()))
  872. self.indent += 4
  873. self.fd.write('%s<parameter name="%s" prompt="%s">\n' % \
  874. (' ' * self.indent, data.GetName(), data.GetPrompt()))
  875. self.indent += 4
  876. self.fd.write('%s<value>%s</value>\n' %
  877. (' ' * self.indent, self._filterValue(data.GetValue())))
  878. self.indent -= 4
  879. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  880. self.indent -= 4
  881. for action in data.GetActions('from'):
  882. self.fd.write('%s<action id="1" dir="from" />\n' % \
  883. (' ' * self.indent))
  884. for action in data.GetActions('to'):
  885. self.fd.write('%s<action id="1" dir="to" />\n' % \
  886. (' ' * self.indent))
  887. self.fd.write('%s</data>\n' % (' ' * self.indent))
  888. self.indent -= 4
  889. def main():
  890. app = wx.PySimpleApp()
  891. frame = ModelFrame(parent = None)
  892. if len(sys.argv) > 1:
  893. frame.LoadModelFile(sys.argv[1])
  894. # frame.CentreOnScreen()
  895. frame.Show()
  896. app.MainLoop()
  897. if __name__ == "__main__":
  898. main()