gmodeler.py 185 KB

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