model.py 87 KB

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