forms.py 106 KB

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