forms.py 120 KB

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