gmodeler.py 180 KB

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