forms.py 108 KB

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