gmodeler.py 119 KB

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