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