gmodeler.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  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. - ModelDataDialog
  11. - ProcessModelFile
  12. - WriteModelFile
  13. (C) 2010 by the GRASS Development Team
  14. This program is free software under the GNU General Public License
  15. (>=v2). Read the file COPYING that comes with GRASS for details.
  16. @author Martin Landa <landa.martin gmail.com>
  17. """
  18. import os
  19. import sys
  20. import shlex
  21. import time
  22. import traceback
  23. try:
  24. import xml.etree.ElementTree as etree
  25. except ImportError:
  26. import elementtree.ElementTree as etree # Python <= 2.4
  27. import globalvar
  28. if not os.getenv("GRASS_WXBUNDLED"):
  29. globalvar.CheckForWx()
  30. import wx
  31. import wx.lib.ogl as ogl
  32. import wx.lib.flatnotebook as FN
  33. import menu
  34. import menudata
  35. import toolbars
  36. import menuform
  37. import prompt
  38. import utils
  39. import goutput
  40. import gselect
  41. from debug import Debug
  42. from gcmd import GMessage
  43. from gdialogs import ElementDialog
  44. from grass.script import core as grass
  45. class ModelFrame(wx.Frame):
  46. def __init__(self, parent, id = wx.ID_ANY, title = _("Graphical modeler (under development)"), **kwargs):
  47. """!Graphical modeler main window
  48. @param parent parent window
  49. @param id window id
  50. @param title window title
  51. @param kwargs wx.Frames' arguments
  52. """
  53. self.parent = parent
  54. self.searchDialog = None # module search dialog
  55. self.actions = list() # list of recorded actions
  56. self.data = list() # list of recorded data items
  57. self.baseTitle = title
  58. self.modelFile = None # loaded model
  59. self.modelChanged = False
  60. self.cursors = {
  61. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  62. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  63. }
  64. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  65. self.SetName("Modeler")
  66. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  67. self.menubar = menu.Menu(parent = self, data = menudata.ModelerData())
  68. self.SetMenuBar(self.menubar)
  69. self.toolbar = toolbars.ModelToolbar(parent = self)
  70. self.SetToolBar(self.toolbar)
  71. self.statusbar = self.CreateStatusBar(number = 1)
  72. self.notebook = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
  73. style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
  74. FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON)
  75. self.canvas = ModelCanvas(self)
  76. self.canvas.SetBackgroundColour(wx.WHITE)
  77. self.canvas.SetCursor(self.cursors["default"])
  78. self.goutput = goutput.GMConsole(parent = self, pageid = 1)
  79. self.modelPage = self.notebook.AddPage(self.canvas, text=_('Model'))
  80. self.commandPage = self.notebook.AddPage(self.goutput, text=_('Command output'))
  81. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  82. self._layout()
  83. self.SetMinSize((350, 200))
  84. self.SetSize((640, 480))
  85. def _layout(self):
  86. """!Do layout"""
  87. sizer = wx.BoxSizer(wx.VERTICAL)
  88. sizer.Add(item = self.notebook, proportion = 1,
  89. flag = wx.EXPAND)
  90. self.SetAutoLayout(True)
  91. self.SetSizer(sizer)
  92. sizer.Fit(self)
  93. self.Layout()
  94. def _addEvent(self, item):
  95. """!Add event to item"""
  96. evthandler = ModelEvtHandler(self.statusbar,
  97. self)
  98. evthandler.SetShape(item)
  99. evthandler.SetPreviousHandler(item.GetEventHandler())
  100. item.SetEventHandler(evthandler)
  101. def FindAction(self, id):
  102. """!Find action by id"""
  103. for action in self.actions:
  104. if action.GetId() == id:
  105. return action
  106. return None
  107. def FindData(self, value, prompt):
  108. """!Find data by value, and prompt"""
  109. for data in self.data:
  110. if data.GetValue() == value and \
  111. data.GetPrompt() == prompt:
  112. return data
  113. return None
  114. def ModelChanged(self):
  115. """!Update window title"""
  116. if not self.modelChanged:
  117. self.modelChanged = True
  118. if self.modelFile:
  119. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile) + '*')
  120. def OnCloseWindow(self, event):
  121. """!Close window"""
  122. self.Destroy()
  123. def OnModelNew(self, event):
  124. """!Create new model"""
  125. Debug.msg(4, "ModelFrame.OnModelNew():")
  126. # ask user to save current model
  127. if self.modelFile and self.modelChanged:
  128. self.OnModelSave()
  129. elif self.modelFile is None and \
  130. (len(self.actions) > 0 or len(self.data) > 0):
  131. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  132. "Do you want to store current settings "
  133. "to model file?"),
  134. caption=_("Create new model?"),
  135. style=wx.YES_NO | wx.YES_DEFAULT |
  136. wx.CANCEL | wx.ICON_QUESTION)
  137. ret = dlg.ShowModal()
  138. if ret == wx.ID_YES:
  139. self.OnModelSaveAs()
  140. elif ret == wx.ID_CANCEL:
  141. dlg.Destroy()
  142. return
  143. dlg.Destroy()
  144. # delete all items
  145. self.canvas.GetDiagram().DeleteAllShapes()
  146. self.actions = list()
  147. self.data = list()
  148. self.canvas.Refresh()
  149. # no model file loaded
  150. self.modelFile = None
  151. self.modelChanged = False
  152. self.SetTitle(self.baseTitle)
  153. def OnModelOpen(self, event):
  154. """!Load model from file"""
  155. filename = ''
  156. dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
  157. defaultDir = os.getcwd(),
  158. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  159. if dlg.ShowModal() == wx.ID_OK:
  160. filename = dlg.GetPath()
  161. if not filename:
  162. return
  163. Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
  164. # close current model
  165. self.OnModelClose()
  166. self.LoadModelFile(filename)
  167. self.modelFile = filename
  168. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  169. self.SetStatusText(_('%d actions loaded into model') % len(self.actions), 0)
  170. def OnModelSave(self, event = None):
  171. """!Save model to file"""
  172. if self.modelFile:
  173. dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
  174. "Do you want to overwrite this file?") % \
  175. self.modelFile,
  176. caption=_("Save model"),
  177. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  178. if dlg.ShowModal() == wx.ID_NO:
  179. dlg.Destroy()
  180. else:
  181. Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
  182. self.WriteModelFile(self.modelFile)
  183. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  184. else:
  185. self.OnModelSaveAs(None)
  186. def OnModelSaveAs(self, event):
  187. """!Create model to file as"""
  188. filename = ''
  189. dlg = wx.FileDialog(parent = self,
  190. message = _("Choose file to save current model"),
  191. defaultDir = os.getcwd(),
  192. wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
  193. style=wx.FD_SAVE)
  194. if dlg.ShowModal() == wx.ID_OK:
  195. filename = dlg.GetPath()
  196. if not filename:
  197. return
  198. # check for extension
  199. if filename[-4:] != ".gxm":
  200. filename += ".gxm"
  201. if os.path.exists(filename):
  202. dlg = wx.MessageDialog(parent = self,
  203. message=_("Model file <%s> already exists. "
  204. "Do you want to overwrite this file?") % filename,
  205. caption=_("File already exists"),
  206. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  207. if dlg.ShowModal() != wx.ID_YES:
  208. dlg.Destroy()
  209. return
  210. Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
  211. self.WriteModelFile(filename)
  212. self.modelFile = filename
  213. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  214. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  215. def OnModelClose(self, event = None):
  216. """!Close model file"""
  217. Debug.msg(4, "ModelFrame.OnModelClose(): file=%s" % self.modelFile)
  218. # ask user to save current model
  219. if self.modelFile and self.modelChanged:
  220. self.OnModelSave()
  221. elif self.modelFile is None and \
  222. (len(self.actions) > 0 or len(self.data) > 0):
  223. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  224. "Do you want to store current settings "
  225. "to model file?"),
  226. caption=_("Create new model?"),
  227. style=wx.YES_NO | wx.YES_DEFAULT |
  228. wx.CANCEL | wx.ICON_QUESTION)
  229. ret = dlg.ShowModal()
  230. if ret == wx.ID_YES:
  231. self.OnModelSaveAs()
  232. elif ret == wx.ID_CANCEL:
  233. dlg.Destroy()
  234. return
  235. dlg.Destroy()
  236. self.modelFile = None
  237. self.SetTitle(self.baseTitle)
  238. self.canvas.GetDiagram().DeleteAllShapes()
  239. self.actions = list()
  240. self.data = list()
  241. self.canvas.Refresh()
  242. def OnRunModel(self, event):
  243. """!Run entire model"""
  244. if len(self.actions) < 1:
  245. GMessage(parent = self,
  246. message = _('Model is empty. Nothing to run.'),
  247. msgType = 'info')
  248. return
  249. errList = self._validateModel()
  250. if errList:
  251. dlg = wx.MessageDialog(parent = self,
  252. message = _('Model is not valid. Do you want to '
  253. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  254. caption=_("Run model?"),
  255. style = wx.YES_NO | wx.NO_DEFAULT |
  256. wx.ICON_QUESTION | wx.CENTRE)
  257. ret = dlg.ShowModal()
  258. if ret != wx.ID_YES:
  259. return
  260. for action in self.actions:
  261. self.SetStatusText(_('Running model...'), 0)
  262. self.goutput.RunCmd(command = action.GetLog(string = False),
  263. onDone = self.OnDone)
  264. def OnDone(self, returncode):
  265. """!Computation finished"""
  266. self.SetStatusText('', 0)
  267. def OnValidateModel(self, event, showMsg = True):
  268. """!Validate entire model"""
  269. if len(self.actions) < 1:
  270. GMessage(parent = self,
  271. message = _('Model is empty. Nothing to validate.'),
  272. msgType = 'info')
  273. return
  274. errList = self._validateModel()
  275. if errList:
  276. GMessage(parent = self,
  277. message = _('Model is not valid.\n\n%s') % '\n'.join(errList),
  278. msgType = 'warning')
  279. else:
  280. GMessage(parent = self,
  281. message = _('Model is valid.'),
  282. msgType = 'info')
  283. def _validateModel(self):
  284. """!Validate model"""
  285. self.SetStatusText(_('Validating model...'), 0)
  286. errList = list()
  287. for action in self.actions:
  288. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  289. show = None)
  290. errList += task.getCmdError()
  291. self.SetStatusText('', 0)
  292. return errList
  293. def OnRemoveItem(self, event):
  294. """!Remove item from model"""
  295. pass
  296. def OnDefineRelation(self, event):
  297. """!Define relation between data and action items"""
  298. self.canvas.SetCursor(self.cursors["cross"])
  299. def OnAddAction(self, event):
  300. """!Add action to model"""
  301. if self.searchDialog is None:
  302. self.searchDialog = ModelSearchDialog(self)
  303. self.searchDialog.CentreOnParent()
  304. else:
  305. self.searchDialog.Reset()
  306. if self.searchDialog.ShowModal() == wx.ID_CANCEL:
  307. self.searchDialog.Hide()
  308. return
  309. cmd = self.searchDialog.GetCmd()
  310. self.searchDialog.Hide()
  311. self.ModelChanged()
  312. # add action to canvas
  313. width, height = self.canvas.GetSize()
  314. action = ModelAction(self, cmd = cmd, x = width/2, y = height/2)
  315. self.canvas.diagram.AddShape(action)
  316. action.Show(True)
  317. self._addEvent(action)
  318. self.actions.append(action)
  319. self.canvas.Refresh()
  320. time.sleep(.1)
  321. # show properties dialog
  322. win = action.GetPropDialog()
  323. if not win:
  324. module = menuform.GUI().ParseCommand(action.GetLog(string = False),
  325. completed = (self.GetOptData, action, None),
  326. parentframe = self, show = True)
  327. elif not win.IsShown():
  328. win.Show()
  329. if win:
  330. win.Raise()
  331. def OnAddData(self, event):
  332. """!Add data item to model"""
  333. # add action to canvas
  334. width, height = self.canvas.GetSize()
  335. data = ModelData(self, x = width/2, y = height/2)
  336. self.canvas.diagram.AddShape(data)
  337. data.Show(True)
  338. self._addEvent(data)
  339. self.data.append(data)
  340. self.canvas.Refresh()
  341. def OnHelp(self, event):
  342. """!Display manual page"""
  343. grass.run_command('g.manual',
  344. entry = 'wxGUI.Modeler')
  345. def OnAbout(self, event):
  346. """!Display About window"""
  347. info = wx.AboutDialogInfo()
  348. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  349. info.SetName(_('wxGUI Graphical Modeler'))
  350. info.SetWebSite('http://grass.osgeo.org')
  351. info.SetDescription(_('(C) 2010 by the GRASS Development Team\n\n'
  352. 'This program is free software under the GNU General Public License'
  353. '(>=v2). Read the file COPYING that comes with GRASS for details.'))
  354. wx.AboutBox(info)
  355. def GetOptData(self, dcmd, layer, params, propwin):
  356. """!Process action data"""
  357. layer.SetProperties(dcmd, params, propwin)
  358. if params: # add data items
  359. width, height = self.canvas.GetSize()
  360. x = [width/2 + 200, width/2 - 200]
  361. for p in params['params']:
  362. if p.get('prompt', '') in ('raster', 'vector', 'raster3d') and \
  363. (p.get('value', None) or \
  364. p.get('age', 'old') != 'old'):
  365. # create data item
  366. data = layer.FindData(p.get('name', ''))
  367. if data:
  368. data.SetValue(p.get('value', ''))
  369. continue
  370. data = self.FindData(p.get('value', ''),
  371. p.get('prompt', ''))
  372. if data:
  373. if p.get('age', 'old') == 'old':
  374. self._addLine(data, layer)
  375. data.AddAction(layer, direction = 'from')
  376. else:
  377. self._addLine(layer, data)
  378. data.AddAction(layer, direction = 'to')
  379. continue
  380. data = ModelData(self, name = p.get('name', ''),
  381. value = p.get('value', ''),
  382. prompt = p.get('prompt', ''),
  383. x = x.pop(), y = height/2)
  384. layer.AddData(data)
  385. self.canvas.diagram.AddShape(data)
  386. data.Show(True)
  387. self._addEvent(data)
  388. self.data.append(data)
  389. if p.get('age', 'old') == 'old':
  390. self._addLine(data, layer)
  391. data.AddAction(layer, direction = 'from')
  392. else:
  393. self._addLine(layer, data)
  394. data.AddAction(layer, direction = 'to')
  395. # valid ?
  396. valid = True
  397. for p in params['params']:
  398. if p.get('value', '') == '' and \
  399. p.get('default', '') == '':
  400. valid = False
  401. break
  402. layer.SetValid(valid)
  403. self.canvas.Refresh()
  404. self.SetStatusText(layer.GetLog(), 0)
  405. def _addLine(self, fromShape, toShape):
  406. """!Add connection
  407. @param fromShape from
  408. @param toShape to
  409. """
  410. line = ogl.LineShape()
  411. line.SetCanvas(self)
  412. line.SetPen(wx.BLACK_PEN)
  413. line.SetBrush(wx.BLACK_BRUSH)
  414. line.AddArrow(ogl.ARROW_ARROW)
  415. line.MakeLineControlPoints(2)
  416. fromShape.AddLine(line, toShape)
  417. self.canvas.diagram.AddShape(line)
  418. line.Show(True)
  419. def LoadModelFile(self, filename):
  420. """!Load model definition stored in GRASS Model XML file (gxm)
  421. @todo Validate against DTD
  422. Raise exception on error.
  423. """
  424. ### dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  425. # parse workspace file
  426. try:
  427. gxmXml = ProcessModelFile(etree.parse(filename))
  428. except:
  429. GMessage(parent = self,
  430. message = _("Reading model file <%s> failed.\n"
  431. "Invalid file, unable to parse XML document.") % filename)
  432. return
  433. self.modelFile = filename
  434. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  435. self.SetStatusText(_("Please wait, loading model..."), 0)
  436. # load actions
  437. for action in gxmXml.actions:
  438. actionShape = ModelAction(parent = self,
  439. x = action['pos'][0],
  440. y = action['pos'][1],
  441. width = action['size'][0],
  442. height = action['size'][1],
  443. cmd = action['cmd'])
  444. actionShape.SetId(action['id'])
  445. self.canvas.diagram.AddShape(actionShape)
  446. actionShape.Show(True)
  447. self._addEvent(actionShape)
  448. self.actions.append(actionShape)
  449. task = menuform.GUI().ParseCommand(cmd = actionShape.GetLog(string = False),
  450. show = None)
  451. valid = True
  452. for p in task.get_options()['params']:
  453. if p.get('value', '') == '' and \
  454. p.get('default', '') == '':
  455. valid = False
  456. break
  457. actionShape.SetValid(valid)
  458. # load data & connections
  459. for data in gxmXml.data:
  460. dataShape = ModelData(parent = self,
  461. x = data['pos'][0],
  462. y = data['pos'][1],
  463. width = data['size'][0],
  464. height = data['size'][1],
  465. name = data['name'],
  466. prompt = data['prompt'],
  467. value = data['value'])
  468. self.canvas.diagram.AddShape(dataShape)
  469. dataShape.Show(True)
  470. self._addEvent(dataShape)
  471. self.data.append(dataShape)
  472. for idx in range(len(data['id'])):
  473. actionShape = self.FindAction(data['id'][idx])
  474. if data['from'][idx] is True:
  475. self._addLine(dataShape, actionShape)
  476. dataShape.AddAction(actionShape, direction = 'from')
  477. elif data['from'][idx] is False:
  478. self._addLine(actionShape, dataShape)
  479. dataShape.AddAction(actionShape, direction = 'to')
  480. actionShape.AddData(dataShape)
  481. self.SetStatusText('', 0)
  482. self.canvas.Refresh(True)
  483. def WriteModelFile(self, filename):
  484. """!Save model to model file
  485. @return True on success
  486. @return False on failure
  487. """
  488. try:
  489. file = open(filename, "w")
  490. except IOError:
  491. wx.MessageBox(parent = self,
  492. message = _("Unable to open file <%s> for writing.") % filename,
  493. caption = _("Error"),
  494. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  495. return False
  496. try:
  497. WriteModelFile(fd = file, actions = self.actions, data = self.data)
  498. except StandardError:
  499. file.close()
  500. GMessage(parent = self,
  501. message = _("Writing current settings to model file failed."))
  502. return False
  503. file.close()
  504. return True
  505. class ModelCanvas(ogl.ShapeCanvas):
  506. """!Canvas where model is drawn"""
  507. def __init__(self, parent):
  508. ogl.OGLInitialize()
  509. ogl.ShapeCanvas.__init__(self, parent)
  510. self.diagram = ogl.Diagram()
  511. self.SetDiagram(self.diagram)
  512. self.diagram.SetCanvas(self)
  513. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  514. class ModelAction(ogl.RectangleShape):
  515. """!Action class (GRASS module)"""
  516. def __init__(self, parent, x, y, cmd = None, width = 100, height = 50):
  517. self.parent = parent
  518. self.cmd = cmd
  519. self.params = None
  520. self.propWin = None
  521. self.id = -1 # used for gxm file
  522. self.data = list() # list of connected data items
  523. # colors
  524. self.colors = dict()
  525. self.colors['valid'] = wx.LIGHT_GREY_BRUSH
  526. self.colors['invalid'] = wx.WHITE_BRUSH
  527. ogl.RectangleShape.__init__(self, width, height)
  528. # self.Draggable(True)
  529. self.SetCanvas(self.parent)
  530. self.SetX(x)
  531. self.SetY(y)
  532. self.SetPen(wx.BLACK_PEN)
  533. self.SetBrush(self.colors['invalid'])
  534. if self.cmd and len(self.cmd) > 0:
  535. self.AddText(self.cmd[0])
  536. else:
  537. self.AddText('<<module>>')
  538. def GetId(self):
  539. """!Get id"""
  540. return self.id
  541. def SetId(self, id):
  542. """!Set id"""
  543. self.id = id
  544. def SetProperties(self, dcmd, params, propwin):
  545. """!Record properties dialog"""
  546. self.cmd = dcmd
  547. self.params = params
  548. self.propWin = propwin
  549. def GetPropDialog(self):
  550. """!Get properties dialog"""
  551. return self.propWin
  552. def GetLog(self, string = True):
  553. """!Get logging info"""
  554. if string:
  555. if self.cmd is None:
  556. return ''
  557. else:
  558. return ' '.join(self.cmd)
  559. return self.cmd
  560. def GetName(self):
  561. """!Get name"""
  562. if self.cmd and len(self.cmd) > 0:
  563. return self.cmd[0]
  564. return _('unknown')
  565. def GetParams(self):
  566. """!Get dictionary of parameters"""
  567. return self.params
  568. def SetParams(self, params, cmd):
  569. """!Set dictionary of parameters"""
  570. self.params = params
  571. self.cmd = cmd
  572. def SetValid(self, isvalid):
  573. """!Set instance to be valid/invalid"""
  574. if isvalid:
  575. self.SetBrush(self.colors['valid'])
  576. else:
  577. self.SetBrush(self.colors['invalid'])
  578. def AddData(self, item):
  579. """!Register new data item"""
  580. if item not in self.data:
  581. self.data.append(item)
  582. def FindData(self, name):
  583. """!Find data item by name"""
  584. for d in self.data:
  585. if d.GetName() == name:
  586. return d
  587. return None
  588. class ModelData(ogl.EllipseShape):
  589. """!Data item class"""
  590. def __init__(self, parent, x, y, name = '', value = '', prompt = '', width = 175, height = 50):
  591. self.parent = parent
  592. self.name = name
  593. self.value = value
  594. self.prompt = prompt
  595. self.propWin = None
  596. self.actions = { 'from' : list(), 'to' : list() }
  597. ogl.EllipseShape.__init__(self, width, height)
  598. # self.Draggable(True)
  599. self.SetCanvas(self.parent)
  600. self.SetX(x)
  601. self.SetY(y)
  602. self.SetPen(wx.BLACK_PEN)
  603. if self.prompt == 'raster':
  604. self.SetBrush(wx.Brush(wx.Colour(215, 215, 248)))
  605. elif self.prompt == 'vector':
  606. self.SetBrush(wx.Brush(wx.Colour(248, 215, 215)))
  607. else:
  608. self.SetBrush(wx.LIGHT_GREY_BRUSH)
  609. if name:
  610. self.AddText(name)
  611. else:
  612. self.AddText(_('unknown'))
  613. if value:
  614. self.AddText(value)
  615. else:
  616. self.AddText('\n')
  617. def GetLog(self, string = True):
  618. """!Get logging info"""
  619. if self.name:
  620. return self.name + '=' + self.value + ' (' + self.prompt + ')'
  621. else:
  622. return _('unknown')
  623. def GetName(self):
  624. """!Get name"""
  625. return self.name
  626. def GetPrompt(self):
  627. """!Get prompt"""
  628. return self.prompt
  629. def GetValue(self):
  630. """!Get value"""
  631. return self.value
  632. def SetValue(self, value):
  633. """!Set value"""
  634. self.value = value
  635. self.ClearText()
  636. self.AddText(self.name)
  637. if value:
  638. self.AddText(self.value)
  639. else:
  640. self.AddText('\n')
  641. for direction in ('from', 'to'):
  642. for action in self.actions[direction]:
  643. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  644. show = None)
  645. task.set_param(self.name, self.value)
  646. action.SetParams(params = task.get_options(),
  647. cmd = task.getCmd(ignoreErrors = True))
  648. def GetActions(self, direction):
  649. """!Get related actions
  650. @param direction direction - 'from' or 'to'
  651. """
  652. return self.actions[direction]
  653. def AddAction(self, action, direction):
  654. """!Record related actions
  655. @param action action to be recoreded
  656. @param direction direction of relation
  657. """
  658. self.actions[direction].append(action)
  659. def GetPropDialog(self):
  660. """!Get properties dialog"""
  661. return self.propWin
  662. def SetPropDialog(self, win):
  663. """!Get properties dialog"""
  664. self.propWin = win
  665. class ModelDataDialog(ElementDialog):
  666. """!Data item properties dialog"""
  667. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Data properties"),
  668. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  669. self.parent = parent
  670. self.shape = shape
  671. prompt = shape.GetPrompt()
  672. if prompt == 'raster':
  673. label = _('Name of raster map:')
  674. elif prompt == 'vector':
  675. label = _('Name of vector map:')
  676. else:
  677. label = _('Name of element:')
  678. ElementDialog.__init__(self, parent, title, label = label)
  679. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY,
  680. size = globalvar.DIALOG_GSELECT_SIZE,
  681. type = prompt)
  682. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  683. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  684. self.PostInit()
  685. self._layout()
  686. self.SetMinSize(self.GetSize())
  687. def _layout(self):
  688. """!Do layout"""
  689. self.dataSizer.Add(self.element, proportion=0,
  690. flag=wx.EXPAND | wx.ALL, border=1)
  691. self.panel.SetSizer(self.sizer)
  692. self.sizer.Fit(self)
  693. def OnOK(self, event):
  694. """!Ok pressed"""
  695. self.shape.SetValue(self.GetElement())
  696. self.parent.canvas.Refresh()
  697. self.parent.SetStatusText('', 0)
  698. self.OnCancel(event)
  699. def OnCancel(self, event):
  700. """!Cancel pressed"""
  701. self.shape.SetPropDialog(None)
  702. self.Destroy()
  703. class ModelEvtHandler(ogl.ShapeEvtHandler):
  704. """!Model event handler class"""
  705. def __init__(self, log, frame):
  706. ogl.ShapeEvtHandler.__init__(self)
  707. self.log = log
  708. self.frame = frame
  709. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  710. """!Left mouse button pressed -> select item & update statusbar"""
  711. shape = self.GetShape()
  712. canvas = shape.GetCanvas()
  713. dc = wx.ClientDC(canvas)
  714. canvas.PrepareDC(dc)
  715. if shape.Selected():
  716. shape.Select(False, dc)
  717. else:
  718. redraw = False
  719. shapeList = canvas.GetDiagram().GetShapeList()
  720. toUnselect = list()
  721. for s in shapeList:
  722. if s.Selected():
  723. toUnselect.append(s)
  724. shape.Select(True, dc)
  725. for s in toUnselect:
  726. s.Select(False, dc)
  727. canvas.Refresh(False)
  728. self.log.SetStatusText(shape.GetLog(), 0)
  729. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  730. """!Left mouse button pressed (double-click) -> show properties"""
  731. self.OnProperties()
  732. def OnProperties(self, event = None):
  733. """!Show properties dialog"""
  734. self.frame.ModelChanged()
  735. shape = self.GetShape()
  736. win = shape.GetPropDialog()
  737. if not win:
  738. if isinstance(shape, ModelAction):
  739. module = menuform.GUI().ParseCommand(shape.cmd,
  740. completed = (self.frame.GetOptData, shape, None),
  741. parentframe = self.frame, show = True)
  742. elif isinstance(shape, ModelData):
  743. dlg = ModelDataDialog(parent = self.frame, shape = shape)
  744. shape.SetPropDialog(dlg)
  745. dlg.CentreOnParent()
  746. dlg.Show()
  747. elif win and not win.IsShown():
  748. win.Show()
  749. if win:
  750. win.Raise()
  751. def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
  752. """!Drag shape"""
  753. self.frame.ModelChanged()
  754. if self._previousHandler:
  755. self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
  756. def OnRightClick(self, x, y, keys = 0, attachment = 0):
  757. """!Right click -> pop-up menu"""
  758. if not hasattr (self, "popupID1"):
  759. self.popupID1 = wx.NewId()
  760. self.popupID2 = wx.NewId()
  761. popupMenu = wx.Menu()
  762. popupMenu.Append(self.popupID1, text=_('Remove'))
  763. self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  764. popupMenu.AppendSeparator()
  765. popupMenu.Append(self.popupID2, text=_('Properties'))
  766. self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID2)
  767. self.frame.PopupMenu(popupMenu)
  768. popupMenu.Destroy()
  769. def OnRemove(self, event):
  770. """!Remove shape"""
  771. shape = self.GetShape()
  772. self.frame.canvas.GetDiagram().RemoveShape(shape)
  773. self.frame.canvas.Refresh()
  774. class ModelSearchDialog(wx.Dialog):
  775. def __init__(self, parent, id = wx.ID_ANY, title = _("Find GRASS module"),
  776. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  777. """!Graphical modeler module search window
  778. @param parent parent window
  779. @param id window id
  780. @param title window title
  781. @param kwargs wx.Dialogs' arguments
  782. """
  783. self.parent = parent
  784. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  785. self.SetName("ModelerDialog")
  786. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  787. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  788. self.searchBy = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  789. choices = [_("description"),
  790. _("keywords")])
  791. self.search = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  792. value = "", size = (-1, 25))
  793. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  794. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  795. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  796. self.btnOk.SetDefault()
  797. self._layout()
  798. def _layout(self):
  799. btnSizer = wx.StdDialogButtonSizer()
  800. btnSizer.AddButton(self.btnCancel)
  801. btnSizer.AddButton(self.btnOk)
  802. btnSizer.Realize()
  803. bodyBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  804. label=" %s " % _("Find GRASS module"))
  805. bodySizer = wx.StaticBoxSizer(bodyBox, wx.VERTICAL)
  806. searchSizer = wx.BoxSizer(wx.HORIZONTAL)
  807. searchSizer.Add(item = self.searchBy,
  808. proportion = 0, flag = wx.LEFT, border = 3)
  809. searchSizer.Add(item = self.search,
  810. proportion = 1, flag = wx.LEFT | wx.EXPAND, border = 3)
  811. bodySizer.Add(item=searchSizer, proportion=0,
  812. flag=wx.EXPAND | wx.ALL, border=1)
  813. bodySizer.Add(item=self.cmd_prompt, proportion=1,
  814. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  815. mainSizer = wx.BoxSizer(wx.VERTICAL)
  816. mainSizer.Add(item=bodySizer, proportion=1,
  817. flag=wx.EXPAND | wx.ALL, border=5)
  818. mainSizer.Add(item=btnSizer, proportion=0,
  819. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  820. self.panel.SetSizer(mainSizer)
  821. mainSizer.Fit(self.panel)
  822. def GetPanel(self):
  823. """!Get dialog panel"""
  824. return self.panel
  825. def GetCmd(self):
  826. """!Get command"""
  827. line = self.cmd_prompt.GetCurLine()[0].strip()
  828. if len(line) == 0:
  829. list()
  830. try:
  831. cmd = shlex.split(str(line))
  832. except UnicodeError:
  833. cmd = shlex.split(utils.EncodeString((line)))
  834. return cmd
  835. def OnOk(self, event):
  836. self.btnOk.SetFocus()
  837. def Reset(self):
  838. """!Reset dialog"""
  839. self.searchBy.SetSelection(0)
  840. self.search.SetValue('')
  841. self.cmd_prompt.OnCmdErase(None)
  842. class ProcessModelFile:
  843. """!Process GRASS model file (gxm)"""
  844. def __init__(self, tree):
  845. """!A ElementTree handler for the GXM XML file, as defined in
  846. grass-gxm.dtd.
  847. """
  848. self.tree = tree
  849. self.root = self.tree.getroot()
  850. # list of actions, data
  851. self.actions = list()
  852. self.data = list()
  853. self._processActions()
  854. self._processData()
  855. def _filterValue(self, value):
  856. """!Filter value
  857. @param value
  858. """
  859. value = value.replace('&lt;', '<')
  860. value = value.replace('&gt;', '>')
  861. return value
  862. def _getNodeText(self, node, tag, default = ''):
  863. """!Get node text"""
  864. p = node.find(tag)
  865. if p is not None:
  866. if p.text:
  867. return utils.normalize_whitespace(p.text)
  868. else:
  869. return ''
  870. return default
  871. def _processActions(self):
  872. """!Process model file"""
  873. for action in self.root.findall('action'):
  874. pos, size = self._getDim(action)
  875. task = action.find('task')
  876. if task:
  877. cmd = self._processTask(task)
  878. else:
  879. cmd = None
  880. aId = int(action.get('id', -1))
  881. self.actions.append({ 'pos' : pos,
  882. 'size': size,
  883. 'cmd' : cmd,
  884. 'id' : aId })
  885. def _getDim(self, node):
  886. """!Get position and size of shape"""
  887. pos = size = None
  888. posAttr = node.get('pos', None)
  889. if posAttr:
  890. posVal = map(int, posAttr.split(','))
  891. try:
  892. pos = (posVal[0], posVal[1])
  893. except:
  894. pos = None
  895. sizeAttr = node.get('size', None)
  896. if sizeAttr:
  897. sizeVal = map(int, sizeAttr.split(','))
  898. try:
  899. size = (sizeVal[0], sizeVal[1])
  900. except:
  901. size = None
  902. return pos, size
  903. def _processData(self):
  904. """!Process model file"""
  905. for data in self.root.findall('data'):
  906. pos, size = self._getDim(data)
  907. param = data.find('data-parameter')
  908. name = prompt = value = None
  909. if param is not None:
  910. name = param.get('name', None)
  911. prompt = param.get('prompt', None)
  912. value = self._filterValue(self._getNodeText(param, 'value'))
  913. aId = list()
  914. fromDir = list()
  915. for action in data.findall('data-action'):
  916. aId.append(int(action.get('id', None)))
  917. if action.get('dir', 'to') == 'to':
  918. fromDir.append(False)
  919. else:
  920. fromDir.append(True)
  921. self.data.append({ 'pos' : pos,
  922. 'size': size,
  923. 'name' : name,
  924. 'prompt' : prompt,
  925. 'value' : value,
  926. 'id' : aId,
  927. 'from' : fromDir })
  928. def _processTask(self, node):
  929. """!Process task"""
  930. cmd = list()
  931. name = node.get('name', None)
  932. if not name:
  933. return cmd
  934. cmd.append(name)
  935. # flags
  936. for p in node.findall('flag'):
  937. flag = p.get('name', '')
  938. if len(flag) > 1:
  939. cmd.append('--' + flag)
  940. else:
  941. cmd.append('-' + flag)
  942. # parameters
  943. for p in node.findall('parameter'):
  944. cmd.append('%s=%s' % (p.get('name', ''),
  945. self._filterValue(self._getNodeText(p, 'value'))))
  946. return cmd
  947. class WriteModelFile:
  948. """!Generic class for writing model file"""
  949. def __init__(self, fd, actions, data):
  950. self.fd = fd
  951. self.actions = actions
  952. self.data = data
  953. self.indent = 0
  954. self._header()
  955. self._actions()
  956. self._data()
  957. self._footer()
  958. def _filterValue(self, value):
  959. """!Make value XML-valid"""
  960. value = value.replace('<', '&lt;')
  961. value = value.replace('>', '&gt;')
  962. return value
  963. def _header(self):
  964. """!Write header"""
  965. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  966. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  967. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  968. def _footer(self):
  969. """!Write footer"""
  970. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  971. def _actions(self):
  972. """!Write actions"""
  973. id = 1
  974. self.indent += 4
  975. for action in self.actions:
  976. action.SetId(id)
  977. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  978. (' ' * self.indent, id, action.GetName(), action.GetX(), action.GetY(),
  979. action.GetWidth(), action.GetHeight()))
  980. self.indent += 4
  981. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  982. self.indent += 4
  983. for key, val in action.GetParams().iteritems():
  984. if key == 'flags':
  985. for f in val:
  986. if f.get('value', False):
  987. self.fd.write('%s<flag name="%s" />\n' %
  988. (' ' * self.indent, f.get('name', '')))
  989. else: # parameter
  990. for p in val:
  991. if not p.get('value', ''):
  992. continue
  993. self.fd.write('%s<parameter name="%s">\n' %
  994. (' ' * self.indent, p.get('name', '')))
  995. self.indent += 4
  996. self.fd.write('%s<value>%s</value>\n' %
  997. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  998. self.indent -= 4
  999. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1000. self.indent -= 4
  1001. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1002. self.indent -= 4
  1003. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1004. id += 1
  1005. self.indent -= 4
  1006. def _data(self):
  1007. """!Write data"""
  1008. self.indent += 4
  1009. for data in self.data:
  1010. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1011. (' ' * self.indent, data.GetX(), data.GetY(),
  1012. data.GetWidth(), data.GetHeight()))
  1013. self.indent += 4
  1014. self.fd.write('%s<data-parameter name="%s" prompt="%s">\n' % \
  1015. (' ' * self.indent, data.GetName(), data.GetPrompt()))
  1016. self.indent += 4
  1017. self.fd.write('%s<value>%s</value>\n' %
  1018. (' ' * self.indent, self._filterValue(data.GetValue())))
  1019. self.indent -= 4
  1020. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1021. for action in data.GetActions('from'):
  1022. id = action.GetId()
  1023. self.fd.write('%s<data-action id="%d" dir="from" />\n' % \
  1024. (' ' * self.indent, id))
  1025. for action in data.GetActions('to'):
  1026. id = action.GetId()
  1027. self.fd.write('%s<data-action id="%d" dir="to" />\n' % \
  1028. (' ' * self.indent, id))
  1029. self.indent -= 4
  1030. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1031. self.indent -= 4
  1032. def main():
  1033. app = wx.PySimpleApp()
  1034. frame = ModelFrame(parent = None)
  1035. if len(sys.argv) > 1:
  1036. frame.LoadModelFile(sys.argv[1])
  1037. # frame.CentreOnScreen()
  1038. frame.Show()
  1039. app.MainLoop()
  1040. if __name__ == "__main__":
  1041. main()