gmodeler.py 48 KB

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