forms.py 101 KB

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