model.py 89 KB

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