model.py 86 KB

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