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, giface, task_description, id = wx.ID_ANY,
  294. get_dcmd = None, layer = None,
  295. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **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._giface = giface
  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, giface = self._giface, task = self.task,
  352. frame = self)
  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 core.gconsole import wxCmdAbort
  570. event = wxCmdAbort(aborted = True)
  571. wx.PostEvent(self._gconsole, 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, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
  619. if frame:
  620. self.parent = frame
  621. else:
  622. self.parent = parent
  623. self.task = task
  624. self._giface = giface
  625. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  626. # Determine tab layout
  627. sections = []
  628. is_section = {}
  629. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  630. self.label_id = [] # wrap titles on resize
  631. self.Bind(wx.EVT_SIZE, self.OnSize)
  632. for task in not_hidden:
  633. if task.get('required', False):
  634. # All required go into Main, even if they had defined another guisection
  635. task['guisection'] = _('Required')
  636. if task.get('guisection','') == '':
  637. # Undefined guisections end up into Options
  638. task['guisection'] = _('Optional')
  639. if task['guisection'] not in is_section:
  640. # We do it like this to keep the original order, except for Main which goes first
  641. is_section[task['guisection']] = 1
  642. sections.append(task['guisection'])
  643. else:
  644. is_section[ task['guisection'] ] += 1
  645. del is_section
  646. # 'Required' tab goes first, 'Optional' as the last one
  647. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  648. if content in sections:
  649. idx = sections.index(content)
  650. sections[idx:idx+1] = []
  651. sections[newidx:newidx] = [content]
  652. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  653. # build notebook
  654. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  655. if style == 0: # basic top
  656. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  657. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  658. elif style == 1: # basic left
  659. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  660. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  661. elif style == 2: # fancy green
  662. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  663. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  664. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  665. elif style == 3:
  666. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  667. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  668. self.notebook.Refresh()
  669. tab = {}
  670. tabsizer = {}
  671. for section in sections:
  672. tab[section] = ScrolledPanel(parent = self.notebook)
  673. tab[section].SetScrollRate(10, 10)
  674. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  675. #
  676. # flags
  677. #
  678. text_style = wx.FONTWEIGHT_NORMAL
  679. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  680. for f in visible_flags:
  681. which_sizer = tabsizer[ f['guisection'] ]
  682. which_panel = tab[ f['guisection'] ]
  683. # if label is given: description -> tooltip
  684. if f.get('label','') != '':
  685. title = text_beautify(f['label'])
  686. tooltip = text_beautify(f['description'], width = -1)
  687. else:
  688. title = text_beautify(f['description'])
  689. tooltip = None
  690. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  691. rtitle_txt = wx.StaticText(parent = which_panel,
  692. label = '(' + f['name'] + ')')
  693. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  694. self.label_id.append(chk.GetId())
  695. if tooltip:
  696. chk.SetToolTipString(tooltip)
  697. chk.SetValue(f.get('value', False))
  698. title_sizer.Add(item = chk, proportion = 1,
  699. flag = wx.EXPAND)
  700. title_sizer.Add(item = rtitle_txt, proportion = 0,
  701. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  702. which_sizer.Add(item = title_sizer, proportion = 0,
  703. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  704. f['wxId'] = [ chk.GetId(), ]
  705. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  706. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  707. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  708. label = _("Parameterized in model"))
  709. parChk.SetName('ModelParam')
  710. parChk.SetValue(f.get('parameterized', False))
  711. if 'wxId' in f:
  712. f['wxId'].append(parChk.GetId())
  713. else:
  714. f['wxId'] = [ parChk.GetId() ]
  715. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  716. which_sizer.Add(item = parChk, proportion = 0,
  717. flag = wx.LEFT, border = 20)
  718. if f['name'] in ('verbose', 'quiet'):
  719. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  720. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  721. if f['name'] == vq:
  722. chk.SetValue(True)
  723. f['value'] = True
  724. elif f['name'] == 'overwrite' and 'value' not in f:
  725. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  726. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  727. #
  728. # parameters
  729. #
  730. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  731. try:
  732. first_param = visible_params[0]
  733. except IndexError:
  734. first_param = None
  735. for p in visible_params:
  736. which_sizer = tabsizer[p['guisection']]
  737. which_panel = tab[p['guisection']]
  738. # if label is given -> label and description -> tooltip
  739. # otherwise description -> lavel
  740. if p.get('label','') != '':
  741. title = text_beautify(p['label'])
  742. tooltip = text_beautify(p['description'], width = -1)
  743. else:
  744. title = text_beautify(p['description'])
  745. tooltip = None
  746. txt = None
  747. prompt = p.get('prompt', '')
  748. # text style (required -> bold)
  749. if not p.get('required', False):
  750. text_style = wx.FONTWEIGHT_NORMAL
  751. else:
  752. text_style = wx.FONTWEIGHT_BOLD
  753. # title sizer (description, name, type)
  754. if (len(p.get('values', [])) > 0) and \
  755. p.get('multiple', False) and \
  756. p.get('gisprompt', False) == False and \
  757. p.get('type', '') == 'string':
  758. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  759. else:
  760. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  761. title_txt = wx.StaticText(parent = which_panel)
  762. if p['key_desc']:
  763. ltype = ','.join(p['key_desc'])
  764. else:
  765. ltype = p['type']
  766. rtitle_txt = wx.StaticText(parent = which_panel,
  767. label = '(' + p['name'] + '=' + ltype + ')')
  768. title_sizer.Add(item = title_txt, proportion = 1,
  769. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  770. title_sizer.Add(item = rtitle_txt, proportion = 0,
  771. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  772. which_sizer.Add(item = title_sizer, proportion = 0,
  773. flag = wx.EXPAND)
  774. self.label_id.append(title_txt.GetId())
  775. # title expansion
  776. if p.get('multiple', False) and len(p.get('values','')) == 0:
  777. title = _("[multiple]") + " " + title
  778. if p.get('value','') == '' :
  779. p['value'] = p.get('default','')
  780. if (len(p.get('values', [])) > 0):
  781. valuelist = map(str, p.get('values',[]))
  782. valuelist_desc = map(unicode, p.get('values_desc',[]))
  783. if p.get('multiple', False) and \
  784. p.get('gisprompt',False) == False and \
  785. p.get('type', '') == 'string':
  786. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  787. if valuelist_desc:
  788. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  789. else:
  790. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  791. isEnabled = {}
  792. # copy default values
  793. if p['value'] == '':
  794. p['value'] = p.get('default', '')
  795. for defval in p.get('value', '').split(','):
  796. isEnabled[ defval ] = 'yes'
  797. # for multi checkboxes, this is an array of all wx IDs
  798. # for each individual checkbox
  799. p[ 'wxId' ] = list()
  800. idx = 0
  801. for val in valuelist:
  802. try:
  803. label = valuelist_desc[idx]
  804. except IndexError:
  805. label = val
  806. chkbox = wx.CheckBox(parent = which_panel,
  807. label = text_beautify(label))
  808. p[ 'wxId' ].append(chkbox.GetId())
  809. if val in isEnabled:
  810. chkbox.SetValue(True)
  811. hSizer.Add(item = chkbox, proportion = 0,
  812. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  813. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  814. idx += 1
  815. which_sizer.Add(item = hSizer, proportion = 0,
  816. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  817. elif p.get('gisprompt', False) == False:
  818. if len(valuelist) == 1: # -> textctrl
  819. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  820. str(valuelist[0])))
  821. if p.get('type', '') == 'integer' and \
  822. not p.get('multiple', False):
  823. # for multiple integers use textctrl instead of spinsctrl
  824. try:
  825. minValue, maxValue = map(int, valuelist[0].split('-'))
  826. except ValueError:
  827. minValue = -1e6
  828. maxValue = 1e6
  829. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  830. min = minValue, max = maxValue)
  831. txt2.SetName("SpinCtrl")
  832. style = wx.BOTTOM | wx.LEFT
  833. else:
  834. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  835. txt2.SetName("TextCtrl")
  836. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  837. value = self._getValue(p)
  838. # parameter previously set
  839. if value:
  840. if txt2.GetName() == "SpinCtrl":
  841. txt2.SetValue(int(value))
  842. else:
  843. txt2.SetValue(value)
  844. which_sizer.Add(item = txt2, proportion = 0,
  845. flag = style, border = 5)
  846. p['wxId'] = [ txt2.GetId(), ]
  847. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  848. else:
  849. title_txt.SetLabel(title + ':')
  850. value = self._getValue(p)
  851. if p['name'] == 'icon': # symbols
  852. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  853. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  854. bitmap = bitmap)
  855. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  856. iconLabel.SetLabel(value)
  857. p['value'] = value
  858. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  859. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  860. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  861. this_sizer.Add(item = bb, proportion = 0,
  862. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  863. this_sizer.Add(item = iconLabel, proportion = 0,
  864. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  865. which_sizer.Add(item = this_sizer, proportion = 0,
  866. flag = wx.ADJUST_MINSIZE, border = 0)
  867. else:
  868. # list of values (combo)
  869. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  870. size = globalvar.DIALOG_COMBOBOX_SIZE,
  871. choices = valuelist, style = wx.CB_DROPDOWN)
  872. if value:
  873. cb.SetValue(value) # parameter previously set
  874. which_sizer.Add(item = cb, proportion = 0,
  875. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  876. p['wxId'] = [cb.GetId(),]
  877. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  878. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  879. if p.get('guidependency', ''):
  880. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  881. # text entry
  882. if (p.get('type','string') in ('string','integer','float')
  883. and len(p.get('values',[])) == 0
  884. and p.get('gisprompt',False) == False
  885. and p.get('prompt','') != 'color'):
  886. title_txt.SetLabel(title + ':')
  887. if p.get('multiple', False) or \
  888. p.get('type', 'string') == 'string' or \
  889. len(p.get('key_desc', [])) > 1:
  890. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  891. value = self._getValue(p)
  892. if value:
  893. # parameter previously set
  894. txt3.SetValue(str(value))
  895. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  896. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  897. else:
  898. minValue = -1e9
  899. maxValue = 1e9
  900. if p.get('type', '') == 'integer':
  901. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  902. size = globalvar.DIALOG_SPIN_SIZE,
  903. min = minValue, max = maxValue)
  904. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  905. value = self._getValue(p)
  906. if value:
  907. txt3.SetValue(int(value)) # parameter previously set
  908. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  909. else:
  910. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  911. validator = FloatValidator())
  912. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  913. value = self._getValue(p)
  914. if value:
  915. txt3.SetValue(str(value)) # parameter previously set
  916. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  917. which_sizer.Add(item = txt3, proportion = 0,
  918. flag = style, border = 5)
  919. p['wxId'] = [ txt3.GetId(), ]
  920. #
  921. # element selection tree combobox (maps, icons, regions, etc.)
  922. #
  923. if p.get('gisprompt', False):
  924. title_txt.SetLabel(title + ':')
  925. # GIS element entry
  926. if p.get('prompt','') not in ('color',
  927. 'color_none',
  928. 'subgroup',
  929. 'dbdriver',
  930. 'dbname',
  931. 'dbtable',
  932. 'dbcolumn',
  933. 'layer',
  934. 'layer_all',
  935. 'location',
  936. 'mapset',
  937. 'dbase',
  938. 'coords') and \
  939. p.get('element', '') not in ('file', 'dir'):
  940. multiple = p.get('multiple', False)
  941. if p.get('age', '') == 'new':
  942. mapsets = [grass.gisenv()['MAPSET'],]
  943. else:
  944. mapsets = None
  945. if self.task.name in ('r.proj', 'v.proj') \
  946. and p.get('name', '') == 'input':
  947. if self.task.name == 'r.proj':
  948. isRaster = True
  949. else:
  950. isRaster = False
  951. selection = gselect.ProjSelect(parent = which_panel,
  952. isRaster = isRaster)
  953. p['wxId'] = [ selection.GetId(), ]
  954. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  955. formatSelector = False
  956. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  957. else:
  958. elem = p.get('element', None)
  959. # hack for t.* modules
  960. if elem in ('stds', 'map'):
  961. orig_elem = elem
  962. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  963. if type_param:
  964. elem = type_param.get('default', None)
  965. # for t.(un)register:
  966. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  967. if maps_param and orig_elem == 'stds':
  968. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  969. elem = element_dict[type_param.get('default')]
  970. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  971. size = globalvar.DIALOG_GSELECT_SIZE,
  972. type = elem,
  973. multiple = multiple, nmaps = len(p.get('key_desc', [])),
  974. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old')
  975. value = self._getValue(p)
  976. if value:
  977. selection.SetValue(value)
  978. formatSelector = True
  979. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  980. # we target the textctl here
  981. textWin = selection.GetTextCtrl()
  982. p['wxId'] = [ textWin.GetId(), ]
  983. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  984. if prompt == 'vector':
  985. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  986. # if formatSelector and p.get('age', 'old') == 'old':
  987. # # OGR supported (read-only)
  988. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  989. # self.hsizer.Add(item = selection,
  990. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  991. # border = 5)
  992. # # format (native / ogr)
  993. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  994. # label = " %s " % _("Format"),
  995. # style = wx.RA_SPECIFY_ROWS,
  996. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  997. # if p.get('value', '').lower().rfind('@ogr') > -1:
  998. # rbox.SetSelection(1)
  999. # rbox.SetName('VectorFormat')
  1000. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1001. # self.hsizer.Add(item = rbox,
  1002. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1003. # wx.RIGHT | wx.ALIGN_TOP,
  1004. # border = 5)
  1005. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1006. # default = 'dir',
  1007. # exclude = ['file'])
  1008. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1009. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1010. # ogrSelection.SetName('OgrSelect')
  1011. # ogrSelection.Hide()
  1012. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1013. # p['wxId'].append(rbox.GetId())
  1014. # p['wxId'].append(ogrSelection.GetId())
  1015. # for win in ogrSelection.GetDsnWin():
  1016. # p['wxId'].append(win.GetId())
  1017. # else:
  1018. which_sizer.Add(item = selection, proportion = 0,
  1019. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1020. border = 5)
  1021. elif prompt == 'group':
  1022. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  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. else:
  1027. which_sizer.Add(item = selection, proportion = 0,
  1028. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1029. border = 5)
  1030. # subgroup
  1031. elif prompt == 'subgroup':
  1032. selection = gselect.SubGroupSelect(parent = which_panel)
  1033. p['wxId'] = [ selection.GetId() ]
  1034. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1035. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1036. which_sizer.Add(item = selection, proportion = 0,
  1037. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1038. border = 5)
  1039. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1040. elif prompt in ('dbdriver',
  1041. 'dbname',
  1042. 'dbtable',
  1043. 'dbcolumn',
  1044. 'layer',
  1045. 'layer_all',
  1046. 'location',
  1047. 'mapset',
  1048. 'dbase'):
  1049. if p.get('multiple', 'no') == 'yes':
  1050. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1051. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1052. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1053. else:
  1054. value = self._getValue(p)
  1055. if prompt in ('layer', 'layer_all'):
  1056. if prompt == 'layer_all':
  1057. all = True
  1058. else:
  1059. all = False
  1060. if p.get('age', 'old') == 'old':
  1061. win = gselect.LayerSelect(parent = which_panel,
  1062. all = all,
  1063. default = p['default'])
  1064. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1065. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1066. win.SetValue(str(value)) # default or previously set value
  1067. else:
  1068. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1069. min = 1, max = 100, initial = int(p['default']))
  1070. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1071. win.SetValue(int(value)) # default or previously set value
  1072. p['wxId'] = [ win.GetId() ]
  1073. elif prompt == 'dbdriver':
  1074. win = gselect.DriverSelect(parent = which_panel,
  1075. choices = p.get('values', []),
  1076. value = value)
  1077. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1078. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1079. elif prompt == 'dbname':
  1080. win = gselect.DatabaseSelect(parent = which_panel,
  1081. value = value)
  1082. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1083. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1084. elif prompt == 'dbtable':
  1085. if p.get('age', 'old') == 'old':
  1086. win = gselect.TableSelect(parent = which_panel)
  1087. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1088. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1089. else:
  1090. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1091. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1092. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1093. elif prompt == 'dbcolumn':
  1094. win = gselect.ColumnSelect(parent = which_panel,
  1095. value = value,
  1096. param = p)
  1097. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1098. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1099. elif prompt == 'location':
  1100. win = gselect.LocationSelect(parent = which_panel,
  1101. value = value)
  1102. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1103. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1104. elif prompt == 'mapset':
  1105. if p.get('age', 'old') == 'old':
  1106. new = False
  1107. else:
  1108. new = True
  1109. win = gselect.MapsetSelect(parent = which_panel,
  1110. value = value, new = new)
  1111. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1112. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1113. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1114. elif prompt == 'dbase':
  1115. win = gselect.DbaseSelect(parent = which_panel,
  1116. changeCallback = self.OnSetValue)
  1117. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1118. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1119. if 'wxId' not in p:
  1120. try:
  1121. p['wxId'] = [ win.GetId(), ]
  1122. except AttributeError:
  1123. pass
  1124. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1125. if prompt == 'dbname':
  1126. flags |= wx.EXPAND
  1127. which_sizer.Add(item = win, proportion = 0,
  1128. flag = flags, border = 5)
  1129. # color entry
  1130. elif prompt in ('color',
  1131. 'color_none'):
  1132. default_color = (200,200,200)
  1133. label_color = _("Select Color")
  1134. if p.get('default','') != '':
  1135. default_color, label_color = utils.color_resolve(p['default'])
  1136. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1137. default_color, label_color = utils.color_resolve(p['value'])
  1138. if prompt == 'color_none':
  1139. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1140. else:
  1141. this_sizer = which_sizer
  1142. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1143. label = label_color, colour = default_color,
  1144. pos = wx.DefaultPosition, size = (150,-1))
  1145. this_sizer.Add(item = btn_colour, proportion = 0,
  1146. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1147. # For color selectors, this is a two-member array, holding the IDs of
  1148. # the selector proper and either a "transparent" button or None
  1149. p['wxId'] = [btn_colour.GetId(),]
  1150. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1151. if prompt == 'color_none':
  1152. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1153. if p.get('value','') == "none":
  1154. none_check.SetValue(True)
  1155. else:
  1156. none_check.SetValue(False)
  1157. this_sizer.Add(item = none_check, proportion = 0,
  1158. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1159. which_sizer.Add(this_sizer)
  1160. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1161. p['wxId'].append(none_check.GetId())
  1162. else:
  1163. p['wxId'].append(None)
  1164. # file selector
  1165. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1166. if p.get('age', 'new') == 'new':
  1167. fmode = wx.SAVE
  1168. else:
  1169. fmode = wx.OPEN
  1170. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1171. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1172. dialogTitle = _('Choose %s') % \
  1173. p.get('description',_('File')),
  1174. buttonText = _('Browse'),
  1175. startDirectory = os.getcwd(), fileMode = fmode,
  1176. changeCallback = self.OnSetValue)
  1177. value = self._getValue(p)
  1178. if value:
  1179. fbb.SetValue(value) # parameter previously set
  1180. which_sizer.Add(item = fbb, proportion = 0,
  1181. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1182. # A file browse button is a combobox with two children:
  1183. # a textctl and a button;
  1184. # we have to target the button here
  1185. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1186. if p.get('age', 'new') == 'old' and \
  1187. p.get('prompt', 'input') == 'input' and \
  1188. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1189. # widget for interactive input
  1190. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1191. style = wx.TE_MULTILINE,
  1192. size = (-1, 75))
  1193. if p.get('value', '') and os.path.isfile(p['value']):
  1194. f = open(p['value'])
  1195. ifbb.SetValue(''.join(f.readlines()))
  1196. f.close()
  1197. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1198. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1199. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1200. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVEAS)
  1201. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1202. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1203. label = _('or enter values interactively')),
  1204. proportion = 0,
  1205. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1206. which_sizer.Add(item = ifbb, proportion = 1,
  1207. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1208. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1209. btnSizer.Add(item = btnLoad, proportion = 0,
  1210. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1211. btnSizer.Add(item = btnSave, proportion = 0,
  1212. flag = wx.ALIGN_RIGHT)
  1213. which_sizer.Add(item = btnSizer, proportion = 0,
  1214. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1215. p['wxId'].append(ifbb.GetId())
  1216. p['wxId'].append(btnLoad.GetId())
  1217. p['wxId'].append(btnSave.GetId())
  1218. # directory selector
  1219. elif p.get('prompt','') != 'color' and p.get('element', '') == 'dir':
  1220. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1221. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1222. dialogTitle = _('Choose %s') % \
  1223. p.get('description', _('Directory')),
  1224. buttonText = _('Browse'),
  1225. startDirectory = os.getcwd(),
  1226. changeCallback = self.OnSetValue)
  1227. value = self._getValue(p)
  1228. if value:
  1229. fbb.SetValue(value) # parameter previously set
  1230. which_sizer.Add(item = fbb, proportion = 0,
  1231. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1232. # A file browse button is a combobox with two children:
  1233. # a textctl and a button;
  1234. # we have to target the button here
  1235. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1236. # interactive inserting of coordinates from map window
  1237. elif prompt == 'coords':
  1238. # interactive inserting if layer manager is accessible
  1239. if self._giface:
  1240. win = gselect.CoordinatesSelect(parent = which_panel,
  1241. giface = self._giface,
  1242. multiple = p.get('multiple', False),
  1243. param = p)
  1244. p['wxId'] = [win.GetTextWin().GetId()]
  1245. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1246. # normal text field
  1247. else:
  1248. win = wx.TextCtrl(parent = which_panel)
  1249. p['wxId'] = [win.GetId()]
  1250. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1251. which_sizer.Add(item = win,
  1252. proportion = 0,
  1253. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1254. border = 5)
  1255. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1256. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1257. label = _("Parameterized in model"))
  1258. parChk.SetName('ModelParam')
  1259. parChk.SetValue(p.get('parameterized', False))
  1260. if 'wxId' in p:
  1261. p['wxId'].append(parChk.GetId())
  1262. else:
  1263. p['wxId'] = [ parChk.GetId() ]
  1264. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1265. which_sizer.Add(item = parChk, proportion = 0,
  1266. flag = wx.LEFT, border = 20)
  1267. if title_txt is not None:
  1268. # create tooltip if given
  1269. if len(p['values_desc']) > 0:
  1270. if tooltip:
  1271. tooltip += 2 * os.linesep
  1272. else:
  1273. tooltip = ''
  1274. if len(p['values']) == len(p['values_desc']):
  1275. for i in range(len(p['values'])):
  1276. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1277. tooltip.strip(os.linesep)
  1278. if tooltip:
  1279. title_txt.SetToolTipString(tooltip)
  1280. if p == first_param:
  1281. if 'wxId' in p and len(p['wxId']) > 0:
  1282. win = self.FindWindowById(p['wxId'][0])
  1283. win.SetFocus()
  1284. #
  1285. # set widget relations for OnUpdateSelection
  1286. #
  1287. pMap = None
  1288. pLayer = []
  1289. pDriver = None
  1290. pDatabase = None
  1291. pTable = None
  1292. pColumn = []
  1293. pGroup = None
  1294. pSubGroup = None
  1295. pDbase = None
  1296. pLocation = None
  1297. pMapset = None
  1298. for p in self.task.params:
  1299. guidep = p.get('guidependency', '')
  1300. if guidep:
  1301. # fixed options dependency defined
  1302. options = guidep.split(',')
  1303. for opt in options:
  1304. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1305. if id:
  1306. if 'wxId-bind' not in p:
  1307. p['wxId-bind'] = list()
  1308. p['wxId-bind'] += pOpt['wxId']
  1309. continue
  1310. if p.get('gisprompt', False) == False:
  1311. continue
  1312. prompt = p.get('element', '')
  1313. if prompt in ('cell', 'vector'):
  1314. name = p.get('name', '')
  1315. if name in ('map', 'input'):
  1316. pMap = p
  1317. elif prompt == 'layer':
  1318. pLayer.append(p)
  1319. elif prompt == 'dbcolumn':
  1320. pColumn.append(p)
  1321. elif prompt == 'dbdriver':
  1322. pDriver = p
  1323. elif prompt == 'dbname':
  1324. pDatabase = p
  1325. elif prompt == 'dbtable':
  1326. pTable = p
  1327. elif prompt == 'group':
  1328. pGroup = p
  1329. elif prompt == 'subgroup':
  1330. pSubGroup = p
  1331. elif prompt == 'dbase':
  1332. pDbase = p
  1333. elif prompt == 'location':
  1334. pLocation = p
  1335. elif prompt == 'mapset':
  1336. pMapset = p
  1337. # collect ids
  1338. pColumnIds = []
  1339. for p in pColumn:
  1340. pColumnIds += p['wxId']
  1341. pLayerIds = []
  1342. for p in pLayer:
  1343. pLayerIds += p['wxId']
  1344. # set wxId-bindings
  1345. if pMap:
  1346. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1347. if pLayer:
  1348. pMap['wxId-bind'] += pLayerIds
  1349. if pLayer:
  1350. for p in pLayer:
  1351. p['wxId-bind'] = copy.copy(pColumnIds)
  1352. if pDriver and pTable:
  1353. pDriver['wxId-bind'] = pTable['wxId']
  1354. if pDatabase and pTable:
  1355. pDatabase['wxId-bind'] = pTable['wxId']
  1356. if pTable and pColumnIds:
  1357. pTable['wxId-bind'] = pColumnIds
  1358. if pGroup and pSubGroup:
  1359. pGroup['wxId-bind'] = pSubGroup['wxId']
  1360. if pDbase and pLocation:
  1361. pDbase['wxId-bind'] = pLocation['wxId']
  1362. if pLocation and pMapset:
  1363. pLocation['wxId-bind'] = pMapset['wxId']
  1364. if pLocation and pMapset and pMap:
  1365. pLocation['wxId-bind'] += pMap['wxId']
  1366. pMapset['wxId-bind'] = pMap['wxId']
  1367. #
  1368. # determine panel size
  1369. #
  1370. maxsizes = (0, 0)
  1371. for section in sections:
  1372. tab[section].SetSizer(tabsizer[section])
  1373. tabsizer[section].Fit(tab[section])
  1374. tab[section].Layout()
  1375. minsecsizes = tabsizer[section].GetSize()
  1376. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1377. # TODO: be less arbitrary with these 600
  1378. self.panelMinHeight = 100
  1379. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1380. for section in sections:
  1381. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1382. # add pages to notebook
  1383. imageList = wx.ImageList(16, 16)
  1384. self.notebook.AssignImageList(imageList)
  1385. for section in sections:
  1386. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1387. index = self.AddBitmapToImageList(section, imageList)
  1388. if index >= 0:
  1389. self.notebook.SetPageImage(section, index)
  1390. # are we running from command line?
  1391. ### add 'command output' tab regardless standalone dialog
  1392. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1393. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1394. from gui_core.goutput import GConsoleWindow
  1395. self._gconsole = GConsole(guiparent = self.notebook)
  1396. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1397. self._gconsole.Bind(EVT_CMD_RUN,
  1398. lambda event:
  1399. self._switchPageHandler(event = event, priority = 2))
  1400. self._gconsole.Bind(EVT_CMD_DONE,
  1401. lambda event:
  1402. self._switchPageHandler(event = event, priority = 3))
  1403. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1404. index = self.AddBitmapToImageList(section = 'output', imageList = imageList)
  1405. if index >= 0:
  1406. self.notebook.SetPageImage('output', index)
  1407. else:
  1408. self.goutput = None
  1409. self._gconsole = None
  1410. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.name)
  1411. if not self.manualTab.GetFile():
  1412. self.manualTab.Hide()
  1413. else:
  1414. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1415. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1416. if index >= 0:
  1417. self.notebook.SetPageImage('manual', index)
  1418. if self.manualTab.IsLoaded():
  1419. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1420. self.notebook.SetSelection(0)
  1421. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1422. self.SetSizer(panelsizer)
  1423. panelsizer.Fit(self.notebook)
  1424. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1425. def _getValue(self, p):
  1426. """!Get value or default value of given parameter
  1427. @param p parameter directory
  1428. """
  1429. if p.get('value', '') != '':
  1430. return p['value']
  1431. return p.get('default', '')
  1432. def OnFileLoad(self, event):
  1433. """!Load file to interactive input"""
  1434. me = event.GetId()
  1435. win = dict()
  1436. for p in self.task.params:
  1437. if 'wxId' in p and me in p['wxId']:
  1438. win['file'] = self.FindWindowById(p['wxId'][0])
  1439. win['text'] = self.FindWindowById(p['wxId'][1])
  1440. break
  1441. if not win:
  1442. return
  1443. path = win['file'].GetValue()
  1444. if not path:
  1445. gcmd.GMessage(parent = self,
  1446. message = _("Nothing to load."))
  1447. return
  1448. data = ''
  1449. f = open(path, "r")
  1450. try:
  1451. data = f.read()
  1452. finally:
  1453. f.close()
  1454. win['text'].SetValue(data)
  1455. def OnFileSave(self, event):
  1456. """!Save interactive input to the file"""
  1457. wId = event.GetId()
  1458. win = {}
  1459. for p in self.task.params:
  1460. if wId in p.get('wxId', []):
  1461. win['file'] = self.FindWindowById(p['wxId'][0])
  1462. win['text'] = self.FindWindowById(p['wxId'][1])
  1463. break
  1464. if not win:
  1465. return
  1466. text = win['text'].GetValue()
  1467. if not text:
  1468. gcmd.GMessage(parent = self,
  1469. message = _("Nothing to save."))
  1470. return
  1471. dlg = wx.FileDialog(parent = self,
  1472. message = _("Save input as..."),
  1473. defaultDir = os.getcwd(),
  1474. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1475. if dlg.ShowModal() == wx.ID_OK:
  1476. path = dlg.GetPath()
  1477. f = open(path, "w")
  1478. try:
  1479. f.write(text + os.linesep)
  1480. finally:
  1481. f.close()
  1482. win['file'].SetValue(path)
  1483. dlg.Destroy()
  1484. def OnFileText(self, event):
  1485. """File input interactively entered"""
  1486. text = event.GetString()
  1487. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1488. if not p:
  1489. return # should not happen
  1490. win = self.FindWindowById(p['wxId'][0])
  1491. if text:
  1492. filename = win.GetValue()
  1493. if not filename:
  1494. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1495. filename = grass.tempfile()
  1496. win.SetValue(filename)
  1497. f = open(filename, "w")
  1498. try:
  1499. f.write(text)
  1500. if text[-1] != os.linesep:
  1501. f.write(os.linesep)
  1502. finally:
  1503. f.close()
  1504. else:
  1505. win.SetValue('')
  1506. def OnVectorFormat(self, event):
  1507. """!Change vector format (native / ogr)"""
  1508. sel = event.GetSelection()
  1509. idEvent = event.GetId()
  1510. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1511. if not p:
  1512. return # should not happen
  1513. # detect windows
  1514. winNative = None
  1515. winOgr = None
  1516. for id in p['wxId']:
  1517. if id == idEvent:
  1518. continue
  1519. name = self.FindWindowById(id).GetName()
  1520. if name == 'Select':
  1521. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1522. elif name == 'OgrSelect':
  1523. winOgr = self.FindWindowById(id)
  1524. # enable / disable widgets & update values
  1525. rbox = self.FindWindowByName('VectorFormat')
  1526. self.hsizer.Remove(rbox)
  1527. if sel == 0: # -> native
  1528. winOgr.Hide()
  1529. self.hsizer.Remove(winOgr)
  1530. self.hsizer.Add(item = winNative,
  1531. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1532. border = 5)
  1533. winNative.Show()
  1534. p['value'] = winNative.GetValue()
  1535. elif sel == 1: # -> OGR
  1536. sizer = wx.BoxSizer(wx.VERTICAL)
  1537. winNative.Hide()
  1538. self.hsizer.Remove(winNative)
  1539. sizer.Add(item = winOgr)
  1540. winOgr.Show()
  1541. p['value'] = winOgr.GetDsn()
  1542. self.hsizer.Add(item = sizer,
  1543. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1544. border = 5)
  1545. self.hsizer.Add(item = rbox,
  1546. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1547. wx.RIGHT | wx.ALIGN_TOP,
  1548. border = 5)
  1549. self.hsizer.Layout()
  1550. self.Layout()
  1551. self.OnUpdateValues()
  1552. self.OnUpdateSelection(event)
  1553. def OnUpdateDialog(self, event):
  1554. for fn, kwargs in event.data.iteritems():
  1555. fn(**kwargs)
  1556. self.parent.updateValuesHook()
  1557. def OnVerbosity(self, event):
  1558. """!Verbosity level changed"""
  1559. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1560. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1561. if event.IsChecked():
  1562. if event.GetId() == verbose.GetId():
  1563. if quiet.IsChecked():
  1564. quiet.SetValue(False)
  1565. self.task.get_flag('quiet')['value'] = False
  1566. else:
  1567. if verbose.IsChecked():
  1568. verbose.SetValue(False)
  1569. self.task.get_flag('verbose')['value'] = False
  1570. event.Skip()
  1571. def OnPageChange(self, event):
  1572. if not event:
  1573. sel = self.notebook.GetSelection()
  1574. else:
  1575. sel = event.GetSelection()
  1576. idx = self.notebook.GetPageIndexByName('manual')
  1577. if idx > -1 and sel == idx:
  1578. # calling LoadPage() is strangely time-consuming (only first call)
  1579. # FIXME: move to helpPage.__init__()
  1580. if not self.manualTab.IsLoaded():
  1581. wx.Yield()
  1582. self.manualTab.LoadPage()
  1583. self.Layout()
  1584. if event:
  1585. # skip is needed for wx.Notebook on Windows
  1586. event.Skip()
  1587. # this is needed for dialogs launched from layer manager
  1588. # event is somehow propagated?
  1589. event.StopPropagation()
  1590. def _switchPageHandler(self, event, priority):
  1591. self._switchPage(priority = priority)
  1592. event.Skip()
  1593. def _switchPage(self, priority):
  1594. """!Manages @c 'output' notebook page according to event priority."""
  1595. if priority == 1:
  1596. self.notebook.HighlightPageByName('output')
  1597. if priority >= 2:
  1598. self.notebook.SetSelectionByName('output')
  1599. if priority >= 3:
  1600. self.SetFocus()
  1601. self.Raise()
  1602. def OnColorChange(self, event):
  1603. myId = event.GetId()
  1604. for p in self.task.params:
  1605. if 'wxId' in p and myId in p['wxId']:
  1606. has_button = p['wxId'][1] is not None
  1607. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1608. p[ 'value' ] = 'none'
  1609. else:
  1610. colorchooser = wx.FindWindowById(p['wxId'][0])
  1611. new_color = colorchooser.GetValue()[:]
  1612. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1613. # under wx2.8.1
  1614. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1615. colorchooser.SetLabel(new_label)
  1616. colorchooser.SetColour(new_color)
  1617. colorchooser.Refresh()
  1618. p[ 'value' ] = colorchooser.GetLabel()
  1619. self.OnUpdateValues()
  1620. def OnUpdateValues(self, event = None):
  1621. """!If we were part of a richer interface, report back the
  1622. current command being built.
  1623. This method should be set by the parent of this panel if
  1624. needed. It's a hook, actually. Beware of what is 'self' in
  1625. the method def, though. It will be called with no arguments.
  1626. """
  1627. pass
  1628. def OnCheckBoxMulti(self, event):
  1629. """!Fill the values as a ','-separated string according to
  1630. current status of the checkboxes.
  1631. """
  1632. me = event.GetId()
  1633. theParam = None
  1634. for p in self.task.params:
  1635. if 'wxId' in p and me in p['wxId']:
  1636. theParam = p
  1637. myIndex = p['wxId'].index(me)
  1638. # Unpack current value list
  1639. currentValues = {}
  1640. for isThere in theParam.get('value', '').split(','):
  1641. currentValues[isThere] = 1
  1642. theValue = theParam['values'][myIndex]
  1643. if event.Checked():
  1644. currentValues[ theValue ] = 1
  1645. else:
  1646. del currentValues[ theValue ]
  1647. # Keep the original order, so that some defaults may be recovered
  1648. currentValueList = []
  1649. for v in theParam['values']:
  1650. if v in currentValues:
  1651. currentValueList.append(v)
  1652. # Pack it back
  1653. theParam['value'] = ','.join(currentValueList)
  1654. self.OnUpdateValues()
  1655. def OnSetValue(self, event):
  1656. """!Retrieve the widget value and set the task value field
  1657. accordingly.
  1658. Use for widgets that have a proper GetValue() method, i.e. not
  1659. for selectors.
  1660. """
  1661. myId = event.GetId()
  1662. me = wx.FindWindowById(myId)
  1663. name = me.GetName()
  1664. found = False
  1665. for porf in self.task.params + self.task.flags:
  1666. if 'wxId' not in porf:
  1667. continue
  1668. if myId in porf['wxId']:
  1669. found = True
  1670. break
  1671. if not found:
  1672. return
  1673. if name == 'GdalSelect':
  1674. porf['value'] = event.dsn
  1675. elif name == 'ModelParam':
  1676. porf['parameterized'] = me.IsChecked()
  1677. else:
  1678. porf['value'] = me.GetValue()
  1679. self.OnUpdateValues(event)
  1680. event.Skip()
  1681. def OnSetSymbol(self, event):
  1682. """!Shows dialog for symbol selection"""
  1683. myId = event.GetId()
  1684. for p in self.task.params:
  1685. if 'wxId' in p and myId in p['wxId']:
  1686. from gui_core.dialogs import SymbolDialog
  1687. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1688. currentSymbol = p['value'])
  1689. if dlg.ShowModal() == wx.ID_OK:
  1690. img = dlg.GetSelectedSymbolPath()
  1691. p['value'] = dlg.GetSelectedSymbolName()
  1692. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1693. label = wx.FindWindowById(p['wxId'][1])
  1694. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1695. label.SetLabel(p['value'])
  1696. self.OnUpdateValues(event)
  1697. dlg.Destroy()
  1698. def OnUpdateSelection(self, event):
  1699. """!Update dialog (layers, tables, columns, etc.)
  1700. """
  1701. if not hasattr(self.parent, "updateThread"):
  1702. if event:
  1703. event.Skip()
  1704. return
  1705. if event:
  1706. self.parent.updateThread.Update(UpdateDialog,
  1707. self,
  1708. event,
  1709. event.GetId(),
  1710. self.task)
  1711. else:
  1712. self.parent.updateThread.Update(UpdateDialog,
  1713. self,
  1714. None,
  1715. None,
  1716. self.task)
  1717. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1718. """!Produce a command line string (list) or feeding into GRASS.
  1719. @param ignoreErrors True then it will return whatever has been
  1720. built so far, even though it would not be a correct command
  1721. for GRASS
  1722. """
  1723. try:
  1724. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1725. ignoreRequired = ignoreRequired)
  1726. except ValueError, err:
  1727. dlg = wx.MessageDialog(parent = self,
  1728. message = unicode(err),
  1729. caption = _("Error in %s") % self.task.name,
  1730. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1731. dlg.ShowModal()
  1732. dlg.Destroy()
  1733. cmd = None
  1734. return cmd
  1735. def OnSize(self, event):
  1736. width = event.GetSize()[0]
  1737. fontsize = self.GetFont().GetPointSize()
  1738. text_width = max(width / (fontsize - 3), 70)
  1739. for id in self.label_id:
  1740. win = self.FindWindowById(id)
  1741. label = win.GetLabel()
  1742. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1743. win.SetLabel(label_new)
  1744. event.Skip()
  1745. def AddBitmapToImageList(self, section, imageList):
  1746. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1747. iconSectionDict = {'manual': os.path.join(globalvar.ETCICONDIR, iconTheme, 'help.png'),
  1748. _("Optional"): os.path.join(globalvar.ETCICONDIR, iconTheme, 'settings.png')}
  1749. if section in iconSectionDict.keys():
  1750. bitmap = wx.Bitmap(iconSectionDict[section])
  1751. bitmap.SetSize((16, 16))
  1752. idx = imageList.Add(bitmap)
  1753. return idx
  1754. return -1
  1755. class GUI:
  1756. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1757. centreOnParent = False, checkError = False):
  1758. """!Parses GRASS commands when module is imported and used from
  1759. Layer Manager.
  1760. """
  1761. self.parent = parent
  1762. self.show = show
  1763. self.modal = modal
  1764. self._giface = giface
  1765. self.centreOnParent = centreOnParent
  1766. self.checkError = checkError
  1767. self.grass_task = None
  1768. self.cmd = list()
  1769. global _blackList
  1770. if self.parent:
  1771. _blackList['enabled'] = True
  1772. else:
  1773. _blackList['enabled'] = False
  1774. def GetCmd(self):
  1775. """!Get validated command"""
  1776. return self.cmd
  1777. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1778. """!Parse command
  1779. Note: cmd is given as list
  1780. If command is given with options, return validated cmd list:
  1781. - add key name for first parameter if not given
  1782. - change mapname to mapname@mapset
  1783. """
  1784. start = time.time()
  1785. dcmd_params = {}
  1786. if completed == None:
  1787. get_dcmd = None
  1788. layer = None
  1789. dcmd_params = None
  1790. else:
  1791. get_dcmd = completed[0]
  1792. layer = completed[1]
  1793. if completed[2]:
  1794. dcmd_params.update(completed[2])
  1795. # parse the interface decription
  1796. try:
  1797. global _blackList
  1798. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1799. blackList = _blackList)
  1800. except (grass.ScriptError, ValueError), e:
  1801. raise gcmd.GException(e.value)
  1802. # if layer parameters previously set, re-insert them into dialog
  1803. if completed is not None:
  1804. if 'params' in dcmd_params:
  1805. self.grass_task.params = dcmd_params['params']
  1806. if 'flags' in dcmd_params:
  1807. self.grass_task.flags = dcmd_params['flags']
  1808. err = list()
  1809. # update parameters if needed && validate command
  1810. if len(cmd) > 1:
  1811. i = 0
  1812. cmd_validated = [cmd[0]]
  1813. for option in cmd[1:]:
  1814. if option[0] == '-': # flag
  1815. if option[1] == '-':
  1816. self.grass_task.set_flag(option[2:], True)
  1817. else:
  1818. self.grass_task.set_flag(option[1], True)
  1819. cmd_validated.append(option)
  1820. else: # parameter
  1821. try:
  1822. key, value = option.split('=', 1)
  1823. except:
  1824. if self.grass_task.firstParam:
  1825. if i == 0: # add key name of first parameter if not given
  1826. key = self.grass_task.firstParam
  1827. value = option
  1828. else:
  1829. raise GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1830. else:
  1831. continue
  1832. element = self.grass_task.get_param(key, raiseError = False)
  1833. if not element:
  1834. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1835. { 'cmd' : cmd[0],
  1836. 'key' : key })
  1837. continue
  1838. element = element['element']
  1839. if element in ['cell', 'vector']:
  1840. # mapname -> mapname@mapset
  1841. try:
  1842. name, mapset = value.split('@')
  1843. except ValueError:
  1844. mapset = grass.find_file(value, element)['mapset']
  1845. curr_mapset = grass.gisenv()['MAPSET']
  1846. if mapset and mapset != curr_mapset:
  1847. value = value + '@' + mapset
  1848. self.grass_task.set_param(key, value)
  1849. cmd_validated.append(key + '=' + value)
  1850. i += 1
  1851. # update original command list
  1852. cmd = cmd_validated
  1853. if self.show is not None:
  1854. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  1855. task_description = self.grass_task,
  1856. get_dcmd = get_dcmd, layer = layer)
  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, giface = 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()