gmodeler.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  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 dcmd:
  459. layer.SetProperties(dcmd, params, propwin)
  460. if params: # add data items
  461. width, height = self.canvas.GetSize()
  462. x = [width/2 + 200, width/2 - 200]
  463. for p in params['params']:
  464. if p.get('prompt', '') in ('raster', 'vector', 'raster3d') and \
  465. (p.get('value', None) or \
  466. p.get('age', 'old') != 'old'):
  467. # create data item
  468. data = layer.FindData(p.get('name', ''))
  469. if data:
  470. data.SetValue(p.get('value', ''))
  471. continue
  472. data = self.FindData(p.get('value', ''),
  473. p.get('prompt', ''))
  474. if data:
  475. if p.get('age', 'old') == 'old':
  476. self._addLine(data, layer)
  477. data.AddAction(layer, direction = 'from')
  478. else:
  479. self._addLine(layer, data)
  480. data.AddAction(layer, direction = 'to')
  481. continue
  482. data = ModelData(self, name = p.get('name', ''),
  483. value = p.get('value', ''),
  484. prompt = p.get('prompt', ''),
  485. x = x.pop(), y = height/2)
  486. layer.AddData(data)
  487. self.canvas.diagram.AddShape(data)
  488. data.Show(True)
  489. self._addEvent(data)
  490. self.data.append(data)
  491. if p.get('age', 'old') == 'old':
  492. self._addLine(data, layer)
  493. data.AddAction(layer, direction = 'from')
  494. else:
  495. self._addLine(layer, data)
  496. data.AddAction(layer, direction = 'to')
  497. # valid ?
  498. valid = True
  499. for p in params['params']:
  500. if p.get('value', '') == '' and \
  501. p.get('default', '') == '':
  502. valid = False
  503. break
  504. layer.SetValid(valid)
  505. self.canvas.Refresh()
  506. self.SetStatusText(layer.GetLog(), 0)
  507. def _addLine(self, fromShape, toShape):
  508. """!Add connection
  509. @param fromShape from
  510. @param toShape to
  511. """
  512. line = ogl.LineShape()
  513. line.SetCanvas(self)
  514. line.SetPen(wx.BLACK_PEN)
  515. line.SetBrush(wx.BLACK_BRUSH)
  516. line.AddArrow(ogl.ARROW_ARROW)
  517. line.MakeLineControlPoints(2)
  518. fromShape.AddLine(line, toShape)
  519. self.canvas.diagram.AddShape(line)
  520. line.Show(True)
  521. def LoadModelFile(self, filename):
  522. """!Load model definition stored in GRASS Model XML file (gxm)
  523. @todo Validate against DTD
  524. Raise exception on error.
  525. """
  526. ### dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  527. # parse workspace file
  528. try:
  529. gxmXml = ProcessModelFile(etree.parse(filename))
  530. except:
  531. GMessage(parent = self,
  532. message = _("Reading model file <%s> failed.\n"
  533. "Invalid file, unable to parse XML document.") % filename)
  534. return
  535. self.modelFile = filename
  536. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  537. self.SetStatusText(_("Please wait, loading model..."), 0)
  538. # load actions
  539. for action in gxmXml.actions:
  540. actionShape = ModelAction(parent = self,
  541. x = action['pos'][0],
  542. y = action['pos'][1],
  543. width = action['size'][0],
  544. height = action['size'][1],
  545. cmd = action['cmd'])
  546. actionShape.SetId(action['id'])
  547. self.canvas.diagram.AddShape(actionShape)
  548. actionShape.Show(True)
  549. self._addEvent(actionShape)
  550. self.actions.append(actionShape)
  551. task = menuform.GUI().ParseCommand(cmd = actionShape.GetLog(string = False),
  552. show = None)
  553. valid = True
  554. for p in task.get_options()['params']:
  555. if p.get('value', '') == '' and \
  556. p.get('default', '') == '':
  557. valid = False
  558. break
  559. actionShape.SetValid(valid)
  560. # load data & connections
  561. for data in gxmXml.data:
  562. dataShape = ModelData(parent = self,
  563. x = data['pos'][0],
  564. y = data['pos'][1],
  565. width = data['size'][0],
  566. height = data['size'][1],
  567. name = data['name'],
  568. prompt = data['prompt'],
  569. value = data['value'])
  570. self.canvas.diagram.AddShape(dataShape)
  571. dataShape.Show(True)
  572. self._addEvent(dataShape)
  573. self.data.append(dataShape)
  574. for idx in range(len(data['id'])):
  575. actionShape = self.FindAction(data['id'][idx])
  576. if data['from'][idx] is True:
  577. self._addLine(dataShape, actionShape)
  578. dataShape.AddAction(actionShape, direction = 'from')
  579. elif data['from'][idx] is False:
  580. self._addLine(actionShape, dataShape)
  581. dataShape.AddAction(actionShape, direction = 'to')
  582. actionShape.AddData(dataShape)
  583. self.SetStatusText('', 0)
  584. self.canvas.Refresh(True)
  585. def WriteModelFile(self, filename):
  586. """!Save model to model file
  587. @return True on success
  588. @return False on failure
  589. """
  590. try:
  591. file = open(filename, "w")
  592. except IOError:
  593. wx.MessageBox(parent = self,
  594. message = _("Unable to open file <%s> for writing.") % filename,
  595. caption = _("Error"),
  596. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  597. return False
  598. try:
  599. WriteModelFile(fd = file, actions = self.actions, data = self.data)
  600. except StandardError:
  601. file.close()
  602. GMessage(parent = self,
  603. message = _("Writing current settings to model file failed."))
  604. return False
  605. file.close()
  606. return True
  607. class ModelCanvas(ogl.ShapeCanvas):
  608. """!Canvas where model is drawn"""
  609. def __init__(self, parent):
  610. ogl.OGLInitialize()
  611. ogl.ShapeCanvas.__init__(self, parent)
  612. self.diagram = ogl.Diagram()
  613. self.SetDiagram(self.diagram)
  614. self.diagram.SetCanvas(self)
  615. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  616. class ModelAction(ogl.RectangleShape):
  617. """!Action class (GRASS module)"""
  618. def __init__(self, parent, x, y, cmd = None, width = 100, height = 50):
  619. self.parent = parent
  620. self.cmd = cmd
  621. self.params = None
  622. self.propWin = None
  623. self.id = -1 # used for gxm file
  624. self.data = list() # list of connected data items
  625. # colors
  626. self.colors = dict()
  627. self.colors['valid'] = wx.LIGHT_GREY_BRUSH
  628. self.colors['invalid'] = wx.WHITE_BRUSH
  629. ogl.RectangleShape.__init__(self, width, height)
  630. # self.Draggable(True)
  631. self.SetCanvas(self.parent)
  632. self.SetX(x)
  633. self.SetY(y)
  634. self.SetPen(wx.BLACK_PEN)
  635. self.SetBrush(self.colors['invalid'])
  636. if self.cmd and len(self.cmd) > 0:
  637. self.AddText(self.cmd[0])
  638. else:
  639. self.AddText('<<module>>')
  640. def GetId(self):
  641. """!Get id"""
  642. return self.id
  643. def SetId(self, id):
  644. """!Set id"""
  645. self.id = id
  646. def SetProperties(self, dcmd, params, propwin):
  647. """!Record properties dialog"""
  648. self.cmd = dcmd
  649. self.params = params
  650. self.propWin = propwin
  651. def GetPropDialog(self):
  652. """!Get properties dialog"""
  653. return self.propWin
  654. def GetLog(self, string = True):
  655. """!Get logging info"""
  656. if string:
  657. if self.cmd is None:
  658. return ''
  659. else:
  660. return ' '.join(self.cmd)
  661. return self.cmd
  662. def GetName(self):
  663. """!Get name"""
  664. if self.cmd and len(self.cmd) > 0:
  665. return self.cmd[0]
  666. return _('unknown')
  667. def GetParams(self):
  668. """!Get dictionary of parameters"""
  669. return self.params
  670. def SetParams(self, params, cmd):
  671. """!Set dictionary of parameters"""
  672. self.params = params
  673. self.cmd = cmd
  674. def SetValid(self, isvalid):
  675. """!Set instance to be valid/invalid"""
  676. if isvalid:
  677. self.SetBrush(self.colors['valid'])
  678. else:
  679. self.SetBrush(self.colors['invalid'])
  680. def AddData(self, item):
  681. """!Register new data item"""
  682. if item not in self.data:
  683. self.data.append(item)
  684. def FindData(self, name):
  685. """!Find data item by name"""
  686. for d in self.data:
  687. if d.GetName() == name:
  688. return d
  689. return None
  690. class ModelData(ogl.EllipseShape):
  691. """!Data item class"""
  692. def __init__(self, parent, x, y, name = '', value = '', prompt = '', width = 175, height = 50):
  693. self.parent = parent
  694. self.name = name
  695. self.value = value
  696. self.prompt = prompt
  697. self.propWin = None
  698. self.actions = { 'from' : list(), 'to' : list() }
  699. ogl.EllipseShape.__init__(self, width, height)
  700. # self.Draggable(True)
  701. self.SetCanvas(self.parent)
  702. self.SetX(x)
  703. self.SetY(y)
  704. self.SetPen(wx.BLACK_PEN)
  705. if self.prompt == 'raster':
  706. self.SetBrush(wx.Brush(wx.Colour(215, 215, 248)))
  707. elif self.prompt == 'vector':
  708. self.SetBrush(wx.Brush(wx.Colour(248, 215, 215)))
  709. else:
  710. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  711. if name:
  712. self.AddText(name)
  713. else:
  714. self.AddText(_('unknown'))
  715. if value:
  716. self.AddText(value)
  717. else:
  718. self.AddText('\n')
  719. def GetLog(self, string = True):
  720. """!Get logging info"""
  721. if self.name:
  722. return self.name + '=' + self.value + ' (' + self.prompt + ')'
  723. else:
  724. return _('unknown')
  725. def GetName(self):
  726. """!Get name"""
  727. return self.name
  728. def GetPrompt(self):
  729. """!Get prompt"""
  730. return self.prompt
  731. def GetValue(self):
  732. """!Get value"""
  733. return self.value
  734. def SetValue(self, value):
  735. """!Set value"""
  736. self.value = value
  737. self.ClearText()
  738. self.AddText(self.name)
  739. if value:
  740. self.AddText(self.value)
  741. else:
  742. self.AddText('\n')
  743. for direction in ('from', 'to'):
  744. for action in self.actions[direction]:
  745. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  746. show = None)
  747. task.set_param(self.name, self.value)
  748. action.SetParams(params = task.get_options(),
  749. cmd = task.getCmd(ignoreErrors = True))
  750. def GetActions(self, direction):
  751. """!Get related actions
  752. @param direction direction - 'from' or 'to'
  753. """
  754. return self.actions[direction]
  755. def AddAction(self, action, direction):
  756. """!Record related actions
  757. @param action action to be recoreded
  758. @param direction direction of relation
  759. """
  760. self.actions[direction].append(action)
  761. def GetPropDialog(self):
  762. """!Get properties dialog"""
  763. return self.propWin
  764. def SetPropDialog(self, win):
  765. """!Get properties dialog"""
  766. self.propWin = win
  767. class ModelDataDialog(ElementDialog):
  768. """!Data item properties dialog"""
  769. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Data properties"),
  770. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  771. self.parent = parent
  772. self.shape = shape
  773. prompt = shape.GetPrompt()
  774. if prompt == 'raster':
  775. label = _('Name of raster map:')
  776. elif prompt == 'vector':
  777. label = _('Name of vector map:')
  778. else:
  779. label = _('Name of element:')
  780. ElementDialog.__init__(self, parent, title, label = label)
  781. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY,
  782. size = globalvar.DIALOG_GSELECT_SIZE,
  783. type = prompt)
  784. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  785. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  786. self.PostInit()
  787. self._layout()
  788. self.SetMinSize(self.GetSize())
  789. def _layout(self):
  790. """!Do layout"""
  791. self.dataSizer.Add(self.element, proportion=0,
  792. flag=wx.EXPAND | wx.ALL, border=1)
  793. self.panel.SetSizer(self.sizer)
  794. self.sizer.Fit(self)
  795. def OnOK(self, event):
  796. """!Ok pressed"""
  797. self.shape.SetValue(self.GetElement())
  798. self.parent.canvas.Refresh()
  799. self.parent.SetStatusText('', 0)
  800. self.OnCancel(event)
  801. def OnCancel(self, event):
  802. """!Cancel pressed"""
  803. self.shape.SetPropDialog(None)
  804. self.Destroy()
  805. class ModelEvtHandler(ogl.ShapeEvtHandler):
  806. """!Model event handler class"""
  807. def __init__(self, log, frame):
  808. ogl.ShapeEvtHandler.__init__(self)
  809. self.log = log
  810. self.frame = frame
  811. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  812. """!Left mouse button pressed -> select item & update statusbar"""
  813. shape = self.GetShape()
  814. canvas = shape.GetCanvas()
  815. dc = wx.ClientDC(canvas)
  816. canvas.PrepareDC(dc)
  817. if shape.Selected():
  818. shape.Select(False, dc)
  819. else:
  820. redraw = False
  821. shapeList = canvas.GetDiagram().GetShapeList()
  822. toUnselect = list()
  823. for s in shapeList:
  824. if s.Selected():
  825. toUnselect.append(s)
  826. shape.Select(True, dc)
  827. for s in toUnselect:
  828. s.Select(False, dc)
  829. canvas.Refresh(False)
  830. self.log.SetStatusText(shape.GetLog(), 0)
  831. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  832. """!Left mouse button pressed (double-click) -> show properties"""
  833. self.OnProperties()
  834. def OnProperties(self, event = None):
  835. """!Show properties dialog"""
  836. self.frame.ModelChanged()
  837. shape = self.GetShape()
  838. # win = shape.GetPropDialog()
  839. if isinstance(shape, ModelAction):
  840. module = menuform.GUI().ParseCommand(shape.GetLog(string = False),
  841. completed = (self.frame.GetOptData, shape, shape.GetParams()),
  842. parentframe = self.frame, show = True)
  843. elif isinstance(shape, ModelData):
  844. dlg = ModelDataDialog(parent = self.frame, shape = shape)
  845. shape.SetPropDialog(dlg)
  846. dlg.CentreOnParent()
  847. dlg.Show()
  848. def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
  849. """!Drag shape"""
  850. self.frame.ModelChanged()
  851. if self._previousHandler:
  852. self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
  853. def OnRightClick(self, x, y, keys = 0, attachment = 0):
  854. """!Right click -> pop-up menu"""
  855. if not hasattr (self, "popupID1"):
  856. self.popupID1 = wx.NewId()
  857. self.popupID2 = wx.NewId()
  858. popupMenu = wx.Menu()
  859. popupMenu.Append(self.popupID1, text=_('Remove'))
  860. self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  861. popupMenu.AppendSeparator()
  862. popupMenu.Append(self.popupID2, text=_('Properties'))
  863. self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID2)
  864. self.frame.PopupMenu(popupMenu)
  865. popupMenu.Destroy()
  866. def OnRemove(self, event):
  867. """!Remove shape"""
  868. shape = self.GetShape()
  869. self.frame.canvas.GetDiagram().RemoveShape(shape)
  870. self.frame.canvas.Refresh()
  871. class ModelSearchDialog(wx.Dialog):
  872. def __init__(self, parent, id = wx.ID_ANY, title = _("Find GRASS module"),
  873. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  874. """!Graphical modeler module search window
  875. @param parent parent window
  876. @param id window id
  877. @param title window title
  878. @param kwargs wx.Dialogs' arguments
  879. """
  880. self.parent = parent
  881. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  882. self.SetName("ModelerDialog")
  883. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  884. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  885. self.searchBy = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  886. choices = [_("description"),
  887. _("keywords")])
  888. self.search = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  889. value = "", size = (-1, 25))
  890. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  891. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  892. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  893. self.btnOk.SetDefault()
  894. self._layout()
  895. def _layout(self):
  896. btnSizer = wx.StdDialogButtonSizer()
  897. btnSizer.AddButton(self.btnCancel)
  898. btnSizer.AddButton(self.btnOk)
  899. btnSizer.Realize()
  900. bodyBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  901. label=" %s " % _("Find GRASS module"))
  902. bodySizer = wx.StaticBoxSizer(bodyBox, wx.VERTICAL)
  903. searchSizer = wx.BoxSizer(wx.HORIZONTAL)
  904. searchSizer.Add(item = self.searchBy,
  905. proportion = 0, flag = wx.LEFT, border = 3)
  906. searchSizer.Add(item = self.search,
  907. proportion = 1, flag = wx.LEFT | wx.EXPAND, border = 3)
  908. bodySizer.Add(item=searchSizer, proportion=0,
  909. flag=wx.EXPAND | wx.ALL, border=1)
  910. bodySizer.Add(item=self.cmd_prompt, proportion=1,
  911. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  912. mainSizer = wx.BoxSizer(wx.VERTICAL)
  913. mainSizer.Add(item=bodySizer, proportion=1,
  914. flag=wx.EXPAND | wx.ALL, border=5)
  915. mainSizer.Add(item=btnSizer, proportion=0,
  916. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  917. self.panel.SetSizer(mainSizer)
  918. mainSizer.Fit(self.panel)
  919. def GetPanel(self):
  920. """!Get dialog panel"""
  921. return self.panel
  922. def GetCmd(self):
  923. """!Get command"""
  924. line = self.cmd_prompt.GetCurLine()[0].strip()
  925. if len(line) == 0:
  926. list()
  927. try:
  928. cmd = shlex.split(str(line))
  929. except UnicodeError:
  930. cmd = shlex.split(utils.EncodeString((line)))
  931. return cmd
  932. def OnOk(self, event):
  933. self.btnOk.SetFocus()
  934. def Reset(self):
  935. """!Reset dialog"""
  936. self.searchBy.SetSelection(0)
  937. self.search.SetValue('')
  938. self.cmd_prompt.OnCmdErase(None)
  939. class ProcessModelFile:
  940. """!Process GRASS model file (gxm)"""
  941. def __init__(self, tree):
  942. """!A ElementTree handler for the GXM XML file, as defined in
  943. grass-gxm.dtd.
  944. """
  945. self.tree = tree
  946. self.root = self.tree.getroot()
  947. # list of actions, data
  948. self.actions = list()
  949. self.data = list()
  950. self._processActions()
  951. self._processData()
  952. def _filterValue(self, value):
  953. """!Filter value
  954. @param value
  955. """
  956. value = value.replace('&lt;', '<')
  957. value = value.replace('&gt;', '>')
  958. return value
  959. def _getNodeText(self, node, tag, default = ''):
  960. """!Get node text"""
  961. p = node.find(tag)
  962. if p is not None:
  963. if p.text:
  964. return utils.normalize_whitespace(p.text)
  965. else:
  966. return ''
  967. return default
  968. def _processActions(self):
  969. """!Process model file"""
  970. for action in self.root.findall('action'):
  971. pos, size = self._getDim(action)
  972. task = action.find('task')
  973. if task:
  974. cmd = self._processTask(task)
  975. else:
  976. cmd = None
  977. aId = int(action.get('id', -1))
  978. self.actions.append({ 'pos' : pos,
  979. 'size': size,
  980. 'cmd' : cmd,
  981. 'id' : aId })
  982. def _getDim(self, node):
  983. """!Get position and size of shape"""
  984. pos = size = None
  985. posAttr = node.get('pos', None)
  986. if posAttr:
  987. posVal = map(int, posAttr.split(','))
  988. try:
  989. pos = (posVal[0], posVal[1])
  990. except:
  991. pos = None
  992. sizeAttr = node.get('size', None)
  993. if sizeAttr:
  994. sizeVal = map(int, sizeAttr.split(','))
  995. try:
  996. size = (sizeVal[0], sizeVal[1])
  997. except:
  998. size = None
  999. return pos, size
  1000. def _processData(self):
  1001. """!Process model file"""
  1002. for data in self.root.findall('data'):
  1003. pos, size = self._getDim(data)
  1004. param = data.find('data-parameter')
  1005. name = prompt = value = None
  1006. if param is not None:
  1007. name = param.get('name', None)
  1008. prompt = param.get('prompt', None)
  1009. value = self._filterValue(self._getNodeText(param, 'value'))
  1010. aId = list()
  1011. fromDir = list()
  1012. for action in data.findall('data-action'):
  1013. aId.append(int(action.get('id', None)))
  1014. if action.get('dir', 'to') == 'to':
  1015. fromDir.append(False)
  1016. else:
  1017. fromDir.append(True)
  1018. self.data.append({ 'pos' : pos,
  1019. 'size': size,
  1020. 'name' : name,
  1021. 'prompt' : prompt,
  1022. 'value' : value,
  1023. 'id' : aId,
  1024. 'from' : fromDir })
  1025. def _processTask(self, node):
  1026. """!Process task"""
  1027. cmd = list()
  1028. name = node.get('name', None)
  1029. if not name:
  1030. return cmd
  1031. cmd.append(name)
  1032. # flags
  1033. for p in node.findall('flag'):
  1034. flag = p.get('name', '')
  1035. if len(flag) > 1:
  1036. cmd.append('--' + flag)
  1037. else:
  1038. cmd.append('-' + flag)
  1039. # parameters
  1040. for p in node.findall('parameter'):
  1041. cmd.append('%s=%s' % (p.get('name', ''),
  1042. self._filterValue(self._getNodeText(p, 'value'))))
  1043. return cmd
  1044. class WriteModelFile:
  1045. """!Generic class for writing model file"""
  1046. def __init__(self, fd, actions, data):
  1047. self.fd = fd
  1048. self.actions = actions
  1049. self.data = data
  1050. self.indent = 0
  1051. self._header()
  1052. self._actions()
  1053. self._data()
  1054. self._footer()
  1055. def _filterValue(self, value):
  1056. """!Make value XML-valid"""
  1057. value = value.replace('<', '&lt;')
  1058. value = value.replace('>', '&gt;')
  1059. return value
  1060. def _header(self):
  1061. """!Write header"""
  1062. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  1063. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1064. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1065. def _footer(self):
  1066. """!Write footer"""
  1067. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1068. def _actions(self):
  1069. """!Write actions"""
  1070. id = 1
  1071. self.indent += 4
  1072. for action in self.actions:
  1073. action.SetId(id)
  1074. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1075. (' ' * self.indent, id, action.GetName(), action.GetX(), action.GetY(),
  1076. action.GetWidth(), action.GetHeight()))
  1077. self.indent += 4
  1078. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1079. self.indent += 4
  1080. for key, val in action.GetParams().iteritems():
  1081. if key == 'flags':
  1082. for f in val:
  1083. if f.get('value', False):
  1084. self.fd.write('%s<flag name="%s" />\n' %
  1085. (' ' * self.indent, f.get('name', '')))
  1086. else: # parameter
  1087. for p in val:
  1088. if not p.get('value', ''):
  1089. continue
  1090. self.fd.write('%s<parameter name="%s">\n' %
  1091. (' ' * self.indent, p.get('name', '')))
  1092. self.indent += 4
  1093. self.fd.write('%s<value>%s</value>\n' %
  1094. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1095. self.indent -= 4
  1096. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1097. self.indent -= 4
  1098. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1099. self.indent -= 4
  1100. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1101. id += 1
  1102. self.indent -= 4
  1103. def _data(self):
  1104. """!Write data"""
  1105. self.indent += 4
  1106. for data in self.data:
  1107. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1108. (' ' * self.indent, data.GetX(), data.GetY(),
  1109. data.GetWidth(), data.GetHeight()))
  1110. self.indent += 4
  1111. self.fd.write('%s<data-parameter name="%s" prompt="%s">\n' % \
  1112. (' ' * self.indent, data.GetName(), data.GetPrompt()))
  1113. self.indent += 4
  1114. self.fd.write('%s<value>%s</value>\n' %
  1115. (' ' * self.indent, self._filterValue(data.GetValue())))
  1116. self.indent -= 4
  1117. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1118. for action in data.GetActions('from'):
  1119. id = action.GetId()
  1120. self.fd.write('%s<data-action id="%d" dir="from" />\n' % \
  1121. (' ' * self.indent, id))
  1122. for action in data.GetActions('to'):
  1123. id = action.GetId()
  1124. self.fd.write('%s<data-action id="%d" dir="to" />\n' % \
  1125. (' ' * self.indent, id))
  1126. self.indent -= 4
  1127. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1128. self.indent -= 4
  1129. def main():
  1130. app = wx.PySimpleApp()
  1131. frame = ModelFrame(parent = None)
  1132. if len(sys.argv) > 1:
  1133. frame.LoadModelFile(sys.argv[1])
  1134. # frame.CentreOnScreen()
  1135. frame.Show()
  1136. app.MainLoop()
  1137. if __name__ == "__main__":
  1138. main()