forms.py 105 KB

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