gmodeler.py 100 KB

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