gmodeler.py 78 KB

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