forms.py 101 KB

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