model.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446
  1. """!
  2. @package gmodeler.model
  3. @brief wxGUI Graphical Modeler (base classes & read/write)
  4. Classes:
  5. - model::Model
  6. - model::ModelObject
  7. - model::ModelAction
  8. - model::ModelData
  9. - model::ModelRelation
  10. - model::ModelItem
  11. - model::ModelLoop
  12. - model::ModelCondition
  13. - model::ModelComment
  14. - model::ProcessModelFile
  15. - model::WriteModelFile
  16. - model::WritePythonFile
  17. - model::ModelParamDialog
  18. (C) 2010-2013 by the GRASS Development Team
  19. This program is free software under the GNU General Public License
  20. (>=v2). Read the file COPYING that comes with GRASS for details.
  21. @author Martin Landa <landa.martin gmail.com>
  22. """
  23. import os
  24. import getpass
  25. import copy
  26. import re
  27. import mimetypes
  28. import time
  29. try:
  30. import xml.etree.ElementTree as etree
  31. except ImportError:
  32. import elementtree.ElementTree as etree # Python <= 2.4
  33. import xml.sax.saxutils as saxutils
  34. import wx
  35. from wx.lib import ogl
  36. from core import globalvar
  37. from core import utils
  38. from core.utils import _
  39. from core.gcmd import GMessage, GException, GError, RunCommand, EncodeString, GWarning, GetDefaultEncoding
  40. from core.settings import UserSettings
  41. from gui_core.forms import GUI, CmdPanel
  42. from gui_core.widgets import GNotebook
  43. from gmodeler.giface import GraphicalModelerGrassInterface
  44. from grass.script import core as grass
  45. from grass.script import task as gtask
  46. class Model(object):
  47. """!Class representing the model"""
  48. def __init__(self, canvas = None):
  49. self.items = list() # list of ordered items (action/loop/condition)
  50. # model properties
  51. self.properties = { 'name' : _("model"),
  52. 'description' : _("Script generated by wxGUI Graphical Modeler."),
  53. 'author' : getpass.getuser() }
  54. # model variables
  55. self.variables = dict()
  56. self.variablesParams = dict()
  57. self.canvas = canvas
  58. def GetCanvas(self):
  59. """!Get canvas or None"""
  60. return self.canvas
  61. def GetItems(self, objType = None):
  62. """!Get list of model items
  63. @param objType Object type to filter model objects
  64. """
  65. if not objType:
  66. return self.items
  67. result = list()
  68. for item in self.items:
  69. if isinstance(item, objType):
  70. result.append(item)
  71. return result
  72. def GetItem(self, aId, objType=None):
  73. """!Get item of given id
  74. @param aId item id
  75. @return Model* instance
  76. @return None if no item found
  77. """
  78. ilist = self.GetItems(objType)
  79. for item in ilist:
  80. if item.GetId() == aId:
  81. return item
  82. return None
  83. def GetItemIndex(self, item):
  84. """!Return list index of given item"""
  85. return self.items.index(item)
  86. def GetNumItems(self, actionOnly = False):
  87. """!Get number of items"""
  88. if actionOnly:
  89. return len(self.GetItems(objType = ModelAction))
  90. return len(self.GetItems())
  91. def ReorderItems(self, idxList):
  92. items = list()
  93. for oldIdx, newIdx in idxList.iteritems():
  94. item = self.items.pop(oldIdx)
  95. items.append(item)
  96. self.items.insert(newIdx, item)
  97. nextItem = self.items[newIdx+1]
  98. items.append(nextItem)
  99. x = item.GetX()
  100. y = item.GetY()
  101. item.SetX(nextItem.GetX())
  102. item.SetY(nextItem.GetY())
  103. nextItem.SetX(x)
  104. nextItem.SetY(y)
  105. dc = wx.ClientDC(self.canvas)
  106. for item in items:
  107. item.MoveLinks(dc)
  108. for mo in item.GetBlock():
  109. if isinstance(mo, ModelLoop):
  110. self.canvas.parent.DefineLoop(mo)
  111. elif isinstance(mo, ModelCondition):
  112. self.canvas.parent.DefineCondition(mo)
  113. def Normalize(self):
  114. iId = 1
  115. for item in self.items:
  116. item.SetId(iId)
  117. item.SetLabel()
  118. iId += 1
  119. def GetNextId(self):
  120. """!Get next id (data ignored)
  121. @return next id to be used (default: 1)
  122. """
  123. if len(self.items) < 1:
  124. return 1
  125. currId = self.items[-1].GetId()
  126. if currId > 0:
  127. return currId + 1
  128. return 1
  129. def GetProperties(self):
  130. """!Get model properties"""
  131. return self.properties
  132. def GetVariables(self, params = False):
  133. """!Get model variables"""
  134. if params:
  135. return self.variablesParams
  136. return self.variables
  137. def SetVariables(self, data):
  138. """!Set model variables"""
  139. self.variables = data
  140. def Reset(self):
  141. """!Reset model"""
  142. self.items = list()
  143. def RemoveItem(self, item):
  144. """!Remove item from model
  145. @return list of related items to remove/update
  146. """
  147. relList = list()
  148. upList = list()
  149. self.items.remove(item)
  150. if isinstance(item, ModelAction):
  151. for rel in item.GetRelations():
  152. relList.append(rel)
  153. data = rel.GetData()
  154. if len(data.GetRelations()) < 2:
  155. relList.append(data)
  156. else:
  157. upList.append(data)
  158. elif isinstance(item, ModelData):
  159. for rel in item.GetRelations():
  160. relList.append(rel)
  161. if rel.GetFrom() == self:
  162. relList.append(rel.GetTo())
  163. else:
  164. relList.append(rel.GetFrom())
  165. elif isinstance(item, ModelLoop):
  166. for rel in item.GetRelations():
  167. relList.append(rel)
  168. for action in self.GetItems():
  169. action.UnSetBlock(item)
  170. return relList, upList
  171. def FindAction(self, aId):
  172. """!Find action by id"""
  173. alist = self.GetItems(objType = ModelAction)
  174. for action in alist:
  175. if action.GetId() == aId:
  176. return action
  177. return None
  178. def GetMaps(self, prompt):
  179. """!Get list of maps of selected type
  180. @param promt to filter maps"""
  181. maps = list()
  182. for data in self.GetData():
  183. if prompt == data.GetPrompt():
  184. mapName = data.GetValue()
  185. if not mapName or mapName[0] is '%':
  186. continue # skip variables
  187. maps.append(mapName)
  188. return maps
  189. def GetData(self):
  190. """!Get list of data items"""
  191. result = list()
  192. dataItems = self.GetItems(objType = ModelData)
  193. for action in self.GetItems(objType = ModelAction):
  194. for rel in action.GetRelations():
  195. dataItem = rel.GetData()
  196. if dataItem not in result:
  197. result.append(dataItem)
  198. if dataItem in dataItems:
  199. dataItems.remove(dataItem)
  200. # standalone data
  201. if dataItems:
  202. result += dataItems
  203. return result
  204. def FindData(self, value, prompt):
  205. """!Find data item in the model
  206. @param value value
  207. @param prompt prompt
  208. @return ModelData instance
  209. @return None if not found
  210. """
  211. for data in self.GetData():
  212. if data.GetValue() == value and \
  213. data.GetPrompt() == prompt:
  214. return data
  215. return None
  216. def LoadModel(self, filename):
  217. """!Load model definition stored in GRASS Model XML file (gxm)
  218. @todo Validate against DTD
  219. Raise exception on error.
  220. """
  221. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  222. # parse workspace file
  223. try:
  224. gxmXml = ProcessModelFile(etree.parse(filename))
  225. except StandardError, e:
  226. raise GException(e)
  227. if self.canvas:
  228. win = self.canvas.parent
  229. if gxmXml.pos:
  230. win.SetPosition(gxmXml.pos)
  231. if gxmXml.size:
  232. win.SetSize(gxmXml.size)
  233. # load properties
  234. self.properties = gxmXml.properties
  235. self.variables = gxmXml.variables
  236. # load actions
  237. for action in gxmXml.actions:
  238. actionItem = ModelAction(parent = self,
  239. x = action['pos'][0],
  240. y = action['pos'][1],
  241. width = action['size'][0],
  242. height = action['size'][1],
  243. task = action['task'],
  244. id = action['id'],
  245. label = action['label'],
  246. comment = action['comment'])
  247. if action['disabled']:
  248. actionItem.Enable(False)
  249. self.AddItem(actionItem, pos = actionItem.GetId()-1)
  250. actionItem.SetValid(actionItem.GetTask().get_options())
  251. actionItem.GetLog() # substitute variables (-> valid/invalid)
  252. # load data & relations
  253. for data in gxmXml.data:
  254. dataItem = ModelData(parent = self,
  255. x = data['pos'][0],
  256. y = data['pos'][1],
  257. width = data['size'][0],
  258. height = data['size'][1],
  259. prompt = data['prompt'],
  260. value = data['value'])
  261. dataItem.SetIntermediate(data['intermediate'])
  262. for rel in data['rels']:
  263. actionItem = self.FindAction(rel['id'])
  264. if rel['dir'] == 'from':
  265. relation = ModelRelation(parent = self, fromShape = dataItem,
  266. toShape = actionItem, param = rel['name'])
  267. else:
  268. relation = ModelRelation(parent = self, fromShape = actionItem,
  269. toShape = dataItem, param = rel['name'])
  270. relation.SetControlPoints(rel['points'])
  271. actionItem.AddRelation(relation)
  272. dataItem.AddRelation(relation)
  273. if self.canvas:
  274. dataItem.Update()
  275. # load loops
  276. for loop in gxmXml.loops:
  277. loopItem = ModelLoop(parent = self,
  278. x = loop['pos'][0],
  279. y = loop['pos'][1],
  280. width = loop['size'][0],
  281. height = loop['size'][1],
  282. label = loop['text'],
  283. id = loop['id'])
  284. self.AddItem(loopItem, pos = loopItem.GetId()-1)
  285. # load conditions
  286. for condition in gxmXml.conditions:
  287. conditionItem = ModelCondition(parent = self,
  288. x = condition['pos'][0],
  289. y = condition['pos'][1],
  290. width = condition['size'][0],
  291. height = condition['size'][1],
  292. label = condition['text'],
  293. id = condition['id'])
  294. self.AddItem(conditionItem, pos = conditionItem.GetId()-1)
  295. # define loops & if/else items
  296. for loop in gxmXml.loops:
  297. loopItem = self.GetItem(loop['id'], objType=ModelLoop)
  298. loopItem.SetItems(loop['items'])
  299. for idx in loop['items']:
  300. action = self.GetItem(idx, objType=ModelAction)
  301. action.SetBlock(loopItem)
  302. for condition in gxmXml.conditions:
  303. conditionItem = self.GetItem(condition['id'])
  304. for b in condition['items'].keys():
  305. alist = list()
  306. for aId in condition['items'][b]:
  307. action = self.GetItem(aId)
  308. alist.append(action)
  309. conditionItem.SetItems(alist, branch = b)
  310. items = conditionItem.GetItems()
  311. for b in items.keys():
  312. for action in items[b]:
  313. action.SetBlock(conditionItem)
  314. # load comments
  315. for comment in gxmXml.comments:
  316. commentItem = ModelComment(parent = self,
  317. x = comment['pos'][0],
  318. y = comment['pos'][1],
  319. width = comment['size'][0],
  320. height = comment['size'][1],
  321. id = comment['id'],
  322. label = comment['text'])
  323. self.AddItem(commentItem, pos = commentItem.GetId()-1)
  324. def AddItem(self, newItem, pos = -1):
  325. """!Add item to the list"""
  326. if pos != -1:
  327. self.items.insert(pos, newItem)
  328. else:
  329. self.items.append(newItem)
  330. # i = 1
  331. # for item in self.items:
  332. # item.SetId(i)
  333. # i += 1
  334. def IsValid(self):
  335. """Return True if model is valid"""
  336. if self.Validate():
  337. return False
  338. return True
  339. def Validate(self):
  340. """!Validate model, return None if model is valid otherwise
  341. error string"""
  342. errList = list()
  343. variables = self.GetVariables().keys()
  344. pattern = re.compile(r'(.*)(%.+\s?)(.*)')
  345. for action in self.GetItems(objType = ModelAction):
  346. cmd = action.GetLog(string = False)
  347. task = GUI(show = None).ParseCommand(cmd = cmd)
  348. errList += map(lambda x: cmd[0] + ': ' + x, task.get_cmd_error())
  349. # check also variables
  350. for opt in cmd[1:]:
  351. if '=' not in opt:
  352. continue
  353. key, value = opt.split('=', 1)
  354. sval = pattern.search(value)
  355. if sval:
  356. var = sval.group(2).strip()[1:] # ignore '%'
  357. if var not in variables:
  358. report = True
  359. for item in filter(lambda x: isinstance(x, ModelLoop), action.GetBlock()):
  360. if var in item.GetLabel():
  361. report = False
  362. break
  363. if report:
  364. errList.append(cmd[0] + ": " + _("undefined variable '%s'") % var)
  365. ### TODO: check variables in file only optionally
  366. ### errList += self._substituteFile(action, checkOnly = True)
  367. return errList
  368. def _substituteFile(self, item, params = None, checkOnly = False):
  369. """!Subsitute variables in command file inputs
  370. @param checkOnly tuble - True to check variable, don't touch files
  371. @return list of undefined variables
  372. """
  373. errList = list()
  374. self.fileInput = dict()
  375. # collect ascii inputs
  376. for p in item.GetParams()['params']:
  377. if p.get('element', '') == 'file' and \
  378. p.get('prompt', '') == 'input' and \
  379. p.get('age', '') == 'old':
  380. filename = p.get('value', p.get('default', ''))
  381. if filename and \
  382. mimetypes.guess_type(filename)[0] == 'text/plain':
  383. self.fileInput[filename] = None
  384. for finput in self.fileInput:
  385. # read lines
  386. fd = open(finput, "r")
  387. try:
  388. data = self.fileInput[finput] = fd.read()
  389. finally:
  390. fd.close()
  391. # substitute variables
  392. write = False
  393. variables = self.GetVariables()
  394. for variable in variables:
  395. pattern = re.compile('%' + variable)
  396. value = ''
  397. if params and 'variables' in params:
  398. for p in params['variables']['params']:
  399. if variable == p.get('name', ''):
  400. if p.get('type', 'string') == 'string':
  401. value = p.get('value', '')
  402. else:
  403. value = str(p.get('value', ''))
  404. break
  405. if not value:
  406. value = variables[variable].get('value', '')
  407. data = pattern.sub(value, data)
  408. if not checkOnly:
  409. write = True
  410. pattern = re.compile(r'(.*)(%.+\s?)(.*)')
  411. sval = pattern.search(data)
  412. if sval:
  413. var = sval.group(2).strip()[1:] # ignore '%'
  414. cmd = item.GetLog(string = False)[0]
  415. errList.append(cmd + ": " + _("undefined variable '%s'") % var)
  416. if not checkOnly:
  417. if write:
  418. fd = open(finput, "w")
  419. try:
  420. fd.write(data)
  421. finally:
  422. fd.close()
  423. else:
  424. self.fileInput[finput] = None
  425. return errList
  426. def OnPrepare(self, item, params):
  427. self._substituteFile(item, params, checkOnly = False)
  428. def RunAction(self, item, params, log, onDone, onPrepare = None, statusbar = None):
  429. """!Run given action
  430. @param item action item
  431. @param params parameters dict
  432. @param log logging window
  433. @param onDone on-done method
  434. @param onPrepare on-prepare method
  435. @param statusbar wx.StatusBar instance or None
  436. """
  437. name = item.GetLabel()
  438. if name in params:
  439. paramsOrig = item.GetParams(dcopy = True)
  440. item.MergeParams(params[name])
  441. if statusbar:
  442. statusbar.SetStatusText(_('Running model...'), 0)
  443. data = { 'item' : item,
  444. 'params' : copy.deepcopy(params) }
  445. log.RunCmd(command = item.GetLog(string = False, substitute = params),
  446. onDone = onDone, onPrepare = self.OnPrepare, userData = data)
  447. if name in params:
  448. item.SetParams(paramsOrig)
  449. def Run(self, log, onDone, parent = None):
  450. """!Run model
  451. @param log logging window (see gconsole.GConsole)
  452. @param onDone on-done method
  453. @param parent window for messages or None
  454. """
  455. if self.GetNumItems() < 1:
  456. GMessage(parent = parent,
  457. message = _('Model is empty. Nothing to run.'))
  458. return
  459. statusbar = None
  460. if isinstance(parent, wx.Frame):
  461. statusbar = parent.GetStatusBar()
  462. # validation
  463. if statusbar:
  464. statusbar.SetStatusText(_('Validating model...'), 0)
  465. errList = self.Validate()
  466. if statusbar:
  467. statusbar.SetStatusText('', 0)
  468. if errList:
  469. dlg = wx.MessageDialog(parent = parent,
  470. message = _('Model is not valid. Do you want to '
  471. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  472. caption = _("Run model?"),
  473. style = wx.YES_NO | wx.NO_DEFAULT |
  474. wx.ICON_QUESTION | wx.CENTRE)
  475. ret = dlg.ShowModal()
  476. dlg.Destroy()
  477. if ret != wx.ID_YES:
  478. return
  479. # parametrization
  480. params = self.Parameterize()
  481. delInterData = False
  482. if params:
  483. dlg = ModelParamDialog(parent = parent,
  484. params = params)
  485. dlg.CenterOnParent()
  486. ret = dlg.ShowModal()
  487. if ret != wx.ID_OK:
  488. dlg.Destroy()
  489. return
  490. err = dlg.GetErrors()
  491. delInterData = dlg.DeleteIntermediateData()
  492. dlg.Destroy()
  493. if err:
  494. GError(parent = parent, message = unicode('\n'.join(err)))
  495. return
  496. err = list()
  497. for key, item in params.iteritems():
  498. for p in item['params']:
  499. if p.get('value', '') == '':
  500. err.append((key, p.get('name', ''), p.get('description', '')))
  501. if err:
  502. GError(parent = parent,
  503. message = _("Variables below not defined:") + \
  504. "\n\n" + unicode('\n'.join(map(lambda x: "%s: %s (%s)" % (x[0], x[1], x[2]), err))))
  505. return
  506. log.cmdThread.SetId(-1)
  507. for item in self.GetItems():
  508. if not item.IsEnabled():
  509. continue
  510. if isinstance(item, ModelAction):
  511. if item.GetBlockId():
  512. continue
  513. self.RunAction(item, params, log, onDone)
  514. elif isinstance(item, ModelLoop):
  515. cond = item.GetLabel()
  516. # substitute variables in condition
  517. variables = self.GetVariables()
  518. for variable in variables:
  519. pattern = re.compile('%' + variable)
  520. if pattern.search(cond):
  521. value = ''
  522. if params and 'variables' in params:
  523. for p in params['variables']['params']:
  524. if variable == p.get('name', ''):
  525. value = p.get('value', '')
  526. break
  527. if not value:
  528. value = variables[variable].get('value', '')
  529. if not value:
  530. continue
  531. vtype = variables[variable].get('type', 'string')
  532. if vtype == 'string':
  533. value = '"' + value + '"'
  534. cond = pattern.sub(value, cond)
  535. # split condition
  536. ### TODO: this part needs some better solution
  537. condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
  538. pattern = re.compile('%' + condVar)
  539. ### for vars()[condVar] in eval(condText): ?
  540. vlist = list()
  541. if condText[0] == '`' and condText[-1] == '`':
  542. # run command
  543. cmd, dcmd = utils.CmdToTuple(condText[1:-1].split(' '))
  544. ret = RunCommand(cmd,
  545. read = True,
  546. **dcmd)
  547. if ret:
  548. vlist = ret.splitlines()
  549. else:
  550. vlist = eval(condText)
  551. if 'variables' not in params:
  552. params['variables'] = { 'params' : [] }
  553. varDict = { 'name' : condVar, 'value' : '' }
  554. params['variables']['params'].append(varDict)
  555. for var in vlist:
  556. for action in item.GetItems(self.GetItems()):
  557. if not action.IsEnabled():
  558. continue
  559. varDict['value'] = var
  560. self.RunAction(item = action, params = params,
  561. log = log, onDone = onDone)
  562. params['variables']['params'].remove(varDict)
  563. if delInterData:
  564. self.DeleteIntermediateData(log)
  565. # discard values
  566. if params:
  567. for item in params.itervalues():
  568. for p in item['params']:
  569. p['value'] = ''
  570. def DeleteIntermediateData(self, log):
  571. """!Detele intermediate data"""
  572. rast, vect, rast3d, msg = self.GetIntermediateData()
  573. if rast:
  574. log.RunCmd(['g.remove', 'rast=%s' %','.join(rast)])
  575. if rast3d:
  576. log.RunCmd(['g.remove', 'rast3d=%s' %','.join(rast3d)])
  577. if vect:
  578. log.RunCmd(['g.remove', 'vect=%s' %','.join(vect)])
  579. def GetIntermediateData(self):
  580. """!Get info about intermediate data"""
  581. rast = list()
  582. rast3d = list()
  583. vect = list()
  584. for data in self.GetData():
  585. if not data.IsIntermediate():
  586. continue
  587. name = data.GetValue()
  588. prompt = data.GetPrompt()
  589. if prompt == 'raster':
  590. rast.append(name)
  591. elif prompt == 'vector':
  592. vect.append(name)
  593. elif prompt == 'rast3d':
  594. rast3d.append(name)
  595. msg = ''
  596. if rast:
  597. msg += '\n\n%s: ' % _('Raster maps')
  598. msg += ', '.join(rast)
  599. if rast3d:
  600. msg += '\n\n%s: ' % _('3D raster maps')
  601. msg += ', '.join(rast3d)
  602. if vect:
  603. msg += '\n\n%s: ' % _('Vector maps')
  604. msg += ', '.join(vect)
  605. return rast, vect, rast3d, msg
  606. def Update(self):
  607. """!Update model"""
  608. for item in self.items:
  609. item.Update()
  610. def IsParameterized(self):
  611. """!Return True if model is parameterized"""
  612. if self.Parameterize():
  613. return True
  614. return False
  615. def Parameterize(self):
  616. """!Return parameterized options"""
  617. result = dict()
  618. idx = 0
  619. if self.variables:
  620. params = list()
  621. result["variables"] = { 'flags' : list(),
  622. 'params' : params,
  623. 'idx' : idx }
  624. for name, values in self.variables.iteritems():
  625. gtype = values.get('type', 'string')
  626. if gtype in ('raster', 'vector', 'mapset', 'file'):
  627. gisprompt = True
  628. prompt = gtype
  629. if gtype == 'raster':
  630. element = 'cell'
  631. else:
  632. element = gtype
  633. ptype = 'string'
  634. else:
  635. gisprompt = False
  636. prompt = None
  637. element = None
  638. ptype = gtype
  639. params.append({ 'gisprompt' : gisprompt,
  640. 'multiple' : False,
  641. 'description' : values.get('description', ''),
  642. 'guidependency' : '',
  643. 'default' : '',
  644. 'age' : None,
  645. 'required' : True,
  646. 'value' : values.get('value', ''),
  647. 'label' : '',
  648. 'guisection' : '',
  649. 'key_desc' : '',
  650. 'values' : list(),
  651. 'parameterized' : False,
  652. 'values_desc' : list(),
  653. 'prompt' : prompt,
  654. 'element' : element,
  655. 'type' : ptype,
  656. 'name' : name })
  657. idx += 1
  658. for action in self.GetItems(objType = ModelAction):
  659. if not action.IsEnabled():
  660. continue
  661. name = action.GetLabel()
  662. params = action.GetParams()
  663. for f in params['flags']:
  664. if f.get('parameterized', False):
  665. if name not in result:
  666. result[name] = { 'flags' : list(),
  667. 'params': list(),
  668. 'idx' : idx }
  669. result[name]['flags'].append(f)
  670. for p in params['params']:
  671. if p.get('parameterized', False):
  672. if name not in result:
  673. result[name] = { 'flags' : list(),
  674. 'params': list(),
  675. 'idx' : idx }
  676. result[name]['params'].append(p)
  677. if name in result:
  678. idx += 1
  679. self.variablesParams = result # record parameters
  680. return result
  681. class ModelObject(object):
  682. def __init__(self, id = -1, label = ''):
  683. self.id = id # internal id, should be not changed
  684. self.label = ''
  685. self.rels = list() # list of ModelRelations
  686. self.isEnabled = True
  687. self.inBlock = list() # list of related loops/conditions
  688. def __del__(self):
  689. pass
  690. def GetLabel(self):
  691. """!Get label"""
  692. return self.label
  693. def SetLabel(self, label=''):
  694. """!Set label"""
  695. self.label = label
  696. def GetId(self):
  697. """!Get id"""
  698. return self.id
  699. def SetId(self, id):
  700. """!Set id"""
  701. self.id = id
  702. def AddRelation(self, rel):
  703. """!Record new relation
  704. """
  705. self.rels.append(rel)
  706. def GetRelations(self, fdir = None):
  707. """!Get list of relations
  708. @param fdir True for 'from'
  709. """
  710. if fdir is None:
  711. return self.rels
  712. result = list()
  713. for rel in self.rels:
  714. if fdir == 'from':
  715. if rel.GetFrom() == self:
  716. result.append(rel)
  717. else:
  718. if rel.GetTo() == self:
  719. result.append(rel)
  720. return result
  721. def IsEnabled(self):
  722. """!Get True if action is enabled, otherwise False"""
  723. return self.isEnabled
  724. def Enable(self, enabled = True):
  725. """!Enable/disable action"""
  726. self.isEnabled = enabled
  727. self.Update()
  728. def Update(self):
  729. pass
  730. def SetBlock(self, item):
  731. """!Add object to the block (loop/condition)
  732. @param item reference to ModelLoop or ModelCondition which
  733. defines loops/condition
  734. """
  735. if item not in self.inBlock:
  736. self.inBlock.append(item)
  737. def UnSetBlock(self, item):
  738. """!Remove object from the block (loop/consition)
  739. @param item reference to ModelLoop or ModelCondition which
  740. defines loops/codition
  741. """
  742. if item in self.inBlock:
  743. self.inBlock.remove(item)
  744. def GetBlock(self):
  745. """!Get list of related ModelObject(s) which defines block
  746. (loop/condition)
  747. @return list of ModelObjects
  748. """
  749. return self.inBlock
  750. def GetBlockId(self):
  751. """!Get list of related ids which defines block
  752. @return list of ids
  753. """
  754. ret = list()
  755. for mo in self.inBlock:
  756. ret.append(mo.GetId())
  757. return ret
  758. class ModelAction(ModelObject, ogl.RectangleShape):
  759. """!Action class (GRASS module)"""
  760. def __init__(self, parent, x, y, id = -1, cmd = None, task = None,
  761. width = None, height = None, label = None, comment = ''):
  762. ModelObject.__init__(self, id, label)
  763. self.parent = parent
  764. self.task = task
  765. self.comment = comment
  766. if not width:
  767. width = UserSettings.Get(group='modeler', key='action', subkey=('size', 'width'))
  768. if not height:
  769. height = UserSettings.Get(group='modeler', key='action', subkey=('size', 'height'))
  770. if cmd:
  771. self.task = GUI(show = None).ParseCommand(cmd = cmd)
  772. else:
  773. if task:
  774. self.task = task
  775. else:
  776. self.task = None
  777. self.propWin = None
  778. self.data = list() # list of connected data items
  779. self.isValid = False
  780. self.isParameterized = False
  781. if self.parent.GetCanvas():
  782. ogl.RectangleShape.__init__(self, width, height)
  783. self.SetCanvas(self.parent)
  784. self.SetX(x)
  785. self.SetY(y)
  786. self._setPen()
  787. self._setBrush()
  788. self.SetLabel(label)
  789. if self.task:
  790. self.SetValid(self.task.get_options())
  791. def _setBrush(self, running = False):
  792. """!Set brush"""
  793. if running:
  794. color = UserSettings.Get(group='modeler', key='action',
  795. subkey=('color', 'running'))
  796. elif not self.isEnabled:
  797. color = UserSettings.Get(group='modeler', key='disabled',
  798. subkey='color')
  799. elif self.isValid:
  800. color = UserSettings.Get(group='modeler', key='action',
  801. subkey=('color', 'valid'))
  802. else:
  803. color = UserSettings.Get(group='modeler', key='action',
  804. subkey=('color', 'invalid'))
  805. wxColor = wx.Colour(color[0], color[1], color[2])
  806. self.SetBrush(wx.Brush(wxColor))
  807. def _setPen(self):
  808. """!Set pen"""
  809. if self.isParameterized:
  810. width = int(UserSettings.Get(group='modeler', key='action',
  811. subkey=('width', 'parameterized')))
  812. else:
  813. width = int(UserSettings.Get(group='modeler', key='action',
  814. subkey=('width', 'default')))
  815. if self.isEnabled:
  816. style = wx.SOLID
  817. else:
  818. style = wx.DOT
  819. pen = wx.Pen(wx.BLACK, width, style)
  820. self.SetPen(pen)
  821. def SetLabel(self, label=None):
  822. """!Set label
  823. @param label if None use command string instead
  824. """
  825. if label:
  826. self.label = label
  827. elif self.label:
  828. label = self.label
  829. else:
  830. try:
  831. label = self.task.get_cmd(ignoreErrors = True)[0]
  832. except:
  833. label = _("unknown")
  834. idx = self.GetId()
  835. self.ClearText()
  836. self.AddText('(%d) %s' % (idx, label))
  837. def SetComment(self, comment):
  838. """!Set comment"""
  839. self.comment = comment
  840. def GetComment(self):
  841. """!Get comment"""
  842. return self.comment
  843. def SetProperties(self, params, propwin):
  844. """!Record properties dialog"""
  845. self.task.params = params['params']
  846. self.task.flags = params['flags']
  847. self.propWin = propwin
  848. def GetPropDialog(self):
  849. """!Get properties dialog"""
  850. return self.propWin
  851. def GetLog(self, string = True, substitute = None):
  852. """!Get logging info
  853. @param string True to get cmd as a string otherwise a list
  854. @param substitute dictionary of parameter to substitute or None
  855. """
  856. cmd = self.task.get_cmd(ignoreErrors = True, ignoreRequired = True,
  857. ignoreDefault = False)
  858. # substitute variables
  859. if substitute:
  860. variables = []
  861. if 'variables' in substitute:
  862. for p in substitute['variables']['params']:
  863. variables.append(p.get('name', ''))
  864. else:
  865. variables = self.parent.GetVariables()
  866. for variable in variables:
  867. pattern= re.compile('%' + variable)
  868. value = ''
  869. if substitute and 'variables' in substitute:
  870. for p in substitute['variables']['params']:
  871. if variable == p.get('name', ''):
  872. if p.get('type', 'string') == 'string':
  873. value = p.get('value', '')
  874. else:
  875. value = str(p.get('value', ''))
  876. break
  877. if not value:
  878. value = variables[variable].get('value', '')
  879. if not value:
  880. continue
  881. for idx in range(len(cmd)):
  882. if pattern.search(cmd[idx]):
  883. cmd[idx] = pattern.sub(value, cmd[idx])
  884. break
  885. idx += 1
  886. if string:
  887. if cmd is None:
  888. return ''
  889. else:
  890. return ' '.join(cmd)
  891. return cmd
  892. def GetLabel(self):
  893. """!Get name"""
  894. if self.label:
  895. return self.label
  896. cmd = self.task.get_cmd(ignoreErrors = True)
  897. if cmd and len(cmd) > 0:
  898. return cmd[0]
  899. return _('unknown')
  900. def GetParams(self, dcopy = False):
  901. """!Get dictionary of parameters"""
  902. if dcopy:
  903. return copy.deepcopy(self.task.get_options())
  904. return self.task.get_options()
  905. def GetTask(self):
  906. """!Get grassTask instance"""
  907. return self.task
  908. def SetParams(self, params):
  909. """!Set dictionary of parameters"""
  910. self.task.params = params['params']
  911. self.task.flags = params['flags']
  912. def MergeParams(self, params):
  913. """!Merge dictionary of parameters"""
  914. if 'flags' in params:
  915. for f in params['flags']:
  916. self.task.set_flag(f['name'],
  917. f.get('value', False))
  918. if 'params' in params:
  919. for p in params['params']:
  920. self.task.set_param(p['name'],
  921. p.get('value', ''))
  922. def SetValid(self, options):
  923. """!Set validity for action
  924. @param options dictionary with flags and params (gtask)
  925. """
  926. self.isValid = True
  927. self.isParameterized = False
  928. for f in options['flags']:
  929. if f.get('parameterized', False):
  930. self.IsParameterized = True
  931. break
  932. for p in options['params']:
  933. if self.isValid and p.get('required', False) and \
  934. p.get('value', '') == '' and \
  935. p.get('default', '') == '':
  936. self.isValid = False
  937. if not self.isParameterized and p.get('parameterized', False):
  938. self.isParameterized = True
  939. if self.parent.GetCanvas():
  940. self._setBrush()
  941. self._setPen()
  942. def IsValid(self):
  943. """!Check validity (all required parameters set)"""
  944. return self.isValid
  945. def IsParameterized(self):
  946. """!Check if action is parameterized"""
  947. return self.isParameterized
  948. def FindData(self, name):
  949. """!Find data item by name"""
  950. for rel in self.GetRelations():
  951. data = rel.GetData()
  952. if name == rel.GetLabel() and name in data.GetLabel():
  953. return data
  954. return None
  955. def Update(self, running = False):
  956. """!Update action"""
  957. if running:
  958. self._setBrush(running = True)
  959. else:
  960. self._setBrush()
  961. self._setPen()
  962. def OnDraw(self, dc):
  963. """!Draw action in canvas"""
  964. self._setBrush()
  965. self._setPen()
  966. ogl.RectangleShape.Recentre(self, dc) # re-center text
  967. ogl.RectangleShape.OnDraw(self, dc)
  968. class ModelData(ModelObject, ogl.EllipseShape):
  969. def __init__(self, parent, x, y, value = '', prompt = '', width = None, height = None):
  970. """Data item class
  971. @param parent window parent
  972. @param x, y position of the shape
  973. @param fname, tname list of parameter names from / to
  974. @param value value
  975. @param prompt type of GIS element
  976. @param width,height dimension of the shape
  977. """
  978. ModelObject.__init__(self)
  979. self.parent = parent
  980. self.value = value
  981. self.prompt = prompt
  982. self.intermediate = False
  983. self.propWin = None
  984. if not width:
  985. width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
  986. if not height:
  987. height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
  988. if self.parent.GetCanvas():
  989. ogl.EllipseShape.__init__(self, width, height)
  990. self.SetCanvas(self.parent)
  991. self.SetX(x)
  992. self.SetY(y)
  993. self.SetPen(wx.BLACK_PEN)
  994. self._setBrush()
  995. self.SetLabel()
  996. def IsIntermediate(self):
  997. """!Checks if data item is intermediate"""
  998. return self.intermediate
  999. def SetIntermediate(self, im):
  1000. """!Set intermediate flag"""
  1001. self.intermediate = im
  1002. def OnDraw(self, dc):
  1003. pen = wx.Pen(wx.BLACK, 1, wx.SOLID)
  1004. if self.intermediate:
  1005. pen.SetStyle(wx.SHORT_DASH)
  1006. self.SetPen(pen)
  1007. ogl.EllipseShape.OnDraw(self, dc)
  1008. def GetLog(self, string = True):
  1009. """!Get logging info"""
  1010. name = list()
  1011. for rel in self.GetRelations():
  1012. name.append(rel.GetLabel())
  1013. if name:
  1014. return '/'.join(name) + '=' + self.value + ' (' + self.prompt + ')'
  1015. else:
  1016. return self.value + ' (' + self.prompt + ')'
  1017. def GetLabel(self):
  1018. """!Get list of names"""
  1019. name = list()
  1020. for rel in self.GetRelations():
  1021. name.append(rel.GetLabel())
  1022. return name
  1023. def GetPrompt(self):
  1024. """!Get prompt"""
  1025. return self.prompt
  1026. def SetPrompt(self, prompt):
  1027. """!Set prompt
  1028. @param prompt
  1029. """
  1030. self.prompt = prompt
  1031. def GetValue(self):
  1032. """!Get value"""
  1033. return self.value
  1034. def SetValue(self, value):
  1035. """!Set value
  1036. @param value
  1037. """
  1038. self.value = value
  1039. self.SetLabel()
  1040. for direction in ('from', 'to'):
  1041. for rel in self.GetRelations(direction):
  1042. if direction == 'from':
  1043. action = rel.GetTo()
  1044. else:
  1045. action = rel.GetFrom()
  1046. task = GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
  1047. task.set_param(rel.GetLabel(), self.value)
  1048. action.SetParams(params = task.get_options())
  1049. def GetPropDialog(self):
  1050. """!Get properties dialog"""
  1051. return self.propWin
  1052. def SetPropDialog(self, win):
  1053. """!Get properties dialog"""
  1054. self.propWin = win
  1055. def _setBrush(self):
  1056. """!Set brush"""
  1057. if self.prompt == 'raster':
  1058. color = UserSettings.Get(group = 'modeler', key = 'data',
  1059. subkey = ('color', 'raster'))
  1060. elif self.prompt == 'raster3d':
  1061. color = UserSettings.Get(group = 'modeler', key = 'data',
  1062. subkey = ('color', 'raster3d'))
  1063. elif self.prompt == 'vector':
  1064. color = UserSettings.Get(group = 'modeler', key = 'data',
  1065. subkey = ('color', 'vector'))
  1066. else:
  1067. color = UserSettings.Get(group = 'modeler', key = 'action',
  1068. subkey = ('color', 'invalid'))
  1069. wxColor = wx.Colour(color[0], color[1], color[2])
  1070. self.SetBrush(wx.Brush(wxColor))
  1071. def _setPen(self):
  1072. """!Set pen"""
  1073. isParameterized = False
  1074. for rel in self.GetRelations('from'):
  1075. if rel.GetTo().IsParameterized():
  1076. isParameterized = True
  1077. break
  1078. if not isParameterized:
  1079. for rel in self.GetRelations('to'):
  1080. if rel.GetFrom().IsParameterized():
  1081. isParameterized = True
  1082. break
  1083. if isParameterized:
  1084. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1085. subkey = ('width', 'parameterized')))
  1086. else:
  1087. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1088. subkey = ('width', 'default')))
  1089. pen = wx.Pen(wx.BLACK, width, wx.SOLID)
  1090. self.SetPen(pen)
  1091. def SetLabel(self):
  1092. """!Update text"""
  1093. self.ClearText()
  1094. name = []
  1095. for rel in self.GetRelations():
  1096. name.append(rel.GetLabel())
  1097. self.AddText('/'.join(name))
  1098. if self.value:
  1099. self.AddText(self.value)
  1100. else:
  1101. self.AddText(_('<not defined>'))
  1102. def Update(self):
  1103. """!Update action"""
  1104. self._setBrush()
  1105. self._setPen()
  1106. self.SetLabel()
  1107. class ModelRelation(ogl.LineShape):
  1108. """!Data - action relation"""
  1109. def __init__(self, parent, fromShape, toShape, param = ''):
  1110. self.fromShape = fromShape
  1111. self.toShape = toShape
  1112. self.param = param
  1113. self.parent = parent
  1114. self._points = None
  1115. if self.parent.GetCanvas():
  1116. ogl.LineShape.__init__(self)
  1117. def __del__(self):
  1118. if self in self.fromShape.rels:
  1119. self.fromShape.rels.remove(self)
  1120. if self in self.toShape.rels:
  1121. self.toShape.rels.remove(self)
  1122. def GetFrom(self):
  1123. """!Get id of 'from' shape"""
  1124. return self.fromShape
  1125. def GetTo(self):
  1126. """!Get id of 'to' shape"""
  1127. return self.toShape
  1128. def GetData(self):
  1129. """!Get related ModelData instance
  1130. @return ModelData instance
  1131. @return None if not found
  1132. """
  1133. if isinstance(self.fromShape, ModelData):
  1134. return self.fromShape
  1135. elif isinstance(self.toShape, ModelData):
  1136. return self.toShape
  1137. return None
  1138. def GetLabel(self):
  1139. """!Get parameter name"""
  1140. return self.param
  1141. def ResetShapes(self):
  1142. """!Reset related objects"""
  1143. self.fromShape.ResetControlPoints()
  1144. self.toShape.ResetControlPoints()
  1145. self.ResetControlPoints()
  1146. def SetControlPoints(self, points):
  1147. """!Set control points"""
  1148. self._points = points
  1149. def GetControlPoints(self):
  1150. """!Get list of control points"""
  1151. return self._points
  1152. def _setPen(self):
  1153. """!Set pen"""
  1154. pen = wx.Pen(wx.BLACK, 1, wx.SOLID)
  1155. self.SetPen(pen)
  1156. def OnDraw(self, dc):
  1157. """!Draw relation"""
  1158. self._setPen()
  1159. ogl.LineShape.OnDraw(self, dc)
  1160. def SetName(self, param):
  1161. self.param = param
  1162. class ModelItem(ModelObject):
  1163. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '', items = []):
  1164. """!Abstract class for loops and conditions"""
  1165. ModelObject.__init__(self, id, label)
  1166. self.parent = parent
  1167. def SetId(self, id):
  1168. """!Set loop id"""
  1169. self.id = id
  1170. def SetLabel(self, label=''):
  1171. """!Set loop text (condition)"""
  1172. self.label = label
  1173. self.ClearText()
  1174. self.AddText('(' + str(self.id) + ') ' + self.label)
  1175. def GetLog(self):
  1176. """!Get log info"""
  1177. if self.label:
  1178. return _("Condition: ") + self.label
  1179. else:
  1180. return _("Condition: not defined")
  1181. def AddRelation(self, rel):
  1182. """!Record relation"""
  1183. self.rels.append(rel)
  1184. def Clear(self):
  1185. """!Clear object, remove rels"""
  1186. self.rels = list()
  1187. class ModelLoop(ModelItem, ogl.RectangleShape):
  1188. def __init__(self, parent, x, y, id=-1, idx=-1, width = None, height = None, label = '', items = []):
  1189. """!Defines a loop"""
  1190. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1191. self.itemIds = list() # unordered
  1192. if not width:
  1193. width = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'width'))
  1194. if not height:
  1195. height = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'height'))
  1196. if self.parent.GetCanvas():
  1197. ogl.RectangleShape.__init__(self, width, height)
  1198. self.SetCanvas(self.parent)
  1199. self.SetX(x)
  1200. self.SetY(y)
  1201. self.SetPen(wx.BLACK_PEN)
  1202. self.SetCornerRadius(100)
  1203. self.SetLabel(label)
  1204. self._setBrush()
  1205. def _setBrush(self):
  1206. """!Set brush"""
  1207. if not self.isEnabled:
  1208. color = UserSettings.Get(group='modeler', key='disabled',
  1209. subkey='color')
  1210. else:
  1211. color = UserSettings.Get(group='modeler', key='loop',
  1212. subkey=('color', 'valid'))
  1213. wxColor = wx.Colour(color[0], color[1], color[2])
  1214. self.SetBrush(wx.Brush(wxColor))
  1215. def Enable(self, enabled = True):
  1216. """!Enable/disable action"""
  1217. for item in self.items:
  1218. if not isinstance(item, ModelAction):
  1219. continue
  1220. item.Enable(enabled)
  1221. ModelObject.Enable(self, enabled)
  1222. def Update(self):
  1223. self._setBrush()
  1224. def GetItems(self, items):
  1225. """!Get sorted items by id"""
  1226. result = list()
  1227. for item in items:
  1228. if item.GetId() in self.itemIds:
  1229. result.append(item)
  1230. return result
  1231. def SetItems(self, items):
  1232. """!Set items (id)"""
  1233. self.itemIds = items
  1234. def OnDraw(self, dc):
  1235. """!Draw loop in canvas"""
  1236. self._setBrush()
  1237. ogl.RectangleShape.Recentre(self, dc) # re-center text
  1238. ogl.RectangleShape.OnDraw(self, dc)
  1239. class ModelCondition(ModelItem, ogl.PolygonShape):
  1240. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '',
  1241. items = { 'if' : [], 'else' : [] }):
  1242. """!Defines a if-else condition"""
  1243. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1244. self.itemIds = {'if' : [], 'else': []}
  1245. if not width:
  1246. self.width = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'width'))
  1247. else:
  1248. self.width = width
  1249. if not height:
  1250. self.height = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'height'))
  1251. else:
  1252. self.height = height
  1253. if self.parent.GetCanvas():
  1254. ogl.PolygonShape.__init__(self)
  1255. points = [(0, - self.height / 2),
  1256. (self.width / 2, 0),
  1257. (0, self.height / 2),
  1258. (- self.width / 2, 0)]
  1259. self.Create(points)
  1260. self.SetCanvas(self.parent)
  1261. self.SetX(x)
  1262. self.SetY(y)
  1263. self.SetPen(wx.BLACK_PEN)
  1264. if label:
  1265. self.AddText('(' + str(self.id) + ') ' + label)
  1266. else:
  1267. self.AddText('(' + str(self.id) + ')')
  1268. def GetLabel(self):
  1269. """!Get name"""
  1270. return _("if-else")
  1271. def GetWidth(self):
  1272. """!Get object width"""
  1273. return self.width
  1274. def GetHeight(self):
  1275. """!Get object height"""
  1276. return self.height
  1277. def GetItems(self, items):
  1278. """!Get sorted items by id"""
  1279. result = {'if' : [], 'else': []}
  1280. for item in items:
  1281. if item.GetId() in self.itemIds['if']:
  1282. result['if'].append(item)
  1283. elif item.GetId() in self.itemIds['else']:
  1284. result['else'].append(item)
  1285. return result
  1286. def SetItems(self, items, branch = 'if'):
  1287. """!Set items (id)
  1288. @param items list of items
  1289. @param branch 'if' / 'else'
  1290. """
  1291. if branch in ['if', 'else']:
  1292. self.itemIds[branch] = items
  1293. class ModelComment(ModelObject, ogl.RectangleShape):
  1294. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = ''):
  1295. """!Defines a model comment"""
  1296. ModelObject.__init__(self, id, label)
  1297. if not width:
  1298. width = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'width'))
  1299. if not height:
  1300. height = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'height'))
  1301. if parent.GetCanvas():
  1302. ogl.RectangleShape.__init__(self, width, height)
  1303. self.SetCanvas(parent)
  1304. self.SetX(x)
  1305. self.SetY(y)
  1306. self._setPen()
  1307. self._setBrush()
  1308. self.SetLabel(label)
  1309. def _setBrush(self, running = False):
  1310. """!Set brush"""
  1311. color = UserSettings.Get(group='modeler', key='comment',
  1312. subkey='color')
  1313. wxColor = wx.Colour(color[0], color[1], color[2])
  1314. self.SetBrush(wx.Brush(wxColor))
  1315. def _setPen(self):
  1316. """!Set pen"""
  1317. pen = wx.Pen(wx.BLACK, 1, wx.DOT)
  1318. self.SetPen(pen)
  1319. def SetLabel(self, label=None):
  1320. """!Set label
  1321. @param label if None use command string instead
  1322. """
  1323. if label:
  1324. self.label = label
  1325. elif self.label:
  1326. label = self.label
  1327. else:
  1328. label = ''
  1329. idx = self.GetId()
  1330. self.ClearText()
  1331. self.AddText('(%d) %s' % (idx, label))
  1332. class ProcessModelFile:
  1333. """!Process GRASS model file (gxm)"""
  1334. def __init__(self, tree):
  1335. """!A ElementTree handler for the GXM XML file, as defined in
  1336. grass-gxm.dtd.
  1337. """
  1338. self.tree = tree
  1339. self.root = self.tree.getroot()
  1340. # list of actions, data
  1341. self.properties = dict()
  1342. self.variables = dict()
  1343. self.actions = list()
  1344. self.data = list()
  1345. self.loops = list()
  1346. self.conditions = list()
  1347. self.comments = list()
  1348. self._processWindow()
  1349. self._processProperties()
  1350. self._processVariables()
  1351. self._processItems()
  1352. self._processData()
  1353. def _filterValue(self, value):
  1354. """!Filter value
  1355. @param value
  1356. """
  1357. value = value.replace('&lt;', '<')
  1358. value = value.replace('&gt;', '>')
  1359. return value
  1360. def _getNodeText(self, node, tag, default = ''):
  1361. """!Get node text"""
  1362. p = node.find(tag)
  1363. if p is not None:
  1364. if p.text:
  1365. return utils.normalize_whitespace(p.text)
  1366. else:
  1367. return ''
  1368. return default
  1369. def _processWindow(self):
  1370. """!Process window properties"""
  1371. node = self.root.find('window')
  1372. if node is None:
  1373. self.pos = self.size = None
  1374. return
  1375. self.pos, self.size = self._getDim(node)
  1376. def _processProperties(self):
  1377. """!Process model properties"""
  1378. node = self.root.find('properties')
  1379. if node is None:
  1380. return
  1381. for key in ('name', 'description', 'author'):
  1382. self._processProperty(node, key)
  1383. for f in node.findall('flag'):
  1384. name = f.get('name', '')
  1385. if name == 'overwrite':
  1386. self.properties['overwrite'] = True
  1387. def _processProperty(self, pnode, name):
  1388. """!Process given property"""
  1389. node = pnode.find(name)
  1390. if node is not None:
  1391. self.properties[name] = node.text
  1392. else:
  1393. self.properties[name] = ''
  1394. def _processVariables(self):
  1395. """!Process model variables"""
  1396. vnode = self.root.find('variables')
  1397. if vnode is None:
  1398. return
  1399. for node in vnode.findall('variable'):
  1400. name = node.get('name', '')
  1401. if not name:
  1402. continue # should not happen
  1403. self.variables[name] = { 'type' : node.get('type', 'string') }
  1404. for key in ('description', 'value'):
  1405. self._processVariable(node, name, key)
  1406. def _processVariable(self, pnode, name, key):
  1407. """!Process given variable"""
  1408. node = pnode.find(key)
  1409. if node is not None:
  1410. if node.text:
  1411. self.variables[name][key] = node.text
  1412. def _processItems(self):
  1413. """!Process model items (actions, loops, conditions)"""
  1414. self._processActions()
  1415. self._processLoops()
  1416. self._processConditions()
  1417. self._processComments()
  1418. def _processActions(self):
  1419. """!Process model file"""
  1420. for action in self.root.findall('action'):
  1421. pos, size = self._getDim(action)
  1422. disabled = False
  1423. task = action.find('task')
  1424. if task is not None:
  1425. if task.find('disabled') is not None:
  1426. disabled = True
  1427. task = self._processTask(task)
  1428. else:
  1429. task = None
  1430. aId = int(action.get('id', -1))
  1431. label = action.get('name')
  1432. comment = action.find('comment')
  1433. if comment is not None:
  1434. commentString = comment.text
  1435. else:
  1436. commentString = ''
  1437. self.actions.append({ 'pos' : pos,
  1438. 'size' : size,
  1439. 'task' : task,
  1440. 'id' : aId,
  1441. 'disabled' : disabled,
  1442. 'label' : label,
  1443. 'comment' : commentString})
  1444. def _getDim(self, node):
  1445. """!Get position and size of shape"""
  1446. pos = size = None
  1447. posAttr = node.get('pos', None)
  1448. if posAttr:
  1449. posVal = map(int, posAttr.split(','))
  1450. try:
  1451. pos = (posVal[0], posVal[1])
  1452. except:
  1453. pos = None
  1454. sizeAttr = node.get('size', None)
  1455. if sizeAttr:
  1456. sizeVal = map(int, sizeAttr.split(','))
  1457. try:
  1458. size = (sizeVal[0], sizeVal[1])
  1459. except:
  1460. size = None
  1461. return pos, size
  1462. def _processData(self):
  1463. """!Process model file"""
  1464. for data in self.root.findall('data'):
  1465. pos, size = self._getDim(data)
  1466. param = data.find('data-parameter')
  1467. prompt = value = None
  1468. if param is not None:
  1469. prompt = param.get('prompt', None)
  1470. value = self._filterValue(self._getNodeText(param, 'value'))
  1471. if data.find('intermediate') is None:
  1472. intermediate = False
  1473. else:
  1474. intermediate = True
  1475. rels = list()
  1476. for rel in data.findall('relation'):
  1477. defrel = { 'id' : int(rel.get('id', -1)),
  1478. 'dir' : rel.get('dir', 'to'),
  1479. 'name' : rel.get('name', '') }
  1480. points = list()
  1481. for point in rel.findall('point'):
  1482. x = self._filterValue(self._getNodeText(point, 'x'))
  1483. y = self._filterValue(self._getNodeText(point, 'y'))
  1484. points.append((float(x), float(y)))
  1485. defrel['points'] = points
  1486. rels.append(defrel)
  1487. self.data.append({ 'pos' : pos,
  1488. 'size': size,
  1489. 'prompt' : prompt,
  1490. 'value' : value,
  1491. 'intermediate' : intermediate,
  1492. 'rels' : rels })
  1493. def _processTask(self, node):
  1494. """!Process task
  1495. @return grassTask instance
  1496. @return None on error
  1497. """
  1498. cmd = list()
  1499. parameterized = list()
  1500. name = node.get('name', None)
  1501. if not name:
  1502. return None
  1503. cmd.append(name)
  1504. # flags
  1505. for f in node.findall('flag'):
  1506. flag = f.get('name', '')
  1507. if f.get('parameterized', '0') == '1':
  1508. parameterized.append(('flag', flag))
  1509. if f.get('value', '1') == '0':
  1510. continue
  1511. if len(flag) > 1:
  1512. cmd.append('--' + flag)
  1513. else:
  1514. cmd.append('-' + flag)
  1515. # parameters
  1516. for p in node.findall('parameter'):
  1517. name = p.get('name', '')
  1518. if p.find('parameterized') is not None:
  1519. parameterized.append(('param', name))
  1520. cmd.append('%s=%s' % (name,
  1521. self._filterValue(self._getNodeText(p, 'value'))))
  1522. task, err = GUI(show = None, checkError = True).ParseCommand(cmd = cmd)
  1523. if err:
  1524. GWarning(os.linesep.join(err))
  1525. for opt, name in parameterized:
  1526. if opt == 'flag':
  1527. task.set_flag(name, True, element = 'parameterized')
  1528. else:
  1529. task.set_param(name, True, element = 'parameterized')
  1530. return task
  1531. def _processLoops(self):
  1532. """!Process model loops"""
  1533. for node in self.root.findall('loop'):
  1534. pos, size = self._getDim(node)
  1535. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1536. aid = list()
  1537. for anode in node.findall('item'):
  1538. try:
  1539. aid.append(int(anode.text))
  1540. except ValueError:
  1541. pass
  1542. self.loops.append({ 'pos' : pos,
  1543. 'size' : size,
  1544. 'text' : text,
  1545. 'id' : int(node.get('id', -1)),
  1546. 'items' : aid })
  1547. def _processConditions(self):
  1548. """!Process model conditions"""
  1549. for node in self.root.findall('if-else'):
  1550. pos, size = self._getDim(node)
  1551. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1552. aid = { 'if' : list(),
  1553. 'else' : list() }
  1554. for b in aid.keys():
  1555. bnode = node.find(b)
  1556. if bnode is None:
  1557. continue
  1558. for anode in bnode.findall('item'):
  1559. try:
  1560. aid[b].append(int(anode.text))
  1561. except ValueError:
  1562. pass
  1563. self.conditions.append({ 'pos' : pos,
  1564. 'size' : size,
  1565. 'text' : text,
  1566. 'id' : int(node.get('id', -1)),
  1567. 'items' : aid })
  1568. def _processComments(self):
  1569. """!Process model comments"""
  1570. for node in self.root.findall('comment'):
  1571. pos, size = self._getDim(node)
  1572. text = self._filterValue(node.text)
  1573. self.comments.append({ 'pos' : pos,
  1574. 'size' : size,
  1575. 'text' : text,
  1576. 'id' : int(node.get('id', -1)),
  1577. 'text' : text })
  1578. class WriteModelFile:
  1579. """!Generic class for writing model file"""
  1580. def __init__(self, fd, model):
  1581. self.fd = fd
  1582. self.model = model
  1583. self.properties = model.GetProperties()
  1584. self.variables = model.GetVariables()
  1585. self.items = model.GetItems()
  1586. self.indent = 0
  1587. self._header()
  1588. self._window()
  1589. self._properties()
  1590. self._variables()
  1591. self._items()
  1592. dataList = list()
  1593. for action in model.GetItems(objType = ModelAction):
  1594. for rel in action.GetRelations():
  1595. dataItem = rel.GetData()
  1596. if dataItem not in dataList:
  1597. dataList.append(dataItem)
  1598. self._data(dataList)
  1599. self._footer()
  1600. def _filterValue(self, value):
  1601. """!Escapes value to be stored in XML.
  1602. @param value string to be escaped as XML
  1603. @returns a XML-valid string
  1604. """
  1605. value = saxutils.escape(value)
  1606. return value
  1607. def _header(self):
  1608. """!Write header"""
  1609. self.fd.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
  1610. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1611. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1612. self.indent += 4
  1613. def _footer(self):
  1614. """!Write footer"""
  1615. self.indent -= 4
  1616. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1617. def _window(self):
  1618. """!Write window properties"""
  1619. canvas = self.model.GetCanvas()
  1620. if canvas is None:
  1621. return
  1622. win = canvas.parent
  1623. pos = win.GetPosition()
  1624. size = win.GetSize()
  1625. self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' % \
  1626. (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
  1627. def _properties(self):
  1628. """!Write model properties"""
  1629. self.fd.write('%s<properties>\n' % (' ' * self.indent))
  1630. self.indent += 4
  1631. if self.properties['name']:
  1632. self.fd.write('%s<name>%s</name>\n' % (' ' * self.indent, EncodeString(self.properties['name'])))
  1633. if self.properties['description']:
  1634. self.fd.write('%s<description>%s</description>\n' % (' ' * self.indent,
  1635. EncodeString(self.properties['description'])))
  1636. if self.properties['author']:
  1637. self.fd.write('%s<author>%s</author>\n' % (' ' * self.indent,
  1638. EncodeString(self.properties['author'])))
  1639. if 'overwrite' in self.properties and \
  1640. self.properties['overwrite']:
  1641. self.fd.write('%s<flag name="overwrite" />\n' % (' ' * self.indent))
  1642. self.indent -= 4
  1643. self.fd.write('%s</properties>\n' % (' ' * self.indent))
  1644. def _variables(self):
  1645. """!Write model variables"""
  1646. if not self.variables:
  1647. return
  1648. self.fd.write('%s<variables>\n' % (' ' * self.indent))
  1649. self.indent += 4
  1650. for name, values in self.variables.iteritems():
  1651. self.fd.write('%s<variable name="%s" type="%s">\n' % \
  1652. (' ' * self.indent, EncodeString(name), values['type']))
  1653. self.indent += 4
  1654. if 'value' in values:
  1655. self.fd.write('%s<value>%s</value>\n' % \
  1656. (' ' * self.indent, EncodeString(values['value'])))
  1657. if 'description' in values:
  1658. self.fd.write('%s<description>%s</description>\n' % \
  1659. (' ' * self.indent, EncodeString(values['description'])))
  1660. self.indent -= 4
  1661. self.fd.write('%s</variable>\n' % (' ' * self.indent))
  1662. self.indent -= 4
  1663. self.fd.write('%s</variables>\n' % (' ' * self.indent))
  1664. def _items(self):
  1665. """!Write actions/loops/conditions"""
  1666. for item in self.items:
  1667. if isinstance(item, ModelAction):
  1668. self._action(item)
  1669. elif isinstance(item, ModelLoop):
  1670. self._loop(item)
  1671. elif isinstance(item, ModelCondition):
  1672. self._condition(item)
  1673. elif isinstance(item, ModelComment):
  1674. self._comment(item)
  1675. def _action(self, action):
  1676. """!Write actions"""
  1677. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1678. (' ' * self.indent, action.GetId(), EncodeString(action.GetLabel()), action.GetX(), action.GetY(),
  1679. action.GetWidth(), action.GetHeight()))
  1680. self.indent += 4
  1681. comment = action.GetComment()
  1682. if comment:
  1683. self.fd.write('%s<comment>%s</comment>\n' % (' ' * self.indent, EncodeString(comment)))
  1684. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1685. self.indent += 4
  1686. if not action.IsEnabled():
  1687. self.fd.write('%s<disabled />\n' % (' ' * self.indent))
  1688. for key, val in action.GetParams().iteritems():
  1689. if key == 'flags':
  1690. for f in val:
  1691. if f.get('value', False) or f.get('parameterized', False):
  1692. if f.get('parameterized', False):
  1693. if f.get('value', False) == False:
  1694. self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
  1695. (' ' * self.indent, f.get('name', '')))
  1696. else:
  1697. self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
  1698. (' ' * self.indent, f.get('name', '')))
  1699. else:
  1700. self.fd.write('%s<flag name="%s" />\n' %
  1701. (' ' * self.indent, f.get('name', '')))
  1702. else: # parameter
  1703. for p in val:
  1704. if not p.get('value', '') and not p.get('parameterized', False):
  1705. continue
  1706. self.fd.write('%s<parameter name="%s">\n' %
  1707. (' ' * self.indent, p.get('name', '')))
  1708. self.indent += 4
  1709. if p.get('parameterized', False):
  1710. self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
  1711. self.fd.write('%s<value>%s</value>\n' %
  1712. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1713. self.indent -= 4
  1714. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1715. self.indent -= 4
  1716. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1717. self.indent -= 4
  1718. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1719. def _data(self, dataList):
  1720. """!Write data"""
  1721. for data in dataList:
  1722. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1723. (' ' * self.indent, data.GetX(), data.GetY(),
  1724. data.GetWidth(), data.GetHeight()))
  1725. self.indent += 4
  1726. self.fd.write('%s<data-parameter prompt="%s">\n' % \
  1727. (' ' * self.indent, data.GetPrompt()))
  1728. self.indent += 4
  1729. self.fd.write('%s<value>%s</value>\n' %
  1730. (' ' * self.indent, self._filterValue(data.GetValue())))
  1731. self.indent -= 4
  1732. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1733. if data.IsIntermediate():
  1734. self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
  1735. # relations
  1736. for ft in ('from', 'to'):
  1737. for rel in data.GetRelations(ft):
  1738. if ft == 'from':
  1739. aid = rel.GetTo().GetId()
  1740. else:
  1741. aid = rel.GetFrom().GetId()
  1742. self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' % \
  1743. (' ' * self.indent, ft, aid, rel.GetLabel()))
  1744. self.indent += 4
  1745. for point in rel.GetLineControlPoints()[1:-1]:
  1746. self.fd.write('%s<point>\n' % (' ' * self.indent))
  1747. self.indent += 4
  1748. x, y = point.Get()
  1749. self.fd.write('%s<x>%d</x>\n' % (' ' * self.indent, int(x)))
  1750. self.fd.write('%s<y>%d</y>\n' % (' ' * self.indent, int(y)))
  1751. self.indent -= 4
  1752. self.fd.write('%s</point>\n' % (' ' * self.indent))
  1753. self.indent -= 4
  1754. self.fd.write('%s</relation>\n' % (' ' * self.indent))
  1755. self.indent -= 4
  1756. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1757. def _loop(self, loop):
  1758. """!Write loops"""
  1759. self.fd.write('%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1760. (' ' * self.indent, loop.GetId(), loop.GetX(), loop.GetY(),
  1761. loop.GetWidth(), loop.GetHeight()))
  1762. self.indent += 4
  1763. cond = loop.GetLabel()
  1764. if cond:
  1765. self.fd.write('%s<condition>%s</condition>\n' %
  1766. (' ' * self.indent, self._filterValue(cond)))
  1767. for item in loop.GetItems(self.model.GetItems(objType=ModelAction)):
  1768. self.fd.write('%s<item>%d</item>\n' %
  1769. (' ' * self.indent, item.GetId()))
  1770. self.indent -= 4
  1771. self.fd.write('%s</loop>\n' % (' ' * self.indent))
  1772. def _condition(self, condition):
  1773. """!Write conditions"""
  1774. bbox = condition.GetBoundingBoxMin()
  1775. self.fd.write('%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1776. (' ' * self.indent, condition.GetId(), condition.GetX(), condition.GetY(),
  1777. bbox[0], bbox[1]))
  1778. text = condition.GetLabel()
  1779. self.indent += 4
  1780. if text:
  1781. self.fd.write('%s<condition>%s</condition>\n' %
  1782. (' ' * self.indent, self._filterValue(text)))
  1783. items = condition.GetItems()
  1784. for b in items.keys():
  1785. if len(items[b]) < 1:
  1786. continue
  1787. self.fd.write('%s<%s>\n' % (' ' * self.indent, b))
  1788. self.indent += 4
  1789. for item in items[b]:
  1790. self.fd.write('%s<item>%d</item>\n' %
  1791. (' ' * self.indent, item.GetId()))
  1792. self.indent -= 4
  1793. self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
  1794. self.indent -= 4
  1795. self.fd.write('%s</if-else>\n' % (' ' * self.indent))
  1796. def _comment(self, comment):
  1797. """!Write comment"""
  1798. self.fd.write('%s<comment id="%d" pos="%d,%d" size="%d,%d">%s</comment>\n' % \
  1799. (' ' * self.indent, comment.GetId(), comment.GetX(), comment.GetY(),
  1800. comment.GetWidth(), comment.GetHeight(), EncodeString(comment.GetLabel())))
  1801. class WritePythonFile:
  1802. def __init__(self, fd, model):
  1803. """!Class for exporting model to Python script
  1804. @param fd file desciptor
  1805. """
  1806. self.fd = fd
  1807. self.model = model
  1808. self.indent = 4
  1809. self._writePython()
  1810. def _writePython(self):
  1811. """!Write model to file"""
  1812. properties = self.model.GetProperties()
  1813. self.fd.write(
  1814. r"""#!/usr/bin/env python
  1815. #
  1816. #%s
  1817. #
  1818. # MODULE: %s
  1819. #
  1820. # AUTHOR(S): %s
  1821. #
  1822. # PURPOSE: %s
  1823. #
  1824. # DATE: %s
  1825. #
  1826. #%s
  1827. """ % ('#' * 77,
  1828. EncodeString(properties['name']),
  1829. EncodeString(properties['author']),
  1830. EncodeString('\n# '.join(properties['description'].splitlines())),
  1831. time.asctime(),
  1832. '#' * 77))
  1833. self.fd.write(
  1834. r"""
  1835. import sys
  1836. import os
  1837. import atexit
  1838. from grass.script import parser, run_command
  1839. """)
  1840. # cleanup()
  1841. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  1842. self.fd.write(
  1843. r"""
  1844. def cleanup():
  1845. """)
  1846. if rast:
  1847. self.fd.write(
  1848. r""" grass.run_command('g.remove',
  1849. rast=%s)
  1850. """ % ','.join(map(lambda x: "'" + x + "'", rast)))
  1851. if vect:
  1852. self.fd.write(
  1853. r""" grass.run_command('g.remove',
  1854. vect = %s)
  1855. """ % ','.join(map(lambda x: "'" + x + "'", vect)))
  1856. if rast3d:
  1857. self.fd.write(
  1858. r""" grass.run_command('g.remove',
  1859. rast3d = %s)
  1860. """ % ','.join(map(lambda x: "'" + x + "'", rast3d)))
  1861. if not rast and not vect and not rast3d:
  1862. self.fd.write(' pass\n')
  1863. self.fd.write("\ndef main():\n")
  1864. for item in self.model.GetItems():
  1865. self._writePythonItem(item)
  1866. self.fd.write("\n return 0\n")
  1867. self.fd.write(
  1868. r"""
  1869. if __name__ == "__main__":
  1870. options, flags = grass.parser()
  1871. atexit.register(cleanup)
  1872. sys.exit(main())
  1873. """)
  1874. def _writePythonItem(self, item, ignoreBlock = True, variables = []):
  1875. """!Write model object to Python file"""
  1876. if isinstance(item, ModelAction):
  1877. if ignoreBlock and item.GetBlockId(): # ignore items in loops of conditions
  1878. return
  1879. self._writePythonAction(item, variables = variables)
  1880. elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition):
  1881. # substitute condition
  1882. variables = self.model.GetVariables()
  1883. cond = item.GetLabel()
  1884. for variable in variables:
  1885. pattern = re.compile('%' + variable)
  1886. if pattern.search(cond):
  1887. value = variables[variable].get('value', '')
  1888. if variables[variable].get('type', 'string') == 'string':
  1889. value = '"' + value + '"'
  1890. cond = pattern.sub(value, cond)
  1891. if isinstance(item, ModelLoop):
  1892. condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
  1893. cond = "%sfor %s in " % (' ' * self.indent, condVar)
  1894. if condText[0] == '`' and condText[-1] == '`':
  1895. task = GUI(show = None).ParseCommand(cmd = utils.split(condText[1:-1]))
  1896. cond += "grass.read_command("
  1897. cond += self._getPythonActionCmd(task, len(cond), variables = [condVar]) + ".splitlines()"
  1898. else:
  1899. cond += condText
  1900. self.fd.write('%s:\n' % cond)
  1901. self.indent += 4
  1902. for action in item.GetItems(self.model.GetItems(objType=ModelAction)):
  1903. self._writePythonItem(action, ignoreBlock = False, variables = [condVar])
  1904. self.indent -= 4
  1905. if isinstance(item, ModelCondition):
  1906. self.fd.write('%sif %s:\n' % (' ' * self.indent, cond))
  1907. self.indent += 4
  1908. condItems = item.GetItems()
  1909. for action in condItems['if']:
  1910. self._writePythonItem(action, ignoreBlock = False)
  1911. if condItems['else']:
  1912. self.indent -= 4
  1913. self.fd.write('%selse:\n' % (' ' * self.indent))
  1914. self.indent += 4
  1915. for action in condItems['else']:
  1916. self._writePythonItem(action, ignoreBlock = False)
  1917. self.indent += 4
  1918. if isinstance(item, ModelComment):
  1919. self._writePythonComment(item)
  1920. def _writePythonAction(self, item, variables = []):
  1921. """!Write model action to Python file"""
  1922. task = GUI(show = None).ParseCommand(cmd = item.GetLog(string = False, substitute = self.model.GetVariables()))
  1923. strcmd = "%sgrass.run_command(" % (' ' * self.indent)
  1924. self.fd.write(strcmd + self._getPythonActionCmd(task, len(strcmd), variables) + '\n')
  1925. def _getPythonActionCmd(self, task, cmdIndent, variables = []):
  1926. opts = task.get_options()
  1927. ret = ''
  1928. flags = ''
  1929. params = list()
  1930. for f in opts['flags']:
  1931. if f.get('value', False):
  1932. name = f.get('name', '')
  1933. if len(name) > 1:
  1934. params.append('%s = True' % name)
  1935. else:
  1936. flags += name
  1937. for p in opts['params']:
  1938. name = p.get('name', None)
  1939. value = p.get('value', None)
  1940. if name and value:
  1941. ptype = p.get('type', 'string')
  1942. if value[0] == '%':
  1943. params.append("%s = %s" % (name, value[1:]))
  1944. elif ptype == 'string':
  1945. params.append('%s = "%s"' % (name, value))
  1946. else:
  1947. params.append("%s = %s" % (name, value))
  1948. ret += '"%s"' % task.get_name()
  1949. if flags:
  1950. ret += ",\n%sflags = '%s'" % (' ' * cmdIndent, flags)
  1951. if len(params) > 0:
  1952. ret += ",\n"
  1953. for opt in params[:-1]:
  1954. ret += "%s%s,\n" % (' ' * cmdIndent, opt)
  1955. ret += "%s%s)" % (' ' * cmdIndent, params[-1])
  1956. else:
  1957. ret += ")"
  1958. return ret
  1959. def _writePythonComment(self, item):
  1960. """!Write model comment to Python file"""
  1961. for line in item.GetLabel().splitlines():
  1962. self.fd.write('#' + line + '\n')
  1963. class ModelParamDialog(wx.Dialog):
  1964. def __init__(self, parent, params, id = wx.ID_ANY, title = _("Model parameters"),
  1965. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  1966. """!Model parameters dialog
  1967. """
  1968. self.parent = parent
  1969. self.params = params
  1970. self.tasks = list() # list of tasks/pages
  1971. wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
  1972. self.notebook = GNotebook(parent = self,
  1973. style = globalvar.FNPageDStyle)
  1974. panel = self._createPages()
  1975. wx.CallAfter(self.notebook.SetSelection, 0)
  1976. # intermediate data?
  1977. self.interData = wx.CheckBox(parent = self, label = _("Delete intermediate data when finish"))
  1978. self.interData.SetValue(True)
  1979. rast, vect, rast3d, msg = self.parent.GetModel().GetIntermediateData()
  1980. if not rast and not vect and not rast3d:
  1981. self.interData.Hide()
  1982. self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  1983. self.btnRun = wx.Button(parent = self, id = wx.ID_OK,
  1984. label = _("&Run"))
  1985. self.btnRun.SetDefault()
  1986. self._layout()
  1987. size = self.GetBestSize()
  1988. self.SetMinSize(size)
  1989. self.SetSize((size.width, size.height +
  1990. panel.constrained_size[1] -
  1991. panel.panelMinHeight))
  1992. def _layout(self):
  1993. btnSizer = wx.StdDialogButtonSizer()
  1994. btnSizer.AddButton(self.btnCancel)
  1995. btnSizer.AddButton(self.btnRun)
  1996. btnSizer.Realize()
  1997. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1998. mainSizer.Add(item = self.notebook, proportion = 1,
  1999. flag = wx.EXPAND)
  2000. if self.interData.IsShown():
  2001. mainSizer.Add(item = self.interData, proportion = 0,
  2002. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2003. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  2004. style = wx.LI_HORIZONTAL),
  2005. proportion = 0,
  2006. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  2007. mainSizer.Add(item = btnSizer, proportion = 0,
  2008. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2009. self.SetSizer(mainSizer)
  2010. mainSizer.Fit(self)
  2011. def _createPages(self):
  2012. """!Create for each parameterized module its own page"""
  2013. nameOrdered = [''] * len(self.params.keys())
  2014. for name, params in self.params.iteritems():
  2015. nameOrdered[params['idx']] = name
  2016. for name in nameOrdered:
  2017. params = self.params[name]
  2018. panel = self._createPage(name, params)
  2019. if name == 'variables':
  2020. name = _('Variables')
  2021. self.notebook.AddPage(page = panel, text = name)
  2022. return panel
  2023. def _createPage(self, name, params):
  2024. """!Define notebook page"""
  2025. if name in globalvar.grassCmd:
  2026. task = gtask.grassTask(name)
  2027. else:
  2028. task = gtask.grassTask()
  2029. task.flags = params['flags']
  2030. task.params = params['params']
  2031. panel = CmdPanel(parent = self, id = wx.ID_ANY, task = task,
  2032. giface = GraphicalModelerGrassInterface(self.parent.GetModel()))
  2033. self.tasks.append(task)
  2034. return panel
  2035. def GetErrors(self):
  2036. """!Check for errors, get list of messages"""
  2037. errList = list()
  2038. for task in self.tasks:
  2039. errList += task.get_cmd_error()
  2040. return errList
  2041. def DeleteIntermediateData(self):
  2042. """!Check if to detele intermediate data"""
  2043. if self.interData.IsShown() and self.interData.IsChecked():
  2044. return True
  2045. return False