gmodeler.py 85 KB

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