gmodeler.py 90 KB

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