gmodeler.py 184 KB

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