gmodeler.py 31 KB

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