gmodeler.py 94 KB

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