forms.py 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357
  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-2012 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. from threading import Thread
  43. import Queue
  44. import re
  45. gisbase = os.getenv("GISBASE")
  46. if gisbase is None:
  47. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  48. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  49. wxbase = gisbase
  50. else:
  51. wxbase = os.path.join(gisbase, 'etc', 'gui', 'wxpython')
  52. sys.path.append(wxbase)
  53. from core import globalvar
  54. import wx
  55. try:
  56. import wx.lib.agw.flatnotebook as FN
  57. except ImportError:
  58. import wx.lib.flatnotebook as FN
  59. import wx.lib.colourselect as csel
  60. import wx.lib.filebrowsebutton as filebrowse
  61. from wx.lib.newevent import NewEvent
  62. try:
  63. import xml.etree.ElementTree as etree
  64. except ImportError:
  65. import elementtree.ElementTree as etree # Python <= 2.4
  66. from grass.script import core as grass
  67. from grass.script import task as gtask
  68. from gui_core.widgets import StaticWrapText, ScrolledPanel
  69. from gui_core.ghelp import HelpPanel
  70. from gui_core import gselect
  71. from core import gcmd
  72. from core import utils
  73. from core.settings import UserSettings
  74. from core.events import EVT_MAP_CREATED
  75. from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
  76. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  77. """!Hide some options in the GUI"""
  78. #_blackList = { 'enabled' : False,
  79. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  80. # 'flags' : ['z', 'overwrite']}}}
  81. _blackList = { 'enabled' : False,
  82. 'items' : {} }
  83. def text_beautify(someString , width = 70):
  84. """!Make really long texts shorter, clean up whitespace and remove
  85. trailing punctuation.
  86. """
  87. if width > 0:
  88. return escape_ampersand(string.strip(
  89. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  90. ".,;:"))
  91. else:
  92. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  93. def escape_ampersand(text):
  94. """!Escapes ampersands with additional ampersand for GUI"""
  95. return string.replace(text, "&", "&&")
  96. class UpdateThread(Thread):
  97. """!Update dialog widgets in the thread"""
  98. def __init__(self, parent, event, eventId, task):
  99. Thread.__init__(self)
  100. self.parent = parent
  101. self.event = event
  102. self.eventId = eventId
  103. self.task = task
  104. self.setDaemon(True)
  105. # list of functions which updates the dialog
  106. self.data = {}
  107. def run(self):
  108. # get widget id
  109. if not self.eventId:
  110. for p in self.task.params:
  111. if p.get('gisprompt', False) == False:
  112. continue
  113. prompt = p.get('element', '')
  114. if prompt == 'vector':
  115. name = p.get('name', '')
  116. if name in ('map', 'input'):
  117. self.eventId = p['wxId'][0]
  118. if self.eventId is None:
  119. return
  120. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  121. if not p or 'wxId-bind' not in p:
  122. return
  123. # is this check necessary?
  124. # get widget prompt
  125. # pType = p.get('prompt', '')
  126. # if not pType:
  127. # return
  128. # check for map/input parameter
  129. pMap = self.task.get_param('map', raiseError = False)
  130. if not pMap:
  131. pMap = self.task.get_param('input', raiseError = False)
  132. if pMap:
  133. map = pMap.get('value', '')
  134. else:
  135. map = None
  136. # avoid running db.describe several times
  137. cparams = dict()
  138. cparams[map] = { 'dbInfo' : None,
  139. 'layers' : None, }
  140. # update reference widgets
  141. for uid in p['wxId-bind']:
  142. win = self.parent.FindWindowById(uid)
  143. if not win:
  144. continue
  145. name = win.GetName()
  146. pBind = self.task.get_param(uid, element = 'wxId', raiseError = False)
  147. if pBind:
  148. pBind['value'] = ''
  149. # set appropriate types in t.* modules element selections
  150. if name == 'Select':
  151. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  152. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  153. self.data[win.GetParent().SetType] = {'etype': type_param.get('value')}
  154. # t.(un)register has one type for 'input', 'maps'
  155. if maps_param is not None:
  156. if maps_param['wxId'][0] != uid:
  157. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  158. self.data[win.GetParent().SetType] = {'etype': element_dict[type_param.get('value')]}
  159. map = layer = None
  160. driver = db = None
  161. if name in ('LayerSelect', 'ColumnSelect'):
  162. if p.get('element', '') == 'vector': # -> vector
  163. # get map name
  164. map = p.get('value', '')
  165. # get layer
  166. for bid in p['wxId-bind']:
  167. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  168. if not p:
  169. continue
  170. if p.get('element', '') == 'layer':
  171. layer = p.get('value', '')
  172. if layer != '':
  173. layer = p.get('value', '')
  174. else:
  175. layer = p.get('default', '')
  176. break
  177. elif p.get('element', '') == 'layer': # -> layer
  178. # get layer
  179. layer = p.get('value', '')
  180. if layer != '':
  181. layer = p.get('value', '')
  182. else:
  183. layer = p.get('default', '')
  184. # get map name
  185. pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  186. if pMapL:
  187. map = pMapL.get('value', '')
  188. if name == 'TableSelect' or \
  189. (name == 'ColumnSelect' and not map):
  190. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  191. if pDriver:
  192. driver = pDriver.get('value', '')
  193. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  194. if pDb:
  195. db = pDb.get('value', '')
  196. if name == 'ColumnSelect':
  197. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  198. if pTable:
  199. table = pTable.get('value', '')
  200. if name == 'LayerSelect':
  201. # determine format
  202. native = True
  203. for id in pMap['wxId']:
  204. winVec = self.parent.FindWindowById(id)
  205. if winVec.GetName() == 'VectorFormat' and \
  206. winVec.GetSelection() != 0:
  207. native = False
  208. break
  209. # TODO: update only if needed
  210. if native:
  211. if map:
  212. self.data[win.InsertLayers] = { 'vector' : map }
  213. else:
  214. self.data[win.InsertLayers] = { }
  215. else:
  216. if map:
  217. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  218. else:
  219. self.data[win.InsertLayers] = { }
  220. elif name == 'TableSelect':
  221. self.data[win.InsertTables] = { 'driver' : driver,
  222. 'database' : db }
  223. elif name == 'ColumnSelect':
  224. if map:
  225. if map in cparams:
  226. if not cparams[map]['dbInfo']:
  227. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  228. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  229. 'dbInfo' : cparams[map]['dbInfo'] }
  230. else: # table
  231. if driver and db:
  232. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  233. 'driver' : driver,
  234. 'database' : db }
  235. elif pTable:
  236. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  237. elif name == 'SubGroupSelect':
  238. self.data[win.Insert] = { 'group' : p.get('value', '')}
  239. elif name == 'LocationSelect':
  240. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  241. if pDbase:
  242. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  243. elif name == 'MapsetSelect':
  244. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  245. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  246. if pDbase and pLocation:
  247. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  248. 'location' : pLocation.get('value', '')}
  249. elif name == 'ProjSelect':
  250. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  251. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  252. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  253. if pDbase and pLocation and pMapset:
  254. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  255. 'location' : pLocation.get('value', ''),
  256. 'mapset' : pMapset.get('value', '')}
  257. def UpdateDialog(parent, event, eventId, task):
  258. return UpdateThread(parent, event, eventId, task)
  259. class UpdateQThread(Thread):
  260. """!Update dialog widgets in the thread"""
  261. requestId = 0
  262. def __init__(self, parent, requestQ, resultQ, **kwds):
  263. Thread.__init__(self, **kwds)
  264. self.parent = parent # cmdPanel
  265. self.setDaemon(True)
  266. self.requestQ = requestQ
  267. self.resultQ = resultQ
  268. self.start()
  269. def Update(self, callable, *args, **kwds):
  270. UpdateQThread.requestId += 1
  271. self.request = None
  272. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  273. return UpdateQThread.requestId
  274. def run(self):
  275. while True:
  276. requestId, callable, args, kwds = self.requestQ.get()
  277. self.request = callable(*args, **kwds)
  278. self.resultQ.put((requestId, self.request.run()))
  279. if self.request:
  280. event = wxUpdateDialog(data = self.request.data)
  281. wx.PostEvent(self.parent, event)
  282. class TaskFrame(wx.Frame):
  283. """!This is the Frame containing the dialog for options input.
  284. The dialog is organized in a notebook according to the guisections
  285. defined by each GRASS command.
  286. If run with a parent, it may Apply, Ok or Cancel; the latter two
  287. close the dialog. The former two trigger a callback.
  288. If run standalone, it will allow execution of the command.
  289. The command is checked and sent to the clipboard when clicking
  290. 'Copy'.
  291. """
  292. def __init__(self, parent, giface, task_description, id = wx.ID_ANY,
  293. get_dcmd = None, layer = None,
  294. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  295. self.get_dcmd = get_dcmd
  296. self.layer = layer
  297. self.task = task_description
  298. self.parent = parent # LayerTree | Modeler | None | ...
  299. self._giface = giface
  300. if parent and parent.GetName() == 'Modeler':
  301. self.modeler = self.parent
  302. else:
  303. self.modeler = None
  304. # module name + keywords
  305. if self.task.name.split('.')[-1] in ('py', 'sh'):
  306. title = str(self.task.name.rsplit('.',1)[0])
  307. else:
  308. title = self.task.name
  309. try:
  310. if self.task.keywords != ['']:
  311. title += " [" + ', '.join(self.task.keywords) + "]"
  312. except ValueError:
  313. pass
  314. wx.Frame.__init__(self, parent = parent, id = id, title = title,
  315. name = "MainFrame", style = style, **kwargs)
  316. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  317. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  318. # statusbar
  319. self.CreateStatusBar()
  320. # icon
  321. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  322. guisizer = wx.BoxSizer(wx.VERTICAL)
  323. # set apropriate output window
  324. if self.parent:
  325. self.standalone = False
  326. else:
  327. self.standalone = True
  328. # logo + description
  329. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  330. # GRASS logo
  331. self.logo = wx.StaticBitmap(parent = self.panel,
  332. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  333. 'grass_form.png'),
  334. type = wx.BITMAP_TYPE_PNG))
  335. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  336. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  337. # add module description
  338. if self.task.label:
  339. module_desc = self.task.label + ' ' + self.task.description
  340. else:
  341. module_desc = self.task.description
  342. self.description = StaticWrapText(parent = self.panel,
  343. label = module_desc)
  344. topsizer.Add(item = self.description, proportion = 1, border = 5,
  345. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  346. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  347. self.panel.SetSizerAndFit(guisizer)
  348. self.Layout()
  349. # notebooks
  350. self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
  351. frame = self)
  352. self._gconsole = self.notebookpanel._gconsole
  353. self.goutput = self.notebookpanel.goutput
  354. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  355. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  356. # status bar
  357. status_text = _("Enter parameters for '") + self.task.name + "'"
  358. try:
  359. self.task.get_cmd()
  360. self.updateValuesHook()
  361. except ValueError:
  362. self.SetStatusText(status_text)
  363. # buttons
  364. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  365. # cancel
  366. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  367. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  368. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  369. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  370. if self.get_dcmd is not None: # A callback has been set up
  371. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  372. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  373. btn_ok.SetDefault()
  374. btnsizer.Add(item = btn_apply, proportion = 0,
  375. flag = wx.ALL | wx.ALIGN_CENTER,
  376. border = 10)
  377. btnsizer.Add(item = btn_ok, proportion = 0,
  378. flag = wx.ALL | wx.ALIGN_CENTER,
  379. border = 10)
  380. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  381. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  382. else: # We're standalone
  383. # run
  384. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  385. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  386. self.btn_run.SetDefault()
  387. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  388. # copy
  389. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY)
  390. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  391. btnsizer.Add(item = self.btn_run, proportion = 0,
  392. flag = wx.ALL | wx.ALIGN_CENTER,
  393. border = 10)
  394. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  395. flag = wx.ALL | wx.ALIGN_CENTER,
  396. border = 10)
  397. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  398. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  399. # help
  400. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  401. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  402. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  403. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  404. self.btn_help.Hide()
  405. # add help button
  406. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  407. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  408. border = 30)
  409. if self.parent and not self.modeler:
  410. addLayer = False
  411. for p in self.task.params:
  412. if p.get('age', 'old') == 'new' and \
  413. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  414. addLayer = True
  415. if addLayer:
  416. # add newly created map into layer tree
  417. self.addbox = wx.CheckBox(parent = self.panel,
  418. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  419. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  420. guisizer.Add(item = self.addbox, proportion = 0,
  421. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  422. border = 5)
  423. hasNew = False
  424. for p in self.task.params:
  425. if p.get('age', 'old') == 'new':
  426. hasNew = True
  427. break
  428. if self.get_dcmd is None and hasNew:
  429. # close dialog when command is terminated
  430. self.closebox = wx.CheckBox(parent = self.panel,
  431. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  432. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  433. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  434. "Change this settings in Preferences dialog ('Command' tab)."))
  435. guisizer.Add(item = self.closebox, proportion = 0,
  436. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  437. border = 5)
  438. # bindings
  439. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  440. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  441. self.Bind(EVT_MAP_CREATED, self.OnMapCreated)
  442. # do layout
  443. # called automatically by SetSizer()
  444. self.panel.SetAutoLayout(True)
  445. self.panel.SetSizerAndFit(guisizer)
  446. sizeFrame = self.GetBestSize()
  447. self.SetMinSize(sizeFrame)
  448. if hasattr(self, "closebox"):
  449. scale = 0.33
  450. else:
  451. scale = 0.50
  452. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  453. self.notebookpanel.constrained_size[1])))
  454. # thread to update dialog
  455. # create queues
  456. self.requestQ = Queue.Queue()
  457. self.resultQ = Queue.Queue()
  458. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  459. self.Layout()
  460. # keep initial window size limited for small screens
  461. width, height = self.GetSizeTuple()
  462. self.SetSize(wx.Size(min(width, 650),
  463. min(height, 500)))
  464. # fix goutput's pane size (required for Mac OSX)
  465. if self.goutput:
  466. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  467. def updateValuesHook(self, event = None):
  468. """!Update status bar data"""
  469. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  470. if event:
  471. event.Skip()
  472. def OnKeyUp(self, event):
  473. """!Key released (check hot-keys)"""
  474. try:
  475. kc = chr(event.GetKeyCode())
  476. except ValueError:
  477. event.Skip()
  478. return
  479. if not event.ControlDown():
  480. event.Skip()
  481. return
  482. if kc == 'Q':
  483. self.OnCancel(None)
  484. elif kc == 'S':
  485. self.OnAbort(None)
  486. elif kc == 'H':
  487. self.OnHelp(None)
  488. elif kc == 'R':
  489. self.OnRun(None)
  490. elif kc == 'C':
  491. self.OnCopy(None)
  492. event.Skip()
  493. def OnDone(self, cmd, returncode):
  494. """!This function is launched from OnRun() when command is
  495. finished
  496. @param returncode command's return code (0 for success)
  497. """
  498. if hasattr(self, "btn_cancel"):
  499. self.btn_cancel.Enable(True)
  500. if hasattr(self, "btn_clipboard"):
  501. self.btn_clipboard.Enable(True)
  502. if hasattr(self, "btn_help"):
  503. self.btn_help.Enable(True)
  504. if hasattr(self, "btn_run"):
  505. self.btn_run.Enable(True)
  506. if hasattr(self, "get_dcmd") and \
  507. self.get_dcmd is None and \
  508. hasattr(self, "closebox") and \
  509. self.closebox.IsChecked() and \
  510. (returncode == 0):
  511. # was closed also when aborted but better is leave it open
  512. wx.FutureCall(2000, self.Close)
  513. def OnMapCreated(self, event):
  514. if hasattr(self, "addbox") and self.addbox.IsChecked():
  515. event.add = True
  516. else:
  517. event.add = False
  518. event.Skip()
  519. def OnOK(self, event):
  520. """!OK button pressed"""
  521. cmd = self.OnApply(event)
  522. if cmd is not None and self.get_dcmd is not None:
  523. self.OnCancel(event)
  524. def OnApply(self, event):
  525. """!Apply the command"""
  526. if self.modeler:
  527. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  528. else:
  529. cmd = self.createCmd()
  530. if cmd is not None and self.get_dcmd is not None:
  531. # return d.* command to layer tree for rendering
  532. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  533. "flags" : self.task.flags},
  534. self)
  535. # echo d.* command to output console
  536. # self.parent.writeDCommand(cmd)
  537. return cmd
  538. def OnRun(self, event):
  539. """!Run the command"""
  540. cmd = self.createCmd()
  541. if not cmd or len(cmd) < 1:
  542. return
  543. ret = 0
  544. if self.standalone or cmd[0][0:2] != "d.":
  545. # Send any non-display command to parent window (probably wxgui.py)
  546. # put to parents switch to 'Command output'
  547. self.notebookpanel.notebook.SetSelectionByName('output')
  548. try:
  549. if self.task.path:
  550. cmd[0] = self.task.path # full path
  551. ret = self._gconsole.RunCmd(cmd, onDone = self.OnDone)
  552. except AttributeError, e:
  553. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  554. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  555. else:
  556. gcmd.Command(cmd)
  557. if ret != 0:
  558. self.notebookpanel.notebook.SetSelection(0)
  559. return
  560. # update buttons status
  561. for btn in (self.btn_run,
  562. self.btn_cancel,
  563. self.btn_clipboard,
  564. self.btn_help):
  565. btn.Enable(False)
  566. def OnAbort(self, event):
  567. """!Abort running command"""
  568. from core.gconsole import wxCmdAbort
  569. event = wxCmdAbort(aborted = True)
  570. wx.PostEvent(self._gconsole, event)
  571. def OnCopy(self, event):
  572. """!Copy the command"""
  573. cmddata = wx.TextDataObject()
  574. # list -> string
  575. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  576. cmddata.SetText(cmdstring)
  577. if wx.TheClipboard.Open():
  578. # wx.TheClipboard.UsePrimarySelection(True)
  579. wx.TheClipboard.SetData(cmddata)
  580. wx.TheClipboard.Close()
  581. self.SetStatusText(_("'%s' copied to clipboard") % \
  582. (cmdstring))
  583. def OnCancel(self, event):
  584. """!Cancel button pressed"""
  585. self.MakeModal(False)
  586. if self.get_dcmd and \
  587. self.parent and \
  588. self.parent.GetName() in ('LayerTree',
  589. 'MapWindow'):
  590. # display decorations and
  591. # pressing OK or cancel after setting layer properties
  592. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  593. or len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) >= 1:
  594. self.Hide()
  595. # canceled layer with nothing set
  596. elif len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) < 1:
  597. self.parent.Delete(self.layer)
  598. self.Destroy()
  599. else:
  600. # cancel for non-display commands
  601. self.Destroy()
  602. def OnHelp(self, event):
  603. """!Show manual page (switch to the 'Manual' notebook page)"""
  604. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  605. self.notebookpanel.notebook.SetSelectionByName('manual')
  606. self.notebookpanel.OnPageChange(None)
  607. if event:
  608. event.Skip()
  609. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  610. """!Create command string (python list)"""
  611. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  612. ignoreRequired = ignoreRequired)
  613. class CmdPanel(wx.Panel):
  614. """!A panel containing a notebook dividing in tabs the different
  615. guisections of the GRASS cmd.
  616. """
  617. def __init__(self, parent, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
  618. if frame:
  619. self.parent = frame
  620. else:
  621. self.parent = parent
  622. self.task = task
  623. self._giface = giface
  624. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  625. # Determine tab layout
  626. sections = []
  627. is_section = {}
  628. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  629. self.label_id = [] # wrap titles on resize
  630. self.Bind(wx.EVT_SIZE, self.OnSize)
  631. for task in not_hidden:
  632. if task.get('required', False):
  633. # All required go into Main, even if they had defined another guisection
  634. task['guisection'] = _('Required')
  635. if task.get('guisection','') == '':
  636. # Undefined guisections end up into Options
  637. task['guisection'] = _('Optional')
  638. if task['guisection'] not in is_section:
  639. # We do it like this to keep the original order, except for Main which goes first
  640. is_section[task['guisection']] = 1
  641. sections.append(task['guisection'])
  642. else:
  643. is_section[ task['guisection'] ] += 1
  644. del is_section
  645. # 'Required' tab goes first, 'Optional' as the last one
  646. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  647. if content in sections:
  648. idx = sections.index(content)
  649. sections[idx:idx+1] = []
  650. sections[newidx:newidx] = [content]
  651. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  652. # build notebook
  653. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  654. if style == 0: # basic top
  655. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  656. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  657. elif style == 1: # basic left
  658. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  659. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  660. elif style == 2: # fancy green
  661. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  662. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  663. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  664. elif style == 3:
  665. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  666. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  667. self.notebook.Refresh()
  668. tab = {}
  669. tabsizer = {}
  670. for section in sections:
  671. tab[section] = ScrolledPanel(parent = self.notebook)
  672. tab[section].SetScrollRate(10, 10)
  673. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  674. #
  675. # flags
  676. #
  677. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  678. for f in visible_flags:
  679. which_sizer = tabsizer[ f['guisection'] ]
  680. which_panel = tab[ f['guisection'] ]
  681. # if label is given: description -> tooltip
  682. if f.get('label','') != '':
  683. title = text_beautify(f['label'])
  684. tooltip = text_beautify(f['description'], width = -1)
  685. else:
  686. title = text_beautify(f['description'])
  687. tooltip = None
  688. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  689. rtitle_txt = wx.StaticText(parent = which_panel,
  690. label = '(' + f['name'] + ')')
  691. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  692. self.label_id.append(chk.GetId())
  693. if tooltip:
  694. chk.SetToolTipString(tooltip)
  695. chk.SetValue(f.get('value', False))
  696. title_sizer.Add(item = chk, proportion = 1,
  697. flag = wx.EXPAND)
  698. title_sizer.Add(item = rtitle_txt, proportion = 0,
  699. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  700. which_sizer.Add(item = title_sizer, proportion = 0,
  701. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  702. f['wxId'] = [ chk.GetId(), ]
  703. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  704. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  705. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  706. label = _("Parameterized in model"))
  707. parChk.SetName('ModelParam')
  708. parChk.SetValue(f.get('parameterized', False))
  709. if 'wxId' in f:
  710. f['wxId'].append(parChk.GetId())
  711. else:
  712. f['wxId'] = [ parChk.GetId() ]
  713. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  714. which_sizer.Add(item = parChk, proportion = 0,
  715. flag = wx.LEFT, border = 20)
  716. if f['name'] in ('verbose', 'quiet'):
  717. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  718. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  719. if f['name'] == vq:
  720. chk.SetValue(True)
  721. f['value'] = True
  722. elif f['name'] == 'overwrite' and 'value' not in f:
  723. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  724. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  725. #
  726. # parameters
  727. #
  728. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  729. try:
  730. first_param = visible_params[0]
  731. except IndexError:
  732. first_param = None
  733. for p in visible_params:
  734. which_sizer = tabsizer[p['guisection']]
  735. which_panel = tab[p['guisection']]
  736. # if label is given -> label and description -> tooltip
  737. # otherwise description -> lavel
  738. if p.get('label','') != '':
  739. title = text_beautify(p['label'])
  740. tooltip = text_beautify(p['description'], width = -1)
  741. else:
  742. title = text_beautify(p['description'])
  743. tooltip = None
  744. prompt = p.get('prompt', '')
  745. # text style (required -> bold)
  746. if not p.get('required', False):
  747. text_style = wx.FONTWEIGHT_NORMAL
  748. else:
  749. text_style = wx.FONTWEIGHT_BOLD
  750. # title sizer (description, name, type)
  751. if (len(p.get('values', [])) > 0) and \
  752. p.get('multiple', False) and \
  753. p.get('gisprompt', False) == False and \
  754. p.get('type', '') == 'string':
  755. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  756. else:
  757. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  758. title_txt = wx.StaticText(parent = which_panel)
  759. if p['key_desc']:
  760. ltype = ','.join(p['key_desc'])
  761. else:
  762. ltype = p['type']
  763. rtitle_txt = wx.StaticText(parent = which_panel,
  764. label = '(' + p['name'] + '=' + ltype + ')')
  765. title_sizer.Add(item = title_txt, proportion = 1,
  766. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  767. title_sizer.Add(item = rtitle_txt, proportion = 0,
  768. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  769. which_sizer.Add(item = title_sizer, proportion = 0,
  770. flag = wx.EXPAND)
  771. self.label_id.append(title_txt.GetId())
  772. # title expansion
  773. if p.get('multiple', False) and len(p.get('values','')) == 0:
  774. title = _("[multiple]") + " " + title
  775. if p.get('value','') == '' :
  776. p['value'] = p.get('default','')
  777. if (len(p.get('values', [])) > 0):
  778. valuelist = map(str, p.get('values',[]))
  779. valuelist_desc = map(unicode, p.get('values_desc',[]))
  780. if p.get('multiple', False) and \
  781. p.get('gisprompt',False) == False and \
  782. p.get('type', '') == 'string':
  783. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  784. if valuelist_desc:
  785. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  786. else:
  787. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  788. isEnabled = {}
  789. # copy default values
  790. if p['value'] == '':
  791. p['value'] = p.get('default', '')
  792. for defval in p.get('value', '').split(','):
  793. isEnabled[ defval ] = 'yes'
  794. # for multi checkboxes, this is an array of all wx IDs
  795. # for each individual checkbox
  796. p[ 'wxId' ] = list()
  797. idx = 0
  798. for val in valuelist:
  799. try:
  800. label = valuelist_desc[idx]
  801. except IndexError:
  802. label = val
  803. chkbox = wx.CheckBox(parent = which_panel,
  804. label = text_beautify(label))
  805. p[ 'wxId' ].append(chkbox.GetId())
  806. if val in isEnabled:
  807. chkbox.SetValue(True)
  808. hSizer.Add(item = chkbox, proportion = 0,
  809. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  810. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  811. idx += 1
  812. which_sizer.Add(item = hSizer, proportion = 0,
  813. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  814. elif p.get('gisprompt', False) == False:
  815. if len(valuelist) == 1: # -> textctrl
  816. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  817. str(valuelist[0])))
  818. if p.get('type', '') == 'integer' and \
  819. not p.get('multiple', False):
  820. # for multiple integers use textctrl instead of spinsctrl
  821. try:
  822. minValue, maxValue = map(int, valuelist[0].split('-'))
  823. except ValueError:
  824. minValue = -1e6
  825. maxValue = 1e6
  826. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  827. min = minValue, max = maxValue)
  828. txt2.SetName("SpinCtrl")
  829. style = wx.BOTTOM | wx.LEFT
  830. else:
  831. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  832. txt2.SetName("TextCtrl")
  833. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  834. value = self._getValue(p)
  835. # parameter previously set
  836. if value:
  837. if txt2.GetName() == "SpinCtrl":
  838. txt2.SetValue(int(value))
  839. else:
  840. txt2.SetValue(value)
  841. which_sizer.Add(item = txt2, proportion = 0,
  842. flag = style, border = 5)
  843. p['wxId'] = [ txt2.GetId(), ]
  844. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  845. else:
  846. title_txt.SetLabel(title + ':')
  847. value = self._getValue(p)
  848. if p['name'] == 'icon': # symbols
  849. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  850. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  851. bitmap = bitmap)
  852. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  853. iconLabel.SetLabel(value)
  854. p['value'] = value
  855. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  856. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  857. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  858. this_sizer.Add(item = bb, proportion = 0,
  859. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  860. this_sizer.Add(item = iconLabel, proportion = 0,
  861. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  862. which_sizer.Add(item = this_sizer, proportion = 0,
  863. flag = wx.ADJUST_MINSIZE, border = 0)
  864. else:
  865. # list of values (combo)
  866. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  867. size = globalvar.DIALOG_COMBOBOX_SIZE,
  868. choices = valuelist, style = wx.CB_DROPDOWN)
  869. if value:
  870. cb.SetValue(value) # parameter previously set
  871. which_sizer.Add(item = cb, proportion = 0,
  872. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  873. p['wxId'] = [cb.GetId(),]
  874. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  875. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  876. if p.get('guidependency', ''):
  877. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  878. # text entry
  879. if (p.get('type','string') in ('string','integer','float')
  880. and len(p.get('values',[])) == 0
  881. and p.get('gisprompt',False) == False
  882. and p.get('prompt','') != 'color'):
  883. title_txt.SetLabel(title + ':')
  884. if p.get('multiple', False) or \
  885. p.get('type', 'string') == 'string' or \
  886. len(p.get('key_desc', [])) > 1:
  887. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  888. value = self._getValue(p)
  889. if value:
  890. # parameter previously set
  891. txt3.SetValue(str(value))
  892. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  893. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  894. else:
  895. minValue = -1e9
  896. maxValue = 1e9
  897. if p.get('type', '') == 'integer':
  898. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  899. size = globalvar.DIALOG_SPIN_SIZE,
  900. min = minValue, max = maxValue)
  901. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  902. value = self._getValue(p)
  903. if value:
  904. txt3.SetValue(int(value)) # parameter previously set
  905. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  906. else:
  907. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  908. validator = FloatValidator())
  909. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  910. value = self._getValue(p)
  911. if value:
  912. txt3.SetValue(str(value)) # parameter previously set
  913. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  914. which_sizer.Add(item = txt3, proportion = 0,
  915. flag = style, border = 5)
  916. p['wxId'] = [ txt3.GetId(), ]
  917. #
  918. # element selection tree combobox (maps, icons, regions, etc.)
  919. #
  920. if p.get('gisprompt', False):
  921. title_txt.SetLabel(title + ':')
  922. # GIS element entry
  923. if p.get('prompt','') not in ('color',
  924. 'color_none',
  925. 'subgroup',
  926. 'dbdriver',
  927. 'dbname',
  928. 'dbtable',
  929. 'dbcolumn',
  930. 'layer',
  931. 'layer_all',
  932. 'location',
  933. 'mapset',
  934. 'dbase',
  935. 'coords') and \
  936. p.get('element', '') not in ('file', 'dir'):
  937. multiple = p.get('multiple', False)
  938. if p.get('age', '') == 'new':
  939. mapsets = [grass.gisenv()['MAPSET'],]
  940. else:
  941. mapsets = None
  942. if self.task.name in ('r.proj', 'v.proj') \
  943. and p.get('name', '') == 'input':
  944. if self.task.name == 'r.proj':
  945. isRaster = True
  946. else:
  947. isRaster = False
  948. selection = gselect.ProjSelect(parent = which_panel,
  949. isRaster = isRaster)
  950. p['wxId'] = [ selection.GetId(), ]
  951. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  952. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  953. else:
  954. elem = p.get('element', None)
  955. # hack for t.* modules
  956. if elem in ('stds', 'map'):
  957. orig_elem = elem
  958. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  959. if type_param:
  960. elem = type_param.get('default', None)
  961. # for t.(un)register:
  962. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  963. if maps_param and orig_elem == 'stds':
  964. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  965. elem = element_dict[type_param.get('default')]
  966. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  967. size = globalvar.DIALOG_GSELECT_SIZE,
  968. type = elem,
  969. multiple = multiple, nmaps = len(p.get('key_desc', [])),
  970. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old')
  971. value = self._getValue(p)
  972. if value:
  973. selection.SetValue(value)
  974. formatSelector = True
  975. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  976. # we target the textctl here
  977. textWin = selection.GetTextCtrl()
  978. p['wxId'] = [ textWin.GetId(), ]
  979. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  980. if prompt == 'vector':
  981. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  982. # if formatSelector and p.get('age', 'old') == 'old':
  983. # # OGR supported (read-only)
  984. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  985. # self.hsizer.Add(item = selection,
  986. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  987. # border = 5)
  988. # # format (native / ogr)
  989. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  990. # label = " %s " % _("Format"),
  991. # style = wx.RA_SPECIFY_ROWS,
  992. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  993. # if p.get('value', '').lower().rfind('@ogr') > -1:
  994. # rbox.SetSelection(1)
  995. # rbox.SetName('VectorFormat')
  996. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  997. # self.hsizer.Add(item = rbox,
  998. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  999. # wx.RIGHT | wx.ALIGN_TOP,
  1000. # border = 5)
  1001. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1002. # default = 'dir',
  1003. # exclude = ['file'])
  1004. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1005. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1006. # ogrSelection.SetName('OgrSelect')
  1007. # ogrSelection.Hide()
  1008. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1009. # p['wxId'].append(rbox.GetId())
  1010. # p['wxId'].append(ogrSelection.GetId())
  1011. # for win in ogrSelection.GetDsnWin():
  1012. # p['wxId'].append(win.GetId())
  1013. # else:
  1014. which_sizer.Add(item = selection, proportion = 0,
  1015. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1016. border = 5)
  1017. elif prompt == 'group':
  1018. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1019. which_sizer.Add(item = selection, proportion = 0,
  1020. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1021. border = 5)
  1022. else:
  1023. which_sizer.Add(item = selection, proportion = 0,
  1024. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1025. border = 5)
  1026. # subgroup
  1027. elif prompt == 'subgroup':
  1028. selection = gselect.SubGroupSelect(parent = which_panel)
  1029. p['wxId'] = [ selection.GetId() ]
  1030. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1031. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1032. which_sizer.Add(item = selection, proportion = 0,
  1033. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1034. border = 5)
  1035. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1036. elif prompt in ('dbdriver',
  1037. 'dbname',
  1038. 'dbtable',
  1039. 'dbcolumn',
  1040. 'layer',
  1041. 'layer_all',
  1042. 'location',
  1043. 'mapset',
  1044. 'dbase'):
  1045. if p.get('multiple', 'no') == 'yes':
  1046. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1047. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1048. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1049. else:
  1050. value = self._getValue(p)
  1051. if prompt in ('layer', 'layer_all'):
  1052. if prompt == 'layer_all':
  1053. all = True
  1054. else:
  1055. all = False
  1056. if p.get('age', 'old') == 'old':
  1057. win = gselect.LayerSelect(parent = which_panel,
  1058. all = all,
  1059. default = p['default'])
  1060. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1061. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1062. win.SetValue(str(value)) # default or previously set value
  1063. else:
  1064. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1065. min = 1, max = 100, initial = int(p['default']))
  1066. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1067. win.SetValue(int(value)) # default or previously set value
  1068. p['wxId'] = [ win.GetId() ]
  1069. elif prompt == 'dbdriver':
  1070. win = gselect.DriverSelect(parent = which_panel,
  1071. choices = p.get('values', []),
  1072. value = value)
  1073. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1074. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1075. elif prompt == 'dbname':
  1076. win = gselect.DatabaseSelect(parent = which_panel,
  1077. value = value)
  1078. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1079. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1080. elif prompt == 'dbtable':
  1081. if p.get('age', 'old') == 'old':
  1082. win = gselect.TableSelect(parent = which_panel)
  1083. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1084. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1085. else:
  1086. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1087. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1088. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1089. elif prompt == 'dbcolumn':
  1090. win = gselect.ColumnSelect(parent = which_panel,
  1091. value = value,
  1092. param = p)
  1093. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1094. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1095. elif prompt == 'location':
  1096. win = gselect.LocationSelect(parent = which_panel,
  1097. value = value)
  1098. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1099. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1100. elif prompt == 'mapset':
  1101. if p.get('age', 'old') == 'old':
  1102. new = False
  1103. else:
  1104. new = True
  1105. win = gselect.MapsetSelect(parent = which_panel,
  1106. value = value, new = new)
  1107. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1108. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1109. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1110. elif prompt == 'dbase':
  1111. win = gselect.DbaseSelect(parent = which_panel,
  1112. changeCallback = self.OnSetValue)
  1113. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1114. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1115. if 'wxId' not in p:
  1116. try:
  1117. p['wxId'] = [ win.GetId(), ]
  1118. except AttributeError:
  1119. pass
  1120. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1121. if prompt == 'dbname':
  1122. flags |= wx.EXPAND
  1123. which_sizer.Add(item = win, proportion = 0,
  1124. flag = flags, border = 5)
  1125. # color entry
  1126. elif prompt in ('color',
  1127. 'color_none'):
  1128. default_color = (200,200,200)
  1129. label_color = _("Select Color")
  1130. if p.get('default','') != '':
  1131. default_color, label_color = utils.color_resolve(p['default'])
  1132. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1133. default_color, label_color = utils.color_resolve(p['value'])
  1134. if prompt == 'color_none':
  1135. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1136. else:
  1137. this_sizer = which_sizer
  1138. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1139. label = label_color, colour = default_color,
  1140. pos = wx.DefaultPosition, size = (150,-1))
  1141. this_sizer.Add(item = btn_colour, proportion = 0,
  1142. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1143. # For color selectors, this is a two-member array, holding the IDs of
  1144. # the selector proper and either a "transparent" button or None
  1145. p['wxId'] = [btn_colour.GetId(),]
  1146. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1147. if prompt == 'color_none':
  1148. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1149. if p.get('value','') == "none":
  1150. none_check.SetValue(True)
  1151. else:
  1152. none_check.SetValue(False)
  1153. this_sizer.Add(item = none_check, proportion = 0,
  1154. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1155. which_sizer.Add(this_sizer)
  1156. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1157. p['wxId'].append(none_check.GetId())
  1158. else:
  1159. p['wxId'].append(None)
  1160. # file selector
  1161. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1162. if p.get('age', 'new') == 'new':
  1163. fmode = wx.SAVE
  1164. else:
  1165. fmode = wx.OPEN
  1166. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1167. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1168. dialogTitle = _('Choose %s') % \
  1169. p.get('description',_('File')),
  1170. buttonText = _('Browse'),
  1171. startDirectory = os.getcwd(), fileMode = fmode,
  1172. changeCallback = self.OnSetValue)
  1173. value = self._getValue(p)
  1174. if value:
  1175. fbb.SetValue(value) # parameter previously set
  1176. which_sizer.Add(item = fbb, proportion = 0,
  1177. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1178. # A file browse button is a combobox with two children:
  1179. # a textctl and a button;
  1180. # we have to target the button here
  1181. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1182. if p.get('age', 'new') == 'old' and \
  1183. p.get('prompt', 'input') == 'input' and \
  1184. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1185. # widget for interactive input
  1186. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1187. style = wx.TE_MULTILINE,
  1188. size = (-1, 75))
  1189. if p.get('value', '') and os.path.isfile(p['value']):
  1190. f = open(p['value'])
  1191. ifbb.SetValue(''.join(f.readlines()))
  1192. f.close()
  1193. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1194. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1195. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1196. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVEAS)
  1197. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1198. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1199. label = _('or enter values interactively')),
  1200. proportion = 0,
  1201. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1202. which_sizer.Add(item = ifbb, proportion = 1,
  1203. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1204. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1205. btnSizer.Add(item = btnLoad, proportion = 0,
  1206. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1207. btnSizer.Add(item = btnSave, proportion = 0,
  1208. flag = wx.ALIGN_RIGHT)
  1209. which_sizer.Add(item = btnSizer, proportion = 0,
  1210. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1211. p['wxId'].append(ifbb.GetId())
  1212. p['wxId'].append(btnLoad.GetId())
  1213. p['wxId'].append(btnSave.GetId())
  1214. # directory selector
  1215. elif p.get('prompt','') != 'color' and p.get('element', '') == 'dir':
  1216. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1217. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1218. dialogTitle = _('Choose %s') % \
  1219. p.get('description', _('Directory')),
  1220. buttonText = _('Browse'),
  1221. startDirectory = os.getcwd(),
  1222. changeCallback = self.OnSetValue)
  1223. value = self._getValue(p)
  1224. if value:
  1225. fbb.SetValue(value) # parameter previously set
  1226. which_sizer.Add(item = fbb, proportion = 0,
  1227. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1228. # A file browse button is a combobox with two children:
  1229. # a textctl and a button;
  1230. # we have to target the button here
  1231. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1232. # interactive inserting of coordinates from map window
  1233. elif prompt == 'coords':
  1234. # interactive inserting if layer manager is accessible
  1235. if self._giface:
  1236. win = gselect.CoordinatesSelect(parent = which_panel,
  1237. giface = self._giface,
  1238. multiple = p.get('multiple', False),
  1239. param = p)
  1240. p['wxId'] = [win.GetTextWin().GetId()]
  1241. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1242. # normal text field
  1243. else:
  1244. win = wx.TextCtrl(parent = which_panel)
  1245. p['wxId'] = [win.GetId()]
  1246. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1247. which_sizer.Add(item = win,
  1248. proportion = 0,
  1249. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1250. border = 5)
  1251. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1252. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1253. label = _("Parameterized in model"))
  1254. parChk.SetName('ModelParam')
  1255. parChk.SetValue(p.get('parameterized', False))
  1256. if 'wxId' in p:
  1257. p['wxId'].append(parChk.GetId())
  1258. else:
  1259. p['wxId'] = [ parChk.GetId() ]
  1260. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1261. which_sizer.Add(item = parChk, proportion = 0,
  1262. flag = wx.LEFT, border = 20)
  1263. if title_txt is not None:
  1264. # create tooltip if given
  1265. if len(p['values_desc']) > 0:
  1266. if tooltip:
  1267. tooltip += 2 * os.linesep
  1268. else:
  1269. tooltip = ''
  1270. if len(p['values']) == len(p['values_desc']):
  1271. for i in range(len(p['values'])):
  1272. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1273. tooltip.strip(os.linesep)
  1274. if tooltip:
  1275. title_txt.SetToolTipString(tooltip)
  1276. if p == first_param:
  1277. if 'wxId' in p and len(p['wxId']) > 0:
  1278. win = self.FindWindowById(p['wxId'][0])
  1279. win.SetFocus()
  1280. #
  1281. # set widget relations for OnUpdateSelection
  1282. #
  1283. pMap = None
  1284. pLayer = []
  1285. pDriver = None
  1286. pDatabase = None
  1287. pTable = None
  1288. pColumn = []
  1289. pGroup = None
  1290. pSubGroup = None
  1291. pDbase = None
  1292. pLocation = None
  1293. pMapset = None
  1294. for p in self.task.params:
  1295. guidep = p.get('guidependency', '')
  1296. if guidep:
  1297. # fixed options dependency defined
  1298. options = guidep.split(',')
  1299. for opt in options:
  1300. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1301. if id:
  1302. if 'wxId-bind' not in p:
  1303. p['wxId-bind'] = list()
  1304. p['wxId-bind'] += pOpt['wxId']
  1305. continue
  1306. if p.get('gisprompt', False) == False:
  1307. continue
  1308. prompt = p.get('element', '')
  1309. if prompt in ('cell', 'vector'):
  1310. name = p.get('name', '')
  1311. if name in ('map', 'input'):
  1312. pMap = p
  1313. elif prompt == 'layer':
  1314. pLayer.append(p)
  1315. elif prompt == 'dbcolumn':
  1316. pColumn.append(p)
  1317. elif prompt == 'dbdriver':
  1318. pDriver = p
  1319. elif prompt == 'dbname':
  1320. pDatabase = p
  1321. elif prompt == 'dbtable':
  1322. pTable = p
  1323. elif prompt == 'group':
  1324. pGroup = p
  1325. elif prompt == 'subgroup':
  1326. pSubGroup = p
  1327. elif prompt == 'dbase':
  1328. pDbase = p
  1329. elif prompt == 'location':
  1330. pLocation = p
  1331. elif prompt == 'mapset':
  1332. pMapset = p
  1333. # collect ids
  1334. pColumnIds = []
  1335. for p in pColumn:
  1336. pColumnIds += p['wxId']
  1337. pLayerIds = []
  1338. for p in pLayer:
  1339. pLayerIds += p['wxId']
  1340. # set wxId-bindings
  1341. if pMap:
  1342. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1343. if pLayer:
  1344. pMap['wxId-bind'] += pLayerIds
  1345. if pLayer:
  1346. for p in pLayer:
  1347. p['wxId-bind'] = copy.copy(pColumnIds)
  1348. if pDriver and pTable:
  1349. pDriver['wxId-bind'] = pTable['wxId']
  1350. if pDatabase and pTable:
  1351. pDatabase['wxId-bind'] = pTable['wxId']
  1352. if pTable and pColumnIds:
  1353. pTable['wxId-bind'] = pColumnIds
  1354. if pGroup and pSubGroup:
  1355. pGroup['wxId-bind'] = pSubGroup['wxId']
  1356. if pDbase and pLocation:
  1357. pDbase['wxId-bind'] = pLocation['wxId']
  1358. if pLocation and pMapset:
  1359. pLocation['wxId-bind'] = pMapset['wxId']
  1360. if pLocation and pMapset and pMap:
  1361. pLocation['wxId-bind'] += pMap['wxId']
  1362. pMapset['wxId-bind'] = pMap['wxId']
  1363. #
  1364. # determine panel size
  1365. #
  1366. maxsizes = (0, 0)
  1367. for section in sections:
  1368. tab[section].SetSizer(tabsizer[section])
  1369. tabsizer[section].Fit(tab[section])
  1370. tab[section].Layout()
  1371. minsecsizes = tabsizer[section].GetSize()
  1372. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1373. # TODO: be less arbitrary with these 600
  1374. self.panelMinHeight = 100
  1375. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1376. for section in sections:
  1377. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1378. # add pages to notebook
  1379. imageList = wx.ImageList(16, 16)
  1380. self.notebook.AssignImageList(imageList)
  1381. for section in sections:
  1382. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1383. index = self.AddBitmapToImageList(section, imageList)
  1384. if index >= 0:
  1385. self.notebook.SetPageImage(section, index)
  1386. # are we running from command line?
  1387. ### add 'command output' tab regardless standalone dialog
  1388. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1389. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1390. from gui_core.goutput import GConsoleWindow
  1391. self._gconsole = GConsole(guiparent = self.notebook)
  1392. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1393. self._gconsole.Bind(EVT_CMD_RUN,
  1394. lambda event:
  1395. self._switchPageHandler(event = event, priority = 2))
  1396. self._gconsole.Bind(EVT_CMD_DONE,
  1397. lambda event:
  1398. self._switchPageHandler(event = event, priority = 3))
  1399. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1400. index = self.AddBitmapToImageList(section = 'output', imageList = imageList)
  1401. if index >= 0:
  1402. self.notebook.SetPageImage('output', index)
  1403. else:
  1404. self.goutput = None
  1405. self._gconsole = None
  1406. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.name)
  1407. if not self.manualTab.GetFile():
  1408. self.manualTab.Hide()
  1409. else:
  1410. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1411. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1412. if index >= 0:
  1413. self.notebook.SetPageImage('manual', index)
  1414. if self.manualTab.IsLoaded():
  1415. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1416. self.notebook.SetSelection(0)
  1417. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1418. self.SetSizer(panelsizer)
  1419. panelsizer.Fit(self.notebook)
  1420. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1421. def _getValue(self, p):
  1422. """!Get value or default value of given parameter
  1423. @param p parameter directory
  1424. """
  1425. if p.get('value', '') != '':
  1426. return p['value']
  1427. return p.get('default', '')
  1428. def OnFileLoad(self, event):
  1429. """!Load file to interactive input"""
  1430. me = event.GetId()
  1431. win = dict()
  1432. for p in self.task.params:
  1433. if 'wxId' in p and me in p['wxId']:
  1434. win['file'] = self.FindWindowById(p['wxId'][0])
  1435. win['text'] = self.FindWindowById(p['wxId'][1])
  1436. break
  1437. if not win:
  1438. return
  1439. path = win['file'].GetValue()
  1440. if not path:
  1441. gcmd.GMessage(parent = self,
  1442. message = _("Nothing to load."))
  1443. return
  1444. data = ''
  1445. f = open(path, "r")
  1446. try:
  1447. data = f.read()
  1448. finally:
  1449. f.close()
  1450. win['text'].SetValue(data)
  1451. def OnFileSave(self, event):
  1452. """!Save interactive input to the file"""
  1453. wId = event.GetId()
  1454. win = {}
  1455. for p in self.task.params:
  1456. if wId in p.get('wxId', []):
  1457. win['file'] = self.FindWindowById(p['wxId'][0])
  1458. win['text'] = self.FindWindowById(p['wxId'][1])
  1459. break
  1460. if not win:
  1461. return
  1462. text = win['text'].GetValue()
  1463. if not text:
  1464. gcmd.GMessage(parent = self,
  1465. message = _("Nothing to save."))
  1466. return
  1467. dlg = wx.FileDialog(parent = self,
  1468. message = _("Save input as..."),
  1469. defaultDir = os.getcwd(),
  1470. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1471. if dlg.ShowModal() == wx.ID_OK:
  1472. path = dlg.GetPath()
  1473. f = open(path, "w")
  1474. try:
  1475. f.write(text + os.linesep)
  1476. finally:
  1477. f.close()
  1478. win['file'].SetValue(path)
  1479. dlg.Destroy()
  1480. def OnFileText(self, event):
  1481. """File input interactively entered"""
  1482. text = event.GetString()
  1483. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1484. if not p:
  1485. return # should not happen
  1486. win = self.FindWindowById(p['wxId'][0])
  1487. if text:
  1488. filename = win.GetValue()
  1489. if not filename:
  1490. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1491. filename = grass.tempfile()
  1492. win.SetValue(filename)
  1493. f = open(filename, "w")
  1494. try:
  1495. f.write(text)
  1496. if text[-1] != os.linesep:
  1497. f.write(os.linesep)
  1498. finally:
  1499. f.close()
  1500. else:
  1501. win.SetValue('')
  1502. def OnVectorFormat(self, event):
  1503. """!Change vector format (native / ogr).
  1504. Currently unused.
  1505. """
  1506. sel = event.GetSelection()
  1507. idEvent = event.GetId()
  1508. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1509. if not p:
  1510. return # should not happen
  1511. # detect windows
  1512. winNative = None
  1513. winOgr = None
  1514. for id in p['wxId']:
  1515. if id == idEvent:
  1516. continue
  1517. name = self.FindWindowById(id).GetName()
  1518. if name == 'Select':
  1519. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1520. elif name == 'OgrSelect':
  1521. winOgr = self.FindWindowById(id)
  1522. # enable / disable widgets & update values
  1523. rbox = self.FindWindowByName('VectorFormat')
  1524. self.hsizer.Remove(rbox)
  1525. if sel == 0: # -> native
  1526. winOgr.Hide()
  1527. self.hsizer.Remove(winOgr)
  1528. self.hsizer.Add(item = winNative,
  1529. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1530. border = 5)
  1531. winNative.Show()
  1532. p['value'] = winNative.GetValue()
  1533. elif sel == 1: # -> OGR
  1534. sizer = wx.BoxSizer(wx.VERTICAL)
  1535. winNative.Hide()
  1536. self.hsizer.Remove(winNative)
  1537. sizer.Add(item = winOgr)
  1538. winOgr.Show()
  1539. p['value'] = winOgr.GetDsn()
  1540. self.hsizer.Add(item = sizer,
  1541. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1542. border = 5)
  1543. self.hsizer.Add(item = rbox,
  1544. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1545. wx.RIGHT | wx.ALIGN_TOP,
  1546. border = 5)
  1547. self.hsizer.Layout()
  1548. self.Layout()
  1549. self.OnUpdateValues()
  1550. self.OnUpdateSelection(event)
  1551. def OnUpdateDialog(self, event):
  1552. for fn, kwargs in event.data.iteritems():
  1553. fn(**kwargs)
  1554. self.parent.updateValuesHook()
  1555. def OnVerbosity(self, event):
  1556. """!Verbosity level changed"""
  1557. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1558. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1559. if event.IsChecked():
  1560. if event.GetId() == verbose.GetId():
  1561. if quiet.IsChecked():
  1562. quiet.SetValue(False)
  1563. self.task.get_flag('quiet')['value'] = False
  1564. else:
  1565. if verbose.IsChecked():
  1566. verbose.SetValue(False)
  1567. self.task.get_flag('verbose')['value'] = False
  1568. event.Skip()
  1569. def OnPageChange(self, event):
  1570. if not event:
  1571. sel = self.notebook.GetSelection()
  1572. else:
  1573. sel = event.GetSelection()
  1574. idx = self.notebook.GetPageIndexByName('manual')
  1575. if idx > -1 and sel == idx:
  1576. # calling LoadPage() is strangely time-consuming (only first call)
  1577. # FIXME: move to helpPage.__init__()
  1578. if not self.manualTab.IsLoaded():
  1579. wx.Yield()
  1580. self.manualTab.LoadPage()
  1581. self.Layout()
  1582. if event:
  1583. # skip is needed for wx.Notebook on Windows
  1584. event.Skip()
  1585. # this is needed for dialogs launched from layer manager
  1586. # event is somehow propagated?
  1587. event.StopPropagation()
  1588. def _switchPageHandler(self, event, priority):
  1589. self._switchPage(priority = priority)
  1590. event.Skip()
  1591. def _switchPage(self, priority):
  1592. """!Manages @c 'output' notebook page according to event priority."""
  1593. if priority == 1:
  1594. self.notebook.HighlightPageByName('output')
  1595. if priority >= 2:
  1596. self.notebook.SetSelectionByName('output')
  1597. if priority >= 3:
  1598. self.SetFocus()
  1599. self.Raise()
  1600. def OnColorChange(self, event):
  1601. myId = event.GetId()
  1602. for p in self.task.params:
  1603. if 'wxId' in p and myId in p['wxId']:
  1604. has_button = p['wxId'][1] is not None
  1605. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1606. p[ 'value' ] = 'none'
  1607. else:
  1608. colorchooser = wx.FindWindowById(p['wxId'][0])
  1609. new_color = colorchooser.GetValue()[:]
  1610. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1611. # under wx2.8.1
  1612. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1613. colorchooser.SetLabel(new_label)
  1614. colorchooser.SetColour(new_color)
  1615. colorchooser.Refresh()
  1616. p[ 'value' ] = colorchooser.GetLabel()
  1617. self.OnUpdateValues()
  1618. def OnUpdateValues(self, event = None):
  1619. """!If we were part of a richer interface, report back the
  1620. current command being built.
  1621. This method should be set by the parent of this panel if
  1622. needed. It's a hook, actually. Beware of what is 'self' in
  1623. the method def, though. It will be called with no arguments.
  1624. """
  1625. pass
  1626. def OnCheckBoxMulti(self, event):
  1627. """!Fill the values as a ','-separated string according to
  1628. current status of the checkboxes.
  1629. """
  1630. me = event.GetId()
  1631. theParam = None
  1632. for p in self.task.params:
  1633. if 'wxId' in p and me in p['wxId']:
  1634. theParam = p
  1635. myIndex = p['wxId'].index(me)
  1636. # Unpack current value list
  1637. currentValues = {}
  1638. for isThere in theParam.get('value', '').split(','):
  1639. currentValues[isThere] = 1
  1640. theValue = theParam['values'][myIndex]
  1641. if event.Checked():
  1642. currentValues[ theValue ] = 1
  1643. else:
  1644. del currentValues[ theValue ]
  1645. # Keep the original order, so that some defaults may be recovered
  1646. currentValueList = []
  1647. for v in theParam['values']:
  1648. if v in currentValues:
  1649. currentValueList.append(v)
  1650. # Pack it back
  1651. theParam['value'] = ','.join(currentValueList)
  1652. self.OnUpdateValues()
  1653. def OnSetValue(self, event):
  1654. """!Retrieve the widget value and set the task value field
  1655. accordingly.
  1656. Use for widgets that have a proper GetValue() method, i.e. not
  1657. for selectors.
  1658. """
  1659. myId = event.GetId()
  1660. me = wx.FindWindowById(myId)
  1661. name = me.GetName()
  1662. found = False
  1663. for porf in self.task.params + self.task.flags:
  1664. if 'wxId' not in porf:
  1665. continue
  1666. if myId in porf['wxId']:
  1667. found = True
  1668. break
  1669. if not found:
  1670. return
  1671. if name == 'GdalSelect':
  1672. porf['value'] = event.dsn
  1673. elif name == 'ModelParam':
  1674. porf['parameterized'] = me.IsChecked()
  1675. else:
  1676. porf['value'] = me.GetValue()
  1677. self.OnUpdateValues(event)
  1678. event.Skip()
  1679. def OnSetSymbol(self, event):
  1680. """!Shows dialog for symbol selection"""
  1681. myId = event.GetId()
  1682. for p in self.task.params:
  1683. if 'wxId' in p and myId in p['wxId']:
  1684. from gui_core.dialogs import SymbolDialog
  1685. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1686. currentSymbol = p['value'])
  1687. if dlg.ShowModal() == wx.ID_OK:
  1688. img = dlg.GetSelectedSymbolPath()
  1689. p['value'] = dlg.GetSelectedSymbolName()
  1690. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1691. label = wx.FindWindowById(p['wxId'][1])
  1692. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1693. label.SetLabel(p['value'])
  1694. self.OnUpdateValues(event)
  1695. dlg.Destroy()
  1696. def OnUpdateSelection(self, event):
  1697. """!Update dialog (layers, tables, columns, etc.)
  1698. """
  1699. if not hasattr(self.parent, "updateThread"):
  1700. if event:
  1701. event.Skip()
  1702. return
  1703. if event:
  1704. self.parent.updateThread.Update(UpdateDialog,
  1705. self,
  1706. event,
  1707. event.GetId(),
  1708. self.task)
  1709. else:
  1710. self.parent.updateThread.Update(UpdateDialog,
  1711. self,
  1712. None,
  1713. None,
  1714. self.task)
  1715. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1716. """!Produce a command line string (list) or feeding into GRASS.
  1717. @param ignoreErrors True then it will return whatever has been
  1718. built so far, even though it would not be a correct command
  1719. for GRASS
  1720. """
  1721. try:
  1722. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1723. ignoreRequired = ignoreRequired)
  1724. except ValueError, err:
  1725. dlg = wx.MessageDialog(parent = self,
  1726. message = unicode(err),
  1727. caption = _("Error in %s") % self.task.name,
  1728. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1729. dlg.ShowModal()
  1730. dlg.Destroy()
  1731. cmd = None
  1732. return cmd
  1733. def OnSize(self, event):
  1734. width = event.GetSize()[0]
  1735. fontsize = self.GetFont().GetPointSize()
  1736. text_width = max(width / (fontsize - 3), 70)
  1737. for id in self.label_id:
  1738. win = self.FindWindowById(id)
  1739. label = win.GetLabel()
  1740. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1741. win.SetLabel(label_new)
  1742. event.Skip()
  1743. def AddBitmapToImageList(self, section, imageList):
  1744. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1745. iconSectionDict = {'manual': os.path.join(globalvar.ETCICONDIR, iconTheme, 'help.png'),
  1746. _("Optional"): os.path.join(globalvar.ETCICONDIR, iconTheme, 'settings.png')}
  1747. if section in iconSectionDict.keys():
  1748. bitmap = wx.Bitmap(iconSectionDict[section])
  1749. bitmap.SetSize((16, 16))
  1750. idx = imageList.Add(bitmap)
  1751. return idx
  1752. return -1
  1753. class GUI:
  1754. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1755. centreOnParent = False, checkError = False):
  1756. """!Parses GRASS commands when module is imported and used from
  1757. Layer Manager.
  1758. """
  1759. self.parent = parent
  1760. self.show = show
  1761. self.modal = modal
  1762. self._giface = giface
  1763. self.centreOnParent = centreOnParent
  1764. self.checkError = checkError
  1765. self.grass_task = None
  1766. self.cmd = list()
  1767. global _blackList
  1768. if self.parent:
  1769. _blackList['enabled'] = True
  1770. else:
  1771. _blackList['enabled'] = False
  1772. def GetCmd(self):
  1773. """!Get validated command"""
  1774. return self.cmd
  1775. def ParseCommand(self, cmd, completed = None):
  1776. """!Parse command
  1777. Note: cmd is given as list
  1778. If command is given with options, return validated cmd list:
  1779. - add key name for first parameter if not given
  1780. - change mapname to mapname@mapset
  1781. """
  1782. dcmd_params = {}
  1783. if completed == None:
  1784. get_dcmd = None
  1785. layer = None
  1786. dcmd_params = None
  1787. else:
  1788. get_dcmd = completed[0]
  1789. layer = completed[1]
  1790. if completed[2]:
  1791. dcmd_params.update(completed[2])
  1792. # parse the interface decription
  1793. try:
  1794. global _blackList
  1795. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1796. blackList = _blackList)
  1797. except (grass.ScriptError, ValueError), e:
  1798. raise gcmd.GException(e.value)
  1799. # if layer parameters previously set, re-insert them into dialog
  1800. if completed is not None:
  1801. if 'params' in dcmd_params:
  1802. self.grass_task.params = dcmd_params['params']
  1803. if 'flags' in dcmd_params:
  1804. self.grass_task.flags = dcmd_params['flags']
  1805. err = list()
  1806. # update parameters if needed && validate command
  1807. if len(cmd) > 1:
  1808. i = 0
  1809. cmd_validated = [cmd[0]]
  1810. for option in cmd[1:]:
  1811. if option[0] == '-': # flag
  1812. if option[1] == '-':
  1813. self.grass_task.set_flag(option[2:], True)
  1814. else:
  1815. self.grass_task.set_flag(option[1], True)
  1816. cmd_validated.append(option)
  1817. else: # parameter
  1818. try:
  1819. key, value = option.split('=', 1)
  1820. except ValueError:
  1821. if self.grass_task.firstParam:
  1822. if i == 0: # add key name of first parameter if not given
  1823. key = self.grass_task.firstParam
  1824. value = option
  1825. else:
  1826. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1827. else:
  1828. continue
  1829. element = self.grass_task.get_param(key, raiseError = False)
  1830. if not element:
  1831. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1832. { 'cmd' : cmd[0],
  1833. 'key' : key })
  1834. continue
  1835. element = element['element']
  1836. if element in ['cell', 'vector']:
  1837. # mapname -> mapname@mapset
  1838. try:
  1839. name, mapset = value.split('@')
  1840. except ValueError:
  1841. mapset = grass.find_file(value, element)['mapset']
  1842. curr_mapset = grass.gisenv()['MAPSET']
  1843. if mapset and mapset != curr_mapset:
  1844. value = value + '@' + mapset
  1845. self.grass_task.set_param(key, value)
  1846. cmd_validated.append(key + '=' + value)
  1847. i += 1
  1848. # update original command list
  1849. cmd = cmd_validated
  1850. if self.show is not None:
  1851. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  1852. task_description = self.grass_task,
  1853. get_dcmd = get_dcmd, layer = layer)
  1854. else:
  1855. self.mf = None
  1856. if get_dcmd is not None:
  1857. # update only propwin reference
  1858. get_dcmd(dcmd = None, layer = layer, params = None,
  1859. propwin = self.mf)
  1860. if self.show is not None:
  1861. self.mf.notebookpanel.OnUpdateSelection(None)
  1862. if self.show is True:
  1863. if self.parent and self.centreOnParent:
  1864. self.mf.CentreOnParent()
  1865. else:
  1866. self.mf.CenterOnScreen()
  1867. self.mf.Show(self.show)
  1868. self.mf.MakeModal(self.modal)
  1869. else:
  1870. self.mf.OnApply(None)
  1871. self.cmd = cmd
  1872. if self.checkError:
  1873. return self.grass_task, err
  1874. else:
  1875. return self.grass_task
  1876. def GetCommandInputMapParamKey(self, cmd):
  1877. """!Get parameter key for input raster/vector map
  1878. @param cmd module name
  1879. @return parameter key
  1880. @return None on failure
  1881. """
  1882. # parse the interface decription
  1883. if not self.grass_task:
  1884. enc = locale.getdefaultlocale()[1]
  1885. if enc and enc.lower() == "cp932":
  1886. p = re.compile('encoding="' + enc + '"', re.IGNORECASE)
  1887. tree = etree.fromstring(p.sub('encoding="utf-8"',
  1888. gtask.get_interface_description(cmd).decode(enc).encode('utf-8')))
  1889. else:
  1890. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1891. self.grass_task = gtask.processTask(tree).get_task()
  1892. for p in self.grass_task.params:
  1893. if p.get('name', '') in ('input', 'map'):
  1894. age = p.get('age', '')
  1895. prompt = p.get('prompt', '')
  1896. element = p.get('element', '')
  1897. if age == 'old' and \
  1898. element in ('cell', 'grid3', 'vector') and \
  1899. prompt in ('raster', '3d-raster', 'vector'):
  1900. return p.get('name', None)
  1901. return None
  1902. class GrassGUIApp(wx.App):
  1903. """!Stand-alone GRASS command GUI
  1904. """
  1905. def __init__(self, grass_task):
  1906. self.grass_task = grass_task
  1907. wx.App.__init__(self, False)
  1908. def OnInit(self):
  1909. msg = self.grass_task.get_error_msg()
  1910. if msg:
  1911. gcmd.GError(msg + '\n\n' +
  1912. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  1913. return True
  1914. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  1915. self.mf.CentreOnScreen()
  1916. self.mf.Show(True)
  1917. self.SetTopWindow(self.mf)
  1918. return True
  1919. if __name__ == "__main__":
  1920. import gettext
  1921. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1922. if len(sys.argv) == 1:
  1923. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1924. if sys.argv[1] != 'test':
  1925. q = wx.LogNull()
  1926. cmd = utils.split(sys.argv[1])
  1927. task = gtask.grassTask(gcmd.GetRealCmd(cmd[0]))
  1928. task.set_options(cmd[1:])
  1929. app = GrassGUIApp(task)
  1930. app.MainLoop()
  1931. else: #Test
  1932. # Test grassTask from within a GRASS session
  1933. if os.getenv("GISBASE") is not None:
  1934. task = gtask.grassTask("d.vect")
  1935. task.get_param('map')['value'] = "map_name"
  1936. task.get_flag('v')['value'] = True
  1937. task.get_param('layer')['value'] = 1
  1938. task.get_param('bcolor')['value'] = "red"
  1939. assert ' '.join(task.get_cmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1940. # Test interface building with handmade grassTask,
  1941. # possibly outside of a GRASS session.
  1942. task = gtask.grassTask()
  1943. task.name = "TestTask"
  1944. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1945. task.keywords = ["grass","test","task"]
  1946. task.params = [
  1947. {
  1948. "name" : "text",
  1949. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1950. "label" : "Enter some text",
  1951. },{
  1952. "name" : "hidden_text",
  1953. "description" : "This text should not appear in the form",
  1954. "hidden" : True
  1955. },{
  1956. "name" : "text_default",
  1957. "description" : "Enter text to override the default",
  1958. "default" : "default text"
  1959. },{
  1960. "name" : "text_prefilled",
  1961. "description" : "You should see a friendly welcome message here",
  1962. "value" : "hello, world"
  1963. },{
  1964. "name" : "plain_color",
  1965. "description" : "This is a plain color, and it is a compulsory parameter",
  1966. "required" : False,
  1967. "gisprompt" : True,
  1968. "prompt" : "color"
  1969. },{
  1970. "name" : "transparent_color",
  1971. "description" : "This color becomes transparent when set to none",
  1972. "guisection" : "tab",
  1973. "gisprompt" : True,
  1974. "prompt" : "color"
  1975. },{
  1976. "name" : "multi",
  1977. "description" : "A multiple selection",
  1978. 'default': u'red,green,blue',
  1979. 'gisprompt': False,
  1980. 'guisection': 'tab',
  1981. 'multiple': u'yes',
  1982. 'type': u'string',
  1983. 'value': '',
  1984. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1985. },{
  1986. "name" : "single",
  1987. "description" : "A single multiple-choice selection",
  1988. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1989. "guisection" : "tab"
  1990. },{
  1991. "name" : "large_multi",
  1992. "description" : "A large multiple selection",
  1993. "gisprompt" : False,
  1994. "multiple" : "yes",
  1995. # values must be an array of strings
  1996. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values())
  1997. },{
  1998. "name" : "a_file",
  1999. "description" : "A file selector",
  2000. "gisprompt" : True,
  2001. "element" : "file"
  2002. }
  2003. ]
  2004. task.flags = [
  2005. {
  2006. "name" : "a",
  2007. "description" : "Some flag, will appear in Main since it is required",
  2008. "required" : True
  2009. },{
  2010. "name" : "b",
  2011. "description" : "pre-filled flag, will appear in options since it is not required",
  2012. "value" : True
  2013. },{
  2014. "name" : "hidden_flag",
  2015. "description" : "hidden flag, should not be changeable",
  2016. "hidden" : "yes",
  2017. "value" : True
  2018. }
  2019. ]
  2020. q = wx.LogNull()
  2021. GrassGUIApp(task).MainLoop()