gmodeler.py 47 KB

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