forms.py 126 KB

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