gmodeler.py 171 KB

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