forms.py 105 KB

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