forms.py 126 KB

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