gmodeler.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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. import getpass
  24. import stat
  25. import textwrap
  26. try:
  27. import xml.etree.ElementTree as etree
  28. except ImportError:
  29. import elementtree.ElementTree as etree # Python <= 2.4
  30. import globalvar
  31. if not os.getenv("GRASS_WXBUNDLED"):
  32. globalvar.CheckForWx()
  33. import wx
  34. import wx.lib.ogl as ogl
  35. import wx.lib.flatnotebook as FN
  36. import menu
  37. import menudata
  38. import toolbars
  39. import menuform
  40. import prompt
  41. import utils
  42. import goutput
  43. import gselect
  44. from debug import Debug
  45. from gcmd import GMessage
  46. from gdialogs import ElementDialog
  47. from grass.script import core as grass
  48. class ModelFrame(wx.Frame):
  49. def __init__(self, parent, id = wx.ID_ANY, title = _("Graphical modeler (under development)"), **kwargs):
  50. """!Graphical modeler main window
  51. @param parent parent window
  52. @param id window id
  53. @param title window title
  54. @param kwargs wx.Frames' arguments
  55. """
  56. self.parent = parent
  57. self.searchDialog = None # module search dialog
  58. self.actions = list() # list of recorded actions
  59. self.data = list() # list of recorded data items
  60. self.baseTitle = title
  61. self.modelFile = None # loaded model
  62. self.modelChanged = False
  63. self.cursors = {
  64. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  65. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  66. }
  67. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  68. self.SetName("Modeler")
  69. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  70. self.menubar = menu.Menu(parent = self, data = menudata.ModelerData())
  71. self.SetMenuBar(self.menubar)
  72. self.toolbar = toolbars.ModelToolbar(parent = self)
  73. self.SetToolBar(self.toolbar)
  74. self.statusbar = self.CreateStatusBar(number = 1)
  75. self.notebook = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
  76. style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
  77. FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON)
  78. self.canvas = ModelCanvas(self)
  79. self.canvas.SetBackgroundColour(wx.WHITE)
  80. self.canvas.SetCursor(self.cursors["default"])
  81. self.goutput = goutput.GMConsole(parent = self, pageid = 1)
  82. self.modelPage = self.notebook.AddPage(self.canvas, text=_('Model'))
  83. self.commandPage = self.notebook.AddPage(self.goutput, text=_('Command output'))
  84. wx.CallAfter(self.notebook.SetSelection, 0)
  85. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  86. self._layout()
  87. self.SetMinSize((350, 200))
  88. self.SetSize((640, 480))
  89. def _layout(self):
  90. """!Do layout"""
  91. sizer = wx.BoxSizer(wx.VERTICAL)
  92. sizer.Add(item = self.notebook, proportion = 1,
  93. flag = wx.EXPAND)
  94. self.SetAutoLayout(True)
  95. self.SetSizer(sizer)
  96. sizer.Fit(self)
  97. self.Layout()
  98. def _addEvent(self, item):
  99. """!Add event to item"""
  100. evthandler = ModelEvtHandler(self.statusbar,
  101. self)
  102. evthandler.SetShape(item)
  103. evthandler.SetPreviousHandler(item.GetEventHandler())
  104. item.SetEventHandler(evthandler)
  105. def FindAction(self, id):
  106. """!Find action by id"""
  107. for action in self.actions:
  108. if action.GetId() == id:
  109. return action
  110. return None
  111. def FindData(self, value, prompt):
  112. """!Find data by value, and prompt"""
  113. for data in self.data:
  114. if data.GetValue() == value and \
  115. data.GetPrompt() == prompt:
  116. return data
  117. return None
  118. def ModelChanged(self):
  119. """!Update window title"""
  120. if not self.modelChanged:
  121. self.modelChanged = True
  122. if self.modelFile:
  123. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile) + '*')
  124. def OnCloseWindow(self, event):
  125. """!Close window"""
  126. self.Destroy()
  127. def OnModelNew(self, event):
  128. """!Create new model"""
  129. Debug.msg(4, "ModelFrame.OnModelNew():")
  130. # ask user to save current model
  131. if self.modelFile and self.modelChanged:
  132. self.OnModelSave()
  133. elif self.modelFile is None and \
  134. (len(self.actions) > 0 or len(self.data) > 0):
  135. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  136. "Do you want to store current settings "
  137. "to model file?"),
  138. caption=_("Create new model?"),
  139. style=wx.YES_NO | wx.YES_DEFAULT |
  140. wx.CANCEL | wx.ICON_QUESTION)
  141. ret = dlg.ShowModal()
  142. if ret == wx.ID_YES:
  143. self.OnModelSaveAs()
  144. elif ret == wx.ID_CANCEL:
  145. dlg.Destroy()
  146. return
  147. dlg.Destroy()
  148. # delete all items
  149. self.canvas.GetDiagram().DeleteAllShapes()
  150. self.actions = list()
  151. self.data = list()
  152. self.canvas.Refresh()
  153. # no model file loaded
  154. self.modelFile = None
  155. self.modelChanged = False
  156. self.SetTitle(self.baseTitle)
  157. def OnModelOpen(self, event):
  158. """!Load model from file"""
  159. filename = ''
  160. dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
  161. defaultDir = os.getcwd(),
  162. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  163. if dlg.ShowModal() == wx.ID_OK:
  164. filename = dlg.GetPath()
  165. if not filename:
  166. return
  167. Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
  168. # close current model
  169. self.OnModelClose()
  170. self.LoadModelFile(filename)
  171. self.modelFile = filename
  172. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  173. self.SetStatusText(_('%d actions loaded into model') % len(self.actions), 0)
  174. def OnModelSave(self, event = None):
  175. """!Save model to file"""
  176. if self.modelFile:
  177. dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
  178. "Do you want to overwrite this file?") % \
  179. self.modelFile,
  180. caption=_("Save model"),
  181. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  182. if dlg.ShowModal() == wx.ID_NO:
  183. dlg.Destroy()
  184. else:
  185. Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
  186. self.WriteModelFile(self.modelFile)
  187. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  188. else:
  189. self.OnModelSaveAs(None)
  190. def OnModelSaveAs(self, event):
  191. """!Create model to file as"""
  192. filename = ''
  193. dlg = wx.FileDialog(parent = self,
  194. message = _("Choose file to save current model"),
  195. defaultDir = os.getcwd(),
  196. wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
  197. style=wx.FD_SAVE)
  198. if dlg.ShowModal() == wx.ID_OK:
  199. filename = dlg.GetPath()
  200. if not filename:
  201. return
  202. # check for extension
  203. if filename[-4:] != ".gxm":
  204. filename += ".gxm"
  205. if os.path.exists(filename):
  206. dlg = wx.MessageDialog(parent = self,
  207. message=_("Model file <%s> already exists. "
  208. "Do you want to overwrite this file?") % filename,
  209. caption=_("File already exists"),
  210. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  211. if dlg.ShowModal() != wx.ID_YES:
  212. dlg.Destroy()
  213. return
  214. Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
  215. self.WriteModelFile(filename)
  216. self.modelFile = filename
  217. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  218. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  219. def OnModelClose(self, event = None):
  220. """!Close model file"""
  221. Debug.msg(4, "ModelFrame.OnModelClose(): file=%s" % self.modelFile)
  222. # ask user to save current model
  223. if self.modelFile and self.modelChanged:
  224. self.OnModelSave()
  225. elif self.modelFile is None and \
  226. (len(self.actions) > 0 or len(self.data) > 0):
  227. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  228. "Do you want to store current settings "
  229. "to model file?"),
  230. caption=_("Create new model?"),
  231. style=wx.YES_NO | wx.YES_DEFAULT |
  232. wx.CANCEL | wx.ICON_QUESTION)
  233. ret = dlg.ShowModal()
  234. if ret == wx.ID_YES:
  235. self.OnModelSaveAs()
  236. elif ret == wx.ID_CANCEL:
  237. dlg.Destroy()
  238. return
  239. dlg.Destroy()
  240. self.modelFile = None
  241. self.SetTitle(self.baseTitle)
  242. self.canvas.GetDiagram().DeleteAllShapes()
  243. self.actions = list()
  244. self.data = list()
  245. self.canvas.Refresh()
  246. def OnRunModel(self, event):
  247. """!Run entire model"""
  248. if len(self.actions) < 1:
  249. GMessage(parent = self,
  250. message = _('Model is empty. Nothing to run.'),
  251. msgType = 'info')
  252. return
  253. errList = self._validateModel()
  254. if errList:
  255. dlg = wx.MessageDialog(parent = self,
  256. message = _('Model is not valid. Do you want to '
  257. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  258. caption=_("Run model?"),
  259. style = wx.YES_NO | wx.NO_DEFAULT |
  260. wx.ICON_QUESTION | wx.CENTRE)
  261. ret = dlg.ShowModal()
  262. if ret != wx.ID_YES:
  263. return
  264. for action in self.actions:
  265. self.SetStatusText(_('Running model...'), 0)
  266. self.goutput.RunCmd(command = action.GetLog(string = False),
  267. onDone = self.OnDone)
  268. def OnDone(self, returncode):
  269. """!Computation finished"""
  270. self.SetStatusText('', 0)
  271. def OnValidateModel(self, event, showMsg = True):
  272. """!Validate entire model"""
  273. if len(self.actions) < 1:
  274. GMessage(parent = self,
  275. message = _('Model is empty. Nothing to validate.'),
  276. msgType = 'info')
  277. return
  278. errList = self._validateModel()
  279. if errList:
  280. GMessage(parent = self,
  281. message = _('Model is not valid.\n\n%s') % '\n'.join(errList),
  282. msgType = 'warning')
  283. else:
  284. GMessage(parent = self,
  285. message = _('Model is valid.'),
  286. msgType = 'info')
  287. def OnExportPython(self, event):
  288. """!Export model to Python script"""
  289. filename = ''
  290. dlg = wx.FileDialog(parent = self,
  291. message = _("Choose file to save"),
  292. defaultDir = os.getcwd(),
  293. wildcard=_("Python script (*.py)|*.py"),
  294. style=wx.FD_SAVE)
  295. if dlg.ShowModal() == wx.ID_OK:
  296. filename = dlg.GetPath()
  297. if not filename:
  298. return
  299. # check for extension
  300. if filename[-3:] != ".py":
  301. filename += ".py"
  302. if os.path.exists(filename):
  303. dlg = wx.MessageDialog(self, message=_("File <%s> already exists. "
  304. "Do you want to overwrite this file?") % filename,
  305. caption=_("Save file"),
  306. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  307. if dlg.ShowModal() == wx.ID_NO:
  308. dlg.Destroy()
  309. return
  310. dlg.Destroy()
  311. fd = open(filename, "w")
  312. try:
  313. self._writePython(fd)
  314. finally:
  315. fd.close()
  316. # executable file
  317. os.chmod(filename, stat.S_IRWXU | stat.S_IWUSR)
  318. self.SetStatusText(_("Model exported to <%s>") % filename)
  319. def _writePython(self, fd):
  320. """!Write model to file"""
  321. fd.write(
  322. r"""#!/usr/bin/env python
  323. #
  324. ############################################################################
  325. #
  326. # MODULE: Graphical modeler script
  327. #
  328. # AUTHOR(S): %s
  329. #
  330. # PURPOSE: Script generated by wxGUI Graphical Modeler
  331. #
  332. # DATE: %s
  333. #
  334. #############################################################################
  335. """ % (getpass.getuser(), time.asctime()))
  336. fd.write(
  337. r"""
  338. import sys
  339. import os
  340. import grass.script as grass
  341. import atexit
  342. """)
  343. fd.write(
  344. r"""
  345. def cleanup():
  346. pass
  347. """)
  348. fd.write("\ndef main():\n")
  349. for action in self.actions:
  350. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  351. show = None)
  352. opts = task.get_options()
  353. flags = ''
  354. params = list()
  355. strcmd = " grass.run_command("
  356. indent = len(strcmd)
  357. fd.write(strcmd + "'%s',\n" % task.get_name())
  358. for f in opts['flags']:
  359. if f.get('value', False) == True:
  360. name = f.get('name', '')
  361. if len(name) > 1:
  362. params.append('%s=True' % name)
  363. else:
  364. flags += name
  365. for p in opts['params']:
  366. name = p.get('name', None)
  367. value = p.get('value', None)
  368. if name and value:
  369. ptype = p.get('type', 'string')
  370. if ptype == 'string':
  371. params.append("%s='%s'" % (name, value))
  372. else:
  373. params.append("%s=%s" % (name, value))
  374. for opt in params[:-1]:
  375. fd.write("%s%s,\n" % (' ' * indent, opt))
  376. fd.write("%s%s)\n" % (' ' * indent, params[-1]))
  377. fd.write("\n return 0\n")
  378. fd.write(
  379. r"""
  380. if __name__ == "__main__":
  381. options, flags = grass.parser()
  382. atexit.register(cleanup)
  383. sys.exit(main())
  384. """)
  385. def _validateModel(self):
  386. """!Validate model"""
  387. self.SetStatusText(_('Validating model...'), 0)
  388. errList = list()
  389. for action in self.actions:
  390. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  391. show = None)
  392. errList += task.getCmdError()
  393. self.SetStatusText('', 0)
  394. return errList
  395. def OnRemoveItem(self, event):
  396. """!Remove item from model"""
  397. pass
  398. def OnDefineRelation(self, event):
  399. """!Define relation between data and action items"""
  400. self.canvas.SetCursor(self.cursors["cross"])
  401. def OnAddAction(self, event):
  402. """!Add action to model"""
  403. if self.searchDialog is None:
  404. self.searchDialog = ModelSearchDialog(self)
  405. self.searchDialog.CentreOnParent()
  406. else:
  407. self.searchDialog.Reset()
  408. if self.searchDialog.ShowModal() == wx.ID_CANCEL:
  409. self.searchDialog.Hide()
  410. return
  411. cmd = self.searchDialog.GetCmd()
  412. self.searchDialog.Hide()
  413. self.ModelChanged()
  414. # add action to canvas
  415. width, height = self.canvas.GetSize()
  416. action = ModelAction(self, cmd = cmd, x = width/2, y = height/2)
  417. self.canvas.diagram.AddShape(action)
  418. action.Show(True)
  419. self._addEvent(action)
  420. self.actions.append(action)
  421. self.canvas.Refresh()
  422. time.sleep(.1)
  423. # show properties dialog
  424. win = action.GetPropDialog()
  425. if not win:
  426. module = menuform.GUI().ParseCommand(action.GetLog(string = False),
  427. completed = (self.GetOptData, action, None),
  428. parentframe = self, show = True)
  429. elif not win.IsShown():
  430. win.Show()
  431. if win:
  432. win.Raise()
  433. def OnAddData(self, event):
  434. """!Add data item to model"""
  435. # add action to canvas
  436. width, height = self.canvas.GetSize()
  437. data = ModelData(self, x = width/2, y = height/2)
  438. self.canvas.diagram.AddShape(data)
  439. data.Show(True)
  440. self._addEvent(data)
  441. self.data.append(data)
  442. self.canvas.Refresh()
  443. def OnHelp(self, event):
  444. """!Display manual page"""
  445. grass.run_command('g.manual',
  446. entry = 'wxGUI.Modeler')
  447. def OnAbout(self, event):
  448. """!Display About window"""
  449. info = wx.AboutDialogInfo()
  450. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  451. info.SetName(_('wxGUI Graphical Modeler'))
  452. info.SetWebSite('http://grass.osgeo.org')
  453. info.SetDescription(_('(C) 2010 by the GRASS Development Team\n\n') +
  454. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  455. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 100)))
  456. wx.AboutBox(info)
  457. def GetOptData(self, dcmd, layer, params, propwin):
  458. """!Process action data"""
  459. if params: # add data items
  460. for p in params['params']:
  461. if p.get('prompt', '') in ('raster', 'vector', 'raster3d'):
  462. try:
  463. name, mapset = p.get('value', '').split('@', 1)
  464. except (ValueError, IndexError):
  465. continue
  466. if mapset != grass.gisenv()['MAPSET']:
  467. continue
  468. # don't use fully qualified names
  469. p['value'] = p.get('value', '').split('@')[0]
  470. for idx in range(1, len(dcmd)):
  471. if p.get('name', '') in dcmd[idx]:
  472. dcmd[idx] = p.get('name', '') + '=' + p.get('value', '')
  473. break
  474. width, height = self.canvas.GetSize()
  475. x = [width/2 + 200, width/2 - 200]
  476. for p in params['params']:
  477. if p.get('prompt', '') in ('raster', 'vector', 'raster3d') and \
  478. (p.get('value', None) or \
  479. p.get('age', 'old') != 'old'):
  480. data = layer.FindData(p.get('name', ''))
  481. if data:
  482. data.SetValue(p.get('value', ''))
  483. continue
  484. data = self.FindData(p.get('value', ''),
  485. p.get('prompt', ''))
  486. if data:
  487. if p.get('age', 'old') == 'old':
  488. self._addLine(data, layer)
  489. data.AddAction(layer, direction = 'from')
  490. else:
  491. self._addLine(layer, data)
  492. data.AddAction(layer, direction = 'to')
  493. continue
  494. data = ModelData(self, name = p.get('name', ''),
  495. value = p.get('value', ''),
  496. prompt = p.get('prompt', ''),
  497. x = x.pop(), y = height/2)
  498. layer.AddData(data)
  499. self.canvas.diagram.AddShape(data)
  500. data.Show(True)
  501. self._addEvent(data)
  502. self.data.append(data)
  503. if p.get('age', 'old') == 'old':
  504. self._addLine(data, layer)
  505. data.AddAction(layer, direction = 'from')
  506. else:
  507. self._addLine(layer, data)
  508. data.AddAction(layer, direction = 'to')
  509. # valid ?
  510. valid = True
  511. for p in params['params']:
  512. if p.get('value', '') == '' and \
  513. p.get('default', '') == '':
  514. valid = False
  515. break
  516. layer.SetValid(valid)
  517. self.canvas.Refresh()
  518. if dcmd:
  519. layer.SetProperties(dcmd, params, propwin)
  520. self.SetStatusText(layer.GetLog(), 0)
  521. def _addLine(self, fromShape, toShape):
  522. """!Add connection
  523. @param fromShape from
  524. @param toShape to
  525. """
  526. line = ogl.LineShape()
  527. line.SetCanvas(self)
  528. line.SetPen(wx.BLACK_PEN)
  529. line.SetBrush(wx.BLACK_BRUSH)
  530. line.AddArrow(ogl.ARROW_ARROW)
  531. line.MakeLineControlPoints(2)
  532. fromShape.AddLine(line, toShape)
  533. self.canvas.diagram.AddShape(line)
  534. line.Show(True)
  535. def LoadModelFile(self, filename):
  536. """!Load model definition stored in GRASS Model XML file (gxm)
  537. @todo Validate against DTD
  538. Raise exception on error.
  539. """
  540. ### dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  541. # parse workspace file
  542. try:
  543. gxmXml = ProcessModelFile(etree.parse(filename))
  544. except:
  545. GMessage(parent = self,
  546. message = _("Reading model file <%s> failed.\n"
  547. "Invalid file, unable to parse XML document.") % filename)
  548. return
  549. self.modelFile = filename
  550. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  551. self.SetStatusText(_("Please wait, loading model..."), 0)
  552. # load actions
  553. for action in gxmXml.actions:
  554. actionShape = ModelAction(parent = self,
  555. x = action['pos'][0],
  556. y = action['pos'][1],
  557. width = action['size'][0],
  558. height = action['size'][1],
  559. cmd = action['cmd'])
  560. actionShape.SetId(action['id'])
  561. self.canvas.diagram.AddShape(actionShape)
  562. actionShape.Show(True)
  563. self._addEvent(actionShape)
  564. self.actions.append(actionShape)
  565. task = menuform.GUI().ParseCommand(cmd = actionShape.GetLog(string = False),
  566. show = None)
  567. valid = True
  568. for p in task.get_options()['params']:
  569. if p.get('value', '') == '' and \
  570. p.get('default', '') == '':
  571. valid = False
  572. break
  573. actionShape.SetValid(valid)
  574. # load data & connections
  575. for data in gxmXml.data:
  576. dataShape = ModelData(parent = self,
  577. x = data['pos'][0],
  578. y = data['pos'][1],
  579. width = data['size'][0],
  580. height = data['size'][1],
  581. name = data['name'],
  582. prompt = data['prompt'],
  583. value = data['value'])
  584. self.canvas.diagram.AddShape(dataShape)
  585. dataShape.Show(True)
  586. self._addEvent(dataShape)
  587. self.data.append(dataShape)
  588. for idx in range(len(data['id'])):
  589. actionShape = self.FindAction(data['id'][idx])
  590. if data['from'][idx] is True:
  591. self._addLine(dataShape, actionShape)
  592. dataShape.AddAction(actionShape, direction = 'from')
  593. elif data['from'][idx] is False:
  594. self._addLine(actionShape, dataShape)
  595. dataShape.AddAction(actionShape, direction = 'to')
  596. actionShape.AddData(dataShape)
  597. self.SetStatusText('', 0)
  598. self.canvas.Refresh(True)
  599. def WriteModelFile(self, filename):
  600. """!Save model to model file
  601. @return True on success
  602. @return False on failure
  603. """
  604. try:
  605. file = open(filename, "w")
  606. except IOError:
  607. wx.MessageBox(parent = self,
  608. message = _("Unable to open file <%s> for writing.") % filename,
  609. caption = _("Error"),
  610. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  611. return False
  612. try:
  613. WriteModelFile(fd = file, actions = self.actions, data = self.data)
  614. except StandardError:
  615. file.close()
  616. GMessage(parent = self,
  617. message = _("Writing current settings to model file failed."))
  618. return False
  619. file.close()
  620. return True
  621. class ModelCanvas(ogl.ShapeCanvas):
  622. """!Canvas where model is drawn"""
  623. def __init__(self, parent):
  624. ogl.OGLInitialize()
  625. ogl.ShapeCanvas.__init__(self, parent)
  626. self.diagram = ogl.Diagram()
  627. self.SetDiagram(self.diagram)
  628. self.diagram.SetCanvas(self)
  629. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  630. class ModelAction(ogl.RectangleShape):
  631. """!Action class (GRASS module)"""
  632. def __init__(self, parent, x, y, cmd = None, width = 100, height = 50):
  633. self.parent = parent
  634. self.cmd = cmd
  635. self.params = None
  636. self.propWin = None
  637. self.id = -1 # used for gxm file
  638. self.data = list() # list of connected data items
  639. # colors
  640. self.colors = dict()
  641. self.colors['valid'] = wx.LIGHT_GREY_BRUSH
  642. self.colors['invalid'] = wx.WHITE_BRUSH
  643. ogl.RectangleShape.__init__(self, width, height)
  644. # self.Draggable(True)
  645. self.SetCanvas(self.parent)
  646. self.SetX(x)
  647. self.SetY(y)
  648. self.SetPen(wx.BLACK_PEN)
  649. self.SetBrush(self.colors['invalid'])
  650. if self.cmd and len(self.cmd) > 0:
  651. self.AddText(self.cmd[0])
  652. else:
  653. self.AddText('<<module>>')
  654. def GetId(self):
  655. """!Get id"""
  656. return self.id
  657. def SetId(self, id):
  658. """!Set id"""
  659. self.id = id
  660. def SetProperties(self, dcmd, params, propwin):
  661. """!Record properties dialog"""
  662. self.cmd = dcmd
  663. self.params = params
  664. self.propWin = propwin
  665. def GetPropDialog(self):
  666. """!Get properties dialog"""
  667. return self.propWin
  668. def GetLog(self, string = True):
  669. """!Get logging info"""
  670. if string:
  671. if self.cmd is None:
  672. return ''
  673. else:
  674. return ' '.join(self.cmd)
  675. return self.cmd
  676. def GetName(self):
  677. """!Get name"""
  678. if self.cmd and len(self.cmd) > 0:
  679. return self.cmd[0]
  680. return _('unknown')
  681. def GetParams(self):
  682. """!Get dictionary of parameters"""
  683. return self.params
  684. def SetParams(self, params, cmd):
  685. """!Set dictionary of parameters"""
  686. self.params = params
  687. self.cmd = cmd
  688. def SetValid(self, isvalid):
  689. """!Set instance to be valid/invalid"""
  690. if isvalid:
  691. self.SetBrush(self.colors['valid'])
  692. else:
  693. self.SetBrush(self.colors['invalid'])
  694. def AddData(self, item):
  695. """!Register new data item"""
  696. if item not in self.data:
  697. self.data.append(item)
  698. def FindData(self, name):
  699. """!Find data item by name"""
  700. for d in self.data:
  701. if d.GetName() == name:
  702. return d
  703. return None
  704. class ModelData(ogl.EllipseShape):
  705. """!Data item class"""
  706. def __init__(self, parent, x, y, name = '', value = '', prompt = '', width = 175, height = 50):
  707. self.parent = parent
  708. self.name = name
  709. self.value = value
  710. self.prompt = prompt
  711. self.propWin = None
  712. self.actions = { 'from' : list(), 'to' : list() }
  713. ogl.EllipseShape.__init__(self, width, height)
  714. # self.Draggable(True)
  715. self.SetCanvas(self.parent)
  716. self.SetX(x)
  717. self.SetY(y)
  718. self.SetPen(wx.BLACK_PEN)
  719. if self.prompt == 'raster':
  720. self.SetBrush(wx.Brush(wx.Colour(215, 215, 248)))
  721. elif self.prompt == 'vector':
  722. self.SetBrush(wx.Brush(wx.Colour(248, 215, 215)))
  723. else:
  724. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  725. if name:
  726. self.AddText(name)
  727. else:
  728. self.AddText(_('unknown'))
  729. if value:
  730. self.AddText(value)
  731. else:
  732. self.AddText('\n')
  733. def GetLog(self, string = True):
  734. """!Get logging info"""
  735. if self.name:
  736. return self.name + '=' + self.value + ' (' + self.prompt + ')'
  737. else:
  738. return _('unknown')
  739. def GetName(self):
  740. """!Get name"""
  741. return self.name
  742. def GetPrompt(self):
  743. """!Get prompt"""
  744. return self.prompt
  745. def GetValue(self):
  746. """!Get value"""
  747. return self.value
  748. def SetValue(self, value):
  749. """!Set value"""
  750. self.value = value
  751. self.ClearText()
  752. self.AddText(self.name)
  753. if value:
  754. self.AddText(self.value)
  755. else:
  756. self.AddText('\n')
  757. for direction in ('from', 'to'):
  758. for action in self.actions[direction]:
  759. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  760. show = None)
  761. task.set_param(self.name, self.value)
  762. action.SetParams(params = task.get_options(),
  763. cmd = task.getCmd(ignoreErrors = True))
  764. def GetActions(self, direction):
  765. """!Get related actions
  766. @param direction direction - 'from' or 'to'
  767. """
  768. return self.actions[direction]
  769. def AddAction(self, action, direction):
  770. """!Record related actions
  771. @param action action to be recoreded
  772. @param direction direction of relation
  773. """
  774. self.actions[direction].append(action)
  775. def GetPropDialog(self):
  776. """!Get properties dialog"""
  777. return self.propWin
  778. def SetPropDialog(self, win):
  779. """!Get properties dialog"""
  780. self.propWin = win
  781. class ModelDataDialog(ElementDialog):
  782. """!Data item properties dialog"""
  783. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Data properties"),
  784. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  785. self.parent = parent
  786. self.shape = shape
  787. prompt = shape.GetPrompt()
  788. if prompt == 'raster':
  789. label = _('Name of raster map:')
  790. elif prompt == 'vector':
  791. label = _('Name of vector map:')
  792. else:
  793. label = _('Name of element:')
  794. ElementDialog.__init__(self, parent, title, label = label)
  795. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY,
  796. size = globalvar.DIALOG_GSELECT_SIZE,
  797. type = prompt)
  798. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  799. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  800. self.PostInit()
  801. self._layout()
  802. self.SetMinSize(self.GetSize())
  803. def _layout(self):
  804. """!Do layout"""
  805. self.dataSizer.Add(self.element, proportion=0,
  806. flag=wx.EXPAND | wx.ALL, border=1)
  807. self.panel.SetSizer(self.sizer)
  808. self.sizer.Fit(self)
  809. def OnOK(self, event):
  810. """!Ok pressed"""
  811. self.shape.SetValue(self.GetElement())
  812. self.parent.canvas.Refresh()
  813. self.parent.SetStatusText('', 0)
  814. self.OnCancel(event)
  815. def OnCancel(self, event):
  816. """!Cancel pressed"""
  817. self.shape.SetPropDialog(None)
  818. self.Destroy()
  819. class ModelEvtHandler(ogl.ShapeEvtHandler):
  820. """!Model event handler class"""
  821. def __init__(self, log, frame):
  822. ogl.ShapeEvtHandler.__init__(self)
  823. self.log = log
  824. self.frame = frame
  825. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  826. """!Left mouse button pressed -> select item & update statusbar"""
  827. shape = self.GetShape()
  828. canvas = shape.GetCanvas()
  829. dc = wx.ClientDC(canvas)
  830. canvas.PrepareDC(dc)
  831. if shape.Selected():
  832. shape.Select(False, dc)
  833. else:
  834. redraw = False
  835. shapeList = canvas.GetDiagram().GetShapeList()
  836. toUnselect = list()
  837. for s in shapeList:
  838. if s.Selected():
  839. toUnselect.append(s)
  840. shape.Select(True, dc)
  841. for s in toUnselect:
  842. s.Select(False, dc)
  843. canvas.Refresh(False)
  844. self.log.SetStatusText(shape.GetLog(), 0)
  845. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  846. """!Left mouse button pressed (double-click) -> show properties"""
  847. self.OnProperties()
  848. def OnProperties(self, event = None):
  849. """!Show properties dialog"""
  850. self.frame.ModelChanged()
  851. shape = self.GetShape()
  852. # win = shape.GetPropDialog()
  853. if isinstance(shape, ModelAction):
  854. module = menuform.GUI().ParseCommand(shape.GetLog(string = False),
  855. completed = (self.frame.GetOptData, shape, shape.GetParams()),
  856. parentframe = self.frame, show = True)
  857. elif isinstance(shape, ModelData):
  858. dlg = ModelDataDialog(parent = self.frame, shape = shape)
  859. shape.SetPropDialog(dlg)
  860. dlg.CentreOnParent()
  861. dlg.Show()
  862. def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
  863. """!Drag shape"""
  864. self.frame.ModelChanged()
  865. if self._previousHandler:
  866. self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
  867. def OnRightClick(self, x, y, keys = 0, attachment = 0):
  868. """!Right click -> pop-up menu"""
  869. if not hasattr (self, "popupID1"):
  870. self.popupID1 = wx.NewId()
  871. self.popupID2 = wx.NewId()
  872. popupMenu = wx.Menu()
  873. popupMenu.Append(self.popupID1, text=_('Remove'))
  874. self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  875. popupMenu.AppendSeparator()
  876. popupMenu.Append(self.popupID2, text=_('Properties'))
  877. self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID2)
  878. self.frame.PopupMenu(popupMenu)
  879. popupMenu.Destroy()
  880. def OnRemove(self, event):
  881. """!Remove shape"""
  882. shape = self.GetShape()
  883. self.frame.canvas.GetDiagram().RemoveShape(shape)
  884. self.frame.canvas.Refresh()
  885. class ModelSearchDialog(wx.Dialog):
  886. def __init__(self, parent, id = wx.ID_ANY, title = _("Select GRASS module"),
  887. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  888. """!Graphical modeler module search window
  889. @param parent parent window
  890. @param id window id
  891. @param title window title
  892. @param kwargs wx.Dialogs' arguments
  893. """
  894. self.parent = parent
  895. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  896. self.SetName("ModelerDialog")
  897. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  898. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  899. self.findBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  900. label=" %s " % _("Find module(s) by"))
  901. self.cmdBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  902. label=" %s " % _("Command"))
  903. self.searchBy = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  904. choices = [_("description"),
  905. _("keywords")])
  906. self.search = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  907. value = "", size = (-1, 25))
  908. self.searchTip = menuform.StaticWrapText(parent = self.panel, id = wx.ID_ANY,
  909. size = (-1, 35))
  910. self.searchChoice = wx.Choice(parent = self.panel, id = wx.ID_ANY)
  911. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  912. # get commands
  913. items = self.cmd_prompt.GetCommandItems()
  914. self.searchTip.SetLabel(_("%d modules found") % len(items))
  915. self.searchChoice.SetItems(items)
  916. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  917. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  918. self.btnOk.SetDefault()
  919. self.search.Bind(wx.EVT_TEXT, self.OnSearchModule)
  920. self.searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
  921. self._layout()
  922. self.SetSize((500, 250))
  923. def _layout(self):
  924. btnSizer = wx.StdDialogButtonSizer()
  925. btnSizer.AddButton(self.btnCancel)
  926. btnSizer.AddButton(self.btnOk)
  927. btnSizer.Realize()
  928. findSizer = wx.StaticBoxSizer(self.findBox, wx.HORIZONTAL)
  929. gridSizer = wx.GridBagSizer(hgap = 3, vgap = 3)
  930. gridSizer.AddGrowableCol(1)
  931. cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
  932. gridSizer.Add(item = self.searchBy,
  933. flag=wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
  934. gridSizer.Add(item = self.search,
  935. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos = (0, 1))
  936. gridSizer.Add(item = self.searchTip,
  937. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos = (1, 0), span = (1, 2))
  938. gridSizer.Add(item = self.searchChoice,
  939. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos = (2, 0), span = (1, 2))
  940. findSizer.Add(item = gridSizer, proportion = 1)
  941. cmdSizer.Add(item=self.cmd_prompt, proportion=1,
  942. flag=wx.EXPAND | wx.ALL, border=1)
  943. mainSizer = wx.BoxSizer(wx.VERTICAL)
  944. mainSizer.Add(item=findSizer, proportion=0,
  945. flag=wx.EXPAND | wx.ALL, border=5)
  946. mainSizer.Add(item=cmdSizer, proportion=1,
  947. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  948. mainSizer.Add(item=btnSizer, proportion=0,
  949. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  950. self.panel.SetSizer(mainSizer)
  951. mainSizer.Fit(self.panel)
  952. self.Layout()
  953. def GetPanel(self):
  954. """!Get dialog panel"""
  955. return self.panel
  956. def GetCmd(self):
  957. """!Get command"""
  958. line = self.cmd_prompt.GetCurLine()[0].strip()
  959. if len(line) == 0:
  960. list()
  961. try:
  962. cmd = shlex.split(str(line))
  963. except UnicodeError:
  964. cmd = shlex.split(utils.EncodeString((line)))
  965. return cmd
  966. def OnSearchModule(self, event):
  967. """!Search module by keywords or description"""
  968. text = event.GetString()
  969. if not text:
  970. self.cmd_prompt.SetFilter(None)
  971. return
  972. modules = dict()
  973. iFound = 0
  974. for module, data in self.cmd_prompt.moduleDesc.iteritems():
  975. found = False
  976. if self.searchBy.GetSelection() == 0: # -> description
  977. if text in data['desc']:
  978. found = True
  979. else: # -> keywords
  980. if self.cmd_prompt.CheckKey(text, data['keywords']):
  981. found = True
  982. if found:
  983. iFound += 1
  984. try:
  985. group, name = module.split('.')
  986. except ValueError:
  987. continue # TODO
  988. if not modules.has_key(group):
  989. modules[group] = list()
  990. modules[group].append(name)
  991. self.cmd_prompt.SetFilter(modules)
  992. self.searchTip.SetLabel(_("%d modules found") % iFound)
  993. self.searchChoice.SetItems(self.cmd_prompt.GetCommandItems())
  994. def OnSelectModule(self, event):
  995. """!Module selected from choice, update command prompt"""
  996. cmd = event.GetString().split(' ', 1)[0]
  997. text = cmd + ' '
  998. pos = len(text)
  999. self.cmd_prompt.SetText(text)
  1000. self.cmd_prompt.SetSelectionStart(pos)
  1001. self.cmd_prompt.SetCurrentPos(pos)
  1002. self.cmd_prompt.SetFocus()
  1003. desc = self.cmd_prompt.GetCommandDesc(cmd)
  1004. self.searchTip.SetLabel(desc)
  1005. def OnOk(self, event):
  1006. self.btnOk.SetFocus()
  1007. def Reset(self):
  1008. """!Reset dialog"""
  1009. self.searchBy.SetSelection(0)
  1010. self.search.SetValue('')
  1011. self.cmd_prompt.OnCmdErase(None)
  1012. class ProcessModelFile:
  1013. """!Process GRASS model file (gxm)"""
  1014. def __init__(self, tree):
  1015. """!A ElementTree handler for the GXM XML file, as defined in
  1016. grass-gxm.dtd.
  1017. """
  1018. self.tree = tree
  1019. self.root = self.tree.getroot()
  1020. # list of actions, data
  1021. self.actions = list()
  1022. self.data = list()
  1023. self._processActions()
  1024. self._processData()
  1025. def _filterValue(self, value):
  1026. """!Filter value
  1027. @param value
  1028. """
  1029. value = value.replace('&lt;', '<')
  1030. value = value.replace('&gt;', '>')
  1031. return value
  1032. def _getNodeText(self, node, tag, default = ''):
  1033. """!Get node text"""
  1034. p = node.find(tag)
  1035. if p is not None:
  1036. if p.text:
  1037. return utils.normalize_whitespace(p.text)
  1038. else:
  1039. return ''
  1040. return default
  1041. def _processActions(self):
  1042. """!Process model file"""
  1043. for action in self.root.findall('action'):
  1044. pos, size = self._getDim(action)
  1045. task = action.find('task')
  1046. if task:
  1047. cmd = self._processTask(task)
  1048. else:
  1049. cmd = None
  1050. aId = int(action.get('id', -1))
  1051. self.actions.append({ 'pos' : pos,
  1052. 'size': size,
  1053. 'cmd' : cmd,
  1054. 'id' : aId })
  1055. def _getDim(self, node):
  1056. """!Get position and size of shape"""
  1057. pos = size = None
  1058. posAttr = node.get('pos', None)
  1059. if posAttr:
  1060. posVal = map(int, posAttr.split(','))
  1061. try:
  1062. pos = (posVal[0], posVal[1])
  1063. except:
  1064. pos = None
  1065. sizeAttr = node.get('size', None)
  1066. if sizeAttr:
  1067. sizeVal = map(int, sizeAttr.split(','))
  1068. try:
  1069. size = (sizeVal[0], sizeVal[1])
  1070. except:
  1071. size = None
  1072. return pos, size
  1073. def _processData(self):
  1074. """!Process model file"""
  1075. for data in self.root.findall('data'):
  1076. pos, size = self._getDim(data)
  1077. param = data.find('data-parameter')
  1078. name = prompt = value = None
  1079. if param is not None:
  1080. name = param.get('name', None)
  1081. prompt = param.get('prompt', None)
  1082. value = self._filterValue(self._getNodeText(param, 'value'))
  1083. aId = list()
  1084. fromDir = list()
  1085. for action in data.findall('data-action'):
  1086. aId.append(int(action.get('id', None)))
  1087. if action.get('dir', 'to') == 'to':
  1088. fromDir.append(False)
  1089. else:
  1090. fromDir.append(True)
  1091. self.data.append({ 'pos' : pos,
  1092. 'size': size,
  1093. 'name' : name,
  1094. 'prompt' : prompt,
  1095. 'value' : value,
  1096. 'id' : aId,
  1097. 'from' : fromDir })
  1098. def _processTask(self, node):
  1099. """!Process task"""
  1100. cmd = list()
  1101. name = node.get('name', None)
  1102. if not name:
  1103. return cmd
  1104. cmd.append(name)
  1105. # flags
  1106. for p in node.findall('flag'):
  1107. flag = p.get('name', '')
  1108. if len(flag) > 1:
  1109. cmd.append('--' + flag)
  1110. else:
  1111. cmd.append('-' + flag)
  1112. # parameters
  1113. for p in node.findall('parameter'):
  1114. cmd.append('%s=%s' % (p.get('name', ''),
  1115. self._filterValue(self._getNodeText(p, 'value'))))
  1116. return cmd
  1117. class WriteModelFile:
  1118. """!Generic class for writing model file"""
  1119. def __init__(self, fd, actions, data):
  1120. self.fd = fd
  1121. self.actions = actions
  1122. self.data = data
  1123. self.indent = 0
  1124. self._header()
  1125. self._actions()
  1126. self._data()
  1127. self._footer()
  1128. def _filterValue(self, value):
  1129. """!Make value XML-valid"""
  1130. value = value.replace('<', '&lt;')
  1131. value = value.replace('>', '&gt;')
  1132. return value
  1133. def _header(self):
  1134. """!Write header"""
  1135. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  1136. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1137. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1138. def _footer(self):
  1139. """!Write footer"""
  1140. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1141. def _actions(self):
  1142. """!Write actions"""
  1143. id = 1
  1144. self.indent += 4
  1145. for action in self.actions:
  1146. action.SetId(id)
  1147. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1148. (' ' * self.indent, id, action.GetName(), action.GetX(), action.GetY(),
  1149. action.GetWidth(), action.GetHeight()))
  1150. self.indent += 4
  1151. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1152. self.indent += 4
  1153. for key, val in action.GetParams().iteritems():
  1154. if key == 'flags':
  1155. for f in val:
  1156. if f.get('value', False):
  1157. self.fd.write('%s<flag name="%s" />\n' %
  1158. (' ' * self.indent, f.get('name', '')))
  1159. else: # parameter
  1160. for p in val:
  1161. if not p.get('value', ''):
  1162. continue
  1163. self.fd.write('%s<parameter name="%s">\n' %
  1164. (' ' * self.indent, p.get('name', '')))
  1165. self.indent += 4
  1166. self.fd.write('%s<value>%s</value>\n' %
  1167. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1168. self.indent -= 4
  1169. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1170. self.indent -= 4
  1171. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1172. self.indent -= 4
  1173. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1174. id += 1
  1175. self.indent -= 4
  1176. def _data(self):
  1177. """!Write data"""
  1178. self.indent += 4
  1179. for data in self.data:
  1180. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1181. (' ' * self.indent, data.GetX(), data.GetY(),
  1182. data.GetWidth(), data.GetHeight()))
  1183. self.indent += 4
  1184. self.fd.write('%s<data-parameter name="%s" prompt="%s">\n' % \
  1185. (' ' * self.indent, data.GetName(), data.GetPrompt()))
  1186. self.indent += 4
  1187. self.fd.write('%s<value>%s</value>\n' %
  1188. (' ' * self.indent, self._filterValue(data.GetValue())))
  1189. self.indent -= 4
  1190. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1191. for action in data.GetActions('from'):
  1192. id = action.GetId()
  1193. self.fd.write('%s<data-action id="%d" dir="from" />\n' % \
  1194. (' ' * self.indent, id))
  1195. for action in data.GetActions('to'):
  1196. id = action.GetId()
  1197. self.fd.write('%s<data-action id="%d" dir="to" />\n' % \
  1198. (' ' * self.indent, id))
  1199. self.indent -= 4
  1200. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1201. self.indent -= 4
  1202. def main():
  1203. app = wx.PySimpleApp()
  1204. frame = ModelFrame(parent = None)
  1205. if len(sys.argv) > 1:
  1206. frame.LoadModelFile(sys.argv[1])
  1207. # frame.CentreOnScreen()
  1208. frame.Show()
  1209. app.MainLoop()
  1210. if __name__ == "__main__":
  1211. main()