forms.py 123 KB

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