gmodeler.py 169 KB

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