gmodeler.py 163 KB

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