gmodeler.py 173 KB

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