model.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496
  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.DividedShape):
  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.DividedShape.__init__(self, width, height)
  783. self.regionLabel = ogl.ShapeRegion()
  784. self.regionLabel.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ | ogl.FORMAT_CENTRE_VERT)
  785. self.AddRegion(self.regionLabel)
  786. self.regionComment = None
  787. self.SetCanvas(self.parent)
  788. self.SetX(x)
  789. self.SetY(y)
  790. self._setPen()
  791. self._setBrush()
  792. self.SetLabel(label)
  793. if comment:
  794. self.SetComment(comment)
  795. self.SetRegionSizes()
  796. self.ReformatRegions()
  797. if self.task:
  798. self.SetValid(self.task.get_options())
  799. def _setBrush(self, running = False):
  800. """!Set brush"""
  801. if running:
  802. color = UserSettings.Get(group='modeler', key='action',
  803. subkey=('color', 'running'))
  804. elif not self.isEnabled:
  805. color = UserSettings.Get(group='modeler', key='disabled',
  806. subkey='color')
  807. elif self.isValid:
  808. color = UserSettings.Get(group='modeler', key='action',
  809. subkey=('color', 'valid'))
  810. else:
  811. color = UserSettings.Get(group='modeler', key='action',
  812. subkey=('color', 'invalid'))
  813. wxColor = wx.Colour(color[0], color[1], color[2])
  814. self.SetBrush(wx.Brush(wxColor))
  815. def _setPen(self):
  816. """!Set pen"""
  817. if self.isParameterized:
  818. width = int(UserSettings.Get(group='modeler', key='action',
  819. subkey=('width', 'parameterized')))
  820. else:
  821. width = int(UserSettings.Get(group='modeler', key='action',
  822. subkey=('width', 'default')))
  823. if self.isEnabled:
  824. style = wx.SOLID
  825. else:
  826. style = wx.DOT
  827. pen = wx.Pen(wx.BLACK, width, style)
  828. self.SetPen(pen)
  829. def ReformatRegions(self):
  830. rnum = 0
  831. canvas = self.parent.GetCanvas()
  832. dc = wx.ClientDC(canvas) # used for measuring
  833. for region in self.GetRegions():
  834. text = region.GetText()
  835. self.FormatText(dc, text, rnum)
  836. rnum += 1
  837. def OnSizingEndDragLeft(self, pt, x, y, keys, attch):
  838. ogl.DividedShape.OnSizingEndDragLeft(self, pt, x, y, keys, attch)
  839. self.SetRegionSizes()
  840. self.ReformatRegions()
  841. self.GetCanvas().Refresh()
  842. def SetLabel(self, label=None):
  843. """!Set label
  844. @param label if None use command string instead
  845. """
  846. if label:
  847. self.label = label
  848. elif self.label:
  849. label = self.label
  850. else:
  851. try:
  852. label = self.task.get_cmd(ignoreErrors = True)[0]
  853. except:
  854. label = _("unknown")
  855. idx = self.GetId()
  856. self.regionLabel.SetText('(%d) %s' % (idx, label))
  857. def SetComment(self, comment):
  858. """!Set comment"""
  859. if self.regionComment is None:
  860. self.SetHeight(self.GetHeight() * 2)
  861. self.regionComment = ogl.ShapeRegion()
  862. self.regionComment.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ)
  863. font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
  864. font.SetStyle(wx.ITALIC)
  865. self.regionComment.SetFont(font)
  866. self.AddRegion(self.regionComment)
  867. self.regionLabel.SetProportions(0.0, 0.3)
  868. self.comment = comment
  869. self.regionComment.SetText(comment)
  870. self.SetRegionSizes()
  871. self.ReformatRegions()
  872. def GetComment(self):
  873. """!Get comment"""
  874. return self.comment
  875. def SetProperties(self, params, propwin):
  876. """!Record properties dialog"""
  877. self.task.params = params['params']
  878. self.task.flags = params['flags']
  879. self.propWin = propwin
  880. def GetPropDialog(self):
  881. """!Get properties dialog"""
  882. return self.propWin
  883. def GetLog(self, string = True, substitute = None):
  884. """!Get logging info
  885. @param string True to get cmd as a string otherwise a list
  886. @param substitute dictionary of parameter to substitute or None
  887. """
  888. cmd = self.task.get_cmd(ignoreErrors = True, ignoreRequired = True,
  889. ignoreDefault = False)
  890. # substitute variables
  891. if substitute:
  892. variables = []
  893. if 'variables' in substitute:
  894. for p in substitute['variables']['params']:
  895. variables.append(p.get('name', ''))
  896. else:
  897. variables = self.parent.GetVariables()
  898. for variable in variables:
  899. pattern= re.compile('%' + variable)
  900. value = ''
  901. if substitute and 'variables' in substitute:
  902. for p in substitute['variables']['params']:
  903. if variable == p.get('name', ''):
  904. if p.get('type', 'string') == 'string':
  905. value = p.get('value', '')
  906. else:
  907. value = str(p.get('value', ''))
  908. break
  909. if not value:
  910. value = variables[variable].get('value', '')
  911. if not value:
  912. continue
  913. for idx in range(len(cmd)):
  914. if pattern.search(cmd[idx]):
  915. cmd[idx] = pattern.sub(value, cmd[idx])
  916. break
  917. idx += 1
  918. if string:
  919. if cmd is None:
  920. return ''
  921. else:
  922. return ' '.join(cmd)
  923. return cmd
  924. def GetLabel(self):
  925. """!Get name"""
  926. if self.label:
  927. return self.label
  928. cmd = self.task.get_cmd(ignoreErrors = True)
  929. if cmd and len(cmd) > 0:
  930. return cmd[0]
  931. return _('unknown')
  932. def GetParams(self, dcopy = False):
  933. """!Get dictionary of parameters"""
  934. if dcopy:
  935. return copy.deepcopy(self.task.get_options())
  936. return self.task.get_options()
  937. def GetTask(self):
  938. """!Get grassTask instance"""
  939. return self.task
  940. def SetParams(self, params):
  941. """!Set dictionary of parameters"""
  942. self.task.params = params['params']
  943. self.task.flags = params['flags']
  944. def MergeParams(self, params):
  945. """!Merge dictionary of parameters"""
  946. if 'flags' in params:
  947. for f in params['flags']:
  948. self.task.set_flag(f['name'],
  949. f.get('value', False))
  950. if 'params' in params:
  951. for p in params['params']:
  952. self.task.set_param(p['name'],
  953. p.get('value', ''))
  954. def SetValid(self, options):
  955. """!Set validity for action
  956. @param options dictionary with flags and params (gtask)
  957. """
  958. self.isValid = True
  959. self.isParameterized = False
  960. for f in options['flags']:
  961. if f.get('parameterized', False):
  962. self.IsParameterized = True
  963. break
  964. for p in options['params']:
  965. if self.isValid and p.get('required', False) and \
  966. p.get('value', '') == '' and \
  967. p.get('default', '') == '':
  968. self.isValid = False
  969. if not self.isParameterized and p.get('parameterized', False):
  970. self.isParameterized = True
  971. if self.parent.GetCanvas():
  972. self._setBrush()
  973. self._setPen()
  974. def IsValid(self):
  975. """!Check validity (all required parameters set)"""
  976. return self.isValid
  977. def IsParameterized(self):
  978. """!Check if action is parameterized"""
  979. return self.isParameterized
  980. def FindData(self, name):
  981. """!Find data item by name"""
  982. for rel in self.GetRelations():
  983. data = rel.GetData()
  984. if name == rel.GetLabel() and name in data.GetLabel():
  985. return data
  986. return None
  987. def Update(self, running = False):
  988. """!Update action"""
  989. if running:
  990. self._setBrush(running = True)
  991. else:
  992. self._setBrush()
  993. self._setPen()
  994. def OnDraw(self, dc):
  995. """!Draw action in canvas"""
  996. self._setBrush()
  997. self._setPen()
  998. ogl.RectangleShape.Recentre(self, dc) # re-center text
  999. ogl.RectangleShape.OnDraw(self, dc)
  1000. class ModelData(ModelObject, ogl.EllipseShape):
  1001. def __init__(self, parent, x, y, value = '', prompt = '', width = None, height = None):
  1002. """Data item class
  1003. @param parent window parent
  1004. @param x, y position of the shape
  1005. @param fname, tname list of parameter names from / to
  1006. @param value value
  1007. @param prompt type of GIS element
  1008. @param width,height dimension of the shape
  1009. """
  1010. ModelObject.__init__(self)
  1011. self.parent = parent
  1012. self.value = value
  1013. self.prompt = prompt
  1014. self.intermediate = False
  1015. self.propWin = None
  1016. if not width:
  1017. width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
  1018. if not height:
  1019. height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
  1020. if self.parent.GetCanvas():
  1021. ogl.EllipseShape.__init__(self, width, height)
  1022. self.SetCanvas(self.parent)
  1023. self.SetX(x)
  1024. self.SetY(y)
  1025. self._setPen()
  1026. self._setBrush()
  1027. self.SetLabel()
  1028. def IsIntermediate(self):
  1029. """!Checks if data item is intermediate"""
  1030. return self.intermediate
  1031. def SetIntermediate(self, im):
  1032. """!Set intermediate flag"""
  1033. self.intermediate = im
  1034. def OnDraw(self, dc):
  1035. self._setPen()
  1036. ogl.EllipseShape.OnDraw(self, dc)
  1037. def GetLog(self, string = True):
  1038. """!Get logging info"""
  1039. name = list()
  1040. for rel in self.GetRelations():
  1041. name.append(rel.GetLabel())
  1042. if name:
  1043. return '/'.join(name) + '=' + self.value + ' (' + self.prompt + ')'
  1044. else:
  1045. return self.value + ' (' + self.prompt + ')'
  1046. def GetLabel(self):
  1047. """!Get list of names"""
  1048. name = list()
  1049. for rel in self.GetRelations():
  1050. name.append(rel.GetLabel())
  1051. return name
  1052. def GetPrompt(self):
  1053. """!Get prompt"""
  1054. return self.prompt
  1055. def SetPrompt(self, prompt):
  1056. """!Set prompt
  1057. @param prompt
  1058. """
  1059. self.prompt = prompt
  1060. def GetValue(self):
  1061. """!Get value"""
  1062. return self.value
  1063. def SetValue(self, value):
  1064. """!Set value
  1065. @param value
  1066. """
  1067. self.value = value
  1068. self.SetLabel()
  1069. for direction in ('from', 'to'):
  1070. for rel in self.GetRelations(direction):
  1071. if direction == 'from':
  1072. action = rel.GetTo()
  1073. else:
  1074. action = rel.GetFrom()
  1075. task = GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
  1076. task.set_param(rel.GetLabel(), self.value)
  1077. action.SetParams(params = task.get_options())
  1078. def GetPropDialog(self):
  1079. """!Get properties dialog"""
  1080. return self.propWin
  1081. def SetPropDialog(self, win):
  1082. """!Get properties dialog"""
  1083. self.propWin = win
  1084. def _setBrush(self):
  1085. """!Set brush"""
  1086. if self.prompt == 'raster':
  1087. color = UserSettings.Get(group = 'modeler', key = 'data',
  1088. subkey = ('color', 'raster'))
  1089. elif self.prompt == 'raster3d':
  1090. color = UserSettings.Get(group = 'modeler', key = 'data',
  1091. subkey = ('color', 'raster3d'))
  1092. elif self.prompt == 'vector':
  1093. color = UserSettings.Get(group = 'modeler', key = 'data',
  1094. subkey = ('color', 'vector'))
  1095. else:
  1096. color = UserSettings.Get(group = 'modeler', key = 'action',
  1097. subkey = ('color', 'invalid'))
  1098. wxColor = wx.Colour(color[0], color[1], color[2])
  1099. self.SetBrush(wx.Brush(wxColor))
  1100. def _setPen(self):
  1101. """!Set pen"""
  1102. isParameterized = False
  1103. for rel in self.GetRelations('from'):
  1104. if rel.GetTo().IsParameterized():
  1105. isParameterized = True
  1106. break
  1107. if not isParameterized:
  1108. for rel in self.GetRelations('to'):
  1109. if rel.GetFrom().IsParameterized():
  1110. isParameterized = True
  1111. break
  1112. if isParameterized:
  1113. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1114. subkey = ('width', 'parameterized')))
  1115. else:
  1116. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1117. subkey = ('width', 'default')))
  1118. if self.intermediate:
  1119. style = wx.DOT
  1120. else:
  1121. style = wx.SOLID
  1122. pen = wx.Pen(wx.BLACK, width, style)
  1123. self.SetPen(pen)
  1124. def SetLabel(self):
  1125. """!Update text"""
  1126. self.ClearText()
  1127. name = []
  1128. for rel in self.GetRelations():
  1129. name.append(rel.GetLabel())
  1130. self.AddText('/'.join(name))
  1131. if self.value:
  1132. self.AddText(self.value)
  1133. else:
  1134. self.AddText(_('<not defined>'))
  1135. def Update(self):
  1136. """!Update action"""
  1137. self._setBrush()
  1138. self._setPen()
  1139. self.SetLabel()
  1140. class ModelRelation(ogl.LineShape):
  1141. """!Data - action relation"""
  1142. def __init__(self, parent, fromShape, toShape, param = ''):
  1143. self.fromShape = fromShape
  1144. self.toShape = toShape
  1145. self.param = param
  1146. self.parent = parent
  1147. self._points = None
  1148. if self.parent.GetCanvas():
  1149. ogl.LineShape.__init__(self)
  1150. def __del__(self):
  1151. if self in self.fromShape.rels:
  1152. self.fromShape.rels.remove(self)
  1153. if self in self.toShape.rels:
  1154. self.toShape.rels.remove(self)
  1155. def GetFrom(self):
  1156. """!Get id of 'from' shape"""
  1157. return self.fromShape
  1158. def GetTo(self):
  1159. """!Get id of 'to' shape"""
  1160. return self.toShape
  1161. def GetData(self):
  1162. """!Get related ModelData instance
  1163. @return ModelData instance
  1164. @return None if not found
  1165. """
  1166. if isinstance(self.fromShape, ModelData):
  1167. return self.fromShape
  1168. elif isinstance(self.toShape, ModelData):
  1169. return self.toShape
  1170. return None
  1171. def GetLabel(self):
  1172. """!Get parameter name"""
  1173. return self.param
  1174. def ResetShapes(self):
  1175. """!Reset related objects"""
  1176. self.fromShape.ResetControlPoints()
  1177. self.toShape.ResetControlPoints()
  1178. self.ResetControlPoints()
  1179. def SetControlPoints(self, points):
  1180. """!Set control points"""
  1181. self._points = points
  1182. def GetControlPoints(self):
  1183. """!Get list of control points"""
  1184. return self._points
  1185. def _setPen(self):
  1186. """!Set pen"""
  1187. pen = wx.Pen(wx.BLACK, 1, wx.SOLID)
  1188. self.SetPen(pen)
  1189. def OnDraw(self, dc):
  1190. """!Draw relation"""
  1191. self._setPen()
  1192. ogl.LineShape.OnDraw(self, dc)
  1193. def SetName(self, param):
  1194. self.param = param
  1195. class ModelItem(ModelObject):
  1196. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '', items = []):
  1197. """!Abstract class for loops and conditions"""
  1198. ModelObject.__init__(self, id, label)
  1199. self.parent = parent
  1200. def SetId(self, id):
  1201. """!Set loop id"""
  1202. self.id = id
  1203. def SetLabel(self, label=''):
  1204. """!Set loop text (condition)"""
  1205. self.label = label
  1206. self.ClearText()
  1207. self.AddText('(' + str(self.id) + ') ' + self.label)
  1208. def GetLog(self):
  1209. """!Get log info"""
  1210. if self.label:
  1211. return _("Condition: ") + self.label
  1212. else:
  1213. return _("Condition: not defined")
  1214. def AddRelation(self, rel):
  1215. """!Record relation"""
  1216. self.rels.append(rel)
  1217. def Clear(self):
  1218. """!Clear object, remove rels"""
  1219. self.rels = list()
  1220. class ModelLoop(ModelItem, ogl.RectangleShape):
  1221. def __init__(self, parent, x, y, id=-1, idx=-1, width = None, height = None, label = '', items = []):
  1222. """!Defines a loop"""
  1223. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1224. self.itemIds = list() # unordered
  1225. if not width:
  1226. width = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'width'))
  1227. if not height:
  1228. height = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'height'))
  1229. if self.parent.GetCanvas():
  1230. ogl.RectangleShape.__init__(self, width, height)
  1231. self.SetCanvas(self.parent)
  1232. self.SetX(x)
  1233. self.SetY(y)
  1234. self.SetPen(wx.BLACK_PEN)
  1235. self.SetCornerRadius(100)
  1236. self.SetLabel(label)
  1237. self._setBrush()
  1238. def _setBrush(self):
  1239. """!Set brush"""
  1240. if not self.isEnabled:
  1241. color = UserSettings.Get(group='modeler', key='disabled',
  1242. subkey='color')
  1243. else:
  1244. color = UserSettings.Get(group='modeler', key='loop',
  1245. subkey=('color', 'valid'))
  1246. wxColor = wx.Colour(color[0], color[1], color[2])
  1247. self.SetBrush(wx.Brush(wxColor))
  1248. def Enable(self, enabled = True):
  1249. """!Enable/disable action"""
  1250. for item in self.items:
  1251. if not isinstance(item, ModelAction):
  1252. continue
  1253. item.Enable(enabled)
  1254. ModelObject.Enable(self, enabled)
  1255. def Update(self):
  1256. self._setBrush()
  1257. def GetItems(self, items):
  1258. """!Get sorted items by id"""
  1259. result = list()
  1260. for item in items:
  1261. if item.GetId() in self.itemIds:
  1262. result.append(item)
  1263. return result
  1264. def SetItems(self, items):
  1265. """!Set items (id)"""
  1266. self.itemIds = items
  1267. def OnDraw(self, dc):
  1268. """!Draw loop in canvas"""
  1269. self._setBrush()
  1270. ogl.RectangleShape.Recentre(self, dc) # re-center text
  1271. ogl.RectangleShape.OnDraw(self, dc)
  1272. class ModelCondition(ModelItem, ogl.PolygonShape):
  1273. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '',
  1274. items = { 'if' : [], 'else' : [] }):
  1275. """!Defines a if-else condition"""
  1276. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1277. self.itemIds = {'if' : [], 'else': []}
  1278. if not width:
  1279. self.width = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'width'))
  1280. else:
  1281. self.width = width
  1282. if not height:
  1283. self.height = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'height'))
  1284. else:
  1285. self.height = height
  1286. if self.parent.GetCanvas():
  1287. ogl.PolygonShape.__init__(self)
  1288. points = [(0, - self.height / 2),
  1289. (self.width / 2, 0),
  1290. (0, self.height / 2),
  1291. (- self.width / 2, 0)]
  1292. self.Create(points)
  1293. self.SetCanvas(self.parent)
  1294. self.SetX(x)
  1295. self.SetY(y)
  1296. self.SetPen(wx.BLACK_PEN)
  1297. if label:
  1298. self.AddText('(' + str(self.id) + ') ' + label)
  1299. else:
  1300. self.AddText('(' + str(self.id) + ')')
  1301. def GetLabel(self):
  1302. """!Get name"""
  1303. return _("if-else")
  1304. def GetWidth(self):
  1305. """!Get object width"""
  1306. return self.width
  1307. def GetHeight(self):
  1308. """!Get object height"""
  1309. return self.height
  1310. def GetItems(self, items):
  1311. """!Get sorted items by id"""
  1312. result = {'if' : [], 'else': []}
  1313. for item in items:
  1314. if item.GetId() in self.itemIds['if']:
  1315. result['if'].append(item)
  1316. elif item.GetId() in self.itemIds['else']:
  1317. result['else'].append(item)
  1318. return result
  1319. def SetItems(self, items, branch = 'if'):
  1320. """!Set items (id)
  1321. @param items list of items
  1322. @param branch 'if' / 'else'
  1323. """
  1324. if branch in ['if', 'else']:
  1325. self.itemIds[branch] = items
  1326. class ModelComment(ModelObject, ogl.RectangleShape):
  1327. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = ''):
  1328. """!Defines a model comment"""
  1329. ModelObject.__init__(self, id, label)
  1330. if not width:
  1331. width = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'width'))
  1332. if not height:
  1333. height = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'height'))
  1334. if parent.GetCanvas():
  1335. ogl.RectangleShape.__init__(self, width, height)
  1336. self.SetCanvas(parent)
  1337. self.SetX(x)
  1338. self.SetY(y)
  1339. font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
  1340. font.SetStyle(wx.ITALIC)
  1341. self.SetFont(font)
  1342. self._setPen()
  1343. self._setBrush()
  1344. self.SetLabel(label)
  1345. def _setBrush(self, running = False):
  1346. """!Set brush"""
  1347. color = UserSettings.Get(group='modeler', key='comment',
  1348. subkey='color')
  1349. wxColor = wx.Colour(color[0], color[1], color[2])
  1350. self.SetBrush(wx.Brush(wxColor))
  1351. def _setPen(self):
  1352. """!Set pen"""
  1353. pen = wx.Pen(wx.BLACK, 1, wx.DOT)
  1354. self.SetPen(pen)
  1355. def SetLabel(self, label=None):
  1356. """!Set label
  1357. @param label if None use command string instead
  1358. """
  1359. if label:
  1360. self.label = label
  1361. elif self.label:
  1362. label = self.label
  1363. else:
  1364. label = ''
  1365. idx = self.GetId()
  1366. self.ClearText()
  1367. self.AddText('(%d) %s' % (idx, label))
  1368. def GetComment(self):
  1369. return self.GetLabel()
  1370. def SetComment(self, comment):
  1371. self.SetLabel(comment)
  1372. self.GetCanvas().Refresh()
  1373. class ProcessModelFile:
  1374. """!Process GRASS model file (gxm)"""
  1375. def __init__(self, tree):
  1376. """!A ElementTree handler for the GXM XML file, as defined in
  1377. grass-gxm.dtd.
  1378. """
  1379. self.tree = tree
  1380. self.root = self.tree.getroot()
  1381. # list of actions, data
  1382. self.properties = dict()
  1383. self.variables = dict()
  1384. self.actions = list()
  1385. self.data = list()
  1386. self.loops = list()
  1387. self.conditions = list()
  1388. self.comments = list()
  1389. self._processWindow()
  1390. self._processProperties()
  1391. self._processVariables()
  1392. self._processItems()
  1393. self._processData()
  1394. def _filterValue(self, value):
  1395. """!Filter value
  1396. @param value
  1397. """
  1398. value = value.replace('&lt;', '<')
  1399. value = value.replace('&gt;', '>')
  1400. return value
  1401. def _getNodeText(self, node, tag, default = ''):
  1402. """!Get node text"""
  1403. p = node.find(tag)
  1404. if p is not None:
  1405. if p.text:
  1406. return utils.normalize_whitespace(p.text)
  1407. else:
  1408. return ''
  1409. return default
  1410. def _processWindow(self):
  1411. """!Process window properties"""
  1412. node = self.root.find('window')
  1413. if node is None:
  1414. self.pos = self.size = None
  1415. return
  1416. self.pos, self.size = self._getDim(node)
  1417. def _processProperties(self):
  1418. """!Process model properties"""
  1419. node = self.root.find('properties')
  1420. if node is None:
  1421. return
  1422. for key in ('name', 'description', 'author'):
  1423. self._processProperty(node, key)
  1424. for f in node.findall('flag'):
  1425. name = f.get('name', '')
  1426. if name == 'overwrite':
  1427. self.properties['overwrite'] = True
  1428. def _processProperty(self, pnode, name):
  1429. """!Process given property"""
  1430. node = pnode.find(name)
  1431. if node is not None:
  1432. self.properties[name] = node.text
  1433. else:
  1434. self.properties[name] = ''
  1435. def _processVariables(self):
  1436. """!Process model variables"""
  1437. vnode = self.root.find('variables')
  1438. if vnode is None:
  1439. return
  1440. for node in vnode.findall('variable'):
  1441. name = node.get('name', '')
  1442. if not name:
  1443. continue # should not happen
  1444. self.variables[name] = { 'type' : node.get('type', 'string') }
  1445. for key in ('description', 'value'):
  1446. self._processVariable(node, name, key)
  1447. def _processVariable(self, pnode, name, key):
  1448. """!Process given variable"""
  1449. node = pnode.find(key)
  1450. if node is not None:
  1451. if node.text:
  1452. self.variables[name][key] = node.text
  1453. def _processItems(self):
  1454. """!Process model items (actions, loops, conditions)"""
  1455. self._processActions()
  1456. self._processLoops()
  1457. self._processConditions()
  1458. self._processComments()
  1459. def _processActions(self):
  1460. """!Process model file"""
  1461. for action in self.root.findall('action'):
  1462. pos, size = self._getDim(action)
  1463. disabled = False
  1464. task = action.find('task')
  1465. if task is not None:
  1466. if task.find('disabled') is not None:
  1467. disabled = True
  1468. task = self._processTask(task)
  1469. else:
  1470. task = None
  1471. aId = int(action.get('id', -1))
  1472. label = action.get('name')
  1473. comment = action.find('comment')
  1474. if comment is not None:
  1475. commentString = comment.text
  1476. else:
  1477. commentString = ''
  1478. self.actions.append({ 'pos' : pos,
  1479. 'size' : size,
  1480. 'task' : task,
  1481. 'id' : aId,
  1482. 'disabled' : disabled,
  1483. 'label' : label,
  1484. 'comment' : commentString})
  1485. def _getDim(self, node):
  1486. """!Get position and size of shape"""
  1487. pos = size = None
  1488. posAttr = node.get('pos', None)
  1489. if posAttr:
  1490. posVal = map(int, posAttr.split(','))
  1491. try:
  1492. pos = (posVal[0], posVal[1])
  1493. except:
  1494. pos = None
  1495. sizeAttr = node.get('size', None)
  1496. if sizeAttr:
  1497. sizeVal = map(int, sizeAttr.split(','))
  1498. try:
  1499. size = (sizeVal[0], sizeVal[1])
  1500. except:
  1501. size = None
  1502. return pos, size
  1503. def _processData(self):
  1504. """!Process model file"""
  1505. for data in self.root.findall('data'):
  1506. pos, size = self._getDim(data)
  1507. param = data.find('data-parameter')
  1508. prompt = value = None
  1509. if param is not None:
  1510. prompt = param.get('prompt', None)
  1511. value = self._filterValue(self._getNodeText(param, 'value'))
  1512. if data.find('intermediate') is None:
  1513. intermediate = False
  1514. else:
  1515. intermediate = True
  1516. rels = list()
  1517. for rel in data.findall('relation'):
  1518. defrel = { 'id' : int(rel.get('id', -1)),
  1519. 'dir' : rel.get('dir', 'to'),
  1520. 'name' : rel.get('name', '') }
  1521. points = list()
  1522. for point in rel.findall('point'):
  1523. x = self._filterValue(self._getNodeText(point, 'x'))
  1524. y = self._filterValue(self._getNodeText(point, 'y'))
  1525. points.append((float(x), float(y)))
  1526. defrel['points'] = points
  1527. rels.append(defrel)
  1528. self.data.append({ 'pos' : pos,
  1529. 'size': size,
  1530. 'prompt' : prompt,
  1531. 'value' : value,
  1532. 'intermediate' : intermediate,
  1533. 'rels' : rels })
  1534. def _processTask(self, node):
  1535. """!Process task
  1536. @return grassTask instance
  1537. @return None on error
  1538. """
  1539. cmd = list()
  1540. parameterized = list()
  1541. name = node.get('name', None)
  1542. if not name:
  1543. return None
  1544. cmd.append(name)
  1545. # flags
  1546. for f in node.findall('flag'):
  1547. flag = f.get('name', '')
  1548. if f.get('parameterized', '0') == '1':
  1549. parameterized.append(('flag', flag))
  1550. if f.get('value', '1') == '0':
  1551. continue
  1552. if len(flag) > 1:
  1553. cmd.append('--' + flag)
  1554. else:
  1555. cmd.append('-' + flag)
  1556. # parameters
  1557. for p in node.findall('parameter'):
  1558. name = p.get('name', '')
  1559. if p.find('parameterized') is not None:
  1560. parameterized.append(('param', name))
  1561. cmd.append('%s=%s' % (name,
  1562. self._filterValue(self._getNodeText(p, 'value'))))
  1563. task, err = GUI(show = None, checkError = True).ParseCommand(cmd = cmd)
  1564. if err:
  1565. GWarning(os.linesep.join(err))
  1566. for opt, name in parameterized:
  1567. if opt == 'flag':
  1568. task.set_flag(name, True, element = 'parameterized')
  1569. else:
  1570. task.set_param(name, True, element = 'parameterized')
  1571. return task
  1572. def _processLoops(self):
  1573. """!Process model loops"""
  1574. for node in self.root.findall('loop'):
  1575. pos, size = self._getDim(node)
  1576. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1577. aid = list()
  1578. for anode in node.findall('item'):
  1579. try:
  1580. aid.append(int(anode.text))
  1581. except ValueError:
  1582. pass
  1583. self.loops.append({ 'pos' : pos,
  1584. 'size' : size,
  1585. 'text' : text,
  1586. 'id' : int(node.get('id', -1)),
  1587. 'items' : aid })
  1588. def _processConditions(self):
  1589. """!Process model conditions"""
  1590. for node in self.root.findall('if-else'):
  1591. pos, size = self._getDim(node)
  1592. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1593. aid = { 'if' : list(),
  1594. 'else' : list() }
  1595. for b in aid.keys():
  1596. bnode = node.find(b)
  1597. if bnode is None:
  1598. continue
  1599. for anode in bnode.findall('item'):
  1600. try:
  1601. aid[b].append(int(anode.text))
  1602. except ValueError:
  1603. pass
  1604. self.conditions.append({ 'pos' : pos,
  1605. 'size' : size,
  1606. 'text' : text,
  1607. 'id' : int(node.get('id', -1)),
  1608. 'items' : aid })
  1609. def _processComments(self):
  1610. """!Process model comments"""
  1611. for node in self.root.findall('comment'):
  1612. pos, size = self._getDim(node)
  1613. text = self._filterValue(node.text)
  1614. self.comments.append({ 'pos' : pos,
  1615. 'size' : size,
  1616. 'text' : text,
  1617. 'id' : int(node.get('id', -1)),
  1618. 'text' : text })
  1619. class WriteModelFile:
  1620. """!Generic class for writing model file"""
  1621. def __init__(self, fd, model):
  1622. self.fd = fd
  1623. self.model = model
  1624. self.properties = model.GetProperties()
  1625. self.variables = model.GetVariables()
  1626. self.items = model.GetItems()
  1627. self.indent = 0
  1628. self._header()
  1629. self._window()
  1630. self._properties()
  1631. self._variables()
  1632. self._items()
  1633. dataList = list()
  1634. for action in model.GetItems(objType = ModelAction):
  1635. for rel in action.GetRelations():
  1636. dataItem = rel.GetData()
  1637. if dataItem not in dataList:
  1638. dataList.append(dataItem)
  1639. self._data(dataList)
  1640. self._footer()
  1641. def _filterValue(self, value):
  1642. """!Escapes value to be stored in XML.
  1643. @param value string to be escaped as XML
  1644. @returns a XML-valid string
  1645. """
  1646. value = saxutils.escape(value)
  1647. return value
  1648. def _header(self):
  1649. """!Write header"""
  1650. self.fd.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
  1651. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1652. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1653. self.indent += 4
  1654. def _footer(self):
  1655. """!Write footer"""
  1656. self.indent -= 4
  1657. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1658. def _window(self):
  1659. """!Write window properties"""
  1660. canvas = self.model.GetCanvas()
  1661. if canvas is None:
  1662. return
  1663. win = canvas.parent
  1664. pos = win.GetPosition()
  1665. size = win.GetSize()
  1666. self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' % \
  1667. (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
  1668. def _properties(self):
  1669. """!Write model properties"""
  1670. self.fd.write('%s<properties>\n' % (' ' * self.indent))
  1671. self.indent += 4
  1672. if self.properties['name']:
  1673. self.fd.write('%s<name>%s</name>\n' % (' ' * self.indent, EncodeString(self.properties['name'])))
  1674. if self.properties['description']:
  1675. self.fd.write('%s<description>%s</description>\n' % (' ' * self.indent,
  1676. EncodeString(self.properties['description'])))
  1677. if self.properties['author']:
  1678. self.fd.write('%s<author>%s</author>\n' % (' ' * self.indent,
  1679. EncodeString(self.properties['author'])))
  1680. if 'overwrite' in self.properties and \
  1681. self.properties['overwrite']:
  1682. self.fd.write('%s<flag name="overwrite" />\n' % (' ' * self.indent))
  1683. self.indent -= 4
  1684. self.fd.write('%s</properties>\n' % (' ' * self.indent))
  1685. def _variables(self):
  1686. """!Write model variables"""
  1687. if not self.variables:
  1688. return
  1689. self.fd.write('%s<variables>\n' % (' ' * self.indent))
  1690. self.indent += 4
  1691. for name, values in self.variables.iteritems():
  1692. self.fd.write('%s<variable name="%s" type="%s">\n' % \
  1693. (' ' * self.indent, EncodeString(name), values['type']))
  1694. self.indent += 4
  1695. if 'value' in values:
  1696. self.fd.write('%s<value>%s</value>\n' % \
  1697. (' ' * self.indent, EncodeString(values['value'])))
  1698. if 'description' in values:
  1699. self.fd.write('%s<description>%s</description>\n' % \
  1700. (' ' * self.indent, EncodeString(values['description'])))
  1701. self.indent -= 4
  1702. self.fd.write('%s</variable>\n' % (' ' * self.indent))
  1703. self.indent -= 4
  1704. self.fd.write('%s</variables>\n' % (' ' * self.indent))
  1705. def _items(self):
  1706. """!Write actions/loops/conditions"""
  1707. for item in self.items:
  1708. if isinstance(item, ModelAction):
  1709. self._action(item)
  1710. elif isinstance(item, ModelLoop):
  1711. self._loop(item)
  1712. elif isinstance(item, ModelCondition):
  1713. self._condition(item)
  1714. elif isinstance(item, ModelComment):
  1715. self._comment(item)
  1716. def _action(self, action):
  1717. """!Write actions"""
  1718. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1719. (' ' * self.indent, action.GetId(), EncodeString(action.GetLabel()), action.GetX(), action.GetY(),
  1720. action.GetWidth(), action.GetHeight()))
  1721. self.indent += 4
  1722. comment = action.GetComment()
  1723. if comment:
  1724. self.fd.write('%s<comment>%s</comment>\n' % (' ' * self.indent, EncodeString(comment)))
  1725. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1726. self.indent += 4
  1727. if not action.IsEnabled():
  1728. self.fd.write('%s<disabled />\n' % (' ' * self.indent))
  1729. for key, val in action.GetParams().iteritems():
  1730. if key == 'flags':
  1731. for f in val:
  1732. if f.get('value', False) or f.get('parameterized', False):
  1733. if f.get('parameterized', False):
  1734. if f.get('value', False) == False:
  1735. self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
  1736. (' ' * self.indent, f.get('name', '')))
  1737. else:
  1738. self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
  1739. (' ' * self.indent, f.get('name', '')))
  1740. else:
  1741. self.fd.write('%s<flag name="%s" />\n' %
  1742. (' ' * self.indent, f.get('name', '')))
  1743. else: # parameter
  1744. for p in val:
  1745. if not p.get('value', '') and not p.get('parameterized', False):
  1746. continue
  1747. self.fd.write('%s<parameter name="%s">\n' %
  1748. (' ' * self.indent, p.get('name', '')))
  1749. self.indent += 4
  1750. if p.get('parameterized', False):
  1751. self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
  1752. self.fd.write('%s<value>%s</value>\n' %
  1753. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1754. self.indent -= 4
  1755. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1756. self.indent -= 4
  1757. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1758. self.indent -= 4
  1759. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1760. def _data(self, dataList):
  1761. """!Write data"""
  1762. for data in dataList:
  1763. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1764. (' ' * self.indent, data.GetX(), data.GetY(),
  1765. data.GetWidth(), data.GetHeight()))
  1766. self.indent += 4
  1767. self.fd.write('%s<data-parameter prompt="%s">\n' % \
  1768. (' ' * self.indent, data.GetPrompt()))
  1769. self.indent += 4
  1770. self.fd.write('%s<value>%s</value>\n' %
  1771. (' ' * self.indent, self._filterValue(data.GetValue())))
  1772. self.indent -= 4
  1773. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1774. if data.IsIntermediate():
  1775. self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
  1776. # relations
  1777. for ft in ('from', 'to'):
  1778. for rel in data.GetRelations(ft):
  1779. if ft == 'from':
  1780. aid = rel.GetTo().GetId()
  1781. else:
  1782. aid = rel.GetFrom().GetId()
  1783. self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' % \
  1784. (' ' * self.indent, ft, aid, rel.GetLabel()))
  1785. self.indent += 4
  1786. for point in rel.GetLineControlPoints()[1:-1]:
  1787. self.fd.write('%s<point>\n' % (' ' * self.indent))
  1788. self.indent += 4
  1789. x, y = point.Get()
  1790. self.fd.write('%s<x>%d</x>\n' % (' ' * self.indent, int(x)))
  1791. self.fd.write('%s<y>%d</y>\n' % (' ' * self.indent, int(y)))
  1792. self.indent -= 4
  1793. self.fd.write('%s</point>\n' % (' ' * self.indent))
  1794. self.indent -= 4
  1795. self.fd.write('%s</relation>\n' % (' ' * self.indent))
  1796. self.indent -= 4
  1797. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1798. def _loop(self, loop):
  1799. """!Write loops"""
  1800. self.fd.write('%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1801. (' ' * self.indent, loop.GetId(), loop.GetX(), loop.GetY(),
  1802. loop.GetWidth(), loop.GetHeight()))
  1803. self.indent += 4
  1804. cond = loop.GetLabel()
  1805. if cond:
  1806. self.fd.write('%s<condition>%s</condition>\n' %
  1807. (' ' * self.indent, self._filterValue(cond)))
  1808. for item in loop.GetItems(self.model.GetItems(objType=ModelAction)):
  1809. self.fd.write('%s<item>%d</item>\n' %
  1810. (' ' * self.indent, item.GetId()))
  1811. self.indent -= 4
  1812. self.fd.write('%s</loop>\n' % (' ' * self.indent))
  1813. def _condition(self, condition):
  1814. """!Write conditions"""
  1815. bbox = condition.GetBoundingBoxMin()
  1816. self.fd.write('%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1817. (' ' * self.indent, condition.GetId(), condition.GetX(), condition.GetY(),
  1818. bbox[0], bbox[1]))
  1819. text = condition.GetLabel()
  1820. self.indent += 4
  1821. if text:
  1822. self.fd.write('%s<condition>%s</condition>\n' %
  1823. (' ' * self.indent, self._filterValue(text)))
  1824. items = condition.GetItems()
  1825. for b in items.keys():
  1826. if len(items[b]) < 1:
  1827. continue
  1828. self.fd.write('%s<%s>\n' % (' ' * self.indent, b))
  1829. self.indent += 4
  1830. for item in items[b]:
  1831. self.fd.write('%s<item>%d</item>\n' %
  1832. (' ' * self.indent, item.GetId()))
  1833. self.indent -= 4
  1834. self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
  1835. self.indent -= 4
  1836. self.fd.write('%s</if-else>\n' % (' ' * self.indent))
  1837. def _comment(self, comment):
  1838. """!Write comment"""
  1839. self.fd.write('%s<comment id="%d" pos="%d,%d" size="%d,%d">%s</comment>\n' % \
  1840. (' ' * self.indent, comment.GetId(), comment.GetX(), comment.GetY(),
  1841. comment.GetWidth(), comment.GetHeight(), EncodeString(comment.GetLabel())))
  1842. class WritePythonFile:
  1843. def __init__(self, fd, model):
  1844. """!Class for exporting model to Python script
  1845. @param fd file desciptor
  1846. """
  1847. self.fd = fd
  1848. self.model = model
  1849. self.indent = 4
  1850. self._writePython()
  1851. def _writePython(self):
  1852. """!Write model to file"""
  1853. properties = self.model.GetProperties()
  1854. self.fd.write(
  1855. r"""#!/usr/bin/env python
  1856. #
  1857. #%s
  1858. #
  1859. # MODULE: %s
  1860. #
  1861. # AUTHOR(S): %s
  1862. #
  1863. # PURPOSE: %s
  1864. #
  1865. # DATE: %s
  1866. #
  1867. #%s
  1868. """ % ('#' * 77,
  1869. EncodeString(properties['name']),
  1870. EncodeString(properties['author']),
  1871. EncodeString('\n# '.join(properties['description'].splitlines())),
  1872. time.asctime(),
  1873. '#' * 77))
  1874. self.fd.write(
  1875. r"""
  1876. import sys
  1877. import os
  1878. import atexit
  1879. from grass.script import parser, run_command
  1880. """)
  1881. # cleanup()
  1882. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  1883. self.fd.write(
  1884. r"""
  1885. def cleanup():
  1886. """)
  1887. if rast:
  1888. self.fd.write(
  1889. r""" grass.run_command('g.remove',
  1890. rast=%s)
  1891. """ % ','.join(map(lambda x: "'" + x + "'", rast)))
  1892. if vect:
  1893. self.fd.write(
  1894. r""" grass.run_command('g.remove',
  1895. vect = %s)
  1896. """ % ','.join(map(lambda x: "'" + x + "'", vect)))
  1897. if rast3d:
  1898. self.fd.write(
  1899. r""" grass.run_command('g.remove',
  1900. rast3d = %s)
  1901. """ % ','.join(map(lambda x: "'" + x + "'", rast3d)))
  1902. if not rast and not vect and not rast3d:
  1903. self.fd.write(' pass\n')
  1904. self.fd.write("\ndef main():\n")
  1905. for item in self.model.GetItems():
  1906. self._writePythonItem(item)
  1907. self.fd.write("\n return 0\n")
  1908. self.fd.write(
  1909. r"""
  1910. if __name__ == "__main__":
  1911. options, flags = grass.parser()
  1912. atexit.register(cleanup)
  1913. sys.exit(main())
  1914. """)
  1915. def _writePythonItem(self, item, ignoreBlock = True, variables = []):
  1916. """!Write model object to Python file"""
  1917. if isinstance(item, ModelAction):
  1918. if ignoreBlock and item.GetBlockId(): # ignore items in loops of conditions
  1919. return
  1920. self._writePythonAction(item, variables = variables)
  1921. elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition):
  1922. # substitute condition
  1923. variables = self.model.GetVariables()
  1924. cond = item.GetLabel()
  1925. for variable in variables:
  1926. pattern = re.compile('%' + variable)
  1927. if pattern.search(cond):
  1928. value = variables[variable].get('value', '')
  1929. if variables[variable].get('type', 'string') == 'string':
  1930. value = '"' + value + '"'
  1931. cond = pattern.sub(value, cond)
  1932. if isinstance(item, ModelLoop):
  1933. condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
  1934. cond = "%sfor %s in " % (' ' * self.indent, condVar)
  1935. if condText[0] == '`' and condText[-1] == '`':
  1936. task = GUI(show = None).ParseCommand(cmd = utils.split(condText[1:-1]))
  1937. cond += "grass.read_command("
  1938. cond += self._getPythonActionCmd(task, len(cond), variables = [condVar]) + ".splitlines()"
  1939. else:
  1940. cond += condText
  1941. self.fd.write('%s:\n' % cond)
  1942. self.indent += 4
  1943. for action in item.GetItems(self.model.GetItems(objType=ModelAction)):
  1944. self._writePythonItem(action, ignoreBlock = False, variables = [condVar])
  1945. self.indent -= 4
  1946. if isinstance(item, ModelCondition):
  1947. self.fd.write('%sif %s:\n' % (' ' * self.indent, cond))
  1948. self.indent += 4
  1949. condItems = item.GetItems()
  1950. for action in condItems['if']:
  1951. self._writePythonItem(action, ignoreBlock = False)
  1952. if condItems['else']:
  1953. self.indent -= 4
  1954. self.fd.write('%selse:\n' % (' ' * self.indent))
  1955. self.indent += 4
  1956. for action in condItems['else']:
  1957. self._writePythonItem(action, ignoreBlock = False)
  1958. self.indent += 4
  1959. if isinstance(item, ModelComment):
  1960. self._writePythonComment(item)
  1961. def _writePythonAction(self, item, variables = []):
  1962. """!Write model action to Python file"""
  1963. task = GUI(show = None).ParseCommand(cmd = item.GetLog(string = False, substitute = self.model.GetVariables()))
  1964. strcmd = "%sgrass.run_command(" % (' ' * self.indent)
  1965. self.fd.write(strcmd + self._getPythonActionCmd(task, len(strcmd), variables) + '\n')
  1966. def _getPythonActionCmd(self, task, cmdIndent, variables = []):
  1967. opts = task.get_options()
  1968. ret = ''
  1969. flags = ''
  1970. params = list()
  1971. for f in opts['flags']:
  1972. if f.get('value', False):
  1973. name = f.get('name', '')
  1974. if len(name) > 1:
  1975. params.append('%s = True' % name)
  1976. else:
  1977. flags += name
  1978. for p in opts['params']:
  1979. name = p.get('name', None)
  1980. value = p.get('value', None)
  1981. if name and value:
  1982. ptype = p.get('type', 'string')
  1983. if value[0] == '%':
  1984. params.append("%s = %s" % (name, value[1:]))
  1985. elif ptype == 'string':
  1986. params.append('%s = "%s"' % (name, value))
  1987. else:
  1988. params.append("%s = %s" % (name, value))
  1989. ret += '"%s"' % task.get_name()
  1990. if flags:
  1991. ret += ",\n%sflags = '%s'" % (' ' * cmdIndent, flags)
  1992. if len(params) > 0:
  1993. ret += ",\n"
  1994. for opt in params[:-1]:
  1995. ret += "%s%s,\n" % (' ' * cmdIndent, opt)
  1996. ret += "%s%s)" % (' ' * cmdIndent, params[-1])
  1997. else:
  1998. ret += ")"
  1999. return ret
  2000. def _writePythonComment(self, item):
  2001. """!Write model comment to Python file"""
  2002. for line in item.GetLabel().splitlines():
  2003. self.fd.write('#' + line + '\n')
  2004. class ModelParamDialog(wx.Dialog):
  2005. def __init__(self, parent, params, id = wx.ID_ANY, title = _("Model parameters"),
  2006. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  2007. """!Model parameters dialog
  2008. """
  2009. self.parent = parent
  2010. self.params = params
  2011. self.tasks = list() # list of tasks/pages
  2012. wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
  2013. self.notebook = GNotebook(parent = self,
  2014. style = globalvar.FNPageDStyle)
  2015. panel = self._createPages()
  2016. wx.CallAfter(self.notebook.SetSelection, 0)
  2017. # intermediate data?
  2018. self.interData = wx.CheckBox(parent = self, label = _("Delete intermediate data when finish"))
  2019. self.interData.SetValue(True)
  2020. rast, vect, rast3d, msg = self.parent.GetModel().GetIntermediateData()
  2021. if not rast and not vect and not rast3d:
  2022. self.interData.Hide()
  2023. self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  2024. self.btnRun = wx.Button(parent = self, id = wx.ID_OK,
  2025. label = _("&Run"))
  2026. self.btnRun.SetDefault()
  2027. self._layout()
  2028. size = self.GetBestSize()
  2029. self.SetMinSize(size)
  2030. self.SetSize((size.width, size.height +
  2031. panel.constrained_size[1] -
  2032. panel.panelMinHeight))
  2033. def _layout(self):
  2034. btnSizer = wx.StdDialogButtonSizer()
  2035. btnSizer.AddButton(self.btnCancel)
  2036. btnSizer.AddButton(self.btnRun)
  2037. btnSizer.Realize()
  2038. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2039. mainSizer.Add(item = self.notebook, proportion = 1,
  2040. flag = wx.EXPAND)
  2041. if self.interData.IsShown():
  2042. mainSizer.Add(item = self.interData, proportion = 0,
  2043. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2044. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  2045. style = wx.LI_HORIZONTAL),
  2046. proportion = 0,
  2047. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  2048. mainSizer.Add(item = btnSizer, proportion = 0,
  2049. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2050. self.SetSizer(mainSizer)
  2051. mainSizer.Fit(self)
  2052. def _createPages(self):
  2053. """!Create for each parameterized module its own page"""
  2054. nameOrdered = [''] * len(self.params.keys())
  2055. for name, params in self.params.iteritems():
  2056. nameOrdered[params['idx']] = name
  2057. for name in nameOrdered:
  2058. params = self.params[name]
  2059. panel = self._createPage(name, params)
  2060. if name == 'variables':
  2061. name = _('Variables')
  2062. self.notebook.AddPage(page = panel, text = name)
  2063. return panel
  2064. def _createPage(self, name, params):
  2065. """!Define notebook page"""
  2066. if name in globalvar.grassCmd:
  2067. task = gtask.grassTask(name)
  2068. else:
  2069. task = gtask.grassTask()
  2070. task.flags = params['flags']
  2071. task.params = params['params']
  2072. panel = CmdPanel(parent = self, id = wx.ID_ANY, task = task,
  2073. giface = GraphicalModelerGrassInterface(self.parent.GetModel()))
  2074. self.tasks.append(task)
  2075. return panel
  2076. def GetErrors(self):
  2077. """!Check for errors, get list of messages"""
  2078. errList = list()
  2079. for task in self.tasks:
  2080. errList += task.get_cmd_error()
  2081. return errList
  2082. def DeleteIntermediateData(self):
  2083. """!Check if to detele intermediate data"""
  2084. if self.interData.IsShown() and self.interData.IsChecked():
  2085. return True
  2086. return False