forms.py 115 KB

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