gmodeler.py 174 KB

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