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