forms.py 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041
  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'] \
  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. if p.get('multiple', False) or \
  1097. p.get('type', 'string') == 'string' or \
  1098. len(p.get('key_desc', [])) > 1:
  1099. win = wx.TextCtrl(
  1100. parent=which_panel, value=p.get(
  1101. 'default', ''))
  1102. value = self._getValue(p)
  1103. if value:
  1104. # parameter previously set
  1105. win.SetValue(str(value))
  1106. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1107. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1108. elif p.get('type', '') == 'integer':
  1109. minValue = -1e9
  1110. maxValue = 1e9
  1111. value = self._getValue(p)
  1112. win = wx.SpinCtrl(
  1113. parent=which_panel,
  1114. value=p.get(
  1115. 'default',
  1116. ''),
  1117. size=globalvar.DIALOG_SPIN_SIZE,
  1118. min=minValue,
  1119. max=maxValue)
  1120. if value:
  1121. win.SetValue(int(value)) # parameter previously set
  1122. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1123. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1124. else: # float
  1125. win = wx.TextCtrl(
  1126. parent=which_panel, value=p.get(
  1127. 'default', ''), validator=FloatValidator())
  1128. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1129. value = self._getValue(p)
  1130. if value:
  1131. win.SetValue(str(value)) # parameter previously set
  1132. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1133. which_sizer.Add(item=win, proportion=0,
  1134. flag=style, border=5)
  1135. p['wxId'] = [win.GetId()]
  1136. #
  1137. # element selection tree combobox (maps, icons, regions, etc.)
  1138. #
  1139. if p.get('gisprompt', False):
  1140. title_txt.SetLabel(title + ':')
  1141. # GIS element entry
  1142. if p.get('prompt', '') not in ('color',
  1143. 'cat',
  1144. 'cats',
  1145. 'subgroup',
  1146. 'sigfile',
  1147. 'separator',
  1148. 'dbdriver',
  1149. 'dbname',
  1150. 'dbtable',
  1151. 'dbcolumn',
  1152. 'layer',
  1153. 'location',
  1154. 'mapset',
  1155. 'dbase',
  1156. 'coords',
  1157. 'file',
  1158. 'dir',
  1159. 'colortable',
  1160. 'barscale',
  1161. 'northarrow',
  1162. 'datasource',
  1163. 'datasource_layer'):
  1164. multiple = p.get('multiple', False)
  1165. if p.get('age', '') == 'new':
  1166. mapsets = [grass.gisenv()['MAPSET'], ]
  1167. else:
  1168. mapsets = None
  1169. if self.task.name in ('r.proj', 'v.proj') \
  1170. and p.get('name', '') == 'input':
  1171. selection = gselect.ProjSelect(
  1172. parent=which_panel, isRaster=self.task.name == 'r.proj')
  1173. p['wxId'] = [selection.GetId(), ]
  1174. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1175. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1176. else:
  1177. elem = p.get('element', None)
  1178. # hack for t.* modules
  1179. if elem in ('stds', 'map'):
  1180. orig_elem = elem
  1181. type_param = self.task.get_param(
  1182. 'type', element='name', raiseError=False)
  1183. if type_param:
  1184. elem = type_param.get('default', None)
  1185. # for t.(un)register:
  1186. maps_param = self.task.get_param(
  1187. 'maps', element='name', raiseError=False)
  1188. if maps_param and orig_elem == 'stds':
  1189. element_dict = {
  1190. 'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  1191. elem = element_dict[
  1192. type_param.get('default')]
  1193. extraItems = None
  1194. if self._giface:
  1195. if hasattr(self._giface, "_model"):
  1196. extraItems = {
  1197. _('Graphical Modeler'): self._giface.GetLayerList(
  1198. p.get('prompt'))}
  1199. else:
  1200. layers = self._giface.GetLayerList()
  1201. if len(layers) > 0:
  1202. mapList = []
  1203. extraItems = {_('Map Display'): mapList}
  1204. for layer in layers:
  1205. if layer.type != p.get('prompt'):
  1206. continue
  1207. mapList.append(str(layer))
  1208. selection = gselect.Select(
  1209. parent=which_panel, id=wx.ID_ANY,
  1210. size=globalvar.DIALOG_GSELECT_SIZE, type=elem,
  1211. multiple=multiple, nmaps=len(
  1212. p.get('key_desc', [])),
  1213. mapsets=mapsets, fullyQualified=p.get(
  1214. 'age', 'old') == 'old', extraItems=extraItems)
  1215. value = self._getValue(p)
  1216. if value:
  1217. selection.SetValue(value)
  1218. formatSelector = True
  1219. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1220. # we target the textctl here
  1221. textWin = selection.GetTextCtrl()
  1222. if globalvar.CheckWxVersion([3]):
  1223. p['wxId'] = [selection.GetId(), ]
  1224. else:
  1225. p['wxId'] = [textWin.GetId(), ]
  1226. if prompt != 'vector':
  1227. self.FindWindowById(
  1228. p['wxId'][0]).Bind(
  1229. wx.EVT_TEXT, self.OnSetValue)
  1230. if prompt == 'vector':
  1231. win = self.FindWindowById(p['wxId'][0])
  1232. # handlers should be bound in this order
  1233. # OnUpdateSelection depends on calling OnSetValue first
  1234. # which is bad
  1235. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1236. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1237. # if formatSelector and p.get('age', 'old') == 'old':
  1238. # # OGR supported (read-only)
  1239. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1240. # self.hsizer.Add(item = selection,
  1241. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1242. # border = 5)
  1243. # # format (native / ogr)
  1244. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1245. # label = " %s " % _("Format"),
  1246. # style = wx.RA_SPECIFY_ROWS,
  1247. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1248. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1249. # rbox.SetSelection(1)
  1250. # rbox.SetName('VectorFormat')
  1251. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1252. # self.hsizer.Add(item = rbox,
  1253. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1254. # wx.RIGHT | wx.ALIGN_TOP,
  1255. # border = 5)
  1256. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1257. # default = 'dir',
  1258. # exclude = ['file'])
  1259. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1260. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1261. # ogrSelection.SetName('OgrSelect')
  1262. # ogrSelection.Hide()
  1263. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1264. # p['wxId'].append(rbox.GetId())
  1265. # p['wxId'].append(ogrSelection.GetId())
  1266. # for win in ogrSelection.GetDsnWin():
  1267. # p['wxId'].append(win.GetId())
  1268. # else:
  1269. which_sizer.Add(
  1270. item=selection,
  1271. proportion=0,
  1272. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1273. border=5)
  1274. elif prompt == 'group':
  1275. win = self.FindWindowById(p['wxId'][0])
  1276. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1277. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1278. which_sizer.Add(
  1279. item=selection,
  1280. proportion=0,
  1281. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1282. border=5)
  1283. else:
  1284. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1285. showButton = True
  1286. try:
  1287. # if matplotlib is there
  1288. from timeline import frame
  1289. showButton = True
  1290. except ImportError:
  1291. showButton = False
  1292. else:
  1293. showButton = False
  1294. if showButton:
  1295. iconTheme = UserSettings.Get(
  1296. group='appearance', key='iconTheme', subkey='type')
  1297. bitmap = wx.Bitmap(
  1298. os.path.join(
  1299. globalvar.ICONDIR, iconTheme,
  1300. 'map-info.png'))
  1301. bb = wx.BitmapButton(
  1302. parent=which_panel, bitmap=bitmap)
  1303. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1304. bb.SetToolTipString(
  1305. _("Show graphical representation of temporal extent of dataset(s) ."))
  1306. p['wxId'].append(bb.GetId())
  1307. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1308. hSizer.Add(
  1309. item=selection,
  1310. proportion=0,
  1311. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1312. border=5)
  1313. hSizer.Add(
  1314. item=bb,
  1315. proportion=0,
  1316. flag=wx.EXPAND | wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1317. border=5)
  1318. which_sizer.Add(hSizer)
  1319. else:
  1320. which_sizer.Add(
  1321. item=selection,
  1322. proportion=0,
  1323. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1324. border=5)
  1325. # subgroup
  1326. elif prompt == 'subgroup':
  1327. selection = gselect.SubGroupSelect(parent=which_panel)
  1328. p['wxId'] = [selection.GetId()]
  1329. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1330. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1331. which_sizer.Add(
  1332. item=selection,
  1333. proportion=0,
  1334. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1335. border=5)
  1336. # sigrature file
  1337. elif prompt == 'sigfile':
  1338. selection = gselect.SignatureSelect(
  1339. parent=which_panel, element=p.get('element', 'sig'))
  1340. p['wxId'] = [selection.GetId()]
  1341. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1342. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1343. which_sizer.Add(
  1344. item=selection,
  1345. proportion=0,
  1346. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1347. border=5)
  1348. # separator
  1349. elif prompt == 'separator':
  1350. win = gselect.SeparatorSelect(parent=which_panel)
  1351. value = self._getValue(p)
  1352. win.SetValue(value)
  1353. p['wxId'] = [win.GetId()]
  1354. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1355. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1356. which_sizer.Add(
  1357. item=win,
  1358. proportion=0,
  1359. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1360. border=5)
  1361. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1362. elif prompt in ('dbdriver',
  1363. 'dbname',
  1364. 'dbtable',
  1365. 'dbcolumn',
  1366. 'layer',
  1367. 'location',
  1368. 'mapset',
  1369. 'dbase'):
  1370. if p.get('multiple', 'no') == 'yes':
  1371. win = wx.TextCtrl(
  1372. parent=which_panel, value=p.get(
  1373. 'default', ''), size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1374. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1375. else:
  1376. value = self._getValue(p)
  1377. if prompt == 'layer':
  1378. if p.get('element', 'layer') == 'layer_all':
  1379. all = True
  1380. else:
  1381. all = False
  1382. if p.get('age', 'old') == 'old':
  1383. win = gselect.LayerSelect(parent=which_panel,
  1384. all=all,
  1385. default=p['default'])
  1386. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1387. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1388. win.SetValue(
  1389. str(value)) # default or previously set value
  1390. else:
  1391. win = wx.SpinCtrl(
  1392. parent=which_panel, id=wx.ID_ANY, min=1,
  1393. max=100, initial=int(p['default']))
  1394. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1395. win.SetValue(
  1396. int(value)) # default or previously set value
  1397. p['wxId'] = [win.GetId()]
  1398. elif prompt == 'dbdriver':
  1399. win = gselect.DriverSelect(
  1400. parent=which_panel, choices=p.get(
  1401. 'values', []),
  1402. value=value)
  1403. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1404. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1405. elif prompt == 'dbname':
  1406. win = gselect.DatabaseSelect(parent=which_panel,
  1407. value=value)
  1408. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1409. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1410. elif prompt == 'dbtable':
  1411. if p.get('age', 'old') == 'old':
  1412. win = gselect.TableSelect(parent=which_panel)
  1413. win.Bind(
  1414. wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1415. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1416. else:
  1417. win = wx.TextCtrl(
  1418. parent=which_panel, value=p.get(
  1419. 'default', ''),
  1420. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1421. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1422. elif prompt == 'dbcolumn':
  1423. win = gselect.ColumnSelect(
  1424. parent=which_panel, value=value, param=p,
  1425. multiple=p.get('multiple', False))
  1426. # A gselect.ColumnSelect is a combobox
  1427. # with two children: a textctl and a
  1428. # popupwindow; we target the textctl here
  1429. textWin = win.GetTextCtrl()
  1430. p['wxId'] = [textWin.GetId(), ]
  1431. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1432. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1433. elif prompt == 'location':
  1434. win = gselect.LocationSelect(parent=which_panel,
  1435. value=value)
  1436. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1437. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1438. elif prompt == 'mapset':
  1439. if p.get('age', 'old') == 'old':
  1440. new = False
  1441. else:
  1442. new = True
  1443. win = gselect.MapsetSelect(
  1444. parent=which_panel, value=value, new=new,
  1445. multiple=p.get('multiple', False))
  1446. textWin = win.GetTextCtrl()
  1447. p['wxId'] = [textWin.GetId(), win.GetId()]
  1448. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1449. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1450. elif prompt == 'dbase':
  1451. win = gselect.DbaseSelect(
  1452. parent=which_panel, changeCallback=self.OnSetValue)
  1453. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1454. p['wxId'] = [win.GetChildren()[1].GetId()]
  1455. if 'wxId' not in p:
  1456. try:
  1457. p['wxId'] = [win.GetId(), ]
  1458. except AttributeError:
  1459. pass
  1460. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1461. if prompt == 'dbname':
  1462. flags |= wx.EXPAND
  1463. which_sizer.Add(item=win, proportion=0,
  1464. flag=flags, border=5)
  1465. # color entry
  1466. elif prompt == 'color':
  1467. default_color = (200, 200, 200)
  1468. label_color = _("Select Color")
  1469. if p.get('default', '') != '':
  1470. default_color, label_color = utils.color_resolve(p[
  1471. 'default'])
  1472. if p.get('value', '') != '' and p.get(
  1473. 'value', '') != 'none': # parameter previously set
  1474. if not p.get('multiple', False):
  1475. default_color, label_color = utils.color_resolve(p[
  1476. 'value'])
  1477. if p.get(
  1478. 'element', '') == 'color_none' or p.get(
  1479. 'multiple', False):
  1480. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  1481. else:
  1482. this_sizer = which_sizer
  1483. colorSize = 150
  1484. # For color selectors, this is a three-member array, holding the IDs of
  1485. # the color picker, the text control for multiple colors (or None),
  1486. # and either a "transparent" checkbox or None
  1487. p['wxId'] = [None] * 3
  1488. if p.get('multiple', False):
  1489. txt = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY)
  1490. this_sizer.Add(
  1491. item=txt,
  1492. proportion=1,
  1493. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP,
  1494. border=5)
  1495. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1496. if p.get('value', ''):
  1497. txt.SetValue(p['value'])
  1498. colorSize = 40
  1499. label_color = ''
  1500. p['wxId'][1] = txt.GetId()
  1501. which_sizer.Add(
  1502. this_sizer, flag=wx.EXPAND | wx.RIGHT, border=5)
  1503. btn_colour = csel.ColourSelect(
  1504. parent=which_panel, id=wx.ID_ANY, label=label_color,
  1505. colour=default_color, pos=wx.DefaultPosition,
  1506. size=(colorSize, 32))
  1507. this_sizer.Add(
  1508. item=btn_colour,
  1509. proportion=0,
  1510. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
  1511. border=5)
  1512. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1513. p['wxId'][0] = btn_colour.GetId()
  1514. if p.get('element', '') == 'color_none':
  1515. none_check = wx.CheckBox(
  1516. which_panel, wx.ID_ANY, _("Transparent"))
  1517. if p.get('value', '') == "none":
  1518. none_check.SetValue(True)
  1519. else:
  1520. none_check.SetValue(False)
  1521. this_sizer.Add(
  1522. item=none_check, proportion=0,
  1523. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP,
  1524. border=5)
  1525. which_sizer.Add(this_sizer)
  1526. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1527. p['wxId'][2] = none_check.GetId()
  1528. # file selector
  1529. elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'file':
  1530. if p.get('age', 'new') == 'new':
  1531. fmode = wx.FD_SAVE
  1532. else:
  1533. fmode = wx.FD_OPEN
  1534. # check wildcard
  1535. try:
  1536. fExt = os.path.splitext(
  1537. p.get('key_desc', ['*.*'])[0])[1]
  1538. except:
  1539. fExt = None
  1540. if not fExt:
  1541. fMask = '*'
  1542. else:
  1543. fMask = '%s files (*%s)|*%s|Files (*)|*' % (
  1544. fExt[1:].upper(), fExt, fExt)
  1545. fbb = filebrowse.FileBrowseButton(
  1546. parent=which_panel,
  1547. id=wx.ID_ANY,
  1548. fileMask=fMask,
  1549. size=globalvar.DIALOG_GSELECT_SIZE,
  1550. labelText='',
  1551. dialogTitle=_('Choose %s') %
  1552. p.get(
  1553. 'description',
  1554. _('file')).lower(),
  1555. buttonText=_('Browse'),
  1556. startDirectory=os.getcwd(),
  1557. fileMode=fmode,
  1558. changeCallback=self.OnSetValue)
  1559. value = self._getValue(p)
  1560. if value:
  1561. fbb.SetValue(value) # parameter previously set
  1562. which_sizer.Add(item=fbb, proportion=0,
  1563. flag=wx.EXPAND | wx.RIGHT, border=5)
  1564. # A file browse button is a combobox with two children:
  1565. # a textctl and a button;
  1566. # we have to target the button here
  1567. p['wxId'] = [fbb.GetChildren()[1].GetId()]
  1568. if p.get(
  1569. 'age', 'new') == 'old' and p.get(
  1570. 'prompt', '') == 'file' and p.get(
  1571. 'element', '') == 'file' and UserSettings.Get(
  1572. group='cmd', key='interactiveInput', subkey='enabled'):
  1573. # widget for interactive input
  1574. ifbb = wx.TextCtrl(parent=which_panel, id=wx.ID_ANY,
  1575. style=wx.TE_MULTILINE,
  1576. size=(-1, 75))
  1577. if p.get('value', '') and os.path.isfile(p['value']):
  1578. f = open(p['value'])
  1579. ifbb.SetValue(''.join(f.readlines()))
  1580. f.close()
  1581. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1582. btnLoad = wx.Button(
  1583. parent=which_panel, id=wx.ID_ANY, label=_("&Load"))
  1584. btnLoad.SetToolTipString(
  1585. _("Load and edit content of a file"))
  1586. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1587. btnSave = wx.Button(
  1588. parent=which_panel, id=wx.ID_ANY, label=_("&Save as"))
  1589. btnSave.SetToolTipString(
  1590. _("Save content to a file for further use"))
  1591. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1592. fileContentLabel = wx.StaticText(
  1593. parent=which_panel, id=wx.ID_ANY,
  1594. label=_('or enter values directly:'))
  1595. fileContentLabel.SetToolTipString(
  1596. _("Enter file content directly instead of specifying"
  1597. " a file."
  1598. " Temporary file will be automatically created."))
  1599. which_sizer.Add(
  1600. item=fileContentLabel,
  1601. proportion=0,
  1602. flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM,
  1603. border=5)
  1604. which_sizer.Add(
  1605. item=ifbb,
  1606. proportion=1,
  1607. flag=wx.EXPAND | wx.RIGHT | wx.LEFT,
  1608. border=5)
  1609. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1610. btnSizer.Add(item=btnLoad, proportion=0,
  1611. flag=wx.ALIGN_RIGHT | wx.RIGHT, border=10)
  1612. btnSizer.Add(item=btnSave, proportion=0,
  1613. flag=wx.ALIGN_RIGHT)
  1614. which_sizer.Add(
  1615. item=btnSizer,
  1616. proportion=0,
  1617. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
  1618. border=5)
  1619. p['wxId'].append(ifbb.GetId())
  1620. p['wxId'].append(btnLoad.GetId())
  1621. p['wxId'].append(btnSave.GetId())
  1622. # directory selector
  1623. elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'dir':
  1624. fbb = filebrowse.DirBrowseButton(
  1625. parent=which_panel,
  1626. id=wx.ID_ANY,
  1627. size=globalvar.DIALOG_GSELECT_SIZE,
  1628. labelText='',
  1629. dialogTitle=_('Choose %s') %
  1630. p.get(
  1631. 'description',
  1632. _('Directory')),
  1633. buttonText=_('Browse'),
  1634. startDirectory=os.getcwd(),
  1635. changeCallback=self.OnSetValue)
  1636. value = self._getValue(p)
  1637. if value:
  1638. fbb.SetValue(value) # parameter previously set
  1639. which_sizer.Add(item=fbb, proportion=0,
  1640. flag=wx.EXPAND | wx.RIGHT, border=5)
  1641. # A file browse button is a combobox with two children:
  1642. # a textctl and a button;
  1643. # we have to target the button here
  1644. p['wxId'] = [fbb.GetChildren()[1].GetId()]
  1645. # interactive inserting of coordinates from map window
  1646. elif prompt == 'coords':
  1647. # interactive inserting if layer manager is accessible
  1648. if self._giface:
  1649. win = gselect.CoordinatesSelect(
  1650. parent=which_panel, giface=self._giface, multiple=p.get(
  1651. 'multiple', False), param=p)
  1652. p['wxId'] = [win.GetTextWin().GetId()]
  1653. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1654. # bind closing event because destructor is not working
  1655. # properly
  1656. if hasattr(self.parent, 'dialogClosing'):
  1657. self.parent.dialogClosing.connect(win.OnClose)
  1658. # normal text field
  1659. else:
  1660. win = wx.TextCtrl(parent=which_panel)
  1661. p['wxId'] = [win.GetId()]
  1662. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1663. which_sizer.Add(
  1664. item=win,
  1665. proportion=0,
  1666. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1667. border=5)
  1668. elif prompt in ('cat', 'cats'):
  1669. # interactive selection of vector categories if layer
  1670. # manager is accessible
  1671. if self._giface:
  1672. win = gselect.VectorCategorySelect(
  1673. parent=which_panel, giface=self._giface, task=self.task)
  1674. p['wxId'] = [win.GetTextWin().GetId()]
  1675. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1676. # bind closing event because destructor is not working
  1677. # properly
  1678. if hasattr(self.parent, 'dialogClosing'):
  1679. self.parent.dialogClosing.connect(win.OnClose)
  1680. # normal text field
  1681. else:
  1682. win = wx.TextCtrl(parent=which_panel)
  1683. value = self._getValue(p)
  1684. win.SetValue(value)
  1685. p['wxId'] = [win.GetId()]
  1686. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1687. which_sizer.Add(
  1688. item=win,
  1689. proportion=0,
  1690. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1691. border=5)
  1692. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1693. if prompt == 'colortable':
  1694. cb = ColorTablesComboBox(
  1695. parent=which_panel, value=p.get('default', ''),
  1696. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1697. choices=valuelist)
  1698. elif prompt == 'barscale':
  1699. cb = BarscalesComboBox(
  1700. parent=which_panel, value=p.get('default', ''),
  1701. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1702. choices=valuelist)
  1703. elif prompt == 'northarrow':
  1704. cb = NArrowsComboBox(
  1705. parent=which_panel, value=p.get('default', ''),
  1706. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1707. choices=valuelist)
  1708. value = self._getValue(p)
  1709. if value:
  1710. cb.SetValue(value) # parameter previously set
  1711. which_sizer.Add(
  1712. item=cb,
  1713. proportion=0,
  1714. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
  1715. border=5)
  1716. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1717. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1718. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1719. if p.get('guidependency', ''):
  1720. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1721. elif prompt == 'datasource':
  1722. win = gselect.GdalSelect(parent=parent, panel=which_panel,
  1723. ogr=True)
  1724. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1725. win.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1726. p['wxId'] = [
  1727. win.GetId(),
  1728. win.fileWidgets['browse'].GetChildren()[1].GetId(),
  1729. win.dirWidgets['browse'].GetChildren()[1].GetId(),
  1730. win.dbWidgets['choice'].GetId()]
  1731. value = self._getValue(p)
  1732. if value:
  1733. win.fileWidgets['browse'].GetChildren()[1].SetValue(
  1734. value) # parameter previously set
  1735. which_sizer.Add(item=win, proportion=0,
  1736. flag=wx.EXPAND)
  1737. elif prompt == 'datasource_layer':
  1738. self.win1 = LayersList(
  1739. parent=which_panel,
  1740. columns=[
  1741. _('Layer id'),
  1742. _('Layer name'),
  1743. _('Feature type'),
  1744. _('Projection match')])
  1745. which_sizer.Add(item=self.win1, proportion=0,
  1746. flag=wx.EXPAND | wx.ALL, border=3)
  1747. porf = self.task.get_param(
  1748. 'input', element='name', raiseError=False)
  1749. if porf and 'wxId' in porf:
  1750. winDataSource = self.FindWindowById(porf['wxId'][0])
  1751. winDataSource.reloadDataRequired.connect(
  1752. lambda listData: self.win1.LoadData(
  1753. listData, False))
  1754. p['wxId'] = [self.win1.GetId()]
  1755. def OnCheckItem(index, flag):
  1756. layers = list()
  1757. for layer, match, listId in self.win1.GetLayers():
  1758. layers.append(layer)
  1759. porf = self.task.get_param(
  1760. 'layer', element='name', raiseError=False)
  1761. porf['value'] = ','.join(layers)
  1762. self.OnUpdateValues() # TODO: replace by signal
  1763. self.win1.OnCheckItem = OnCheckItem
  1764. if self.parent.GetName() == 'MainFrame' and (
  1765. self._giface and hasattr(self._giface, "_model")):
  1766. parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
  1767. label=_("Parameterized in model"))
  1768. parChk.SetName('ModelParam')
  1769. parChk.SetValue(p.get('parameterized', False))
  1770. if 'wxId' in p:
  1771. p['wxId'].append(parChk.GetId())
  1772. else:
  1773. p['wxId'] = [parChk.GetId()]
  1774. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1775. which_sizer.Add(item=parChk, proportion=0,
  1776. flag=wx.LEFT, border=20)
  1777. if title_txt is not None:
  1778. # create tooltip if given
  1779. if len(p['values_desc']) > 0:
  1780. if tooltip:
  1781. tooltip += 2 * os.linesep
  1782. else:
  1783. tooltip = ''
  1784. if len(p['values']) == len(p['values_desc']):
  1785. for i in range(len(p['values'])):
  1786. tooltip += p['values'][i] + ': ' + \
  1787. p['values_desc'][i] + os.linesep
  1788. tooltip.strip(os.linesep)
  1789. if tooltip:
  1790. title_txt.SetToolTipString(tooltip)
  1791. if p == first_param:
  1792. if 'wxId' in p and len(p['wxId']) > 0:
  1793. win = self.FindWindowById(p['wxId'][0])
  1794. win.SetFocus()
  1795. #
  1796. # set widget relations for OnUpdateSelection
  1797. #
  1798. pMap = None
  1799. pLayer = []
  1800. pDriver = None
  1801. pDatabase = None
  1802. pTable = None
  1803. pColumn = []
  1804. pGroup = None
  1805. pSubGroup = None
  1806. pSigFile = []
  1807. pDbase = None
  1808. pLocation = None
  1809. pMapset = None
  1810. for p in self.task.params:
  1811. guidep = p.get('guidependency', '')
  1812. if guidep:
  1813. # fixed options dependency defined
  1814. options = guidep.split(',')
  1815. for opt in options:
  1816. pOpt = self.task.get_param(
  1817. opt, element='name', raiseError=False)
  1818. if pOpt and id:
  1819. if 'wxId-bind' not in p:
  1820. p['wxId-bind'] = list()
  1821. p['wxId-bind'] += pOpt['wxId']
  1822. continue
  1823. if p.get('gisprompt', False) == False:
  1824. continue
  1825. prompt = p.get('prompt', '')
  1826. if prompt in ('raster', 'vector'):
  1827. name = p.get('name', '')
  1828. if name in ('map', 'input'):
  1829. pMap = p
  1830. elif prompt == 'layer':
  1831. pLayer.append(p)
  1832. elif prompt == 'dbcolumn':
  1833. pColumn.append(p)
  1834. elif prompt == 'dbdriver':
  1835. pDriver = p
  1836. elif prompt == 'dbname':
  1837. pDatabase = p
  1838. elif prompt == 'dbtable':
  1839. pTable = p
  1840. elif prompt == 'group':
  1841. pGroup = p
  1842. elif prompt == 'subgroup':
  1843. pSubGroup = p
  1844. elif prompt == 'sigfile':
  1845. pSigFile.append(p)
  1846. elif prompt == 'dbase':
  1847. pDbase = p
  1848. elif prompt == 'location':
  1849. pLocation = p
  1850. elif prompt == 'mapset':
  1851. pMapset = p
  1852. # collect ids
  1853. pColumnIds = []
  1854. for p in pColumn:
  1855. pColumnIds += p['wxId']
  1856. pLayerIds = []
  1857. for p in pLayer:
  1858. pLayerIds += p['wxId']
  1859. pSigFileIds = []
  1860. for p in pSigFile:
  1861. pSigFileIds += p['wxId']
  1862. # set wxId-bindings
  1863. if pMap:
  1864. pMap['wxId-bind'] = []
  1865. if pLayer:
  1866. pMap['wxId-bind'] += pLayerIds
  1867. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1868. if pLayer:
  1869. for p in pLayer:
  1870. p['wxId-bind'] = copy.copy(pColumnIds)
  1871. if pDriver and pTable:
  1872. pDriver['wxId-bind'] = pTable['wxId']
  1873. if pDatabase and pTable:
  1874. pDatabase['wxId-bind'] = pTable['wxId']
  1875. if pTable and pColumnIds:
  1876. pTable['wxId-bind'] = pColumnIds
  1877. if pGroup and pSubGroup:
  1878. if pSigFile:
  1879. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1880. pSubGroup['wxId-bind'] = pSigFileIds
  1881. else:
  1882. pGroup['wxId-bind'] = pSubGroup['wxId']
  1883. if pDbase and pLocation:
  1884. pDbase['wxId-bind'] = pLocation['wxId']
  1885. if pLocation and pMapset:
  1886. pLocation['wxId-bind'] = pMapset['wxId']
  1887. if pLocation and pMapset and pMap:
  1888. # pLocation['wxId-bind'] += pMap['wxId']
  1889. pMapset['wxId-bind'] = pMap['wxId']
  1890. #
  1891. # determine panel size
  1892. #
  1893. maxsizes = (0, 0)
  1894. for section in sections:
  1895. tab[section].SetSizer(tabsizer[section])
  1896. tabsizer[section].Fit(tab[section])
  1897. tab[section].Layout()
  1898. minsecsizes = tabsizer[section].GetSize()
  1899. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1900. # TODO: be less arbitrary with these 600
  1901. self.panelMinHeight = 100
  1902. self.constrained_size = (
  1903. min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1904. for section in sections:
  1905. tab[section].SetMinSize(
  1906. (self.constrained_size[0], self.panelMinHeight))
  1907. # add pages to notebook
  1908. imageList = wx.ImageList(16, 16)
  1909. self.notebook.AssignImageList(imageList)
  1910. for section in sections:
  1911. self.notebook.AddPage(
  1912. page=tab[section],
  1913. text=section, name=section)
  1914. index = self.AddBitmapToImageList(section, imageList)
  1915. if index >= 0:
  1916. self.notebook.SetPageImage(section, index)
  1917. # are we running from command line?
  1918. # add 'command output' tab regardless standalone dialog
  1919. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1920. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1921. from gui_core.goutput import GConsoleWindow
  1922. self._gconsole = GConsole(
  1923. guiparent=self.notebook, giface=self._giface)
  1924. self.goutput = GConsoleWindow(
  1925. parent=self.notebook,
  1926. gconsole=self._gconsole,
  1927. margin=False)
  1928. self._gconsole.Bind(
  1929. EVT_CMD_RUN, lambda event: self._switchPageHandler(
  1930. event=event, notification=Notification.MAKE_VISIBLE))
  1931. self._gconsole.Bind(
  1932. EVT_CMD_DONE, lambda event: self._switchPageHandler(
  1933. event=event, notification=Notification.RAISE_WINDOW))
  1934. self.outpage = self.notebook.AddPage(
  1935. page=self.goutput, text=_("Command output"), name='output')
  1936. else:
  1937. self.goutput = None
  1938. self._gconsole = None
  1939. self.manualTab = HelpPanel(
  1940. parent=self.notebook,
  1941. command=self.task.get_name())
  1942. if not self.manualTab.GetFile():
  1943. self.manualTab.Hide()
  1944. else:
  1945. self.notebook.AddPage(
  1946. page=self.manualTab,
  1947. text=_("Manual"),
  1948. name='manual')
  1949. index = self.AddBitmapToImageList(
  1950. section='manual', imageList=imageList)
  1951. if index >= 0:
  1952. self.notebook.SetPageImage('manual', index)
  1953. if self.manualTab.IsLoaded():
  1954. self.manualTab.SetMinSize(
  1955. (self.constrained_size[0], self.panelMinHeight))
  1956. self.notebook.SetSelection(0)
  1957. panelsizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND)
  1958. self.SetSizer(panelsizer)
  1959. panelsizer.Fit(self.notebook)
  1960. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1961. def _getValue(self, p):
  1962. """Get value or default value of given parameter
  1963. :param p: parameter directory
  1964. """
  1965. if p.get('value', '') != '':
  1966. return p['value']
  1967. return p.get('default', '')
  1968. def OnFileLoad(self, event):
  1969. """Load file to interactive input"""
  1970. me = event.GetId()
  1971. win = dict()
  1972. for p in self.task.params:
  1973. if 'wxId' in p and me in p['wxId']:
  1974. win['file'] = self.FindWindowById(p['wxId'][0])
  1975. win['text'] = self.FindWindowById(p['wxId'][1])
  1976. break
  1977. if not win:
  1978. return
  1979. path = win['file'].GetValue()
  1980. if not path:
  1981. gcmd.GMessage(parent=self,
  1982. message=_("Nothing to load."))
  1983. return
  1984. data = ''
  1985. try:
  1986. f = open(path, "r")
  1987. except IOError as e:
  1988. gcmd.GError(parent=self, showTraceback=False,
  1989. message=_("Unable to load file.\n\nReason: %s") % e)
  1990. return
  1991. try:
  1992. data = f.read()
  1993. finally:
  1994. f.close()
  1995. win['text'].SetValue(data)
  1996. def OnFileSave(self, event):
  1997. """Save interactive input to the file"""
  1998. wId = event.GetId()
  1999. win = {}
  2000. for p in self.task.params:
  2001. if wId in p.get('wxId', []):
  2002. win['file'] = self.FindWindowById(p['wxId'][0])
  2003. win['text'] = self.FindWindowById(p['wxId'][1])
  2004. break
  2005. if not win:
  2006. return
  2007. text = win['text'].GetValue()
  2008. if not text:
  2009. gcmd.GMessage(parent=self,
  2010. message=_("Nothing to save."))
  2011. return
  2012. dlg = wx.FileDialog(parent=self,
  2013. message=_("Save input as..."),
  2014. defaultDir=os.getcwd(),
  2015. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  2016. if dlg.ShowModal() == wx.ID_OK:
  2017. path = dlg.GetPath()
  2018. enc = locale.getdefaultlocale()[1]
  2019. f = codecs.open(path, encoding=enc, mode='w', errors='replace')
  2020. try:
  2021. f.write(text + os.linesep)
  2022. finally:
  2023. f.close()
  2024. win['file'].SetValue(path)
  2025. dlg.Destroy()
  2026. def OnFileText(self, event):
  2027. """File input interactively entered"""
  2028. text = event.GetString()
  2029. p = self.task.get_param(
  2030. value=event.GetId(),
  2031. element='wxId',
  2032. raiseError=False)
  2033. if not p:
  2034. return # should not happen
  2035. win = self.FindWindowById(p['wxId'][0])
  2036. if text:
  2037. filename = win.GetValue()
  2038. if not filename or filename == p[
  2039. 'default']: # m.proj has - as default
  2040. filename = grass.tempfile()
  2041. win.SetValue(filename)
  2042. enc = locale.getdefaultlocale()[1]
  2043. f = codecs.open(filename, encoding=enc, mode='w', errors='replace')
  2044. try:
  2045. f.write(text)
  2046. if text[-1] != os.linesep:
  2047. f.write(os.linesep)
  2048. finally:
  2049. f.close()
  2050. else:
  2051. win.SetValue('')
  2052. def OnVectorFormat(self, event):
  2053. """Change vector format (native / ogr).
  2054. Currently unused.
  2055. """
  2056. sel = event.GetSelection()
  2057. idEvent = event.GetId()
  2058. p = self.task.get_param(
  2059. value=idEvent,
  2060. element='wxId',
  2061. raiseError=False)
  2062. if not p:
  2063. return # should not happen
  2064. # detect windows
  2065. winNative = None
  2066. winOgr = None
  2067. for id in p['wxId']:
  2068. if id == idEvent:
  2069. continue
  2070. name = self.FindWindowById(id).GetName()
  2071. if name == 'Select':
  2072. # fix the mystery (also in nviz_tools.py)
  2073. winNative = self.FindWindowById(id + 1)
  2074. elif name == 'OgrSelect':
  2075. winOgr = self.FindWindowById(id)
  2076. # enable / disable widgets & update values
  2077. rbox = self.FindWindowByName('VectorFormat')
  2078. self.hsizer.Remove(rbox)
  2079. if sel == 0: # -> native
  2080. winOgr.Hide()
  2081. self.hsizer.Remove(winOgr)
  2082. self.hsizer.Add(
  2083. item=winNative,
  2084. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  2085. border=5)
  2086. winNative.Show()
  2087. p['value'] = winNative.GetValue()
  2088. elif sel == 1: # -> OGR
  2089. sizer = wx.BoxSizer(wx.VERTICAL)
  2090. winNative.Hide()
  2091. self.hsizer.Remove(winNative)
  2092. sizer.Add(item=winOgr)
  2093. winOgr.Show()
  2094. p['value'] = winOgr.GetDsn()
  2095. self.hsizer.Add(
  2096. item=sizer,
  2097. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  2098. border=5)
  2099. self.hsizer.Add(item=rbox,
  2100. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  2101. wx.RIGHT | wx.ALIGN_TOP,
  2102. border=5)
  2103. self.hsizer.Layout()
  2104. self.Layout()
  2105. self.OnUpdateValues()
  2106. self.OnUpdateSelection(event)
  2107. def OnUpdateDialog(self, event):
  2108. for fn, kwargs in event.data.iteritems():
  2109. fn(**kwargs)
  2110. self.parent.updateValuesHook()
  2111. def OnVerbosity(self, event):
  2112. """Verbosity level changed"""
  2113. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  2114. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  2115. if event.IsChecked():
  2116. if event.GetId() == verbose.GetId():
  2117. if quiet.IsChecked():
  2118. quiet.SetValue(False)
  2119. self.task.get_flag('quiet')['value'] = False
  2120. else:
  2121. if verbose.IsChecked():
  2122. verbose.SetValue(False)
  2123. self.task.get_flag('verbose')['value'] = False
  2124. event.Skip()
  2125. def OnPageChange(self, event):
  2126. if not event:
  2127. sel = self.notebook.GetSelection()
  2128. else:
  2129. sel = event.GetSelection()
  2130. idx = self.notebook.GetPageIndexByName('manual')
  2131. if idx > -1 and sel == idx:
  2132. # calling LoadPage() is strangely time-consuming (only first call)
  2133. # FIXME: move to helpPage.__init__()
  2134. if not self.manualTab.IsLoaded():
  2135. wx.Yield()
  2136. self.manualTab.LoadPage()
  2137. self.Layout()
  2138. if event:
  2139. # skip is needed for wx.Notebook on Windows
  2140. event.Skip()
  2141. # this is needed for dialogs launched from layer manager
  2142. # event is somehow propagated?
  2143. event.StopPropagation()
  2144. def _switchPageHandler(self, event, notification):
  2145. self._switchPage(notification=notification)
  2146. event.Skip()
  2147. def _switchPage(self, notification):
  2148. """Manages @c 'output' notebook page according to event notification."""
  2149. if notification == Notification.HIGHLIGHT:
  2150. self.notebook.HighlightPageByName('output')
  2151. if notification == Notification.MAKE_VISIBLE:
  2152. self.notebook.SetSelectionByName('output')
  2153. if notification == Notification.RAISE_WINDOW:
  2154. self.notebook.SetSelectionByName('output')
  2155. self.SetFocus()
  2156. self.Raise()
  2157. def OnColorChange(self, event):
  2158. myId = event.GetId()
  2159. for p in self.task.params:
  2160. if 'wxId' in p and myId in p['wxId']:
  2161. multiple = p['wxId'][1] is not None # multiple colors
  2162. hasTansp = p['wxId'][2] is not None
  2163. if multiple:
  2164. # selected color is added at the end of textCtrl
  2165. colorchooser = wx.FindWindowById(p['wxId'][0])
  2166. new_color = colorchooser.GetValue()[:]
  2167. new_label = utils.rgb2str.get(
  2168. new_color, ':'.join(map(str, new_color)))
  2169. textCtrl = wx.FindWindowById(p['wxId'][1])
  2170. val = textCtrl.GetValue()
  2171. sep = ','
  2172. if val and val[-1] != sep:
  2173. val += sep
  2174. val += new_label
  2175. textCtrl.SetValue(val)
  2176. p['value'] = val
  2177. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  2178. p['value'] = 'none'
  2179. else:
  2180. colorchooser = wx.FindWindowById(p['wxId'][0])
  2181. new_color = colorchooser.GetValue()[:]
  2182. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  2183. # under wx2.8.1
  2184. new_label = utils.rgb2str.get(
  2185. new_color, ':'.join(map(str, new_color)))
  2186. colorchooser.SetLabel(new_label)
  2187. colorchooser.SetColour(new_color)
  2188. colorchooser.Refresh()
  2189. p['value'] = colorchooser.GetLabel()
  2190. self.OnUpdateValues()
  2191. def OnUpdateValues(self, event=None):
  2192. """If we were part of a richer interface, report back the
  2193. current command being built.
  2194. This method should be set by the parent of this panel if
  2195. needed. It's a hook, actually. Beware of what is 'self' in
  2196. the method def, though. It will be called with no arguments.
  2197. """
  2198. pass
  2199. def OnCheckBoxMulti(self, event):
  2200. """Fill the values as a ','-separated string according to
  2201. current status of the checkboxes.
  2202. """
  2203. me = event.GetId()
  2204. theParam = None
  2205. for p in self.task.params:
  2206. if 'wxId' in p and me in p['wxId']:
  2207. theParam = p
  2208. myIndex = p['wxId'].index(me)
  2209. # Unpack current value list
  2210. currentValues = {}
  2211. for isThere in theParam.get('value', '').split(','):
  2212. currentValues[isThere] = 1
  2213. theValue = theParam['values'][myIndex]
  2214. if event.Checked():
  2215. currentValues[theValue] = 1
  2216. else:
  2217. del currentValues[theValue]
  2218. # Keep the original order, so that some defaults may be recovered
  2219. currentValueList = []
  2220. for v in theParam['values']:
  2221. if v in currentValues:
  2222. currentValueList.append(v)
  2223. # Pack it back
  2224. theParam['value'] = ','.join(currentValueList)
  2225. self.OnUpdateValues()
  2226. event.Skip()
  2227. def OnSetValue(self, event):
  2228. """Retrieve the widget value and set the task value field
  2229. accordingly.
  2230. Use for widgets that have a proper GetValue() method, i.e. not
  2231. for selectors.
  2232. """
  2233. myId = event.GetId()
  2234. me = wx.FindWindowById(myId)
  2235. name = me.GetName()
  2236. found = False
  2237. for porf in self.task.params + self.task.flags:
  2238. if 'wxId' not in porf:
  2239. continue
  2240. if myId in porf['wxId']:
  2241. found = True
  2242. break
  2243. if not found:
  2244. return
  2245. if name == 'GdalSelect':
  2246. porf['value'] = event.dsn
  2247. elif name == 'ModelParam':
  2248. porf['parameterized'] = me.IsChecked()
  2249. elif name == 'GdalSelectDataSource':
  2250. win = self.FindWindowById(porf['wxId'][0])
  2251. porf['value'] = win.GetDsn()
  2252. pLayer = self.task.get_param(
  2253. 'layer', element='name', raiseError=False)
  2254. if pLayer:
  2255. pLayer['value'] = ''
  2256. else:
  2257. if isinstance(me, wx.SpinCtrl):
  2258. porf['value'] = str(me.GetValue())
  2259. elif isinstance(me, wx.ComboBox):
  2260. porf['value'] = me.GetValue()
  2261. elif isinstance(me, wx.Choice):
  2262. porf['value'] = me.GetStringSelection()
  2263. else:
  2264. porf['value'] = me.GetValue()
  2265. self.OnUpdateValues(event)
  2266. event.Skip()
  2267. def OnSetSymbol(self, event):
  2268. """Shows dialog for symbol selection"""
  2269. myId = event.GetId()
  2270. for p in self.task.params:
  2271. if 'wxId' in p and myId in p['wxId']:
  2272. from gui_core.dialogs import SymbolDialog
  2273. dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
  2274. currentSymbol=p['value'])
  2275. if dlg.ShowModal() == wx.ID_OK:
  2276. img = dlg.GetSelectedSymbolPath()
  2277. p['value'] = dlg.GetSelectedSymbolName()
  2278. bitmapButton = wx.FindWindowById(p['wxId'][0])
  2279. label = wx.FindWindowById(p['wxId'][1])
  2280. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  2281. label.SetLabel(p['value'])
  2282. self.OnUpdateValues(event)
  2283. dlg.Destroy()
  2284. def OnTimelineTool(self, event):
  2285. """Show Timeline Tool with dataset(s) from gselect.
  2286. .. todo::
  2287. update from gselect automatically
  2288. """
  2289. myId = event.GetId()
  2290. for p in self.task.params:
  2291. if 'wxId' in p and myId in p['wxId']:
  2292. select = self.FindWindowById(p['wxId'][0])
  2293. if not select.GetValue():
  2294. gcmd.GMessage(parent=self, message=_("No dataset given."))
  2295. return
  2296. datasets = select.GetValue().split(',')
  2297. from timeline import frame
  2298. frame.run(parent=self, datasets=datasets)
  2299. def OnUpdateSelection(self, event):
  2300. """Update dialog (layers, tables, columns, etc.)
  2301. """
  2302. if not hasattr(self.parent, "updateThread"):
  2303. if event:
  2304. event.Skip()
  2305. return
  2306. if event:
  2307. self.parent.updateThread.Update(UpdateDialog,
  2308. self,
  2309. event,
  2310. event.GetId(),
  2311. self.task)
  2312. else:
  2313. self.parent.updateThread.Update(UpdateDialog,
  2314. self,
  2315. None,
  2316. None,
  2317. self.task)
  2318. def createCmd(self, ignoreErrors=False, ignoreRequired=False):
  2319. """Produce a command line string (list) or feeding into GRASS.
  2320. :param ignoreErrors: True then it will return whatever has been
  2321. built so far, even though it would not be
  2322. a correct command for GRASS
  2323. """
  2324. try:
  2325. cmd = self.task.get_cmd(ignoreErrors=ignoreErrors,
  2326. ignoreRequired=ignoreRequired)
  2327. except ValueError as err:
  2328. dlg = wx.MessageDialog(parent=self,
  2329. message=gcmd.DecodeString(str(err)),
  2330. caption=_("Error in %s") % self.task.name,
  2331. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  2332. dlg.ShowModal()
  2333. dlg.Destroy()
  2334. cmd = None
  2335. return cmd
  2336. def OnSize(self, event):
  2337. width = event.GetSize()[0]
  2338. fontsize = self.GetFont().GetPointSize()
  2339. text_width = max(width / (fontsize - 3), 70)
  2340. for id in self.label_id:
  2341. win = self.FindWindowById(id)
  2342. label = win.GetLabel()
  2343. label_new = '\n'.join(textwrap.wrap(label, text_width))
  2344. win.SetLabel(label_new)
  2345. event.Skip()
  2346. def AddBitmapToImageList(self, section, imageList):
  2347. iconTheme = UserSettings.Get(
  2348. group='appearance',
  2349. key='iconTheme',
  2350. subkey='type')
  2351. iconSectionDict = {
  2352. 'manual': os.path.join(
  2353. globalvar.ICONDIR,
  2354. iconTheme,
  2355. 'help.png')}
  2356. if section in iconSectionDict.keys():
  2357. image = wx.Image(
  2358. iconSectionDict[section]).Scale(
  2359. 16, 16, wx.IMAGE_QUALITY_HIGH)
  2360. idx = imageList.Add(wx.BitmapFromImage(image))
  2361. return idx
  2362. return -1
  2363. class GUI:
  2364. def __init__(self, parent=None, giface=None, show=True, modal=False,
  2365. centreOnParent=False, checkError=False):
  2366. """Parses GRASS commands when module is imported and used from
  2367. Layer Manager.
  2368. """
  2369. self.parent = parent
  2370. self.show = show
  2371. self.modal = modal
  2372. self._giface = giface
  2373. self.centreOnParent = centreOnParent
  2374. self.checkError = checkError
  2375. self.grass_task = None
  2376. self.cmd = list()
  2377. global _blackList
  2378. if self.parent:
  2379. _blackList['enabled'] = True
  2380. else:
  2381. _blackList['enabled'] = False
  2382. def GetCmd(self):
  2383. """Get validated command"""
  2384. return self.cmd
  2385. def ParseCommand(self, cmd, completed=None):
  2386. """Parse command
  2387. Note: cmd is given as list
  2388. If command is given with options, return validated cmd list:
  2389. - add key name for first parameter if not given
  2390. - change mapname to mapname@mapset
  2391. """
  2392. dcmd_params = {}
  2393. if completed is None:
  2394. get_dcmd = None
  2395. layer = None
  2396. dcmd_params = None
  2397. else:
  2398. get_dcmd = completed[0]
  2399. layer = completed[1]
  2400. if completed[2]:
  2401. dcmd_params.update(completed[2])
  2402. # parse the interface decription
  2403. try:
  2404. global _blackList
  2405. self.grass_task = gtask.parse_interface(cmd[0],
  2406. blackList=_blackList)
  2407. except (grass.ScriptError, ValueError) as e:
  2408. raise gcmd.GException(e.value)
  2409. # if layer parameters previously set, re-insert them into dialog
  2410. if completed is not None:
  2411. if 'params' in dcmd_params:
  2412. self.grass_task.params = dcmd_params['params']
  2413. if 'flags' in dcmd_params:
  2414. self.grass_task.flags = dcmd_params['flags']
  2415. err = list()
  2416. # update parameters if needed && validate command
  2417. if len(cmd) > 1:
  2418. i = 0
  2419. cmd_validated = [cmd[0]]
  2420. for option in cmd[1:]:
  2421. if option[0] == '-': # flag
  2422. if len(option) == 1: # catch typo like 'g.proj - w'
  2423. raise gcmd.GException(
  2424. _("Unable to parse command '%s'") %
  2425. ' '.join(cmd))
  2426. if option[1] == '-':
  2427. self.grass_task.set_flag(option[2:], True)
  2428. else:
  2429. self.grass_task.set_flag(option[1], True)
  2430. cmd_validated.append(option)
  2431. else: # parameter
  2432. try:
  2433. key, value = option.split('=', 1)
  2434. except ValueError:
  2435. if self.grass_task.firstParam:
  2436. if i == 0: # add key name of first parameter if not given
  2437. key = self.grass_task.firstParam
  2438. value = option
  2439. else:
  2440. raise gcmd.GException(
  2441. _("Unable to parse command '%s'") % ' '.join(cmd))
  2442. else:
  2443. continue
  2444. task = self.grass_task.get_param(key, raiseError=False)
  2445. if not task:
  2446. err.append(
  2447. _("%(cmd)s: parameter '%(key)s' not available") % {
  2448. 'cmd': cmd[0],
  2449. 'key': key})
  2450. continue
  2451. self.grass_task.set_param(key, value)
  2452. cmd_validated.append(key + '=' + value)
  2453. i += 1
  2454. # update original command list
  2455. cmd = cmd_validated
  2456. if self.show is not None:
  2457. self.mf = TaskFrame(parent=self.parent, giface=self._giface,
  2458. task_description=self.grass_task,
  2459. get_dcmd=get_dcmd, layer=layer)
  2460. else:
  2461. self.mf = None
  2462. if get_dcmd is not None:
  2463. # update only propwin reference
  2464. get_dcmd(dcmd=None, layer=layer, params=None,
  2465. propwin=self.mf)
  2466. if self.show is not None:
  2467. self.mf.notebookpanel.OnUpdateSelection(None)
  2468. if self.show is True:
  2469. if self.parent and self.centreOnParent:
  2470. self.mf.CentreOnParent()
  2471. else:
  2472. self.mf.CenterOnScreen()
  2473. self.mf.Show(self.show)
  2474. self.mf.MakeModal(self.modal)
  2475. else:
  2476. self.mf.OnApply(None)
  2477. self.cmd = cmd
  2478. if self.checkError:
  2479. return self.grass_task, err
  2480. else:
  2481. return self.grass_task
  2482. def GetCommandInputMapParamKey(self, cmd):
  2483. """Get parameter key for input raster/vector map
  2484. :param cmd: module name
  2485. :return: parameter key
  2486. :return: None on failure
  2487. """
  2488. # parse the interface decription
  2489. if not self.grass_task:
  2490. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2491. self.grass_task = gtask.processTask(tree).get_task()
  2492. for p in self.grass_task.params:
  2493. if p.get('name', '') in ('input', 'map'):
  2494. age = p.get('age', '')
  2495. prompt = p.get('prompt', '')
  2496. element = p.get('element', '')
  2497. if age == 'old' and \
  2498. element in ('cell', 'grid3', 'vector') and \
  2499. prompt in ('raster', 'raster_3d', 'vector'):
  2500. return p.get('name', None)
  2501. return None
  2502. class GrassGUIApp(wx.App):
  2503. """Stand-alone GRASS command GUI
  2504. """
  2505. def __init__(self, grass_task):
  2506. self.grass_task = grass_task
  2507. wx.App.__init__(self, False)
  2508. def OnInit(self):
  2509. msg = self.grass_task.get_error_msg()
  2510. if msg:
  2511. gcmd.GError(
  2512. msg +
  2513. '\n\n' +
  2514. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2515. return True
  2516. self.mf = TaskFrame(
  2517. parent=None,
  2518. giface=None,
  2519. task_description=self.grass_task)
  2520. self.mf.CentreOnScreen()
  2521. self.mf.Show(True)
  2522. self.SetTopWindow(self.mf)
  2523. return True
  2524. USAGE_MESSAGE = """Usage:
  2525. {name} <grass module>
  2526. {name} <full path to file>
  2527. python {name} <grass module>
  2528. Test:
  2529. python {name} test
  2530. python {name} g.region
  2531. python {name} "g.region -p"
  2532. python {name} temporal/t.list/t.list.py"""
  2533. if __name__ == "__main__":
  2534. if len(sys.argv) == 1:
  2535. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2536. if sys.argv[1] != 'test':
  2537. q = wx.LogNull()
  2538. from core.debug import Debug
  2539. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2540. cmd = utils.split(sys.argv[1])
  2541. task = gtask.grassTask(cmd[0])
  2542. task.set_options(cmd[1:])
  2543. Debug.msg(1, "forms.py opening form for: %s" %
  2544. task.get_cmd(ignoreErrors=True, ignoreRequired=True))
  2545. app = GrassGUIApp(task)
  2546. app.MainLoop()
  2547. else: # Test
  2548. # Test grassTask from within a GRASS session
  2549. if os.getenv("GISBASE") is not None:
  2550. task = gtask.grassTask("d.vect")
  2551. task.get_param('map')['value'] = "map_name"
  2552. task.get_flag('i')['value'] = True
  2553. task.get_param('layer')['value'] = 1
  2554. task.get_param('label_bcolor')['value'] = "red"
  2555. # the default parameter display is added automatically
  2556. assert ' '.join(
  2557. task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
  2558. print "Creation of task successful"
  2559. # Test interface building with handmade grassTask,
  2560. # possibly outside of a GRASS session.
  2561. print "Now creating a module dialog (task frame)"
  2562. task = gtask.grassTask()
  2563. task.name = "TestTask"
  2564. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2565. task.keywords = ["grass", "test", "task"]
  2566. task.params = [
  2567. {
  2568. "name": "text",
  2569. "description": "Descriptions go into tooltips if labels are present, like this one",
  2570. "label": "Enter some text",
  2571. "key_desc": ["value"],
  2572. "values_desc": []
  2573. }, {
  2574. "name": "hidden_text",
  2575. "description": "This text should not appear in the form",
  2576. "hidden": True,
  2577. "key_desc": ["value"],
  2578. "values_desc": []
  2579. }, {
  2580. "name": "text_default",
  2581. "description": "Enter text to override the default",
  2582. "default": "default text",
  2583. "key_desc": ["value"],
  2584. "values_desc": []
  2585. }, {
  2586. "name": "text_prefilled",
  2587. "description": "You should see a friendly welcome message here",
  2588. "value": "hello, world",
  2589. "key_desc": ["value"],
  2590. "values_desc": []
  2591. }, {
  2592. "name": "plain_color",
  2593. "description": "This is a plain color, and it is a compulsory parameter",
  2594. "required": False,
  2595. "gisprompt": True,
  2596. "prompt": "color",
  2597. "key_desc": ["value"],
  2598. "values_desc": []
  2599. }, {
  2600. "name": "transparent_color",
  2601. "description": "This color becomes transparent when set to none",
  2602. "guisection": "tab",
  2603. "gisprompt": True,
  2604. "prompt": "color",
  2605. "key_desc": ["value"],
  2606. "values_desc": []
  2607. }, {
  2608. "name": "multi",
  2609. "description": "A multiple selection",
  2610. 'default': u'red,green,blue',
  2611. 'gisprompt': False,
  2612. 'guisection': 'tab',
  2613. 'multiple': u'yes',
  2614. 'type': u'string',
  2615. 'value': '',
  2616. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2617. "key_desc": ["value"],
  2618. "values_desc": []
  2619. }, {
  2620. "name": "single",
  2621. "description": "A single multiple-choice selection",
  2622. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2623. "guisection": "tab",
  2624. "key_desc": ["value"],
  2625. "values_desc": []
  2626. }, {
  2627. "name": "large_multi",
  2628. "description": "A large multiple selection",
  2629. "gisprompt": False,
  2630. "multiple": "yes",
  2631. # values must be an array of strings
  2632. "values": utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
  2633. "key_desc": ["value"],
  2634. "values_desc": []
  2635. }, {
  2636. "name": "a_file",
  2637. "description": "A file selector",
  2638. "gisprompt": True,
  2639. "element": "file",
  2640. "key_desc": ["value"],
  2641. "values_desc": []
  2642. }
  2643. ]
  2644. task.flags = [{"name": "a",
  2645. "description": "Some flag, will appear in Main since it is required",
  2646. "required": True,
  2647. "value": False,
  2648. "suppress_required": False},
  2649. {"name": "b",
  2650. "description": "pre-filled flag, will appear in options since it is not required",
  2651. "value": True,
  2652. "suppress_required": False},
  2653. {"name": "hidden_flag",
  2654. "description": "hidden flag, should not be changeable",
  2655. "hidden": "yes",
  2656. "value": True,
  2657. "suppress_required": False}]
  2658. q = wx.LogNull()
  2659. GrassGUIApp(task).MainLoop()