forms.py 123 KB

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