gmodeler.py 29 KB

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