forms.py 126 KB

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