forms.py 126 KB

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