gmodeler.py 30 KB

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