gmodeler.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. - ProcessModelFile
  11. - WriteModelFile
  12. (C) 2010 by the GRASS Development Team
  13. This program is free software under the GNU General Public License
  14. (>=v2). Read the file COPYING that comes with GRASS for details.
  15. @author Martin Landa <landa.martin gmail.com>
  16. """
  17. import os
  18. import sys
  19. import shlex
  20. import time
  21. import traceback
  22. try:
  23. import xml.etree.ElementTree as etree
  24. except ImportError:
  25. import elementtree.ElementTree as etree # Python <= 2.4
  26. import globalvar
  27. if not os.getenv("GRASS_WXBUNDLED"):
  28. globalvar.CheckForWx()
  29. import wx
  30. import wx.lib.ogl as ogl
  31. import menu
  32. import menudata
  33. import toolbars
  34. import menuform
  35. import prompt
  36. import utils
  37. from debug import Debug
  38. from gcmd import GMessage
  39. from grass.script import core as grass
  40. class ModelFrame(wx.Frame):
  41. def __init__(self, parent, id = wx.ID_ANY, title = _("Graphical modeler (under development)"), **kwargs):
  42. """!Graphical modeler main window
  43. @param parent parent window
  44. @param id window id
  45. @param title window title
  46. @param kwargs wx.Frames' arguments
  47. """
  48. self.parent = parent
  49. self.searchDialog = None # module search dialog
  50. self.actions = list() # list of recorded actions
  51. self.data = list() # list of recorded data items
  52. self.baseTitle = title
  53. self.modelFile = None # loaded model
  54. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  55. self.SetName("Modeler")
  56. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  57. self.menubar = menu.Menu(parent = self, data = menudata.ModelerData())
  58. self.SetMenuBar(self.menubar)
  59. self.toolbar = toolbars.ModelToolbar(parent = self)
  60. self.SetToolBar(self.toolbar)
  61. self.statusbar = self.CreateStatusBar(number = 1)
  62. self.canvas = ModelCanvas(self)
  63. self.canvas.SetBackgroundColour(wx.WHITE)
  64. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  65. self._layout()
  66. self.SetMinSize((640, 480))
  67. def _layout(self):
  68. """!Do layout"""
  69. sizer = wx.BoxSizer(wx.VERTICAL)
  70. sizer.Add(item = self.canvas, proportion = 1,
  71. flag = wx.EXPAND)
  72. self.SetAutoLayout(True)
  73. self.SetSizer(sizer)
  74. sizer.Fit(self)
  75. self.Layout()
  76. def _addEvent(self, item):
  77. """!Add event to item"""
  78. evthandler = ModelEvtHandler(self.statusbar,
  79. self)
  80. evthandler.SetShape(item)
  81. evthandler.SetPreviousHandler(item.GetEventHandler())
  82. item.SetEventHandler(evthandler)
  83. def OnCloseWindow(self, event):
  84. """!Close window"""
  85. self.Destroy()
  86. def OnModelNew(self, event):
  87. """!Create new model"""
  88. pass
  89. def OnModelOpen(self, event):
  90. """!Load model from file"""
  91. filename = ''
  92. dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
  93. defaultDir = os.getcwd(),
  94. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  95. if dlg.ShowModal() == wx.ID_OK:
  96. filename = dlg.GetPath()
  97. if not filename:
  98. return
  99. Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
  100. # close current model
  101. ### self.OnModelClose()
  102. self.LoadModelFile(filename)
  103. self.modelFile = filename
  104. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  105. self.SetStatusText(_('%d actions loaded into model') % len(self.actions), 0)
  106. def OnModelSave(self, event):
  107. """!Save model to file"""
  108. if self.modelFile:
  109. dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
  110. "Do you want to overwrite this file?") % \
  111. self.modelFile,
  112. caption=_("Save model"),
  113. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  114. if dlg.ShowModal() == wx.ID_NO:
  115. dlg.Destroy()
  116. else:
  117. Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
  118. self.WriteModelFile(self.modelFile)
  119. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  120. else:
  121. self.OnModelSaveAs(None)
  122. def OnModelSaveAs(self, event):
  123. """!Create model to file as"""
  124. filename = ''
  125. dlg = wx.FileDialog(parent = self,
  126. message = _("Choose file to save current model"),
  127. defaultDir = os.getcwd(),
  128. wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
  129. style=wx.FD_SAVE)
  130. if dlg.ShowModal() == wx.ID_OK:
  131. filename = dlg.GetPath()
  132. if not filename:
  133. return
  134. # check for extension
  135. if filename[-4:] != ".gxm":
  136. filename += ".gxm"
  137. if os.path.exists(filename):
  138. dlg = wx.MessageDialog(parent = self,
  139. message=_("Model file <%s> already exists. "
  140. "Do you want to overwrite this file?") % filename,
  141. caption=_("File already exists"),
  142. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  143. if dlg.ShowModal() != wx.ID_YES:
  144. dlg.Destroy()
  145. return
  146. Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
  147. self.WriteModelFile(filename)
  148. self.modelFile = filename
  149. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  150. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  151. def OnRunModel(self, event):
  152. """!Run entire model"""
  153. pass
  154. def OnValidateModel(self, event):
  155. """!Validate entire model"""
  156. for s in self.actions:
  157. print s
  158. def OnRemoveItem(self, event):
  159. """!Remove item from model"""
  160. pass
  161. def OnAddAction(self, event):
  162. """!Add action to model"""
  163. if self.searchDialog is None:
  164. self.searchDialog = ModelSearchDialog(self)
  165. self.searchDialog.CentreOnParent()
  166. else:
  167. self.searchDialog.Reset()
  168. if self.searchDialog.ShowModal() == wx.ID_CANCEL:
  169. self.searchDialog.Hide()
  170. return
  171. cmd = self.searchDialog.GetCmd()
  172. self.searchDialog.Hide()
  173. # add action to canvas
  174. width, height = self.canvas.GetSize()
  175. action = ModelAction(self, cmd = cmd, x = width/2, y = height/2)
  176. self.canvas.diagram.AddShape(action)
  177. action.Show(True)
  178. self._addEvent(action)
  179. self.actions.append(action)
  180. self.canvas.Refresh()
  181. time.sleep(.1)
  182. # show properties dialog
  183. win = action.GetPropDialog()
  184. if not win:
  185. module = menuform.GUI().ParseCommand(action.GetLog(string = False),
  186. completed = (self.GetOptData, action, None),
  187. parentframe = self, show = True)
  188. elif not win.IsShown():
  189. win.Show()
  190. if win:
  191. win.Raise()
  192. def OnAddData(self, event):
  193. """!Add data item to model"""
  194. # add action to canvas
  195. width, height = self.canvas.GetSize()
  196. data = ModelData(self, x = width/2, y = height/2)
  197. self.canvas.diagram.AddShape(data)
  198. data.Show(True)
  199. self._addEvent(data)
  200. self.data.append(data)
  201. self.canvas.Refresh()
  202. def OnHelp(self, event):
  203. """!Display manual page"""
  204. grass.run_command('g.manual',
  205. entry = 'wxGUI.Modeler')
  206. def GetOptData(self, dcmd, layer, params, propwin):
  207. """!Process action data"""
  208. layer.SetProperties(dcmd, params, propwin)
  209. if params: # add data items
  210. width, height = self.canvas.GetSize()
  211. x = [width/2 + 200, width/2 - 200]
  212. for p in params['params']:
  213. if p.get('value', None) and \
  214. p.get('prompt', '') in ('raster', 'vector', 'raster3d'):
  215. # create data item
  216. data = ModelData(self, name = p.get('name', ''),
  217. value = p.get('value', ''),
  218. prompt = p.get('prompt', ''),
  219. x = x.pop(), y = height/2)
  220. self.canvas.diagram.AddShape(data)
  221. data.Show(True)
  222. self._addEvent(data)
  223. self.data.append(data)
  224. if p.get('age', 'old') == 'old':
  225. self._addLine(data, layer)
  226. data.AddAction(layer, direction = 'from')
  227. else:
  228. self._addLine(layer, data)
  229. data.AddAction(layer, direction = 'to')
  230. self.canvas.Refresh()
  231. self.SetStatusText(layer.GetLog(), 0)
  232. def _addLine(self, fromShape, toShape):
  233. """!Add connection
  234. @param fromShape from
  235. @param toShape to
  236. """
  237. line = ogl.LineShape()
  238. line.SetCanvas(self)
  239. line.SetPen(wx.BLACK_PEN)
  240. line.SetBrush(wx.BLACK_BRUSH)
  241. line.AddArrow(ogl.ARROW_ARROW)
  242. line.MakeLineControlPoints(2)
  243. fromShape.AddLine(line, toShape)
  244. self.canvas.diagram.AddShape(line)
  245. line.Show(True)
  246. def LoadModelFile(self, filename):
  247. """!Load model definition stored in GRASS Model XML file (gxm)
  248. @todo Validate against DTD
  249. Raise exception on error.
  250. """
  251. ### dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  252. # parse workspace file
  253. try:
  254. gxmXml = ProcessModelFile(etree.parse(filename))
  255. except:
  256. GMessage(parent = self,
  257. message = _("Reading model file <%s> failed.\n"
  258. "Invalid file, unable to parse XML document.") % filename)
  259. return
  260. busy = wx.BusyInfo(message=_("Please wait, loading model..."),
  261. parent=self)
  262. wx.Yield()
  263. # load actions
  264. for action in gxmXml.actions:
  265. actionShape = ModelAction(parent = self,
  266. x = action['pos'][0],
  267. y = action['pos'][1],
  268. width = action['size'][0],
  269. height = action['size'][1],
  270. cmd = action['cmd'])
  271. self.canvas.diagram.AddShape(actionShape)
  272. actionShape.Show(True)
  273. self._addEvent(actionShape)
  274. self.actions.append(actionShape)
  275. # load data & connections
  276. for data in gxmXml.data:
  277. dataShape = ModelData(parent = self,
  278. x = data['pos'][0],
  279. y = data['pos'][1],
  280. width = data['size'][0],
  281. height = data['size'][1],
  282. name = data['name'],
  283. prompt = data['prompt'],
  284. value = data['value'])
  285. self.canvas.diagram.AddShape(dataShape)
  286. dataShape.Show(True)
  287. self._addEvent(dataShape)
  288. self.data.append(dataShape)
  289. actionShape = self.actions[0]
  290. if data['from'] is True:
  291. self._addLine(dataShape, actionShape)
  292. elif data['from'] is False:
  293. self._addLine(actionShape, dataShape)
  294. self.canvas.Refresh(True)
  295. def WriteModelFile(self, filename):
  296. """!Save model to model file
  297. @return True on success
  298. @return False on failure
  299. """
  300. try:
  301. file = open(filename, "w")
  302. except IOError:
  303. wx.MessageBox(parent = self,
  304. message = _("Unable to open file <%s> for writing.") % filename,
  305. caption = _("Error"),
  306. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  307. return False
  308. try:
  309. WriteModelFile(fd = file, actions = self.actions, data = self.data)
  310. except StandardError:
  311. file.close()
  312. GMessage(parent = self,
  313. message = _("Writing current settings to model file failed."))
  314. return False
  315. file.close()
  316. return True
  317. class ModelCanvas(ogl.ShapeCanvas):
  318. """!Canvas where model is drawn"""
  319. def __init__(self, parent):
  320. ogl.OGLInitialize()
  321. ogl.ShapeCanvas.__init__(self, parent)
  322. self.diagram = ogl.Diagram()
  323. self.SetDiagram(self.diagram)
  324. self.diagram.SetCanvas(self)
  325. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  326. class ModelAction(ogl.RectangleShape):
  327. """!Action class (GRASS module)"""
  328. def __init__(self, parent, x, y, cmd = None, width = 100, height = 50):
  329. self.parent = parent
  330. self.cmd = cmd
  331. self.params = None
  332. self.propWin = None
  333. ogl.RectangleShape.__init__(self, width, height)
  334. # self.Draggable(True)
  335. self.SetCanvas(self.parent)
  336. self.SetX(x)
  337. self.SetY(y)
  338. self.SetPen(wx.BLACK_PEN)
  339. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  340. if self.cmd and len(self.cmd) > 0:
  341. self.AddText(self.cmd[0])
  342. else:
  343. self.AddText('<<module>>')
  344. def SetProperties(self, dcmd, params, propwin):
  345. """!Record properties dialog"""
  346. self.cmd = dcmd
  347. self.params = params
  348. self.propWin = propwin
  349. def GetPropDialog(self):
  350. """!Get properties dialog"""
  351. return self.propWin
  352. def GetLog(self, string = True):
  353. """!Get logging info"""
  354. if string:
  355. if self.cmd is None:
  356. return ''
  357. else:
  358. return ' '.join(self.cmd)
  359. return self.cmd
  360. def GetName(self):
  361. """!Get name"""
  362. if self.cmd and len(self.cmd) > 0:
  363. return self.cmd[0]
  364. return _('unknown')
  365. def GetParams(self):
  366. """!Get dictionary of parameters"""
  367. return self.params
  368. class ModelData(ogl.EllipseShape):
  369. """!Data item class"""
  370. def __init__(self, parent, x, y, name = '', value = '', prompt = '', width = 175, height = 50):
  371. self.parent = parent
  372. self.name = name
  373. self.value = value
  374. self.prompt = prompt
  375. self.actions = { 'from' : list(), 'to' : list() }
  376. ogl.EllipseShape.__init__(self, width, height)
  377. # self.Draggable(True)
  378. self.SetCanvas(self.parent)
  379. self.SetX(x)
  380. self.SetY(y)
  381. self.SetPen(wx.BLACK_PEN)
  382. if self.prompt == 'raster':
  383. self.SetBrush(wx.Brush(wx.Colour(215, 215, 248)))
  384. elif self.prompt == 'vector':
  385. self.SetBrush(wx.Brush(wx.Colour(248, 215, 215)))
  386. else:
  387. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  388. if name:
  389. self.AddText(name)
  390. self.AddText(value)
  391. else:
  392. self.AddText(_('unknown'))
  393. def GetLog(self, string = True):
  394. """!Get logging info"""
  395. if self.name:
  396. return self.name + '=' + self.value + ' (' + self.prompt + ')'
  397. else:
  398. return _('unknown')
  399. def GetName(self):
  400. """!Get name"""
  401. return self.name
  402. def GetPrompt(self):
  403. """!Get prompt"""
  404. return self.prompt
  405. def GetValue(self):
  406. """!Get value"""
  407. return self.value
  408. def GetActions(self, direction):
  409. """!Get related actions
  410. @param direction direction - 'from' or 'to'
  411. """
  412. return self.actions[direction]
  413. def AddAction(self, action, direction):
  414. """!Record related actions
  415. @param action action to be recoreded
  416. @param direction direction of relation
  417. """
  418. self.actions[direction].append(action)
  419. def GetPropDialog(self):
  420. """!Get properties dialog"""
  421. return None
  422. class ModelEvtHandler(ogl.ShapeEvtHandler):
  423. """!Model event handler class"""
  424. def __init__(self, log, frame):
  425. ogl.ShapeEvtHandler.__init__(self)
  426. self.log = log
  427. self.frame = frame
  428. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  429. """!Left mouse button pressed -> select item & update statusbar"""
  430. shape = self.GetShape()
  431. canvas = shape.GetCanvas()
  432. dc = wx.ClientDC(canvas)
  433. canvas.PrepareDC(dc)
  434. if shape.Selected():
  435. shape.Select(False, dc)
  436. else:
  437. redraw = False
  438. shapeList = canvas.GetDiagram().GetShapeList()
  439. toUnselect = list()
  440. for s in shapeList:
  441. if s.Selected():
  442. toUnselect.append(s)
  443. shape.Select(True, dc)
  444. for s in toUnselect:
  445. s.Select(False, dc)
  446. canvas.Refresh(False)
  447. self.log.SetStatusText(shape.GetLog(), 0)
  448. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  449. """!Left mouse button pressed (double-click) -> show properties"""
  450. shape = self.GetShape()
  451. win = shape.GetPropDialog()
  452. if isinstance(shape, ModelAction) and not win:
  453. module = menuform.GUI().ParseCommand(shape.cmd,
  454. completed = (self.frame.GetOptData, shape, None),
  455. parentframe = self.frame, show = True)
  456. elif win and not win.IsShown():
  457. win.Show()
  458. if win:
  459. win.Raise()
  460. class ModelSearchDialog(wx.Dialog):
  461. def __init__(self, parent, id = wx.ID_ANY, title = _("Find GRASS module"),
  462. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  463. """!Graphical modeler module search window
  464. @param parent parent window
  465. @param id window id
  466. @param title window title
  467. @param kwargs wx.Dialogs' arguments
  468. """
  469. self.parent = parent
  470. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  471. self.SetName("ModelerDialog")
  472. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  473. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  474. self.searchBy = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  475. choices = [_("description"),
  476. _("keywords")])
  477. self.search = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  478. value = "", size = (-1, 25))
  479. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  480. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  481. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  482. self.btnOk.SetDefault()
  483. self._layout()
  484. def _layout(self):
  485. btnSizer = wx.StdDialogButtonSizer()
  486. btnSizer.AddButton(self.btnCancel)
  487. btnSizer.AddButton(self.btnOk)
  488. btnSizer.Realize()
  489. bodyBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  490. label=" %s " % _("Find GRASS module"))
  491. bodySizer = wx.StaticBoxSizer(bodyBox, wx.VERTICAL)
  492. searchSizer = wx.BoxSizer(wx.HORIZONTAL)
  493. searchSizer.Add(item = self.searchBy,
  494. proportion = 0, flag = wx.LEFT, border = 3)
  495. searchSizer.Add(item = self.search,
  496. proportion = 1, flag = wx.LEFT | wx.EXPAND, border = 3)
  497. bodySizer.Add(item=searchSizer, proportion=0,
  498. flag=wx.EXPAND | wx.ALL, border=1)
  499. bodySizer.Add(item=self.cmd_prompt, proportion=1,
  500. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  501. mainSizer = wx.BoxSizer(wx.VERTICAL)
  502. mainSizer.Add(item=bodySizer, proportion=1,
  503. flag=wx.EXPAND | wx.ALL, border=5)
  504. mainSizer.Add(item=btnSizer, proportion=0,
  505. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  506. self.panel.SetSizer(mainSizer)
  507. mainSizer.Fit(self.panel)
  508. def GetPanel(self):
  509. """!Get dialog panel"""
  510. return self.panel
  511. def GetCmd(self):
  512. """!Get command"""
  513. line = self.cmd_prompt.GetCurLine()[0].strip()
  514. if len(line) == 0:
  515. list()
  516. try:
  517. cmd = shlex.split(str(line))
  518. except UnicodeError:
  519. cmd = shlex.split(utils.EncodeString((line)))
  520. return cmd
  521. def OnOk(self, event):
  522. self.btnOk.SetFocus()
  523. def Reset(self):
  524. """!Reset dialog"""
  525. self.searchBy.SetSelection(0)
  526. self.search.SetValue('')
  527. self.cmd_prompt.OnCmdErase(None)
  528. class ProcessModelFile:
  529. """!Process GRASS model file (gxm)"""
  530. def __init__(self, tree):
  531. """!A ElementTree handler for the GXM XML file, as defined in
  532. grass-gxm.dtd.
  533. """
  534. self.tree = tree
  535. self.root = self.tree.getroot()
  536. # list of actions, data
  537. self.actions = list()
  538. self.data = list()
  539. self._processActions()
  540. self._processData()
  541. def _filterValue(self, value):
  542. """!Filter value
  543. @param value
  544. """
  545. value = value.replace('&lt;', '<')
  546. value = value.replace('&gt;', '>')
  547. return value
  548. def _getNodeText(self, node, tag, default = ''):
  549. """!Get node text"""
  550. p = node.find(tag)
  551. if p is not None:
  552. return utils.normalize_whitespace(p.text)
  553. return default
  554. def _processActions(self):
  555. """!Process model file"""
  556. for action in self.root.findall('action'):
  557. pos, size = self._getDim(action)
  558. task = action.find('task')
  559. if task:
  560. cmd = self._processTask(task)
  561. else:
  562. cmd = None
  563. self.actions.append({ 'pos' : pos,
  564. 'size': size,
  565. 'cmd' : cmd })
  566. def _getDim(self, node):
  567. """!Get position and size of shape"""
  568. pos = size = None
  569. posAttr = node.get('pos', None)
  570. if posAttr:
  571. posVal = map(int, posAttr.split(','))
  572. try:
  573. pos = (posVal[0], posVal[1])
  574. except:
  575. pos = None
  576. sizeAttr = node.get('size', None)
  577. if sizeAttr:
  578. sizeVal = map(int, sizeAttr.split(','))
  579. try:
  580. size = (sizeVal[0], sizeVal[1])
  581. except:
  582. size = None
  583. return pos, size
  584. def _processData(self):
  585. """!Process model file"""
  586. for data in self.root.findall('data'):
  587. pos, size = self._getDim(data)
  588. param = data.find('parameter')
  589. name = prompt = value = None
  590. if param is not None:
  591. name = param.get('name', None)
  592. prompt = param.get('prompt', None)
  593. value = self._filterValue(self._getNodeText(param, 'value'))
  594. action = data.find('action')
  595. aId = fromDir = None
  596. if action is not None:
  597. aId = int(action.get('id', None))
  598. if action.get('dir', 'to') == 'to':
  599. fromDir = False
  600. else:
  601. fromDir = True
  602. self.data.append({ 'pos' : pos,
  603. 'size': size,
  604. 'name' : name,
  605. 'prompt' : prompt,
  606. 'value' : value,
  607. 'id' : aId,
  608. 'from' : fromDir })
  609. def _processTask(self, node):
  610. """!Process task"""
  611. cmd = list()
  612. name = node.get('name', None)
  613. if not name:
  614. return cmd
  615. cmd.append(name)
  616. # flags
  617. for p in node.findall('flag'):
  618. flag = p.get('name', '')
  619. if len(flag) > 1:
  620. cmd.append('--' + flag)
  621. else:
  622. cmd.append('-' + flag)
  623. # parameters
  624. for p in node.findall('parameter'):
  625. cmd.append('%s=%s' % (p.get('name', ''),
  626. self._filterValue(self._getNodeText(p, 'value'))))
  627. return cmd
  628. class WriteModelFile:
  629. """!Generic class for writing model file"""
  630. def __init__(self, fd, actions, data):
  631. self.fd = fd
  632. self.actions = actions
  633. self.data = data
  634. self.indent = 0
  635. self._header()
  636. self._actions()
  637. self._data()
  638. self._footer()
  639. def _filterValue(self, value):
  640. """!Make value XML-valid"""
  641. value = value.replace('<', '&lt;')
  642. value = value.replace('>', '&gt;')
  643. return value
  644. def _header(self):
  645. """!Write header"""
  646. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  647. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  648. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  649. def _footer(self):
  650. """!Write footer"""
  651. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  652. def _actions(self):
  653. """!Write actions"""
  654. id = 1
  655. self.indent += 4
  656. for action in self.actions:
  657. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  658. (' ' * self.indent, id, action.GetName(), action.GetX(), action.GetY(),
  659. action.GetWidth(), action.GetHeight()))
  660. self.indent += 4
  661. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  662. self.indent += 4
  663. for key, val in action.GetParams().iteritems():
  664. if key == 'flags':
  665. for f in val:
  666. if f.get('value', False):
  667. self.fd.write('%s<flag name="%s" />\n' %
  668. (' ' * self.indent, f.get('name', '')))
  669. else: # parameter
  670. for p in val:
  671. if not p.get('value', ''):
  672. continue
  673. self.fd.write('%s<parameter name="%s">\n' %
  674. (' ' * self.indent, p.get('name', '')))
  675. self.indent += 4
  676. self.fd.write('%s<value>%s</value>\n' %
  677. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  678. self.indent -= 4
  679. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  680. self.indent -= 4
  681. self.fd.write('%s</task>\n' % (' ' * self.indent))
  682. self.indent -= 4
  683. self.fd.write('%s</action>\n' % (' ' * self.indent))
  684. id += 1
  685. self.indent -= 4
  686. def _data(self):
  687. """!Write data"""
  688. self.indent += 4
  689. for data in self.data:
  690. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  691. (' ' * self.indent, data.GetX(), data.GetY(),
  692. data.GetWidth(), data.GetHeight()))
  693. self.indent += 4
  694. self.fd.write('%s<parameter name="%s" prompt="%s">\n' % \
  695. (' ' * self.indent, data.GetName(), data.GetPrompt()))
  696. self.indent += 4
  697. self.fd.write('%s<value>%s</value>\n' %
  698. (' ' * self.indent, self._filterValue(data.GetValue())))
  699. self.indent -= 4
  700. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  701. self.indent -= 4
  702. for action in data.GetActions('from'):
  703. self.fd.write('%s<action id="1" dir="from" />\n' % \
  704. (' ' * self.indent))
  705. for action in data.GetActions('to'):
  706. self.fd.write('%s<action id="1" dir="to" />\n' % \
  707. (' ' * self.indent))
  708. self.fd.write('%s</data>\n' % (' ' * self.indent))
  709. self.indent -= 4
  710. def main():
  711. app = wx.PySimpleApp()
  712. frame = ModelFrame(parent = None)
  713. if len(sys.argv) > 1:
  714. frame.LoadModelFile(sys.argv[1])
  715. # frame.CentreOnScreen()
  716. frame.Show()
  717. app.MainLoop()
  718. if __name__ == "__main__":
  719. main()