forms.py 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708
  1. """
  2. @package gui_core.forms
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - forms::UpdateThread
  7. - forms::UpdateQThread
  8. - forms::TaskFrame
  9. - forms::CmdPanel
  10. - forms::GUI
  11. - forms::GrassGUIApp
  12. This program is just a coarse approach to automatically build a GUI
  13. from a xml-based GRASS user interface description.
  14. You need to have Python 2.4, wxPython 2.8 and python-xml.
  15. The XML stream is read from executing the command given in the
  16. command line, thus you may call it for instance this way:
  17. python <this file.py> r.basins.fill
  18. Or you set an alias or wrap the call up in a nice shell script, GUI
  19. environment ... please contribute your idea.
  20. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  21. make it callable by gui. Method added to automatically re-run with
  22. pythonw on a Mac.
  23. .. todo::
  24. verify option value types
  25. Copyright(C) 2000-2013 by the GRASS Development Team
  26. This program is free software under the GPL(>=v2) Read the file
  27. COPYING coming with GRASS for details.
  28. @author Jan-Oliver Wagner <jan@intevation.de>
  29. @author Bernhard Reiter <bernhard@intevation.de>
  30. @author Michael Barton, Arizona State University
  31. @author Daniel Calvelo <dca.gis@gmail.com>
  32. @author Martin Landa <landa.martin@gmail.com>
  33. @author Luca Delucchi <lucadeluge@gmail.com>
  34. @author Stepan Turek <stepan.turek seznam.cz> (CoordinatesSelect)
  35. """
  36. import sys
  37. import string
  38. import textwrap
  39. import os
  40. import copy
  41. import locale
  42. import Queue
  43. import re
  44. import codecs
  45. from threading import Thread
  46. 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.dialogs 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. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  765. chk.SetValue(f['value'])
  766. #
  767. # parameters
  768. #
  769. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  770. try:
  771. first_param = visible_params[0]
  772. except IndexError:
  773. first_param = None
  774. for p in visible_params:
  775. which_sizer = tabsizer[p['guisection']]
  776. which_panel = tab[p['guisection']]
  777. # if label is given -> label and description -> tooltip
  778. # otherwise description -> lavel
  779. if p.get('label','') != '':
  780. title = text_beautify(p['label'])
  781. tooltip = text_beautify(p['description'], width = -1)
  782. else:
  783. title = text_beautify(p['description'])
  784. tooltip = None
  785. prompt = p.get('prompt', '')
  786. # title sizer (description, name, type)
  787. if (len(p.get('values', [])) > 0) and \
  788. p.get('multiple', False) and \
  789. p.get('gisprompt', False) == False and \
  790. p.get('type', '') == 'string':
  791. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  792. else:
  793. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  794. title_txt = wx.StaticText(parent = which_panel)
  795. if p['key_desc']:
  796. ltype = ','.join(p['key_desc'])
  797. else:
  798. ltype = p['type']
  799. # red star for required options
  800. if p.get('required', False):
  801. required_txt = wx.StaticText(parent=which_panel, label="*")
  802. required_txt.SetForegroundColour(wx.RED)
  803. required_txt.SetToolTipString(_("This option is required"))
  804. else:
  805. required_txt = wx.StaticText(parent=which_panel, label="")
  806. rtitle_txt = wx.StaticText(parent = which_panel,
  807. label = '(' + p['name'] + '=' + ltype + ')')
  808. title_sizer.Add(item = title_txt, proportion = 0,
  809. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  810. title_sizer.Add(item = required_txt, proportion=1,
  811. flag = wx.EXPAND, border=0)
  812. title_sizer.Add(item = rtitle_txt, proportion = 0,
  813. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  814. which_sizer.Add(item = title_sizer, proportion = 0,
  815. flag = wx.EXPAND)
  816. self.label_id.append(title_txt.GetId())
  817. # title expansion
  818. if p.get('multiple', False) and len(p.get('values','')) == 0:
  819. title = _("[multiple]") + " " + title
  820. if p.get('value','') == '' :
  821. p['value'] = p.get('default','')
  822. if (len(p.get('values', [])) > 0):
  823. valuelist = map(str, p.get('values',[]))
  824. valuelist_desc = map(unicode, p.get('values_desc',[]))
  825. required_text = "*" if p.get('required', False) else ""
  826. if p.get('multiple', False) and \
  827. p.get('gisprompt',False) == False and \
  828. p.get('type', '') == 'string':
  829. title_txt.SetLabel(" %s:%s (%s=%s) " % (title, required_text, p['name'], p['type']))
  830. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  831. if valuelist_desc:
  832. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  833. else:
  834. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  835. isEnabled = {}
  836. # copy default values
  837. if p['value'] == '':
  838. p['value'] = p.get('default', '')
  839. for defval in p.get('value', '').split(','):
  840. isEnabled[ defval ] = 'yes'
  841. # for multi checkboxes, this is an array of all wx IDs
  842. # for each individual checkbox
  843. p[ 'wxId' ] = list()
  844. idx = 0
  845. for val in valuelist:
  846. try:
  847. label = valuelist_desc[idx]
  848. except IndexError:
  849. label = val
  850. chkbox = wx.CheckBox(parent = which_panel,
  851. label = text_beautify(label))
  852. p[ 'wxId' ].append(chkbox.GetId())
  853. if val in isEnabled:
  854. chkbox.SetValue(True)
  855. hSizer.Add(item = chkbox, proportion = 0)
  856. chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
  857. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  858. idx += 1
  859. stSizer.Add(item = hSizer, proportion = 0,
  860. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  861. which_sizer.Add(item = stSizer, proportion = 0,
  862. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  863. elif p.get('gisprompt', False) is False:
  864. if len(valuelist) == 1: # -> textctrl
  865. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  866. str(valuelist[0])))
  867. if p.get('type', '') == 'integer' and \
  868. not p.get('multiple', False):
  869. # for multiple integers use textctrl instead of spinsctrl
  870. try:
  871. minValue, maxValue = map(int, valuelist[0].rsplit('-', 1))
  872. except ValueError:
  873. minValue = -1e6
  874. maxValue = 1e6
  875. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  876. min = minValue, max = maxValue)
  877. style = wx.BOTTOM | wx.LEFT
  878. else:
  879. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  880. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  881. value = self._getValue(p)
  882. # parameter previously set
  883. if value:
  884. if isinstance(txt2, wx.SpinCtrl):
  885. txt2.SetValue(int(value))
  886. else:
  887. txt2.SetValue(value)
  888. which_sizer.Add(item = txt2, proportion = 0,
  889. flag = style, border = 5)
  890. p['wxId'] = [ txt2.GetId(), ]
  891. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  892. else:
  893. title_txt.SetLabel(title + ':')
  894. value = self._getValue(p)
  895. if p['name'] == 'icon': # symbols
  896. bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR, value) + '.png')
  897. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  898. bitmap = bitmap)
  899. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  900. iconLabel.SetLabel(value)
  901. p['value'] = value
  902. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  903. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  904. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  905. this_sizer.Add(item = bb, proportion = 0,
  906. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  907. this_sizer.Add(item = iconLabel, proportion = 0,
  908. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  909. which_sizer.Add(item = this_sizer, proportion = 0,
  910. flag = wx.ADJUST_MINSIZE, border = 0)
  911. else:
  912. # list of values (combo)
  913. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  914. size=globalvar.DIALOG_COMBOBOX_SIZE,
  915. choices=valuelist, style=wx.CB_DROPDOWN)
  916. if value:
  917. cb.SetValue(value) # parameter previously set
  918. which_sizer.Add(item = cb, proportion = 0,
  919. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  920. p['wxId'] = [cb.GetId(),]
  921. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  922. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  923. if p.get('guidependency', ''):
  924. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  925. # text entry
  926. if (p.get('type','string') in ('string','integer','float')
  927. and len(p.get('values',[])) == 0
  928. and p.get('gisprompt',False) == False
  929. and p.get('prompt','') != 'color'):
  930. title_txt.SetLabel(title + ':')
  931. if p.get('multiple', False) or \
  932. p.get('type', 'string') == 'string' or \
  933. len(p.get('key_desc', [])) > 1:
  934. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  935. value = self._getValue(p)
  936. if value:
  937. # parameter previously set
  938. win.SetValue(str(value))
  939. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  940. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  941. elif p.get('type', '') == 'integer':
  942. minValue = -1e9
  943. maxValue = 1e9
  944. value = self._getValue(p)
  945. win = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
  946. size = globalvar.DIALOG_SPIN_SIZE,
  947. min = minValue, max = maxValue)
  948. if value:
  949. win.SetValue(int(value)) # parameter previously set
  950. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  951. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  952. else: # float
  953. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  954. validator = FloatValidator())
  955. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  956. value = self._getValue(p)
  957. if value:
  958. win.SetValue(str(value)) # parameter previously set
  959. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  960. which_sizer.Add(item = win, proportion = 0,
  961. flag = style, border = 5)
  962. p['wxId'] = [win.GetId()]
  963. #
  964. # element selection tree combobox (maps, icons, regions, etc.)
  965. #
  966. if p.get('gisprompt', False):
  967. title_txt.SetLabel(title + ':')
  968. # GIS element entry
  969. if p.get('prompt','') not in ('color',
  970. 'cat',
  971. 'cats',
  972. 'subgroup',
  973. 'sigfile',
  974. 'separator',
  975. 'dbdriver',
  976. 'dbname',
  977. 'dbtable',
  978. 'dbcolumn',
  979. 'layer',
  980. 'location',
  981. 'mapset',
  982. 'dbase',
  983. 'coords',
  984. 'file',
  985. 'dir',
  986. 'colortable',
  987. 'barscale',
  988. 'northarrow',
  989. 'datasource',
  990. 'datasource_layer'):
  991. multiple = p.get('multiple', False)
  992. if p.get('age', '') == 'new':
  993. mapsets = [grass.gisenv()['MAPSET'],]
  994. else:
  995. mapsets = None
  996. if self.task.name in ('r.proj', 'v.proj') \
  997. and p.get('name', '') == 'input':
  998. selection = gselect.ProjSelect(parent = which_panel,
  999. isRaster = self.task.name == 'r.proj')
  1000. p['wxId'] = [ selection.GetId(), ]
  1001. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1002. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1003. else:
  1004. elem = p.get('element', None)
  1005. # hack for t.* modules
  1006. if elem in ('stds', 'map'):
  1007. orig_elem = elem
  1008. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  1009. if type_param:
  1010. elem = type_param.get('default', None)
  1011. # for t.(un)register:
  1012. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  1013. if maps_param and orig_elem == 'stds':
  1014. element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  1015. elem = element_dict[type_param.get('default')]
  1016. extraItems = None
  1017. if self._giface:
  1018. if hasattr(self._giface, "_model"):
  1019. extraItems = {_('Graphical Modeler') : self._giface.GetLayerList(p.get('prompt'))}
  1020. else:
  1021. layers = self._giface.GetLayerList()
  1022. if len(layers) > 0:
  1023. mapList = []
  1024. extraItems = {_('Map Display') : mapList}
  1025. for layer in layers:
  1026. if layer.type != p.get('prompt'):
  1027. continue
  1028. mapList.append(str(layer))
  1029. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  1030. size = globalvar.DIALOG_GSELECT_SIZE,
  1031. type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
  1032. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
  1033. extraItems = extraItems)
  1034. value = self._getValue(p)
  1035. if value:
  1036. selection.SetValue(value)
  1037. formatSelector = True
  1038. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1039. # we target the textctl here
  1040. textWin = selection.GetTextCtrl()
  1041. if globalvar.CheckWxVersion([3]):
  1042. p['wxId'] = [selection.GetId(), ]
  1043. else:
  1044. p['wxId'] = [textWin.GetId(), ]
  1045. if prompt != 'vector':
  1046. self.FindWindowById(p['wxId'][0]).Bind(wx.EVT_TEXT, self.OnSetValue)
  1047. if prompt == 'vector':
  1048. win = self.FindWindowById(p['wxId'][0])
  1049. # handlers should be bound in this order
  1050. # OnUpdateSelection depends on calling OnSetValue first which is bad
  1051. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1052. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1053. # if formatSelector and p.get('age', 'old') == 'old':
  1054. # # OGR supported (read-only)
  1055. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1056. # self.hsizer.Add(item = selection,
  1057. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1058. # border = 5)
  1059. # # format (native / ogr)
  1060. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1061. # label = " %s " % _("Format"),
  1062. # style = wx.RA_SPECIFY_ROWS,
  1063. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1064. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1065. # rbox.SetSelection(1)
  1066. # rbox.SetName('VectorFormat')
  1067. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1068. # self.hsizer.Add(item = rbox,
  1069. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1070. # wx.RIGHT | wx.ALIGN_TOP,
  1071. # border = 5)
  1072. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1073. # default = 'dir',
  1074. # exclude = ['file'])
  1075. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1076. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1077. # ogrSelection.SetName('OgrSelect')
  1078. # ogrSelection.Hide()
  1079. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1080. # p['wxId'].append(rbox.GetId())
  1081. # p['wxId'].append(ogrSelection.GetId())
  1082. # for win in ogrSelection.GetDsnWin():
  1083. # p['wxId'].append(win.GetId())
  1084. # else:
  1085. which_sizer.Add(item = selection, proportion = 0,
  1086. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1087. border = 5)
  1088. elif prompt == 'group':
  1089. win = self.FindWindowById(p['wxId'][0])
  1090. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1091. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1092. which_sizer.Add(item = selection, proportion = 0,
  1093. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1094. border = 5)
  1095. else:
  1096. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1097. showButton = True
  1098. try:
  1099. # if matplotlib is there
  1100. from timeline import frame
  1101. showButton = True
  1102. except ImportError:
  1103. showButton = False
  1104. else:
  1105. showButton = False
  1106. if showButton:
  1107. iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
  1108. bitmap = wx.Bitmap(os.path.join(globalvar.ICONDIR, iconTheme, 'map-info.png'))
  1109. bb = wx.BitmapButton(parent=which_panel, bitmap=bitmap)
  1110. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1111. bb.SetToolTipString(_("Show graphical representation of temporal extent of dataset(s) ."))
  1112. p['wxId'].append(bb.GetId())
  1113. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1114. hSizer.Add(item=selection, proportion=0,
  1115. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1116. border=5)
  1117. hSizer.Add(item=bb, proportion=0,
  1118. flag=wx.EXPAND|wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1119. border=5)
  1120. which_sizer.Add(hSizer)
  1121. else:
  1122. which_sizer.Add(item=selection, proportion=0,
  1123. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1124. border=5)
  1125. # subgroup
  1126. elif prompt == 'subgroup':
  1127. selection = gselect.SubGroupSelect(parent = which_panel)
  1128. p['wxId'] = [ selection.GetId() ]
  1129. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1130. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1131. which_sizer.Add(item = selection, proportion = 0,
  1132. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1133. border = 5)
  1134. # sigrature file
  1135. elif prompt == 'sigfile':
  1136. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1137. p['wxId'] = [ selection.GetId() ]
  1138. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1139. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1140. which_sizer.Add(item = selection, proportion = 0,
  1141. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1142. border = 5)
  1143. # separator
  1144. elif prompt == 'separator':
  1145. win = gselect.SeparatorSelect(parent = which_panel)
  1146. value = self._getValue(p)
  1147. win.SetValue(value)
  1148. p['wxId'] = [ win.GetId() ]
  1149. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1150. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1151. which_sizer.Add(item = win, proportion = 0,
  1152. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1153. border = 5)
  1154. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1155. elif prompt in ('dbdriver',
  1156. 'dbname',
  1157. 'dbtable',
  1158. 'dbcolumn',
  1159. 'layer',
  1160. 'location',
  1161. 'mapset',
  1162. 'dbase'):
  1163. if p.get('multiple', 'no') == 'yes':
  1164. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1165. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1166. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1167. else:
  1168. value = self._getValue(p)
  1169. if prompt == 'layer':
  1170. if p.get('element', 'layer') == 'layer_all':
  1171. all = True
  1172. else:
  1173. all = False
  1174. if p.get('age', 'old') == 'old':
  1175. win = gselect.LayerSelect(parent = which_panel,
  1176. all = all,
  1177. default = p['default'])
  1178. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1179. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1180. win.SetValue(str(value)) # default or previously set value
  1181. else:
  1182. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1183. min = 1, max = 100, initial = int(p['default']))
  1184. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1185. win.SetValue(int(value)) # default or previously set value
  1186. p['wxId'] = [ win.GetId() ]
  1187. elif prompt == 'dbdriver':
  1188. win = gselect.DriverSelect(parent = which_panel,
  1189. choices = p.get('values', []),
  1190. value = value)
  1191. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1192. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1193. elif prompt == 'dbname':
  1194. win = gselect.DatabaseSelect(parent = which_panel,
  1195. value = value)
  1196. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1197. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1198. elif prompt == 'dbtable':
  1199. if p.get('age', 'old') == 'old':
  1200. win = gselect.TableSelect(parent = which_panel)
  1201. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1202. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1203. else:
  1204. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1205. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1206. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1207. elif prompt == 'dbcolumn':
  1208. win = gselect.ColumnSelect(parent = which_panel,
  1209. value = value,
  1210. param = p,
  1211. multiple = p.get('multiple', False))
  1212. # A gselect.ColumnSelect is a combobox
  1213. # with two children: a textctl and a
  1214. # popupwindow; we target the textctl here
  1215. textWin = win.GetTextCtrl()
  1216. p['wxId'] = [ textWin.GetId(), ]
  1217. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1218. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1219. elif prompt == 'location':
  1220. win = gselect.LocationSelect(parent = which_panel,
  1221. value = value)
  1222. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1223. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1224. elif prompt == 'mapset':
  1225. if p.get('age', 'old') == 'old':
  1226. new = False
  1227. else:
  1228. new = True
  1229. win = gselect.MapsetSelect(parent = which_panel,
  1230. value = value, new = new,
  1231. multiple = p.get('multiple', False))
  1232. textWin = win.GetTextCtrl()
  1233. p['wxId'] = [ textWin.GetId(), win.GetId() ]
  1234. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1235. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1236. elif prompt == 'dbase':
  1237. win = gselect.DbaseSelect(parent = which_panel,
  1238. changeCallback = self.OnSetValue)
  1239. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1240. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1241. if 'wxId' not in p:
  1242. try:
  1243. p['wxId'] = [ win.GetId(), ]
  1244. except AttributeError:
  1245. pass
  1246. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1247. if prompt == 'dbname':
  1248. flags |= wx.EXPAND
  1249. which_sizer.Add(item = win, proportion = 0,
  1250. flag = flags, border = 5)
  1251. # color entry
  1252. elif prompt == 'color':
  1253. default_color = (200,200,200)
  1254. label_color = _("Select Color")
  1255. if p.get('default','') != '':
  1256. default_color, label_color = utils.color_resolve(p['default'])
  1257. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1258. default_color, label_color = utils.color_resolve(p['value'])
  1259. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1260. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1261. else:
  1262. this_sizer = which_sizer
  1263. colorSize = 150
  1264. # For color selectors, this is a three-member array, holding the IDs of
  1265. # the color picker, the text control for multiple colors (or None),
  1266. # and either a "transparent" checkbox or None
  1267. p['wxId'] = [None] * 3
  1268. if p.get('multiple', False):
  1269. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1270. this_sizer.Add(item = txt, proportion = 1,
  1271. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1272. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1273. colorSize = 40
  1274. label_color = ''
  1275. p['wxId'][1] = txt.GetId()
  1276. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1277. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1278. label = label_color, colour = default_color,
  1279. pos = wx.DefaultPosition, size = (colorSize, 32))
  1280. this_sizer.Add(item = btn_colour, proportion = 0,
  1281. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1282. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1283. p['wxId'][0] = btn_colour.GetId()
  1284. if p.get('element', '') == 'color_none':
  1285. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1286. if p.get('value','') == "none":
  1287. none_check.SetValue(True)
  1288. else:
  1289. none_check.SetValue(False)
  1290. this_sizer.Add(item = none_check, proportion = 0,
  1291. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1292. which_sizer.Add(this_sizer)
  1293. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1294. p['wxId'][2] = none_check.GetId()
  1295. # file selector
  1296. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1297. if p.get('age', 'new') == 'new':
  1298. fmode = wx.FD_SAVE
  1299. else:
  1300. fmode = wx.FD_OPEN
  1301. # check wildcard
  1302. try:
  1303. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1304. except:
  1305. fExt = None
  1306. if not fExt:
  1307. fMask = '*'
  1308. else:
  1309. fMask = '%s files (*%s)|*%s|Files (*)|*' % (fExt[1:].upper(), fExt, fExt)
  1310. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1311. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1312. dialogTitle = _('Choose %s') % \
  1313. p.get('description', _('file')).lower(),
  1314. buttonText = _('Browse'),
  1315. startDirectory = os.getcwd(), fileMode = fmode,
  1316. changeCallback = self.OnSetValue)
  1317. value = self._getValue(p)
  1318. if value:
  1319. fbb.SetValue(value) # parameter previously set
  1320. which_sizer.Add(item = fbb, proportion = 0,
  1321. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1322. # A file browse button is a combobox with two children:
  1323. # a textctl and a button;
  1324. # we have to target the button here
  1325. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1326. if p.get('age', 'new') == 'old' and \
  1327. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1328. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1329. # widget for interactive input
  1330. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1331. style = wx.TE_MULTILINE,
  1332. size = (-1, 75))
  1333. if p.get('value', '') and os.path.isfile(p['value']):
  1334. f = open(p['value'])
  1335. ifbb.SetValue(''.join(f.readlines()))
  1336. f.close()
  1337. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1338. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1339. btnLoad.SetToolTipString(_("Load and edit content of a file"))
  1340. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1341. btnSave = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Save as"))
  1342. btnSave.SetToolTipString(_("Save content to a file for further use"))
  1343. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1344. fileContentLabel = wx.StaticText(parent=which_panel,
  1345. id=wx.ID_ANY,
  1346. label=_('or enter values directly:'))
  1347. fileContentLabel.SetToolTipString(
  1348. _("Enter file content directly instead of specifying"
  1349. " a file."
  1350. " Temporary file will be automatically created."))
  1351. which_sizer.Add(item=fileContentLabel,
  1352. proportion = 0,
  1353. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1354. which_sizer.Add(item = ifbb, proportion = 1,
  1355. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1356. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1357. btnSizer.Add(item = btnLoad, proportion = 0,
  1358. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1359. btnSizer.Add(item = btnSave, proportion = 0,
  1360. flag = wx.ALIGN_RIGHT)
  1361. which_sizer.Add(item = btnSizer, proportion = 0,
  1362. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1363. p['wxId'].append(ifbb.GetId())
  1364. p['wxId'].append(btnLoad.GetId())
  1365. p['wxId'].append(btnSave.GetId())
  1366. # directory selector
  1367. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1368. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1369. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1370. dialogTitle = _('Choose %s') % \
  1371. p.get('description', _('Directory')),
  1372. buttonText = _('Browse'),
  1373. startDirectory = os.getcwd(),
  1374. changeCallback = self.OnSetValue)
  1375. value = self._getValue(p)
  1376. if value:
  1377. fbb.SetValue(value) # parameter previously set
  1378. which_sizer.Add(item = fbb, proportion = 0,
  1379. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1380. # A file browse button is a combobox with two children:
  1381. # a textctl and a button;
  1382. # we have to target the button here
  1383. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1384. # interactive inserting of coordinates from map window
  1385. elif prompt == 'coords':
  1386. # interactive inserting if layer manager is accessible
  1387. if self._giface:
  1388. win = gselect.CoordinatesSelect(parent = which_panel,
  1389. giface = self._giface,
  1390. multiple = p.get('multiple', False),
  1391. param = p)
  1392. p['wxId'] = [win.GetTextWin().GetId()]
  1393. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1394. # bind closing event because destructor is not working properly
  1395. if hasattr(self.parent, 'dialogClosing'):
  1396. self.parent.dialogClosing.connect(win.OnClose)
  1397. # normal text field
  1398. else:
  1399. win = wx.TextCtrl(parent = which_panel)
  1400. p['wxId'] = [win.GetId()]
  1401. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1402. which_sizer.Add(item = win,
  1403. proportion = 0,
  1404. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1405. border = 5)
  1406. elif prompt in ('cat', 'cats'):
  1407. # interactive selection of vector categories if layer manager is accessible
  1408. if self._giface:
  1409. win = gselect.VectorCategorySelect(parent = which_panel, giface = self._giface, task=self.task)
  1410. p['wxId'] = [win.GetTextWin().GetId()]
  1411. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1412. # bind closing event because destructor is not working properly
  1413. if hasattr(self.parent, 'dialogClosing'):
  1414. self.parent.dialogClosing.connect(win.OnClose)
  1415. # normal text field
  1416. else:
  1417. win = wx.TextCtrl(parent = which_panel)
  1418. value = self._getValue(p)
  1419. win.SetValue(value)
  1420. p['wxId'] = [win.GetId()]
  1421. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1422. which_sizer.Add(item = win,
  1423. proportion = 0,
  1424. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1425. border = 5)
  1426. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1427. if prompt == 'colortable':
  1428. cb = ColorTablesComboBox(parent=which_panel, value=p.get('default',''),
  1429. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1430. choices=valuelist)
  1431. elif prompt == 'barscale':
  1432. cb = BarscalesComboBox(parent=which_panel, value=p.get('default',''),
  1433. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1434. choices=valuelist)
  1435. elif prompt == 'northarrow':
  1436. cb = NArrowsComboBox(parent=which_panel, value=p.get('default',''),
  1437. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1438. choices=valuelist)
  1439. value = self._getValue(p)
  1440. if value:
  1441. cb.SetValue(value) # parameter previously set
  1442. which_sizer.Add(item = cb, proportion = 0,
  1443. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1444. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1445. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1446. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1447. if p.get('guidependency', ''):
  1448. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1449. elif prompt == 'datasource':
  1450. win = gselect.GdalSelect(parent = parent, panel = which_panel,
  1451. ogr = True)
  1452. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1453. win.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1454. p['wxId'] = [win.GetId(),
  1455. win.fileWidgets['browse'].GetChildren()[1].GetId(),
  1456. win.dirWidgets['browse'].GetChildren()[1].GetId(),
  1457. win.dbWidgets['choice'].GetId()]
  1458. which_sizer.Add(item = win, proportion = 0,
  1459. flag = wx.EXPAND)
  1460. elif prompt == 'datasource_layer':
  1461. self.win1 = LayersList(parent = which_panel, columns = [_('Layer id'),
  1462. _('Layer name'),
  1463. _('Feature type'),
  1464. _('Projection match')])
  1465. which_sizer.Add(item = self.win1, proportion = 0,
  1466. flag = wx.EXPAND | wx.ALL, border = 3)
  1467. porf = self.task.get_param('input', element = 'name', raiseError = False)
  1468. winDataSource = self.FindWindowById(porf['wxId'][0])
  1469. winDataSource.reloadDataRequired.connect(lambda data: self.win1.LoadData(data, False))
  1470. p['wxId'] = [self.win1.GetId()]
  1471. def OnCheckItem(index, flag):
  1472. layers = list()
  1473. for layer, match in self.win1.GetLayers():
  1474. layers.append(layer)
  1475. porf = self.task.get_param('layer', element = 'name', raiseError = False)
  1476. porf['value'] = ','.join(layers)
  1477. self.OnUpdateValues() # TODO: replace by signal
  1478. self.win1.OnCheckItem = OnCheckItem
  1479. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  1480. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1481. label = _("Parameterized in model"))
  1482. parChk.SetName('ModelParam')
  1483. parChk.SetValue(p.get('parameterized', False))
  1484. if 'wxId' in p:
  1485. p['wxId'].append(parChk.GetId())
  1486. else:
  1487. p['wxId'] = [ parChk.GetId() ]
  1488. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1489. which_sizer.Add(item = parChk, proportion = 0,
  1490. flag = wx.LEFT, border = 20)
  1491. if title_txt is not None:
  1492. # create tooltip if given
  1493. if len(p['values_desc']) > 0:
  1494. if tooltip:
  1495. tooltip += 2 * os.linesep
  1496. else:
  1497. tooltip = ''
  1498. if len(p['values']) == len(p['values_desc']):
  1499. for i in range(len(p['values'])):
  1500. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1501. tooltip.strip(os.linesep)
  1502. if tooltip:
  1503. title_txt.SetToolTipString(tooltip)
  1504. if p == first_param:
  1505. if 'wxId' in p and len(p['wxId']) > 0:
  1506. win = self.FindWindowById(p['wxId'][0])
  1507. win.SetFocus()
  1508. #
  1509. # set widget relations for OnUpdateSelection
  1510. #
  1511. pMap = None
  1512. pLayer = []
  1513. pDriver = None
  1514. pDatabase = None
  1515. pTable = None
  1516. pColumn = []
  1517. pGroup = None
  1518. pSubGroup = None
  1519. pSigFile = []
  1520. pDbase = None
  1521. pLocation = None
  1522. pMapset = None
  1523. for p in self.task.params:
  1524. guidep = p.get('guidependency', '')
  1525. if guidep:
  1526. # fixed options dependency defined
  1527. options = guidep.split(',')
  1528. for opt in options:
  1529. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1530. if pOpt and id:
  1531. if 'wxId-bind' not in p:
  1532. p['wxId-bind'] = list()
  1533. p['wxId-bind'] += pOpt['wxId']
  1534. continue
  1535. if p.get('gisprompt', False) == False:
  1536. continue
  1537. prompt = p.get('prompt', '')
  1538. if prompt in ('raster', 'vector'):
  1539. name = p.get('name', '')
  1540. if name in ('map', 'input'):
  1541. pMap = p
  1542. elif prompt == 'layer':
  1543. pLayer.append(p)
  1544. elif prompt == 'dbcolumn':
  1545. pColumn.append(p)
  1546. elif prompt == 'dbdriver':
  1547. pDriver = p
  1548. elif prompt == 'dbname':
  1549. pDatabase = p
  1550. elif prompt == 'dbtable':
  1551. pTable = p
  1552. elif prompt == 'group':
  1553. pGroup = p
  1554. elif prompt == 'subgroup':
  1555. pSubGroup = p
  1556. elif prompt == 'sigfile':
  1557. pSigFile.append(p)
  1558. elif prompt == 'dbase':
  1559. pDbase = p
  1560. elif prompt == 'location':
  1561. pLocation = p
  1562. elif prompt == 'mapset':
  1563. pMapset = p
  1564. # collect ids
  1565. pColumnIds = []
  1566. for p in pColumn:
  1567. pColumnIds += p['wxId']
  1568. pLayerIds = []
  1569. for p in pLayer:
  1570. pLayerIds += p['wxId']
  1571. pSigFileIds = []
  1572. for p in pSigFile:
  1573. pSigFileIds += p['wxId']
  1574. # set wxId-bindings
  1575. if pMap:
  1576. pMap['wxId-bind'] = []
  1577. if pLayer:
  1578. pMap['wxId-bind'] += pLayerIds
  1579. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1580. if pLayer:
  1581. for p in pLayer:
  1582. p['wxId-bind'] = copy.copy(pColumnIds)
  1583. if pDriver and pTable:
  1584. pDriver['wxId-bind'] = pTable['wxId']
  1585. if pDatabase and pTable:
  1586. pDatabase['wxId-bind'] = pTable['wxId']
  1587. if pTable and pColumnIds:
  1588. pTable['wxId-bind'] = pColumnIds
  1589. if pGroup and pSubGroup:
  1590. if pSigFile:
  1591. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1592. pSubGroup['wxId-bind'] = pSigFileIds
  1593. else:
  1594. pGroup['wxId-bind'] = pSubGroup['wxId']
  1595. if pDbase and pLocation:
  1596. pDbase['wxId-bind'] = pLocation['wxId']
  1597. if pLocation and pMapset:
  1598. pLocation['wxId-bind'] = pMapset['wxId']
  1599. if pLocation and pMapset and pMap:
  1600. # pLocation['wxId-bind'] += pMap['wxId']
  1601. pMapset['wxId-bind'] = pMap['wxId']
  1602. #
  1603. # determine panel size
  1604. #
  1605. maxsizes = (0, 0)
  1606. for section in sections:
  1607. tab[section].SetSizer(tabsizer[section])
  1608. tabsizer[section].Fit(tab[section])
  1609. tab[section].Layout()
  1610. minsecsizes = tabsizer[section].GetSize()
  1611. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1612. # TODO: be less arbitrary with these 600
  1613. self.panelMinHeight = 100
  1614. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1615. for section in sections:
  1616. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1617. # add pages to notebook
  1618. imageList = wx.ImageList(16, 16)
  1619. self.notebook.AssignImageList(imageList)
  1620. for section in sections:
  1621. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1622. index = self.AddBitmapToImageList(section, imageList)
  1623. if index >= 0:
  1624. self.notebook.SetPageImage(section, index)
  1625. # are we running from command line?
  1626. ### add 'command output' tab regardless standalone dialog
  1627. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1628. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1629. from gui_core.goutput import GConsoleWindow
  1630. self._gconsole = GConsole(guiparent = self.notebook, giface = self._giface)
  1631. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1632. self._gconsole.Bind(EVT_CMD_RUN,
  1633. lambda event:
  1634. self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
  1635. self._gconsole.Bind(EVT_CMD_DONE,
  1636. lambda event:
  1637. self._switchPageHandler(event = event, notification=Notification.RAISE_WINDOW))
  1638. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1639. else:
  1640. self.goutput = None
  1641. self._gconsole = None
  1642. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.get_name())
  1643. if not self.manualTab.GetFile():
  1644. self.manualTab.Hide()
  1645. else:
  1646. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1647. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1648. if index >= 0:
  1649. self.notebook.SetPageImage('manual', index)
  1650. if self.manualTab.IsLoaded():
  1651. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1652. self.notebook.SetSelection(0)
  1653. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1654. self.SetSizer(panelsizer)
  1655. panelsizer.Fit(self.notebook)
  1656. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1657. def _getValue(self, p):
  1658. """Get value or default value of given parameter
  1659. :param p: parameter directory
  1660. """
  1661. if p.get('value', '') != '':
  1662. return p['value']
  1663. return p.get('default', '')
  1664. def OnFileLoad(self, event):
  1665. """Load file to interactive input"""
  1666. me = event.GetId()
  1667. win = dict()
  1668. for p in self.task.params:
  1669. if 'wxId' in p and me in p['wxId']:
  1670. win['file'] = self.FindWindowById(p['wxId'][0])
  1671. win['text'] = self.FindWindowById(p['wxId'][1])
  1672. break
  1673. if not win:
  1674. return
  1675. path = win['file'].GetValue()
  1676. if not path:
  1677. gcmd.GMessage(parent = self,
  1678. message = _("Nothing to load."))
  1679. return
  1680. data = ''
  1681. try:
  1682. f = open(path, "r")
  1683. except IOError as e:
  1684. gcmd.GError(parent = self, showTraceback = False,
  1685. message = _("Unable to load file.\n\nReason: %s") % e)
  1686. return
  1687. try:
  1688. data = f.read()
  1689. finally:
  1690. f.close()
  1691. win['text'].SetValue(data)
  1692. def OnFileSave(self, event):
  1693. """Save interactive input to the file"""
  1694. wId = event.GetId()
  1695. win = {}
  1696. for p in self.task.params:
  1697. if wId in p.get('wxId', []):
  1698. win['file'] = self.FindWindowById(p['wxId'][0])
  1699. win['text'] = self.FindWindowById(p['wxId'][1])
  1700. break
  1701. if not win:
  1702. return
  1703. text = win['text'].GetValue()
  1704. if not text:
  1705. gcmd.GMessage(parent = self,
  1706. message = _("Nothing to save."))
  1707. return
  1708. dlg = wx.FileDialog(parent = self,
  1709. message = _("Save input as..."),
  1710. defaultDir = os.getcwd(),
  1711. style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  1712. if dlg.ShowModal() == wx.ID_OK:
  1713. path = dlg.GetPath()
  1714. enc = locale.getdefaultlocale()[1]
  1715. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1716. try:
  1717. f.write(text + os.linesep)
  1718. finally:
  1719. f.close()
  1720. win['file'].SetValue(path)
  1721. dlg.Destroy()
  1722. def OnFileText(self, event):
  1723. """File input interactively entered"""
  1724. text = event.GetString()
  1725. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1726. if not p:
  1727. return # should not happen
  1728. win = self.FindWindowById(p['wxId'][0])
  1729. if text:
  1730. filename = win.GetValue()
  1731. if not filename or filename == p['default']: # m.proj has - as default
  1732. filename = grass.tempfile()
  1733. win.SetValue(filename)
  1734. enc = locale.getdefaultlocale()[1]
  1735. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1736. try:
  1737. f.write(text)
  1738. if text[-1] != os.linesep:
  1739. f.write(os.linesep)
  1740. finally:
  1741. f.close()
  1742. else:
  1743. win.SetValue('')
  1744. def OnVectorFormat(self, event):
  1745. """Change vector format (native / ogr).
  1746. Currently unused.
  1747. """
  1748. sel = event.GetSelection()
  1749. idEvent = event.GetId()
  1750. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1751. if not p:
  1752. return # should not happen
  1753. # detect windows
  1754. winNative = None
  1755. winOgr = None
  1756. for id in p['wxId']:
  1757. if id == idEvent:
  1758. continue
  1759. name = self.FindWindowById(id).GetName()
  1760. if name == 'Select':
  1761. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1762. elif name == 'OgrSelect':
  1763. winOgr = self.FindWindowById(id)
  1764. # enable / disable widgets & update values
  1765. rbox = self.FindWindowByName('VectorFormat')
  1766. self.hsizer.Remove(rbox)
  1767. if sel == 0: # -> native
  1768. winOgr.Hide()
  1769. self.hsizer.Remove(winOgr)
  1770. self.hsizer.Add(item = winNative,
  1771. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1772. border = 5)
  1773. winNative.Show()
  1774. p['value'] = winNative.GetValue()
  1775. elif sel == 1: # -> OGR
  1776. sizer = wx.BoxSizer(wx.VERTICAL)
  1777. winNative.Hide()
  1778. self.hsizer.Remove(winNative)
  1779. sizer.Add(item = winOgr)
  1780. winOgr.Show()
  1781. p['value'] = winOgr.GetDsn()
  1782. self.hsizer.Add(item = sizer,
  1783. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1784. border = 5)
  1785. self.hsizer.Add(item = rbox,
  1786. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1787. wx.RIGHT | wx.ALIGN_TOP,
  1788. border = 5)
  1789. self.hsizer.Layout()
  1790. self.Layout()
  1791. self.OnUpdateValues()
  1792. self.OnUpdateSelection(event)
  1793. def OnUpdateDialog(self, event):
  1794. for fn, kwargs in event.data.iteritems():
  1795. fn(**kwargs)
  1796. self.parent.updateValuesHook()
  1797. def OnVerbosity(self, event):
  1798. """Verbosity level changed"""
  1799. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1800. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1801. if event.IsChecked():
  1802. if event.GetId() == verbose.GetId():
  1803. if quiet.IsChecked():
  1804. quiet.SetValue(False)
  1805. self.task.get_flag('quiet')['value'] = False
  1806. else:
  1807. if verbose.IsChecked():
  1808. verbose.SetValue(False)
  1809. self.task.get_flag('verbose')['value'] = False
  1810. event.Skip()
  1811. def OnPageChange(self, event):
  1812. if not event:
  1813. sel = self.notebook.GetSelection()
  1814. else:
  1815. sel = event.GetSelection()
  1816. idx = self.notebook.GetPageIndexByName('manual')
  1817. if idx > -1 and sel == idx:
  1818. # calling LoadPage() is strangely time-consuming (only first call)
  1819. # FIXME: move to helpPage.__init__()
  1820. if not self.manualTab.IsLoaded():
  1821. wx.Yield()
  1822. self.manualTab.LoadPage()
  1823. self.Layout()
  1824. if event:
  1825. # skip is needed for wx.Notebook on Windows
  1826. event.Skip()
  1827. # this is needed for dialogs launched from layer manager
  1828. # event is somehow propagated?
  1829. event.StopPropagation()
  1830. def _switchPageHandler(self, event, notification):
  1831. self._switchPage(notification=notification)
  1832. event.Skip()
  1833. def _switchPage(self, notification):
  1834. """Manages @c 'output' notebook page according to event notification."""
  1835. if notification == Notification.HIGHLIGHT:
  1836. self.notebook.HighlightPageByName('output')
  1837. if notification == Notification.MAKE_VISIBLE:
  1838. self.notebook.SetSelectionByName('output')
  1839. if notification == Notification.RAISE_WINDOW:
  1840. self.notebook.SetSelectionByName('output')
  1841. self.SetFocus()
  1842. self.Raise()
  1843. def OnColorChange(self, event):
  1844. myId = event.GetId()
  1845. for p in self.task.params:
  1846. if 'wxId' in p and myId in p['wxId']:
  1847. multiple = p['wxId'][1] is not None # multiple colors
  1848. hasTansp = p['wxId'][2] is not None
  1849. if multiple:
  1850. # selected color is added at the end of textCtrl
  1851. colorchooser = wx.FindWindowById(p['wxId'][0])
  1852. new_color = colorchooser.GetValue()[:]
  1853. new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
  1854. textCtrl = wx.FindWindowById(p['wxId'][1])
  1855. val = textCtrl.GetValue()
  1856. sep = ','
  1857. if val and val[-1] != sep:
  1858. val += sep
  1859. val += new_label
  1860. textCtrl.SetValue(val)
  1861. p[ 'value' ] = val
  1862. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  1863. p[ 'value' ] = 'none'
  1864. else:
  1865. colorchooser = wx.FindWindowById(p['wxId'][0])
  1866. new_color = colorchooser.GetValue()[:]
  1867. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1868. # under wx2.8.1
  1869. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1870. colorchooser.SetLabel(new_label)
  1871. colorchooser.SetColour(new_color)
  1872. colorchooser.Refresh()
  1873. p[ 'value' ] = colorchooser.GetLabel()
  1874. self.OnUpdateValues()
  1875. def OnUpdateValues(self, event = None):
  1876. """If we were part of a richer interface, report back the
  1877. current command being built.
  1878. This method should be set by the parent of this panel if
  1879. needed. It's a hook, actually. Beware of what is 'self' in
  1880. the method def, though. It will be called with no arguments.
  1881. """
  1882. pass
  1883. def OnCheckBoxMulti(self, event):
  1884. """Fill the values as a ','-separated string according to
  1885. current status of the checkboxes.
  1886. """
  1887. me = event.GetId()
  1888. theParam = None
  1889. for p in self.task.params:
  1890. if 'wxId' in p and me in p['wxId']:
  1891. theParam = p
  1892. myIndex = p['wxId'].index(me)
  1893. # Unpack current value list
  1894. currentValues = {}
  1895. for isThere in theParam.get('value', '').split(','):
  1896. currentValues[isThere] = 1
  1897. theValue = theParam['values'][myIndex]
  1898. if event.Checked():
  1899. currentValues[ theValue ] = 1
  1900. else:
  1901. del currentValues[ theValue ]
  1902. # Keep the original order, so that some defaults may be recovered
  1903. currentValueList = []
  1904. for v in theParam['values']:
  1905. if v in currentValues:
  1906. currentValueList.append(v)
  1907. # Pack it back
  1908. theParam['value'] = ','.join(currentValueList)
  1909. self.OnUpdateValues()
  1910. event.Skip()
  1911. def OnSetValue(self, event):
  1912. """Retrieve the widget value and set the task value field
  1913. accordingly.
  1914. Use for widgets that have a proper GetValue() method, i.e. not
  1915. for selectors.
  1916. """
  1917. myId = event.GetId()
  1918. me = wx.FindWindowById(myId)
  1919. name = me.GetName()
  1920. found = False
  1921. for porf in self.task.params + self.task.flags:
  1922. if 'wxId' not in porf:
  1923. continue
  1924. if myId in porf['wxId']:
  1925. found = True
  1926. break
  1927. if not found:
  1928. return
  1929. if name == 'GdalSelect':
  1930. porf['value'] = event.dsn
  1931. elif name == 'ModelParam':
  1932. porf['parameterized'] = me.IsChecked()
  1933. elif name == 'GdalSelectDataSource':
  1934. win = self.FindWindowById(porf['wxId'][0])
  1935. porf['value'] = win.GetDsn()
  1936. pLayer = self.task.get_param('layer', element = 'name', raiseError = False)
  1937. pLayer['value'] = ''
  1938. else:
  1939. if isinstance(me, wx.SpinCtrl):
  1940. porf['value'] = str(me.GetValue())
  1941. elif isinstance(me, wx.Choice):
  1942. porf['value'] = me.GetStringSelection()
  1943. else:
  1944. porf['value'] = me.GetValue()
  1945. self.OnUpdateValues(event)
  1946. event.Skip()
  1947. def OnSetSymbol(self, event):
  1948. """Shows dialog for symbol selection"""
  1949. myId = event.GetId()
  1950. for p in self.task.params:
  1951. if 'wxId' in p and myId in p['wxId']:
  1952. from gui_core.dialogs import SymbolDialog
  1953. dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
  1954. currentSymbol = p['value'])
  1955. if dlg.ShowModal() == wx.ID_OK:
  1956. img = dlg.GetSelectedSymbolPath()
  1957. p['value'] = dlg.GetSelectedSymbolName()
  1958. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1959. label = wx.FindWindowById(p['wxId'][1])
  1960. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1961. label.SetLabel(p['value'])
  1962. self.OnUpdateValues(event)
  1963. dlg.Destroy()
  1964. def OnTimelineTool(self, event):
  1965. """Show Timeline Tool with dataset(s) from gselect.
  1966. .. todo::
  1967. update from gselect automatically
  1968. """
  1969. myId = event.GetId()
  1970. for p in self.task.params:
  1971. if 'wxId' in p and myId in p['wxId']:
  1972. select = self.FindWindowById(p['wxId'][0])
  1973. if not select.GetValue():
  1974. gcmd.GMessage(parent=self, message=_("No dataset given."))
  1975. return
  1976. datasets = select.GetValue().split(',')
  1977. from timeline import frame
  1978. frame.run(parent=self, datasets=datasets)
  1979. def OnUpdateSelection(self, event):
  1980. """Update dialog (layers, tables, columns, etc.)
  1981. """
  1982. if not hasattr(self.parent, "updateThread"):
  1983. if event:
  1984. event.Skip()
  1985. return
  1986. if event:
  1987. self.parent.updateThread.Update(UpdateDialog,
  1988. self,
  1989. event,
  1990. event.GetId(),
  1991. self.task)
  1992. else:
  1993. self.parent.updateThread.Update(UpdateDialog,
  1994. self,
  1995. None,
  1996. None,
  1997. self.task)
  1998. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1999. """Produce a command line string (list) or feeding into GRASS.
  2000. :param ignoreErrors: True then it will return whatever has been
  2001. built so far, even though it would not be
  2002. a correct command for GRASS
  2003. """
  2004. try:
  2005. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  2006. ignoreRequired = ignoreRequired)
  2007. except ValueError as err:
  2008. dlg = wx.MessageDialog(parent = self,
  2009. message = unicode(err),
  2010. caption = _("Error in %s") % self.task.name,
  2011. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  2012. dlg.ShowModal()
  2013. dlg.Destroy()
  2014. cmd = None
  2015. return cmd
  2016. def OnSize(self, event):
  2017. width = event.GetSize()[0]
  2018. fontsize = self.GetFont().GetPointSize()
  2019. text_width = max(width / (fontsize - 3), 70)
  2020. for id in self.label_id:
  2021. win = self.FindWindowById(id)
  2022. label = win.GetLabel()
  2023. label_new = '\n'.join(textwrap.wrap(label, text_width))
  2024. win.SetLabel(label_new)
  2025. event.Skip()
  2026. def AddBitmapToImageList(self, section, imageList):
  2027. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  2028. iconSectionDict = {'manual': os.path.join(globalvar.ICONDIR, iconTheme, 'help.png')}
  2029. if section in iconSectionDict.keys():
  2030. image = wx.Image(iconSectionDict[section]).Scale(16, 16, wx.IMAGE_QUALITY_HIGH)
  2031. idx = imageList.Add(wx.BitmapFromImage(image))
  2032. return idx
  2033. return -1
  2034. class GUI:
  2035. def __init__(self, parent = None, giface = None, show = True, modal = False,
  2036. centreOnParent = False, checkError = False):
  2037. """Parses GRASS commands when module is imported and used from
  2038. Layer Manager.
  2039. """
  2040. self.parent = parent
  2041. self.show = show
  2042. self.modal = modal
  2043. self._giface = giface
  2044. self.centreOnParent = centreOnParent
  2045. self.checkError = checkError
  2046. self.grass_task = None
  2047. self.cmd = list()
  2048. global _blackList
  2049. if self.parent:
  2050. _blackList['enabled'] = True
  2051. else:
  2052. _blackList['enabled'] = False
  2053. def GetCmd(self):
  2054. """Get validated command"""
  2055. return self.cmd
  2056. def ParseCommand(self, cmd, completed = None):
  2057. """Parse command
  2058. Note: cmd is given as list
  2059. If command is given with options, return validated cmd list:
  2060. - add key name for first parameter if not given
  2061. - change mapname to mapname@mapset
  2062. """
  2063. dcmd_params = {}
  2064. if completed == None:
  2065. get_dcmd = None
  2066. layer = None
  2067. dcmd_params = None
  2068. else:
  2069. get_dcmd = completed[0]
  2070. layer = completed[1]
  2071. if completed[2]:
  2072. dcmd_params.update(completed[2])
  2073. # parse the interface decription
  2074. try:
  2075. global _blackList
  2076. self.grass_task = gtask.parse_interface(cmd[0],
  2077. blackList = _blackList)
  2078. except (grass.ScriptError, ValueError) as e:
  2079. raise gcmd.GException(e.value)
  2080. # if layer parameters previously set, re-insert them into dialog
  2081. if completed is not None:
  2082. if 'params' in dcmd_params:
  2083. self.grass_task.params = dcmd_params['params']
  2084. if 'flags' in dcmd_params:
  2085. self.grass_task.flags = dcmd_params['flags']
  2086. err = list()
  2087. # update parameters if needed && validate command
  2088. if len(cmd) > 1:
  2089. i = 0
  2090. cmd_validated = [cmd[0]]
  2091. for option in cmd[1:]:
  2092. if option[0] == '-': # flag
  2093. if option[1] == '-':
  2094. self.grass_task.set_flag(option[2:], True)
  2095. else:
  2096. self.grass_task.set_flag(option[1], True)
  2097. cmd_validated.append(option)
  2098. else: # parameter
  2099. try:
  2100. key, value = option.split('=', 1)
  2101. except ValueError:
  2102. if self.grass_task.firstParam:
  2103. if i == 0: # add key name of first parameter if not given
  2104. key = self.grass_task.firstParam
  2105. value = option
  2106. else:
  2107. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  2108. else:
  2109. continue
  2110. task = self.grass_task.get_param(key, raiseError = False)
  2111. if not task:
  2112. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  2113. { 'cmd' : cmd[0],
  2114. 'key' : key })
  2115. continue
  2116. multiple = task['multiple']
  2117. element = task['element']
  2118. # to filter out g.copy, g.rename
  2119. key_desc = task['key_desc']
  2120. # do we need to find mapset for each of multiple maps?
  2121. if element in ['cell', 'vector'] and not multiple and len(key_desc) != 2:
  2122. # mapname -> mapname@mapset
  2123. try:
  2124. name, mapset = value.split('@')
  2125. except ValueError:
  2126. mapset = grass.find_file(value, element)['mapset']
  2127. curr_mapset = grass.gisenv()['MAPSET']
  2128. if mapset and mapset != curr_mapset:
  2129. value = value + '@' + mapset
  2130. self.grass_task.set_param(key, value)
  2131. cmd_validated.append(key + '=' + value)
  2132. i += 1
  2133. # update original command list
  2134. cmd = cmd_validated
  2135. if self.show is not None:
  2136. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  2137. task_description = self.grass_task,
  2138. get_dcmd = get_dcmd, layer = layer)
  2139. else:
  2140. self.mf = None
  2141. if get_dcmd is not None:
  2142. # update only propwin reference
  2143. get_dcmd(dcmd = None, layer = layer, params = None,
  2144. propwin = self.mf)
  2145. if self.show is not None:
  2146. self.mf.notebookpanel.OnUpdateSelection(None)
  2147. if self.show is True:
  2148. if self.parent and self.centreOnParent:
  2149. self.mf.CentreOnParent()
  2150. else:
  2151. self.mf.CenterOnScreen()
  2152. self.mf.Show(self.show)
  2153. self.mf.MakeModal(self.modal)
  2154. else:
  2155. self.mf.OnApply(None)
  2156. self.cmd = cmd
  2157. if self.checkError:
  2158. return self.grass_task, err
  2159. else:
  2160. return self.grass_task
  2161. def GetCommandInputMapParamKey(self, cmd):
  2162. """Get parameter key for input raster/vector map
  2163. :param cmd: module name
  2164. :return: parameter key
  2165. :return: None on failure
  2166. """
  2167. # parse the interface decription
  2168. if not self.grass_task:
  2169. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2170. self.grass_task = gtask.processTask(tree).get_task()
  2171. for p in self.grass_task.params:
  2172. if p.get('name', '') in ('input', 'map'):
  2173. age = p.get('age', '')
  2174. prompt = p.get('prompt', '')
  2175. element = p.get('element', '')
  2176. if age == 'old' and \
  2177. element in ('cell', 'grid3', 'vector') and \
  2178. prompt in ('raster', '3d-raster', 'vector'):
  2179. return p.get('name', None)
  2180. return None
  2181. class GrassGUIApp(wx.App):
  2182. """Stand-alone GRASS command GUI
  2183. """
  2184. def __init__(self, grass_task):
  2185. self.grass_task = grass_task
  2186. wx.App.__init__(self, False)
  2187. def OnInit(self):
  2188. msg = self.grass_task.get_error_msg()
  2189. if msg:
  2190. gcmd.GError(msg + '\n\n' +
  2191. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2192. return True
  2193. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  2194. self.mf.CentreOnScreen()
  2195. self.mf.Show(True)
  2196. self.SetTopWindow(self.mf)
  2197. return True
  2198. USAGE_MESSAGE = """Usage:
  2199. {name} <grass module>
  2200. {name} <full path to file>
  2201. python {name} <grass module>
  2202. Test:
  2203. python {name} test
  2204. python {name} g.region
  2205. python {name} "g.region -p"
  2206. python {name} temporal/t.list/t.list.py"""
  2207. if __name__ == "__main__":
  2208. if len(sys.argv) == 1:
  2209. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2210. if sys.argv[1] != 'test':
  2211. q = wx.LogNull()
  2212. from core.debug import Debug
  2213. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2214. cmd = utils.split(sys.argv[1])
  2215. task = gtask.grassTask(cmd[0])
  2216. task.set_options(cmd[1:])
  2217. Debug.msg(1, "forms.py opening form for: %s" % task.get_cmd(ignoreErrors=True, ignoreRequired=True))
  2218. app = GrassGUIApp(task)
  2219. app.MainLoop()
  2220. else: #Test
  2221. # Test grassTask from within a GRASS session
  2222. if os.getenv("GISBASE") is not None:
  2223. task = gtask.grassTask("d.vect")
  2224. task.get_param('map')['value'] = "map_name"
  2225. task.get_flag('i')['value'] = True
  2226. task.get_param('layer')['value'] = 1
  2227. task.get_param('label_bcolor')['value'] = "red"
  2228. # the default parameter display is added automatically
  2229. assert ' '.join(task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
  2230. print "Creation of task successful"
  2231. # Test interface building with handmade grassTask,
  2232. # possibly outside of a GRASS session.
  2233. print "Now creating a module dialog (task frame)"
  2234. task = gtask.grassTask()
  2235. task.name = "TestTask"
  2236. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2237. task.keywords = ["grass","test","task"]
  2238. task.params = [
  2239. {
  2240. "name" : "text",
  2241. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2242. "label" : "Enter some text",
  2243. "key_desc": ["value"],
  2244. "values_desc": []
  2245. },{
  2246. "name" : "hidden_text",
  2247. "description" : "This text should not appear in the form",
  2248. "hidden" : True,
  2249. "key_desc": ["value"],
  2250. "values_desc": []
  2251. },{
  2252. "name" : "text_default",
  2253. "description" : "Enter text to override the default",
  2254. "default" : "default text",
  2255. "key_desc": ["value"],
  2256. "values_desc": []
  2257. },{
  2258. "name" : "text_prefilled",
  2259. "description" : "You should see a friendly welcome message here",
  2260. "value" : "hello, world",
  2261. "key_desc": ["value"],
  2262. "values_desc": []
  2263. },{
  2264. "name" : "plain_color",
  2265. "description" : "This is a plain color, and it is a compulsory parameter",
  2266. "required" : False,
  2267. "gisprompt" : True,
  2268. "prompt" : "color",
  2269. "key_desc": ["value"],
  2270. "values_desc": []
  2271. },{
  2272. "name" : "transparent_color",
  2273. "description" : "This color becomes transparent when set to none",
  2274. "guisection" : "tab",
  2275. "gisprompt" : True,
  2276. "prompt" : "color",
  2277. "key_desc": ["value"],
  2278. "values_desc": []
  2279. },{
  2280. "name" : "multi",
  2281. "description" : "A multiple selection",
  2282. 'default': u'red,green,blue',
  2283. 'gisprompt': False,
  2284. 'guisection': 'tab',
  2285. 'multiple': u'yes',
  2286. 'type': u'string',
  2287. 'value': '',
  2288. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2289. "key_desc": ["value"],
  2290. "values_desc": []
  2291. },{
  2292. "name" : "single",
  2293. "description" : "A single multiple-choice selection",
  2294. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2295. "guisection" : "tab",
  2296. "key_desc": ["value"],
  2297. "values_desc": []
  2298. },{
  2299. "name" : "large_multi",
  2300. "description" : "A large multiple selection",
  2301. "gisprompt" : False,
  2302. "multiple" : "yes",
  2303. # values must be an array of strings
  2304. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
  2305. "key_desc": ["value"],
  2306. "values_desc": []
  2307. },{
  2308. "name" : "a_file",
  2309. "description" : "A file selector",
  2310. "gisprompt" : True,
  2311. "element" : "file",
  2312. "key_desc": ["value"],
  2313. "values_desc": []
  2314. }
  2315. ]
  2316. task.flags = [
  2317. {
  2318. "name" : "a",
  2319. "description" : "Some flag, will appear in Main since it is required",
  2320. "required" : True,
  2321. "value" : False,
  2322. "suppress_required": False
  2323. },{
  2324. "name" : "b",
  2325. "description" : "pre-filled flag, will appear in options since it is not required",
  2326. "value" : True,
  2327. "suppress_required": False
  2328. },{
  2329. "name" : "hidden_flag",
  2330. "description" : "hidden flag, should not be changeable",
  2331. "hidden" : "yes",
  2332. "value" : True,
  2333. "suppress_required": False
  2334. }
  2335. ]
  2336. q = wx.LogNull()
  2337. GrassGUIApp(task).MainLoop()