gmodeler.py 30 KB

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