forms.py 120 KB

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