gmodeler.py 54 KB

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