forms.py 103 KB

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