forms.py 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450
  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. which_sizer.Add(item = selection, proportion = 0,
  1056. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1057. border = 5)
  1058. # subgroup
  1059. elif prompt == 'subgroup':
  1060. selection = gselect.SubGroupSelect(parent = which_panel)
  1061. p['wxId'] = [ selection.GetId() ]
  1062. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1063. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1064. which_sizer.Add(item = selection, proportion = 0,
  1065. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1066. border = 5)
  1067. # sigrature file
  1068. elif prompt == 'sigfile':
  1069. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1070. p['wxId'] = [ selection.GetId() ]
  1071. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1072. which_sizer.Add(item = selection, proportion = 0,
  1073. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1074. border = 5)
  1075. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1076. elif prompt in ('dbdriver',
  1077. 'dbname',
  1078. 'dbtable',
  1079. 'dbcolumn',
  1080. 'layer',
  1081. 'location',
  1082. 'mapset',
  1083. 'dbase'):
  1084. if p.get('multiple', 'no') == 'yes':
  1085. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1086. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1087. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1088. else:
  1089. value = self._getValue(p)
  1090. if prompt == 'layer':
  1091. if p.get('element', 'layer') == 'layer_all':
  1092. all = True
  1093. else:
  1094. all = False
  1095. if p.get('age', 'old') == 'old':
  1096. win = gselect.LayerSelect(parent = which_panel,
  1097. all = all,
  1098. default = p['default'])
  1099. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1100. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1101. win.SetValue(str(value)) # default or previously set value
  1102. else:
  1103. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1104. min = 1, max = 100, initial = int(p['default']))
  1105. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1106. win.SetValue(int(value)) # default or previously set value
  1107. p['wxId'] = [ win.GetId() ]
  1108. elif prompt == 'dbdriver':
  1109. win = gselect.DriverSelect(parent = which_panel,
  1110. choices = p.get('values', []),
  1111. value = value)
  1112. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1113. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1114. elif prompt == 'dbname':
  1115. win = gselect.DatabaseSelect(parent = which_panel,
  1116. value = value)
  1117. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1118. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1119. elif prompt == 'dbtable':
  1120. if p.get('age', 'old') == 'old':
  1121. win = gselect.TableSelect(parent = which_panel)
  1122. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1123. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1124. else:
  1125. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1126. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1127. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1128. elif prompt == 'dbcolumn':
  1129. win = gselect.ColumnSelect(parent = which_panel,
  1130. value = value,
  1131. param = p,
  1132. multiple = p.get('multiple', False))
  1133. # A gselect.ColumnSelect is a combobox with two children: a textctl and a popupwindow;
  1134. # we target the textctl here
  1135. textWin = win.GetTextCtrl()
  1136. p['wxId'] = [ textWin.GetId(), ]
  1137. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1138. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1139. elif prompt == 'location':
  1140. win = gselect.LocationSelect(parent = which_panel,
  1141. value = value)
  1142. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1143. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1144. elif prompt == 'mapset':
  1145. if p.get('age', 'old') == 'old':
  1146. new = False
  1147. else:
  1148. new = True
  1149. win = gselect.MapsetSelect(parent = which_panel,
  1150. value = value, new = new)
  1151. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1152. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1153. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1154. elif prompt == 'dbase':
  1155. win = gselect.DbaseSelect(parent = which_panel,
  1156. changeCallback = self.OnSetValue)
  1157. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1158. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1159. if 'wxId' not in p:
  1160. try:
  1161. p['wxId'] = [ win.GetId(), ]
  1162. except AttributeError:
  1163. pass
  1164. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1165. if prompt == 'dbname':
  1166. flags |= wx.EXPAND
  1167. which_sizer.Add(item = win, proportion = 0,
  1168. flag = flags, border = 5)
  1169. # color entry
  1170. elif prompt == 'color':
  1171. default_color = (200,200,200)
  1172. label_color = _("Select Color")
  1173. if p.get('default','') != '':
  1174. default_color, label_color = utils.color_resolve(p['default'])
  1175. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1176. default_color, label_color = utils.color_resolve(p['value'])
  1177. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1178. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1179. else:
  1180. this_sizer = which_sizer
  1181. colorSize = 150
  1182. # For color selectors, this is a three-member array, holding the IDs of
  1183. # the color picker, the text control for multiple colors (or None),
  1184. # and either a "transparent" checkbox or None
  1185. p['wxId'] = [None] * 3
  1186. if p.get('multiple', False):
  1187. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1188. this_sizer.Add(item = txt, proportion = 1,
  1189. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1190. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1191. colorSize = 40
  1192. label_color = ''
  1193. p['wxId'][1] = txt.GetId()
  1194. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1195. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1196. label = label_color, colour = default_color,
  1197. pos = wx.DefaultPosition, size = (colorSize,-1))
  1198. this_sizer.Add(item = btn_colour, proportion = 0,
  1199. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1200. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1201. p['wxId'][0] = btn_colour.GetId()
  1202. if p.get('element', '') == 'color_none':
  1203. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1204. if p.get('value','') == "none":
  1205. none_check.SetValue(True)
  1206. else:
  1207. none_check.SetValue(False)
  1208. this_sizer.Add(item = none_check, proportion = 0,
  1209. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1210. which_sizer.Add(this_sizer)
  1211. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1212. p['wxId'][2] = none_check.GetId()
  1213. # file selector
  1214. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1215. if p.get('age', 'new') == 'new':
  1216. fmode = wx.SAVE
  1217. else:
  1218. fmode = wx.OPEN
  1219. # check wildcard
  1220. try:
  1221. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1222. except:
  1223. fExt = None
  1224. if not fExt:
  1225. fMask = '*.*'
  1226. else:
  1227. fMask = '%s files (*%s)|*%s|Files (*.*)|*.*' % (fExt[1:].upper(), fExt, fExt)
  1228. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1229. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1230. dialogTitle = _('Choose %s') % \
  1231. p.get('description', _('file')).lower(),
  1232. buttonText = _('Browse'),
  1233. startDirectory = os.getcwd(), fileMode = fmode,
  1234. changeCallback = self.OnSetValue)
  1235. value = self._getValue(p)
  1236. if value:
  1237. fbb.SetValue(value) # parameter previously set
  1238. which_sizer.Add(item = fbb, proportion = 0,
  1239. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1240. # A file browse button is a combobox with two children:
  1241. # a textctl and a button;
  1242. # we have to target the button here
  1243. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1244. if p.get('age', 'new') == 'old' and \
  1245. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1246. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1247. # widget for interactive input
  1248. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1249. style = wx.TE_MULTILINE,
  1250. size = (-1, 75))
  1251. if p.get('value', '') and os.path.isfile(p['value']):
  1252. f = open(p['value'])
  1253. ifbb.SetValue(''.join(f.readlines()))
  1254. f.close()
  1255. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1256. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1257. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1258. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVEAS)
  1259. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1260. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1261. label = _('or enter values interactively')),
  1262. proportion = 0,
  1263. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1264. which_sizer.Add(item = ifbb, proportion = 1,
  1265. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1266. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1267. btnSizer.Add(item = btnLoad, proportion = 0,
  1268. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1269. btnSizer.Add(item = btnSave, proportion = 0,
  1270. flag = wx.ALIGN_RIGHT)
  1271. which_sizer.Add(item = btnSizer, proportion = 0,
  1272. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1273. p['wxId'].append(ifbb.GetId())
  1274. p['wxId'].append(btnLoad.GetId())
  1275. p['wxId'].append(btnSave.GetId())
  1276. # directory selector
  1277. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1278. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1279. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1280. dialogTitle = _('Choose %s') % \
  1281. p.get('description', _('Directory')),
  1282. buttonText = _('Browse'),
  1283. startDirectory = os.getcwd(),
  1284. changeCallback = self.OnSetValue)
  1285. value = self._getValue(p)
  1286. if value:
  1287. fbb.SetValue(value) # parameter previously set
  1288. which_sizer.Add(item = fbb, proportion = 0,
  1289. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1290. # A file browse button is a combobox with two children:
  1291. # a textctl and a button;
  1292. # we have to target the button here
  1293. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1294. # interactive inserting of coordinates from map window
  1295. elif prompt == 'coords':
  1296. # interactive inserting if layer manager is accessible
  1297. if self._giface:
  1298. win = gselect.CoordinatesSelect(parent = which_panel,
  1299. giface = self._giface,
  1300. multiple = p.get('multiple', False),
  1301. param = p)
  1302. p['wxId'] = [win.GetTextWin().GetId()]
  1303. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1304. # bind closing event because destructor is not working properly
  1305. if hasattr(self.parent, 'dialogClosing'):
  1306. self.parent.dialogClosing.connect(win.OnClose)
  1307. # normal text field
  1308. else:
  1309. win = wx.TextCtrl(parent = which_panel)
  1310. p['wxId'] = [win.GetId()]
  1311. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1312. which_sizer.Add(item = win,
  1313. proportion = 0,
  1314. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1315. border = 5)
  1316. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1317. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1318. label = _("Parameterized in model"))
  1319. parChk.SetName('ModelParam')
  1320. parChk.SetValue(p.get('parameterized', False))
  1321. if 'wxId' in p:
  1322. p['wxId'].append(parChk.GetId())
  1323. else:
  1324. p['wxId'] = [ parChk.GetId() ]
  1325. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1326. which_sizer.Add(item = parChk, proportion = 0,
  1327. flag = wx.LEFT, border = 20)
  1328. if title_txt is not None:
  1329. # create tooltip if given
  1330. if len(p['values_desc']) > 0:
  1331. if tooltip:
  1332. tooltip += 2 * os.linesep
  1333. else:
  1334. tooltip = ''
  1335. if len(p['values']) == len(p['values_desc']):
  1336. for i in range(len(p['values'])):
  1337. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1338. tooltip.strip(os.linesep)
  1339. if tooltip:
  1340. title_txt.SetToolTipString(tooltip)
  1341. if p == first_param:
  1342. if 'wxId' in p and len(p['wxId']) > 0:
  1343. win = self.FindWindowById(p['wxId'][0])
  1344. win.SetFocus()
  1345. #
  1346. # set widget relations for OnUpdateSelection
  1347. #
  1348. pMap = None
  1349. pLayer = []
  1350. pDriver = None
  1351. pDatabase = None
  1352. pTable = None
  1353. pColumn = []
  1354. pGroup = None
  1355. pSubGroup = None
  1356. pSigFile = None
  1357. pDbase = None
  1358. pLocation = None
  1359. pMapset = None
  1360. for p in self.task.params:
  1361. guidep = p.get('guidependency', '')
  1362. if guidep:
  1363. # fixed options dependency defined
  1364. options = guidep.split(',')
  1365. for opt in options:
  1366. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1367. if id:
  1368. if 'wxId-bind' not in p:
  1369. p['wxId-bind'] = list()
  1370. p['wxId-bind'] += pOpt['wxId']
  1371. continue
  1372. if p.get('gisprompt', False) == False:
  1373. continue
  1374. prompt = p.get('prompt', '')
  1375. if prompt in ('raster', 'vector'):
  1376. name = p.get('name', '')
  1377. if name in ('map', 'input'):
  1378. pMap = p
  1379. elif prompt == 'layer':
  1380. pLayer.append(p)
  1381. elif prompt == 'dbcolumn':
  1382. pColumn.append(p)
  1383. elif prompt == 'dbdriver':
  1384. pDriver = p
  1385. elif prompt == 'dbname':
  1386. pDatabase = p
  1387. elif prompt == 'dbtable':
  1388. pTable = p
  1389. elif prompt == 'group':
  1390. pGroup = p
  1391. elif prompt == 'subgroup':
  1392. pSubGroup = p
  1393. elif prompt == 'sigfile':
  1394. pSigFile = p
  1395. elif prompt == 'dbase':
  1396. pDbase = p
  1397. elif prompt == 'location':
  1398. pLocation = p
  1399. elif prompt == 'mapset':
  1400. pMapset = p
  1401. # collect ids
  1402. pColumnIds = []
  1403. for p in pColumn:
  1404. pColumnIds += p['wxId']
  1405. pLayerIds = []
  1406. for p in pLayer:
  1407. pLayerIds += p['wxId']
  1408. # set wxId-bindings
  1409. if pMap:
  1410. pMap['wxId-bind'] = []
  1411. if pLayer:
  1412. pMap['wxId-bind'] += pLayerIds
  1413. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1414. if pLayer:
  1415. for p in pLayer:
  1416. p['wxId-bind'] = copy.copy(pColumnIds)
  1417. if pDriver and pTable:
  1418. pDriver['wxId-bind'] = pTable['wxId']
  1419. if pDatabase and pTable:
  1420. pDatabase['wxId-bind'] = pTable['wxId']
  1421. if pTable and pColumnIds:
  1422. pTable['wxId-bind'] = pColumnIds
  1423. if pGroup and pSubGroup:
  1424. if pSigFile:
  1425. pGroup['wxId-bind'] = copy.copy(pSigFile['wxId']) + pSubGroup['wxId']
  1426. pSubGroup['wxId-bind'] = pSigFile['wxId']
  1427. else:
  1428. pGroup['wxId-bind'] = pSubGroup['wxId']
  1429. if pDbase and pLocation:
  1430. pDbase['wxId-bind'] = pLocation['wxId']
  1431. if pLocation and pMapset:
  1432. pLocation['wxId-bind'] = pMapset['wxId']
  1433. if pLocation and pMapset and pMap:
  1434. pLocation['wxId-bind'] += pMap['wxId']
  1435. pMapset['wxId-bind'] = pMap['wxId']
  1436. #
  1437. # determine panel size
  1438. #
  1439. maxsizes = (0, 0)
  1440. for section in sections:
  1441. tab[section].SetSizer(tabsizer[section])
  1442. tabsizer[section].Fit(tab[section])
  1443. tab[section].Layout()
  1444. minsecsizes = tabsizer[section].GetSize()
  1445. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1446. # TODO: be less arbitrary with these 600
  1447. self.panelMinHeight = 100
  1448. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1449. for section in sections:
  1450. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1451. # add pages to notebook
  1452. imageList = wx.ImageList(16, 16)
  1453. self.notebook.AssignImageList(imageList)
  1454. for section in sections:
  1455. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1456. index = self.AddBitmapToImageList(section, imageList)
  1457. if index >= 0:
  1458. self.notebook.SetPageImage(section, index)
  1459. # are we running from command line?
  1460. ### add 'command output' tab regardless standalone dialog
  1461. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1462. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1463. from gui_core.goutput import GConsoleWindow
  1464. self._gconsole = GConsole(guiparent = self.notebook)
  1465. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1466. self._gconsole.Bind(EVT_CMD_RUN,
  1467. lambda event:
  1468. self._switchPageHandler(event = event, priority = 2))
  1469. self._gconsole.Bind(EVT_CMD_DONE,
  1470. lambda event:
  1471. self._switchPageHandler(event = event, priority = 3))
  1472. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1473. else:
  1474. self.goutput = None
  1475. self._gconsole = None
  1476. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.name)
  1477. if not self.manualTab.GetFile():
  1478. self.manualTab.Hide()
  1479. else:
  1480. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1481. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1482. if index >= 0:
  1483. self.notebook.SetPageImage('manual', index)
  1484. if self.manualTab.IsLoaded():
  1485. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1486. self.notebook.SetSelection(0)
  1487. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1488. self.SetSizer(panelsizer)
  1489. panelsizer.Fit(self.notebook)
  1490. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1491. def _getValue(self, p):
  1492. """!Get value or default value of given parameter
  1493. @param p parameter directory
  1494. """
  1495. if p.get('value', '') != '':
  1496. return p['value']
  1497. return p.get('default', '')
  1498. def OnFileLoad(self, event):
  1499. """!Load file to interactive input"""
  1500. me = event.GetId()
  1501. win = dict()
  1502. for p in self.task.params:
  1503. if 'wxId' in p and me in p['wxId']:
  1504. win['file'] = self.FindWindowById(p['wxId'][0])
  1505. win['text'] = self.FindWindowById(p['wxId'][1])
  1506. break
  1507. if not win:
  1508. return
  1509. path = win['file'].GetValue()
  1510. if not path:
  1511. gcmd.GMessage(parent = self,
  1512. message = _("Nothing to load."))
  1513. return
  1514. data = ''
  1515. f = open(path, "r")
  1516. try:
  1517. data = f.read()
  1518. finally:
  1519. f.close()
  1520. win['text'].SetValue(data)
  1521. def OnFileSave(self, event):
  1522. """!Save interactive input to the file"""
  1523. wId = event.GetId()
  1524. win = {}
  1525. for p in self.task.params:
  1526. if wId in p.get('wxId', []):
  1527. win['file'] = self.FindWindowById(p['wxId'][0])
  1528. win['text'] = self.FindWindowById(p['wxId'][1])
  1529. break
  1530. if not win:
  1531. return
  1532. text = win['text'].GetValue()
  1533. if not text:
  1534. gcmd.GMessage(parent = self,
  1535. message = _("Nothing to save."))
  1536. return
  1537. dlg = wx.FileDialog(parent = self,
  1538. message = _("Save input as..."),
  1539. defaultDir = os.getcwd(),
  1540. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1541. if dlg.ShowModal() == wx.ID_OK:
  1542. path = dlg.GetPath()
  1543. enc = locale.getdefaultlocale()[1]
  1544. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1545. try:
  1546. f.write(text + os.linesep)
  1547. finally:
  1548. f.close()
  1549. win['file'].SetValue(path)
  1550. dlg.Destroy()
  1551. def OnFileText(self, event):
  1552. """File input interactively entered"""
  1553. text = event.GetString()
  1554. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1555. if not p:
  1556. return # should not happen
  1557. win = self.FindWindowById(p['wxId'][0])
  1558. if text:
  1559. filename = win.GetValue()
  1560. if not filename:
  1561. filename = grass.tempfile()
  1562. win.SetValue(filename)
  1563. enc = locale.getdefaultlocale()[1]
  1564. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1565. try:
  1566. f.write(text)
  1567. if text[-1] != os.linesep:
  1568. f.write(os.linesep)
  1569. finally:
  1570. f.close()
  1571. else:
  1572. win.SetValue('')
  1573. def OnVectorFormat(self, event):
  1574. """!Change vector format (native / ogr).
  1575. Currently unused.
  1576. """
  1577. sel = event.GetSelection()
  1578. idEvent = event.GetId()
  1579. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1580. if not p:
  1581. return # should not happen
  1582. # detect windows
  1583. winNative = None
  1584. winOgr = None
  1585. for id in p['wxId']:
  1586. if id == idEvent:
  1587. continue
  1588. name = self.FindWindowById(id).GetName()
  1589. if name == 'Select':
  1590. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1591. elif name == 'OgrSelect':
  1592. winOgr = self.FindWindowById(id)
  1593. # enable / disable widgets & update values
  1594. rbox = self.FindWindowByName('VectorFormat')
  1595. self.hsizer.Remove(rbox)
  1596. if sel == 0: # -> native
  1597. winOgr.Hide()
  1598. self.hsizer.Remove(winOgr)
  1599. self.hsizer.Add(item = winNative,
  1600. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1601. border = 5)
  1602. winNative.Show()
  1603. p['value'] = winNative.GetValue()
  1604. elif sel == 1: # -> OGR
  1605. sizer = wx.BoxSizer(wx.VERTICAL)
  1606. winNative.Hide()
  1607. self.hsizer.Remove(winNative)
  1608. sizer.Add(item = winOgr)
  1609. winOgr.Show()
  1610. p['value'] = winOgr.GetDsn()
  1611. self.hsizer.Add(item = sizer,
  1612. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1613. border = 5)
  1614. self.hsizer.Add(item = rbox,
  1615. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1616. wx.RIGHT | wx.ALIGN_TOP,
  1617. border = 5)
  1618. self.hsizer.Layout()
  1619. self.Layout()
  1620. self.OnUpdateValues()
  1621. self.OnUpdateSelection(event)
  1622. def OnUpdateDialog(self, event):
  1623. for fn, kwargs in event.data.iteritems():
  1624. fn(**kwargs)
  1625. self.parent.updateValuesHook()
  1626. def OnVerbosity(self, event):
  1627. """!Verbosity level changed"""
  1628. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1629. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1630. if event.IsChecked():
  1631. if event.GetId() == verbose.GetId():
  1632. if quiet.IsChecked():
  1633. quiet.SetValue(False)
  1634. self.task.get_flag('quiet')['value'] = False
  1635. else:
  1636. if verbose.IsChecked():
  1637. verbose.SetValue(False)
  1638. self.task.get_flag('verbose')['value'] = False
  1639. event.Skip()
  1640. def OnPageChange(self, event):
  1641. if not event:
  1642. sel = self.notebook.GetSelection()
  1643. else:
  1644. sel = event.GetSelection()
  1645. idx = self.notebook.GetPageIndexByName('manual')
  1646. if idx > -1 and sel == idx:
  1647. # calling LoadPage() is strangely time-consuming (only first call)
  1648. # FIXME: move to helpPage.__init__()
  1649. if not self.manualTab.IsLoaded():
  1650. wx.Yield()
  1651. self.manualTab.LoadPage()
  1652. self.Layout()
  1653. if event:
  1654. # skip is needed for wx.Notebook on Windows
  1655. event.Skip()
  1656. # this is needed for dialogs launched from layer manager
  1657. # event is somehow propagated?
  1658. event.StopPropagation()
  1659. def _switchPageHandler(self, event, priority):
  1660. self._switchPage(priority = priority)
  1661. event.Skip()
  1662. def _switchPage(self, priority):
  1663. """!Manages @c 'output' notebook page according to event priority."""
  1664. if priority == 1:
  1665. self.notebook.HighlightPageByName('output')
  1666. if priority >= 2:
  1667. self.notebook.SetSelectionByName('output')
  1668. if priority >= 3:
  1669. self.SetFocus()
  1670. self.Raise()
  1671. def OnColorChange(self, event):
  1672. myId = event.GetId()
  1673. for p in self.task.params:
  1674. if 'wxId' in p and myId in p['wxId']:
  1675. multiple = p['wxId'][1] is not None # multiple colors
  1676. hasTansp = p['wxId'][2] is not None
  1677. if multiple:
  1678. # selected color is added at the end of textCtrl
  1679. colorchooser = wx.FindWindowById(p['wxId'][0])
  1680. new_color = colorchooser.GetValue()[:]
  1681. new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
  1682. textCtrl = wx.FindWindowById(p['wxId'][1])
  1683. val = textCtrl.GetValue()
  1684. sep = ','
  1685. if val and val[-1] != sep:
  1686. val += sep
  1687. val += new_label
  1688. textCtrl.SetValue(val)
  1689. p[ 'value' ] = val
  1690. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  1691. p[ 'value' ] = 'none'
  1692. else:
  1693. colorchooser = wx.FindWindowById(p['wxId'][0])
  1694. new_color = colorchooser.GetValue()[:]
  1695. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1696. # under wx2.8.1
  1697. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1698. colorchooser.SetLabel(new_label)
  1699. colorchooser.SetColour(new_color)
  1700. colorchooser.Refresh()
  1701. p[ 'value' ] = colorchooser.GetLabel()
  1702. self.OnUpdateValues()
  1703. def OnUpdateValues(self, event = None):
  1704. """!If we were part of a richer interface, report back the
  1705. current command being built.
  1706. This method should be set by the parent of this panel if
  1707. needed. It's a hook, actually. Beware of what is 'self' in
  1708. the method def, though. It will be called with no arguments.
  1709. """
  1710. pass
  1711. def OnCheckBoxMulti(self, event):
  1712. """!Fill the values as a ','-separated string according to
  1713. current status of the checkboxes.
  1714. """
  1715. me = event.GetId()
  1716. theParam = None
  1717. for p in self.task.params:
  1718. if 'wxId' in p and me in p['wxId']:
  1719. theParam = p
  1720. myIndex = p['wxId'].index(me)
  1721. # Unpack current value list
  1722. currentValues = {}
  1723. for isThere in theParam.get('value', '').split(','):
  1724. currentValues[isThere] = 1
  1725. theValue = theParam['values'][myIndex]
  1726. if event.Checked():
  1727. currentValues[ theValue ] = 1
  1728. else:
  1729. del currentValues[ theValue ]
  1730. # Keep the original order, so that some defaults may be recovered
  1731. currentValueList = []
  1732. for v in theParam['values']:
  1733. if v in currentValues:
  1734. currentValueList.append(v)
  1735. # Pack it back
  1736. theParam['value'] = ','.join(currentValueList)
  1737. self.OnUpdateValues()
  1738. def OnSetValue(self, event):
  1739. """!Retrieve the widget value and set the task value field
  1740. accordingly.
  1741. Use for widgets that have a proper GetValue() method, i.e. not
  1742. for selectors.
  1743. """
  1744. myId = event.GetId()
  1745. me = wx.FindWindowById(myId)
  1746. name = me.GetName()
  1747. found = False
  1748. for porf in self.task.params + self.task.flags:
  1749. if 'wxId' not in porf:
  1750. continue
  1751. if myId in porf['wxId']:
  1752. found = True
  1753. break
  1754. if not found:
  1755. return
  1756. if name == 'GdalSelect':
  1757. porf['value'] = event.dsn
  1758. elif name == 'ModelParam':
  1759. porf['parameterized'] = me.IsChecked()
  1760. else:
  1761. if isinstance(me, wx.SpinCtrl):
  1762. porf['value'] = str(me.GetValue())
  1763. else:
  1764. porf['value'] = me.GetValue()
  1765. self.OnUpdateValues(event)
  1766. event.Skip()
  1767. def OnSetSymbol(self, event):
  1768. """!Shows dialog for symbol selection"""
  1769. myId = event.GetId()
  1770. for p in self.task.params:
  1771. if 'wxId' in p and myId in p['wxId']:
  1772. from gui_core.dialogs import SymbolDialog
  1773. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1774. currentSymbol = p['value'])
  1775. if dlg.ShowModal() == wx.ID_OK:
  1776. img = dlg.GetSelectedSymbolPath()
  1777. p['value'] = dlg.GetSelectedSymbolName()
  1778. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1779. label = wx.FindWindowById(p['wxId'][1])
  1780. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1781. label.SetLabel(p['value'])
  1782. self.OnUpdateValues(event)
  1783. dlg.Destroy()
  1784. def OnUpdateSelection(self, event):
  1785. """!Update dialog (layers, tables, columns, etc.)
  1786. """
  1787. if not hasattr(self.parent, "updateThread"):
  1788. if event:
  1789. event.Skip()
  1790. return
  1791. if event:
  1792. self.parent.updateThread.Update(UpdateDialog,
  1793. self,
  1794. event,
  1795. event.GetId(),
  1796. self.task)
  1797. else:
  1798. self.parent.updateThread.Update(UpdateDialog,
  1799. self,
  1800. None,
  1801. None,
  1802. self.task)
  1803. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1804. """!Produce a command line string (list) or feeding into GRASS.
  1805. @param ignoreErrors True then it will return whatever has been
  1806. built so far, even though it would not be a correct command
  1807. for GRASS
  1808. """
  1809. try:
  1810. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1811. ignoreRequired = ignoreRequired)
  1812. except ValueError, err:
  1813. dlg = wx.MessageDialog(parent = self,
  1814. message = unicode(err),
  1815. caption = _("Error in %s") % self.task.name,
  1816. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1817. dlg.ShowModal()
  1818. dlg.Destroy()
  1819. cmd = None
  1820. return cmd
  1821. def OnSize(self, event):
  1822. width = event.GetSize()[0]
  1823. fontsize = self.GetFont().GetPointSize()
  1824. text_width = max(width / (fontsize - 3), 70)
  1825. for id in self.label_id:
  1826. win = self.FindWindowById(id)
  1827. label = win.GetLabel()
  1828. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1829. win.SetLabel(label_new)
  1830. event.Skip()
  1831. def AddBitmapToImageList(self, section, imageList):
  1832. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1833. iconSectionDict = {'manual': os.path.join(globalvar.ETCICONDIR, iconTheme, 'help.png')}
  1834. if section in iconSectionDict.keys():
  1835. image = wx.Image(iconSectionDict[section]).Scale(16, 16, wx.IMAGE_QUALITY_HIGH)
  1836. idx = imageList.Add(wx.BitmapFromImage(image))
  1837. return idx
  1838. return -1
  1839. class GUI:
  1840. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1841. centreOnParent = False, checkError = False):
  1842. """!Parses GRASS commands when module is imported and used from
  1843. Layer Manager.
  1844. """
  1845. self.parent = parent
  1846. self.show = show
  1847. self.modal = modal
  1848. self._giface = giface
  1849. self.centreOnParent = centreOnParent
  1850. self.checkError = checkError
  1851. self.grass_task = None
  1852. self.cmd = list()
  1853. global _blackList
  1854. if self.parent:
  1855. _blackList['enabled'] = True
  1856. else:
  1857. _blackList['enabled'] = False
  1858. def GetCmd(self):
  1859. """!Get validated command"""
  1860. return self.cmd
  1861. def ParseCommand(self, cmd, completed = None):
  1862. """!Parse command
  1863. Note: cmd is given as list
  1864. If command is given with options, return validated cmd list:
  1865. - add key name for first parameter if not given
  1866. - change mapname to mapname@mapset
  1867. """
  1868. dcmd_params = {}
  1869. if completed == None:
  1870. get_dcmd = None
  1871. layer = None
  1872. dcmd_params = None
  1873. else:
  1874. get_dcmd = completed[0]
  1875. layer = completed[1]
  1876. if completed[2]:
  1877. dcmd_params.update(completed[2])
  1878. # parse the interface decription
  1879. try:
  1880. global _blackList
  1881. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1882. blackList = _blackList)
  1883. except (grass.ScriptError, ValueError), e:
  1884. raise gcmd.GException(e.value)
  1885. # if layer parameters previously set, re-insert them into dialog
  1886. if completed is not None:
  1887. if 'params' in dcmd_params:
  1888. self.grass_task.params = dcmd_params['params']
  1889. if 'flags' in dcmd_params:
  1890. self.grass_task.flags = dcmd_params['flags']
  1891. err = list()
  1892. # update parameters if needed && validate command
  1893. if len(cmd) > 1:
  1894. i = 0
  1895. cmd_validated = [cmd[0]]
  1896. for option in cmd[1:]:
  1897. if option[0] == '-': # flag
  1898. if option[1] == '-':
  1899. self.grass_task.set_flag(option[2:], True)
  1900. else:
  1901. self.grass_task.set_flag(option[1], True)
  1902. cmd_validated.append(option)
  1903. else: # parameter
  1904. try:
  1905. key, value = option.split('=', 1)
  1906. except ValueError:
  1907. if self.grass_task.firstParam:
  1908. if i == 0: # add key name of first parameter if not given
  1909. key = self.grass_task.firstParam
  1910. value = option
  1911. else:
  1912. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1913. else:
  1914. continue
  1915. element = self.grass_task.get_param(key, raiseError = False)
  1916. if not element:
  1917. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1918. { 'cmd' : cmd[0],
  1919. 'key' : key })
  1920. continue
  1921. element = element['element']
  1922. if element in ['cell', 'vector']:
  1923. # mapname -> mapname@mapset
  1924. try:
  1925. name, mapset = value.split('@')
  1926. except ValueError:
  1927. mapset = grass.find_file(value, element)['mapset']
  1928. curr_mapset = grass.gisenv()['MAPSET']
  1929. if mapset and mapset != curr_mapset:
  1930. value = value + '@' + mapset
  1931. self.grass_task.set_param(key, value)
  1932. cmd_validated.append(key + '=' + value)
  1933. i += 1
  1934. # update original command list
  1935. cmd = cmd_validated
  1936. if self.show is not None:
  1937. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  1938. task_description = self.grass_task,
  1939. get_dcmd = get_dcmd, layer = layer)
  1940. else:
  1941. self.mf = None
  1942. if get_dcmd is not None:
  1943. # update only propwin reference
  1944. get_dcmd(dcmd = None, layer = layer, params = None,
  1945. propwin = self.mf)
  1946. if self.show is not None:
  1947. self.mf.notebookpanel.OnUpdateSelection(None)
  1948. if self.show is True:
  1949. if self.parent and self.centreOnParent:
  1950. self.mf.CentreOnParent()
  1951. else:
  1952. self.mf.CenterOnScreen()
  1953. self.mf.Show(self.show)
  1954. self.mf.MakeModal(self.modal)
  1955. else:
  1956. self.mf.OnApply(None)
  1957. self.cmd = cmd
  1958. if self.checkError:
  1959. return self.grass_task, err
  1960. else:
  1961. return self.grass_task
  1962. def GetCommandInputMapParamKey(self, cmd):
  1963. """!Get parameter key for input raster/vector map
  1964. @param cmd module name
  1965. @return parameter key
  1966. @return None on failure
  1967. """
  1968. # parse the interface decription
  1969. if not self.grass_task:
  1970. enc = locale.getdefaultlocale()[1]
  1971. if enc and enc.lower() == "cp932":
  1972. p = re.compile('encoding="' + enc + '"', re.IGNORECASE)
  1973. tree = etree.fromstring(p.sub('encoding="utf-8"',
  1974. gtask.get_interface_description(cmd).decode(enc).encode('utf-8')))
  1975. else:
  1976. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1977. self.grass_task = gtask.processTask(tree).get_task()
  1978. for p in self.grass_task.params:
  1979. if p.get('name', '') in ('input', 'map'):
  1980. age = p.get('age', '')
  1981. prompt = p.get('prompt', '')
  1982. element = p.get('element', '')
  1983. if age == 'old' and \
  1984. element in ('cell', 'grid3', 'vector') and \
  1985. prompt in ('raster', '3d-raster', 'vector'):
  1986. return p.get('name', None)
  1987. return None
  1988. class GrassGUIApp(wx.App):
  1989. """!Stand-alone GRASS command GUI
  1990. """
  1991. def __init__(self, grass_task):
  1992. self.grass_task = grass_task
  1993. wx.App.__init__(self, False)
  1994. def OnInit(self):
  1995. msg = self.grass_task.get_error_msg()
  1996. if msg:
  1997. gcmd.GError(msg + '\n\n' +
  1998. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  1999. return True
  2000. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  2001. self.mf.CentreOnScreen()
  2002. self.mf.Show(True)
  2003. self.SetTopWindow(self.mf)
  2004. return True
  2005. if __name__ == "__main__":
  2006. if len(sys.argv) == 1:
  2007. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  2008. if sys.argv[1] != 'test':
  2009. q = wx.LogNull()
  2010. cmd = utils.split(sys.argv[1])
  2011. task = gtask.grassTask(gcmd.GetRealCmd(cmd[0]))
  2012. task.set_options(cmd[1:])
  2013. app = GrassGUIApp(task)
  2014. app.MainLoop()
  2015. else: #Test
  2016. # Test grassTask from within a GRASS session
  2017. if os.getenv("GISBASE") is not None:
  2018. task = gtask.grassTask("d.vect")
  2019. task.get_param('map')['value'] = "map_name"
  2020. task.get_flag('v')['value'] = True
  2021. task.get_param('layer')['value'] = 1
  2022. task.get_param('bcolor')['value'] = "red"
  2023. assert ' '.join(task.get_cmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  2024. # Test interface building with handmade grassTask,
  2025. # possibly outside of a GRASS session.
  2026. task = gtask.grassTask()
  2027. task.name = "TestTask"
  2028. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2029. task.keywords = ["grass","test","task"]
  2030. task.params = [
  2031. {
  2032. "name" : "text",
  2033. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2034. "label" : "Enter some text",
  2035. },{
  2036. "name" : "hidden_text",
  2037. "description" : "This text should not appear in the form",
  2038. "hidden" : True
  2039. },{
  2040. "name" : "text_default",
  2041. "description" : "Enter text to override the default",
  2042. "default" : "default text"
  2043. },{
  2044. "name" : "text_prefilled",
  2045. "description" : "You should see a friendly welcome message here",
  2046. "value" : "hello, world"
  2047. },{
  2048. "name" : "plain_color",
  2049. "description" : "This is a plain color, and it is a compulsory parameter",
  2050. "required" : False,
  2051. "gisprompt" : True,
  2052. "prompt" : "color"
  2053. },{
  2054. "name" : "transparent_color",
  2055. "description" : "This color becomes transparent when set to none",
  2056. "guisection" : "tab",
  2057. "gisprompt" : True,
  2058. "prompt" : "color"
  2059. },{
  2060. "name" : "multi",
  2061. "description" : "A multiple selection",
  2062. 'default': u'red,green,blue',
  2063. 'gisprompt': False,
  2064. 'guisection': 'tab',
  2065. 'multiple': u'yes',
  2066. 'type': u'string',
  2067. 'value': '',
  2068. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  2069. },{
  2070. "name" : "single",
  2071. "description" : "A single multiple-choice selection",
  2072. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2073. "guisection" : "tab"
  2074. },{
  2075. "name" : "large_multi",
  2076. "description" : "A large multiple selection",
  2077. "gisprompt" : False,
  2078. "multiple" : "yes",
  2079. # values must be an array of strings
  2080. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values())
  2081. },{
  2082. "name" : "a_file",
  2083. "description" : "A file selector",
  2084. "gisprompt" : True,
  2085. "element" : "file"
  2086. }
  2087. ]
  2088. task.flags = [
  2089. {
  2090. "name" : "a",
  2091. "description" : "Some flag, will appear in Main since it is required",
  2092. "required" : True
  2093. },{
  2094. "name" : "b",
  2095. "description" : "pre-filled flag, will appear in options since it is not required",
  2096. "value" : True
  2097. },{
  2098. "name" : "hidden_flag",
  2099. "description" : "hidden flag, should not be changeable",
  2100. "hidden" : "yes",
  2101. "value" : True
  2102. }
  2103. ]
  2104. q = wx.LogNull()
  2105. GrassGUIApp(task).MainLoop()