gmodeler.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504
  1. """!
  2. @package gmodeler.py
  3. @brief Graphical modeler to create edit, and manage models
  4. Classes:
  5. - Model
  6. - ModelFrame
  7. - ModelCanvas
  8. - ModelAction
  9. - ModelSearchDialog
  10. - ModelData
  11. - ModelDataDialog
  12. - ModelRelation
  13. - ProcessModelFile
  14. - WriteModelFile
  15. - PreferencesDialog
  16. - PropertiesDialog
  17. - ModelParamDialog
  18. (C) 2010 by the GRASS Development Team
  19. This program is free software under the GNU General Public License
  20. (>=v2). Read the file COPYING that comes with GRASS for details.
  21. @author Martin Landa <landa.martin gmail.com>
  22. """
  23. import os
  24. import sys
  25. import shlex
  26. import time
  27. import traceback
  28. import getpass
  29. import stat
  30. import textwrap
  31. import tempfile
  32. import copy
  33. try:
  34. import xml.etree.ElementTree as etree
  35. except ImportError:
  36. import elementtree.ElementTree as etree # Python <= 2.4
  37. import globalvar
  38. if not os.getenv("GRASS_WXBUNDLED"):
  39. globalvar.CheckForWx()
  40. import wx
  41. import wx.lib.ogl as ogl
  42. import wx.lib.flatnotebook as FN
  43. import wx.lib.colourselect as csel
  44. import menu
  45. import menudata
  46. import toolbars
  47. import menuform
  48. import prompt
  49. import utils
  50. import goutput
  51. import gselect
  52. from debug import Debug
  53. from gcmd import GMessage, GError
  54. from gdialogs import ElementDialog, GetImageHandlers
  55. from preferences import PreferencesBaseDialog, globalSettings as UserSettings
  56. from ghelp import SearchModuleWindow
  57. from grass.script import core as grass
  58. class Model(object):
  59. """!Class representing the model"""
  60. def __init__(self, canvas = None):
  61. self.actions = list() # list of recorded actions
  62. self.data = list() # list of recorded data items
  63. self.canvas = canvas
  64. def GetCanvas(self):
  65. """!Get canvas or None"""
  66. return self.canvas
  67. def GetActions(self):
  68. """!Return list of actions"""
  69. return self.actions
  70. def GetData(self):
  71. """!Return list of data"""
  72. return self.data
  73. def Reset(self):
  74. """!Reset model"""
  75. self.actions = list()
  76. self.data = list()
  77. def AddAction(self, item):
  78. """!Add action to the model"""
  79. self.actions.append(item)
  80. def AddData(self, item):
  81. """!Add data to the model"""
  82. self.data.append(item)
  83. def RemoveItem(self, item):
  84. """!Remove item from model"""
  85. if isinstance(item, ModelAction):
  86. self.actions.remove(item)
  87. elif isinstance(item, ModelData):
  88. self.data.remove(item)
  89. def FindAction(self, id):
  90. """!Find action by id"""
  91. for action in self.actions:
  92. if action.GetId() == id:
  93. return action
  94. return None
  95. def FindData(self, value, prompt):
  96. """!Find data by value, and prompt"""
  97. for data in self.data:
  98. if data.GetValue() == value and \
  99. data.GetPrompt() == prompt:
  100. return data
  101. return None
  102. def LoadModel(self, filename):
  103. """!Load model definition stored in GRASS Model XML file (gxm)
  104. @todo Validate against DTD
  105. Raise exception on error.
  106. """
  107. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  108. # parse workspace file
  109. try:
  110. gxmXml = ProcessModelFile(etree.parse(filename))
  111. except StandardError, e:
  112. raise GError(e)
  113. # load model.GetActions()
  114. for action in gxmXml.actions:
  115. actionItem = ModelAction(parent = self,
  116. x = action['pos'][0],
  117. y = action['pos'][1],
  118. width = action['size'][0],
  119. height = action['size'][1],
  120. task = action['task'])
  121. actionItem.SetId(action['id'])
  122. self.actions.append(actionItem)
  123. task = menuform.GUI().ParseCommand(cmd = actionItem.GetLog(string = False),
  124. show = None)
  125. valid = True
  126. for p in task.get_options()['params']:
  127. if p.get('value', '') == '' and \
  128. p.get('default', '') == '':
  129. valid = False
  130. break
  131. actionItem.SetValid(valid)
  132. # load data & connections
  133. for data in gxmXml.data:
  134. dataItem = ModelData(parent = self,
  135. x = data['pos'][0],
  136. y = data['pos'][1],
  137. width = data['size'][0],
  138. height = data['size'][1],
  139. name = data['name'],
  140. prompt = data['prompt'],
  141. value = data['value'])
  142. dataItem.SetIntermediate(data['intermediate'])
  143. for rel in data['rels']:
  144. actionItem = self.FindAction(rel['id'])
  145. if rel['dir'] == 'from':
  146. relation = ModelRelation(dataItem, actionItem)
  147. relation.SetControlPoints(rel['points'])
  148. dataItem.AddRelation(relation, direction = 'from')
  149. else:
  150. relation = ModelRelation(actionItem, dataItem)
  151. relation.SetControlPoints(rel['points'])
  152. dataItem.AddRelation(relation, direction = 'to')
  153. self.data.append(dataItem)
  154. actionItem.AddData(dataItem)
  155. def IsValid(self):
  156. """Return True if model is valid"""
  157. if self.Validate():
  158. return False
  159. return True
  160. def Validate(self):
  161. """!Validate model, return None if model is valid otherwise
  162. error string"""
  163. errList = list()
  164. for action in self.actions:
  165. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  166. show = None)
  167. errList += task.getCmdError()
  168. return errList
  169. def Run(self, log, onDone):
  170. """!Run model"""
  171. for action in self.actions:
  172. log.RunCmd(command = action.GetLog(string = False),
  173. onDone = onDone)
  174. def DeleteIntermediateData(self, log):
  175. """!Detele intermediate data"""
  176. rast, vect, rast3d, msg = self.GetIntermediateData()
  177. if rast:
  178. log.RunCmd(['g.remove', 'rast=%s' %','.join(rast)])
  179. if rast3d:
  180. log.RunCmd(['g.remove', 'rast3d=%s' %','.join(rast3d)])
  181. if vect:
  182. log.RunCmd(['g.remove', 'vect=%s' %','.join(vect)])
  183. def GetIntermediateData(self):
  184. """!Get info about intermediate data"""
  185. rast = list()
  186. rast3d = list()
  187. vect = list()
  188. for data in self.data:
  189. if not data.IsIntermediate():
  190. continue
  191. name = data.GetValue()
  192. prompt = data.GetPrompt()
  193. if prompt == 'raster':
  194. rast.append(name)
  195. elif prompt == 'vector':
  196. vect.append(name)
  197. elif prompt == 'rast3d':
  198. rast3d.append(name)
  199. msg = ''
  200. if rast:
  201. msg += '\n\n%s: ' % _('Raster maps')
  202. msg += ', '.join(rast)
  203. if rast3d:
  204. msg += '\n\n%s: ' % _('3D raster maps')
  205. msg += ', '.join(rast3d)
  206. if vect:
  207. msg += '\n\n%s: ' % _('Vector maps')
  208. msg += ', '.join(vect)
  209. return rast, vect, rast3d, msg
  210. def Update(self):
  211. """!Update model"""
  212. for action in self.actions:
  213. action.Update()
  214. for data in self.data:
  215. data.Update()
  216. def IsParameterized(self):
  217. """!Return True if model is parameterized"""
  218. if self.Parametrize():
  219. return True
  220. return False
  221. def Parametrize(self):
  222. """!Return parameterized options"""
  223. result = dict()
  224. idx = 0
  225. for action in self.actions:
  226. name = action.GetName()
  227. params = action.GetParams()
  228. for f in params['flags']:
  229. if f.get('parameterized', False):
  230. if not result.has_key(name):
  231. result[name] = { 'flags' : list(),
  232. 'params': list(),
  233. 'idx' : idx }
  234. result[name]['flags'].append(f)
  235. for p in params['params']:
  236. if p.get('parameterized', False):
  237. if not result.has_key(name):
  238. result[name] = { 'flags' : list(),
  239. 'params': list(),
  240. 'idx' : idx }
  241. result[name]['params'].append(p)
  242. idx += 1
  243. return result
  244. class ModelFrame(wx.Frame):
  245. def __init__(self, parent, id = wx.ID_ANY,
  246. title = _("GRASS GIS Graphical Modeler"), **kwargs):
  247. """!Graphical modeler main window
  248. @param parent parent window
  249. @param id window id
  250. @param title window title
  251. @param kwargs wx.Frames' arguments
  252. """
  253. self.parent = parent
  254. self.searchDialog = None # module search dialog
  255. self.baseTitle = title
  256. self.modelFile = None # loaded model
  257. self.modelChanged = False
  258. self.properties = None
  259. self.cursors = {
  260. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  261. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  262. }
  263. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  264. self.SetName("Modeler")
  265. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  266. self.menubar = menu.Menu(parent = self, data = menudata.ModelerData())
  267. self.SetMenuBar(self.menubar)
  268. self.toolbar = toolbars.ModelToolbar(parent = self)
  269. self.SetToolBar(self.toolbar)
  270. self.statusbar = self.CreateStatusBar(number = 1)
  271. self.notebook = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
  272. style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
  273. FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON)
  274. self.canvas = ModelCanvas(self)
  275. self.canvas.SetBackgroundColour(wx.WHITE)
  276. self.canvas.SetCursor(self.cursors["default"])
  277. self.model = Model(self.canvas)
  278. self.goutput = goutput.GMConsole(parent = self, pageid = 1,
  279. notebook = self.notebook)
  280. self.modelPage = self.notebook.AddPage(self.canvas, text=_('Model'))
  281. self.commandPage = self.notebook.AddPage(self.goutput, text=_('Command output'))
  282. wx.CallAfter(self.notebook.SetSelection, 0)
  283. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  284. self._layout()
  285. self.SetMinSize((350, 200))
  286. self.SetSize((640, 480))
  287. # fix goutput's pane size
  288. if self.goutput:
  289. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  290. def _layout(self):
  291. """!Do layout"""
  292. sizer = wx.BoxSizer(wx.VERTICAL)
  293. sizer.Add(item = self.notebook, proportion = 1,
  294. flag = wx.EXPAND)
  295. self.SetAutoLayout(True)
  296. self.SetSizer(sizer)
  297. sizer.Fit(self)
  298. self.Layout()
  299. def _addEvent(self, item):
  300. """!Add event to item"""
  301. evthandler = ModelEvtHandler(self.statusbar,
  302. self)
  303. evthandler.SetShape(item)
  304. evthandler.SetPreviousHandler(item.GetEventHandler())
  305. item.SetEventHandler(evthandler)
  306. def GetCanvas(self):
  307. """!Get canvas"""
  308. return self.canvas
  309. def GetModel(self):
  310. """!Get model"""
  311. return self.model
  312. def ModelChanged(self):
  313. """!Update window title"""
  314. if not self.modelChanged:
  315. self.modelChanged = True
  316. if self.modelFile:
  317. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile) + '*')
  318. def OnRemoveItem(self, event):
  319. """!Remove shape
  320. """
  321. self.GetCanvas().RemoveSelected()
  322. def OnCloseWindow(self, event):
  323. """!Close window"""
  324. self.Destroy()
  325. def OnPreferences(self, event):
  326. """!Open preferences dialog"""
  327. dlg = PreferencesDialog(parent = self)
  328. dlg.CenterOnParent()
  329. dlg.ShowModal()
  330. self.canvas.Refresh()
  331. def OnModelProperties(self, event):
  332. """!Model properties dialog"""
  333. dlg = PropertiesDialog(parent = self)
  334. dlg.CentreOnParent()
  335. if self.properties:
  336. dlg.Init(self.properties)
  337. else:
  338. dlg.Init({ 'name' : '',
  339. 'desc' : '',
  340. 'author' : getpass.getuser() })
  341. if dlg.ShowModal() == wx.ID_OK:
  342. self.properties = dlg.GetValues()
  343. dlg.Destroy()
  344. def OnDeleteData(self, event):
  345. """!Delete intermediate data"""
  346. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  347. if not rast and not vect and not rast3d:
  348. GMessage(parent = self,
  349. message = _('Nothing to delete.'),
  350. msgType = 'info')
  351. return
  352. dlg = wx.MessageDialog(parent = self,
  353. message= _("Do you want to permanently delete data?%s" % msg),
  354. caption=_("Delete intermediate data?"),
  355. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  356. ret = dlg.ShowModal()
  357. if ret == wx.ID_YES:
  358. dlg.Destroy()
  359. if rast:
  360. self.goutput.RunCmd(['g.remove', 'rast=%s' %','.join(rast)])
  361. if rast3d:
  362. self.goutput.RunCmd(['g.remove', 'rast3d=%s' %','.join(rast3d)])
  363. if vect:
  364. self.goutput.RunCmd(['g.remove', 'vect=%s' %','.join(vect)])
  365. self.SetStatusText(_("%d maps deleted from current mapset") % \
  366. int(len(rast) + len(rast3d) + len(vect)))
  367. return
  368. dlg.Destroy()
  369. def OnModelNew(self, event):
  370. """!Create new model"""
  371. Debug.msg(4, "ModelFrame.OnModelNew():")
  372. # ask user to save current model
  373. if self.modelFile and self.modelChanged:
  374. self.OnModelSave()
  375. elif self.modelFile is None and \
  376. (len(self.model.GetActions()) > 0 or len(self.model.GetData()) > 0):
  377. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  378. "Do you want to store current settings "
  379. "to model file?"),
  380. caption=_("Create new model?"),
  381. style=wx.YES_NO | wx.YES_DEFAULT |
  382. wx.CANCEL | wx.ICON_QUESTION)
  383. ret = dlg.ShowModal()
  384. if ret == wx.ID_YES:
  385. self.OnModelSaveAs()
  386. elif ret == wx.ID_CANCEL:
  387. dlg.Destroy()
  388. return
  389. dlg.Destroy()
  390. # delete all items
  391. self.canvas.GetDiagram().DeleteAllShapes()
  392. self.model.Reset()
  393. self.canvas.Refresh()
  394. # no model file loaded
  395. self.modelFile = None
  396. self.modelChanged = False
  397. self.SetTitle(self.baseTitle)
  398. def OnModelOpen(self, event):
  399. """!Load model from file"""
  400. filename = ''
  401. dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
  402. defaultDir = os.getcwd(),
  403. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  404. if dlg.ShowModal() == wx.ID_OK:
  405. filename = dlg.GetPath()
  406. if not filename:
  407. return
  408. Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
  409. # close current model
  410. self.OnModelClose()
  411. self.LoadModelFile(filename)
  412. self.modelFile = filename
  413. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  414. self.SetStatusText(_('%d actions loaded into model') % len(self.model.GetActions()), 0)
  415. def OnModelSave(self, event = None):
  416. """!Save model to file"""
  417. if self.modelFile and self.modelChanged:
  418. dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
  419. "Do you want to overwrite this file?") % \
  420. self.modelFile,
  421. caption=_("Save model"),
  422. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  423. if dlg.ShowModal() == wx.ID_NO:
  424. dlg.Destroy()
  425. else:
  426. Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
  427. self.WriteModelFile(self.modelFile)
  428. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  429. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  430. elif not self.modelFile:
  431. self.OnModelSaveAs(None)
  432. def OnModelSaveAs(self, event):
  433. """!Create model to file as"""
  434. filename = ''
  435. dlg = wx.FileDialog(parent = self,
  436. message = _("Choose file to save current model"),
  437. defaultDir = os.getcwd(),
  438. wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
  439. style=wx.FD_SAVE)
  440. if dlg.ShowModal() == wx.ID_OK:
  441. filename = dlg.GetPath()
  442. if not filename:
  443. return
  444. # check for extension
  445. if filename[-4:] != ".gxm":
  446. filename += ".gxm"
  447. if os.path.exists(filename):
  448. dlg = wx.MessageDialog(parent = self,
  449. message=_("Model file <%s> already exists. "
  450. "Do you want to overwrite this file?") % filename,
  451. caption=_("File already exists"),
  452. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  453. if dlg.ShowModal() != wx.ID_YES:
  454. dlg.Destroy()
  455. return
  456. Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
  457. self.WriteModelFile(filename)
  458. self.modelFile = filename
  459. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  460. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  461. def OnModelClose(self, event = None):
  462. """!Close model file"""
  463. Debug.msg(4, "ModelFrame.OnModelClose(): file=%s" % self.modelFile)
  464. # ask user to save current model
  465. if self.modelFile and self.modelChanged:
  466. self.OnModelSave()
  467. elif self.modelFile is None and \
  468. (len(self.model.GetActions()) > 0 or len(self.model.GetData()) > 0):
  469. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  470. "Do you want to store current settings "
  471. "to model file?"),
  472. caption=_("Create new model?"),
  473. style=wx.YES_NO | wx.YES_DEFAULT |
  474. wx.CANCEL | wx.ICON_QUESTION)
  475. ret = dlg.ShowModal()
  476. if ret == wx.ID_YES:
  477. self.OnModelSaveAs()
  478. elif ret == wx.ID_CANCEL:
  479. dlg.Destroy()
  480. return
  481. dlg.Destroy()
  482. self.modelFile = None
  483. self.SetTitle(self.baseTitle)
  484. self.canvas.GetDiagram().DeleteAllShapes()
  485. self.model.Reset()
  486. self.canvas.Refresh()
  487. def OnRunModel(self, event):
  488. """!Run entire model"""
  489. if len(self.model.GetActions()) < 1:
  490. GMessage(parent = self,
  491. message = _('Model is empty. Nothing to run.'),
  492. msgType = 'info')
  493. return
  494. # validation
  495. errList = self._validateModel()
  496. if errList:
  497. dlg = wx.MessageDialog(parent = self,
  498. message = _('Model is not valid. Do you want to '
  499. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  500. caption=_("Run model?"),
  501. style = wx.YES_NO | wx.NO_DEFAULT |
  502. wx.ICON_QUESTION | wx.CENTRE)
  503. ret = dlg.ShowModal()
  504. if ret != wx.ID_YES:
  505. return
  506. # parametrization
  507. params = self.model.Parametrize()
  508. if params:
  509. dlg = ModelParamDialog(parent = self,
  510. params = params)
  511. dlg.CenterOnParent()
  512. ret = dlg.ShowModal()
  513. if ret != wx.ID_OK:
  514. dlg.Destroy()
  515. return
  516. self.goutput.cmdThread.SetId(-1)
  517. for action in self.model.GetActions():
  518. name = action.GetName()
  519. if params.has_key(name):
  520. paramsOrig = action.GetParams(dcopy = True)
  521. action.MergeParams(params[name])
  522. self.SetStatusText(_('Running model...'), 0)
  523. self.goutput.RunCmd(command = action.GetLog(string = False),
  524. onDone = self.OnDone)
  525. if params.has_key(name):
  526. action.SetParams(paramsOrig)
  527. if params:
  528. dlg.Destroy()
  529. def OnDone(self, returncode):
  530. """!Computation finished"""
  531. self.SetStatusText('', 0)
  532. def OnValidateModel(self, event, showMsg = True):
  533. """!Validate entire model"""
  534. if len(self.model.GetActions()) < 1:
  535. GMessage(parent = self,
  536. message = _('Model is empty. Nothing to validate.'),
  537. msgType = 'info')
  538. return
  539. errList = self._validateModel()
  540. if errList:
  541. GMessage(parent = self,
  542. message = _('Model is not valid.\n\n%s') % '\n'.join(errList),
  543. msgType = 'warning')
  544. else:
  545. GMessage(parent = self,
  546. message = _('Model is valid.'),
  547. msgType = 'info')
  548. def OnExportImage(self, event):
  549. """!Export model to image (default image)
  550. """
  551. xminImg = 0
  552. xmaxImg = 0
  553. yminImg = 0
  554. ymaxImg = 0
  555. for shape in self.canvas.GetDiagram().GetShapeList():
  556. w, h = shape.GetBoundingBoxMax()
  557. x = shape.GetX()
  558. y = shape.GetY()
  559. xmin = x - w / 2
  560. xmax = x + w / 2
  561. ymin = y - h / 2
  562. ymax = y + h / 2
  563. if xmin < xminImg:
  564. xminImg = xmin
  565. if xmax > xmaxImg:
  566. xmaxImg = xmax
  567. if ymin < yminImg:
  568. xminImg = xmin
  569. if ymax < ymaxImg:
  570. xminImg = xmin
  571. size = wx.Size(int(xmaxImg - xminImg),
  572. int(ymaxImg - ymaxImg))
  573. bitmap = wx.EmptyBitmap(width = size.width, height = size.height)
  574. filetype, ltype = GetImageHandlers(wx.ImageFromBitmap(bitmap))
  575. dlg = wx.FileDialog(parent = self,
  576. message = _("Choose a file name to save the image (no need to add extension)"),
  577. defaultDir = "",
  578. defaultFile = "",
  579. wildcard = filetype,
  580. style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  581. if dlg.ShowModal() == wx.ID_OK:
  582. path = dlg.GetPath()
  583. if not path:
  584. dlg.Destroy()
  585. return
  586. base, ext = os.path.splitext(path)
  587. fileType = ltype[dlg.GetFilterIndex()]['type']
  588. extType = ltype[dlg.GetFilterIndex()]['ext']
  589. if ext != extType:
  590. path = base + '.' + extType
  591. dc = wx.MemoryDC(bitmap)
  592. dc.SetBackground(wx.WHITE_BRUSH)
  593. dc.SetBackgroundMode(wx.SOLID)
  594. dc.BeginDrawing()
  595. self.canvas.GetDiagram().Clear(dc)
  596. self.canvas.GetDiagram().Redraw(dc)
  597. dc.EndDrawing()
  598. bitmap.SaveFile(path, fileType)
  599. self.SetStatusText(_("Model exported to <%s>") % path)
  600. dlg.Destroy()
  601. def OnExportPython(self, event):
  602. """!Export model to Python script"""
  603. filename = ''
  604. dlg = wx.FileDialog(parent = self,
  605. message = _("Choose file to save"),
  606. defaultDir = os.getcwd(),
  607. wildcard=_("Python script (*.py)|*.py"),
  608. style=wx.FD_SAVE)
  609. if dlg.ShowModal() == wx.ID_OK:
  610. filename = dlg.GetPath()
  611. if not filename:
  612. return
  613. # check for extension
  614. if filename[-3:] != ".py":
  615. filename += ".py"
  616. if os.path.exists(filename):
  617. dlg = wx.MessageDialog(self, message=_("File <%s> already exists. "
  618. "Do you want to overwrite this file?") % filename,
  619. caption=_("Save file"),
  620. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  621. if dlg.ShowModal() == wx.ID_NO:
  622. dlg.Destroy()
  623. return
  624. dlg.Destroy()
  625. fd = open(filename, "w")
  626. try:
  627. self._writePython(fd)
  628. finally:
  629. fd.close()
  630. # executable file
  631. os.chmod(filename, stat.S_IRWXU | stat.S_IWUSR)
  632. self.SetStatusText(_("Model exported to <%s>") % filename)
  633. def _writePython(self, fd):
  634. """!Write model to file"""
  635. if self.properties:
  636. properties = self.properties
  637. else:
  638. properties = { 'name' : _("Graphical modeler script"),
  639. 'desc' : _("Script generated by wxGUI Graphical Modeler"),
  640. 'author' : getpass.getuser() }
  641. fd.write(
  642. r"""#!/usr/bin/env python
  643. #
  644. ############################################################################
  645. #
  646. # MODULE: %s
  647. #
  648. # AUTHOR(S): %s
  649. #
  650. # PURPOSE: %s
  651. #
  652. # DATE: %s
  653. #
  654. #############################################################################
  655. """ % (properties['name'],
  656. properties['author'],
  657. properties['desc'],
  658. time.asctime()))
  659. fd.write(
  660. r"""
  661. import sys
  662. import os
  663. import grass.script as grass
  664. import atexit
  665. """)
  666. # cleanup()
  667. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  668. fd.write(
  669. r"""
  670. def cleanup():
  671. """)
  672. if rast:
  673. fd.write(
  674. r""" grass.run_command('g.remove',
  675. rast=%s)
  676. """ % ','.join(map(lambda x: "'" + x + "'", rast)))
  677. if vect:
  678. fd.write(
  679. r""" grass.run_command('g.remove',
  680. vect = %s)
  681. """ % ','.join(map(lambda x: "'" + x + "'", vect)))
  682. if rast3d:
  683. fd.write(
  684. r""" grass.run_command('g.remove',
  685. rast3d = %s)
  686. """ % ','.join(map(lambda x: "'" + x + "'", rast3d)))
  687. if not rast and not vect and not rast3d:
  688. fd.write(' pass\n')
  689. fd.write("\ndef main():\n")
  690. for action in self.model.GetActions():
  691. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  692. show = None)
  693. opts = task.get_options()
  694. flags = ''
  695. params = list()
  696. strcmd = " grass.run_command("
  697. indent = len(strcmd)
  698. fd.write(strcmd + "'%s',\n" % task.get_name())
  699. for f in opts['flags']:
  700. if f.get('value', False) == True:
  701. name = f.get('name', '')
  702. if len(name) > 1:
  703. params.append('%s=True' % name)
  704. else:
  705. flags += name
  706. for p in opts['params']:
  707. name = p.get('name', None)
  708. value = p.get('value', None)
  709. if name and value:
  710. ptype = p.get('type', 'string')
  711. if ptype == 'string':
  712. params.append("%s='%s'" % (name, value))
  713. else:
  714. params.append("%s=%s" % (name, value))
  715. for opt in params[:-1]:
  716. fd.write("%s%s,\n" % (' ' * indent, opt))
  717. fd.write("%s%s)\n" % (' ' * indent, params[-1]))
  718. fd.write("\n return 0\n")
  719. fd.write(
  720. r"""
  721. if __name__ == "__main__":
  722. options, flags = grass.parser()
  723. atexit.register(cleanup)
  724. sys.exit(main())
  725. """)
  726. def _validateModel(self):
  727. """!Validate model"""
  728. self.SetStatusText(_('Validating model...'), 0)
  729. errList = self.model.Validate()
  730. self.SetStatusText('', 0)
  731. return errList
  732. def OnDefineRelation(self, event):
  733. """!Define relation between data and action items"""
  734. self.canvas.SetCursor(self.cursors["cross"])
  735. self.defineRelation = { 'from' : None,
  736. 'to' : None }
  737. def OnAddAction(self, event):
  738. """!Add action to model"""
  739. if self.searchDialog is None:
  740. self.searchDialog = ModelSearchDialog(self)
  741. self.searchDialog.CentreOnParent()
  742. else:
  743. self.searchDialog.Reset()
  744. if self.searchDialog.ShowModal() == wx.ID_CANCEL:
  745. self.searchDialog.Hide()
  746. return
  747. cmd = self.searchDialog.GetCmd()
  748. self.searchDialog.Hide()
  749. self.ModelChanged()
  750. # add action to canvas
  751. width, height = self.canvas.GetSize()
  752. action = ModelAction(self, cmd = cmd, x = width/2, y = height/2)
  753. self.canvas.diagram.AddShape(action)
  754. action.Show(True)
  755. self._addEvent(action)
  756. self.model.AddAction(action)
  757. self.canvas.Refresh()
  758. time.sleep(.1)
  759. # show properties dialog
  760. win = action.GetPropDialog()
  761. if not win and action.GetLog(string = False):
  762. module = menuform.GUI().ParseCommand(action.GetLog(string = False),
  763. completed = (self.GetOptData, action, action.GetParams()),
  764. parentframe = self, show = True)
  765. elif win and not win.IsShown():
  766. win.Show()
  767. if win:
  768. win.Raise()
  769. def OnAddData(self, event):
  770. """!Add data item to model"""
  771. # add action to canvas
  772. width, height = self.canvas.GetSize()
  773. data = ModelData(self, x = width/2, y = height/2)
  774. self.canvas.diagram.AddShape(data)
  775. data.Show(True)
  776. self._addEvent(data)
  777. self.model.AddData(data)
  778. self.canvas.Refresh()
  779. def OnHelp(self, event):
  780. """!Display manual page"""
  781. grass.run_command('g.manual',
  782. entry = 'wxGUI.Modeler')
  783. def OnAbout(self, event):
  784. """!Display About window"""
  785. info = wx.AboutDialogInfo()
  786. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  787. info.SetName(_('wxGUI Graphical Modeler'))
  788. info.SetWebSite('http://grass.osgeo.org')
  789. info.SetDescription(_('(C) 2010 by the GRASS Development Team\n\n') +
  790. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  791. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  792. wx.AboutBox(info)
  793. def GetOptData(self, dcmd, layer, params, propwin):
  794. """!Process action data"""
  795. if params: # add data items
  796. for p in params['params']:
  797. if p.get('prompt', '') in ('raster', 'vector', 'raster3d'):
  798. try:
  799. name, mapset = p.get('value', '').split('@', 1)
  800. except (ValueError, IndexError):
  801. continue
  802. if mapset != grass.gisenv()['MAPSET']:
  803. continue
  804. # don't use fully qualified names
  805. p['value'] = p.get('value', '').split('@')[0]
  806. for idx in range(1, len(dcmd)):
  807. if p.get('name', '') in dcmd[idx]:
  808. dcmd[idx] = p.get('name', '') + '=' + p.get('value', '')
  809. break
  810. width, height = self.canvas.GetSize()
  811. x = [width/2 + 200, width/2 - 200]
  812. for p in params['params']:
  813. if p.get('prompt', '') in ('raster', 'vector', 'raster3d') and \
  814. (p.get('value', None) or \
  815. p.get('age', 'old') != 'old'):
  816. data = layer.FindData(p.get('name', ''))
  817. if data:
  818. data.SetValue(p.get('value', ''))
  819. continue
  820. data = self.model.FindData(p.get('value', ''),
  821. p.get('prompt', ''))
  822. if data:
  823. if p.get('age', 'old') == 'old':
  824. rel = ModelRelation(data, layer)
  825. data.AddRelation(rel, direction = 'from')
  826. self.AddLine(rel)
  827. else:
  828. rel = ModelRelation(layer, data)
  829. data.AddRelation(rel, direction = 'to')
  830. self.AddLine(rel)
  831. continue
  832. data = ModelData(self, name = p.get('name', ''),
  833. value = p.get('value', ''),
  834. prompt = p.get('prompt', ''),
  835. x = x.pop(), y = height/2)
  836. layer.AddData(data)
  837. self.canvas.diagram.AddShape(data)
  838. data.Show(True)
  839. self._addEvent(data)
  840. self.model.AddData(data)
  841. if p.get('age', 'old') == 'old':
  842. rel = ModelRelation(data, layer)
  843. data.AddRelation(rel, direction = 'from')
  844. self.AddLine(rel)
  845. else:
  846. rel = ModelRelation(layer, data)
  847. data.AddRelation(rel, direction = 'to')
  848. self.AddLine(rel)
  849. # valid ?
  850. valid = True
  851. for p in params['params']:
  852. if p.get('value', '') == '' and \
  853. p.get('default', '') == '':
  854. valid = False
  855. break
  856. layer.SetValid(valid)
  857. self.canvas.Refresh()
  858. if dcmd:
  859. layer.SetProperties(params, propwin)
  860. self.SetStatusText(layer.GetLog(), 0)
  861. def AddLine(self, rel):
  862. """!Add connection
  863. @param rel relation
  864. """
  865. fromShape = rel.GetFrom()
  866. toShape = rel.GetTo()
  867. rel.SetCanvas(self)
  868. rel.SetPen(wx.BLACK_PEN)
  869. rel.SetBrush(wx.BLACK_BRUSH)
  870. rel.AddArrow(ogl.ARROW_ARROW)
  871. points = rel.GetControlPoints()
  872. rel.MakeLineControlPoints(2)
  873. if points:
  874. for x, y in points:
  875. rel.InsertLineControlPoint(point = wx.RealPoint(x, y))
  876. self._addEvent(rel)
  877. fromShape.AddLine(rel, toShape)
  878. self.canvas.diagram.AddShape(rel)
  879. rel.Show(True)
  880. def LoadModelFile(self, filename):
  881. """!Load model definition stored in GRASS Model XML file (gxm)
  882. """
  883. try:
  884. self.model.LoadModel(filename)
  885. except GError, e:
  886. GMessage(parent = self,
  887. message = _("Reading model file <%s> failed.\n"
  888. "Invalid file, unable to parse XML document.") % filename)
  889. self.modelFile = filename
  890. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  891. self.SetStatusText(_("Please wait, loading model..."), 0)
  892. # load actions
  893. for action in self.model.GetActions():
  894. self._addEvent(action)
  895. self.canvas.diagram.AddShape(action)
  896. action.Show(True)
  897. # load data & relations
  898. for data in self.model.GetData():
  899. self._addEvent(data)
  900. self.canvas.diagram.AddShape(data)
  901. data.Show(True)
  902. for rel in data.GetRelations():
  903. self.AddLine(rel)
  904. self.SetStatusText('', 0)
  905. self.canvas.Refresh(True)
  906. def WriteModelFile(self, filename):
  907. """!Save model to model file, recover original file on error.
  908. @return True on success
  909. @return False on failure
  910. """
  911. tmpfile = tempfile.TemporaryFile(mode='w+b')
  912. try:
  913. WriteModelFile(fd = tmpfile,
  914. actions = self.model.GetActions(),
  915. data = self.model.GetData())
  916. except StandardError:
  917. GMessage(parent = self,
  918. message = _("Writing current settings to model file failed."))
  919. return False
  920. try:
  921. mfile = open(filename, "w")
  922. tmpfile.seek(0)
  923. for line in tmpfile.readlines():
  924. mfile.write(line)
  925. except IOError:
  926. wx.MessageBox(parent = self,
  927. message = _("Unable to open file <%s> for writing.") % filename,
  928. caption = _("Error"),
  929. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  930. return False
  931. mfile.close()
  932. return True
  933. class ModelCanvas(ogl.ShapeCanvas):
  934. """!Canvas where model is drawn"""
  935. def __init__(self, parent):
  936. self.parent = parent
  937. ogl.OGLInitialize()
  938. ogl.ShapeCanvas.__init__(self, parent)
  939. self.diagram = ogl.Diagram()
  940. self.SetDiagram(self.diagram)
  941. self.diagram.SetCanvas(self)
  942. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  943. self.Bind(wx.EVT_CHAR, self.OnChar)
  944. def OnChar(self, event):
  945. """!Key pressed"""
  946. kc = event.GetKeyCode()
  947. diagram = self.GetDiagram()
  948. if kc == wx.WXK_DELETE:
  949. self.RemoveSelected()
  950. def RemoveSelected(self):
  951. """!Remove selected shapes"""
  952. self.parent.ModelChanged()
  953. diagram = self.GetDiagram()
  954. for shape in diagram.GetShapeList():
  955. if not shape.Selected():
  956. continue
  957. self.parent.GetModel().RemoveItem(shape)
  958. shape.Select(False)
  959. diagram.RemoveShape(shape)
  960. self.Refresh()
  961. class ModelAction(ogl.RectangleShape):
  962. """!Action class (GRASS module)"""
  963. def __init__(self, parent, x, y, cmd = None, task = None, width = None, height = None):
  964. self.parent = parent
  965. self.task = task
  966. if not width:
  967. width = UserSettings.Get(group='modeler', key='action', subkey=('size', 'width'))
  968. if not height:
  969. height = UserSettings.Get(group='modeler', key='action', subkey=('size', 'height'))
  970. if cmd:
  971. self.task = menuform.GUI().ParseCommand(cmd = cmd,
  972. show = None)
  973. else:
  974. if task:
  975. self.task = task
  976. else:
  977. self.task = None
  978. self.propWin = None
  979. self.id = -1 # used for gxm file
  980. self.data = list() # list of connected data items
  981. self.isValid = False
  982. if self.parent.GetCanvas():
  983. ogl.RectangleShape.__init__(self, width, height)
  984. self.SetCanvas(self.parent)
  985. self.SetX(x)
  986. self.SetY(y)
  987. self.SetPen(wx.BLACK_PEN)
  988. self._setBrush(False)
  989. cmd = self.task.getCmd(ignoreErrors = True)
  990. if cmd and len(cmd) > 0:
  991. self.AddText(cmd[0])
  992. else:
  993. self.AddText('<<%s>>' % _("module"))
  994. def _setBrush(self, isvalid):
  995. """!Set brush"""
  996. if isvalid is None:
  997. color = UserSettings.Get(group='modeler', key='action',
  998. subkey=('color', 'running'))
  999. elif isvalid:
  1000. color = UserSettings.Get(group='modeler', key='action',
  1001. subkey=('color', 'valid'))
  1002. else:
  1003. color = UserSettings.Get(group='modeler', key='action',
  1004. subkey=('color', 'invalid'))
  1005. wxColor = wx.Color(color[0], color[1], color[2])
  1006. self.SetBrush(wx.Brush(wxColor))
  1007. def GetId(self):
  1008. """!Get id"""
  1009. return self.id
  1010. def SetId(self, id):
  1011. """!Set id"""
  1012. self.id = id
  1013. def SetProperties(self, params, propwin):
  1014. """!Record properties dialog"""
  1015. self.task.params = params['params']
  1016. self.task.flags = params['flags']
  1017. self.propWin = propwin
  1018. def GetPropDialog(self):
  1019. """!Get properties dialog"""
  1020. return self.propWin
  1021. def GetLog(self, string = True):
  1022. """!Get logging info"""
  1023. cmd = self.task.getCmd(ignoreErrors = True)
  1024. if string:
  1025. if cmd is None:
  1026. return ''
  1027. else:
  1028. return ' '.join(cmd)
  1029. return cmd
  1030. def GetName(self):
  1031. """!Get name"""
  1032. cmd = self.task.getCmd(ignoreErrors = True)
  1033. if cmd and len(cmd) > 0:
  1034. return cmd[0]
  1035. return _('unknown')
  1036. def GetParams(self, dcopy = False):
  1037. """!Get dictionary of parameters"""
  1038. if dcopy:
  1039. return copy.deepcopy(self.task.get_options())
  1040. return self.task.get_options()
  1041. def SetParams(self, params):
  1042. """!Set dictionary of parameters"""
  1043. self.task.params = params['params']
  1044. self.task.flags = params['flags']
  1045. def MergeParams(self, params):
  1046. """!Merge dictionary of parameters"""
  1047. for f in params['flags']:
  1048. self.task.set_flag(f['name'],
  1049. f.get('value', False))
  1050. for p in params['params']:
  1051. self.task.set_param(p['name'],
  1052. p.get('value', ''))
  1053. def SetValid(self, isvalid):
  1054. """!Set instance to be valid/invalid"""
  1055. self.isValid = isvalid
  1056. self._setBrush(isvalid)
  1057. def AddData(self, item):
  1058. """!Register new data item"""
  1059. if item not in self.data:
  1060. self.data.append(item)
  1061. def FindData(self, name):
  1062. """!Find data item by name"""
  1063. for d in self.data:
  1064. if d.GetName() == name:
  1065. return d
  1066. return None
  1067. def Update(self, running = False):
  1068. """!Update action"""
  1069. if running:
  1070. self._setBrush(None)
  1071. else:
  1072. self._setBrush(self.isValid)
  1073. class ModelData(ogl.EllipseShape):
  1074. """!Data item class"""
  1075. def __init__(self, parent, x, y, name = '', value = '', prompt = '', width = None, height = None):
  1076. self.parent = parent
  1077. self.name = name
  1078. self.value = value
  1079. self.prompt = prompt
  1080. self.intermediate = False
  1081. self.propWin = None
  1082. if not width:
  1083. width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
  1084. if not height:
  1085. height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
  1086. self.rels = { 'from' : list(), 'to' : list() } # list of recorded relations
  1087. if self.parent.GetCanvas():
  1088. ogl.EllipseShape.__init__(self, width, height)
  1089. self.SetCanvas(self.parent)
  1090. self.SetX(x)
  1091. self.SetY(y)
  1092. self.SetPen(wx.BLACK_PEN)
  1093. self._setBrush()
  1094. if name:
  1095. self.AddText(name)
  1096. else:
  1097. self.AddText(_('unknown'))
  1098. if value:
  1099. self.AddText(value)
  1100. else:
  1101. self.AddText('\n')
  1102. def IsIntermediate(self):
  1103. """!Checks if data item is intermediate"""
  1104. return self.intermediate
  1105. def SetIntermediate(self, im):
  1106. """!Set intermediate flag"""
  1107. self.intermediate = im
  1108. def OnDraw(self, dc):
  1109. pen = self.GetPen()
  1110. if self.intermediate:
  1111. pen.SetStyle(wx.SHORT_DASH)
  1112. else:
  1113. pen.SetStyle(wx.SOLID)
  1114. self.SetPen(pen)
  1115. ogl.EllipseShape.OnDraw(self, dc)
  1116. def GetLog(self, string = True):
  1117. """!Get logging info"""
  1118. if self.name:
  1119. return self.name + '=' + self.value + ' (' + self.prompt + ')'
  1120. else:
  1121. return _('unknown')
  1122. def GetName(self):
  1123. """!Get name"""
  1124. return self.name
  1125. def GetPrompt(self):
  1126. """!Get prompt"""
  1127. return self.prompt
  1128. def GetValue(self):
  1129. """!Get value"""
  1130. return self.value
  1131. def SetValue(self, value):
  1132. """!Set value"""
  1133. self.value = value
  1134. self.ClearText()
  1135. self.AddText(self.name)
  1136. if value:
  1137. self.AddText(self.value)
  1138. else:
  1139. self.AddText('\n')
  1140. for direction in ('from', 'to'):
  1141. for rel in self.rels[direction]:
  1142. if direction == 'from':
  1143. action = rel.GetTo()
  1144. else:
  1145. action = rel.GetFrom()
  1146. task = menuform.GUI().ParseCommand(cmd = action.GetLog(string = False),
  1147. show = None)
  1148. task.set_param(self.name, self.value)
  1149. action.SetParams(params = task.get_options())
  1150. def GetRelations(self, direction = None):
  1151. """!Get relations from/to"""
  1152. if not direction:
  1153. return self.rels['from'] + self.rels['to']
  1154. return self.rels[direction]
  1155. def AddRelation(self, rel, direction):
  1156. """!Record new relation
  1157. @param direction direction - 'from' or 'to'
  1158. """
  1159. self.rels[direction].append(rel)
  1160. def GetPropDialog(self):
  1161. """!Get properties dialog"""
  1162. return self.propWin
  1163. def SetPropDialog(self, win):
  1164. """!Get properties dialog"""
  1165. self.propWin = win
  1166. def _setBrush(self):
  1167. """!Set brush"""
  1168. if self.prompt == 'raster':
  1169. color = UserSettings.Get(group='modeler', key='data',
  1170. subkey=('color', 'raster'))
  1171. elif self.prompt == 'raster3d':
  1172. color = UserSettings.Get(group='modeler', key='data',
  1173. subkey=('color', 'raster3d'))
  1174. elif self.prompt == 'vector':
  1175. color = UserSettings.Get(group='modeler', key='data',
  1176. subkey=('color', 'vector'))
  1177. else:
  1178. color = UserSettings.Get(group='modeler', key='action',
  1179. subkey=('color', 'invalid'))
  1180. wxColor = wx.Color(color[0], color[1], color[2])
  1181. self.SetBrush(wx.Brush(wxColor))
  1182. def Update(self):
  1183. """!Update action"""
  1184. self._setBrush()
  1185. class ModelDataDialog(ElementDialog):
  1186. """!Data item properties dialog"""
  1187. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Data properties"),
  1188. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1189. self.parent = parent
  1190. self.shape = shape
  1191. prompt = shape.GetPrompt()
  1192. if prompt == 'raster':
  1193. label = _('Name of raster map:')
  1194. elif prompt == 'vector':
  1195. label = _('Name of vector map:')
  1196. else:
  1197. label = _('Name of element:')
  1198. ElementDialog.__init__(self, parent, title, label = label)
  1199. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY,
  1200. size = globalvar.DIALOG_GSELECT_SIZE,
  1201. type = prompt)
  1202. self.element.SetValue(shape.GetValue())
  1203. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  1204. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1205. self.PostInit()
  1206. self._layout()
  1207. self.SetMinSize(self.GetSize())
  1208. def _layout(self):
  1209. """!Do layout"""
  1210. self.dataSizer.Add(self.element, proportion=0,
  1211. flag=wx.EXPAND | wx.ALL, border=1)
  1212. self.panel.SetSizer(self.sizer)
  1213. self.sizer.Fit(self)
  1214. def OnOK(self, event):
  1215. """!Ok pressed"""
  1216. self.shape.SetValue(self.GetElement())
  1217. self.parent.canvas.Refresh()
  1218. self.parent.SetStatusText('', 0)
  1219. self.OnCancel(event)
  1220. def OnCancel(self, event):
  1221. """!Cancel pressed"""
  1222. self.shape.SetPropDialog(None)
  1223. self.Destroy()
  1224. class ModelEvtHandler(ogl.ShapeEvtHandler):
  1225. """!Model event handler class"""
  1226. def __init__(self, log, frame):
  1227. ogl.ShapeEvtHandler.__init__(self)
  1228. self.log = log
  1229. self.frame = frame
  1230. self.x = self.y = None
  1231. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  1232. """!Left mouse button pressed -> select item & update statusbar"""
  1233. shape = self.GetShape()
  1234. canvas = shape.GetCanvas()
  1235. dc = wx.ClientDC(canvas)
  1236. canvas.PrepareDC(dc)
  1237. if hasattr(self.frame, 'defineRelation'):
  1238. drel = self.frame.defineRelation
  1239. if drel['from'] is None:
  1240. drel['from'] = shape
  1241. elif drel['to'] is None:
  1242. drel['to'] = shape
  1243. rel = ModelRelation(drel['from'], drel['to'])
  1244. self.frame.AddLine(rel)
  1245. del self.frame.defineRelation
  1246. if shape.Selected():
  1247. shape.Select(False, dc)
  1248. else:
  1249. redraw = False
  1250. shapeList = canvas.GetDiagram().GetShapeList()
  1251. toUnselect = list()
  1252. for s in shapeList:
  1253. if s.Selected():
  1254. toUnselect.append(s)
  1255. shape.Select(True, dc)
  1256. for s in toUnselect:
  1257. s.Select(False, dc)
  1258. canvas.Refresh(False)
  1259. if hasattr(shape, "GetLog"):
  1260. self.log.SetStatusText(shape.GetLog(), 0)
  1261. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  1262. """!Left mouse button pressed (double-click) -> show properties"""
  1263. self.OnProperties()
  1264. def OnProperties(self, event = None):
  1265. """!Show properties dialog"""
  1266. self.frame.ModelChanged()
  1267. shape = self.GetShape()
  1268. if isinstance(shape, ModelAction):
  1269. module = menuform.GUI().ParseCommand(shape.GetLog(string = False),
  1270. completed = (self.frame.GetOptData, shape, shape.GetParams()),
  1271. parentframe = self.frame, show = True)
  1272. elif isinstance(shape, ModelData):
  1273. dlg = ModelDataDialog(parent = self.frame, shape = shape)
  1274. shape.SetPropDialog(dlg)
  1275. dlg.CentreOnParent()
  1276. dlg.Show()
  1277. def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
  1278. """!Drag shape"""
  1279. self.frame.ModelChanged()
  1280. if self._previousHandler:
  1281. self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
  1282. def OnRightClick(self, x, y, keys = 0, attachment = 0):
  1283. """!Right click -> pop-up menu"""
  1284. if not hasattr (self, "popupID1"):
  1285. self.popupID1 = wx.NewId()
  1286. self.popupID2 = wx.NewId()
  1287. self.popupID3 = wx.NewId()
  1288. # record coordinates
  1289. self.x = x
  1290. self.y = y
  1291. shape = self.GetShape()
  1292. popupMenu = wx.Menu()
  1293. popupMenu.Append(self.popupID1, text=_('Remove'))
  1294. self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  1295. if isinstance(shape, ModelRelation):
  1296. popupMenu.AppendSeparator()
  1297. popupMenu.Append(self.popupID2, text=_('Add control point'))
  1298. self.frame.Bind(wx.EVT_MENU, self.OnAddPoint, id = self.popupID2)
  1299. popupMenu.Append(self.popupID3, text=_('Remove control point'))
  1300. self.frame.Bind(wx.EVT_MENU, self.OnRemovePoint, id = self.popupID3)
  1301. if len(shape.GetLineControlPoints()) == 2:
  1302. popupMenu.Enable(self.popupID3, False)
  1303. if isinstance(shape, ModelData) and '@' not in shape.GetValue():
  1304. popupMenu.AppendSeparator()
  1305. popupMenu.Append(self.popupID3, text=_('Intermediate'),
  1306. kind = wx.ITEM_CHECK)
  1307. if self.GetShape().IsIntermediate():
  1308. popupMenu.Check(self.popupID3, True)
  1309. self.frame.Bind(wx.EVT_MENU, self.OnIntermediate, id = self.popupID3)
  1310. if isinstance(shape, ModelData) or \
  1311. isinstance(shape, ModelAction):
  1312. popupMenu.AppendSeparator()
  1313. popupMenu.Append(self.popupID2, text=_('Properties'))
  1314. self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID2)
  1315. self.frame.PopupMenu(popupMenu)
  1316. popupMenu.Destroy()
  1317. def OnAddPoint(self, event):
  1318. """!Add control point"""
  1319. shape = self.GetShape()
  1320. shape.InsertLineControlPoint(point = wx.RealPoint(self.x, self.y))
  1321. shape.ResetShapes()
  1322. shape.Select(True)
  1323. self.frame.canvas.Refresh()
  1324. def OnRemovePoint(self, event):
  1325. """!Remove control point"""
  1326. shape = self.GetShape()
  1327. shape.DeleteLineControlPoint()
  1328. shape.Select(False)
  1329. shape.Select(True)
  1330. self.frame.canvas.Refresh()
  1331. def OnIntermediate(self, event):
  1332. """!Mark data as intermediate"""
  1333. self.frame.ModelChanged()
  1334. shape = self.GetShape()
  1335. shape.SetIntermediate(event.IsChecked())
  1336. self.frame.canvas.Refresh()
  1337. def OnRemove(self, event):
  1338. """!Remove shape
  1339. """
  1340. self.frame.GetCanvas().RemoveSelected()
  1341. class ModelSearchDialog(wx.Dialog):
  1342. def __init__(self, parent, id = wx.ID_ANY, title = _("Select GRASS module"),
  1343. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  1344. """!Graphical modeler module search window
  1345. @param parent parent window
  1346. @param id window id
  1347. @param title window title
  1348. @param kwargs wx.Dialogs' arguments
  1349. """
  1350. self.parent = parent
  1351. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  1352. self.SetName("ModelerDialog")
  1353. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  1354. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1355. self.cmdBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1356. label=" %s " % _("Command"))
  1357. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  1358. self.search = SearchModuleWindow(parent = self.panel, cmdPrompt = self.cmd_prompt, showTip = True)
  1359. # get commands
  1360. items = self.cmd_prompt.GetCommandItems()
  1361. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  1362. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  1363. self.btnOk.SetDefault()
  1364. self.btnOk.Enable(False)
  1365. self.cmd_prompt.Bind(wx.EVT_KEY_UP, self.OnText)
  1366. self.Bind(wx.EVT_BUTTON, self.OnOk, self.btnOk)
  1367. self._layout()
  1368. self.SetSize((500, 275))
  1369. def _layout(self):
  1370. btnSizer = wx.StdDialogButtonSizer()
  1371. btnSizer.AddButton(self.btnCancel)
  1372. btnSizer.AddButton(self.btnOk)
  1373. btnSizer.Realize()
  1374. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1375. mainSizer.Add(item=self.search, proportion=0,
  1376. flag=wx.EXPAND | wx.ALL, border=3)
  1377. mainSizer.Add(item=self.cmd_prompt, proportion=1,
  1378. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  1379. mainSizer.Add(item=btnSizer, proportion=0,
  1380. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  1381. self.panel.SetSizer(mainSizer)
  1382. mainSizer.Fit(self.panel)
  1383. self.Layout()
  1384. def GetPanel(self):
  1385. """!Get dialog panel"""
  1386. return self.panel
  1387. def GetCmd(self):
  1388. """!Get command"""
  1389. line = self.cmd_prompt.GetCurLine()[0].strip()
  1390. if len(line) == 0:
  1391. list()
  1392. try:
  1393. cmd = shlex.split(str(line))
  1394. except UnicodeError:
  1395. cmd = shlex.split(utils.EncodeString((line)))
  1396. return cmd
  1397. def OnOk(self, event):
  1398. self.btnOk.SetFocus()
  1399. cmd = self.GetCmd()
  1400. if len(cmd) < 1:
  1401. GMessage(parent = self,
  1402. message = _("Command not defined.\n\n"
  1403. "Unable to add new action to the model."))
  1404. return
  1405. if cmd[0] not in globalvar.grassCmd['all']:
  1406. GMessage(parent = self,
  1407. message = _("'%s' is not a GRASS module.\n\n"
  1408. "Unable to add new action to the model.") % cmd[0])
  1409. return
  1410. self.EndModal(wx.ID_OK)
  1411. def OnText(self, event):
  1412. if self.cmd_prompt.AutoCompActive():
  1413. return
  1414. entry = self.cmd_prompt.GetTextLeft()
  1415. if len(entry) > 0:
  1416. self.btnOk.Enable()
  1417. else:
  1418. self.btnOk.Enable(False)
  1419. event.Skip()
  1420. def Reset(self):
  1421. """!Reset dialog"""
  1422. self.search.Reset()
  1423. self.cmd_prompt.OnCmdErase(None)
  1424. class ModelRelation(ogl.LineShape):
  1425. """!Data - action relation"""
  1426. def __init__(self, fromShape, toShape):
  1427. self.fromShape = fromShape
  1428. self.toShape = toShape
  1429. self._points = None
  1430. ogl.LineShape.__init__(self)
  1431. def GetFrom(self):
  1432. """!Get id of 'from' shape"""
  1433. return self.fromShape
  1434. def GetTo(self):
  1435. """!Get id of 'to' shape"""
  1436. return self.toShape
  1437. def ResetShapes(self):
  1438. """!Reset related objects"""
  1439. self.fromShape.ResetControlPoints()
  1440. self.toShape.ResetControlPoints()
  1441. self.ResetControlPoints()
  1442. def SetControlPoints(self, points):
  1443. """!Set control points"""
  1444. self._points = points
  1445. def GetControlPoints(self):
  1446. """!Get list of control points"""
  1447. return self._points
  1448. class ProcessModelFile:
  1449. """!Process GRASS model file (gxm)"""
  1450. def __init__(self, tree):
  1451. """!A ElementTree handler for the GXM XML file, as defined in
  1452. grass-gxm.dtd.
  1453. """
  1454. self.tree = tree
  1455. self.root = self.tree.getroot()
  1456. # list of actions, data
  1457. self.actions = list()
  1458. self.data = list()
  1459. self._processActions()
  1460. self._processData()
  1461. def _filterValue(self, value):
  1462. """!Filter value
  1463. @param value
  1464. """
  1465. value = value.replace('&lt;', '<')
  1466. value = value.replace('&gt;', '>')
  1467. return value
  1468. def _getNodeText(self, node, tag, default = ''):
  1469. """!Get node text"""
  1470. p = node.find(tag)
  1471. if p is not None:
  1472. if p.text:
  1473. return utils.normalize_whitespace(p.text)
  1474. else:
  1475. return ''
  1476. return default
  1477. def _processActions(self):
  1478. """!Process model file"""
  1479. for action in self.root.findall('action'):
  1480. pos, size = self._getDim(action)
  1481. task = action.find('task')
  1482. if task:
  1483. task = self._processTask(task)
  1484. else:
  1485. task = None
  1486. aId = int(action.get('id', -1))
  1487. self.actions.append({ 'pos' : pos,
  1488. 'size' : size,
  1489. 'task' : task,
  1490. 'id' : aId })
  1491. def _getDim(self, node):
  1492. """!Get position and size of shape"""
  1493. pos = size = None
  1494. posAttr = node.get('pos', None)
  1495. if posAttr:
  1496. posVal = map(int, posAttr.split(','))
  1497. try:
  1498. pos = (posVal[0], posVal[1])
  1499. except:
  1500. pos = None
  1501. sizeAttr = node.get('size', None)
  1502. if sizeAttr:
  1503. sizeVal = map(int, sizeAttr.split(','))
  1504. try:
  1505. size = (sizeVal[0], sizeVal[1])
  1506. except:
  1507. size = None
  1508. return pos, size
  1509. def _processData(self):
  1510. """!Process model file"""
  1511. for data in self.root.findall('data'):
  1512. pos, size = self._getDim(data)
  1513. param = data.find('data-parameter')
  1514. name = prompt = value = None
  1515. if param is not None:
  1516. name = param.get('name', None)
  1517. prompt = param.get('prompt', None)
  1518. value = self._filterValue(self._getNodeText(param, 'value'))
  1519. if data.find('intermediate') is None:
  1520. intermediate = False
  1521. else:
  1522. intermediate = True
  1523. rels = list()
  1524. for rel in data.findall('relation'):
  1525. defrel = { 'id' : int(rel.get('id', -1)),
  1526. 'dir' : rel.get('dir', 'to') }
  1527. points = list()
  1528. for point in rel.findall('point'):
  1529. x = self._filterValue(self._getNodeText(point, 'x'))
  1530. y = self._filterValue(self._getNodeText(point, 'y'))
  1531. points.append((float(x), float(y)))
  1532. defrel['points'] = points
  1533. rels.append(defrel)
  1534. self.data.append({ 'pos' : pos,
  1535. 'size': size,
  1536. 'name' : name,
  1537. 'prompt' : prompt,
  1538. 'value' : value,
  1539. 'intermediate' : intermediate,
  1540. 'rels' : rels })
  1541. def _processTask(self, node):
  1542. """!Process task
  1543. @return grassTask instance
  1544. @return None on error
  1545. """
  1546. cmd = list()
  1547. parameterized = list()
  1548. name = node.get('name', None)
  1549. if not name:
  1550. return None
  1551. cmd.append(name)
  1552. # flags
  1553. for f in node.findall('flag'):
  1554. flag = f.get('name', '')
  1555. if f.get('parameterized', '0') == '1':
  1556. parameterized.append(('flag', flag))
  1557. if f.get('value', '1') == '0':
  1558. continue
  1559. if len(flag) > 1:
  1560. cmd.append('--' + flag)
  1561. else:
  1562. cmd.append('-' + flag)
  1563. # parameters
  1564. for p in node.findall('parameter'):
  1565. name = p.get('name', '')
  1566. if p.find('parameterized') is not None:
  1567. parameterized.append(('param', name))
  1568. cmd.append('%s=%s' % (name,
  1569. self._filterValue(self._getNodeText(p, 'value'))))
  1570. task = menuform.GUI().ParseCommand(cmd = cmd,
  1571. show = None)
  1572. for opt, name in parameterized:
  1573. if opt == 'flag':
  1574. task.set_flag(name, True, element = 'parameterized')
  1575. else:
  1576. task.set_param(name, True, element = 'parameterized')
  1577. return task
  1578. class WriteModelFile:
  1579. """!Generic class for writing model file"""
  1580. def __init__(self, fd, actions, data):
  1581. self.fd = fd
  1582. self.actions = actions
  1583. self.data = data
  1584. self.indent = 0
  1585. self._header()
  1586. self._actions()
  1587. self._data()
  1588. self._footer()
  1589. def _filterValue(self, value):
  1590. """!Make value XML-valid"""
  1591. value = value.replace('<', '&lt;')
  1592. value = value.replace('>', '&gt;')
  1593. return value
  1594. def _header(self):
  1595. """!Write header"""
  1596. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  1597. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1598. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1599. def _footer(self):
  1600. """!Write footer"""
  1601. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1602. def _actions(self):
  1603. """!Write actions"""
  1604. id = 1
  1605. self.indent += 4
  1606. for action in self.actions:
  1607. action.SetId(id)
  1608. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1609. (' ' * self.indent, id, action.GetName(), action.GetX(), action.GetY(),
  1610. action.GetWidth(), action.GetHeight()))
  1611. self.indent += 4
  1612. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1613. self.indent += 4
  1614. for key, val in action.GetParams().iteritems():
  1615. if key == 'flags':
  1616. for f in val:
  1617. if f.get('value', False) or f.get('parameterized', False):
  1618. if f.get('parameterized', False):
  1619. if f.get('value', False) == False:
  1620. self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
  1621. (' ' * self.indent, f.get('name', '')))
  1622. else:
  1623. self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
  1624. (' ' * self.indent, f.get('name', '')))
  1625. else:
  1626. self.fd.write('%s<flag name="%s" />\n' %
  1627. (' ' * self.indent, f.get('name', '')))
  1628. else: # parameter
  1629. for p in val:
  1630. if not p.get('value', ''):
  1631. continue
  1632. self.fd.write('%s<parameter name="%s">\n' %
  1633. (' ' * self.indent, p.get('name', '')))
  1634. self.indent += 4
  1635. if p.get('parameterized', False):
  1636. self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
  1637. self.fd.write('%s<value>%s</value>\n' %
  1638. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1639. self.indent -= 4
  1640. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1641. self.indent -= 4
  1642. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1643. self.indent -= 4
  1644. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1645. id += 1
  1646. self.indent -= 4
  1647. def _data(self):
  1648. """!Write data"""
  1649. self.indent += 4
  1650. for data in self.data:
  1651. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1652. (' ' * self.indent, data.GetX(), data.GetY(),
  1653. data.GetWidth(), data.GetHeight()))
  1654. self.indent += 4
  1655. self.fd.write('%s<data-parameter name="%s" prompt="%s">\n' % \
  1656. (' ' * self.indent, data.GetName(), data.GetPrompt()))
  1657. self.indent += 4
  1658. self.fd.write('%s<value>%s</value>\n' %
  1659. (' ' * self.indent, self._filterValue(data.GetValue())))
  1660. self.indent -= 4
  1661. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1662. if data.IsIntermediate():
  1663. self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
  1664. # relations
  1665. for ft in ('from', 'to'):
  1666. for rel in data.GetRelations(direction = ft):
  1667. if ft == 'from':
  1668. aid = rel.GetTo().GetId()
  1669. else:
  1670. aid = rel.GetFrom().GetId()
  1671. self.fd.write('%s<relation dir="%s" id="%d">\n' % \
  1672. (' ' * self.indent, ft, aid))
  1673. self.indent += 4
  1674. for point in rel.GetLineControlPoints()[1:-1]:
  1675. self.fd.write('%s<point>\n' % (' ' * self.indent))
  1676. self.indent += 4
  1677. x, y = point.Get()
  1678. self.fd.write('%s<x>%f</x>\n' % (' ' * self.indent, x))
  1679. self.fd.write('%s<y>%f</y>\n' % (' ' * self.indent, y))
  1680. self.indent -= 4
  1681. self.fd.write('%s</point>\n' % (' ' * self.indent))
  1682. self.indent -= 4
  1683. self.fd.write('%s</relation>\n' % (' ' * self.indent))
  1684. self.indent -= 4
  1685. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1686. class PreferencesDialog(PreferencesBaseDialog):
  1687. """!User preferences dialog"""
  1688. def __init__(self, parent, settings = UserSettings,
  1689. title = _("Modeler settings")):
  1690. PreferencesBaseDialog.__init__(self, parent = parent, title = title,
  1691. settings = settings)
  1692. # create notebook pages
  1693. self._createActionPage(self.notebook)
  1694. self._createDataPage(self.notebook)
  1695. self.SetMinSize(self.GetBestSize())
  1696. self.SetSize(self.size)
  1697. def _createActionPage(self, notebook):
  1698. """!Create notebook page for action settings"""
  1699. panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
  1700. notebook.AddPage(page = panel, text = _("Action"))
  1701. # colors
  1702. border = wx.BoxSizer(wx.VERTICAL)
  1703. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  1704. label = " %s " % _("Color settings"))
  1705. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1706. gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
  1707. gridSizer.AddGrowableCol(0)
  1708. row = 0
  1709. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1710. label = _("Valid:")),
  1711. flag = wx.ALIGN_LEFT |
  1712. wx.ALIGN_CENTER_VERTICAL,
  1713. pos = (row, 0))
  1714. vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  1715. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'valid')),
  1716. size = globalvar.DIALOG_COLOR_SIZE)
  1717. vColor.SetName('GetColour')
  1718. self.winId['modeler:action:color:valid'] = vColor.GetId()
  1719. gridSizer.Add(item = vColor,
  1720. flag = wx.ALIGN_RIGHT |
  1721. wx.ALIGN_CENTER_VERTICAL,
  1722. pos = (row, 1))
  1723. row += 1
  1724. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1725. label = _("Invalid:")),
  1726. flag = wx.ALIGN_LEFT |
  1727. wx.ALIGN_CENTER_VERTICAL,
  1728. pos = (row, 0))
  1729. iColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  1730. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'invalid')),
  1731. size = globalvar.DIALOG_COLOR_SIZE)
  1732. iColor.SetName('GetColour')
  1733. self.winId['modeler:action:color:invalid'] = iColor.GetId()
  1734. gridSizer.Add(item = iColor,
  1735. flag = wx.ALIGN_RIGHT |
  1736. wx.ALIGN_CENTER_VERTICAL,
  1737. pos = (row, 1))
  1738. row += 1
  1739. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1740. label = _("Running:")),
  1741. flag = wx.ALIGN_LEFT |
  1742. wx.ALIGN_CENTER_VERTICAL,
  1743. pos = (row, 0))
  1744. rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  1745. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'running')),
  1746. size = globalvar.DIALOG_COLOR_SIZE)
  1747. rColor.SetName('GetColour')
  1748. self.winId['modeler:action:color:running'] = rColor.GetId()
  1749. gridSizer.Add(item = rColor,
  1750. flag = wx.ALIGN_RIGHT |
  1751. wx.ALIGN_CENTER_VERTICAL,
  1752. pos = (row, 1))
  1753. sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
  1754. border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  1755. # size
  1756. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  1757. label = " %s " % _("Size settings"))
  1758. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1759. gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
  1760. gridSizer.AddGrowableCol(0)
  1761. row = 0
  1762. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1763. label = _("Width:")),
  1764. flag = wx.ALIGN_LEFT |
  1765. wx.ALIGN_CENTER_VERTICAL,
  1766. pos = (row, 0))
  1767. width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  1768. min = 0, max = 500,
  1769. initial = self.settings.Get(group='modeler', key='action', subkey=('size', 'width')))
  1770. width.SetName('GetValue')
  1771. self.winId['modeler:action:size:width'] = width.GetId()
  1772. gridSizer.Add(item = width,
  1773. flag = wx.ALIGN_RIGHT |
  1774. wx.ALIGN_CENTER_VERTICAL,
  1775. pos = (row, 1))
  1776. row += 1
  1777. gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1778. label=_("Height:")),
  1779. flag = wx.ALIGN_LEFT |
  1780. wx.ALIGN_CENTER_VERTICAL,
  1781. pos=(row, 0))
  1782. height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  1783. min = 0, max = 500,
  1784. initial = self.settings.Get(group='modeler', key='action', subkey=('size', 'height')))
  1785. height.SetName('GetValue')
  1786. self.winId['modeler:action:size:height'] = height.GetId()
  1787. gridSizer.Add(item = height,
  1788. flag = wx.ALIGN_RIGHT |
  1789. wx.ALIGN_CENTER_VERTICAL,
  1790. pos = (row, 1))
  1791. sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
  1792. border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
  1793. panel.SetSizer(border)
  1794. return panel
  1795. def _createDataPage(self, notebook):
  1796. """!Create notebook page for data settings"""
  1797. panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
  1798. notebook.AddPage(page = panel, text = _("Data"))
  1799. # colors
  1800. border = wx.BoxSizer(wx.VERTICAL)
  1801. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  1802. label = " %s " % _("Color settings"))
  1803. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1804. gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
  1805. gridSizer.AddGrowableCol(0)
  1806. row = 0
  1807. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1808. label = _("Raster:")),
  1809. flag = wx.ALIGN_LEFT |
  1810. wx.ALIGN_CENTER_VERTICAL,
  1811. pos = (row, 0))
  1812. rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  1813. colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'raster')),
  1814. size = globalvar.DIALOG_COLOR_SIZE)
  1815. rColor.SetName('GetColour')
  1816. self.winId['modeler:data:color:raster'] = rColor.GetId()
  1817. gridSizer.Add(item = rColor,
  1818. flag = wx.ALIGN_RIGHT |
  1819. wx.ALIGN_CENTER_VERTICAL,
  1820. pos = (row, 1))
  1821. row += 1
  1822. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1823. label = _("3D raster:")),
  1824. flag = wx.ALIGN_LEFT |
  1825. wx.ALIGN_CENTER_VERTICAL,
  1826. pos = (row, 0))
  1827. r3Color = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  1828. colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'raster3d')),
  1829. size = globalvar.DIALOG_COLOR_SIZE)
  1830. r3Color.SetName('GetColour')
  1831. self.winId['modeler:data:color:raster3d'] = r3Color.GetId()
  1832. gridSizer.Add(item = r3Color,
  1833. flag = wx.ALIGN_RIGHT |
  1834. wx.ALIGN_CENTER_VERTICAL,
  1835. pos = (row, 1))
  1836. row += 1
  1837. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1838. label = _("Vector:")),
  1839. flag = wx.ALIGN_LEFT |
  1840. wx.ALIGN_CENTER_VERTICAL,
  1841. pos = (row, 0))
  1842. vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  1843. colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'vector')),
  1844. size = globalvar.DIALOG_COLOR_SIZE)
  1845. vColor.SetName('GetColour')
  1846. self.winId['modeler:data:color:vector'] = vColor.GetId()
  1847. gridSizer.Add(item = vColor,
  1848. flag = wx.ALIGN_RIGHT |
  1849. wx.ALIGN_CENTER_VERTICAL,
  1850. pos = (row, 1))
  1851. sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
  1852. border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  1853. # size
  1854. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  1855. label = " %s " % _("Size settings"))
  1856. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1857. gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
  1858. gridSizer.AddGrowableCol(0)
  1859. row = 0
  1860. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1861. label = _("Width:")),
  1862. flag = wx.ALIGN_LEFT |
  1863. wx.ALIGN_CENTER_VERTICAL,
  1864. pos = (row, 0))
  1865. width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  1866. min = 0, max = 500,
  1867. initial = self.settings.Get(group='modeler', key='data', subkey=('size', 'width')))
  1868. width.SetName('GetValue')
  1869. self.winId['modeler:data:size:width'] = width.GetId()
  1870. gridSizer.Add(item = width,
  1871. flag = wx.ALIGN_RIGHT |
  1872. wx.ALIGN_CENTER_VERTICAL,
  1873. pos = (row, 1))
  1874. row += 1
  1875. gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1876. label=_("Height:")),
  1877. flag = wx.ALIGN_LEFT |
  1878. wx.ALIGN_CENTER_VERTICAL,
  1879. pos=(row, 0))
  1880. height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  1881. min = 0, max = 500,
  1882. initial = self.settings.Get(group='modeler', key='data', subkey=('size', 'height')))
  1883. height.SetName('GetValue')
  1884. self.winId['modeler:data:size:height'] = height.GetId()
  1885. gridSizer.Add(item = height,
  1886. flag = wx.ALIGN_RIGHT |
  1887. wx.ALIGN_CENTER_VERTICAL,
  1888. pos = (row, 1))
  1889. sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
  1890. border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
  1891. panel.SetSizer(border)
  1892. return panel
  1893. def OnApply(self, event):
  1894. """!Button 'Apply' pressed"""
  1895. PreferencesBaseDialog.OnApply(self, event)
  1896. self.parent.GetModel().Update()
  1897. self.parent.GetCanvas().Refresh()
  1898. def OnSave(self, event):
  1899. """!Button 'Save' pressed"""
  1900. PreferencesBaseDialog.OnSave(self, event)
  1901. self.parent.GetModel().Update()
  1902. self.parent.GetCanvas().Refresh()
  1903. class PropertiesDialog(wx.Dialog):
  1904. """!Model properties dialog
  1905. """
  1906. def __init__(self, parent, id = wx.ID_ANY,
  1907. title = _('Model properties'),
  1908. size = (350, 400),
  1909. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1910. wx.Dialog.__init__(self, parent, id, title, size = size,
  1911. style = style)
  1912. self.name = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1913. size = (300, 25))
  1914. self.desc = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1915. style = wx.TE_MULTILINE,
  1916. size = (300, 50))
  1917. self.author = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1918. size = (300, 25))
  1919. # buttons
  1920. self.btnOk = wx.Button(self, wx.ID_OK)
  1921. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  1922. self.btnOk.SetDefault()
  1923. self.btnOk.SetToolTipString(_("Apply properties"))
  1924. self.btnOk.SetDefault()
  1925. self.btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1926. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  1927. self._layout()
  1928. def _layout(self):
  1929. gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
  1930. gridSizer.AddGrowableCol(0)
  1931. gridSizer.AddGrowableRow(1)
  1932. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1933. label = _("Name:")),
  1934. flag = wx.ALIGN_LEFT |
  1935. wx.ALIGN_CENTER_VERTICAL,
  1936. pos = (0, 0))
  1937. gridSizer.Add(item = self.name,
  1938. flag = wx.ALIGN_LEFT |
  1939. wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  1940. pos = (0, 1))
  1941. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1942. label = _("Description:")),
  1943. flag = wx.ALIGN_LEFT |
  1944. wx.ALIGN_CENTER_VERTICAL,
  1945. pos = (1, 0))
  1946. gridSizer.Add(item = self.desc,
  1947. flag = wx.ALIGN_LEFT |
  1948. wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  1949. pos = (1, 1))
  1950. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1951. label = _("Author(s):")),
  1952. flag = wx.ALIGN_LEFT |
  1953. wx.ALIGN_CENTER_VERTICAL,
  1954. pos = (2, 0))
  1955. gridSizer.Add(item = self.author,
  1956. flag = wx.ALIGN_LEFT |
  1957. wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  1958. pos = (2, 1))
  1959. btnStdSizer = wx.StdDialogButtonSizer()
  1960. btnStdSizer.AddButton(self.btnCancel)
  1961. btnStdSizer.AddButton(self.btnOk)
  1962. btnStdSizer.Realize()
  1963. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1964. mainSizer.Add(item=gridSizer, proportion=1,
  1965. flag=wx.EXPAND | wx.ALL, border=5)
  1966. mainSizer.Add(item=btnStdSizer, proportion=0,
  1967. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  1968. self.SetSizer(mainSizer)
  1969. mainSizer.Fit(self)
  1970. def OnCloseWindow(self, event):
  1971. self.Hide()
  1972. def GetValues(self):
  1973. """!Get values"""
  1974. return { 'name' : self.name.GetValue(),
  1975. 'desc' : self.desc.GetValue(),
  1976. 'author' : self.author.GetValue() }
  1977. def Init(self, prop):
  1978. """!Initialize dialog"""
  1979. self.name.SetValue(prop['name'])
  1980. self.desc.SetValue(prop['desc'])
  1981. self.author.SetValue(prop['author'])
  1982. class ModelParamDialog(wx.Dialog):
  1983. def __init__(self, parent, params, id = wx.ID_ANY, title = _("Model parameters"),
  1984. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  1985. """!Model parameters dialog
  1986. """
  1987. self.parent = parent
  1988. self.params = params
  1989. wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
  1990. self.notebook = FN.FlatNotebook(self, id = wx.ID_ANY,
  1991. style = FN.FNB_FANCY_TABS |
  1992. FN.FNB_BOTTOM |
  1993. FN.FNB_NO_NAV_BUTTONS |
  1994. FN.FNB_NO_X_BUTTON)
  1995. panel = self._createPages()
  1996. wx.CallAfter(self.notebook.SetSelection, 0)
  1997. self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  1998. self.btnRun = wx.Button(parent = self, id = wx.ID_OK,
  1999. label = _("&Run"))
  2000. self.btnRun.SetDefault()
  2001. self._layout()
  2002. size = self.GetBestSize()
  2003. self.SetMinSize(size)
  2004. self.SetSize((size.width, size.height +
  2005. panel.constrained_size[1] -
  2006. panel.panelMinHeight))
  2007. def _layout(self):
  2008. btnSizer = wx.StdDialogButtonSizer()
  2009. btnSizer.AddButton(self.btnCancel)
  2010. btnSizer.AddButton(self.btnRun)
  2011. btnSizer.Realize()
  2012. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2013. mainSizer.Add(item = self.notebook, proportion = 1,
  2014. flag = wx.EXPAND)
  2015. mainSizer.Add(item=btnSizer, proportion=0,
  2016. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  2017. self.SetSizer(mainSizer)
  2018. mainSizer.Fit(self)
  2019. def _createPages(self):
  2020. """!Create for each parameterized module its own page"""
  2021. nameOrdered = [''] * len(self.params.keys())
  2022. for name, params in self.params.iteritems():
  2023. nameOrdered[params['idx']] = name
  2024. for name in nameOrdered:
  2025. params = self.params[name]
  2026. panel = self._createPage(name, params)
  2027. self.notebook.AddPage(panel, text = name)
  2028. return panel
  2029. def _createPage(self, name, params):
  2030. """!Define notebook page"""
  2031. task = menuform.grassTask(name)
  2032. task.flags = params['flags']
  2033. task.params = params['params']
  2034. panel = menuform.cmdPanel(parent = self, id = wx.ID_ANY, task = task)
  2035. return panel
  2036. def main():
  2037. app = wx.PySimpleApp()
  2038. wx.InitAllImageHandlers()
  2039. frame = ModelFrame(parent = None)
  2040. if len(sys.argv) > 1:
  2041. frame.LoadModelFile(sys.argv[1])
  2042. # frame.CentreOnScreen()
  2043. frame.Show()
  2044. app.MainLoop()
  2045. if __name__ == "__main__":
  2046. main()