gmodeler.py 170 KB

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