forms.py 123 KB

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