forms.py 100 KB

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