gmodeler.py 98 KB

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