gmodeler.py 163 KB

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