forms.py 124 KB

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