forms.py 126 KB

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