gmodeler.py 173 KB

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