gmodeler.py 171 KB

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