gmodeler.py 92 KB

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