gmodeler.py 51 KB

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