gmodeler.py 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563
  1. """!
  2. @package gmodeler.py
  3. @brief wxGUI Graphical Modeler for creating, editing, and managing models
  4. Classes:
  5. - Model
  6. - ModelFrame
  7. - ModelCanvas
  8. - ModelObject
  9. - ModelAction
  10. - ModelSearchDialog
  11. - ModelData
  12. - ModelDataDialog
  13. - ModelRelation
  14. - ProcessModelFile
  15. - WriteModelFile
  16. - PreferencesDialog
  17. - PropertiesDialog
  18. - ModelParamDialog
  19. - ModelListCtrl
  20. - VariablePanel
  21. - ValiableListCtrl
  22. - ModelItem
  23. - ModelItemDialog
  24. - ModelLoop
  25. - ModelLoopDialog
  26. - ItemPanel
  27. - ItemListCtrl
  28. - ItemCheckListCtrl
  29. - ModelCondition
  30. - ModelConditionDialog
  31. - WritePythonFile
  32. (C) 2010-2011 by the GRASS Development Team
  33. This program is free software under the GNU General Public License
  34. (>=v2). Read the file COPYING that comes with GRASS for details.
  35. @author Martin Landa <landa.martin gmail.com>
  36. """
  37. import os
  38. import sys
  39. import time
  40. import traceback
  41. import getpass
  42. import stat
  43. import textwrap
  44. import tempfile
  45. import copy
  46. import re
  47. try:
  48. import xml.etree.ElementTree as etree
  49. except ImportError:
  50. import elementtree.ElementTree as etree # Python <= 2.4
  51. import globalvar
  52. import wx
  53. import wx.lib.ogl as ogl
  54. import wx.lib.flatnotebook as FN
  55. import wx.lib.colourselect as csel
  56. import wx.lib.mixins.listctrl as listmix
  57. import menu
  58. import menudata
  59. import toolbars
  60. import menuform
  61. import prompt
  62. import utils
  63. import goutput
  64. import gselect
  65. from debug import Debug
  66. from gcmd import GMessage, GException, GWarning, GError
  67. from gdialogs import ElementDialog, GetImageHandlers
  68. from preferences import PreferencesBaseDialog, globalSettings as UserSettings
  69. from ghelp import SearchModuleWindow
  70. from grass.script import core as grass
  71. from grass.script import task as gtask
  72. class Model(object):
  73. """!Class representing the model"""
  74. def __init__(self, canvas = None):
  75. self.items = list() # list of actions/loops/...
  76. # model properties
  77. self.properties = { 'name' : _("model"),
  78. 'description' : _("Script generated by wxGUI Graphical Modeler."),
  79. 'author' : getpass.getuser() }
  80. # model variables
  81. self.variables = dict()
  82. self.variablesParams = dict()
  83. self.canvas = canvas
  84. def GetCanvas(self):
  85. """!Get canvas or None"""
  86. return self.canvas
  87. def GetItems(self, objType = None):
  88. """!Get list of model items
  89. @param objType Object type to filter model objects
  90. """
  91. if not objType:
  92. return self.items
  93. result = list()
  94. for item in self.items:
  95. if isinstance(item, objType):
  96. result.append(item)
  97. return result
  98. def GetItem(self, aId):
  99. """!Get item of given id
  100. @param aId item id
  101. @return Model* instance
  102. @return None if no item found
  103. """
  104. ilist = self.GetItems()
  105. for item in ilist:
  106. if item.GetId() == aId:
  107. return item
  108. return None
  109. def GetNumItems(self, actionOnly = False):
  110. """!Get number of items"""
  111. if actionOnly:
  112. return len(self.GetItems(objType = ModelAction))
  113. return len(self.GetItems())
  114. def GetNextId(self):
  115. """!Get next id (data ignored)"""
  116. currId = self.items[-1].GetId()
  117. if currId > 0:
  118. return currId + 1
  119. return 1
  120. def GetProperties(self):
  121. """!Get model properties"""
  122. return self.properties
  123. def GetVariables(self, params = False):
  124. """!Get model variables"""
  125. if params:
  126. return self.variablesParams
  127. return self.variables
  128. def SetVariables(self, data):
  129. """!Set model variables"""
  130. self.variables = data
  131. def Reset(self):
  132. """!Reset model"""
  133. self.items = list()
  134. def RemoveItem(self, item):
  135. """!Remove item from model
  136. @return list of related items to remove/update
  137. """
  138. relList = list()
  139. upList = list()
  140. if not isinstance(item, ModelData):
  141. self.items.remove(item)
  142. if isinstance(item, ModelAction):
  143. for rel in item.GetRelations():
  144. relList.append(rel)
  145. data = rel.GetData()
  146. if len(data.GetRelations()) < 2:
  147. relList.append(data)
  148. else:
  149. upList.append(data)
  150. elif isinstance(item, ModelData):
  151. for rel in item.GetRelations():
  152. relList.append(rel)
  153. if rel.GetFrom() == self:
  154. relList.append(rel.GetTo())
  155. else:
  156. relList.append(rel.GetFrom())
  157. return relList, upList
  158. def FindAction(self, aId):
  159. """!Find action by id"""
  160. alist = self.GetItems(objType = ModelAction)
  161. for action in alist:
  162. if action.GetId() == aId:
  163. return action
  164. return None
  165. def GetData(self):
  166. """!Get list of data items"""
  167. result = list()
  168. dataItems = self.GetItems(objType = ModelData)
  169. for action in self.GetItems(objType = ModelAction):
  170. for rel in action.GetRelations():
  171. dataItem = rel.GetData()
  172. if dataItem not in result:
  173. result.append(dataItem)
  174. dataItems.remove(dataItem)
  175. # standalone data
  176. if dataItems:
  177. result += dataItems
  178. return result
  179. def FindData(self, value, prompt):
  180. """!Find data item in the model
  181. @param value value
  182. @param prompt prompt
  183. @return ModelData instance
  184. @return None if not found
  185. """
  186. for data in self.GetData():
  187. if data.GetValue() == value and \
  188. data.GetPrompt() == prompt:
  189. return data
  190. return None
  191. def LoadModel(self, filename):
  192. """!Load model definition stored in GRASS Model XML file (gxm)
  193. @todo Validate against DTD
  194. Raise exception on error.
  195. """
  196. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxm.dtd")
  197. # parse workspace file
  198. try:
  199. gxmXml = ProcessModelFile(etree.parse(filename))
  200. except StandardError, e:
  201. raise GException(e)
  202. if self.canvas:
  203. win = self.canvas.parent
  204. if gxmXml.pos:
  205. win.SetPosition(gxmXml.pos)
  206. if gxmXml.size:
  207. win.SetSize(gxmXml.size)
  208. # load properties
  209. self.properties = gxmXml.properties
  210. self.variables = gxmXml.variables
  211. # load model.GetActions()
  212. for action in gxmXml.actions:
  213. actionItem = ModelAction(parent = self,
  214. x = action['pos'][0],
  215. y = action['pos'][1],
  216. width = action['size'][0],
  217. height = action['size'][1],
  218. task = action['task'],
  219. id = action['id'])
  220. if action['disabled']:
  221. actionItem.Enable(False)
  222. self.AddItem(actionItem)
  223. task = actionItem.GetTask()
  224. parameterized = False
  225. valid = True
  226. for f in task.get_options()['flags']:
  227. if f.get('parameterized', False):
  228. parameterized = True
  229. break
  230. for p in task.get_options()['params']:
  231. if p.get('required', 'no') != 'no' and \
  232. p.get('value', '') == '' and \
  233. p.get('default', '') == '':
  234. valid = False
  235. if p.get('parameterized', False):
  236. parameterized = True
  237. actionItem.SetValid(valid)
  238. actionItem.SetParameterized(parameterized)
  239. actionItem.GetLog() # substitute variables (-> valid/invalid)
  240. # load data & relations
  241. for data in gxmXml.data:
  242. dataItem = ModelData(parent = self,
  243. x = data['pos'][0],
  244. y = data['pos'][1],
  245. width = data['size'][0],
  246. height = data['size'][1],
  247. prompt = data['prompt'],
  248. value = data['value'])
  249. dataItem.SetIntermediate(data['intermediate'])
  250. for rel in data['rels']:
  251. actionItem = self.FindAction(rel['id'])
  252. if rel['dir'] == 'from':
  253. relation = ModelRelation(dataItem, actionItem, rel['name'])
  254. else:
  255. relation = ModelRelation(actionItem, dataItem, rel['name'])
  256. relation.SetControlPoints(rel['points'])
  257. actionItem.AddRelation(relation)
  258. dataItem.AddRelation(relation)
  259. dataItem.Update()
  260. # load loops
  261. for loop in gxmXml.loops:
  262. loopItem = ModelLoop(parent = self,
  263. x = loop['pos'][0],
  264. y = loop['pos'][1],
  265. width = loop['size'][0],
  266. height = loop['size'][1],
  267. text = loop['text'],
  268. id = loop['id'])
  269. self.AddItem(loopItem)
  270. # load conditions
  271. for condition in gxmXml.conditions:
  272. conditionItem = ModelCondition(parent = self,
  273. x = condition['pos'][0],
  274. y = condition['pos'][1],
  275. width = condition['size'][0],
  276. height = condition['size'][1],
  277. text = condition['text'],
  278. id = condition['id'])
  279. self.AddItem(conditionItem)
  280. # define loops & if/else items
  281. for loop in gxmXml.loops:
  282. alist = list()
  283. for aId in loop['items']:
  284. action = self.GetItem(aId)
  285. alist.append(action)
  286. loopItem = self.GetItem(loop['id'])
  287. loopItem.SetItems(alist)
  288. for action in loopItem.GetItems():
  289. action.SetBlock(loopItem)
  290. for condition in gxmXml.conditions:
  291. conditionItem = self.GetItem(condition['id'])
  292. for b in condition['items'].keys():
  293. alist = list()
  294. for aId in condition['items'][b]:
  295. action = self.GetItem(aId)
  296. alist.append(action)
  297. conditionItem.SetItems(alist, branch = b)
  298. items = conditionItem.GetItems()
  299. for b in items.keys():
  300. for action in items[b]:
  301. action.SetBlock(conditionItem)
  302. def AddItem(self, newItem):
  303. """!Add item to the list"""
  304. iId = newItem.GetId()
  305. i = 0
  306. for item in self.items:
  307. if item.GetId() > iId:
  308. self.items.insert(i, newItem)
  309. return
  310. i += 1
  311. self.items.append(newItem)
  312. def IsValid(self):
  313. """Return True if model is valid"""
  314. if self.Validate():
  315. return False
  316. return True
  317. def Validate(self):
  318. """!Validate model, return None if model is valid otherwise
  319. error string"""
  320. errList = list()
  321. for action in self.GetItems(objType = ModelAction):
  322. task = menuform.GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
  323. errList += task.getCmdError()
  324. return errList
  325. def Run(self, log, onDone):
  326. """!Run model"""
  327. for action in self.actions:
  328. if not action.IsEnabled():
  329. continue
  330. log.RunCmd(command = action.GetLog(string = False),
  331. onDone = onDone)
  332. def DeleteIntermediateData(self, log):
  333. """!Detele intermediate data"""
  334. rast, vect, rast3d, msg = self.GetIntermediateData()
  335. if rast:
  336. log.RunCmd(['g.remove', 'rast=%s' %','.join(rast)])
  337. if rast3d:
  338. log.RunCmd(['g.remove', 'rast3d=%s' %','.join(rast3d)])
  339. if vect:
  340. log.RunCmd(['g.remove', 'vect=%s' %','.join(vect)])
  341. def GetIntermediateData(self):
  342. """!Get info about intermediate data"""
  343. rast = list()
  344. rast3d = list()
  345. vect = list()
  346. for data in self.GetData():
  347. if not data.IsIntermediate():
  348. continue
  349. name = data.GetValue()
  350. prompt = data.GetPrompt()
  351. if prompt == 'raster':
  352. rast.append(name)
  353. elif prompt == 'vector':
  354. vect.append(name)
  355. elif prompt == 'rast3d':
  356. rast3d.append(name)
  357. msg = ''
  358. if rast:
  359. msg += '\n\n%s: ' % _('Raster maps')
  360. msg += ', '.join(rast)
  361. if rast3d:
  362. msg += '\n\n%s: ' % _('3D raster maps')
  363. msg += ', '.join(rast3d)
  364. if vect:
  365. msg += '\n\n%s: ' % _('Vector maps')
  366. msg += ', '.join(vect)
  367. return rast, vect, rast3d, msg
  368. def Update(self):
  369. """!Update model"""
  370. for item in self.items:
  371. item.Update()
  372. def IsParameterized(self):
  373. """!Return True if model is parameterized"""
  374. if self.Parameterize():
  375. return True
  376. return False
  377. def Parameterize(self):
  378. """!Return parameterized options"""
  379. result = dict()
  380. idx = 0
  381. if self.variables:
  382. params = list()
  383. result[_("Variables")] = { 'flags' : list(),
  384. 'params' : params,
  385. 'idx' : idx }
  386. for name, values in self.variables.iteritems():
  387. gtype = values.get('type', 'string')
  388. if gtype in ('raster', 'vector'):
  389. gisprompt = True
  390. prompt = gtype
  391. if gtype == 'raster':
  392. element = 'cell'
  393. else:
  394. element = 'vector'
  395. ptype = 'string'
  396. else:
  397. gisprompt = False
  398. prompt = None
  399. element = None
  400. ptype = gtype
  401. params.append({ 'gisprompt' : gisprompt,
  402. 'multiple' : 'no',
  403. 'description' : values.get('description', ''),
  404. 'guidependency' : '',
  405. 'default' : '',
  406. 'age' : None,
  407. 'required' : 'yes',
  408. 'value' : values.get('value', ''),
  409. 'label' : '',
  410. 'guisection' : '',
  411. 'key_desc' : '',
  412. 'values' : list(),
  413. 'parameterized' : False,
  414. 'values_desc' : list(),
  415. 'prompt' : prompt,
  416. 'element' : element,
  417. 'type' : ptype,
  418. 'name' : name })
  419. idx += 1
  420. for action in self.GetItems(objType = ModelAction):
  421. if not action.IsEnabled():
  422. continue
  423. name = action.GetName()
  424. params = action.GetParams()
  425. for f in params['flags']:
  426. if f.get('parameterized', False):
  427. if name not in result:
  428. result[name] = { 'flags' : list(),
  429. 'params': list(),
  430. 'idx' : idx }
  431. result[name]['flags'].append(f)
  432. for p in params['params']:
  433. if p.get('parameterized', False):
  434. if name not in result:
  435. result[name] = { 'flags' : list(),
  436. 'params': list(),
  437. 'idx' : idx }
  438. result[name]['params'].append(p)
  439. idx += 1
  440. self.variablesParams = result # record parameters
  441. return result
  442. class ModelFrame(wx.Frame):
  443. def __init__(self, parent, id = wx.ID_ANY,
  444. title = _("GRASS GIS Graphical Modeler"), **kwargs):
  445. """!Graphical modeler main window
  446. @param parent parent window
  447. @param id window id
  448. @param title window title
  449. @param kwargs wx.Frames' arguments
  450. """
  451. self.parent = parent
  452. self.searchDialog = None # module search dialog
  453. self.baseTitle = title
  454. self.modelFile = None # loaded model
  455. self.modelChanged = False
  456. self.cursors = {
  457. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  458. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  459. }
  460. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  461. self.SetName("Modeler")
  462. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  463. self.menubar = menu.Menu(parent = self, data = menudata.ModelerData())
  464. self.SetMenuBar(self.menubar)
  465. self.toolbar = toolbars.ModelToolbar(parent = self)
  466. self.SetToolBar(self.toolbar)
  467. self.statusbar = self.CreateStatusBar(number = 1)
  468. self.notebook = menuform.GNotebook(parent = self,
  469. style = FN.FNB_FANCY_TABS | FN.FNB_BOTTOM |
  470. FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON)
  471. self.canvas = ModelCanvas(self)
  472. self.canvas.SetBackgroundColour(wx.WHITE)
  473. self.canvas.SetCursor(self.cursors["default"])
  474. self.model = Model(self.canvas)
  475. self.variablePanel = VariablePanel(parent = self)
  476. self.itemPanel = ItemPanel(parent = self)
  477. self.goutput = goutput.GMConsole(parent = self, notebook = self.notebook)
  478. self.notebook.AddPage(page = self.canvas, text=_('Model'), name = 'model')
  479. self.notebook.AddPage(page = self.itemPanel, text=_('Items'), name = 'items')
  480. self.notebook.AddPage(page = self.variablePanel, text=_('Variables'), name = 'variables')
  481. self.notebook.AddPage(page = self.goutput, text=_('Command output'), name = 'output')
  482. wx.CallAfter(self.notebook.SetSelectionByName, 'model')
  483. wx.CallAfter(self.ModelChanged, False)
  484. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  485. self.Bind(wx.EVT_SIZE, self.OnSize)
  486. self._layout()
  487. self.SetMinSize((475, 300))
  488. self.SetSize((640, 480))
  489. # fix goutput's pane size
  490. if self.goutput:
  491. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  492. def _layout(self):
  493. """!Do layout"""
  494. sizer = wx.BoxSizer(wx.VERTICAL)
  495. sizer.Add(item = self.notebook, proportion = 1,
  496. flag = wx.EXPAND)
  497. self.SetAutoLayout(True)
  498. self.SetSizer(sizer)
  499. sizer.Fit(self)
  500. self.Layout()
  501. def _addEvent(self, item):
  502. """!Add event to item"""
  503. evthandler = ModelEvtHandler(self.statusbar,
  504. self)
  505. evthandler.SetShape(item)
  506. evthandler.SetPreviousHandler(item.GetEventHandler())
  507. item.SetEventHandler(evthandler)
  508. def GetCanvas(self):
  509. """!Get canvas"""
  510. return self.canvas
  511. def GetModel(self):
  512. """!Get model"""
  513. return self.model
  514. def ModelChanged(self, changed = True):
  515. """!Update window title"""
  516. self.modelChanged = changed
  517. if self.modelFile:
  518. if self.modelChanged:
  519. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile) + '*')
  520. else:
  521. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  522. else:
  523. self.SetTitle(self.baseTitle)
  524. def OnVariables(self, event):
  525. """!Switch to variables page"""
  526. self.notebook.SetSelectionByName('variables')
  527. def OnRemoveItem(self, event):
  528. """!Remove shape
  529. """
  530. self.GetCanvas().RemoveSelected()
  531. def OnCanvasRefresh(self, event):
  532. """!Refresh canvas"""
  533. self.SetStatusText(_("Redrawing model..."), 0)
  534. self.GetCanvas().Refresh()
  535. self.SetStatusText("", 0)
  536. def OnCmdRun(self, event):
  537. """!Run command"""
  538. try:
  539. action = self.GetModel().GetItems()[event.pid]
  540. if hasattr(action, "task"):
  541. action.Update(running = True)
  542. except IndexError:
  543. pass
  544. def OnCmdDone(self, event):
  545. """!Command done (or aborted)"""
  546. try:
  547. action = self.GetModel().GetItems()[event.pid]
  548. if hasattr(action, "task"):
  549. action.Update(running = True)
  550. except IndexError:
  551. pass
  552. def OnCloseWindow(self, event):
  553. """!Close window"""
  554. if self.modelChanged and \
  555. UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  556. if self.modelFile:
  557. message = _("Do you want to save changes in the model?")
  558. else:
  559. message = _("Do you want to store current model settings "
  560. "to model file?")
  561. # ask user to save current settings
  562. dlg = wx.MessageDialog(self,
  563. message = message,
  564. caption=_("Quit Graphical Modeler"),
  565. style = wx.YES_NO | wx.YES_DEFAULT |
  566. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  567. ret = dlg.ShowModal()
  568. if ret == wx.ID_YES:
  569. if not self.modelFile:
  570. self.OnWorkspaceSaveAs()
  571. else:
  572. self.WriteModelFile(self.modelFile)
  573. elif ret == wx.ID_CANCEL:
  574. dlg.Destroy()
  575. return
  576. dlg.Destroy()
  577. self.Destroy()
  578. def OnSize(self, event):
  579. """Window resized, save to the model"""
  580. self.ModelChanged()
  581. event.Skip()
  582. def OnPreferences(self, event):
  583. """!Open preferences dialog"""
  584. dlg = PreferencesDialog(parent = self)
  585. dlg.CenterOnParent()
  586. dlg.ShowModal()
  587. self.canvas.Refresh()
  588. def OnHelp(self, event):
  589. """!Show help"""
  590. if self.parent and self.parent.GetName() == 'LayerManager':
  591. log = self.parent.GetLogWindow()
  592. log.RunCmd(['g.manual',
  593. 'entry=wxGUI.Modeler'])
  594. else:
  595. gcmd.RunCommand('g.manual',
  596. quiet = True,
  597. entry = 'wxGUI.Modeler')
  598. def OnModelProperties(self, event):
  599. """!Model properties dialog"""
  600. dlg = PropertiesDialog(parent = self)
  601. dlg.CentreOnParent()
  602. properties = self.model.GetProperties()
  603. dlg.Init(properties)
  604. if dlg.ShowModal() == wx.ID_OK:
  605. self.ModelChanged()
  606. for key, value in dlg.GetValues().iteritems():
  607. properties[key] = value
  608. for action in self.model.GetItems(objType = ModelAction):
  609. action.GetTask().set_flag('overwrite', properties['overwrite'])
  610. dlg.Destroy()
  611. def OnDeleteData(self, event):
  612. """!Delete intermediate data"""
  613. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  614. if not rast and not vect and not rast3d:
  615. GMessage(parent = self,
  616. message = _('Nothing to delete.'))
  617. return
  618. dlg = wx.MessageDialog(parent = self,
  619. message= _("Do you want to permanently delete data?%s" % msg),
  620. caption=_("Delete intermediate data?"),
  621. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  622. ret = dlg.ShowModal()
  623. if ret == wx.ID_YES:
  624. dlg.Destroy()
  625. if rast:
  626. self.goutput.RunCmd(['g.remove', 'rast=%s' %','.join(rast)])
  627. if rast3d:
  628. self.goutput.RunCmd(['g.remove', 'rast3d=%s' %','.join(rast3d)])
  629. if vect:
  630. self.goutput.RunCmd(['g.remove', 'vect=%s' %','.join(vect)])
  631. self.SetStatusText(_("%d maps deleted from current mapset") % \
  632. int(len(rast) + len(rast3d) + len(vect)))
  633. return
  634. dlg.Destroy()
  635. def OnModelNew(self, event):
  636. """!Create new model"""
  637. Debug.msg(4, "ModelFrame.OnModelNew():")
  638. # ask user to save current model
  639. if self.modelFile and self.modelChanged:
  640. self.OnModelSave()
  641. elif self.modelFile is None and \
  642. (self.model.GetNumItems() > 0 or len(self.model.GetData()) > 0):
  643. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  644. "Do you want to store current settings "
  645. "to model file?"),
  646. caption=_("Create new model?"),
  647. style=wx.YES_NO | wx.YES_DEFAULT |
  648. wx.CANCEL | wx.ICON_QUESTION)
  649. ret = dlg.ShowModal()
  650. if ret == wx.ID_YES:
  651. self.OnModelSaveAs()
  652. elif ret == wx.ID_CANCEL:
  653. dlg.Destroy()
  654. return
  655. dlg.Destroy()
  656. # delete all items
  657. self.canvas.GetDiagram().DeleteAllShapes()
  658. self.model.Reset()
  659. self.canvas.Refresh()
  660. # no model file loaded
  661. self.modelFile = None
  662. self.modelChanged = False
  663. self.SetTitle(self.baseTitle)
  664. def OnModelOpen(self, event):
  665. """!Load model from file"""
  666. filename = ''
  667. dlg = wx.FileDialog(parent = self, message=_("Choose model file"),
  668. defaultDir = os.getcwd(),
  669. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  670. if dlg.ShowModal() == wx.ID_OK:
  671. filename = dlg.GetPath()
  672. if not filename:
  673. return
  674. Debug.msg(4, "ModelFrame.OnModelOpen(): filename=%s" % filename)
  675. # close current model
  676. self.OnModelClose()
  677. self.LoadModelFile(filename)
  678. self.modelFile = filename
  679. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  680. self.SetStatusText(_('%(items)d items (%(actions)d actions) loaded into model') % \
  681. { 'items' : self.model.GetNumItems(),
  682. 'actions' : self.model.GetNumItems(actionOnly = True) }, 0)
  683. def OnModelSave(self, event = None):
  684. """!Save model to file"""
  685. if self.modelFile and self.modelChanged:
  686. dlg = wx.MessageDialog(self, message=_("Model file <%s> already exists. "
  687. "Do you want to overwrite this file?") % \
  688. self.modelFile,
  689. caption=_("Save model"),
  690. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  691. if dlg.ShowModal() == wx.ID_NO:
  692. dlg.Destroy()
  693. else:
  694. Debug.msg(4, "ModelFrame.OnModelSave(): filename=%s" % self.modelFile)
  695. self.WriteModelFile(self.modelFile)
  696. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  697. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  698. elif not self.modelFile:
  699. self.OnModelSaveAs(None)
  700. def OnModelSaveAs(self, event):
  701. """!Create model to file as"""
  702. filename = ''
  703. dlg = wx.FileDialog(parent = self,
  704. message = _("Choose file to save current model"),
  705. defaultDir = os.getcwd(),
  706. wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
  707. style=wx.FD_SAVE)
  708. if dlg.ShowModal() == wx.ID_OK:
  709. filename = dlg.GetPath()
  710. if not filename:
  711. return
  712. # check for extension
  713. if filename[-4:] != ".gxm":
  714. filename += ".gxm"
  715. if os.path.exists(filename):
  716. dlg = wx.MessageDialog(parent = self,
  717. message=_("Model file <%s> already exists. "
  718. "Do you want to overwrite this file?") % filename,
  719. caption=_("File already exists"),
  720. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  721. if dlg.ShowModal() != wx.ID_YES:
  722. dlg.Destroy()
  723. return
  724. Debug.msg(4, "GMFrame.OnModelSaveAs(): filename=%s" % filename)
  725. self.WriteModelFile(filename)
  726. self.modelFile = filename
  727. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  728. self.SetStatusText(_('File <%s> saved') % self.modelFile, 0)
  729. def OnModelClose(self, event = None):
  730. """!Close model file"""
  731. Debug.msg(4, "ModelFrame.OnModelClose(): file=%s" % self.modelFile)
  732. # ask user to save current model
  733. if self.modelFile and self.modelChanged:
  734. self.OnModelSave()
  735. elif self.modelFile is None and \
  736. (self.model.GetNumItems() > 0 or len(self.model.GetData()) > 0):
  737. dlg = wx.MessageDialog(self, message=_("Current model is not empty. "
  738. "Do you want to store current settings "
  739. "to model file?"),
  740. caption=_("Create new model?"),
  741. style=wx.YES_NO | wx.YES_DEFAULT |
  742. wx.CANCEL | wx.ICON_QUESTION)
  743. ret = dlg.ShowModal()
  744. if ret == wx.ID_YES:
  745. self.OnModelSaveAs()
  746. elif ret == wx.ID_CANCEL:
  747. dlg.Destroy()
  748. return
  749. dlg.Destroy()
  750. self.modelFile = None
  751. self.SetTitle(self.baseTitle)
  752. self.canvas.GetDiagram().DeleteAllShapes()
  753. self.model.Reset()
  754. self.canvas.Refresh()
  755. def OnRunModel(self, event):
  756. """!Run entire model"""
  757. if self.model.GetNumItems() < 1:
  758. GMessage(parent = self,
  759. message = _('Model is empty. Nothing to run.'))
  760. return
  761. # validation
  762. errList = self._validateModel()
  763. if errList:
  764. dlg = wx.MessageDialog(parent = self,
  765. message = _('Model is not valid. Do you want to '
  766. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  767. caption=_("Run model?"),
  768. style = wx.YES_NO | wx.NO_DEFAULT |
  769. wx.ICON_QUESTION | wx.CENTRE)
  770. ret = dlg.ShowModal()
  771. if ret != wx.ID_YES:
  772. return
  773. # parametrization
  774. params = self.model.Parameterize()
  775. if params:
  776. dlg = ModelParamDialog(parent = self,
  777. params = params)
  778. dlg.CenterOnParent()
  779. ret = dlg.ShowModal()
  780. if ret != wx.ID_OK:
  781. dlg.Destroy()
  782. return
  783. err = dlg.GetErrors()
  784. if err:
  785. GError(parent = self,
  786. message = unicode('\n'.join(err)))
  787. return
  788. self.goutput.cmdThread.SetId(-1)
  789. for item in self.model.GetItems():
  790. if not item.IsEnabled():
  791. continue
  792. if isinstance(item, ModelAction):
  793. if item.GetBlockId():
  794. continue
  795. self._runAction(item, params)
  796. elif isinstance(item, ModelLoop):
  797. cond = item.GetText()
  798. # substitute variables in condition
  799. variables = self.model.GetVariables()
  800. for variable in variables:
  801. pattern = re.compile('%' + variable)
  802. if pattern.search(cond):
  803. value = variables[variable].get('value', '')
  804. vtype = variables[variable].get('type', 'string')
  805. if vtype == 'string':
  806. value = '"' + value + '"'
  807. cond = pattern.sub(value, cond)
  808. # split condition
  809. condVar, condText = re.split('\s*in\s*', cond)
  810. for action in item.GetItems():
  811. for vars()[condVar] in eval(condText):
  812. if isinstance(action, ModelAction):
  813. self._runAction(action, params)
  814. if params:
  815. dlg.Destroy()
  816. def _runAction(self, item, params):
  817. """!Run given action"""
  818. name = item.GetName()
  819. if name in params:
  820. paramsOrig = item.GetParams(dcopy = True)
  821. item.MergeParams(params[name])
  822. self.SetStatusText(_('Running model...'), 0)
  823. self.goutput.RunCmd(command = item.GetLog(string = False),
  824. onDone = self.OnDone)
  825. if name in params:
  826. item.SetParams(paramsOrig)
  827. def OnDone(self, cmd, returncode):
  828. """!Computation finished"""
  829. self.SetStatusText('', 0)
  830. def OnValidateModel(self, event, showMsg = True):
  831. """!Validate entire model"""
  832. if self.model.GetNumItems() < 1:
  833. GMessage(parent = self,
  834. message = _('Model is empty. Nothing to validate.'))
  835. return
  836. errList = self._validateModel()
  837. if errList:
  838. GWarning(parent = self,
  839. message = _('Model is not valid.\n\n%s') % '\n'.join(errList))
  840. else:
  841. GMessage(parent = self,
  842. message = _('Model is valid.'))
  843. def OnExportImage(self, event):
  844. """!Export model to image (default image)
  845. """
  846. xminImg = 0
  847. xmaxImg = 0
  848. yminImg = 0
  849. ymaxImg = 0
  850. # get current size of canvas
  851. for shape in self.canvas.GetDiagram().GetShapeList():
  852. w, h = shape.GetBoundingBoxMax()
  853. x = shape.GetX()
  854. y = shape.GetY()
  855. xmin = x - w / 2
  856. xmax = x + w / 2
  857. ymin = y - h / 2
  858. ymax = y + h / 2
  859. if xmin < xminImg:
  860. xminImg = xmin
  861. if xmax > xmaxImg:
  862. xmaxImg = xmax
  863. if ymin < yminImg:
  864. yminImg = ymin
  865. if ymax > ymaxImg:
  866. ymaxImg = ymax
  867. size = wx.Size(int(xmaxImg - xminImg) + 50,
  868. int(ymaxImg - yminImg) + 50)
  869. bitmap = wx.EmptyBitmap(width = size.width, height = size.height)
  870. filetype, ltype = GetImageHandlers(wx.ImageFromBitmap(bitmap))
  871. dlg = wx.FileDialog(parent = self,
  872. message = _("Choose a file name to save the image (no need to add extension)"),
  873. defaultDir = "",
  874. defaultFile = "",
  875. wildcard = filetype,
  876. style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  877. if dlg.ShowModal() == wx.ID_OK:
  878. path = dlg.GetPath()
  879. if not path:
  880. dlg.Destroy()
  881. return
  882. base, ext = os.path.splitext(path)
  883. fileType = ltype[dlg.GetFilterIndex()]['type']
  884. extType = ltype[dlg.GetFilterIndex()]['ext']
  885. if ext != extType:
  886. path = base + '.' + extType
  887. dc = wx.MemoryDC(bitmap)
  888. dc.SetBackground(wx.WHITE_BRUSH)
  889. dc.SetBackgroundMode(wx.SOLID)
  890. dc.BeginDrawing()
  891. self.canvas.GetDiagram().Clear(dc)
  892. self.canvas.GetDiagram().Redraw(dc)
  893. dc.EndDrawing()
  894. bitmap.SaveFile(path, fileType)
  895. self.SetStatusText(_("Model exported to <%s>") % path)
  896. dlg.Destroy()
  897. def OnExportPython(self, event):
  898. """!Export model to Python script"""
  899. filename = ''
  900. dlg = wx.FileDialog(parent = self,
  901. message = _("Choose file to save"),
  902. defaultDir = os.getcwd(),
  903. wildcard=_("Python script (*.py)|*.py"),
  904. style=wx.FD_SAVE)
  905. if dlg.ShowModal() == wx.ID_OK:
  906. filename = dlg.GetPath()
  907. if not filename:
  908. return
  909. # check for extension
  910. if filename[-3:] != ".py":
  911. filename += ".py"
  912. if os.path.exists(filename):
  913. dlg = wx.MessageDialog(self, message=_("File <%s> already exists. "
  914. "Do you want to overwrite this file?") % filename,
  915. caption=_("Save file"),
  916. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  917. if dlg.ShowModal() == wx.ID_NO:
  918. dlg.Destroy()
  919. return
  920. dlg.Destroy()
  921. fd = open(filename, "w")
  922. try:
  923. WritePythonFile(fd, self.model)
  924. finally:
  925. fd.close()
  926. # executable file
  927. os.chmod(filename, stat.S_IRWXU | stat.S_IWUSR)
  928. self.SetStatusText(_("Model exported to <%s>") % filename)
  929. def _validateModel(self):
  930. """!Validate model"""
  931. self.SetStatusText(_('Validating model...'), 0)
  932. errList = self.model.Validate()
  933. self.SetStatusText('', 0)
  934. return errList
  935. def OnDefineRelation(self, event):
  936. """!Define relation between data and action items"""
  937. self.canvas.SetCursor(self.cursors["cross"])
  938. self.defineRelation = { 'from' : None,
  939. 'to' : None }
  940. def OnDefineLoop(self, event):
  941. """!Define new loop in the model"""
  942. self.ModelChanged()
  943. width, height = self.canvas.GetSize()
  944. loop = ModelLoop(self, x = width/2, y = height/2,
  945. id = self.model.GetNumItems() + 1)
  946. self.canvas.diagram.AddShape(loop)
  947. loop.Show(True)
  948. self._addEvent(loop)
  949. self.model.AddItem(loop)
  950. self.canvas.Refresh()
  951. def OnDefineCondition(self, event):
  952. """!Define new condition in the model"""
  953. self.ModelChanged()
  954. width, height = self.canvas.GetSize()
  955. cond = ModelCondition(self, x = width/2, y = height/2,
  956. id = self.model.GetNumItems() + 1)
  957. self.canvas.diagram.AddShape(cond)
  958. cond.Show(True)
  959. self._addEvent(cond)
  960. self.model.AddItem(cond)
  961. self.canvas.Refresh()
  962. def OnAddAction(self, event):
  963. """!Add action to model"""
  964. if self.searchDialog is None:
  965. self.searchDialog = ModelSearchDialog(self)
  966. self.searchDialog.CentreOnParent()
  967. else:
  968. self.searchDialog.Reset()
  969. if self.searchDialog.ShowModal() == wx.ID_CANCEL:
  970. self.searchDialog.Hide()
  971. return
  972. cmd = self.searchDialog.GetCmd()
  973. self.searchDialog.Hide()
  974. self.ModelChanged()
  975. # add action to canvas
  976. width, height = self.canvas.GetSize()
  977. action = ModelAction(self.model, cmd = cmd, x = width/2, y = height/2,
  978. id = self.model.GetNextId())
  979. overwrite = self.model.GetProperties().get('overwrite', None)
  980. if overwrite is not None:
  981. action.GetTask().set_flag('overwrite', overwrite)
  982. self.canvas.diagram.AddShape(action)
  983. action.Show(True)
  984. self._addEvent(action)
  985. self.model.AddItem(action)
  986. self.itemPanel.Update()
  987. self.canvas.Refresh()
  988. time.sleep(.1)
  989. # show properties dialog
  990. win = action.GetPropDialog()
  991. if not win and action.GetLog(string = False):
  992. module = menuform.GUI(parent = self, show = True).ParseCommand(action.GetLog(string = False),
  993. completed = (self.GetOptData, action, action.GetParams()))
  994. elif win and not win.IsShown():
  995. win.Show()
  996. if win:
  997. win.Raise()
  998. def OnAddData(self, event):
  999. """!Add data item to model
  1000. """
  1001. # add action to canvas
  1002. width, height = self.canvas.GetSize()
  1003. data = ModelData(self, x = width/2, y = height/2)
  1004. self.canvas.diagram.AddShape(data)
  1005. data.Show(True)
  1006. self.ModelChanged()
  1007. self._addEvent(data)
  1008. self.model.AddItem(data)
  1009. self.canvas.Refresh()
  1010. # show data properties dialog
  1011. dlg = ModelDataDialog(parent = self, shape = data)
  1012. data.SetPropDialog(dlg)
  1013. dlg.CentreOnParent()
  1014. dlg.Show()
  1015. def OnHelp(self, event):
  1016. """!Display manual page"""
  1017. grass.run_command('g.manual',
  1018. entry = 'wxGUI.Modeler')
  1019. def OnAbout(self, event):
  1020. """!Display About window"""
  1021. info = wx.AboutDialogInfo()
  1022. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  1023. info.SetName(_('wxGUI Graphical Modeler'))
  1024. info.SetWebSite('http://grass.osgeo.org')
  1025. info.SetDescription(_('(C) 2010 by the GRASS Development Team\n\n') +
  1026. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  1027. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  1028. wx.AboutBox(info)
  1029. def GetOptData(self, dcmd, layer, params, propwin):
  1030. """!Process action data"""
  1031. if params: # add data items
  1032. # for p in params['params']:
  1033. # if p.get('prompt', '') in ('raster', 'vector', 'raster3d'):
  1034. # try:
  1035. # name, mapset = p.get('value', '').split('@', 1)
  1036. # except (ValueError, IndexError):
  1037. # continue
  1038. # if mapset != grass.gisenv()['MAPSET']:
  1039. # continue
  1040. # # don't use fully qualified names
  1041. # p['value'] = p.get('value', '').split('@')[0]
  1042. # for idx in range(1, len(dcmd)):
  1043. # if p.get('name', '') in dcmd[idx]:
  1044. # dcmd[idx] = p.get('name', '') + '=' + p.get('value', '')
  1045. # break
  1046. width, height = self.canvas.GetSize()
  1047. x = [width/2 + 200, width/2 - 200]
  1048. for p in params['params']:
  1049. if p.get('prompt', '') in ('raster', 'vector', 'raster3d') and \
  1050. (p.get('value', None) or \
  1051. (p.get('age', 'old') != 'old' and p.get('required', 'no') == 'yes')):
  1052. data = layer.FindData(p.get('name', ''))
  1053. if data:
  1054. data.SetValue(p.get('value', ''))
  1055. data.Update()
  1056. continue
  1057. data = self.model.FindData(p.get('value', ''),
  1058. p.get('prompt', ''))
  1059. if data:
  1060. if p.get('age', 'old') == 'old':
  1061. rel = ModelRelation(data, layer, p.get('name', ''))
  1062. else:
  1063. rel = ModelRelation(layer, data, p.get('name', ''))
  1064. layer.AddRelation(rel)
  1065. data.AddRelation(rel)
  1066. self.AddLine(rel)
  1067. data.Update()
  1068. continue
  1069. data = ModelData(self, value = p.get('value', ''),
  1070. prompt = p.get('prompt', ''),
  1071. x = x.pop(), y = height/2)
  1072. self._addEvent(data)
  1073. self.canvas.diagram.AddShape(data)
  1074. data.Show(True)
  1075. if p.get('age', 'old') == 'old':
  1076. rel = ModelRelation(data, layer, p.get('name', ''))
  1077. else:
  1078. rel = ModelRelation(layer, data, p.get('name', ''))
  1079. layer.AddRelation(rel)
  1080. data.AddRelation(rel)
  1081. self.AddLine(rel)
  1082. data.Update()
  1083. # valid ?
  1084. valid = True
  1085. for p in params['params']:
  1086. if p.get('required', 'no') != 'no' and \
  1087. p.get('value', '') == '' and \
  1088. p.get('default', '') == '':
  1089. valid = False
  1090. break
  1091. layer.SetValid(valid)
  1092. # parameterized ?
  1093. parameterized = False
  1094. for f in params['flags']:
  1095. if f.get('parameterized', False):
  1096. parameterized = True
  1097. break
  1098. if not parameterized:
  1099. for p in params['params']:
  1100. if p.get('parameterized', False):
  1101. parameterized = True
  1102. break
  1103. layer.SetParameterized(parameterized)
  1104. self.canvas.Refresh()
  1105. if dcmd:
  1106. layer.SetProperties(params, propwin)
  1107. self.SetStatusText(layer.GetLog(), 0)
  1108. def AddLine(self, rel):
  1109. """!Add connection between model objects
  1110. @param rel relation
  1111. """
  1112. fromShape = rel.GetFrom()
  1113. toShape = rel.GetTo()
  1114. rel.SetCanvas(self)
  1115. rel.SetPen(wx.BLACK_PEN)
  1116. rel.SetBrush(wx.BLACK_BRUSH)
  1117. rel.AddArrow(ogl.ARROW_ARROW)
  1118. points = rel.GetControlPoints()
  1119. rel.MakeLineControlPoints(2)
  1120. if points:
  1121. for x, y in points:
  1122. rel.InsertLineControlPoint(point = wx.RealPoint(x, y))
  1123. self._addEvent(rel)
  1124. try:
  1125. fromShape.AddLine(rel, toShape)
  1126. except TypeError:
  1127. pass # bug when connecting ModelCondition and ModelLoop - to be fixed
  1128. self.canvas.diagram.AddShape(rel)
  1129. rel.Show(True)
  1130. def LoadModelFile(self, filename):
  1131. """!Load model definition stored in GRASS Model XML file (gxm)
  1132. """
  1133. try:
  1134. self.model.LoadModel(filename)
  1135. except GException, e:
  1136. GError(parent = self,
  1137. message = _("Reading model file <%s> failed.\n"
  1138. "Invalid file, unable to parse XML document.") % filename)
  1139. self.modelFile = filename
  1140. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.modelFile))
  1141. self.SetStatusText(_("Please wait, loading model..."), 0)
  1142. # load actions
  1143. for item in self.model.GetItems(objType = ModelAction):
  1144. self._addEvent(item)
  1145. self.canvas.diagram.AddShape(item)
  1146. item.Show(True)
  1147. # relations/data
  1148. for rel in item.GetRelations():
  1149. if rel.GetFrom() == item:
  1150. dataItem = rel.GetTo()
  1151. else:
  1152. dataItem = rel.GetFrom()
  1153. self._addEvent(dataItem)
  1154. self.canvas.diagram.AddShape(dataItem)
  1155. self.AddLine(rel)
  1156. dataItem.Show(True)
  1157. # load loops
  1158. for item in self.model.GetItems(objType = ModelLoop):
  1159. self._addEvent(item)
  1160. self.canvas.diagram.AddShape(item)
  1161. item.Show(True)
  1162. # connect items in the loop
  1163. self.DefineLoop(item)
  1164. # load conditions
  1165. for item in self.model.GetItems(objType = ModelCondition):
  1166. self._addEvent(item)
  1167. self.canvas.diagram.AddShape(item)
  1168. item.Show(True)
  1169. # connect items in the condition
  1170. self.DefineCondition(item)
  1171. # load variables
  1172. self.variablePanel.Update()
  1173. self.itemPanel.Update()
  1174. self.SetStatusText('', 0)
  1175. self.canvas.Refresh(True)
  1176. def WriteModelFile(self, filename):
  1177. """!Save model to model file, recover original file on error.
  1178. @return True on success
  1179. @return False on failure
  1180. """
  1181. self.ModelChanged(False)
  1182. tmpfile = tempfile.TemporaryFile(mode='w+b')
  1183. try:
  1184. WriteModelFile(fd = tmpfile, model = self.model)
  1185. except StandardError:
  1186. GError(parent = self,
  1187. message = _("Writing current settings to model file failed."))
  1188. return False
  1189. try:
  1190. mfile = open(filename, "w")
  1191. tmpfile.seek(0)
  1192. for line in tmpfile.readlines():
  1193. mfile.write(line)
  1194. except IOError:
  1195. wx.MessageBox(parent = self,
  1196. message = _("Unable to open file <%s> for writing.") % filename,
  1197. caption = _("Error"),
  1198. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1199. return False
  1200. mfile.close()
  1201. return True
  1202. def DefineLoop(self, loop):
  1203. """!Define loop with given list of items"""
  1204. parent = loop
  1205. items = loop.GetItems()
  1206. if not items:
  1207. return
  1208. # remove defined relations first
  1209. for rel in loop.GetRelations():
  1210. self.canvas.GetDiagram().RemoveShape(rel)
  1211. loop.Clear()
  1212. for item in items:
  1213. rel = ModelRelation(parent, item)
  1214. dx = item.GetX() - parent.GetX()
  1215. dy = item.GetY() - parent.GetY()
  1216. loop.AddRelation(rel)
  1217. if dx != 0:
  1218. rel.SetControlPoints(((parent.GetX(), parent.GetY() + dy / 2),
  1219. (parent.GetX() + dx, parent.GetY() + dy / 2)))
  1220. self.AddLine(rel)
  1221. parent = item
  1222. # close loop
  1223. item = loop.GetItems()[-1]
  1224. rel = ModelRelation(item, loop)
  1225. loop.AddRelation(rel)
  1226. self.AddLine(rel)
  1227. dx = (item.GetX() - loop.GetX()) + loop.GetWidth() / 2 + 50
  1228. dy = item.GetHeight() / 2 + 50
  1229. rel.MakeLineControlPoints(0)
  1230. rel.InsertLineControlPoint(point = wx.RealPoint(loop.GetX() - loop.GetWidth() / 2 ,
  1231. loop.GetY()))
  1232. rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX(),
  1233. item.GetY() + item.GetHeight() / 2))
  1234. rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX(),
  1235. item.GetY() + dy))
  1236. rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - dx,
  1237. item.GetY() + dy))
  1238. rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - dx,
  1239. loop.GetY()))
  1240. self.canvas.Refresh()
  1241. def DefineCondition(self, condition):
  1242. """!Define if-else statement with given list of items"""
  1243. parent = condition
  1244. items = condition.GetItems()
  1245. if not items['if'] and not items['else']:
  1246. return
  1247. # remove defined relations first
  1248. for rel in condition.GetRelations():
  1249. self.canvas.GetDiagram().RemoveShape(rel)
  1250. condition.Clear()
  1251. dxIf = condition.GetX() + condition.GetWidth() / 2
  1252. dxElse = condition.GetX() - condition.GetWidth() / 2
  1253. dy = condition.GetY()
  1254. for branch in items.keys():
  1255. for item in items[branch]:
  1256. rel = ModelRelation(parent, item)
  1257. condition.AddRelation(rel)
  1258. self.AddLine(rel)
  1259. rel.MakeLineControlPoints(0)
  1260. if branch == 'if':
  1261. rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - item.GetWidth() / 2, item.GetY()))
  1262. rel.InsertLineControlPoint(point = wx.RealPoint(dxIf, dy))
  1263. else:
  1264. rel.InsertLineControlPoint(point = wx.RealPoint(dxElse, dy))
  1265. rel.InsertLineControlPoint(point = wx.RealPoint(item.GetX() - item.GetWidth() / 2, item.GetY()))
  1266. parent = item
  1267. self.canvas.Refresh()
  1268. class ModelCanvas(ogl.ShapeCanvas):
  1269. """!Canvas where model is drawn"""
  1270. def __init__(self, parent):
  1271. self.parent = parent
  1272. ogl.OGLInitialize()
  1273. ogl.ShapeCanvas.__init__(self, parent)
  1274. self.diagram = ogl.Diagram()
  1275. self.SetDiagram(self.diagram)
  1276. self.diagram.SetCanvas(self)
  1277. self.SetScrollbars(20, 20, 1000/20, 1000/20)
  1278. self.Bind(wx.EVT_CHAR, self.OnChar)
  1279. def OnChar(self, event):
  1280. """!Key pressed"""
  1281. kc = event.GetKeyCode()
  1282. diagram = self.GetDiagram()
  1283. if kc == wx.WXK_DELETE:
  1284. self.RemoveSelected()
  1285. def RemoveSelected(self):
  1286. """!Remove selected shapes"""
  1287. self.parent.ModelChanged()
  1288. diagram = self.GetDiagram()
  1289. for shape in diagram.GetShapeList():
  1290. if not shape.Selected():
  1291. continue
  1292. remList, upList = self.parent.GetModel().RemoveItem(shape)
  1293. shape.Select(False)
  1294. diagram.RemoveShape(shape)
  1295. del shape
  1296. for item in remList:
  1297. diagram.RemoveShape(item)
  1298. item.__del__()
  1299. for item in upList:
  1300. item.Update()
  1301. self.Refresh()
  1302. class ModelObject:
  1303. def __init__(self, id = -1):
  1304. self.id = id
  1305. self.rels = list() # list of ModelRelations
  1306. self.isEnabled = True
  1307. self.inBlock = list() # list of related loops/conditions
  1308. def __del__(self):
  1309. pass
  1310. def GetId(self):
  1311. """!Get id"""
  1312. return self.id
  1313. def AddRelation(self, rel):
  1314. """!Record new relation
  1315. """
  1316. self.rels.append(rel)
  1317. def GetRelations(self, fdir = None):
  1318. """!Get list of relations
  1319. @param fdir True for 'from'
  1320. """
  1321. if fdir is None:
  1322. return self.rels
  1323. result = list()
  1324. for rel in self.rels:
  1325. if fdir == 'from':
  1326. if rel.GetFrom() == self:
  1327. result.append(rel)
  1328. else:
  1329. if rel.GetTo() == self:
  1330. result.append(rel)
  1331. return result
  1332. def IsEnabled(self):
  1333. """!Get True if action is enabled, otherwise False"""
  1334. return self.isEnabled
  1335. def Enable(self, enabled = True):
  1336. """!Enable/disable action"""
  1337. self.isEnabled = enabled
  1338. self.Update()
  1339. def Update(self):
  1340. pass
  1341. def SetBlock(self, item):
  1342. """!Add object to the block (loop/condition)
  1343. @param item reference to ModelLoop or ModelCondition which
  1344. defines loops/condition
  1345. """
  1346. if item not in self.inBlock:
  1347. self.inBlock.append(item)
  1348. def UnSetBlock(self, item):
  1349. """!Remove object from the block (loop/consition)
  1350. @param item reference to ModelLoop or ModelCondition which
  1351. defines loops/codition
  1352. """
  1353. if item in self.inBlock:
  1354. self.inBlock.remove(item)
  1355. def GetBlock(self):
  1356. """!Get list of related ModelObject(s) which defines block
  1357. (loop/condition)
  1358. @return list of ModelObjects
  1359. """
  1360. return self.inBlock
  1361. def GetBlockId(self):
  1362. """!Get list of related ids which defines block
  1363. @return list of ids
  1364. """
  1365. ret = list()
  1366. for mo in self.inBlock:
  1367. ret.append(mo.GetId())
  1368. return ret
  1369. class ModelAction(ModelObject, ogl.RectangleShape):
  1370. """!Action class (GRASS module)"""
  1371. def __init__(self, parent, x, y, id = -1, cmd = None, task = None, width = None, height = None):
  1372. ModelObject.__init__(self, id)
  1373. self.parent = parent
  1374. self.task = task
  1375. if not width:
  1376. width = UserSettings.Get(group='modeler', key='action', subkey=('size', 'width'))
  1377. if not height:
  1378. height = UserSettings.Get(group='modeler', key='action', subkey=('size', 'height'))
  1379. if cmd:
  1380. self.task = menuform.GUI(show = None).ParseCommand(cmd = cmd)
  1381. else:
  1382. if task:
  1383. self.task = task
  1384. else:
  1385. self.task = None
  1386. self.propWin = None
  1387. self.data = list() # list of connected data items
  1388. self.isValid = False
  1389. self.isParameterized = False
  1390. if self.parent.GetCanvas():
  1391. ogl.RectangleShape.__init__(self, width, height)
  1392. self.SetCanvas(self.parent)
  1393. self.SetX(x)
  1394. self.SetY(y)
  1395. self.SetPen(wx.BLACK_PEN)
  1396. self._setPen()
  1397. self._setBrush()
  1398. self.SetId(id)
  1399. def _setBrush(self, running = False):
  1400. """!Set brush"""
  1401. if running:
  1402. color = UserSettings.Get(group='modeler', key='action',
  1403. subkey=('color', 'running'))
  1404. elif not self.isEnabled:
  1405. color = UserSettings.Get(group='modeler', key='action',
  1406. subkey=('color', 'disabled'))
  1407. elif self.isValid:
  1408. color = UserSettings.Get(group='modeler', key='action',
  1409. subkey=('color', 'valid'))
  1410. else:
  1411. color = UserSettings.Get(group='modeler', key='action',
  1412. subkey=('color', 'invalid'))
  1413. wxColor = wx.Color(color[0], color[1], color[2])
  1414. self.SetBrush(wx.Brush(wxColor))
  1415. def _setPen(self):
  1416. """!Set pen"""
  1417. if self.isParameterized:
  1418. width = int(UserSettings.Get(group='modeler', key='action',
  1419. subkey=('width', 'parameterized')))
  1420. else:
  1421. width = int(UserSettings.Get(group='modeler', key='action',
  1422. subkey=('width', 'default')))
  1423. pen = self.GetPen()
  1424. pen.SetWidth(width)
  1425. self.SetPen(pen)
  1426. def SetId(self, id):
  1427. """!Set id"""
  1428. self.id = id
  1429. cmd = self.task.getCmd(ignoreErrors = True)
  1430. if cmd and len(cmd) > 0:
  1431. self.ClearText()
  1432. self.AddText('(%d) %s' % (self.id, cmd[0]))
  1433. else:
  1434. self.AddText('(%d) <<%s>>' % (self.id, _("unknown")))
  1435. def SetProperties(self, params, propwin):
  1436. """!Record properties dialog"""
  1437. self.task.params = params['params']
  1438. self.task.flags = params['flags']
  1439. self.propWin = propwin
  1440. def GetPropDialog(self):
  1441. """!Get properties dialog"""
  1442. return self.propWin
  1443. def GetLog(self, string = True):
  1444. """!Get logging info"""
  1445. cmd = self.task.getCmd(ignoreErrors = True, ignoreRequired = True)
  1446. # substitute variables
  1447. variables = self.parent.GetVariables()
  1448. fparams = self.parent.GetVariables(params = True)
  1449. params = None
  1450. for values in fparams.itervalues():
  1451. params = values['params']
  1452. break
  1453. for variable in variables:
  1454. pattern= re.compile('%' + variable)
  1455. value = None
  1456. if params:
  1457. for p in params:
  1458. if variable == p.get('name', ''):
  1459. value = p.get('value', '')
  1460. break
  1461. if not value:
  1462. value = variables[variable].get('value', '')
  1463. for idx in range(len(cmd)):
  1464. if pattern.search(cmd[idx]):
  1465. if value:
  1466. cmd[idx] = pattern.sub(value, cmd[idx])
  1467. else:
  1468. self.isValid = False
  1469. break
  1470. idx += 1
  1471. if string:
  1472. if cmd is None:
  1473. return ''
  1474. else:
  1475. return ' '.join(cmd)
  1476. return cmd
  1477. def GetName(self):
  1478. """!Get name"""
  1479. cmd = self.task.getCmd(ignoreErrors = True)
  1480. if cmd and len(cmd) > 0:
  1481. return cmd[0]
  1482. return _('unknown')
  1483. def GetParams(self, dcopy = False):
  1484. """!Get dictionary of parameters"""
  1485. if dcopy:
  1486. return copy.deepcopy(self.task.get_options())
  1487. return self.task.get_options()
  1488. def GetTask(self):
  1489. """!Get grassTask instance"""
  1490. return self.task
  1491. def SetParams(self, params):
  1492. """!Set dictionary of parameters"""
  1493. self.task.params = params['params']
  1494. self.task.flags = params['flags']
  1495. def MergeParams(self, params):
  1496. """!Merge dictionary of parameters"""
  1497. if 'flags' in params:
  1498. for f in params['flags']:
  1499. self.task.set_flag(f['name'],
  1500. f.get('value', False))
  1501. if 'params' in params:
  1502. for p in params['params']:
  1503. self.task.set_param(p['name'],
  1504. p.get('value', ''))
  1505. def SetValid(self, isvalid):
  1506. """!Set instance to be valid/invalid"""
  1507. self.isValid = isvalid
  1508. self._setBrush()
  1509. def SetParameterized(self, isparameterized):
  1510. """!Set action parameterized"""
  1511. self.isParameterized = isparameterized
  1512. self._setPen()
  1513. def IsParameterized(self):
  1514. """!Check if action is parameterized"""
  1515. return self.isParameterized
  1516. def FindData(self, name):
  1517. """!Find data item by name"""
  1518. for rel in self.GetRelations():
  1519. data = rel.GetData()
  1520. if name == rel.GetName() and name in data.GetName():
  1521. return data
  1522. return None
  1523. def Update(self, running = False):
  1524. """!Update action"""
  1525. if running:
  1526. self._setBrush(running = True)
  1527. else:
  1528. self._setBrush()
  1529. self._setPen()
  1530. def OnDraw(self, dc):
  1531. """!Draw action in canvas"""
  1532. self._setBrush()
  1533. self._setPen()
  1534. ogl.RectangleShape.OnDraw(self, dc)
  1535. class ModelData(ModelObject, ogl.EllipseShape):
  1536. def __init__(self, parent, x, y, value = '', prompt = '', width = None, height = None):
  1537. """Data item class
  1538. @param parent window parent
  1539. @param x, y position of the shape
  1540. @param fname, tname list of parameter names from / to
  1541. @param value value
  1542. @param prompt type of GIS element
  1543. @param width, height dimension of the shape
  1544. """
  1545. ModelObject.__init__(self)
  1546. self.parent = parent
  1547. self.value = value
  1548. self.prompt = prompt
  1549. self.intermediate = False
  1550. self.propWin = None
  1551. if not width:
  1552. width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
  1553. if not height:
  1554. height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
  1555. if self.parent.GetCanvas():
  1556. ogl.EllipseShape.__init__(self, width, height)
  1557. self.SetCanvas(self.parent)
  1558. self.SetX(x)
  1559. self.SetY(y)
  1560. self.SetPen(wx.BLACK_PEN)
  1561. self._setBrush()
  1562. self._setText()
  1563. def IsIntermediate(self):
  1564. """!Checks if data item is intermediate"""
  1565. return self.intermediate
  1566. def SetIntermediate(self, im):
  1567. """!Set intermediate flag"""
  1568. self.intermediate = im
  1569. def OnDraw(self, dc):
  1570. pen = self.GetPen()
  1571. pen.SetWidth(1)
  1572. if self.intermediate:
  1573. pen.SetStyle(wx.SHORT_DASH)
  1574. else:
  1575. pen.SetStyle(wx.SOLID)
  1576. self.SetPen(pen)
  1577. ogl.EllipseShape.OnDraw(self, dc)
  1578. def GetLog(self, string = True):
  1579. """!Get logging info"""
  1580. name = list()
  1581. for rel in self.GetRelations():
  1582. name.append(rel.GetName())
  1583. if name:
  1584. return '/'.join(name) + '=' + self.value + ' (' + self.prompt + ')'
  1585. else:
  1586. return self.value + ' (' + self.prompt + ')'
  1587. def GetName(self):
  1588. """!Get list of names"""
  1589. name = list()
  1590. for rel in self.GetRelations():
  1591. name.append(rel.GetName())
  1592. return name
  1593. def GetPrompt(self):
  1594. """!Get prompt"""
  1595. return self.prompt
  1596. def SetPrompt(self, prompt):
  1597. """!Set prompt
  1598. @param prompt
  1599. """
  1600. self.prompt = prompt
  1601. def GetValue(self):
  1602. """!Get value"""
  1603. return self.value
  1604. def SetValue(self, value):
  1605. """!Set value
  1606. @param value
  1607. """
  1608. self.value = value
  1609. self._setText()
  1610. for direction in ('from', 'to'):
  1611. for rel in self.GetRelations(direction):
  1612. if direction == 'from':
  1613. action = rel.GetTo()
  1614. else:
  1615. action = rel.GetFrom()
  1616. task = menuform.GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
  1617. task.set_param(rel.GetName(), self.value)
  1618. action.SetParams(params = task.get_options())
  1619. def AddName(self, name, direction):
  1620. """!Record new name (parameter)
  1621. @param direction direction - 'from' or 'to'
  1622. """
  1623. self.name[direction].append(name)
  1624. def GetPropDialog(self):
  1625. """!Get properties dialog"""
  1626. return self.propWin
  1627. def SetPropDialog(self, win):
  1628. """!Get properties dialog"""
  1629. self.propWin = win
  1630. def _setBrush(self):
  1631. """!Set brush"""
  1632. if self.prompt == 'raster':
  1633. color = UserSettings.Get(group='modeler', key='data',
  1634. subkey=('color', 'raster'))
  1635. elif self.prompt == 'raster3d':
  1636. color = UserSettings.Get(group='modeler', key='data',
  1637. subkey=('color', 'raster3d'))
  1638. elif self.prompt == 'vector':
  1639. color = UserSettings.Get(group='modeler', key='data',
  1640. subkey=('color', 'vector'))
  1641. else:
  1642. color = UserSettings.Get(group='modeler', key='action',
  1643. subkey=('color', 'invalid'))
  1644. wxColor = wx.Color(color[0], color[1], color[2])
  1645. self.SetBrush(wx.Brush(wxColor))
  1646. def _setPen(self):
  1647. """!Set pen"""
  1648. isParameterized = False
  1649. for rel in self.GetRelations('from'):
  1650. if rel.GetTo().IsParameterized():
  1651. isParameterized = True
  1652. break
  1653. if not isParameterized:
  1654. for rel in self.GetRelations('to'):
  1655. if rel.GetFrom().IsParameterized():
  1656. isParameterized = True
  1657. break
  1658. if isParameterized:
  1659. width = int(UserSettings.Get(group='modeler', key='action',
  1660. subkey=('width', 'parameterized')))
  1661. else:
  1662. width = int(UserSettings.Get(group='modeler', key='action',
  1663. subkey=('width', 'default')))
  1664. pen = self.GetPen()
  1665. pen.SetWidth(width)
  1666. self.SetPen(pen)
  1667. def _setText(self):
  1668. """!Update text"""
  1669. self.ClearText()
  1670. name = []
  1671. for rel in self.GetRelations():
  1672. name.append(rel.GetName())
  1673. self.AddText('/'.join(name))
  1674. if self.value:
  1675. self.AddText(self.value)
  1676. else:
  1677. self.AddText(_('<not defined>'))
  1678. def Update(self):
  1679. """!Update action"""
  1680. self._setBrush()
  1681. self._setPen()
  1682. self._setText()
  1683. class ModelDataDialog(ElementDialog):
  1684. """!Data item properties dialog"""
  1685. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Data properties"),
  1686. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1687. self.parent = parent
  1688. self.shape = shape
  1689. label, etype = self._getLabel()
  1690. ElementDialog.__init__(self, parent, title, label = label, etype = etype)
  1691. self.element = gselect.Select(parent = self.panel,
  1692. type = prompt)
  1693. self.element.SetValue(shape.GetValue())
  1694. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  1695. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1696. self.PostInit()
  1697. if shape.GetValue():
  1698. self.btnOK.Enable()
  1699. self._layout()
  1700. self.SetMinSize(self.GetSize())
  1701. def _getLabel(self):
  1702. etype = False
  1703. prompt = self.shape.GetPrompt()
  1704. if prompt == 'raster':
  1705. label = _('Name of raster map:')
  1706. elif prompt == 'vector':
  1707. label = _('Name of vector map:')
  1708. else:
  1709. etype = True
  1710. label = _('Name of element:')
  1711. return label, etype
  1712. def _layout(self):
  1713. """!Do layout"""
  1714. self.dataSizer.Add(self.element, proportion=0,
  1715. flag=wx.EXPAND | wx.ALL, border=1)
  1716. self.panel.SetSizer(self.sizer)
  1717. self.sizer.Fit(self)
  1718. def OnOK(self, event):
  1719. """!Ok pressed"""
  1720. self.shape.SetValue(self.GetElement())
  1721. if self.etype:
  1722. elem = self.GetType()
  1723. if elem == 'rast':
  1724. self.shape.SetPrompt('raster')
  1725. elif elem == 'vect':
  1726. self.shape.SetPrompt('raster')
  1727. self.parent.canvas.Refresh()
  1728. self.parent.SetStatusText('', 0)
  1729. self.OnCancel(event)
  1730. def OnCancel(self, event):
  1731. """!Cancel pressed"""
  1732. self.shape.SetPropDialog(None)
  1733. self.Destroy()
  1734. class ModelEvtHandler(ogl.ShapeEvtHandler):
  1735. """!Model event handler class"""
  1736. def __init__(self, log, frame):
  1737. ogl.ShapeEvtHandler.__init__(self)
  1738. self.log = log
  1739. self.frame = frame
  1740. self.x = self.y = None
  1741. def OnLeftClick(self, x, y, keys = 0, attachment = 0):
  1742. """!Left mouse button pressed -> select item & update statusbar"""
  1743. shape = self.GetShape()
  1744. canvas = shape.GetCanvas()
  1745. dc = wx.ClientDC(canvas)
  1746. canvas.PrepareDC(dc)
  1747. if hasattr(self.frame, 'defineRelation'):
  1748. drel = self.frame.defineRelation
  1749. if drel['from'] is None:
  1750. drel['from'] = shape
  1751. elif drel['to'] is None:
  1752. drel['to'] = shape
  1753. rel = ModelRelation(drel['from'], drel['to'])
  1754. drel['from'].AddRelation(rel)
  1755. self.frame.AddLine(rel)
  1756. del self.frame.defineRelation
  1757. if shape.Selected():
  1758. shape.Select(False, dc)
  1759. else:
  1760. redraw = False
  1761. shapeList = canvas.GetDiagram().GetShapeList()
  1762. toUnselect = list()
  1763. for s in shapeList:
  1764. if s.Selected():
  1765. toUnselect.append(s)
  1766. shape.Select(True, dc)
  1767. for s in toUnselect:
  1768. s.Select(False, dc)
  1769. canvas.Refresh(False)
  1770. if hasattr(shape, "GetLog"):
  1771. self.log.SetStatusText(shape.GetLog(), 0)
  1772. else:
  1773. self.log.SetStatusText('', 0)
  1774. def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):
  1775. """!Left mouse button pressed (double-click) -> show properties"""
  1776. self.OnProperties()
  1777. def OnProperties(self, event = None):
  1778. """!Show properties dialog"""
  1779. self.frame.ModelChanged()
  1780. shape = self.GetShape()
  1781. if isinstance(shape, ModelAction):
  1782. module = menuform.GUI(parent = self.frame, show = True).ParseCommand(shape.GetLog(string = False),
  1783. completed = (self.frame.GetOptData, shape, shape.GetParams()))
  1784. elif isinstance(shape, ModelData):
  1785. dlg = ModelDataDialog(parent = self.frame, shape = shape)
  1786. shape.SetPropDialog(dlg)
  1787. dlg.CentreOnParent()
  1788. dlg.Show()
  1789. elif isinstance(shape, ModelLoop):
  1790. dlg = ModelLoopDialog(parent = self.frame, shape = shape)
  1791. dlg.CentreOnParent()
  1792. if dlg.ShowModal() == wx.ID_OK:
  1793. shape.SetText(dlg.GetCondition())
  1794. alist = list()
  1795. ids = dlg.GetItems()
  1796. for aId in ids['unchecked']:
  1797. action = self.frame.GetModel().GetItem(aId)
  1798. action.UnSetBlock(shape)
  1799. for aId in ids['checked']:
  1800. action = self.frame.GetModel().GetItem(aId)
  1801. action.SetBlock(shape)
  1802. if action:
  1803. alist.append(action)
  1804. shape.SetItems(alist)
  1805. self.frame.DefineLoop(shape)
  1806. self.frame.GetCanvas().Refresh()
  1807. dlg.Destroy()
  1808. elif isinstance(shape, ModelCondition):
  1809. dlg = ModelConditionDialog(parent = self.frame, shape = shape)
  1810. dlg.CentreOnParent()
  1811. if dlg.ShowModal() == wx.ID_OK:
  1812. shape.SetText(dlg.GetCondition())
  1813. ids = dlg.GetItems()
  1814. for b in ids.keys():
  1815. alist = list()
  1816. for aId in ids[b]['unchecked']:
  1817. action = self.frame.GetModel().GetItem(aId)
  1818. action.UnSetBlock(shape)
  1819. for aId in ids[b]['checked']:
  1820. action = self.frame.GetModel().GetItem(aId)
  1821. action.SetBlock(shape)
  1822. if action:
  1823. alist.append(action)
  1824. shape.SetItems(alist, branch = b)
  1825. self.frame.DefineCondition(shape)
  1826. self.frame.GetCanvas().Refresh()
  1827. dlg.Destroy()
  1828. def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):
  1829. """!Drag shape (begining)"""
  1830. self.frame.ModelChanged()
  1831. if self._previousHandler:
  1832. self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)
  1833. def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):
  1834. """!Drag shape (end)"""
  1835. if self._previousHandler:
  1836. self._previousHandler.OnEndDragLeft(x, y, keys, attachment)
  1837. shape = self.GetShape()
  1838. if isinstance(shape, ModelLoop):
  1839. self.frame.DefineLoop(shape)
  1840. elif isinstance(shape, ModelCondition):
  1841. self.frame.DefineCondition(shape)
  1842. for mo in shape.GetBlock():
  1843. if isinstance(mo, ModelLoop):
  1844. self.frame.DefineLoop(mo)
  1845. elif isinstance(mo, ModelCondition):
  1846. self.frame.DefineCondition(mo)
  1847. def OnEndSize(self, x, y):
  1848. """!Resize shape"""
  1849. self.frame.ModelChanged()
  1850. if self._previousHandler:
  1851. self._previousHandler.OnEndSize(x, y)
  1852. def OnRightClick(self, x, y, keys = 0, attachment = 0):
  1853. """!Right click -> pop-up menu"""
  1854. if not hasattr (self, "popupID1"):
  1855. self.popupID1 = wx.NewId()
  1856. self.popupID2 = wx.NewId()
  1857. self.popupID3 = wx.NewId()
  1858. self.popupID4 = wx.NewId()
  1859. # record coordinates
  1860. self.x = x
  1861. self.y = y
  1862. shape = self.GetShape()
  1863. popupMenu = wx.Menu()
  1864. popupMenu.Append(self.popupID1, text=_('Remove'))
  1865. self.frame.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  1866. if isinstance(shape, ModelAction):
  1867. if shape.IsEnabled():
  1868. popupMenu.Append(self.popupID3, text=_('Disable'))
  1869. self.frame.Bind(wx.EVT_MENU, self.OnDisable, id = self.popupID3)
  1870. else:
  1871. popupMenu.Append(self.popupID3, text=_('Enable'))
  1872. self.frame.Bind(wx.EVT_MENU, self.OnEnable, id = self.popupID3)
  1873. if isinstance(shape, ModelRelation):
  1874. popupMenu.AppendSeparator()
  1875. popupMenu.Append(self.popupID2, text=_('Add control point'))
  1876. self.frame.Bind(wx.EVT_MENU, self.OnAddPoint, id = self.popupID2)
  1877. popupMenu.Append(self.popupID3, text=_('Remove control point'))
  1878. self.frame.Bind(wx.EVT_MENU, self.OnRemovePoint, id = self.popupID3)
  1879. if len(shape.GetLineControlPoints()) == 2:
  1880. popupMenu.Enable(self.popupID3, False)
  1881. if isinstance(shape, ModelData) and '@' not in shape.GetValue():
  1882. popupMenu.AppendSeparator()
  1883. popupMenu.Append(self.popupID3, text=_('Intermediate'),
  1884. kind = wx.ITEM_CHECK)
  1885. if self.GetShape().IsIntermediate():
  1886. popupMenu.Check(self.popupID3, True)
  1887. self.frame.Bind(wx.EVT_MENU, self.OnIntermediate, id = self.popupID3)
  1888. if isinstance(shape, ModelData) or \
  1889. isinstance(shape, ModelAction) or \
  1890. isinstance(shape, ModelLoop):
  1891. popupMenu.AppendSeparator()
  1892. popupMenu.Append(self.popupID2, text=_('Properties'))
  1893. self.frame.Bind(wx.EVT_MENU, self.OnProperties, id = self.popupID2)
  1894. if isinstance(shape, ModelAction):
  1895. popupMenu.Append(self.popupID4, text=_('Change ID'))
  1896. self.frame.Bind(wx.EVT_MENU, self.OnChangeId, id = self.popupID3)
  1897. self.frame.PopupMenu(popupMenu)
  1898. popupMenu.Destroy()
  1899. def OnChangeId(self, event):
  1900. """!Change action id"""
  1901. pass
  1902. def OnDisable(self, event):
  1903. """!Disable action"""
  1904. action = self.GetShape()
  1905. action.Enable(False)
  1906. self.frame.ModelChanged()
  1907. self.frame.canvas.Refresh()
  1908. def OnEnable(self, event):
  1909. """!Disable action"""
  1910. action = self.GetShape()
  1911. action.Enable(True)
  1912. self.frame.ModelChanged()
  1913. self.frame.canvas.Refresh()
  1914. def OnAddPoint(self, event):
  1915. """!Add control point"""
  1916. shape = self.GetShape()
  1917. shape.InsertLineControlPoint(point = wx.RealPoint(self.x, self.y))
  1918. shape.ResetShapes()
  1919. shape.Select(True)
  1920. self.frame.ModelChanged()
  1921. self.frame.canvas.Refresh()
  1922. def OnRemovePoint(self, event):
  1923. """!Remove control point"""
  1924. shape = self.GetShape()
  1925. shape.DeleteLineControlPoint()
  1926. shape.Select(False)
  1927. shape.Select(True)
  1928. self.frame.ModelChanged()
  1929. self.frame.canvas.Refresh()
  1930. def OnIntermediate(self, event):
  1931. """!Mark data as intermediate"""
  1932. self.frame.ModelChanged()
  1933. shape = self.GetShape()
  1934. shape.SetIntermediate(event.IsChecked())
  1935. self.frame.canvas.Refresh()
  1936. def OnRemove(self, event):
  1937. """!Remove shape
  1938. """
  1939. self.frame.GetCanvas().RemoveSelected()
  1940. self.frame.itemPanel.Update()
  1941. class ModelSearchDialog(wx.Dialog):
  1942. def __init__(self, parent, id = wx.ID_ANY, title = _("Add new GRASS module to the model"),
  1943. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  1944. """!Graphical modeler module search window
  1945. @param parent parent window
  1946. @param id window id
  1947. @param title window title
  1948. @param kwargs wx.Dialogs' arguments
  1949. """
  1950. self.parent = parent
  1951. wx.Dialog.__init__(self, parent = parent, id = id, title = title, **kwargs)
  1952. self.SetName("ModelerDialog")
  1953. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  1954. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1955. self.cmdBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1956. label=" %s " % _("Command"))
  1957. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  1958. self.search = SearchModuleWindow(parent = self.panel, cmdPrompt = self.cmd_prompt, showTip = True)
  1959. wx.CallAfter(self.cmd_prompt.SetFocus)
  1960. # get commands
  1961. items = self.cmd_prompt.GetCommandItems()
  1962. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  1963. self.btnOk = wx.Button(self.panel, wx.ID_OK)
  1964. self.btnOk.SetDefault()
  1965. self.btnOk.Enable(False)
  1966. self.cmd_prompt.Bind(wx.EVT_CHAR, self.OnText)
  1967. self.search.searchChoice.Bind(wx.EVT_CHOICE, self.OnText)
  1968. self.Bind(wx.EVT_BUTTON, self.OnOk, self.btnOk)
  1969. self._layout()
  1970. self.SetSize((500, 275))
  1971. def _layout(self):
  1972. cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
  1973. cmdSizer.Add(item = self.cmd_prompt, proportion = 1,
  1974. flag = wx.EXPAND)
  1975. btnSizer = wx.StdDialogButtonSizer()
  1976. btnSizer.AddButton(self.btnCancel)
  1977. btnSizer.AddButton(self.btnOk)
  1978. btnSizer.Realize()
  1979. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1980. mainSizer.Add(item = self.search, proportion = 0,
  1981. flag = wx.EXPAND | wx.ALL, border = 3)
  1982. mainSizer.Add(item = cmdSizer, proportion = 1,
  1983. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  1984. mainSizer.Add(item = btnSizer, proportion = 0,
  1985. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  1986. self.panel.SetSizer(mainSizer)
  1987. mainSizer.Fit(self.panel)
  1988. self.Layout()
  1989. def GetPanel(self):
  1990. """!Get dialog panel"""
  1991. return self.panel
  1992. def GetCmd(self):
  1993. """!Get command"""
  1994. line = self.cmd_prompt.GetCurLine()[0].strip()
  1995. if len(line) == 0:
  1996. list()
  1997. try:
  1998. cmd = utils.split(str(line))
  1999. except UnicodeError:
  2000. cmd = utils.split(utils.EncodeString((line)))
  2001. return cmd
  2002. def OnOk(self, event):
  2003. self.btnOk.SetFocus()
  2004. cmd = self.GetCmd()
  2005. if len(cmd) < 1:
  2006. GError(parent = self,
  2007. message = _("Command not defined.\n\n"
  2008. "Unable to add new action to the model."))
  2009. return
  2010. if cmd[0] not in globalvar.grassCmd['all']:
  2011. GError(parent = self,
  2012. message = _("'%s' is not a GRASS module.\n\n"
  2013. "Unable to add new action to the model.") % cmd[0])
  2014. return
  2015. self.EndModal(wx.ID_OK)
  2016. def OnText(self, event):
  2017. """!Text entered"""
  2018. if self.cmd_prompt.AutoCompActive():
  2019. event.Skip()
  2020. return
  2021. if isinstance(event, wx.KeyEvent):
  2022. entry = self.cmd_prompt.GetTextLeft() # FIXME
  2023. else:
  2024. entry = event.GetString()
  2025. if entry:
  2026. self.btnOk.Enable()
  2027. else:
  2028. self.btnOk.Enable(False)
  2029. event.Skip()
  2030. def Reset(self):
  2031. """!Reset dialog"""
  2032. self.search.Reset()
  2033. self.cmd_prompt.OnCmdErase(None)
  2034. class ModelRelation(ogl.LineShape):
  2035. """!Data - action relation"""
  2036. def __init__(self, fromShape, toShape, param = ''):
  2037. self.fromShape = fromShape
  2038. self.toShape = toShape
  2039. self.param = param
  2040. self._points = None
  2041. ogl.LineShape.__init__(self)
  2042. def __del__(self):
  2043. self.fromShape.rels.remove(self)
  2044. self.toShape.rels.remove(self)
  2045. def GetFrom(self):
  2046. """!Get id of 'from' shape"""
  2047. return self.fromShape
  2048. def GetTo(self):
  2049. """!Get id of 'to' shape"""
  2050. return self.toShape
  2051. def GetData(self):
  2052. """!Get related ModelData instance
  2053. @return ModelData instance
  2054. @return None if not found
  2055. """
  2056. if isinstance(self.fromShape, ModelData):
  2057. return self.fromShape
  2058. elif isinstance(self.toShape, ModelData):
  2059. return self.toShape
  2060. return None
  2061. def GetName(self):
  2062. """!Get parameter name"""
  2063. return self.param
  2064. def ResetShapes(self):
  2065. """!Reset related objects"""
  2066. self.fromShape.ResetControlPoints()
  2067. self.toShape.ResetControlPoints()
  2068. self.ResetControlPoints()
  2069. def SetControlPoints(self, points):
  2070. """!Set control points"""
  2071. self._points = points
  2072. def GetControlPoints(self):
  2073. """!Get list of control points"""
  2074. return self._points
  2075. def _setPen(self):
  2076. """!Set pen"""
  2077. pen = self.GetPen()
  2078. pen.SetWidth(1)
  2079. pen.SetStyle(wx.SOLID)
  2080. self.SetPen(pen)
  2081. def OnDraw(self, dc):
  2082. """!Draw relation"""
  2083. self._setPen()
  2084. ogl.LineShape.OnDraw(self, dc)
  2085. class ProcessModelFile:
  2086. """!Process GRASS model file (gxm)"""
  2087. def __init__(self, tree):
  2088. """!A ElementTree handler for the GXM XML file, as defined in
  2089. grass-gxm.dtd.
  2090. """
  2091. self.tree = tree
  2092. self.root = self.tree.getroot()
  2093. # list of actions, data
  2094. self.properties = dict()
  2095. self.variables = dict()
  2096. self.actions = list()
  2097. self.data = list()
  2098. self.loops = list()
  2099. self.conditions = list()
  2100. self._processWindow()
  2101. self._processProperties()
  2102. self._processVariables()
  2103. self._processItems()
  2104. self._processData()
  2105. def _filterValue(self, value):
  2106. """!Filter value
  2107. @param value
  2108. """
  2109. value = value.replace('&lt;', '<')
  2110. value = value.replace('&gt;', '>')
  2111. return value
  2112. def _getNodeText(self, node, tag, default = ''):
  2113. """!Get node text"""
  2114. p = node.find(tag)
  2115. if p is not None:
  2116. if p.text:
  2117. return utils.normalize_whitespace(p.text)
  2118. else:
  2119. return ''
  2120. return default
  2121. def _processWindow(self):
  2122. """!Process window properties"""
  2123. node = self.root.find('window')
  2124. if node is None:
  2125. self.pos = self.size = None
  2126. return
  2127. self.pos, self.size = self._getDim(node)
  2128. def _processProperties(self):
  2129. """!Process model properties"""
  2130. node = self.root.find('properties')
  2131. if node is None:
  2132. return
  2133. for key in ('name', 'description', 'author'):
  2134. self._processProperty(node, key)
  2135. for f in node.findall('flag'):
  2136. name = f.get('name', '')
  2137. if name == 'overwrite':
  2138. self.properties['overwrite'] = True
  2139. def _processProperty(self, pnode, name):
  2140. """!Process given property"""
  2141. node = pnode.find(name)
  2142. if node is not None:
  2143. self.properties[name] = node.text
  2144. else:
  2145. self.properties[name] = ''
  2146. def _processVariables(self):
  2147. """!Process model variables"""
  2148. vnode = self.root.find('variables')
  2149. if vnode is None:
  2150. return
  2151. for node in vnode.findall('variable'):
  2152. name = node.get('name', '')
  2153. if not name:
  2154. continue # should not happen
  2155. self.variables[name] = { 'type' : node.get('type', 'string') }
  2156. for key in ('description', 'value'):
  2157. self._processVariable(node, name, key)
  2158. def _processVariable(self, pnode, name, key):
  2159. """!Process given variable"""
  2160. node = pnode.find(key)
  2161. if node is not None:
  2162. if node.text:
  2163. self.variables[name][key] = node.text
  2164. def _processItems(self):
  2165. """!Process model items (actions, loops, conditions)"""
  2166. self._processActions()
  2167. self._processLoops()
  2168. self._processConditions()
  2169. def _processActions(self):
  2170. """!Process model file"""
  2171. for action in self.root.findall('action'):
  2172. pos, size = self._getDim(action)
  2173. disabled = False
  2174. task = action.find('task')
  2175. if task is not None:
  2176. if task.find('disabled') is not None:
  2177. disabled = True
  2178. task = self._processTask(task)
  2179. else:
  2180. task = None
  2181. aId = int(action.get('id', -1))
  2182. self.actions.append({ 'pos' : pos,
  2183. 'size' : size,
  2184. 'task' : task,
  2185. 'id' : aId,
  2186. 'disabled' : disabled })
  2187. def _getDim(self, node):
  2188. """!Get position and size of shape"""
  2189. pos = size = None
  2190. posAttr = node.get('pos', None)
  2191. if posAttr:
  2192. posVal = map(int, posAttr.split(','))
  2193. try:
  2194. pos = (posVal[0], posVal[1])
  2195. except:
  2196. pos = None
  2197. sizeAttr = node.get('size', None)
  2198. if sizeAttr:
  2199. sizeVal = map(int, sizeAttr.split(','))
  2200. try:
  2201. size = (sizeVal[0], sizeVal[1])
  2202. except:
  2203. size = None
  2204. return pos, size
  2205. def _processData(self):
  2206. """!Process model file"""
  2207. for data in self.root.findall('data'):
  2208. pos, size = self._getDim(data)
  2209. param = data.find('data-parameter')
  2210. prompt = value = None
  2211. if param is not None:
  2212. prompt = param.get('prompt', None)
  2213. value = self._filterValue(self._getNodeText(param, 'value'))
  2214. if data.find('intermediate') is None:
  2215. intermediate = False
  2216. else:
  2217. intermediate = True
  2218. rels = list()
  2219. for rel in data.findall('relation'):
  2220. defrel = { 'id' : int(rel.get('id', -1)),
  2221. 'dir' : rel.get('dir', 'to'),
  2222. 'name' : rel.get('name', '') }
  2223. points = list()
  2224. for point in rel.findall('point'):
  2225. x = self._filterValue(self._getNodeText(point, 'x'))
  2226. y = self._filterValue(self._getNodeText(point, 'y'))
  2227. points.append((float(x), float(y)))
  2228. defrel['points'] = points
  2229. rels.append(defrel)
  2230. self.data.append({ 'pos' : pos,
  2231. 'size': size,
  2232. 'prompt' : prompt,
  2233. 'value' : value,
  2234. 'intermediate' : intermediate,
  2235. 'rels' : rels })
  2236. def _processTask(self, node):
  2237. """!Process task
  2238. @return grassTask instance
  2239. @return None on error
  2240. """
  2241. cmd = list()
  2242. parameterized = list()
  2243. name = node.get('name', None)
  2244. if not name:
  2245. return None
  2246. cmd.append(name)
  2247. # flags
  2248. for f in node.findall('flag'):
  2249. flag = f.get('name', '')
  2250. if f.get('parameterized', '0') == '1':
  2251. parameterized.append(('flag', flag))
  2252. if f.get('value', '1') == '0':
  2253. continue
  2254. if len(flag) > 1:
  2255. cmd.append('--' + flag)
  2256. else:
  2257. cmd.append('-' + flag)
  2258. # parameters
  2259. for p in node.findall('parameter'):
  2260. name = p.get('name', '')
  2261. if p.find('parameterized') is not None:
  2262. parameterized.append(('param', name))
  2263. cmd.append('%s=%s' % (name,
  2264. self._filterValue(self._getNodeText(p, 'value'))))
  2265. task, err = menuform.GUI(show = None, checkError = True).ParseCommand(cmd = cmd)
  2266. if err:
  2267. GWarning(os.linesep.join(err))
  2268. for opt, name in parameterized:
  2269. if opt == 'flag':
  2270. task.set_flag(name, True, element = 'parameterized')
  2271. else:
  2272. task.set_param(name, True, element = 'parameterized')
  2273. return task
  2274. def _processLoops(self):
  2275. """!Process model loops"""
  2276. for node in self.root.findall('loop'):
  2277. pos, size = self._getDim(node)
  2278. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  2279. aid = list()
  2280. for anode in node.findall('item'):
  2281. try:
  2282. aid.append(int(anode.text))
  2283. except ValueError:
  2284. pass
  2285. self.loops.append({ 'pos' : pos,
  2286. 'size' : size,
  2287. 'text' : text,
  2288. 'id' : int(node.get('id', -1)),
  2289. 'items' : aid })
  2290. def _processConditions(self):
  2291. """!Process model conditions"""
  2292. for node in self.root.findall('if-else'):
  2293. pos, size = self._getDim(node)
  2294. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  2295. aid = { 'if' : list(),
  2296. 'else' : list() }
  2297. for b in aid.keys():
  2298. bnode = node.find(b)
  2299. if bnode is None:
  2300. continue
  2301. for anode in bnode.findall('item'):
  2302. try:
  2303. aid[b].append(int(anode.text))
  2304. except ValueError:
  2305. pass
  2306. self.conditions.append({ 'pos' : pos,
  2307. 'size' : size,
  2308. 'text' : text,
  2309. 'id' : int(node.get('id', -1)),
  2310. 'items' : aid })
  2311. class WriteModelFile:
  2312. """!Generic class for writing model file"""
  2313. def __init__(self, fd, model):
  2314. self.fd = fd
  2315. self.model = model
  2316. self.properties = model.GetProperties()
  2317. self.variables = model.GetVariables()
  2318. self.items = model.GetItems()
  2319. self.indent = 0
  2320. self._header()
  2321. self._window()
  2322. self._properties()
  2323. self._variables()
  2324. self._items()
  2325. dataList = list()
  2326. for action in model.GetItems(objType = ModelAction):
  2327. for rel in action.GetRelations():
  2328. dataItem = rel.GetData()
  2329. if dataItem not in dataList:
  2330. dataList.append(dataItem)
  2331. self._data(dataList)
  2332. self._footer()
  2333. def _filterValue(self, value):
  2334. """!Make value XML-valid"""
  2335. value = value.replace('<', '&lt;')
  2336. value = value.replace('>', '&gt;')
  2337. return value
  2338. def _header(self):
  2339. """!Write header"""
  2340. self.fd.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  2341. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  2342. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  2343. self.indent += 4
  2344. def _footer(self):
  2345. """!Write footer"""
  2346. self.indent -= 4
  2347. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  2348. def _window(self):
  2349. """!Write window properties"""
  2350. canvas = self.model.GetCanvas()
  2351. if canvas is None:
  2352. return
  2353. win = canvas.parent
  2354. pos = win.GetPosition()
  2355. size = win.GetSize()
  2356. self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' % \
  2357. (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
  2358. def _properties(self):
  2359. """!Write model properties"""
  2360. self.fd.write('%s<properties>\n' % (' ' * self.indent))
  2361. self.indent += 4
  2362. if self.properties['name']:
  2363. self.fd.write('%s<name>%s</name>\n' % (' ' * self.indent, self.properties['name']))
  2364. if self.properties['description']:
  2365. self.fd.write('%s<description>%s</description>\n' % (' ' * self.indent, self.properties['description']))
  2366. if self.properties['author']:
  2367. self.fd.write('%s<author>%s</author>\n' % (' ' * self.indent, self.properties['author']))
  2368. if 'overwrite' in self.properties and \
  2369. self.properties['overwrite']:
  2370. self.fd.write('%s<flag name="overwrite" />\n' % (' ' * self.indent))
  2371. self.indent -= 4
  2372. self.fd.write('%s</properties>\n' % (' ' * self.indent))
  2373. def _variables(self):
  2374. """!Write model variables"""
  2375. if not self.variables:
  2376. return
  2377. self.fd.write('%s<variables>\n' % (' ' * self.indent))
  2378. self.indent += 4
  2379. for name, values in self.variables.iteritems():
  2380. self.fd.write('%s<variable name="%s" type="%s">\n' % \
  2381. (' ' * self.indent, name, values['type']))
  2382. self.indent += 4
  2383. if 'value' in values:
  2384. self.fd.write('%s<value>%s</value>\n' % \
  2385. (' ' * self.indent, values['value']))
  2386. if 'description' in values:
  2387. self.fd.write('%s<description>%s</description>\n' % \
  2388. (' ' * self.indent, values['description']))
  2389. self.indent -= 4
  2390. self.fd.write('%s</variable>\n' % (' ' * self.indent))
  2391. self.indent -= 4
  2392. self.fd.write('%s</variables>\n' % (' ' * self.indent))
  2393. def _items(self):
  2394. """!Write actions/loops/conditions"""
  2395. for item in self.items:
  2396. if isinstance(item, ModelAction):
  2397. self._action(item)
  2398. elif isinstance(item, ModelLoop):
  2399. self._loop(item)
  2400. elif isinstance(item, ModelCondition):
  2401. self._condition(item)
  2402. def _action(self, action):
  2403. """!Write actions"""
  2404. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  2405. (' ' * self.indent, action.GetId(), action.GetName(), action.GetX(), action.GetY(),
  2406. action.GetWidth(), action.GetHeight()))
  2407. self.indent += 4
  2408. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  2409. self.indent += 4
  2410. if not action.IsEnabled():
  2411. self.fd.write('%s<disabled />\n' % (' ' * self.indent))
  2412. for key, val in action.GetParams().iteritems():
  2413. if key == 'flags':
  2414. for f in val:
  2415. if f.get('value', False) or f.get('parameterized', False):
  2416. if f.get('parameterized', False):
  2417. if f.get('value', False) == False:
  2418. self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
  2419. (' ' * self.indent, f.get('name', '')))
  2420. else:
  2421. self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
  2422. (' ' * self.indent, f.get('name', '')))
  2423. else:
  2424. self.fd.write('%s<flag name="%s" />\n' %
  2425. (' ' * self.indent, f.get('name', '')))
  2426. else: # parameter
  2427. for p in val:
  2428. if not p.get('value', ''):
  2429. continue
  2430. self.fd.write('%s<parameter name="%s">\n' %
  2431. (' ' * self.indent, p.get('name', '')))
  2432. self.indent += 4
  2433. if p.get('parameterized', False):
  2434. self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
  2435. self.fd.write('%s<value>%s</value>\n' %
  2436. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  2437. self.indent -= 4
  2438. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  2439. self.indent -= 4
  2440. self.fd.write('%s</task>\n' % (' ' * self.indent))
  2441. self.indent -= 4
  2442. self.fd.write('%s</action>\n' % (' ' * self.indent))
  2443. def _data(self, dataList):
  2444. """!Write data"""
  2445. for data in dataList:
  2446. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  2447. (' ' * self.indent, data.GetX(), data.GetY(),
  2448. data.GetWidth(), data.GetHeight()))
  2449. self.indent += 4
  2450. self.fd.write('%s<data-parameter prompt="%s">\n' % \
  2451. (' ' * self.indent, data.GetPrompt()))
  2452. self.indent += 4
  2453. self.fd.write('%s<value>%s</value>\n' %
  2454. (' ' * self.indent, self._filterValue(data.GetValue())))
  2455. self.indent -= 4
  2456. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  2457. if data.IsIntermediate():
  2458. self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
  2459. # relations
  2460. for ft in ('from', 'to'):
  2461. for rel in data.GetRelations(ft):
  2462. if ft == 'from':
  2463. aid = rel.GetTo().GetId()
  2464. else:
  2465. aid = rel.GetFrom().GetId()
  2466. self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' % \
  2467. (' ' * self.indent, ft, aid, rel.GetName()))
  2468. self.indent += 4
  2469. for point in rel.GetLineControlPoints()[1:-1]:
  2470. self.fd.write('%s<point>\n' % (' ' * self.indent))
  2471. self.indent += 4
  2472. x, y = point.Get()
  2473. self.fd.write('%s<x>%d</x>\n' % (' ' * self.indent, int(x)))
  2474. self.fd.write('%s<y>%d</y>\n' % (' ' * self.indent, int(y)))
  2475. self.indent -= 4
  2476. self.fd.write('%s</point>\n' % (' ' * self.indent))
  2477. self.indent -= 4
  2478. self.fd.write('%s</relation>\n' % (' ' * self.indent))
  2479. self.indent -= 4
  2480. self.fd.write('%s</data>\n' % (' ' * self.indent))
  2481. def _loop(self, loop):
  2482. """!Write loops"""
  2483. self.fd.write('%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' % \
  2484. (' ' * self.indent, loop.GetId(), loop.GetX(), loop.GetY(),
  2485. loop.GetWidth(), loop.GetHeight()))
  2486. text = loop.GetText()
  2487. self.indent += 4
  2488. if text:
  2489. self.fd.write('%s<condition>%s</condition>\n' %
  2490. (' ' * self.indent, self._filterValue(text)))
  2491. for item in loop.GetItems():
  2492. self.fd.write('%s<item>%d</item>\n' %
  2493. (' ' * self.indent, item.GetId()))
  2494. self.indent -= 4
  2495. self.fd.write('%s</loop>\n' % (' ' * self.indent))
  2496. def _condition(self, condition):
  2497. """!Write conditions"""
  2498. bbox = condition.GetBoundingBoxMin()
  2499. self.fd.write('%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' % \
  2500. (' ' * self.indent, condition.GetId(), condition.GetX(), condition.GetY(),
  2501. bbox[0], bbox[1]))
  2502. text = condition.GetText()
  2503. self.indent += 4
  2504. if text:
  2505. self.fd.write('%s<condition>%s</condition>\n' %
  2506. (' ' * self.indent, self._filterValue(text)))
  2507. items = condition.GetItems()
  2508. for b in items.keys():
  2509. if len(items[b]) < 1:
  2510. continue
  2511. self.fd.write('%s<%s>\n' % (' ' * self.indent, b))
  2512. self.indent += 4
  2513. for item in items[b]:
  2514. self.fd.write('%s<item>%d</item>\n' %
  2515. (' ' * self.indent, item.GetId()))
  2516. self.indent -= 4
  2517. self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
  2518. self.indent -= 4
  2519. self.fd.write('%s</if-else>\n' % (' ' * self.indent))
  2520. class PreferencesDialog(PreferencesBaseDialog):
  2521. """!User preferences dialog"""
  2522. def __init__(self, parent, settings = UserSettings,
  2523. title = _("Modeler settings")):
  2524. PreferencesBaseDialog.__init__(self, parent = parent, title = title,
  2525. settings = settings)
  2526. # create notebook pages
  2527. self._createActionPage(self.notebook)
  2528. self._createDataPage(self.notebook)
  2529. self.SetMinSize(self.GetBestSize())
  2530. self.SetSize(self.size)
  2531. def _createActionPage(self, notebook):
  2532. """!Create notebook page for action settings"""
  2533. panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
  2534. notebook.AddPage(page = panel, text = _("Action"))
  2535. # colors
  2536. border = wx.BoxSizer(wx.VERTICAL)
  2537. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  2538. label = " %s " % _("Validity"))
  2539. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2540. gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
  2541. gridSizer.AddGrowableCol(0)
  2542. row = 0
  2543. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2544. label = _("Valid:")),
  2545. flag = wx.ALIGN_LEFT |
  2546. wx.ALIGN_CENTER_VERTICAL,
  2547. pos = (row, 0))
  2548. vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2549. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'valid')),
  2550. size = globalvar.DIALOG_COLOR_SIZE)
  2551. vColor.SetName('GetColour')
  2552. self.winId['modeler:action:color:valid'] = vColor.GetId()
  2553. gridSizer.Add(item = vColor,
  2554. flag = wx.ALIGN_RIGHT |
  2555. wx.ALIGN_CENTER_VERTICAL,
  2556. pos = (row, 1))
  2557. row += 1
  2558. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2559. label = _("Invalid:")),
  2560. flag = wx.ALIGN_LEFT |
  2561. wx.ALIGN_CENTER_VERTICAL,
  2562. pos = (row, 0))
  2563. iColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2564. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'invalid')),
  2565. size = globalvar.DIALOG_COLOR_SIZE)
  2566. iColor.SetName('GetColour')
  2567. self.winId['modeler:action:color:invalid'] = iColor.GetId()
  2568. gridSizer.Add(item = iColor,
  2569. flag = wx.ALIGN_RIGHT |
  2570. wx.ALIGN_CENTER_VERTICAL,
  2571. pos = (row, 1))
  2572. row += 1
  2573. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2574. label = _("Running:")),
  2575. flag = wx.ALIGN_LEFT |
  2576. wx.ALIGN_CENTER_VERTICAL,
  2577. pos = (row, 0))
  2578. rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2579. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'running')),
  2580. size = globalvar.DIALOG_COLOR_SIZE)
  2581. rColor.SetName('GetColour')
  2582. self.winId['modeler:action:color:running'] = rColor.GetId()
  2583. gridSizer.Add(item = rColor,
  2584. flag = wx.ALIGN_RIGHT |
  2585. wx.ALIGN_CENTER_VERTICAL,
  2586. pos = (row, 1))
  2587. row += 1
  2588. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2589. label = _("Disabled:")),
  2590. flag = wx.ALIGN_LEFT |
  2591. wx.ALIGN_CENTER_VERTICAL,
  2592. pos = (row, 0))
  2593. rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2594. colour = self.settings.Get(group='modeler', key='action', subkey=('color', 'disabled')),
  2595. size = globalvar.DIALOG_COLOR_SIZE)
  2596. rColor.SetName('GetColour')
  2597. self.winId['modeler:action:color:disabled'] = rColor.GetId()
  2598. gridSizer.Add(item = rColor,
  2599. flag = wx.ALIGN_RIGHT |
  2600. wx.ALIGN_CENTER_VERTICAL,
  2601. pos = (row, 1))
  2602. sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
  2603. border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  2604. # size
  2605. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  2606. label = " %s " % _("Shape size"))
  2607. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2608. gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
  2609. gridSizer.AddGrowableCol(0)
  2610. row = 0
  2611. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2612. label = _("Width:")),
  2613. flag = wx.ALIGN_LEFT |
  2614. wx.ALIGN_CENTER_VERTICAL,
  2615. pos = (row, 0))
  2616. width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  2617. min = 0, max = 500,
  2618. initial = self.settings.Get(group='modeler', key='action', subkey=('size', 'width')))
  2619. width.SetName('GetValue')
  2620. self.winId['modeler:action:size:width'] = width.GetId()
  2621. gridSizer.Add(item = width,
  2622. flag = wx.ALIGN_RIGHT |
  2623. wx.ALIGN_CENTER_VERTICAL,
  2624. pos = (row, 1))
  2625. row += 1
  2626. gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
  2627. label=_("Height:")),
  2628. flag = wx.ALIGN_LEFT |
  2629. wx.ALIGN_CENTER_VERTICAL,
  2630. pos=(row, 0))
  2631. height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  2632. min = 0, max = 500,
  2633. initial = self.settings.Get(group='modeler', key='action', subkey=('size', 'height')))
  2634. height.SetName('GetValue')
  2635. self.winId['modeler:action:size:height'] = height.GetId()
  2636. gridSizer.Add(item = height,
  2637. flag = wx.ALIGN_RIGHT |
  2638. wx.ALIGN_CENTER_VERTICAL,
  2639. pos = (row, 1))
  2640. sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
  2641. border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
  2642. panel.SetSizer(border)
  2643. return panel
  2644. def _createDataPage(self, notebook):
  2645. """!Create notebook page for data settings"""
  2646. panel = wx.Panel(parent = notebook, id = wx.ID_ANY)
  2647. notebook.AddPage(page = panel, text = _("Data"))
  2648. # colors
  2649. border = wx.BoxSizer(wx.VERTICAL)
  2650. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  2651. label = " %s " % _("Type"))
  2652. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2653. gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
  2654. gridSizer.AddGrowableCol(0)
  2655. row = 0
  2656. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2657. label = _("Raster:")),
  2658. flag = wx.ALIGN_LEFT |
  2659. wx.ALIGN_CENTER_VERTICAL,
  2660. pos = (row, 0))
  2661. rColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2662. colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'raster')),
  2663. size = globalvar.DIALOG_COLOR_SIZE)
  2664. rColor.SetName('GetColour')
  2665. self.winId['modeler:data:color:raster'] = rColor.GetId()
  2666. gridSizer.Add(item = rColor,
  2667. flag = wx.ALIGN_RIGHT |
  2668. wx.ALIGN_CENTER_VERTICAL,
  2669. pos = (row, 1))
  2670. row += 1
  2671. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2672. label = _("3D raster:")),
  2673. flag = wx.ALIGN_LEFT |
  2674. wx.ALIGN_CENTER_VERTICAL,
  2675. pos = (row, 0))
  2676. r3Color = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2677. colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'raster3d')),
  2678. size = globalvar.DIALOG_COLOR_SIZE)
  2679. r3Color.SetName('GetColour')
  2680. self.winId['modeler:data:color:raster3d'] = r3Color.GetId()
  2681. gridSizer.Add(item = r3Color,
  2682. flag = wx.ALIGN_RIGHT |
  2683. wx.ALIGN_CENTER_VERTICAL,
  2684. pos = (row, 1))
  2685. row += 1
  2686. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2687. label = _("Vector:")),
  2688. flag = wx.ALIGN_LEFT |
  2689. wx.ALIGN_CENTER_VERTICAL,
  2690. pos = (row, 0))
  2691. vColor = csel.ColourSelect(parent = panel, id = wx.ID_ANY,
  2692. colour = self.settings.Get(group='modeler', key='data', subkey=('color', 'vector')),
  2693. size = globalvar.DIALOG_COLOR_SIZE)
  2694. vColor.SetName('GetColour')
  2695. self.winId['modeler:data:color:vector'] = vColor.GetId()
  2696. gridSizer.Add(item = vColor,
  2697. flag = wx.ALIGN_RIGHT |
  2698. wx.ALIGN_CENTER_VERTICAL,
  2699. pos = (row, 1))
  2700. sizer.Add(item = gridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
  2701. border.Add(item = sizer, proportion = 0, flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  2702. # size
  2703. box = wx.StaticBox (parent = panel, id = wx.ID_ANY,
  2704. label = " %s " % _("Shape size"))
  2705. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2706. gridSizer = wx.GridBagSizer (hgap=3, vgap=3)
  2707. gridSizer.AddGrowableCol(0)
  2708. row = 0
  2709. gridSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  2710. label = _("Width:")),
  2711. flag = wx.ALIGN_LEFT |
  2712. wx.ALIGN_CENTER_VERTICAL,
  2713. pos = (row, 0))
  2714. width = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  2715. min = 0, max = 500,
  2716. initial = self.settings.Get(group='modeler', key='data', subkey=('size', 'width')))
  2717. width.SetName('GetValue')
  2718. self.winId['modeler:data:size:width'] = width.GetId()
  2719. gridSizer.Add(item = width,
  2720. flag = wx.ALIGN_RIGHT |
  2721. wx.ALIGN_CENTER_VERTICAL,
  2722. pos = (row, 1))
  2723. row += 1
  2724. gridSizer.Add(item = wx.StaticText(parent=panel, id=wx.ID_ANY,
  2725. label=_("Height:")),
  2726. flag = wx.ALIGN_LEFT |
  2727. wx.ALIGN_CENTER_VERTICAL,
  2728. pos=(row, 0))
  2729. height = wx.SpinCtrl(parent = panel, id = wx.ID_ANY,
  2730. min = 0, max = 500,
  2731. initial = self.settings.Get(group='modeler', key='data', subkey=('size', 'height')))
  2732. height.SetName('GetValue')
  2733. self.winId['modeler:data:size:height'] = height.GetId()
  2734. gridSizer.Add(item = height,
  2735. flag = wx.ALIGN_RIGHT |
  2736. wx.ALIGN_CENTER_VERTICAL,
  2737. pos = (row, 1))
  2738. sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
  2739. border.Add(item=sizer, proportion=0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
  2740. panel.SetSizer(border)
  2741. return panel
  2742. def OnApply(self, event):
  2743. """!Button 'Apply' pressed"""
  2744. PreferencesBaseDialog.OnApply(self, event)
  2745. self.parent.GetModel().Update()
  2746. self.parent.GetCanvas().Refresh()
  2747. def OnSave(self, event):
  2748. """!Button 'Save' pressed"""
  2749. PreferencesBaseDialog.OnSave(self, event)
  2750. self.parent.GetModel().Update()
  2751. self.parent.GetCanvas().Refresh()
  2752. class PropertiesDialog(wx.Dialog):
  2753. """!Model properties dialog
  2754. """
  2755. def __init__(self, parent, id = wx.ID_ANY,
  2756. title = _('Model properties'),
  2757. size = (350, 400),
  2758. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  2759. wx.Dialog.__init__(self, parent, id, title, size = size,
  2760. style = style)
  2761. self.metaBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  2762. label=" %s " % _("Metadata"))
  2763. self.cmdBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  2764. label=" %s " % _("Commands"))
  2765. self.name = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  2766. size = (300, 25))
  2767. self.desc = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  2768. style = wx.TE_MULTILINE,
  2769. size = (300, 50))
  2770. self.author = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  2771. size = (300, 25))
  2772. # commands
  2773. self.overwrite = wx.CheckBox(parent = self, id=wx.ID_ANY,
  2774. label=_("Allow output files to overwrite existing files"))
  2775. self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  2776. # buttons
  2777. self.btnOk = wx.Button(self, wx.ID_OK)
  2778. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  2779. self.btnOk.SetDefault()
  2780. self.btnOk.SetToolTipString(_("Apply properties"))
  2781. self.btnOk.SetDefault()
  2782. self.btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  2783. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  2784. self._layout()
  2785. def _layout(self):
  2786. metaSizer = wx.StaticBoxSizer(self.metaBox, wx.VERTICAL)
  2787. gridSizer = wx.GridBagSizer(hgap = 3, vgap = 3)
  2788. gridSizer.AddGrowableCol(0)
  2789. gridSizer.AddGrowableRow(1)
  2790. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  2791. label = _("Name:")),
  2792. flag = wx.ALIGN_LEFT |
  2793. wx.ALIGN_CENTER_VERTICAL,
  2794. pos = (0, 0))
  2795. gridSizer.Add(item = self.name,
  2796. flag = wx.ALIGN_LEFT |
  2797. wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  2798. pos = (0, 1))
  2799. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  2800. label = _("Description:")),
  2801. flag = wx.ALIGN_LEFT |
  2802. wx.ALIGN_CENTER_VERTICAL,
  2803. pos = (1, 0))
  2804. gridSizer.Add(item = self.desc,
  2805. flag = wx.ALIGN_LEFT |
  2806. wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  2807. pos = (1, 1))
  2808. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  2809. label = _("Author(s):")),
  2810. flag = wx.ALIGN_LEFT |
  2811. wx.ALIGN_CENTER_VERTICAL,
  2812. pos = (2, 0))
  2813. gridSizer.Add(item = self.author,
  2814. flag = wx.ALIGN_LEFT |
  2815. wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  2816. pos = (2, 1))
  2817. metaSizer.Add(item = gridSizer)
  2818. cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
  2819. cmdSizer.Add(item = self.overwrite,
  2820. flag = wx.EXPAND | wx.ALL, border = 3)
  2821. btnStdSizer = wx.StdDialogButtonSizer()
  2822. btnStdSizer.AddButton(self.btnCancel)
  2823. btnStdSizer.AddButton(self.btnOk)
  2824. btnStdSizer.Realize()
  2825. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2826. mainSizer.Add(item=metaSizer, proportion=1,
  2827. flag=wx.EXPAND | wx.ALL, border=5)
  2828. mainSizer.Add(item=cmdSizer, proportion=0,
  2829. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  2830. mainSizer.Add(item=btnStdSizer, proportion=0,
  2831. flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
  2832. self.SetSizer(mainSizer)
  2833. mainSizer.Fit(self)
  2834. def OnCloseWindow(self, event):
  2835. self.Hide()
  2836. def GetValues(self):
  2837. """!Get values"""
  2838. return { 'name' : self.name.GetValue(),
  2839. 'description' : self.desc.GetValue(),
  2840. 'author' : self.author.GetValue(),
  2841. 'overwrite' : self.overwrite.IsChecked() }
  2842. def Init(self, prop):
  2843. """!Initialize dialog"""
  2844. self.name.SetValue(prop['name'])
  2845. self.desc.SetValue(prop['description'])
  2846. self.author.SetValue(prop['author'])
  2847. if 'overwrite' in prop:
  2848. self.overwrite.SetValue(prop['overwrite'])
  2849. class ModelParamDialog(wx.Dialog):
  2850. def __init__(self, parent, params, id = wx.ID_ANY, title = _("Model parameters"),
  2851. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  2852. """!Model parameters dialog
  2853. """
  2854. self.parent = parent
  2855. self.params = params
  2856. self.tasks = list() # list of tasks/pages
  2857. wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
  2858. if globalvar.hasAgw:
  2859. self.notebook = FN.FlatNotebook(self, id = wx.ID_ANY,
  2860. agwStyle = FN.FNB_FANCY_TABS |
  2861. FN.FNB_BOTTOM |
  2862. FN.FNB_NO_NAV_BUTTONS |
  2863. FN.FNB_NO_X_BUTTON)
  2864. else:
  2865. self.notebook = FN.FlatNotebook(self, id = wx.ID_ANY,
  2866. style = FN.FNB_FANCY_TABS |
  2867. FN.FNB_BOTTOM |
  2868. FN.FNB_NO_NAV_BUTTONS |
  2869. FN.FNB_NO_X_BUTTON)
  2870. panel = self._createPages()
  2871. wx.CallAfter(self.notebook.SetSelection, 0)
  2872. self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  2873. self.btnRun = wx.Button(parent = self, id = wx.ID_OK,
  2874. label = _("&Run"))
  2875. self.btnRun.SetDefault()
  2876. self._layout()
  2877. size = self.GetBestSize()
  2878. self.SetMinSize(size)
  2879. self.SetSize((size.width, size.height +
  2880. panel.constrained_size[1] -
  2881. panel.panelMinHeight))
  2882. def _layout(self):
  2883. btnSizer = wx.StdDialogButtonSizer()
  2884. btnSizer.AddButton(self.btnCancel)
  2885. btnSizer.AddButton(self.btnRun)
  2886. btnSizer.Realize()
  2887. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2888. mainSizer.Add(item = self.notebook, proportion = 1,
  2889. flag = wx.EXPAND)
  2890. mainSizer.Add(item=btnSizer, proportion=0,
  2891. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  2892. self.SetSizer(mainSizer)
  2893. mainSizer.Fit(self)
  2894. def _createPages(self):
  2895. """!Create for each parameterized module its own page"""
  2896. nameOrdered = [''] * len(self.params.keys())
  2897. for name, params in self.params.iteritems():
  2898. nameOrdered[params['idx']] = name
  2899. for name in nameOrdered:
  2900. params = self.params[name]
  2901. panel = self._createPage(name, params)
  2902. self.notebook.AddPage(panel, text = name)
  2903. return panel
  2904. def _createPage(self, name, params):
  2905. """!Define notebook page"""
  2906. if name in globalvar.grassCmd['all']:
  2907. task = gtask.grassTask(name)
  2908. else:
  2909. task = gtask.grassTask()
  2910. task.flags = params['flags']
  2911. task.params = params['params']
  2912. panel = menuform.cmdPanel(parent = self, id = wx.ID_ANY, task = task)
  2913. self.tasks.append(task)
  2914. return panel
  2915. def GetErrors(self):
  2916. """!Check for errors, get list of messages"""
  2917. errList = list()
  2918. for task in self.tasks:
  2919. errList += task.getCmdError()
  2920. return errList
  2921. class ModelListCtrl(wx.ListCtrl,
  2922. listmix.ListCtrlAutoWidthMixin,
  2923. listmix.TextEditMixin,
  2924. listmix.ColumnSorterMixin):
  2925. def __init__(self, parent, columns, id = wx.ID_ANY,
  2926. style = wx.LC_REPORT | wx.BORDER_NONE |
  2927. wx.LC_SORT_ASCENDING |wx.LC_HRULES |
  2928. wx.LC_VRULES, **kwargs):
  2929. """!List of model variables"""
  2930. self.parent = parent
  2931. self.columns = columns
  2932. self.shape = None
  2933. try:
  2934. self.frame = parent.parent
  2935. except AttributeError:
  2936. self.frame = None
  2937. wx.ListCtrl.__init__(self, parent, id = id, style = style, **kwargs)
  2938. listmix.ListCtrlAutoWidthMixin.__init__(self)
  2939. listmix.TextEditMixin.__init__(self)
  2940. listmix.ColumnSorterMixin.__init__(self, 4)
  2941. i = 0
  2942. for col in columns:
  2943. self.InsertColumn(i, col)
  2944. self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER)
  2945. i += 1
  2946. self.itemDataMap = {} # requested by sorter
  2947. self.itemCount = 0
  2948. self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit)
  2949. self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit)
  2950. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
  2951. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp) #wxMSW
  2952. self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) #wxGTK
  2953. def OnBeginEdit(self, event):
  2954. """!Editing of item started"""
  2955. event.Allow()
  2956. def OnEndEdit(self, event):
  2957. """!Finish editing of item"""
  2958. pass
  2959. def OnColClick(self, event):
  2960. """!Click on column header (order by)"""
  2961. event.Skip()
  2962. class VariablePanel(wx.Panel):
  2963. def __init__(self, parent, id = wx.ID_ANY,
  2964. **kwargs):
  2965. """!Manage model variables panel
  2966. """
  2967. self.parent = parent
  2968. wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
  2969. self.listBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  2970. label=" %s " % _("List of variables - right-click to delete"))
  2971. self.list = VariableListCtrl(parent = self,
  2972. columns = [_("Name"), _("Data type"),
  2973. _("Default value"), _("Description")])
  2974. # add new category
  2975. self.addBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  2976. label = " %s " % _("Add new variable"))
  2977. self.name = wx.TextCtrl(parent = self, id = wx.ID_ANY)
  2978. wx.CallAfter(self.name.SetFocus)
  2979. self.type = wx.Choice(parent = self, id = wx.ID_ANY,
  2980. choices = [_("integer"),
  2981. _("float"),
  2982. _("string"),
  2983. _("raster"),
  2984. _("vector")])
  2985. self.value = wx.TextCtrl(parent = self, id = wx.ID_ANY)
  2986. self.desc = wx.TextCtrl(parent = self, id = wx.ID_ANY)
  2987. # buttons
  2988. self.btnAdd = wx.Button(parent = self, id = wx.ID_ADD)
  2989. self.btnAdd.SetToolTipString(_("Add new variable to the model"))
  2990. self.btnAdd.Enable(False)
  2991. # bindings
  2992. self.name.Bind(wx.EVT_TEXT, self.OnText)
  2993. self.value.Bind(wx.EVT_TEXT, self.OnText)
  2994. self.desc.Bind(wx.EVT_TEXT, self.OnText)
  2995. self.btnAdd.Bind(wx.EVT_BUTTON, self.OnAdd)
  2996. self._layout()
  2997. def _layout(self):
  2998. """!Layout dialog"""
  2999. listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
  3000. listSizer.Add(item = self.list, proportion = 1,
  3001. flag = wx.EXPAND)
  3002. addSizer = wx.StaticBoxSizer(self.addBox, wx.VERTICAL)
  3003. gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  3004. gridSizer.AddGrowableCol(1)
  3005. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  3006. label = "%s:" % _("Name")),
  3007. flag = wx.ALIGN_CENTER_VERTICAL,
  3008. pos = (0, 0))
  3009. gridSizer.Add(item = self.name,
  3010. pos = (0, 1),
  3011. flag = wx.EXPAND)
  3012. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  3013. label = "%s:" % _("Data type")),
  3014. flag = wx.ALIGN_CENTER_VERTICAL,
  3015. pos = (0, 2))
  3016. gridSizer.Add(item = self.type,
  3017. pos = (0, 3))
  3018. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  3019. label = "%s:" % _("Default value")),
  3020. flag = wx.ALIGN_CENTER_VERTICAL,
  3021. pos = (1, 0))
  3022. gridSizer.Add(item = self.value,
  3023. pos = (1, 1), span = (1, 3),
  3024. flag = wx.EXPAND)
  3025. gridSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  3026. label = "%s:" % _("Description")),
  3027. flag = wx.ALIGN_CENTER_VERTICAL,
  3028. pos = (2, 0))
  3029. gridSizer.Add(item = self.desc,
  3030. pos = (2, 1), span = (1, 3),
  3031. flag = wx.EXPAND)
  3032. addSizer.Add(item = gridSizer,
  3033. flag = wx.EXPAND)
  3034. addSizer.Add(item = self.btnAdd, proportion = 0,
  3035. flag = wx.TOP | wx.ALIGN_RIGHT, border = 5)
  3036. mainSizer = wx.BoxSizer(wx.VERTICAL)
  3037. mainSizer.Add(item = listSizer, proportion = 1,
  3038. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  3039. mainSizer.Add(item = addSizer, proportion = 0,
  3040. flag = wx.EXPAND | wx.ALIGN_CENTER |
  3041. wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  3042. self.SetSizer(mainSizer)
  3043. mainSizer.Fit(self)
  3044. def OnText(self, event):
  3045. """!Text entered"""
  3046. if self.name.GetValue():
  3047. self.btnAdd.Enable()
  3048. else:
  3049. self.btnAdd.Enable(False)
  3050. def OnAdd(self, event):
  3051. """!Add new variable to the list"""
  3052. msg = self.list.Append(self.name.GetValue(),
  3053. self.type.GetStringSelection(),
  3054. self.value.GetValue(),
  3055. self.desc.GetValue())
  3056. self.name.SetValue('')
  3057. self.name.SetFocus()
  3058. if msg:
  3059. GError(parent = self,
  3060. message = msg)
  3061. else:
  3062. self.type.SetSelection(0)
  3063. self.value.SetValue('')
  3064. self.desc.SetValue('')
  3065. self.UpdateModelVariables()
  3066. def UpdateModelVariables(self):
  3067. """!Update model variables"""
  3068. variables = dict()
  3069. for values in self.list.GetData().itervalues():
  3070. name = values[0]
  3071. variables[name] = { 'type' : str(values[1]) }
  3072. if values[2]:
  3073. variables[name]['value'] = values[2]
  3074. if values[3]:
  3075. variables[name]['description'] = values[3]
  3076. self.parent.GetModel().SetVariables(variables)
  3077. self.parent.ModelChanged()
  3078. def Update(self):
  3079. """!Reload list of variables"""
  3080. self.list.OnReload(None)
  3081. class VariableListCtrl(ModelListCtrl):
  3082. def __init__(self, parent, columns, **kwargs):
  3083. """!List of model variables"""
  3084. ModelListCtrl.__init__(self, parent, columns, **kwargs)
  3085. def GetListCtrl(self):
  3086. """!Used by ColumnSorterMixin"""
  3087. return self
  3088. def GetData(self):
  3089. """!Get list data"""
  3090. return self.itemDataMap
  3091. def Populate(self, data):
  3092. """!Populate the list"""
  3093. self.itemDataMap = dict()
  3094. i = 0
  3095. for name, values in data.iteritems():
  3096. self.itemDataMap[i] = [name, values['type'],
  3097. values.get('value', ''),
  3098. values.get('description', '')]
  3099. i += 1
  3100. self.itemCount = len(self.itemDataMap.keys())
  3101. self.DeleteAllItems()
  3102. i = 0
  3103. for name, vtype, value, desc in self.itemDataMap.itervalues():
  3104. index = self.InsertStringItem(sys.maxint, name)
  3105. self.SetStringItem(index, 0, name)
  3106. self.SetStringItem(index, 1, vtype)
  3107. self.SetStringItem(index, 2, value)
  3108. self.SetStringItem(index, 3, desc)
  3109. self.SetItemData(index, i)
  3110. i += 1
  3111. def Append(self, name, vtype, value, desc):
  3112. """!Append new item to the list
  3113. @return None on success
  3114. @return error string
  3115. """
  3116. for iname, ivtype, ivalue, idesc in self.itemDataMap.itervalues():
  3117. if iname == name:
  3118. return _("Variable <%s> already exists in the model. "
  3119. "Adding variable failed.") % name
  3120. index = self.InsertStringItem(sys.maxint, name)
  3121. self.SetStringItem(index, 0, name)
  3122. self.SetStringItem(index, 1, vtype)
  3123. self.SetStringItem(index, 2, value)
  3124. self.SetStringItem(index, 3, desc)
  3125. self.SetItemData(index, self.itemCount)
  3126. self.itemDataMap[self.itemCount] = [name, vtype, value, desc]
  3127. self.itemCount += 1
  3128. return None
  3129. def OnRemove(self, event):
  3130. """!Remove selected variable(s) from the model"""
  3131. item = self.GetFirstSelected()
  3132. while item != -1:
  3133. self.DeleteItem(item)
  3134. del self.itemDataMap[item]
  3135. item = self.GetFirstSelected()
  3136. self.parent.UpdateModelVariables()
  3137. event.Skip()
  3138. def OnRemoveAll(self, event):
  3139. """!Remove all variable(s) from the model"""
  3140. dlg = wx.MessageBox(parent=self,
  3141. message=_("Do you want to delete all variables from "
  3142. "the model?"),
  3143. caption=_("Delete variables"),
  3144. style=wx.YES_NO | wx.CENTRE)
  3145. if dlg != wx.YES:
  3146. return
  3147. self.DeleteAllItems()
  3148. self.itemDataMap = dict()
  3149. self.parent.UpdateModelVariables()
  3150. def OnEndEdit(self, event):
  3151. """!Finish editing of item"""
  3152. itemIndex = event.GetIndex()
  3153. columnIndex = event.GetColumn()
  3154. nameOld = self.GetItem(itemIndex, 0).GetText()
  3155. if columnIndex == 0: # TODO
  3156. event.Veto()
  3157. self.itemDataMap[itemIndex][columnIndex] = event.GetText()
  3158. self.parent.UpdateModelVariables()
  3159. def OnReload(self, event):
  3160. """!Reload list of variables"""
  3161. self.Populate(self.parent.parent.GetModel().GetVariables())
  3162. def OnRightUp(self, event):
  3163. """!Mouse right button up"""
  3164. if not hasattr(self, "popupID1"):
  3165. self.popupID1 = wx.NewId()
  3166. self.popupID2 = wx.NewId()
  3167. self.popupID3 = wx.NewId()
  3168. self.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  3169. self.Bind(wx.EVT_MENU, self.OnRemoveAll, id = self.popupID2)
  3170. self.Bind(wx.EVT_MENU, self.OnReload, id = self.popupID3)
  3171. # generate popup-menu
  3172. menu = wx.Menu()
  3173. menu.Append(self.popupID1, _("Delete selected"))
  3174. menu.Append(self.popupID2, _("Delete all"))
  3175. if self.GetFirstSelected() == -1:
  3176. menu.Enable(self.popupID1, False)
  3177. menu.Enable(self.popupID2, False)
  3178. menu.AppendSeparator()
  3179. menu.Append(self.popupID3, _("Reload"))
  3180. self.PopupMenu(menu)
  3181. menu.Destroy()
  3182. class ModelItem(ModelObject):
  3183. def __init__(self, parent, x, y, id = -1, width = None, height = None, text = '', items = []):
  3184. """!Abstract class for loops and conditions"""
  3185. ModelObject.__init__(self, id)
  3186. self.parent = parent
  3187. self.text = text
  3188. self.items = items # list of items in the loop
  3189. def GetText(self):
  3190. """!Get loop text"""
  3191. return self.text
  3192. def GetItems(self):
  3193. """!Get items (id)"""
  3194. return self.items
  3195. def SetId(self, id):
  3196. """!Set loop id"""
  3197. self.id = id
  3198. def SetText(self, cond):
  3199. """!Set loop text (condition)"""
  3200. self.text = cond
  3201. self.ClearText()
  3202. self.AddText('(' + str(self.id) + ') ' + self.text)
  3203. def GetLog(self):
  3204. """!Get log info"""
  3205. if self.text:
  3206. return _("Condition: ") + self.text
  3207. else:
  3208. return _("Condition: not defined")
  3209. def AddRelation(self, rel):
  3210. """!Record relation"""
  3211. self.rels.append(rel)
  3212. def Clear(self):
  3213. """!Clear object, remove rels"""
  3214. self.rels = list()
  3215. class ModelItemDialog(wx.Dialog):
  3216. """!Abstract item properties dialog"""
  3217. def __init__(self, parent, shape, title, id = wx.ID_ANY,
  3218. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  3219. self.parent = parent
  3220. self.shape = shape
  3221. wx.Dialog.__init__(self, parent, id, title = title, style = style, **kwargs)
  3222. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  3223. self.condBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  3224. label=" %s " % _("Condition"))
  3225. self.condText = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  3226. value = shape.GetText())
  3227. self.itemList = ItemCheckListCtrl(parent = self.panel,
  3228. window = self,
  3229. columns = [_("ID"), _("Name"),
  3230. _("Command")],
  3231. shape = shape)
  3232. self.itemList.Populate(self.parent.GetModel().GetItems())
  3233. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  3234. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  3235. self.btnOk.SetDefault()
  3236. def _layout(self):
  3237. """!Do layout (virtual method)"""
  3238. pass
  3239. def GetCondition(self):
  3240. """!Get loop condition"""
  3241. return self.condText.GetValue()
  3242. class ModelLoop(ModelItem, ogl.RectangleShape):
  3243. def __init__(self, parent, x, y, id = -1, width = None, height = None, text = '', items = []):
  3244. """!Defines a loop"""
  3245. ModelItem.__init__(self, parent, x, y, id, width, height, text, items)
  3246. if not width:
  3247. width = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'width'))
  3248. if not height:
  3249. height = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'height'))
  3250. if self.parent.GetCanvas():
  3251. ogl.RectangleShape.__init__(self, width, height)
  3252. self.SetCanvas(self.parent)
  3253. self.SetX(x)
  3254. self.SetY(y)
  3255. self.SetPen(wx.BLACK_PEN)
  3256. self.SetCornerRadius(100)
  3257. if text:
  3258. self.AddText('(' + str(self.id) + ') ' + text)
  3259. else:
  3260. self.AddText('(' + str(self.id) + ')')
  3261. def GetName(self):
  3262. """!Get name"""
  3263. return _("loop")
  3264. def SetItems(self, items):
  3265. """!Set items (id)"""
  3266. self.items = items
  3267. class ModelLoopDialog(ModelItemDialog):
  3268. """!Loop properties dialog"""
  3269. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("Loop properties"),
  3270. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  3271. ModelItemDialog.__init__(self, parent, shape, title,
  3272. style = style, **kwargs)
  3273. self.listBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  3274. label=" %s " % _("List of items in loop"))
  3275. self._layout()
  3276. self.SetMinSize(self.GetSize())
  3277. self.SetSize((500, 400))
  3278. def _layout(self):
  3279. """!Do layout"""
  3280. sizer = wx.BoxSizer(wx.VERTICAL)
  3281. condSizer = wx.StaticBoxSizer(self.condBox, wx.VERTICAL)
  3282. condSizer.Add(item = self.condText, proportion = 1,
  3283. flag = wx.EXPAND)
  3284. listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
  3285. listSizer.Add(item = self.itemList, proportion = 1,
  3286. flag = wx.EXPAND)
  3287. btnSizer = wx.StdDialogButtonSizer()
  3288. btnSizer.AddButton(self.btnCancel)
  3289. btnSizer.AddButton(self.btnOk)
  3290. btnSizer.Realize()
  3291. sizer.Add(item = condSizer, proportion = 0,
  3292. flag = wx.EXPAND | wx.ALL, border = 3)
  3293. sizer.Add(item = listSizer, proportion = 1,
  3294. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  3295. sizer.Add(item = btnSizer, proportion=0,
  3296. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  3297. self.panel.SetSizer(sizer)
  3298. sizer.Fit(self.panel)
  3299. self.Layout()
  3300. def GetItems(self):
  3301. """!Get list of selected actions"""
  3302. return self.itemList.GetItems()
  3303. class ItemPanel(wx.Panel):
  3304. def __init__(self, parent, id = wx.ID_ANY,
  3305. **kwargs):
  3306. """!Manage model items
  3307. """
  3308. self.parent = parent
  3309. wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
  3310. self.listBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  3311. label=" %s " % _("List of items - right-click to delete"))
  3312. self.list = ItemListCtrl(parent = self,
  3313. columns = [_("ID"), _("Name"), _("In block"),
  3314. _("Command / Condition")])
  3315. self._layout()
  3316. def _layout(self):
  3317. """!Layout dialog"""
  3318. listSizer = wx.StaticBoxSizer(self.listBox, wx.VERTICAL)
  3319. listSizer.Add(item = self.list, proportion = 1,
  3320. flag = wx.EXPAND)
  3321. mainSizer = wx.BoxSizer(wx.VERTICAL)
  3322. mainSizer.Add(item = listSizer, proportion = 1,
  3323. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  3324. self.SetSizer(mainSizer)
  3325. mainSizer.Fit(self)
  3326. def Update(self):
  3327. """!Reload list of variables"""
  3328. self.list.OnReload(None)
  3329. class ItemListCtrl(ModelListCtrl):
  3330. def __init__(self, parent, columns, disablePopup = False, **kwargs):
  3331. """!List of model actions"""
  3332. self.disablePopup = disablePopup
  3333. ModelListCtrl.__init__(self, parent, columns, **kwargs)
  3334. self.SetColumnWidth(1, 100)
  3335. self.SetColumnWidth(2, 65)
  3336. def GetListCtrl(self):
  3337. """!Used by ColumnSorterMixin"""
  3338. return self
  3339. def GetData(self):
  3340. """!Get list data"""
  3341. return self.itemDataMap
  3342. def Populate(self, data):
  3343. """!Populate the list"""
  3344. self.itemDataMap = dict()
  3345. if self.shape:
  3346. if isinstance(self.shape, ModelCondition):
  3347. if self.GetName() == 'ElseBlockList':
  3348. shapeItems = map(lambda x: x.GetId(), self.shape.GetItems()['else'])
  3349. else:
  3350. shapeItems = map(lambda x: x.GetId(), self.shape.GetItems()['if'])
  3351. else:
  3352. shapeItems = map(lambda x: x.GetId(), self.shape.GetItems())
  3353. else:
  3354. shapeItems = list()
  3355. i = 0
  3356. if len(self.columns) == 3: # ItemCheckList
  3357. checked = list()
  3358. for action in data:
  3359. if isinstance(action, ModelData):
  3360. continue
  3361. if len(self.columns) == 3:
  3362. self.itemDataMap[i] = [str(action.GetId()),
  3363. action.GetName(),
  3364. action.GetLog()]
  3365. aId = action.GetBlockId()
  3366. if action.GetId() in shapeItems:
  3367. checked.append(aId)
  3368. else:
  3369. checked.append(None)
  3370. else:
  3371. bId = action.GetBlockId()
  3372. if not bId:
  3373. bId = ''
  3374. self.itemDataMap[i] = [str(action.GetId()),
  3375. action.GetName(),
  3376. ','.join(map(str, bId)),
  3377. action.GetLog()]
  3378. i += 1
  3379. self.itemCount = len(self.itemDataMap.keys())
  3380. self.DeleteAllItems()
  3381. i = 0
  3382. if len(self.columns) == 3:
  3383. for aid, name, desc in self.itemDataMap.itervalues():
  3384. index = self.InsertStringItem(sys.maxint, aid)
  3385. self.SetStringItem(index, 0, aid)
  3386. self.SetStringItem(index, 1, name)
  3387. self.SetStringItem(index, 2, desc)
  3388. self.SetItemData(index, i)
  3389. if checked[i]:
  3390. self.CheckItem(index, True)
  3391. i += 1
  3392. else:
  3393. for aid, name, inloop, desc in self.itemDataMap.itervalues():
  3394. index = self.InsertStringItem(sys.maxint, aid)
  3395. self.SetStringItem(index, 0, aid)
  3396. self.SetStringItem(index, 1, name)
  3397. self.SetStringItem(index, 2, inloop)
  3398. self.SetStringItem(index, 3, desc)
  3399. self.SetItemData(index, i)
  3400. i += 1
  3401. def OnRemove(self, event):
  3402. """!Remove selected action(s) from the model"""
  3403. model = self.frame.GetModel()
  3404. canvas = self.frame.GetCanvas()
  3405. item = self.GetFirstSelected()
  3406. while item != -1:
  3407. self.DeleteItem(item)
  3408. del self.itemDataMap[item]
  3409. aId = self.GetItem(item, 0).GetText()
  3410. action = model.GetItem(int(aId))
  3411. if not action:
  3412. item = self.GetFirstSelected()
  3413. continue
  3414. model.RemoveItem(action)
  3415. canvas.GetDiagram().RemoveShape(action)
  3416. self.frame.ModelChanged()
  3417. item = self.GetFirstSelected()
  3418. canvas.Refresh()
  3419. event.Skip()
  3420. def OnRemoveAll(self, event):
  3421. """!Remove all variable(s) from the model"""
  3422. deleteDialog = wx.MessageBox(parent=self,
  3423. message=_("Selected data records (%d) will permanently deleted "
  3424. "from table. Do you want to delete them?") % \
  3425. (len(self.listOfSQLStatements)),
  3426. caption=_("Delete records"),
  3427. style=wx.YES_NO | wx.CENTRE)
  3428. if deleteDialog != wx.YES:
  3429. return False
  3430. self.DeleteAllItems()
  3431. self.itemDataMap = dict()
  3432. self.parent.UpdateModelVariables()
  3433. def OnEndEdit(self, event):
  3434. """!Finish editing of item"""
  3435. itemIndex = event.GetIndex()
  3436. columnIndex = event.GetColumn()
  3437. self.itemDataMap[itemIndex][columnIndex] = event.GetText()
  3438. aId = int(self.GetItem(itemIndex, 0).GetText())
  3439. action = self.frame.GetModel().GetItem(aId)
  3440. if not action:
  3441. event.Veto()
  3442. if columnIndex == 0:
  3443. action.SetId(int(event.GetText()))
  3444. self.frame.ModelChanged()
  3445. def OnReload(self, event = None):
  3446. """!Reload list of actions"""
  3447. self.Populate(self.frame.GetModel().GetItems())
  3448. def OnRightUp(self, event):
  3449. """!Mouse right button up"""
  3450. if self.disablePopup:
  3451. return
  3452. if not hasattr(self, "popupID1"):
  3453. self.popupID1 = wx.NewId()
  3454. self.popupID2 = wx.NewId()
  3455. self.popupID3 = wx.NewId()
  3456. self.popupID4 = wx.NewId()
  3457. self.Bind(wx.EVT_MENU, self.OnRemove, id = self.popupID1)
  3458. self.Bind(wx.EVT_MENU, self.OnRemoveAll, id = self.popupID2)
  3459. self.Bind(wx.EVT_MENU, self.OnReload, id = self.popupID3)
  3460. self.Bind(wx.EVT_MENU, self.OnNormalize, id = self.popupID4)
  3461. # generate popup-menu
  3462. menu = wx.Menu()
  3463. menu.Append(self.popupID1, _("Delete selected"))
  3464. menu.Append(self.popupID2, _("Delete all"))
  3465. if self.GetFirstSelected() == -1:
  3466. menu.Enable(self.popupID1, False)
  3467. menu.Enable(self.popupID2, False)
  3468. menu.AppendSeparator()
  3469. menu.Append(self.popupID4, _("Normalize"))
  3470. menu.Append(self.popupID3, _("Reload"))
  3471. self.PopupMenu(menu)
  3472. menu.Destroy()
  3473. def OnNormalize(self, event):
  3474. """!Update id of actions"""
  3475. model = self.frame.GetModel()
  3476. aId = 1
  3477. for item in model.GetItems():
  3478. item.SetId(aId)
  3479. aId += 1
  3480. self.OnReload(None)
  3481. self.frame.GetCanvas().Refresh()
  3482. self.frame.ModelChanged()
  3483. class ItemCheckListCtrl(ItemListCtrl, listmix.CheckListCtrlMixin):
  3484. def __init__(self, parent, shape, columns, window = None, **kwargs):
  3485. self.parent = parent
  3486. self.window = window
  3487. ItemListCtrl.__init__(self, parent, columns, disablePopup = True, **kwargs)
  3488. listmix.CheckListCtrlMixin.__init__(self)
  3489. self.SetColumnWidth(0, 50)
  3490. self.shape = shape
  3491. def OnBeginEdit(self, event):
  3492. """!Disable editing"""
  3493. event.Veto()
  3494. def OnCheckItem(self, index, flag):
  3495. """!Item checked/unchecked"""
  3496. name = self.GetName()
  3497. if name == 'IfBlockList' and self.window:
  3498. self.window.OnCheckItemIf(index, flag)
  3499. elif name == 'ElseBlockList' and self.window:
  3500. self.window.OnCheckItemElse(index, flag)
  3501. def GetItems(self):
  3502. """!Get list of selected actions"""
  3503. ids = { 'checked' : list(),
  3504. 'unchecked' : list() }
  3505. for i in range(self.GetItemCount()):
  3506. iId = int(self.GetItem(i, 0).GetText())
  3507. if self.IsChecked(i):
  3508. ids['checked'].append(iId)
  3509. else:
  3510. ids['unchecked'].append(iId)
  3511. return ids
  3512. def CheckItemById(self, aId, flag):
  3513. """!Check/uncheck given item by id"""
  3514. for i in range(self.GetItemCount()):
  3515. iId = int(self.GetItem(i, 0).GetText())
  3516. if iId == aId:
  3517. self.CheckItem(i, flag)
  3518. break
  3519. class ModelCondition(ModelItem, ogl.PolygonShape):
  3520. def __init__(self, parent, x, y, id = -1, width = None, height = None, text = '',
  3521. items = { 'if' : [], 'else' : [] }):
  3522. """!Defines a if-else condition"""
  3523. ModelItem.__init__(self, parent, x, y, id, width, height, text, items)
  3524. if not width:
  3525. self.width = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'width'))
  3526. else:
  3527. self.width = width
  3528. if not height:
  3529. self.height = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'height'))
  3530. else:
  3531. self.height = height
  3532. if self.parent.GetCanvas():
  3533. ogl.PolygonShape.__init__(self)
  3534. points = [(0, - self.height / 2),
  3535. (self.width / 2, 0),
  3536. (0, self.height / 2),
  3537. (- self.width / 2, 0)]
  3538. self.Create(points)
  3539. self.SetCanvas(self.parent)
  3540. self.SetX(x)
  3541. self.SetY(y)
  3542. self.SetPen(wx.BLACK_PEN)
  3543. if text:
  3544. self.AddText('(' + str(self.id) + ') ' + text)
  3545. else:
  3546. self.AddText('(' + str(self.id) + ')')
  3547. def GetName(self):
  3548. """!Get name"""
  3549. return _("if-else")
  3550. def GetWidth(self):
  3551. """!Get object width"""
  3552. return self.width
  3553. def GetHeight(self):
  3554. """!Get object height"""
  3555. return self.height
  3556. def SetItems(self, items, branch = 'if'):
  3557. """!Set items (id)
  3558. @param items list of items
  3559. @param branch 'if' / 'else'
  3560. """
  3561. if branch in ['if', 'else']:
  3562. self.items[branch] = items
  3563. class ModelConditionDialog(ModelItemDialog):
  3564. """!Condition properties dialog"""
  3565. def __init__(self, parent, shape, id = wx.ID_ANY, title = _("If-else properties"),
  3566. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  3567. ModelItemDialog.__init__(self, parent, shape, title,
  3568. style = style, **kwargs)
  3569. self.listBoxIf = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  3570. label=" %s " % _("List of items in 'if' block"))
  3571. self.itemListIf = self.itemList
  3572. self.itemListIf.SetName('IfBlockList')
  3573. self.listBoxElse = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  3574. label=" %s " % _("List of items in 'else' block"))
  3575. self.itemListElse = ItemCheckListCtrl(parent = self.panel,
  3576. window = self,
  3577. columns = [_("ID"), _("Name"),
  3578. _("Command")],
  3579. shape = shape)
  3580. self.itemListElse.SetName('ElseBlockList')
  3581. self.itemListElse.Populate(self.parent.GetModel().GetItems())
  3582. self._layout()
  3583. self.SetMinSize(self.GetSize())
  3584. self.SetSize((500, 400))
  3585. def _layout(self):
  3586. """!Do layout"""
  3587. sizer = wx.BoxSizer(wx.VERTICAL)
  3588. condSizer = wx.StaticBoxSizer(self.condBox, wx.VERTICAL)
  3589. condSizer.Add(item = self.condText, proportion = 1,
  3590. flag = wx.EXPAND)
  3591. listIfSizer = wx.StaticBoxSizer(self.listBoxIf, wx.VERTICAL)
  3592. listIfSizer.Add(item = self.itemListIf, proportion = 1,
  3593. flag = wx.EXPAND)
  3594. listElseSizer = wx.StaticBoxSizer(self.listBoxElse, wx.VERTICAL)
  3595. listElseSizer.Add(item = self.itemListElse, proportion = 1,
  3596. flag = wx.EXPAND)
  3597. btnSizer = wx.StdDialogButtonSizer()
  3598. btnSizer.AddButton(self.btnCancel)
  3599. btnSizer.AddButton(self.btnOk)
  3600. btnSizer.Realize()
  3601. sizer.Add(item = condSizer, proportion = 0,
  3602. flag = wx.EXPAND | wx.ALL, border = 3)
  3603. sizer.Add(item = listIfSizer, proportion = 1,
  3604. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  3605. sizer.Add(item = listElseSizer, proportion = 1,
  3606. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  3607. sizer.Add(item = btnSizer, proportion=0,
  3608. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  3609. self.panel.SetSizer(sizer)
  3610. sizer.Fit(self.panel)
  3611. self.Layout()
  3612. def OnCheckItemIf(self, index, flag):
  3613. """!Item in if-block checked/unchecked"""
  3614. if flag is False:
  3615. return
  3616. aId = int(self.itemListIf.GetItem(index, 0).GetText())
  3617. if aId in self.itemListElse.GetItems()['checked']:
  3618. self.itemListElse.CheckItemById(aId, False)
  3619. def OnCheckItemElse(self, index, flag):
  3620. """!Item in else-block checked/unchecked"""
  3621. if flag is False:
  3622. return
  3623. aId = int(self.itemListElse.GetItem(index, 0).GetText())
  3624. if aId in self.itemListIf.GetItems()['checked']:
  3625. self.itemListIf.CheckItemById(aId, False)
  3626. def GetItems(self):
  3627. """!Get items"""
  3628. return { 'if' : self.itemListIf.GetItems(),
  3629. 'else' : self.itemListElse.GetItems() }
  3630. class WritePythonFile:
  3631. def __init__(self, fd, model):
  3632. """!Class for exporting model to Python script
  3633. @param fd file desciptor
  3634. """
  3635. self.fd = fd
  3636. self.model = model
  3637. self.indent = 4
  3638. self._writePython()
  3639. def _writePython(self):
  3640. """!Write model to file"""
  3641. properties = self.model.GetProperties()
  3642. self.fd.write(
  3643. r"""#!/usr/bin/env python
  3644. #
  3645. ############################################################################
  3646. #
  3647. # MODULE: %s
  3648. #
  3649. # AUTHOR(S): %s
  3650. #
  3651. # PURPOSE: %s
  3652. #
  3653. # DATE: %s
  3654. #
  3655. #############################################################################
  3656. """ % (properties['name'],
  3657. properties['author'],
  3658. properties['description'],
  3659. time.asctime()))
  3660. self.fd.write(
  3661. r"""
  3662. import sys
  3663. import os
  3664. import atexit
  3665. import grass.script as grass
  3666. """)
  3667. # cleanup()
  3668. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  3669. self.fd.write(
  3670. r"""
  3671. def cleanup():
  3672. """)
  3673. if rast:
  3674. self.fd.write(
  3675. r""" grass.run_command('g.remove',
  3676. rast=%s)
  3677. """ % ','.join(map(lambda x: "'" + x + "'", rast)))
  3678. if vect:
  3679. self.fd.write(
  3680. r""" grass.run_command('g.remove',
  3681. vect = %s)
  3682. """ % ','.join(map(lambda x: "'" + x + "'", vect)))
  3683. if rast3d:
  3684. self.fd.write(
  3685. r""" grass.run_command('g.remove',
  3686. rast3d = %s)
  3687. """ % ','.join(map(lambda x: "'" + x + "'", rast3d)))
  3688. if not rast and not vect and not rast3d:
  3689. self.fd.write(' pass\n')
  3690. self.fd.write("\ndef main():\n")
  3691. for item in self.model.GetItems():
  3692. self._writePythonItem(item)
  3693. self.fd.write("\n return 0\n")
  3694. self.fd.write(
  3695. r"""
  3696. if __name__ == "__main__":
  3697. options, flags = grass.parser()
  3698. atexit.register(cleanup)
  3699. sys.exit(main())
  3700. """)
  3701. def _writePythonItem(self, item, ignoreBlock = True):
  3702. """!Write model object to Python file"""
  3703. if isinstance(item, ModelAction):
  3704. if ignoreBlock and item.GetBlockId(): # ignore items in loops of conditions
  3705. return
  3706. self._writePythonAction(item)
  3707. elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition):
  3708. # substitute condition
  3709. variables = self.model.GetVariables()
  3710. cond = item.GetText()
  3711. for variable in variables:
  3712. pattern= re.compile('%' + variable)
  3713. if pattern.search(cond):
  3714. value = variables[variable].get('value', '')
  3715. if variables[variable].get('type', 'string') == 'string':
  3716. value = '"' + value + '"'
  3717. cond = pattern.sub(value, cond)
  3718. if isinstance(item, ModelLoop):
  3719. self.fd.write('%sfor %s:\n' % (' ' * self.indent, cond))
  3720. self.indent += 4
  3721. for action in item.GetItems():
  3722. self._writePythonItem(action, ignoreBlock = False)
  3723. self.indent -= 4
  3724. else: # ModelCondition
  3725. self.fd.write('%sif %s:\n' % (' ' * self.indent, cond))
  3726. self.indent += 4
  3727. condItems = item.GetItems()
  3728. for action in condItems['if']:
  3729. self._writePythonItem(action, ignoreBlock = False)
  3730. if condItems['else']:
  3731. self.indent -= 4
  3732. self.fd.write('%selse:\n' % (' ' * self.indent))
  3733. self.indent += 4
  3734. for action in condItems['else']:
  3735. self._writePythonItem(action, ignoreBlock = False)
  3736. self.indent += 4
  3737. def _writePythonAction(self, item):
  3738. """!Write model action to Python file"""
  3739. task = menuform.GUI(show = None).ParseCommand(cmd = item.GetLog(string = False))
  3740. opts = task.get_options()
  3741. flags = ''
  3742. params = list()
  3743. strcmd = "%sgrass.run_command(" % (' ' * self.indent)
  3744. cmdIndent = len(strcmd)
  3745. for f in opts['flags']:
  3746. if f.get('value', False) == True:
  3747. name = f.get('name', '')
  3748. if len(name) > 1:
  3749. params.append('%s = True' % name)
  3750. else:
  3751. flags += name
  3752. for p in opts['params']:
  3753. name = p.get('name', None)
  3754. value = p.get('value', None)
  3755. if name and value:
  3756. ptype = p.get('type', 'string')
  3757. if ptype == 'string':
  3758. params.append('%s = "%s"' % (name, value))
  3759. else:
  3760. params.append("%s = %s" % (name, value))
  3761. self.fd.write(strcmd + '"%s"' % task.get_name())
  3762. if flags:
  3763. self.fd.write(",\n%sflags = '%s'" % (' ' * cmdIndent, flags))
  3764. if len(params) > 0:
  3765. self.fd.write(",\n")
  3766. for opt in params[:-1]:
  3767. self.fd.write("%s%s,\n" % (' ' * cmdIndent, opt))
  3768. self.fd.write("%s%s)\n" % (' ' * cmdIndent, params[-1]))
  3769. else:
  3770. self.fd.write(")\n")
  3771. def main():
  3772. import gettext
  3773. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  3774. app = wx.PySimpleApp()
  3775. wx.InitAllImageHandlers()
  3776. frame = ModelFrame(parent = None)
  3777. if len(sys.argv) > 1:
  3778. frame.LoadModelFile(sys.argv[1])
  3779. frame.Show()
  3780. app.MainLoop()
  3781. if __name__ == "__main__":
  3782. main()