forms.py 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097
  1. """
  2. @package gui_core.forms
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - forms::UpdateThread
  7. - forms::UpdateQThread
  8. - forms::TaskFrame
  9. - forms::CmdPanel
  10. - forms::GUI
  11. - forms::GrassGUIApp
  12. This program is just a coarse approach to automatically build a GUI
  13. from a xml-based GRASS user interface description.
  14. You need to have Python 2.4, wxPython 2.8 and python-xml.
  15. The XML stream is read from executing the command given in the
  16. command line, thus you may call it for instance this way:
  17. python <this file.py> r.basins.fill
  18. Or you set an alias or wrap the call up in a nice shell script, GUI
  19. environment ... please contribute your idea.
  20. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  21. make it callable by gui. Method added to automatically re-run with
  22. pythonw on a Mac.
  23. .. todo::
  24. verify option value types
  25. Copyright(C) 2000-2015 by the GRASS Development Team
  26. This program is free software under the GPL(>=v2) Read the file
  27. COPYING coming with GRASS for details.
  28. @author Jan-Oliver Wagner <jan@intevation.de>
  29. @author Bernhard Reiter <bernhard@intevation.de>
  30. @author Michael Barton, Arizona State University
  31. @author Daniel Calvelo <dca.gis@gmail.com>
  32. @author Martin Landa <landa.martin@gmail.com>
  33. @author Luca Delucchi <lucadeluge@gmail.com>
  34. @author Stepan Turek <stepan.turek seznam.cz> (CoordinatesSelect)
  35. """
  36. import sys
  37. import string
  38. import textwrap
  39. import os
  40. import copy
  41. import locale
  42. import Queue
  43. import re
  44. import codecs
  45. from threading import Thread
  46. import wx
  47. try:
  48. import wx.lib.agw.flatnotebook as FN
  49. except ImportError:
  50. import wx.lib.flatnotebook as FN
  51. import wx.lib.colourselect as csel
  52. import wx.lib.filebrowsebutton as filebrowse
  53. from wx.lib.newevent import NewEvent
  54. try:
  55. import xml.etree.ElementTree as etree
  56. except ImportError:
  57. import elementtree.ElementTree as etree # Python <= 2.4
  58. # needed when started from command line and for testing
  59. if __name__ == '__main__':
  60. if os.getenv("GISBASE") is None:
  61. # intentionally not translatable
  62. sys.exit("Failed to start. GRASS GIS is not running"
  63. " or the installation is broken.")
  64. from grass.script.setup import set_gui_path
  65. set_gui_path()
  66. from grass.pydispatch.signal import Signal
  67. from grass.script import core as grass
  68. from grass.script import task as gtask
  69. from core import globalvar
  70. from gui_core.widgets import StaticWrapText, ScrolledPanel, ColorTablesComboBox, \
  71. BarscalesComboBox, NArrowsComboBox
  72. from gui_core.ghelp import HelpPanel
  73. from gui_core import gselect
  74. from core import gcmd
  75. from core import utils
  76. from core.utils import _
  77. from core.settings import UserSettings
  78. from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
  79. from core.giface import Notification
  80. from gui_core.widgets import LayersList
  81. from gui_core.wrap import BitmapFromImage, Button, StaticText, StaticBox, SpinCtrl
  82. from core.debug import Debug
  83. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  84. """Hide some options in the GUI"""
  85. #_blackList = { 'enabled' : False,
  86. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  87. # 'flags' : ['z', 'overwrite']}}}
  88. _blackList = {'enabled': False,
  89. 'items': {}}
  90. def text_beautify(someString, width=70):
  91. """Make really long texts shorter, clean up whitespace and remove
  92. trailing punctuation.
  93. """
  94. if width > 0:
  95. return escape_ampersand(
  96. string.strip(
  97. os.linesep.join(
  98. textwrap.wrap(
  99. utils.normalize_whitespace(someString),
  100. width)),
  101. ".,;:"))
  102. else:
  103. return escape_ampersand(string.strip(
  104. utils.normalize_whitespace(someString), ".,;:"))
  105. def escape_ampersand(text):
  106. """Escapes ampersands with additional ampersand for GUI"""
  107. return string.replace(text, "&", "&&")
  108. class UpdateThread(Thread):
  109. """Update dialog widgets in the thread"""
  110. def __init__(self, parent, event, eventId, task):
  111. Thread.__init__(self)
  112. self.parent = parent
  113. self.event = event
  114. self.eventId = eventId
  115. self.task = task
  116. self.setDaemon(True)
  117. # list of functions which updates the dialog
  118. self.data = {}
  119. def run(self):
  120. # get widget id
  121. if not self.eventId:
  122. for p in self.task.params:
  123. if p.get('gisprompt', False) == False:
  124. continue
  125. prompt = p.get('element', '')
  126. if prompt == 'vector':
  127. name = p.get('name', '')
  128. if name in ('map', 'input'):
  129. self.eventId = p['wxId'][0]
  130. if self.eventId is None:
  131. return
  132. p = self.task.get_param(self.eventId, element='wxId', raiseError=False)
  133. if not p or 'wxId-bind' not in p:
  134. return
  135. # is this check necessary?
  136. # get widget prompt
  137. # pType = p.get('prompt', '')
  138. # if not pType:
  139. # return
  140. # check for map/input parameter
  141. pMap = self.task.get_param('map', raiseError=False)
  142. if not pMap:
  143. pMap = self.task.get_param('input', raiseError=False)
  144. if pMap:
  145. map = pMap.get('value', '')
  146. else:
  147. map = None
  148. # avoid running db.describe several times
  149. cparams = dict()
  150. cparams[map] = {'dbInfo': None,
  151. 'layers': None, }
  152. # update reference widgets
  153. for uid in p['wxId-bind']:
  154. win = self.parent.FindWindowById(uid)
  155. if not win:
  156. continue
  157. name = win.GetName()
  158. # @todo: replace name by isinstance() and signals
  159. pBind = self.task.get_param(uid, element='wxId', raiseError=False)
  160. if pBind:
  161. pBind['value'] = ''
  162. # set appropriate types in t.* modules and g.list/remove element
  163. # selections
  164. if name == 'Select':
  165. type_param = self.task.get_param(
  166. 'type', element='name', raiseError=False)
  167. if 'all' in type_param.get('value'):
  168. etype = type_param.get('values')[:]
  169. if 'all' in etype:
  170. etype.remove('all')
  171. etype = ','.join(etype)
  172. else:
  173. etype = type_param.get('value')
  174. if globalvar.CheckWxVersion([3]):
  175. self.data[win.SetElementList] = {'type': etype}
  176. else:
  177. self.data[win.GetParent().SetElementList] = {'type': etype}
  178. # t.(un)register has one type for 'input', 'maps'
  179. maps_param = self.task.get_param(
  180. 'maps', element='name', raiseError=False)
  181. if self.task.get_name().startswith('t') and maps_param is not None:
  182. if maps_param['wxId'][0] != uid:
  183. element_dict = {
  184. 'raster': 'strds',
  185. 'vector': 'stvds',
  186. 'raster_3d': 'str3ds'}
  187. self.data[
  188. win.GetParent().SetType] = {
  189. 'etype': element_dict[
  190. type_param.get('value')]}
  191. map = layer = None
  192. driver = db = None
  193. if name in ('LayerSelect', 'ColumnSelect'):
  194. if p.get('element', '') == 'vector': # -> vector
  195. # get map name
  196. map = p.get('value', '')
  197. # get layer
  198. for bid in p['wxId-bind']:
  199. p = self.task.get_param(
  200. bid, element='wxId', raiseError=False)
  201. if not p:
  202. continue
  203. if p.get('element', '') in ['layer', 'layer_all']:
  204. layer = p.get('value', '')
  205. if layer != '':
  206. layer = p.get('value', '')
  207. else:
  208. layer = p.get('default', '')
  209. break
  210. elif p.get('element', '') in ['layer', 'layer_all']: # -> layer
  211. # get layer
  212. layer = p.get('value', '')
  213. if layer != '':
  214. layer = p.get('value', '')
  215. else:
  216. layer = p.get('default', '')
  217. # get map name
  218. pMapL = self.task.get_param(
  219. p['wxId'][0], element='wxId-bind', raiseError=False)
  220. if pMapL:
  221. map = pMapL.get('value', '')
  222. if name == 'TableSelect' or \
  223. (name == 'ColumnSelect' and not map):
  224. pDriver = self.task.get_param(
  225. 'dbdriver', element='prompt', raiseError=False)
  226. if pDriver:
  227. driver = pDriver.get('value', '')
  228. pDb = self.task.get_param(
  229. 'dbname', element='prompt', raiseError=False)
  230. if pDb:
  231. db = pDb.get('value', '')
  232. if name == 'ColumnSelect':
  233. pTable = self.task.get_param(
  234. 'dbtable', element='element', raiseError=False)
  235. if pTable:
  236. table = pTable.get('value', '')
  237. if name == 'LayerSelect':
  238. # determine format
  239. native = True
  240. for id in pMap['wxId']:
  241. winVec = self.parent.FindWindowById(id)
  242. if winVec.GetName() == 'VectorFormat' and \
  243. winVec.GetSelection() != 0:
  244. native = False
  245. break
  246. # TODO: update only if needed
  247. if native:
  248. if map:
  249. self.data[win.InsertLayers] = {'vector': map}
  250. else:
  251. self.data[win.InsertLayers] = {}
  252. else:
  253. if map:
  254. self.data[win.InsertLayers] = {
  255. 'dsn': map.rstrip('@OGR')}
  256. else:
  257. self.data[win.InsertLayers] = {}
  258. elif name == 'TableSelect':
  259. self.data[win.InsertTables] = {'driver': driver,
  260. 'database': db}
  261. elif name == 'ColumnSelect':
  262. if map:
  263. if map not in cparams:
  264. cparams[map] = {'dbInfo': None,
  265. 'layers': None, }
  266. if not cparams[map]['dbInfo']:
  267. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  268. self.data[win.GetParent().InsertColumns] = {
  269. 'vector': map, 'layer': layer,
  270. 'dbInfo': cparams[map]['dbInfo']}
  271. else: # table
  272. if driver and db:
  273. self.data[win.GetParent().InsertTableColumns] = {
  274. 'table': pTable.get('value'),
  275. 'driver': driver, 'database': db}
  276. elif pTable:
  277. self.data[win.GetParent().InsertTableColumns] = {
  278. 'table': pTable.get('value')}
  279. elif name == 'SubGroupSelect':
  280. self.data[win.Insert] = {'group': p.get('value', '')}
  281. elif name == 'SignatureSelect':
  282. if p.get('prompt', 'group') == 'group':
  283. group = p.get('value', '')
  284. pSubGroup = self.task.get_param(
  285. 'subgroup', element='prompt', raiseError=False)
  286. if pSubGroup:
  287. subgroup = pSubGroup.get('value', '')
  288. else:
  289. subgroup = None
  290. else:
  291. subgroup = p.get('value', '')
  292. pGroup = self.task.get_param(
  293. 'group', element='prompt', raiseError=False)
  294. if pGroup:
  295. group = pGroup.get('value', '')
  296. else:
  297. group = None
  298. self.data[win.Insert] = {'group': group,
  299. 'subgroup': subgroup}
  300. elif name == 'LocationSelect':
  301. pDbase = self.task.get_param(
  302. 'dbase', element='element', raiseError=False)
  303. if pDbase:
  304. self.data[
  305. win.UpdateItems] = {
  306. 'dbase': pDbase.get(
  307. 'value', '')}
  308. elif name == 'MapsetSelect':
  309. pDbase = self.task.get_param(
  310. 'dbase', element='element', raiseError=False)
  311. pLocation = self.task.get_param(
  312. 'location', element='element', raiseError=False)
  313. if pDbase and pLocation:
  314. self.data[
  315. win.UpdateItems] = {
  316. 'dbase': pDbase.get(
  317. 'value', ''), 'location': pLocation.get(
  318. 'value', '')}
  319. elif name == 'ProjSelect':
  320. pDbase = self.task.get_param(
  321. 'dbase', element='element', raiseError=False)
  322. pLocation = self.task.get_param(
  323. 'location', element='element', raiseError=False)
  324. pMapset = self.task.get_param(
  325. 'mapset', element='element', raiseError=False)
  326. if pDbase and pLocation and pMapset:
  327. self.data[
  328. win.UpdateItems] = {
  329. 'dbase': pDbase.get(
  330. 'value', ''), 'location': pLocation.get(
  331. 'value', ''), 'mapset': pMapset.get(
  332. 'value', '')}
  333. def UpdateDialog(parent, event, eventId, task):
  334. return UpdateThread(parent, event, eventId, task)
  335. class UpdateQThread(Thread):
  336. """Update dialog widgets in the thread"""
  337. requestId = 0
  338. def __init__(self, parent, requestQ, resultQ, **kwds):
  339. Thread.__init__(self, **kwds)
  340. self.parent = parent # cmdPanel
  341. self.setDaemon(True)
  342. self.requestQ = requestQ
  343. self.resultQ = resultQ
  344. self.start()
  345. def Update(self, callable, *args, **kwds):
  346. UpdateQThread.requestId += 1
  347. self.request = None
  348. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  349. return UpdateQThread.requestId
  350. def run(self):
  351. while True:
  352. requestId, callable, args, kwds = self.requestQ.get()
  353. self.request = callable(*args, **kwds)
  354. self.resultQ.put((requestId, self.request.run()))
  355. if self.request:
  356. event = wxUpdateDialog(data=self.request.data)
  357. wx.PostEvent(self.parent, event)
  358. class TaskFrame(wx.Frame):
  359. """This is the Frame containing the dialog for options input.
  360. The dialog is organized in a notebook according to the guisections
  361. defined by each GRASS command.
  362. If run with a parent, it may Apply, Ok or Cancel; the latter two
  363. close the dialog. The former two trigger a callback.
  364. If run standalone, it will allow execution of the command.
  365. The command is checked and sent to the clipboard when clicking
  366. 'Copy'.
  367. """
  368. def __init__(self, parent, giface, task_description, id=wx.ID_ANY,
  369. get_dcmd=None, layer=None,
  370. style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  371. self.get_dcmd = get_dcmd
  372. self.layer = layer
  373. self.task = task_description
  374. self.parent = parent # LayerTree | Modeler | None | ...
  375. self._giface = giface
  376. self.dialogClosing = Signal('TaskFrame.dialogClosing')
  377. # module name + keywords
  378. title = self.task.get_name()
  379. try:
  380. if self.task.keywords != ['']:
  381. title += " [" + ', '.join(self.task.keywords) + "]"
  382. except ValueError:
  383. pass
  384. wx.Frame.__init__(self, parent=parent, id=id, title=title,
  385. name="MainFrame", style=style, **kwargs)
  386. self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
  387. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  388. # statusbar
  389. self.CreateStatusBar()
  390. # icon
  391. self.SetIcon(
  392. wx.Icon(
  393. os.path.join(
  394. globalvar.ICONDIR,
  395. 'grass_dialog.ico'),
  396. wx.BITMAP_TYPE_ICO))
  397. guisizer = wx.BoxSizer(wx.VERTICAL)
  398. # set apropriate output window
  399. if self.parent:
  400. self.standalone = False
  401. else:
  402. self.standalone = True
  403. # logo + description
  404. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  405. # GRASS logo
  406. self.logo = wx.StaticBitmap(
  407. self.panel, -1,
  408. wx.Bitmap(
  409. name=os.path.join(
  410. globalvar.IMGDIR,
  411. 'grass_form.png'),
  412. type=wx.BITMAP_TYPE_PNG))
  413. topsizer.Add(self.logo, proportion=0, border=3,
  414. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  415. # add module description
  416. if self.task.label:
  417. module_desc = self.task.label + ' ' + self.task.description
  418. else:
  419. module_desc = self.task.description
  420. self.description = StaticWrapText(parent=self.panel,
  421. label=module_desc)
  422. topsizer.Add(self.description, proportion=1, border=5,
  423. flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  424. guisizer.Add(topsizer, proportion=0, flag=wx.EXPAND)
  425. self.panel.SetSizerAndFit(guisizer)
  426. self.Layout()
  427. # notebooks
  428. self.notebookpanel = CmdPanel(
  429. parent=self.panel,
  430. giface=self._giface,
  431. task=self.task,
  432. frame=self)
  433. self._gconsole = self.notebookpanel._gconsole
  434. if self._gconsole:
  435. self._gconsole.mapCreated.connect(self.OnMapCreated)
  436. self._gconsole.updateMap.connect(
  437. lambda: self._giface.updateMap.emit())
  438. self.goutput = self.notebookpanel.goutput
  439. if self.goutput:
  440. self.goutput.showNotification.connect(
  441. lambda message: self.SetStatusText(message))
  442. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  443. guisizer.Add(self.notebookpanel, proportion=1, flag=wx.EXPAND)
  444. # status bar
  445. status_text = _("Enter parameters for '") + self.task.name + "'"
  446. try:
  447. self.task.get_cmd()
  448. self.updateValuesHook()
  449. except ValueError:
  450. self.SetStatusText(status_text)
  451. # buttons
  452. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  453. # cancel
  454. if sys.platform == 'darwin':
  455. # stock id automatically adds ctrl-c shortcut to close dialog
  456. self.btn_cancel = Button(parent=self.panel, label=_("Close"))
  457. else:
  458. self.btn_cancel = Button(parent=self.panel, id=wx.ID_CLOSE)
  459. self.btn_cancel.SetToolTip(
  460. _("Close this window without executing the command (Ctrl+Q)"))
  461. btnsizer.Add(
  462. self.btn_cancel,
  463. proportion=0,
  464. flag=wx.ALL | wx.ALIGN_CENTER,
  465. border=10)
  466. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  467. # bind closing to ESC and CTRL+Q
  468. self.Bind(wx.EVT_MENU, self.OnCancel, id=wx.ID_CLOSE)
  469. accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)]
  470. accelTableList.append((wx.ACCEL_CTRL, ord('Q'), wx.ID_CLOSE))
  471. # TODO: bind Ctrl-t for tile windows here (trac #2004)
  472. if self.get_dcmd is not None: # A callback has been set up
  473. btn_apply = Button(parent=self.panel, id=wx.ID_APPLY)
  474. btn_ok = Button(parent=self.panel, id=wx.ID_OK)
  475. btn_ok.SetDefault()
  476. btnsizer.Add(btn_apply, proportion=0,
  477. flag=wx.ALL | wx.ALIGN_CENTER,
  478. border=10)
  479. btnsizer.Add(btn_ok, proportion=0,
  480. flag=wx.ALL | wx.ALIGN_CENTER,
  481. border=10)
  482. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  483. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  484. else: # We're standalone
  485. # run
  486. self.btn_run = Button(
  487. parent=self.panel, id=wx.ID_OK, label=_("&Run"))
  488. self.btn_run.SetToolTip(_("Run the command (Ctrl+R)"))
  489. self.btn_run.SetDefault()
  490. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  491. btnsizer.Add(self.btn_run, proportion=0,
  492. flag=wx.ALL | wx.ALIGN_CENTER,
  493. border=10)
  494. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  495. self.Bind(wx.EVT_MENU, self.OnRun, id=wx.ID_OK)
  496. accelTableList.append((wx.ACCEL_CTRL, ord('R'), wx.ID_OK))
  497. # copy
  498. if sys.platform == 'darwin':
  499. # stock id automatically adds ctrl-c shortcut to copy command
  500. self.btn_clipboard = Button(parent=self.panel, label=_("Copy"))
  501. else:
  502. self.btn_clipboard = Button(parent=self.panel, id=wx.ID_COPY)
  503. self.btn_clipboard.SetToolTip(
  504. _("Copy the current command string to the clipboard"))
  505. btnsizer.Add(self.btn_clipboard, proportion=0,
  506. flag=wx.ALL | wx.ALIGN_CENTER,
  507. border=10)
  508. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  509. # help
  510. self.btn_help = Button(parent=self.panel, id=wx.ID_HELP)
  511. self.btn_help.SetToolTip(
  512. _("Show manual page of the command (Ctrl+H)"))
  513. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  514. self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
  515. accelTableList.append((wx.ACCEL_CTRL, ord('H'), wx.ID_HELP))
  516. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  517. self.btn_help.Hide()
  518. # add help button
  519. btnsizer.Add(
  520. self.btn_help,
  521. proportion=0,
  522. flag=wx.ALL | wx.ALIGN_CENTER,
  523. border=10)
  524. guisizer.Add(
  525. btnsizer,
  526. proportion=0,
  527. flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  528. border=30)
  529. # abort key bindings
  530. abortId = wx.NewId()
  531. self.Bind(wx.EVT_MENU, self.OnAbort, id=abortId)
  532. accelTableList.append((wx.ACCEL_CTRL, ord('S'), abortId))
  533. # set accelerator table
  534. accelTable = wx.AcceleratorTable(accelTableList)
  535. self.SetAcceleratorTable(accelTable)
  536. if self._giface and self._giface.GetLayerTree():
  537. addLayer = False
  538. for p in self.task.params:
  539. if p.get('age', 'old') == 'new' and \
  540. p.get('prompt', '') in ('raster', 'vector', 'raster_3d'):
  541. addLayer = True
  542. if addLayer:
  543. # add newly created map into layer tree
  544. self.addbox = wx.CheckBox(
  545. parent=self.panel,
  546. label=_('Add created map(s) into layer tree'),
  547. style=wx.NO_BORDER)
  548. self.addbox.SetValue(
  549. UserSettings.Get(
  550. group='cmd',
  551. key='addNewLayer',
  552. subkey='enabled'))
  553. guisizer.Add(self.addbox, proportion=0,
  554. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  555. border=5)
  556. hasNew = False
  557. for p in self.task.params:
  558. if p.get('age', 'old') == 'new':
  559. hasNew = True
  560. break
  561. if self.get_dcmd is None and hasNew:
  562. # close dialog when command is terminated
  563. self.closebox = wx.CheckBox(
  564. parent=self.panel,
  565. label=_('Close dialog on finish'),
  566. style=wx.NO_BORDER)
  567. self.closebox.SetValue(
  568. UserSettings.Get(
  569. group='cmd',
  570. key='closeDlg',
  571. subkey='enabled'))
  572. self.closebox.SetToolTipString(
  573. _(
  574. "Close dialog when command is successfully finished. "
  575. "Change this settings in Preferences dialog ('Command' tab)."))
  576. guisizer.Add(self.closebox, proportion=0,
  577. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  578. border=5)
  579. # bindings
  580. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  581. # do layout
  582. # called automatically by SetSizer()
  583. self.panel.SetAutoLayout(True)
  584. self.panel.SetSizerAndFit(guisizer)
  585. sizeFrame = self.GetBestSize()
  586. self.SetMinSize(sizeFrame)
  587. if hasattr(self, "closebox"):
  588. scale = 0.33
  589. else:
  590. scale = 0.50
  591. self.SetSize(
  592. wx.Size(
  593. sizeFrame[0],
  594. sizeFrame[1] + scale * max(
  595. self.notebookpanel.panelMinHeight,
  596. self.notebookpanel.constrained_size[1])))
  597. # thread to update dialog
  598. # create queues
  599. self.requestQ = Queue.Queue()
  600. self.resultQ = Queue.Queue()
  601. self.updateThread = UpdateQThread(
  602. self.notebookpanel, self.requestQ, self.resultQ)
  603. self.Layout()
  604. # keep initial window size limited for small screens
  605. width, height = self.GetSize()
  606. self.SetSize(wx.Size(min(width, 650),
  607. min(height, 500)))
  608. # fix goutput's pane size (required for Mac OSX)
  609. if self.goutput:
  610. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  611. def MakeModal(self, modal=True):
  612. if globalvar.wxPythonPhoenix:
  613. if modal and not hasattr(self, '_disabler'):
  614. self._disabler = wx.WindowDisabler(self)
  615. if not modal and hasattr(self, '_disabler'):
  616. del self._disabler
  617. else:
  618. super(TaskFrame, self).MakeModal(modal)
  619. def updateValuesHook(self, event=None):
  620. """Update status bar data"""
  621. self.SetStatusText(
  622. ' '.join(
  623. [gcmd.DecodeString(each)
  624. if isinstance(each, str) else each
  625. for each in self.notebookpanel.createCmd(
  626. ignoreErrors=True)]))
  627. if event:
  628. event.Skip()
  629. def OnDone(self, event):
  630. """This function is launched from OnRun() when command is
  631. finished
  632. """
  633. if hasattr(self, "btn_cancel"):
  634. self.btn_cancel.Enable(True)
  635. if hasattr(self, "btn_clipboard"):
  636. self.btn_clipboard.Enable(True)
  637. if hasattr(self, "btn_help"):
  638. self.btn_help.Enable(True)
  639. if hasattr(self, "btn_run"):
  640. self.btn_run.Enable(True)
  641. if hasattr(self, "get_dcmd") and \
  642. self.get_dcmd is None and \
  643. hasattr(self, "closebox") and \
  644. self.closebox.IsChecked() and \
  645. (event.returncode == 0):
  646. # was closed also when aborted but better is leave it open
  647. wx.FutureCall(2000, self.Close)
  648. def OnMapCreated(self, name, ltype):
  649. """Map created or changed
  650. :param name: map name
  651. :param ltype: layer type (prompt value)
  652. """
  653. if hasattr(self, "addbox") and self.addbox.IsChecked():
  654. add = True
  655. else:
  656. add = False
  657. if self._giface:
  658. self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
  659. def OnOK(self, event):
  660. """OK button pressed"""
  661. cmd = self.OnApply(event)
  662. if cmd is not None and self.get_dcmd is not None:
  663. self.OnCancel(event)
  664. def OnApply(self, event):
  665. """Apply the command"""
  666. if self._giface and hasattr(self._giface, "_model"):
  667. cmd = self.createCmd(ignoreErrors=True, ignoreRequired=True)
  668. else:
  669. cmd = self.createCmd()
  670. if cmd is not None and self.get_dcmd is not None:
  671. # return d.* command to layer tree for rendering
  672. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  673. "flags": self.task.flags},
  674. self)
  675. # echo d.* command to output console
  676. # self.parent.writeDCommand(cmd)
  677. return cmd
  678. def OnRun(self, event):
  679. """Run the command"""
  680. cmd = self.createCmd()
  681. if not cmd or len(cmd) < 1:
  682. return
  683. ret = 0
  684. if self.standalone or cmd[0][0:2] != "d.":
  685. # Send any non-display command to parent window (probably wxgui.py)
  686. # put to parents switch to 'Command output'
  687. self.notebookpanel.notebook.SetSelectionByName('output')
  688. try:
  689. if self.task.path:
  690. cmd[0] = self.task.path # full path
  691. ret = self._gconsole.RunCmd(cmd, onDone=self.OnDone)
  692. except AttributeError as e:
  693. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (
  694. e)
  695. print >>sys.stderr, "parent window is: %s" % (
  696. str(self.parent))
  697. else:
  698. gcmd.Command(cmd)
  699. if ret != 0:
  700. self.notebookpanel.notebook.SetSelection(0)
  701. return
  702. # update buttons status
  703. for btn in (self.btn_run,
  704. self.btn_cancel,
  705. self.btn_clipboard,
  706. self.btn_help):
  707. btn.Enable(False)
  708. def OnAbort(self, event):
  709. """Abort running command"""
  710. from core.gconsole import wxCmdAbort
  711. event = wxCmdAbort(aborted=True)
  712. wx.PostEvent(self._gconsole, event)
  713. def OnCopy(self, event):
  714. """Copy the command"""
  715. cmddata = wx.TextDataObject()
  716. # list -> string
  717. cmdlist = self.createCmd(ignoreErrors=True)
  718. # TODO: better protect whitespace with quotes
  719. for i in range(1, len(cmdlist)):
  720. if ' ' in cmdlist[i]:
  721. optname, val = cmdlist[i].split("=", 1)
  722. cmdlist[i] = '%s="%s"' % (optname, val)
  723. cmdstring = ' '.join(cmdlist)
  724. cmddata.SetText(cmdstring)
  725. if wx.TheClipboard.Open():
  726. # wx.TheClipboard.UsePrimarySelection(True)
  727. wx.TheClipboard.SetData(cmddata)
  728. wx.TheClipboard.Close()
  729. self.SetStatusText(_("'%s' copied to clipboard") %
  730. (cmdstring))
  731. def OnCancel(self, event):
  732. """Cancel button pressed"""
  733. self.MakeModal(False)
  734. self.dialogClosing.emit()
  735. if self.get_dcmd and \
  736. self.parent and \
  737. self.parent.GetName() in ('LayerTree',
  738. 'MapWindow'):
  739. Debug.msg(1, "TaskFrame.OnCancel(): known parent")
  740. # display decorations and
  741. # pressing OK or cancel after setting layer properties
  742. if self.task.name in ['d.barscale', 'd.legend', 'd.northarrow', 'd.histogram', 'd.text', 'd.legend.vect'] \
  743. or len(self.parent.GetLayerInfo(self.layer, key='cmd')) >= 1:
  744. # TODO: do this through policy
  745. self.Hide()
  746. # canceled layer with nothing set
  747. elif len(self.parent.GetLayerInfo(self.layer, key='cmd')) < 1:
  748. # TODO: do this through callback or signal
  749. try:
  750. self.parent.Delete(self.layer)
  751. except ValueError:
  752. # happens when closing dialog of a new layer which was
  753. # removed from tree
  754. pass
  755. self.Destroy()
  756. else:
  757. Debug.msg(1, "TaskFrame.OnCancel(): no parent")
  758. # cancel for non-display commands
  759. self.Destroy()
  760. def OnHelp(self, event):
  761. """Show manual page (switch to the 'Manual' notebook page)"""
  762. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  763. self.notebookpanel.notebook.SetSelectionByName('manual')
  764. self.notebookpanel.OnPageChange(None)
  765. if event:
  766. event.Skip()
  767. def createCmd(self, ignoreErrors=False, ignoreRequired=False):
  768. """Create command string (python list)"""
  769. return self.notebookpanel.createCmd(ignoreErrors=ignoreErrors,
  770. ignoreRequired=ignoreRequired)
  771. class CmdPanel(wx.Panel):
  772. """A panel containing a notebook dividing in tabs the different
  773. guisections of the GRASS cmd.
  774. """
  775. def __init__(self, parent, giface, task, id=wx.ID_ANY,
  776. frame=None, *args, **kwargs):
  777. if frame:
  778. self.parent = frame
  779. else:
  780. self.parent = parent
  781. self.task = task
  782. self._giface = giface
  783. wx.Panel.__init__(self, parent, id=id, *args, **kwargs)
  784. self.mapCreated = Signal
  785. self.updateMap = Signal
  786. # Determine tab layout
  787. sections = []
  788. is_section = {}
  789. not_hidden = [
  790. p for p in self.task.params +
  791. self.task.flags if not p.get(
  792. 'hidden',
  793. False) == True]
  794. self.label_id = [] # wrap titles on resize
  795. self.Bind(wx.EVT_SIZE, self.OnSize)
  796. for task in not_hidden:
  797. if task.get('required', False) and not task.get('guisection', ''):
  798. # All required go into Main, even if they had defined another
  799. # guisection
  800. task['guisection'] = _('Required')
  801. if task.get('guisection', '') == '':
  802. # Undefined guisections end up into Options
  803. task['guisection'] = _('Optional')
  804. if task['guisection'] not in is_section:
  805. # We do it like this to keep the original order, except for
  806. # Main which goes first
  807. is_section[task['guisection']] = 1
  808. sections.append(task['guisection'])
  809. else:
  810. is_section[task['guisection']] += 1
  811. del is_section
  812. # 'Required' tab goes first, 'Optional' as the last one
  813. for (newidx, content) in [(0, _('Required')),
  814. (len(sections) - 1, _('Optional'))]:
  815. if content in sections:
  816. idx = sections.index(content)
  817. sections[idx:idx + 1] = []
  818. sections[newidx:newidx] = [content]
  819. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  820. # build notebook
  821. style = UserSettings.Get(
  822. group='appearance',
  823. key='commandNotebook',
  824. subkey='selection')
  825. if style == 0: # basic top
  826. self.notebook = FormNotebook(self, style=wx.BK_TOP)
  827. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  828. elif style == 1: # basic left
  829. self.notebook = FormNotebook(self, style=wx.BK_LEFT)
  830. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  831. elif style == 2: # fancy green
  832. self.notebook = GNotebook(
  833. self, style=globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON)
  834. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  835. self.notebook.Bind(
  836. FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
  837. self.OnPageChange)
  838. elif style == 3:
  839. self.notebook = FormListbook(self, style=wx.BK_LEFT)
  840. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  841. self.notebook.Refresh()
  842. tab = {}
  843. tabsizer = {}
  844. for section in sections:
  845. tab[section] = ScrolledPanel(parent=self.notebook)
  846. tab[section].SetScrollRate(10, 10)
  847. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  848. #
  849. # flags
  850. #
  851. visible_flags = [
  852. f for f in self.task.flags if not f.get(
  853. 'hidden', False) == True]
  854. for f in visible_flags:
  855. # we don't want another help (checkbox appeared in r58783)
  856. if f['name'] == 'help':
  857. continue
  858. which_sizer = tabsizer[f['guisection']]
  859. which_panel = tab[f['guisection']]
  860. # if label is given: description -> tooltip
  861. if f.get('label', '') != '':
  862. title = text_beautify(f['label'])
  863. tooltip = text_beautify(f['description'], width=-1)
  864. else:
  865. title = text_beautify(f['description'])
  866. tooltip = None
  867. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  868. rtitle_txt = StaticText(parent=which_panel,
  869. label='(' + f['name'] + ')')
  870. chk = wx.CheckBox(
  871. parent=which_panel,
  872. label=title,
  873. style=wx.NO_BORDER)
  874. self.label_id.append(chk.GetId())
  875. if tooltip:
  876. chk.SetToolTipString(tooltip)
  877. chk.SetValue(f.get('value', False))
  878. title_sizer.Add(chk, proportion=1,
  879. flag=wx.EXPAND)
  880. title_sizer.Add(rtitle_txt, proportion=0,
  881. flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  882. which_sizer.Add(
  883. title_sizer,
  884. proportion=0,
  885. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT,
  886. border=5)
  887. f['wxId'] = [chk.GetId(), ]
  888. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  889. if self.parent.GetName() == 'MainFrame' and (
  890. self._giface and hasattr(self._giface, "_model")):
  891. parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
  892. label=_("Parameterized in model"))
  893. parChk.SetName('ModelParam')
  894. parChk.SetValue(f.get('parameterized', False))
  895. if 'wxId' in f:
  896. f['wxId'].append(parChk.GetId())
  897. else:
  898. f['wxId'] = [parChk.GetId()]
  899. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  900. which_sizer.Add(parChk, proportion=0,
  901. flag=wx.LEFT, border=20)
  902. if f['name'] in ('verbose', 'quiet'):
  903. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  904. vq = UserSettings.Get(
  905. group='cmd', key='verbosity', subkey='selection')
  906. if f['name'] == vq:
  907. chk.SetValue(True)
  908. f['value'] = True
  909. if f['name'] == 'overwrite':
  910. value = UserSettings.Get(
  911. group='cmd', key='overwrite', subkey='enabled')
  912. if value: # override only when enabled
  913. f['value'] = value
  914. chk.SetValue(f['value'])
  915. #
  916. # parameters
  917. #
  918. visible_params = [
  919. p for p in self.task.params if not p.get(
  920. 'hidden', False) == True]
  921. try:
  922. first_param = visible_params[0]
  923. except IndexError:
  924. first_param = None
  925. for p in visible_params:
  926. which_sizer = tabsizer[p['guisection']]
  927. which_panel = tab[p['guisection']]
  928. # if label is given -> label and description -> tooltip
  929. # otherwise description -> lavel
  930. if p.get('label', '') != '':
  931. title = text_beautify(p['label'])
  932. tooltip = text_beautify(p['description'], width=-1)
  933. else:
  934. title = text_beautify(p['description'])
  935. tooltip = None
  936. prompt = p.get('prompt', '')
  937. # title sizer (description, name, type)
  938. if (len(p.get('values', [])) > 0) and \
  939. p.get('multiple', False) and \
  940. p.get('gisprompt', False) == False and \
  941. p.get('type', '') == 'string':
  942. title_txt = StaticBox(parent=which_panel, id=wx.ID_ANY)
  943. else:
  944. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  945. title_txt = StaticText(parent=which_panel)
  946. if p['key_desc']:
  947. ltype = ','.join(p['key_desc'])
  948. else:
  949. ltype = p['type']
  950. # red star for required options
  951. if p.get('required', False):
  952. required_txt = StaticText(parent=which_panel, label="*")
  953. required_txt.SetForegroundColour(wx.RED)
  954. required_txt.SetToolTip(_("This option is required"))
  955. else:
  956. required_txt = StaticText(parent=which_panel, label="")
  957. rtitle_txt = StaticText(
  958. parent=which_panel,
  959. label='(' + p['name'] + '=' + ltype + ')')
  960. title_sizer.Add(title_txt, proportion=0,
  961. flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  962. title_sizer.Add(required_txt, proportion=1,
  963. flag=wx.EXPAND, border=0)
  964. title_sizer.Add(
  965. rtitle_txt,
  966. proportion=0,
  967. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
  968. border=5)
  969. which_sizer.Add(title_sizer, proportion=0,
  970. flag=wx.EXPAND)
  971. self.label_id.append(title_txt.GetId())
  972. # title expansion
  973. if p.get('multiple', False) and len(p.get('values', '')) == 0:
  974. title = _("[multiple]") + " " + title
  975. if p.get('value', '') == '':
  976. p['value'] = p.get('default', '')
  977. if (len(p.get('values', [])) > 0):
  978. valuelist = map(str, p.get('values', []))
  979. valuelist_desc = map(unicode, p.get('values_desc', []))
  980. required_text = "*" if p.get('required', False) else ""
  981. if p.get('multiple', False) and \
  982. p.get('gisprompt', False) == False and \
  983. p.get('type', '') == 'string':
  984. title_txt.SetLabel(
  985. " %s:%s (%s=%s) " %
  986. (title, required_text, p['name'], p['type']))
  987. stSizer = wx.StaticBoxSizer(
  988. box=title_txt, orient=wx.VERTICAL)
  989. if valuelist_desc:
  990. hSizer = wx.FlexGridSizer(cols=1, vgap=1, hgap=1)
  991. else:
  992. hSizer = wx.FlexGridSizer(cols=6, vgap=1, hgap=1)
  993. isEnabled = {}
  994. # copy default values
  995. if p['value'] == '':
  996. p['value'] = p.get('default', '')
  997. for defval in p.get('value', '').split(','):
  998. isEnabled[defval] = 'yes'
  999. # for multi checkboxes, this is an array of all wx IDs
  1000. # for each individual checkbox
  1001. p['wxId'] = list()
  1002. idx = 0
  1003. for val in valuelist:
  1004. try:
  1005. label = valuelist_desc[idx]
  1006. except IndexError:
  1007. label = val
  1008. chkbox = wx.CheckBox(parent=which_panel,
  1009. label=text_beautify(label))
  1010. p['wxId'].append(chkbox.GetId())
  1011. if val in isEnabled:
  1012. chkbox.SetValue(True)
  1013. hSizer.Add(chkbox, proportion=0)
  1014. chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
  1015. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  1016. idx += 1
  1017. stSizer.Add(hSizer, proportion=0,
  1018. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1)
  1019. which_sizer.Add(
  1020. stSizer,
  1021. proportion=0,
  1022. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT,
  1023. border=5)
  1024. elif p.get('gisprompt', False) is False:
  1025. if len(valuelist) == 1: # -> textctrl
  1026. title_txt.SetLabel(
  1027. "%s (%s %s):" %
  1028. (title, _('valid range'),
  1029. str(valuelist[0])))
  1030. if p.get('type', '') == 'integer' and \
  1031. not p.get('multiple', False):
  1032. # for multiple integers use textctrl instead of
  1033. # spinsctrl
  1034. try:
  1035. minValue, maxValue = map(
  1036. int, valuelist[0].rsplit('-', 1))
  1037. except ValueError:
  1038. minValue = -1e6
  1039. maxValue = 1e6
  1040. txt2 = SpinCtrl(
  1041. parent=which_panel,
  1042. id=wx.ID_ANY,
  1043. size=globalvar.DIALOG_SPIN_SIZE,
  1044. min=minValue,
  1045. max=maxValue)
  1046. style = wx.BOTTOM | wx.LEFT
  1047. else:
  1048. txt2 = wx.TextCtrl(
  1049. parent=which_panel, value=p.get(
  1050. 'default', ''))
  1051. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  1052. value = self._getValue(p)
  1053. # parameter previously set
  1054. if value:
  1055. if isinstance(txt2, SpinCtrl):
  1056. txt2.SetValue(int(value))
  1057. else:
  1058. txt2.SetValue(value)
  1059. which_sizer.Add(txt2, proportion=0,
  1060. flag=style, border=5)
  1061. p['wxId'] = [txt2.GetId(), ]
  1062. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  1063. else:
  1064. title_txt.SetLabel(title + ':')
  1065. value = self._getValue(p)
  1066. if p['name'] in ('icon', 'icon_area', 'icon_line'): # symbols
  1067. bitmap = wx.Bitmap(
  1068. os.path.join(
  1069. globalvar.SYMBDIR,
  1070. value) + '.png')
  1071. bb = wx.BitmapButton(
  1072. parent=which_panel, id=wx.ID_ANY, bitmap=bitmap)
  1073. iconLabel = StaticText(
  1074. parent=which_panel, id=wx.ID_ANY)
  1075. iconLabel.SetLabel(value)
  1076. p['value'] = value
  1077. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  1078. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  1079. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1080. this_sizer.Add(
  1081. bb, proportion=0, flag=wx.ADJUST_MINSIZE |
  1082. wx.BOTTOM | wx.LEFT, border=5)
  1083. this_sizer.Add(
  1084. iconLabel,
  1085. proportion=0,
  1086. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
  1087. border=5)
  1088. which_sizer.Add(this_sizer, proportion=0,
  1089. flag=wx.ADJUST_MINSIZE, border=0)
  1090. else:
  1091. # list of values (combo)
  1092. cb = wx.ComboBox(
  1093. parent=which_panel, id=wx.ID_ANY, value=p.get(
  1094. 'default', ''),
  1095. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1096. choices=valuelist, style=wx.CB_DROPDOWN)
  1097. if value:
  1098. cb.SetValue(value) # parameter previously set
  1099. which_sizer.Add(
  1100. cb, proportion=0, flag=wx.ADJUST_MINSIZE |
  1101. wx.BOTTOM | wx.LEFT, border=5)
  1102. p['wxId'] = [cb.GetId(), ]
  1103. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1104. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  1105. if p.get('guidependency', ''):
  1106. cb.Bind(
  1107. wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1108. # text entry
  1109. if (p.get('type', 'string') in ('string', 'integer', 'float')
  1110. and len(p.get('values', [])) == 0
  1111. and p.get('gisprompt', False) == False
  1112. and p.get('prompt', '') != 'color'):
  1113. title_txt.SetLabel(title + ':')
  1114. p['wxId'] = []
  1115. if p.get('multiple', False) or \
  1116. p.get('type', 'string') == 'string' or \
  1117. len(p.get('key_desc', [])) > 1:
  1118. win = wx.TextCtrl(
  1119. parent=which_panel, value=p.get(
  1120. 'default', ''))
  1121. value = self._getValue(p)
  1122. if value:
  1123. # parameter previously set
  1124. win.SetValue(str(value))
  1125. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1126. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1127. if p.get('name', '') == 'font':
  1128. font_btn = Button(parent=which_panel, label=_("Select font"))
  1129. font_btn.Bind(wx.EVT_BUTTON, self.OnSelectFont)
  1130. font_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1131. font_sizer.Add(win, proportion=1,
  1132. flag=style, border=5)
  1133. font_sizer.Add(font_btn, proportion=0,
  1134. flag=style, border=5)
  1135. which_sizer.Add(font_sizer, proportion=0,
  1136. flag=style, border=5)
  1137. p['wxId'].append(font_btn.GetId())
  1138. else:
  1139. which_sizer.Add(win, proportion=0,
  1140. flag=style, border=5)
  1141. elif p.get('type', '') == 'integer':
  1142. minValue = -1e9
  1143. maxValue = 1e9
  1144. value = self._getValue(p)
  1145. win = SpinCtrl(
  1146. parent=which_panel,
  1147. value=p.get(
  1148. 'default',
  1149. ''),
  1150. size=globalvar.DIALOG_SPIN_SIZE,
  1151. min=minValue,
  1152. max=maxValue)
  1153. if value:
  1154. win.SetValue(int(value)) # parameter previously set
  1155. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1156. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1157. which_sizer.Add(win, proportion=0,
  1158. flag=style, border=5)
  1159. else: # float
  1160. win = wx.TextCtrl(
  1161. parent=which_panel, value=p.get(
  1162. 'default', ''), validator=FloatValidator())
  1163. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1164. which_sizer.Add(win, proportion=0,
  1165. flag=style, border=5)
  1166. value = self._getValue(p)
  1167. if value:
  1168. win.SetValue(str(value)) # parameter previously set
  1169. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1170. p['wxId'].append(win.GetId())
  1171. #
  1172. # element selection tree combobox (maps, icons, regions, etc.)
  1173. #
  1174. if p.get('gisprompt', False):
  1175. title_txt.SetLabel(title + ':')
  1176. # GIS element entry
  1177. if p.get('prompt', '') not in ('color',
  1178. 'cat',
  1179. 'cats',
  1180. 'subgroup',
  1181. 'sigfile',
  1182. 'separator',
  1183. 'dbdriver',
  1184. 'dbname',
  1185. 'dbtable',
  1186. 'dbcolumn',
  1187. 'layer',
  1188. 'location',
  1189. 'mapset',
  1190. 'dbase',
  1191. 'coords',
  1192. 'file',
  1193. 'dir',
  1194. 'colortable',
  1195. 'barscale',
  1196. 'northarrow',
  1197. 'datasource',
  1198. 'datasource_layer'):
  1199. multiple = p.get('multiple', False)
  1200. if p.get('age', '') == 'new':
  1201. mapsets = [grass.gisenv()['MAPSET'], ]
  1202. else:
  1203. mapsets = None
  1204. if self.task.name in ('r.proj', 'v.proj') \
  1205. and p.get('name', '') == 'input':
  1206. selection = gselect.ProjSelect(
  1207. parent=which_panel, isRaster=self.task.name == 'r.proj')
  1208. p['wxId'] = [selection.GetId(), ]
  1209. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1210. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1211. else:
  1212. elem = p.get('element', None)
  1213. # hack for t.* modules
  1214. if elem in ('stds', 'map'):
  1215. orig_elem = elem
  1216. type_param = self.task.get_param(
  1217. 'type', element='name', raiseError=False)
  1218. if type_param:
  1219. elem = type_param.get('default', None)
  1220. # for t.(un)register:
  1221. maps_param = self.task.get_param(
  1222. 'maps', element='name', raiseError=False)
  1223. if maps_param and orig_elem == 'stds':
  1224. element_dict = {
  1225. 'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  1226. elem = element_dict[
  1227. type_param.get('default')]
  1228. extraItems = None
  1229. if self._giface:
  1230. if hasattr(self._giface, "_model"):
  1231. extraItems = {
  1232. _('Graphical Modeler'): self._giface.GetLayerList(
  1233. p.get('prompt'))}
  1234. else:
  1235. layers = self._giface.GetLayerList()
  1236. if len(layers) > 0:
  1237. mapList = []
  1238. extraItems = {_('Map Display'): mapList}
  1239. for layer in layers:
  1240. if layer.type != p.get('prompt'):
  1241. continue
  1242. mapList.append(str(layer))
  1243. selection = gselect.Select(
  1244. parent=which_panel, id=wx.ID_ANY,
  1245. size=globalvar.DIALOG_GSELECT_SIZE, type=elem,
  1246. multiple=multiple, nmaps=len(
  1247. p.get('key_desc', [])),
  1248. mapsets=mapsets, fullyQualified=p.get(
  1249. 'age', 'old') == 'old', extraItems=extraItems)
  1250. value = self._getValue(p)
  1251. if value:
  1252. selection.SetValue(value)
  1253. formatSelector = True
  1254. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1255. # we target the textctl here
  1256. textWin = selection.GetTextCtrl()
  1257. if globalvar.CheckWxVersion([3]):
  1258. p['wxId'] = [selection.GetId(), ]
  1259. else:
  1260. p['wxId'] = [textWin.GetId(), ]
  1261. if prompt != 'vector':
  1262. self.FindWindowById(
  1263. p['wxId'][0]).Bind(
  1264. wx.EVT_TEXT, self.OnSetValue)
  1265. if prompt == 'vector':
  1266. win = self.FindWindowById(p['wxId'][0])
  1267. # handlers should be bound in this order
  1268. # OnUpdateSelection depends on calling OnSetValue first
  1269. # which is bad
  1270. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1271. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1272. # if formatSelector and p.get('age', 'old') == 'old':
  1273. # # OGR supported (read-only)
  1274. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1275. # self.hsizer.Add(item = selection,
  1276. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1277. # border = 5)
  1278. # # format (native / ogr)
  1279. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1280. # label = " %s " % _("Format"),
  1281. # style = wx.RA_SPECIFY_ROWS,
  1282. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1283. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1284. # rbox.SetSelection(1)
  1285. # rbox.SetName('VectorFormat')
  1286. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1287. # self.hsizer.Add(item = rbox,
  1288. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1289. # wx.RIGHT | wx.ALIGN_TOP,
  1290. # border = 5)
  1291. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1292. # default = 'dir',
  1293. # exclude = ['file'])
  1294. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1295. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1296. # ogrSelection.SetName('OgrSelect')
  1297. # ogrSelection.Hide()
  1298. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1299. # p['wxId'].append(rbox.GetId())
  1300. # p['wxId'].append(ogrSelection.GetId())
  1301. # for win in ogrSelection.GetDsnWin():
  1302. # p['wxId'].append(win.GetId())
  1303. # else:
  1304. which_sizer.Add(
  1305. selection,
  1306. proportion=0,
  1307. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1308. border=5)
  1309. elif prompt == 'group':
  1310. win = self.FindWindowById(p['wxId'][0])
  1311. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1312. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1313. which_sizer.Add(
  1314. selection,
  1315. proportion=0,
  1316. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1317. border=5)
  1318. else:
  1319. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1320. showButton = True
  1321. try:
  1322. # if matplotlib is there
  1323. from timeline import frame
  1324. showButton = True
  1325. except ImportError:
  1326. showButton = False
  1327. else:
  1328. showButton = False
  1329. if showButton:
  1330. iconTheme = UserSettings.Get(
  1331. group='appearance', key='iconTheme', subkey='type')
  1332. bitmap = wx.Bitmap(
  1333. os.path.join(
  1334. globalvar.ICONDIR, iconTheme,
  1335. 'map-info.png'))
  1336. bb = wx.BitmapButton(
  1337. parent=which_panel, bitmap=bitmap)
  1338. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1339. bb.SetToolTipString(
  1340. _("Show graphical representation of temporal extent of dataset(s) ."))
  1341. p['wxId'].append(bb.GetId())
  1342. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1343. hSizer.Add(
  1344. selection,
  1345. proportion=0,
  1346. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1347. border=5)
  1348. hSizer.Add(
  1349. bb,
  1350. proportion=0,
  1351. flag=wx.EXPAND | wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1352. border=5)
  1353. which_sizer.Add(hSizer)
  1354. else:
  1355. which_sizer.Add(
  1356. selection,
  1357. proportion=0,
  1358. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1359. border=5)
  1360. # subgroup
  1361. elif prompt == 'subgroup':
  1362. selection = gselect.SubGroupSelect(parent=which_panel)
  1363. p['wxId'] = [selection.GetId()]
  1364. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1365. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1366. which_sizer.Add(
  1367. selection,
  1368. proportion=0,
  1369. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1370. border=5)
  1371. # sigrature file
  1372. elif prompt == 'sigfile':
  1373. selection = gselect.SignatureSelect(
  1374. parent=which_panel, element=p.get('element', 'sig'))
  1375. p['wxId'] = [selection.GetId()]
  1376. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1377. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1378. which_sizer.Add(
  1379. selection,
  1380. proportion=0,
  1381. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1382. border=5)
  1383. # separator
  1384. elif prompt == 'separator':
  1385. win = gselect.SeparatorSelect(parent=which_panel)
  1386. value = self._getValue(p)
  1387. win.SetValue(value)
  1388. p['wxId'] = [win.GetId()]
  1389. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1390. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1391. which_sizer.Add(
  1392. win,
  1393. proportion=0,
  1394. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1395. border=5)
  1396. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1397. elif prompt in ('dbdriver',
  1398. 'dbname',
  1399. 'dbtable',
  1400. 'dbcolumn',
  1401. 'layer',
  1402. 'location',
  1403. 'mapset',
  1404. 'dbase'):
  1405. if p.get('multiple', 'no') == 'yes':
  1406. win = wx.TextCtrl(
  1407. parent=which_panel, value=p.get(
  1408. 'default', ''), size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1409. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1410. else:
  1411. value = self._getValue(p)
  1412. if prompt == 'layer':
  1413. if p.get('element', 'layer') == 'layer_all':
  1414. all = True
  1415. else:
  1416. all = False
  1417. if p.get('age', 'old') == 'old':
  1418. win = gselect.LayerSelect(parent=which_panel,
  1419. all=all,
  1420. default=p['default'])
  1421. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1422. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1423. win.SetValue(
  1424. str(value)) # default or previously set value
  1425. else:
  1426. win = SpinCtrl(
  1427. parent=which_panel, id=wx.ID_ANY, min=1,
  1428. max=100, initial=int(p['default']))
  1429. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1430. win.SetValue(
  1431. int(value)) # default or previously set value
  1432. p['wxId'] = [win.GetId()]
  1433. elif prompt == 'dbdriver':
  1434. win = gselect.DriverSelect(
  1435. parent=which_panel, choices=p.get(
  1436. 'values', []),
  1437. value=value)
  1438. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1439. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1440. elif prompt == 'dbname':
  1441. win = gselect.DatabaseSelect(parent=which_panel,
  1442. value=value)
  1443. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1444. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1445. elif prompt == 'dbtable':
  1446. if p.get('age', 'old') == 'old':
  1447. win = gselect.TableSelect(parent=which_panel)
  1448. win.Bind(
  1449. wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1450. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1451. else:
  1452. win = wx.TextCtrl(
  1453. parent=which_panel, value=p.get(
  1454. 'default', ''),
  1455. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1456. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1457. elif prompt == 'dbcolumn':
  1458. win = gselect.ColumnSelect(
  1459. parent=which_panel, value=value, param=p,
  1460. multiple=p.get('multiple', False))
  1461. # A gselect.ColumnSelect is a combobox
  1462. # with two children: a textctl and a
  1463. # popupwindow; we target the textctl here
  1464. textWin = win.GetTextCtrl()
  1465. p['wxId'] = [textWin.GetId(), ]
  1466. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1467. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1468. elif prompt == 'location':
  1469. win = gselect.LocationSelect(parent=which_panel,
  1470. value=value)
  1471. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1472. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1473. elif prompt == 'mapset':
  1474. if p.get('age', 'old') == 'old':
  1475. new = False
  1476. else:
  1477. new = True
  1478. win = gselect.MapsetSelect(
  1479. parent=which_panel, value=value, new=new,
  1480. multiple=p.get('multiple', False))
  1481. textWin = win.GetTextCtrl()
  1482. p['wxId'] = [textWin.GetId(), win.GetId()]
  1483. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1484. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1485. elif prompt == 'dbase':
  1486. win = gselect.DbaseSelect(
  1487. parent=which_panel, changeCallback=self.OnSetValue)
  1488. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1489. p['wxId'] = [win.GetChildren()[1].GetId()]
  1490. if 'wxId' not in p:
  1491. try:
  1492. p['wxId'] = [win.GetId(), ]
  1493. except AttributeError:
  1494. pass
  1495. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1496. if prompt == 'dbname':
  1497. flags |= wx.EXPAND
  1498. which_sizer.Add(win, proportion=0,
  1499. flag=flags, border=5)
  1500. # color entry
  1501. elif prompt == 'color':
  1502. default_color = (200, 200, 200)
  1503. label_color = _("Select Color")
  1504. if p.get('default', '') != '':
  1505. default_color, label_color = utils.color_resolve(p[
  1506. 'default'])
  1507. if p.get('value', '') != '' and p.get(
  1508. 'value', '') != 'none': # parameter previously set
  1509. if not p.get('multiple', False):
  1510. default_color, label_color = utils.color_resolve(p[
  1511. 'value'])
  1512. if p.get(
  1513. 'element', '') == 'color_none' or p.get(
  1514. 'multiple', False):
  1515. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  1516. else:
  1517. this_sizer = which_sizer
  1518. colorSize = 150
  1519. # For color selectors, this is a three-member array, holding the IDs of
  1520. # the color picker, the text control for multiple colors (or None),
  1521. # and either a "transparent" checkbox or None
  1522. p['wxId'] = [None] * 3
  1523. if p.get('multiple', False):
  1524. txt = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY)
  1525. this_sizer.Add(
  1526. txt,
  1527. proportion=1,
  1528. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP,
  1529. border=5)
  1530. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1531. if p.get('value', ''):
  1532. txt.SetValue(p['value'])
  1533. colorSize = 40
  1534. label_color = ''
  1535. p['wxId'][1] = txt.GetId()
  1536. which_sizer.Add(
  1537. this_sizer, flag=wx.EXPAND | wx.RIGHT, border=5)
  1538. btn_colour = csel.ColourSelect(
  1539. parent=which_panel, id=wx.ID_ANY, label=label_color,
  1540. colour=default_color, pos=wx.DefaultPosition,
  1541. size=(colorSize, 32))
  1542. this_sizer.Add(
  1543. btn_colour,
  1544. proportion=0,
  1545. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
  1546. border=5)
  1547. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1548. p['wxId'][0] = btn_colour.GetId()
  1549. if p.get('element', '') == 'color_none':
  1550. none_check = wx.CheckBox(
  1551. which_panel, wx.ID_ANY, _("Transparent"))
  1552. if p.get('value', '') == "none":
  1553. none_check.SetValue(True)
  1554. else:
  1555. none_check.SetValue(False)
  1556. this_sizer.Add(
  1557. none_check, proportion=0,
  1558. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP,
  1559. border=5)
  1560. which_sizer.Add(this_sizer)
  1561. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1562. p['wxId'][2] = none_check.GetId()
  1563. # file selector
  1564. elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'file':
  1565. if p.get('age', 'new') == 'new':
  1566. fmode = wx.FD_SAVE
  1567. else:
  1568. fmode = wx.FD_OPEN
  1569. # check wildcard
  1570. try:
  1571. fExt = os.path.splitext(
  1572. p.get('key_desc', ['*.*'])[0])[1]
  1573. except:
  1574. fExt = None
  1575. if not fExt:
  1576. fMask = '*'
  1577. else:
  1578. fMask = '%s files (*%s)|*%s|Files (*)|*' % (
  1579. fExt[1:].upper(), fExt, fExt)
  1580. fbb = filebrowse.FileBrowseButton(
  1581. parent=which_panel,
  1582. id=wx.ID_ANY,
  1583. fileMask=fMask,
  1584. size=globalvar.DIALOG_GSELECT_SIZE,
  1585. labelText='',
  1586. dialogTitle=_('Choose %s') %
  1587. p.get(
  1588. 'description',
  1589. _('file')).lower(),
  1590. buttonText=_('Browse'),
  1591. startDirectory=os.getcwd(),
  1592. fileMode=fmode,
  1593. changeCallback=self.OnSetValue)
  1594. value = self._getValue(p)
  1595. if value:
  1596. fbb.SetValue(value) # parameter previously set
  1597. which_sizer.Add(fbb, proportion=0,
  1598. flag=wx.EXPAND | wx.RIGHT, border=5)
  1599. # A file browse button is a combobox with two children:
  1600. # a textctl and a button;
  1601. # we have to target the button here
  1602. p['wxId'] = [fbb.GetChildren()[1].GetId()]
  1603. if p.get(
  1604. 'age', 'new') == 'old' and p.get(
  1605. 'prompt', '') == 'file' and p.get(
  1606. 'element', '') == 'file' and UserSettings.Get(
  1607. group='cmd', key='interactiveInput', subkey='enabled'):
  1608. # widget for interactive input
  1609. ifbb = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY,
  1610. style=wx.TE_MULTILINE,
  1611. size=(-1, 75))
  1612. if p.get('value', '') and os.path.isfile(p['value']):
  1613. f = open(p['value'])
  1614. ifbb.SetValue(''.join(f.readlines()))
  1615. f.close()
  1616. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1617. btnLoad = Button(
  1618. parent=which_panel, id=wx.ID_ANY, label=_("&Load"))
  1619. btnLoad.SetToolTip(
  1620. _("Load and edit content of a file"))
  1621. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1622. btnSave = Button(
  1623. parent=which_panel, id=wx.ID_ANY, label=_("&Save as"))
  1624. btnSave.SetToolTip(
  1625. _("Save content to a file for further use"))
  1626. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1627. fileContentLabel = StaticText(
  1628. parent=which_panel, id=wx.ID_ANY,
  1629. label=_('or enter values directly:'))
  1630. fileContentLabel.SetToolTip(
  1631. _("Enter file content directly instead of specifying"
  1632. " a file."
  1633. " Temporary file will be automatically created."))
  1634. which_sizer.Add(
  1635. fileContentLabel,
  1636. proportion=0,
  1637. flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM,
  1638. border=5)
  1639. which_sizer.Add(
  1640. ifbb,
  1641. proportion=1,
  1642. flag=wx.EXPAND | wx.RIGHT | wx.LEFT,
  1643. border=5)
  1644. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1645. btnSizer.Add(btnLoad, proportion=0,
  1646. flag=wx.ALIGN_RIGHT | wx.RIGHT, border=10)
  1647. btnSizer.Add(btnSave, proportion=0,
  1648. flag=wx.ALIGN_RIGHT)
  1649. which_sizer.Add(
  1650. btnSizer,
  1651. proportion=0,
  1652. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
  1653. border=5)
  1654. p['wxId'].append(ifbb.GetId())
  1655. p['wxId'].append(btnLoad.GetId())
  1656. p['wxId'].append(btnSave.GetId())
  1657. # directory selector
  1658. elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'dir':
  1659. fbb = filebrowse.DirBrowseButton(
  1660. parent=which_panel,
  1661. id=wx.ID_ANY,
  1662. size=globalvar.DIALOG_GSELECT_SIZE,
  1663. labelText='',
  1664. dialogTitle=_('Choose %s') %
  1665. p.get(
  1666. 'description',
  1667. _('Directory')),
  1668. buttonText=_('Browse'),
  1669. startDirectory=os.getcwd(),
  1670. changeCallback=self.OnSetValue)
  1671. value = self._getValue(p)
  1672. if value:
  1673. fbb.SetValue(value) # parameter previously set
  1674. which_sizer.Add(fbb, proportion=0,
  1675. flag=wx.EXPAND | wx.RIGHT, border=5)
  1676. # A file browse button is a combobox with two children:
  1677. # a textctl and a button;
  1678. # we have to target the button here
  1679. p['wxId'] = [fbb.GetChildren()[1].GetId()]
  1680. # interactive inserting of coordinates from map window
  1681. elif prompt == 'coords':
  1682. # interactive inserting if layer manager is accessible
  1683. if self._giface:
  1684. win = gselect.CoordinatesSelect(
  1685. parent=which_panel, giface=self._giface, multiple=p.get(
  1686. 'multiple', False), param=p)
  1687. p['wxId'] = [win.GetTextWin().GetId()]
  1688. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1689. # bind closing event because destructor is not working
  1690. # properly
  1691. if hasattr(self.parent, 'dialogClosing'):
  1692. self.parent.dialogClosing.connect(win.OnClose)
  1693. # normal text field
  1694. else:
  1695. win = wx.TextCtrl(parent=which_panel)
  1696. p['wxId'] = [win.GetId()]
  1697. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1698. which_sizer.Add(
  1699. win,
  1700. proportion=0,
  1701. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1702. border=5)
  1703. elif prompt in ('cat', 'cats'):
  1704. # interactive selection of vector categories if layer
  1705. # manager is accessible
  1706. if self._giface:
  1707. win = gselect.VectorCategorySelect(
  1708. parent=which_panel, giface=self._giface, task=self.task)
  1709. p['wxId'] = [win.GetTextWin().GetId()]
  1710. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1711. # bind closing event because destructor is not working
  1712. # properly
  1713. if hasattr(self.parent, 'dialogClosing'):
  1714. self.parent.dialogClosing.connect(win.OnClose)
  1715. # normal text field
  1716. else:
  1717. win = wx.TextCtrl(parent=which_panel)
  1718. value = self._getValue(p)
  1719. win.SetValue(value)
  1720. p['wxId'] = [win.GetId()]
  1721. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1722. which_sizer.Add(
  1723. win,
  1724. proportion=0,
  1725. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1726. border=5)
  1727. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1728. if prompt == 'colortable':
  1729. cb = ColorTablesComboBox(
  1730. parent=which_panel, value=p.get('default', ''),
  1731. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1732. choices=valuelist)
  1733. elif prompt == 'barscale':
  1734. cb = BarscalesComboBox(
  1735. parent=which_panel, value=p.get('default', ''),
  1736. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1737. choices=valuelist)
  1738. elif prompt == 'northarrow':
  1739. cb = NArrowsComboBox(
  1740. parent=which_panel, value=p.get('default', ''),
  1741. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1742. choices=valuelist)
  1743. value = self._getValue(p)
  1744. if value:
  1745. cb.SetValue(value) # parameter previously set
  1746. which_sizer.Add(
  1747. cb,
  1748. proportion=0,
  1749. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
  1750. border=5)
  1751. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1752. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1753. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1754. if p.get('guidependency', ''):
  1755. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1756. elif prompt == 'datasource':
  1757. win = gselect.GdalSelect(parent=parent, panel=which_panel,
  1758. ogr=True)
  1759. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1760. win.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1761. p['wxId'] = [
  1762. win.GetId(),
  1763. win.fileWidgets['browse'].GetChildren()[1].GetId(),
  1764. win.dirWidgets['browse'].GetChildren()[1].GetId(),
  1765. win.dbWidgets['choice'].GetId()]
  1766. value = self._getValue(p)
  1767. if value:
  1768. win.fileWidgets['browse'].GetChildren()[1].SetValue(
  1769. value) # parameter previously set
  1770. which_sizer.Add(win, proportion=0,
  1771. flag=wx.EXPAND)
  1772. elif prompt == 'datasource_layer':
  1773. self.win1 = LayersList(
  1774. parent=which_panel,
  1775. columns=[
  1776. _('Layer id'),
  1777. _('Layer name'),
  1778. _('Feature type'),
  1779. _('Projection match')])
  1780. which_sizer.Add(self.win1, proportion=0,
  1781. flag=wx.EXPAND | wx.ALL, border=3)
  1782. porf = self.task.get_param(
  1783. 'input', element='name', raiseError=False)
  1784. if porf and 'wxId' in porf:
  1785. winDataSource = self.FindWindowById(porf['wxId'][0])
  1786. winDataSource.reloadDataRequired.connect(
  1787. lambda listData: self.win1.LoadData(
  1788. listData, False))
  1789. p['wxId'] = [self.win1.GetId()]
  1790. def OnCheckItem(index, flag):
  1791. layers = list()
  1792. for layer, match, listId in self.win1.GetLayers():
  1793. layers.append(layer)
  1794. porf = self.task.get_param(
  1795. 'layer', element='name', raiseError=False)
  1796. porf['value'] = ','.join(layers)
  1797. self.OnUpdateValues() # TODO: replace by signal
  1798. self.win1.OnCheckItem = OnCheckItem
  1799. if self.parent.GetName() == 'MainFrame' and (
  1800. self._giface and hasattr(self._giface, "_model")):
  1801. parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
  1802. label=_("Parameterized in model"))
  1803. parChk.SetName('ModelParam')
  1804. parChk.SetValue(p.get('parameterized', False))
  1805. if 'wxId' in p:
  1806. p['wxId'].append(parChk.GetId())
  1807. else:
  1808. p['wxId'] = [parChk.GetId()]
  1809. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1810. which_sizer.Add(parChk, proportion=0,
  1811. flag=wx.LEFT, border=20)
  1812. if title_txt is not None:
  1813. # create tooltip if given
  1814. if len(p['values_desc']) > 0:
  1815. if tooltip:
  1816. tooltip += 2 * os.linesep
  1817. else:
  1818. tooltip = ''
  1819. if len(p['values']) == len(p['values_desc']):
  1820. for i in range(len(p['values'])):
  1821. tooltip += p['values'][i] + ': ' + \
  1822. p['values_desc'][i] + os.linesep
  1823. tooltip.strip(os.linesep)
  1824. if tooltip:
  1825. title_txt.SetToolTip(tooltip)
  1826. if p == first_param:
  1827. if 'wxId' in p and len(p['wxId']) > 0:
  1828. win = self.FindWindowById(p['wxId'][0])
  1829. win.SetFocus()
  1830. #
  1831. # set widget relations for OnUpdateSelection
  1832. #
  1833. pMap = None
  1834. pLayer = []
  1835. pDriver = None
  1836. pDatabase = None
  1837. pTable = None
  1838. pColumn = []
  1839. pGroup = None
  1840. pSubGroup = None
  1841. pSigFile = []
  1842. pDbase = None
  1843. pLocation = None
  1844. pMapset = None
  1845. for p in self.task.params:
  1846. if self.task.blackList['enabled'] and self.task.get_name() in self.task.blackList['items'] and \
  1847. p.get('name', '') in self.task.blackList['items'][self.task.get_name()]['params']:
  1848. continue
  1849. guidep = p.get('guidependency', '')
  1850. if guidep:
  1851. # fixed options dependency defined
  1852. options = guidep.split(',')
  1853. for opt in options:
  1854. pOpt = self.task.get_param(
  1855. opt, element='name', raiseError=False)
  1856. if pOpt and id:
  1857. if 'wxId-bind' not in p:
  1858. p['wxId-bind'] = list()
  1859. p['wxId-bind'] += pOpt['wxId']
  1860. continue
  1861. if p.get('gisprompt', False) == False:
  1862. continue
  1863. prompt = p.get('prompt', '')
  1864. if prompt in ('raster', 'vector'):
  1865. name = p.get('name', '')
  1866. if name in ('map', 'input'):
  1867. pMap = p
  1868. elif prompt == 'layer':
  1869. pLayer.append(p)
  1870. elif prompt == 'dbcolumn':
  1871. pColumn.append(p)
  1872. elif prompt == 'dbdriver':
  1873. pDriver = p
  1874. elif prompt == 'dbname':
  1875. pDatabase = p
  1876. elif prompt == 'dbtable':
  1877. pTable = p
  1878. elif prompt == 'group':
  1879. pGroup = p
  1880. elif prompt == 'subgroup':
  1881. pSubGroup = p
  1882. elif prompt == 'sigfile':
  1883. pSigFile.append(p)
  1884. elif prompt == 'dbase':
  1885. pDbase = p
  1886. elif prompt == 'location':
  1887. pLocation = p
  1888. elif prompt == 'mapset':
  1889. pMapset = p
  1890. # collect ids
  1891. pColumnIds = []
  1892. for p in pColumn:
  1893. pColumnIds += p['wxId']
  1894. pLayerIds = []
  1895. for p in pLayer:
  1896. pLayerIds += p['wxId']
  1897. pSigFileIds = []
  1898. for p in pSigFile:
  1899. pSigFileIds += p['wxId']
  1900. # set wxId-bindings
  1901. if pMap:
  1902. pMap['wxId-bind'] = []
  1903. if pLayer:
  1904. pMap['wxId-bind'] += pLayerIds
  1905. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1906. if pLayer:
  1907. for p in pLayer:
  1908. p['wxId-bind'] = copy.copy(pColumnIds)
  1909. if pDriver and pTable:
  1910. pDriver['wxId-bind'] = pTable['wxId']
  1911. if pDatabase and pTable:
  1912. pDatabase['wxId-bind'] = pTable['wxId']
  1913. if pTable and pColumnIds:
  1914. pTable['wxId-bind'] = pColumnIds
  1915. if pGroup and pSubGroup:
  1916. if pSigFile:
  1917. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1918. pSubGroup['wxId-bind'] = pSigFileIds
  1919. else:
  1920. pGroup['wxId-bind'] = pSubGroup['wxId']
  1921. if pDbase and pLocation:
  1922. pDbase['wxId-bind'] = pLocation['wxId']
  1923. if pLocation and pMapset:
  1924. pLocation['wxId-bind'] = pMapset['wxId']
  1925. if pLocation and pMapset and pMap:
  1926. # pLocation['wxId-bind'] += pMap['wxId']
  1927. pMapset['wxId-bind'] = pMap['wxId']
  1928. #
  1929. # determine panel size
  1930. #
  1931. maxsizes = (0, 0)
  1932. for section in sections:
  1933. tab[section].SetSizer(tabsizer[section])
  1934. tabsizer[section].Fit(tab[section])
  1935. tab[section].Layout()
  1936. minsecsizes = tabsizer[section].GetSize()
  1937. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1938. # TODO: be less arbitrary with these 600
  1939. self.panelMinHeight = 100
  1940. self.constrained_size = (
  1941. min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1942. for section in sections:
  1943. tab[section].SetMinSize(
  1944. (self.constrained_size[0], self.panelMinHeight))
  1945. # add pages to notebook
  1946. imageList = wx.ImageList(16, 16)
  1947. self.notebook.AssignImageList(imageList)
  1948. for section in sections:
  1949. self.notebook.AddPage(
  1950. page=tab[section],
  1951. text=section, name=section)
  1952. index = self.AddBitmapToImageList(section, imageList)
  1953. if index >= 0:
  1954. self.notebook.SetPageImage(section, index)
  1955. # are we running from command line?
  1956. # add 'command output' tab regardless standalone dialog
  1957. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1958. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1959. from gui_core.goutput import GConsoleWindow
  1960. self._gconsole = GConsole(
  1961. guiparent=self.notebook, giface=self._giface)
  1962. self.goutput = GConsoleWindow(
  1963. parent=self.notebook,
  1964. gconsole=self._gconsole,
  1965. margin=False)
  1966. self._gconsole.Bind(
  1967. EVT_CMD_RUN, lambda event: self._switchPageHandler(
  1968. event=event, notification=Notification.MAKE_VISIBLE))
  1969. self._gconsole.Bind(
  1970. EVT_CMD_DONE, lambda event: self._switchPageHandler(
  1971. event=event, notification=Notification.RAISE_WINDOW))
  1972. self.outpage = self.notebook.AddPage(
  1973. page=self.goutput, text=_("Command output"), name='output')
  1974. else:
  1975. self.goutput = None
  1976. self._gconsole = None
  1977. self.manualTab = HelpPanel(
  1978. parent=self.notebook,
  1979. command=self.task.get_name())
  1980. if not self.manualTab.GetFile():
  1981. self.manualTab.Hide()
  1982. else:
  1983. self.notebook.AddPage(
  1984. page=self.manualTab,
  1985. text=_("Manual"),
  1986. name='manual')
  1987. index = self.AddBitmapToImageList(
  1988. section='manual', imageList=imageList)
  1989. if index >= 0:
  1990. self.notebook.SetPageImage('manual', index)
  1991. if self.manualTab.IsLoaded():
  1992. self.manualTab.SetMinSize(
  1993. (self.constrained_size[0], self.panelMinHeight))
  1994. self.notebook.SetSelection(0)
  1995. panelsizer.Add(self.notebook, proportion=1, flag=wx.EXPAND)
  1996. self.SetSizer(panelsizer)
  1997. panelsizer.Fit(self.notebook)
  1998. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1999. def _getValue(self, p):
  2000. """Get value or default value of given parameter
  2001. :param p: parameter directory
  2002. """
  2003. if p.get('value', '') != '':
  2004. return p['value']
  2005. return p.get('default', '')
  2006. def OnFileLoad(self, event):
  2007. """Load file to interactive input"""
  2008. me = event.GetId()
  2009. win = dict()
  2010. for p in self.task.params:
  2011. if 'wxId' in p and me in p['wxId']:
  2012. win['file'] = self.FindWindowById(p['wxId'][0])
  2013. win['text'] = self.FindWindowById(p['wxId'][1])
  2014. break
  2015. if not win:
  2016. return
  2017. path = win['file'].GetValue()
  2018. if not path:
  2019. gcmd.GMessage(parent=self,
  2020. message=_("Nothing to load."))
  2021. return
  2022. data = ''
  2023. try:
  2024. f = open(path, "r")
  2025. except IOError as e:
  2026. gcmd.GError(parent=self, showTraceback=False,
  2027. message=_("Unable to load file.\n\nReason: %s") % e)
  2028. return
  2029. try:
  2030. data = f.read()
  2031. finally:
  2032. f.close()
  2033. win['text'].SetValue(data)
  2034. def OnFileSave(self, event):
  2035. """Save interactive input to the file"""
  2036. wId = event.GetId()
  2037. win = {}
  2038. for p in self.task.params:
  2039. if wId in p.get('wxId', []):
  2040. win['file'] = self.FindWindowById(p['wxId'][0])
  2041. win['text'] = self.FindWindowById(p['wxId'][1])
  2042. break
  2043. if not win:
  2044. return
  2045. text = win['text'].GetValue()
  2046. if not text:
  2047. gcmd.GMessage(parent=self,
  2048. message=_("Nothing to save."))
  2049. return
  2050. dlg = wx.FileDialog(parent=self,
  2051. message=_("Save input as..."),
  2052. defaultDir=os.getcwd(),
  2053. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  2054. if dlg.ShowModal() == wx.ID_OK:
  2055. path = dlg.GetPath()
  2056. enc = locale.getdefaultlocale()[1]
  2057. f = codecs.open(path, encoding=enc, mode='w', errors='replace')
  2058. try:
  2059. f.write(text + os.linesep)
  2060. finally:
  2061. f.close()
  2062. win['file'].SetValue(path)
  2063. dlg.Destroy()
  2064. def OnFileText(self, event):
  2065. """File input interactively entered"""
  2066. text = event.GetString()
  2067. p = self.task.get_param(
  2068. value=event.GetId(),
  2069. element='wxId',
  2070. raiseError=False)
  2071. if not p:
  2072. return # should not happen
  2073. win = self.FindWindowById(p['wxId'][0])
  2074. if text:
  2075. filename = win.GetValue()
  2076. if not filename or filename == p[
  2077. 'default']: # m.proj has - as default
  2078. filename = grass.tempfile()
  2079. win.SetValue(filename)
  2080. enc = locale.getdefaultlocale()[1]
  2081. f = codecs.open(filename, encoding=enc, mode='w', errors='replace')
  2082. try:
  2083. f.write(text)
  2084. if text[-1] != os.linesep:
  2085. f.write(os.linesep)
  2086. finally:
  2087. f.close()
  2088. else:
  2089. win.SetValue('')
  2090. def OnVectorFormat(self, event):
  2091. """Change vector format (native / ogr).
  2092. Currently unused.
  2093. """
  2094. sel = event.GetSelection()
  2095. idEvent = event.GetId()
  2096. p = self.task.get_param(
  2097. value=idEvent,
  2098. element='wxId',
  2099. raiseError=False)
  2100. if not p:
  2101. return # should not happen
  2102. # detect windows
  2103. winNative = None
  2104. winOgr = None
  2105. for id in p['wxId']:
  2106. if id == idEvent:
  2107. continue
  2108. name = self.FindWindowById(id).GetName()
  2109. if name == 'Select':
  2110. # fix the mystery (also in nviz_tools.py)
  2111. winNative = self.FindWindowById(id + 1)
  2112. elif name == 'OgrSelect':
  2113. winOgr = self.FindWindowById(id)
  2114. # enable / disable widgets & update values
  2115. rbox = self.FindWindowByName('VectorFormat')
  2116. self.hsizer.Remove(rbox)
  2117. if sel == 0: # -> native
  2118. winOgr.Hide()
  2119. self.hsizer.Remove(winOgr)
  2120. self.hsizer.Add(
  2121. winNative,
  2122. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  2123. border=5)
  2124. winNative.Show()
  2125. p['value'] = winNative.GetValue()
  2126. elif sel == 1: # -> OGR
  2127. sizer = wx.BoxSizer(wx.VERTICAL)
  2128. winNative.Hide()
  2129. self.hsizer.Remove(winNative)
  2130. sizer.Add(winOgr)
  2131. winOgr.Show()
  2132. p['value'] = winOgr.GetDsn()
  2133. self.hsizer.Add(
  2134. sizer,
  2135. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  2136. border=5)
  2137. self.hsizer.Add(rbox,
  2138. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  2139. wx.RIGHT | wx.ALIGN_TOP,
  2140. border=5)
  2141. self.hsizer.Layout()
  2142. self.Layout()
  2143. self.OnUpdateValues()
  2144. self.OnUpdateSelection(event)
  2145. def OnUpdateDialog(self, event):
  2146. for fn, kwargs in event.data.iteritems():
  2147. fn(**kwargs)
  2148. self.parent.updateValuesHook()
  2149. def OnVerbosity(self, event):
  2150. """Verbosity level changed"""
  2151. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  2152. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  2153. if event.IsChecked():
  2154. if event.GetId() == verbose.GetId():
  2155. if quiet.IsChecked():
  2156. quiet.SetValue(False)
  2157. self.task.get_flag('quiet')['value'] = False
  2158. else:
  2159. if verbose.IsChecked():
  2160. verbose.SetValue(False)
  2161. self.task.get_flag('verbose')['value'] = False
  2162. event.Skip()
  2163. def OnPageChange(self, event):
  2164. if not event:
  2165. sel = self.notebook.GetSelection()
  2166. else:
  2167. sel = event.GetSelection()
  2168. idx = self.notebook.GetPageIndexByName('manual')
  2169. if idx > -1 and sel == idx:
  2170. # calling LoadPage() is strangely time-consuming (only first call)
  2171. # FIXME: move to helpPage.__init__()
  2172. if not self.manualTab.IsLoaded():
  2173. wx.Yield()
  2174. self.manualTab.LoadPage()
  2175. self.Layout()
  2176. if event:
  2177. # skip is needed for wx.Notebook on Windows
  2178. event.Skip()
  2179. # this is needed for dialogs launched from layer manager
  2180. # event is somehow propagated?
  2181. event.StopPropagation()
  2182. def _switchPageHandler(self, event, notification):
  2183. self._switchPage(notification=notification)
  2184. event.Skip()
  2185. def _switchPage(self, notification):
  2186. """Manages @c 'output' notebook page according to event notification."""
  2187. if notification == Notification.HIGHLIGHT:
  2188. self.notebook.HighlightPageByName('output')
  2189. if notification == Notification.MAKE_VISIBLE:
  2190. self.notebook.SetSelectionByName('output')
  2191. if notification == Notification.RAISE_WINDOW:
  2192. self.notebook.SetSelectionByName('output')
  2193. self.SetFocus()
  2194. self.Raise()
  2195. def OnColorChange(self, event):
  2196. myId = event.GetId()
  2197. for p in self.task.params:
  2198. if 'wxId' in p and myId in p['wxId']:
  2199. multiple = p['wxId'][1] is not None # multiple colors
  2200. hasTansp = p['wxId'][2] is not None
  2201. if multiple:
  2202. # selected color is added at the end of textCtrl
  2203. colorchooser = wx.FindWindowById(p['wxId'][0])
  2204. new_color = colorchooser.GetValue()[:]
  2205. new_label = utils.rgb2str.get(
  2206. new_color, ':'.join(map(str, new_color)))
  2207. textCtrl = wx.FindWindowById(p['wxId'][1])
  2208. val = textCtrl.GetValue()
  2209. sep = ','
  2210. if val and val[-1] != sep:
  2211. val += sep
  2212. val += new_label
  2213. textCtrl.SetValue(val)
  2214. p['value'] = val
  2215. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  2216. p['value'] = 'none'
  2217. else:
  2218. colorchooser = wx.FindWindowById(p['wxId'][0])
  2219. new_color = colorchooser.GetValue()[:]
  2220. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  2221. # under wx2.8.1
  2222. new_label = utils.rgb2str.get(
  2223. new_color, ':'.join(map(str, new_color)))
  2224. colorchooser.SetLabel(new_label)
  2225. colorchooser.SetColour(new_color)
  2226. colorchooser.Refresh()
  2227. p['value'] = colorchooser.GetLabel()
  2228. self.OnUpdateValues()
  2229. def OnUpdateValues(self, event=None):
  2230. """If we were part of a richer interface, report back the
  2231. current command being built.
  2232. This method should be set by the parent of this panel if
  2233. needed. It's a hook, actually. Beware of what is 'self' in
  2234. the method def, though. It will be called with no arguments.
  2235. """
  2236. pass
  2237. def OnCheckBoxMulti(self, event):
  2238. """Fill the values as a ','-separated string according to
  2239. current status of the checkboxes.
  2240. """
  2241. me = event.GetId()
  2242. theParam = None
  2243. for p in self.task.params:
  2244. if 'wxId' in p and me in p['wxId']:
  2245. theParam = p
  2246. myIndex = p['wxId'].index(me)
  2247. # Unpack current value list
  2248. currentValues = {}
  2249. for isThere in theParam.get('value', '').split(','):
  2250. currentValues[isThere] = 1
  2251. theValue = theParam['values'][myIndex]
  2252. if event.Checked():
  2253. currentValues[theValue] = 1
  2254. else:
  2255. del currentValues[theValue]
  2256. # Keep the original order, so that some defaults may be recovered
  2257. currentValueList = []
  2258. for v in theParam['values']:
  2259. if v in currentValues:
  2260. currentValueList.append(v)
  2261. # Pack it back
  2262. theParam['value'] = ','.join(currentValueList)
  2263. self.OnUpdateValues()
  2264. event.Skip()
  2265. def OnSetValue(self, event):
  2266. """Retrieve the widget value and set the task value field
  2267. accordingly.
  2268. Use for widgets that have a proper GetValue() method, i.e. not
  2269. for selectors.
  2270. """
  2271. myId = event.GetId()
  2272. me = wx.FindWindowById(myId)
  2273. name = me.GetName()
  2274. found = False
  2275. for porf in self.task.params + self.task.flags:
  2276. if 'wxId' not in porf:
  2277. continue
  2278. if myId in porf['wxId']:
  2279. found = True
  2280. break
  2281. if not found:
  2282. return
  2283. if name == 'GdalSelect':
  2284. porf['value'] = event.dsn
  2285. elif name == 'ModelParam':
  2286. porf['parameterized'] = me.IsChecked()
  2287. elif name == 'GdalSelectDataSource':
  2288. win = self.FindWindowById(porf['wxId'][0])
  2289. porf['value'] = win.GetDsn()
  2290. pLayer = self.task.get_param(
  2291. 'layer', element='name', raiseError=False)
  2292. if pLayer:
  2293. pLayer['value'] = ''
  2294. else:
  2295. if isinstance(me, SpinCtrl):
  2296. porf['value'] = str(me.GetValue())
  2297. elif isinstance(me, wx.ComboBox):
  2298. porf['value'] = me.GetValue()
  2299. elif isinstance(me, wx.Choice):
  2300. porf['value'] = me.GetStringSelection()
  2301. else:
  2302. porf['value'] = me.GetValue()
  2303. self.OnUpdateValues(event)
  2304. event.Skip()
  2305. def OnSetSymbol(self, event):
  2306. """Shows dialog for symbol selection"""
  2307. myId = event.GetId()
  2308. for p in self.task.params:
  2309. if 'wxId' in p and myId in p['wxId']:
  2310. from gui_core.dialogs import SymbolDialog
  2311. dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
  2312. currentSymbol=p['value'])
  2313. if dlg.ShowModal() == wx.ID_OK:
  2314. img = dlg.GetSelectedSymbolPath()
  2315. p['value'] = dlg.GetSelectedSymbolName()
  2316. bitmapButton = wx.FindWindowById(p['wxId'][0])
  2317. label = wx.FindWindowById(p['wxId'][1])
  2318. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  2319. label.SetLabel(p['value'])
  2320. self.OnUpdateValues(event)
  2321. dlg.Destroy()
  2322. def OnTimelineTool(self, event):
  2323. """Show Timeline Tool with dataset(s) from gselect.
  2324. .. todo::
  2325. update from gselect automatically
  2326. """
  2327. myId = event.GetId()
  2328. for p in self.task.params:
  2329. if 'wxId' in p and myId in p['wxId']:
  2330. select = self.FindWindowById(p['wxId'][0])
  2331. if not select.GetValue():
  2332. gcmd.GMessage(parent=self, message=_("No dataset given."))
  2333. return
  2334. datasets = select.GetValue().split(',')
  2335. from timeline import frame
  2336. frame.run(parent=self, datasets=datasets)
  2337. def OnSelectFont(self, event):
  2338. """Select font using font dialog"""
  2339. myId = event.GetId()
  2340. for p in self.task.params:
  2341. if 'wxId' in p and myId in p['wxId']:
  2342. from gui_core.dialogs import DefaultFontDialog
  2343. dlg = DefaultFontDialog(parent=self,
  2344. title=_('Select font'),
  2345. style=wx.DEFAULT_DIALOG_STYLE,
  2346. type='font')
  2347. if dlg.ShowModal() == wx.ID_OK:
  2348. if dlg.font:
  2349. p['value'] = dlg.font
  2350. self.FindWindowById(p['wxId'][1]).SetValue(dlg.font)
  2351. self.OnUpdateValues(event)
  2352. dlg.Destroy()
  2353. def OnUpdateSelection(self, event):
  2354. """Update dialog (layers, tables, columns, etc.)
  2355. """
  2356. if not hasattr(self.parent, "updateThread"):
  2357. if event:
  2358. event.Skip()
  2359. return
  2360. if event:
  2361. self.parent.updateThread.Update(UpdateDialog,
  2362. self,
  2363. event,
  2364. event.GetId(),
  2365. self.task)
  2366. else:
  2367. self.parent.updateThread.Update(UpdateDialog,
  2368. self,
  2369. None,
  2370. None,
  2371. self.task)
  2372. def createCmd(self, ignoreErrors=False, ignoreRequired=False):
  2373. """Produce a command line string (list) or feeding into GRASS.
  2374. :param ignoreErrors: True then it will return whatever has been
  2375. built so far, even though it would not be
  2376. a correct command for GRASS
  2377. """
  2378. try:
  2379. cmd = self.task.get_cmd(ignoreErrors=ignoreErrors,
  2380. ignoreRequired=ignoreRequired)
  2381. except ValueError as err:
  2382. dlg = wx.MessageDialog(parent=self,
  2383. message=gcmd.DecodeString(str(err)),
  2384. caption=_("Error in %s") % self.task.name,
  2385. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  2386. dlg.ShowModal()
  2387. dlg.Destroy()
  2388. cmd = None
  2389. return cmd
  2390. def OnSize(self, event):
  2391. width = event.GetSize()[0]
  2392. fontsize = self.GetFont().GetPointSize()
  2393. text_width = max(width / (fontsize - 3), 70)
  2394. for id in self.label_id:
  2395. win = self.FindWindowById(id)
  2396. label = win.GetLabel()
  2397. label_new = '\n'.join(textwrap.wrap(label, text_width))
  2398. win.SetLabel(label_new)
  2399. event.Skip()
  2400. def AddBitmapToImageList(self, section, imageList):
  2401. iconTheme = UserSettings.Get(
  2402. group='appearance',
  2403. key='iconTheme',
  2404. subkey='type')
  2405. iconSectionDict = {
  2406. 'manual': os.path.join(
  2407. globalvar.ICONDIR,
  2408. iconTheme,
  2409. 'help.png')}
  2410. if section in iconSectionDict.keys():
  2411. image = wx.Image(
  2412. iconSectionDict[section]).Scale(
  2413. 16, 16, wx.IMAGE_QUALITY_HIGH)
  2414. idx = imageList.Add(BitmapFromImage(image))
  2415. return idx
  2416. return -1
  2417. class GUI:
  2418. def __init__(self, parent=None, giface=None, show=True, modal=False,
  2419. centreOnParent=False, checkError=False):
  2420. """Parses GRASS commands when module is imported and used from
  2421. Layer Manager.
  2422. """
  2423. self.parent = parent
  2424. self.show = show
  2425. self.modal = modal
  2426. self._giface = giface
  2427. self.centreOnParent = centreOnParent
  2428. self.checkError = checkError
  2429. self.grass_task = None
  2430. self.cmd = list()
  2431. global _blackList
  2432. if self.parent:
  2433. _blackList['enabled'] = True
  2434. else:
  2435. _blackList['enabled'] = False
  2436. def GetCmd(self):
  2437. """Get validated command"""
  2438. return self.cmd
  2439. def ParseCommand(self, cmd, completed=None):
  2440. """Parse command
  2441. Note: cmd is given as list
  2442. If command is given with options, return validated cmd list:
  2443. - add key name for first parameter if not given
  2444. - change mapname to mapname@mapset
  2445. """
  2446. dcmd_params = {}
  2447. if completed is None:
  2448. get_dcmd = None
  2449. layer = None
  2450. dcmd_params = None
  2451. else:
  2452. get_dcmd = completed[0]
  2453. layer = completed[1]
  2454. if completed[2]:
  2455. dcmd_params.update(completed[2])
  2456. # parse the interface decription
  2457. try:
  2458. global _blackList
  2459. self.grass_task = gtask.parse_interface(cmd[0],
  2460. blackList=_blackList)
  2461. except (grass.ScriptError, ValueError) as e:
  2462. raise gcmd.GException(e.value)
  2463. # if layer parameters previously set, re-insert them into dialog
  2464. if completed is not None:
  2465. if 'params' in dcmd_params:
  2466. self.grass_task.params = dcmd_params['params']
  2467. if 'flags' in dcmd_params:
  2468. self.grass_task.flags = dcmd_params['flags']
  2469. err = list()
  2470. # update parameters if needed && validate command
  2471. if len(cmd) > 1:
  2472. i = 0
  2473. cmd_validated = [cmd[0]]
  2474. for option in cmd[1:]:
  2475. if option[0] == '-': # flag
  2476. if len(option) == 1: # catch typo like 'g.proj - w'
  2477. raise gcmd.GException(
  2478. _("Unable to parse command '%s'") %
  2479. ' '.join(cmd))
  2480. if option[1] == '-':
  2481. self.grass_task.set_flag(option[2:], True)
  2482. else:
  2483. self.grass_task.set_flag(option[1], True)
  2484. cmd_validated.append(option)
  2485. else: # parameter
  2486. try:
  2487. key, value = option.split('=', 1)
  2488. except ValueError:
  2489. if self.grass_task.firstParam:
  2490. if i == 0: # add key name of first parameter if not given
  2491. key = self.grass_task.firstParam
  2492. value = option
  2493. else:
  2494. raise gcmd.GException(
  2495. _("Unable to parse command '%s'") % ' '.join(cmd))
  2496. else:
  2497. continue
  2498. task = self.grass_task.get_param(key, raiseError=False)
  2499. if not task:
  2500. err.append(
  2501. _("%(cmd)s: parameter '%(key)s' not available") % {
  2502. 'cmd': cmd[0],
  2503. 'key': key})
  2504. continue
  2505. self.grass_task.set_param(key, value)
  2506. cmd_validated.append(key + '=' + value)
  2507. i += 1
  2508. # update original command list
  2509. cmd = cmd_validated
  2510. if self.show is not None:
  2511. self.mf = TaskFrame(parent=self.parent, giface=self._giface,
  2512. task_description=self.grass_task,
  2513. get_dcmd=get_dcmd, layer=layer)
  2514. else:
  2515. self.mf = None
  2516. if get_dcmd is not None:
  2517. # update only propwin reference
  2518. get_dcmd(dcmd=None, layer=layer, params=None,
  2519. propwin=self.mf)
  2520. if self.show is not None:
  2521. self.mf.notebookpanel.OnUpdateSelection(None)
  2522. if self.show is True:
  2523. if self.parent and self.centreOnParent:
  2524. self.mf.CentreOnParent()
  2525. else:
  2526. self.mf.CenterOnScreen()
  2527. self.mf.Show(self.show)
  2528. self.mf.MakeModal(self.modal)
  2529. else:
  2530. self.mf.OnApply(None)
  2531. self.cmd = cmd
  2532. if self.checkError:
  2533. return self.grass_task, err
  2534. else:
  2535. return self.grass_task
  2536. def GetCommandInputMapParamKey(self, cmd):
  2537. """Get parameter key for input raster/vector map
  2538. :param cmd: module name
  2539. :return: parameter key
  2540. :return: None on failure
  2541. """
  2542. # parse the interface decription
  2543. if not self.grass_task:
  2544. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2545. self.grass_task = gtask.processTask(tree).get_task()
  2546. for p in self.grass_task.params:
  2547. if p.get('name', '') in ('input', 'map'):
  2548. age = p.get('age', '')
  2549. prompt = p.get('prompt', '')
  2550. element = p.get('element', '')
  2551. if age == 'old' and \
  2552. element in ('cell', 'grid3', 'vector') and \
  2553. prompt in ('raster', 'raster_3d', 'vector'):
  2554. return p.get('name', None)
  2555. return None
  2556. class GrassGUIApp(wx.App):
  2557. """Stand-alone GRASS command GUI
  2558. """
  2559. def __init__(self, grass_task):
  2560. self.grass_task = grass_task
  2561. wx.App.__init__(self, False)
  2562. def OnInit(self):
  2563. msg = self.grass_task.get_error_msg()
  2564. if msg:
  2565. gcmd.GError(
  2566. msg +
  2567. '\n\n' +
  2568. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2569. return True
  2570. self.mf = TaskFrame(
  2571. parent=None,
  2572. giface=None,
  2573. task_description=self.grass_task)
  2574. self.mf.CentreOnScreen()
  2575. self.mf.Show(True)
  2576. self.SetTopWindow(self.mf)
  2577. return True
  2578. USAGE_MESSAGE = """Usage:
  2579. {name} <grass module>
  2580. {name} <full path to file>
  2581. python {name} <grass module>
  2582. Test:
  2583. python {name} test
  2584. python {name} g.region
  2585. python {name} "g.region -p"
  2586. python {name} temporal/t.list/t.list.py"""
  2587. if __name__ == "__main__":
  2588. if len(sys.argv) == 1:
  2589. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2590. if sys.argv[1] != 'test':
  2591. q = wx.LogNull()
  2592. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2593. cmd = utils.split(sys.argv[1])
  2594. task = gtask.grassTask(cmd[0])
  2595. task.set_options(cmd[1:])
  2596. Debug.msg(1, "forms.py opening form for: %s" %
  2597. task.get_cmd(ignoreErrors=True, ignoreRequired=True))
  2598. app = GrassGUIApp(task)
  2599. app.MainLoop()
  2600. else: # Test
  2601. # Test grassTask from within a GRASS session
  2602. if os.getenv("GISBASE") is not None:
  2603. task = gtask.grassTask("d.vect")
  2604. task.get_param('map')['value'] = "map_name"
  2605. task.get_flag('i')['value'] = True
  2606. task.get_param('layer')['value'] = 1
  2607. task.get_param('label_bcolor')['value'] = "red"
  2608. # the default parameter display is added automatically
  2609. assert ' '.join(
  2610. task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
  2611. print "Creation of task successful"
  2612. # Test interface building with handmade grassTask,
  2613. # possibly outside of a GRASS session.
  2614. print "Now creating a module dialog (task frame)"
  2615. task = gtask.grassTask()
  2616. task.name = "TestTask"
  2617. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2618. task.keywords = ["grass", "test", "task"]
  2619. task.params = [
  2620. {
  2621. "name": "text",
  2622. "description": "Descriptions go into tooltips if labels are present, like this one",
  2623. "label": "Enter some text",
  2624. "key_desc": ["value"],
  2625. "values_desc": []
  2626. }, {
  2627. "name": "hidden_text",
  2628. "description": "This text should not appear in the form",
  2629. "hidden": True,
  2630. "key_desc": ["value"],
  2631. "values_desc": []
  2632. }, {
  2633. "name": "text_default",
  2634. "description": "Enter text to override the default",
  2635. "default": "default text",
  2636. "key_desc": ["value"],
  2637. "values_desc": []
  2638. }, {
  2639. "name": "text_prefilled",
  2640. "description": "You should see a friendly welcome message here",
  2641. "value": "hello, world",
  2642. "key_desc": ["value"],
  2643. "values_desc": []
  2644. }, {
  2645. "name": "plain_color",
  2646. "description": "This is a plain color, and it is a compulsory parameter",
  2647. "required": False,
  2648. "gisprompt": True,
  2649. "prompt": "color",
  2650. "key_desc": ["value"],
  2651. "values_desc": []
  2652. }, {
  2653. "name": "transparent_color",
  2654. "description": "This color becomes transparent when set to none",
  2655. "guisection": "tab",
  2656. "gisprompt": True,
  2657. "prompt": "color",
  2658. "key_desc": ["value"],
  2659. "values_desc": []
  2660. }, {
  2661. "name": "multi",
  2662. "description": "A multiple selection",
  2663. 'default': u'red,green,blue',
  2664. 'gisprompt': False,
  2665. 'guisection': 'tab',
  2666. 'multiple': u'yes',
  2667. 'type': u'string',
  2668. 'value': '',
  2669. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2670. "key_desc": ["value"],
  2671. "values_desc": []
  2672. }, {
  2673. "name": "single",
  2674. "description": "A single multiple-choice selection",
  2675. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2676. "guisection": "tab",
  2677. "key_desc": ["value"],
  2678. "values_desc": []
  2679. }, {
  2680. "name": "large_multi",
  2681. "description": "A large multiple selection",
  2682. "gisprompt": False,
  2683. "multiple": "yes",
  2684. # values must be an array of strings
  2685. "values": utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
  2686. "key_desc": ["value"],
  2687. "values_desc": []
  2688. }, {
  2689. "name": "a_file",
  2690. "description": "A file selector",
  2691. "gisprompt": True,
  2692. "element": "file",
  2693. "key_desc": ["value"],
  2694. "values_desc": []
  2695. }
  2696. ]
  2697. task.flags = [{"name": "a",
  2698. "description": "Some flag, will appear in Main since it is required",
  2699. "required": True,
  2700. "value": False,
  2701. "suppress_required": False},
  2702. {"name": "b",
  2703. "description": "pre-filled flag, will appear in options since it is not required",
  2704. "value": True,
  2705. "suppress_required": False},
  2706. {"name": "hidden_flag",
  2707. "description": "hidden flag, should not be changeable",
  2708. "hidden": "yes",
  2709. "value": True,
  2710. "suppress_required": False}]
  2711. q = wx.LogNull()
  2712. GrassGUIApp(task).MainLoop()