forms.py 103 KB

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