forms.py 103 KB

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