forms.py 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151
  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. def _Destroy(self):
  785. """Destroy Frame"""
  786. self.notebookpanel.notebook.Unbind(wx.EVT_NOTEBOOK_PAGE_CHANGED)
  787. self.notebookpanel.notebook.widget.Unbind(wx.EVT_NOTEBOOK_PAGE_CHANGED)
  788. self.Destroy()
  789. class CmdPanel(wx.Panel):
  790. """A panel containing a notebook dividing in tabs the different
  791. guisections of the GRASS cmd.
  792. """
  793. def __init__(self, parent, giface, task, id=wx.ID_ANY,
  794. frame=None, *args, **kwargs):
  795. if frame:
  796. self.parent = frame
  797. else:
  798. self.parent = parent
  799. self.task = task
  800. self._giface = giface
  801. wx.Panel.__init__(self, parent, id=id, *args, **kwargs)
  802. self.mapCreated = Signal
  803. self.updateMap = Signal
  804. # Determine tab layout
  805. sections = []
  806. is_section = {}
  807. not_hidden = [
  808. p for p in self.task.params +
  809. self.task.flags if not p.get(
  810. 'hidden',
  811. False) == True]
  812. self.label_id = [] # wrap titles on resize
  813. self.Bind(wx.EVT_SIZE, self.OnSize)
  814. for task in not_hidden:
  815. if task.get('required', False) and not task.get('guisection', ''):
  816. # All required go into Main, even if they had defined another
  817. # guisection
  818. task['guisection'] = _('Required')
  819. if task.get('guisection', '') == '':
  820. # Undefined guisections end up into Options
  821. task['guisection'] = _('Optional')
  822. if task['guisection'] not in is_section:
  823. # We do it like this to keep the original order, except for
  824. # Main which goes first
  825. is_section[task['guisection']] = 1
  826. sections.append(task['guisection'])
  827. else:
  828. is_section[task['guisection']] += 1
  829. del is_section
  830. # 'Required' tab goes first, 'Optional' as the last one
  831. for (newidx, content) in [(0, _('Required')),
  832. (len(sections) - 1, _('Optional'))]:
  833. if content in sections:
  834. idx = sections.index(content)
  835. sections[idx:idx + 1] = []
  836. sections[newidx:newidx] = [content]
  837. panelsizer = wx.BoxSizer(orient=wx.VERTICAL)
  838. # build notebook
  839. style = UserSettings.Get(
  840. group='appearance',
  841. key='commandNotebook',
  842. subkey='selection')
  843. if style == 0: # basic top
  844. self.notebook = FormNotebook(self, style=wx.BK_TOP)
  845. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  846. elif style == 1: # basic left
  847. self.notebook = FormNotebook(self, style=wx.BK_LEFT)
  848. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  849. elif style == 2: # fancy green
  850. self.notebook = GNotebook(
  851. self, style=globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON)
  852. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  853. self.notebook.Bind(
  854. FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
  855. self.OnPageChange)
  856. elif style == 3:
  857. self.notebook = FormListbook(self, style=wx.BK_LEFT)
  858. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  859. self.notebook.Refresh()
  860. tab = {}
  861. tabsizer = {}
  862. for section in sections:
  863. tab[section] = ScrolledPanel(parent=self.notebook)
  864. tab[section].SetScrollRate(10, 10)
  865. tabsizer[section] = wx.BoxSizer(orient=wx.VERTICAL)
  866. #
  867. # flags
  868. #
  869. visible_flags = [
  870. f for f in self.task.flags if not f.get(
  871. 'hidden', False) == True]
  872. for f in visible_flags:
  873. # we don't want another help (checkbox appeared in r58783)
  874. if f['name'] == 'help':
  875. continue
  876. which_sizer = tabsizer[f['guisection']]
  877. which_panel = tab[f['guisection']]
  878. # if label is given: description -> tooltip
  879. if f.get('label', '') != '':
  880. title = text_beautify(f['label'])
  881. tooltip = text_beautify(f['description'], width=-1)
  882. else:
  883. title = text_beautify(f['description'])
  884. tooltip = None
  885. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  886. rtitle_txt = StaticText(parent=which_panel,
  887. label='(' + f['name'] + ')')
  888. chk = CheckBox(
  889. parent=which_panel,
  890. label=title,
  891. style=wx.NO_BORDER)
  892. self.label_id.append(chk.GetId())
  893. if tooltip:
  894. chk.SetToolTip(tooltip)
  895. chk.SetValue(f.get('value', False))
  896. title_sizer.Add(chk, proportion=1,
  897. flag=wx.EXPAND)
  898. title_sizer.Add(rtitle_txt, proportion=0,
  899. flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  900. which_sizer.Add(
  901. title_sizer,
  902. proportion=0,
  903. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT,
  904. border=5)
  905. f['wxId'] = [chk.GetId(), ]
  906. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  907. if self.parent.GetName() == 'MainFrame' and (
  908. self._giface and hasattr(self._giface, "_model")):
  909. parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
  910. label=_("Parameterized in model"))
  911. parChk.SetName('ModelParam')
  912. parChk.SetValue(f.get('parameterized', False))
  913. if 'wxId' in f:
  914. f['wxId'].append(parChk.GetId())
  915. else:
  916. f['wxId'] = [parChk.GetId()]
  917. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  918. which_sizer.Add(parChk, proportion=0,
  919. flag=wx.LEFT, border=20)
  920. if f['name'] in ('verbose', 'quiet'):
  921. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  922. vq = UserSettings.Get(
  923. group='cmd', key='verbosity', subkey='selection')
  924. if f['name'] == vq:
  925. chk.SetValue(True)
  926. f['value'] = True
  927. if f['name'] == 'overwrite':
  928. value = UserSettings.Get(
  929. group='cmd', key='overwrite', subkey='enabled')
  930. if value: # override only when enabled
  931. f['value'] = value
  932. chk.SetValue(f['value'])
  933. #
  934. # parameters
  935. #
  936. visible_params = [
  937. p for p in self.task.params if not p.get(
  938. 'hidden', False) == True]
  939. try:
  940. first_param = visible_params[0]
  941. except IndexError:
  942. first_param = None
  943. for p in visible_params:
  944. which_sizer = tabsizer[p['guisection']]
  945. which_panel = tab[p['guisection']]
  946. # if label is given -> label and description -> tooltip
  947. # otherwise description -> lavel
  948. if p.get('label', '') != '':
  949. title = text_beautify(p['label'])
  950. tooltip = text_beautify(p['description'], width=-1)
  951. else:
  952. title = text_beautify(p['description'])
  953. tooltip = None
  954. prompt = p.get('prompt', '')
  955. # title sizer (description, name, type)
  956. if (len(p.get('values', [])) > 0) and \
  957. p.get('multiple', False) and \
  958. p.get('gisprompt', False) == False and \
  959. p.get('type', '') == 'string':
  960. title_txt = StaticBox(parent=which_panel, id=wx.ID_ANY)
  961. else:
  962. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  963. title_txt = StaticText(parent=which_panel)
  964. if p['key_desc']:
  965. ltype = ','.join(p['key_desc'])
  966. else:
  967. ltype = p['type']
  968. # red star for required options
  969. if p.get('required', False):
  970. required_txt = StaticText(parent=which_panel, label="*")
  971. required_txt.SetForegroundColour(wx.RED)
  972. required_txt.SetToolTip(_("This option is required"))
  973. else:
  974. required_txt = StaticText(parent=which_panel, label="")
  975. rtitle_txt = StaticText(
  976. parent=which_panel,
  977. label='(' + p['name'] + '=' + ltype + ')')
  978. title_sizer.Add(title_txt, proportion=0,
  979. flag=wx.LEFT | wx.TOP | wx.EXPAND, border=5)
  980. title_sizer.Add(required_txt, proportion=1,
  981. flag=wx.EXPAND, border=0)
  982. title_sizer.Add(
  983. rtitle_txt,
  984. proportion=0,
  985. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
  986. border=5)
  987. which_sizer.Add(title_sizer, proportion=0,
  988. flag=wx.EXPAND)
  989. self.label_id.append(title_txt.GetId())
  990. # title expansion
  991. if p.get('multiple', False) and len(p.get('values', '')) == 0:
  992. title = _("[multiple]") + " " + title
  993. if p.get('value', '') == '':
  994. p['value'] = p.get('default', '')
  995. if (len(p.get('values', [])) > 0):
  996. valuelist = list(map(str, p.get('values', [])))
  997. valuelist_desc = list(map(unicode, p.get('values_desc', [])))
  998. required_text = "*" if p.get('required', False) else ""
  999. if p.get('multiple', False) and \
  1000. p.get('gisprompt', False) == False and \
  1001. p.get('type', '') == 'string':
  1002. title_txt.SetLabel(
  1003. " %s:%s (%s=%s) " %
  1004. (title, required_text, p['name'], p['type']))
  1005. stSizer = wx.StaticBoxSizer(
  1006. box=title_txt, orient=wx.VERTICAL)
  1007. if valuelist_desc:
  1008. hSizer = wx.FlexGridSizer(cols=1, vgap=1, hgap=1)
  1009. else:
  1010. hSizer = wx.FlexGridSizer(cols=6, vgap=1, hgap=1)
  1011. isEnabled = {}
  1012. # copy default values
  1013. if p['value'] == '':
  1014. p['value'] = p.get('default', '')
  1015. for defval in p.get('value', '').split(','):
  1016. isEnabled[defval] = 'yes'
  1017. # for multi checkboxes, this is an array of all wx IDs
  1018. # for each individual checkbox
  1019. p['wxId'] = list()
  1020. idx = 0
  1021. for val in valuelist:
  1022. try:
  1023. label = valuelist_desc[idx]
  1024. except IndexError:
  1025. label = val
  1026. chkbox = wx.CheckBox(parent=which_panel,
  1027. label=text_beautify(label))
  1028. p['wxId'].append(chkbox.GetId())
  1029. if val in isEnabled:
  1030. chkbox.SetValue(True)
  1031. hSizer.Add(chkbox, proportion=0)
  1032. chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
  1033. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  1034. idx += 1
  1035. stSizer.Add(hSizer, proportion=0,
  1036. flag=wx.ADJUST_MINSIZE | wx.ALL, border=1)
  1037. which_sizer.Add(
  1038. stSizer,
  1039. proportion=0,
  1040. flag=wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT,
  1041. border=5)
  1042. elif p.get('gisprompt', False) is False:
  1043. if len(valuelist) == 1: # -> textctrl
  1044. title_txt.SetLabel(
  1045. "%s (%s %s):" %
  1046. (title, _('valid range'),
  1047. str(valuelist[0])))
  1048. if p.get('type', '') == 'integer' and \
  1049. not p.get('multiple', False):
  1050. # for multiple integers use textctrl instead of
  1051. # spinsctrl
  1052. try:
  1053. minValue, maxValue = list(map(
  1054. int, valuelist[0].rsplit('-', 1)))
  1055. except ValueError:
  1056. minValue = -1e6
  1057. maxValue = 1e6
  1058. txt2 = SpinCtrl(
  1059. parent=which_panel,
  1060. id=wx.ID_ANY,
  1061. size=globalvar.DIALOG_SPIN_SIZE,
  1062. min=minValue,
  1063. max=maxValue)
  1064. style = wx.BOTTOM | wx.LEFT
  1065. else:
  1066. txt2 = TextCtrl(
  1067. parent=which_panel, value=p.get(
  1068. 'default', ''))
  1069. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  1070. value = self._getValue(p)
  1071. # parameter previously set
  1072. if value:
  1073. if isinstance(txt2, SpinCtrl):
  1074. txt2.SetValue(int(value))
  1075. else:
  1076. txt2.SetValue(value)
  1077. which_sizer.Add(txt2, proportion=0,
  1078. flag=style, border=5)
  1079. p['wxId'] = [txt2.GetId(), ]
  1080. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  1081. else:
  1082. title_txt.SetLabel(title + ':')
  1083. value = self._getValue(p)
  1084. if p['name'] in ('icon', 'icon_area', 'icon_line'): # symbols
  1085. bitmap = wx.Bitmap(
  1086. os.path.join(
  1087. globalvar.SYMBDIR,
  1088. value) + '.png')
  1089. bb = BitmapButton(
  1090. parent=which_panel, id=wx.ID_ANY, bitmap=bitmap)
  1091. iconLabel = StaticText(
  1092. parent=which_panel, id=wx.ID_ANY)
  1093. iconLabel.SetLabel(value)
  1094. p['value'] = value
  1095. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  1096. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  1097. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1098. this_sizer.Add(
  1099. bb, proportion=0, flag=wx.ADJUST_MINSIZE |
  1100. wx.BOTTOM | wx.LEFT, border=5)
  1101. this_sizer.Add(
  1102. iconLabel,
  1103. proportion=0,
  1104. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL,
  1105. border=5)
  1106. which_sizer.Add(this_sizer, proportion=0,
  1107. flag=wx.ADJUST_MINSIZE, border=0)
  1108. else:
  1109. # list of values (combo)
  1110. cb = wx.ComboBox(
  1111. parent=which_panel, id=wx.ID_ANY, value=p.get(
  1112. 'default', ''),
  1113. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1114. choices=valuelist, style=wx.CB_DROPDOWN)
  1115. if value:
  1116. cb.SetValue(value) # parameter previously set
  1117. which_sizer.Add(
  1118. cb, proportion=0, flag=wx.ADJUST_MINSIZE |
  1119. wx.BOTTOM | wx.LEFT, border=5)
  1120. p['wxId'] = [cb.GetId(), ]
  1121. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1122. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  1123. if p.get('guidependency', ''):
  1124. cb.Bind(
  1125. wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1126. # text entry
  1127. if (p.get('type', 'string') in ('string', 'integer', 'float')
  1128. and len(p.get('values', [])) == 0
  1129. and p.get('gisprompt', False) == False
  1130. and p.get('prompt', '') != 'color'):
  1131. title_txt.SetLabel(title + ':')
  1132. p['wxId'] = []
  1133. if p.get('multiple', False) or \
  1134. p.get('type', 'string') == 'string' or \
  1135. len(p.get('key_desc', [])) > 1:
  1136. win = TextCtrl(
  1137. parent=which_panel, value=p.get(
  1138. 'default', ''))
  1139. value = self._getValue(p)
  1140. if value:
  1141. # parameter previously set
  1142. win.SetValue(value if p.get('type', 'string') == 'string' else str(value))
  1143. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1144. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1145. if p.get('name', '') == 'font':
  1146. font_btn = Button(parent=which_panel, label=_("Select font"))
  1147. font_btn.Bind(wx.EVT_BUTTON, self.OnSelectFont)
  1148. font_sizer = wx.BoxSizer(wx.HORIZONTAL)
  1149. font_sizer.Add(win, proportion=1,
  1150. flag=style, border=5)
  1151. font_sizer.Add(font_btn, proportion=0,
  1152. flag=style, border=5)
  1153. which_sizer.Add(font_sizer, proportion=0,
  1154. flag=style, border=5)
  1155. p['wxId'].append(font_btn.GetId())
  1156. else:
  1157. which_sizer.Add(win, proportion=0,
  1158. flag=style, border=5)
  1159. elif p.get('type', '') == 'integer':
  1160. minValue = -1e9
  1161. maxValue = 1e9
  1162. value = self._getValue(p)
  1163. win = SpinCtrl(
  1164. parent=which_panel,
  1165. value=p.get(
  1166. 'default',
  1167. ''),
  1168. size=globalvar.DIALOG_SPIN_SIZE,
  1169. min=minValue,
  1170. max=maxValue)
  1171. if value:
  1172. win.SetValue(int(value)) # parameter previously set
  1173. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1174. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1175. which_sizer.Add(win, proportion=0,
  1176. flag=style, border=5)
  1177. else: # float
  1178. win = TextCtrl(
  1179. parent=which_panel, value=p.get(
  1180. 'default', ''), validator=FloatValidator())
  1181. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  1182. which_sizer.Add(win, proportion=0,
  1183. flag=style, border=5)
  1184. value = self._getValue(p)
  1185. if value:
  1186. win.SetValue(str(value)) # parameter previously set
  1187. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1188. p['wxId'].append(win.GetId())
  1189. #
  1190. # element selection tree combobox (maps, icons, regions, etc.)
  1191. #
  1192. if p.get('gisprompt', False):
  1193. title_txt.SetLabel(title + ':')
  1194. # GIS element entry
  1195. if p.get('prompt', '') not in ('color',
  1196. 'cat',
  1197. 'cats',
  1198. 'subgroup',
  1199. 'sigfile',
  1200. 'separator',
  1201. 'dbdriver',
  1202. 'dbname',
  1203. 'dbtable',
  1204. 'dbcolumn',
  1205. 'layer',
  1206. 'location',
  1207. 'mapset',
  1208. 'dbase',
  1209. 'coords',
  1210. 'file',
  1211. 'dir',
  1212. 'colortable',
  1213. 'barscale',
  1214. 'northarrow',
  1215. 'datasource',
  1216. 'datasource_layer',
  1217. 'sql_query'):
  1218. multiple = p.get('multiple', False)
  1219. if p.get('age', '') == 'new':
  1220. mapsets = [grass.gisenv()['MAPSET'], ]
  1221. else:
  1222. mapsets = None
  1223. if self.task.name in ('r.proj', 'v.proj') \
  1224. and p.get('name', '') == 'input':
  1225. selection = gselect.ProjSelect(
  1226. parent=which_panel, isRaster=self.task.name == 'r.proj')
  1227. p['wxId'] = [selection.GetId(), ]
  1228. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1229. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1230. else:
  1231. elem = p.get('element', None)
  1232. # hack for t.* modules
  1233. if elem in ('stds', 'map'):
  1234. orig_elem = elem
  1235. type_param = self.task.get_param(
  1236. 'type', element='name', raiseError=False)
  1237. if type_param:
  1238. elem = type_param.get('default', None)
  1239. # for t.(un)register:
  1240. maps_param = self.task.get_param(
  1241. 'maps', element='name', raiseError=False)
  1242. if maps_param and orig_elem == 'stds':
  1243. element_dict = {
  1244. 'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  1245. elem = element_dict[
  1246. type_param.get('default')]
  1247. extraItems = None
  1248. if self._giface:
  1249. if hasattr(self._giface, "_model"):
  1250. extraItems = {
  1251. _('Graphical Modeler'): self._giface.GetLayerList(
  1252. p.get('prompt'))}
  1253. else:
  1254. layers = self._giface.GetLayerList()
  1255. if len(layers) > 0:
  1256. mapList = []
  1257. extraItems = {_('Map Display'): mapList}
  1258. for layer in layers:
  1259. if layer.type != p.get('prompt'):
  1260. continue
  1261. mapList.append(str(layer))
  1262. selection = gselect.Select(
  1263. parent=which_panel, id=wx.ID_ANY,
  1264. size=globalvar.DIALOG_GSELECT_SIZE, type=elem,
  1265. multiple=multiple, nmaps=len(
  1266. p.get('key_desc', [])),
  1267. mapsets=mapsets, fullyQualified=p.get(
  1268. 'age', 'old') == 'old', extraItems=extraItems)
  1269. value = self._getValue(p)
  1270. if value:
  1271. selection.SetValue(value)
  1272. formatSelector = True
  1273. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1274. # we target the textctl here
  1275. textWin = selection.GetTextCtrl()
  1276. if globalvar.CheckWxVersion([3]):
  1277. p['wxId'] = [selection.GetId(), ]
  1278. else:
  1279. p['wxId'] = [textWin.GetId(), ]
  1280. if prompt != 'vector':
  1281. self.FindWindowById(
  1282. p['wxId'][0]).Bind(
  1283. wx.EVT_TEXT, self.OnSetValue)
  1284. if prompt == 'vector':
  1285. win = self.FindWindowById(p['wxId'][0])
  1286. # handlers should be bound in this order
  1287. # OnUpdateSelection depends on calling OnSetValue first
  1288. # which is bad
  1289. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1290. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1291. # if formatSelector and p.get('age', 'old') == 'old':
  1292. # # OGR supported (read-only)
  1293. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1294. # self.hsizer.Add(item = selection,
  1295. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1296. # border = 5)
  1297. # # format (native / ogr)
  1298. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1299. # label = " %s " % _("Format"),
  1300. # style = wx.RA_SPECIFY_ROWS,
  1301. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1302. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1303. # rbox.SetSelection(1)
  1304. # rbox.SetName('VectorFormat')
  1305. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1306. # self.hsizer.Add(item = rbox,
  1307. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1308. # wx.RIGHT | wx.ALIGN_TOP,
  1309. # border = 5)
  1310. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1311. # default = 'dir',
  1312. # exclude = ['file'])
  1313. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1314. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1315. # ogrSelection.SetName('OgrSelect')
  1316. # ogrSelection.Hide()
  1317. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1318. # p['wxId'].append(rbox.GetId())
  1319. # p['wxId'].append(ogrSelection.GetId())
  1320. # for win in ogrSelection.GetDsnWin():
  1321. # p['wxId'].append(win.GetId())
  1322. # else:
  1323. which_sizer.Add(
  1324. selection,
  1325. proportion=0,
  1326. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1327. border=5)
  1328. elif prompt == 'group':
  1329. win = self.FindWindowById(p['wxId'][0])
  1330. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1331. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1332. which_sizer.Add(
  1333. selection,
  1334. proportion=0,
  1335. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1336. border=5)
  1337. else:
  1338. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1339. showButton = True
  1340. try:
  1341. # if matplotlib is there
  1342. from timeline import frame
  1343. showButton = True
  1344. except ImportError:
  1345. showButton = False
  1346. else:
  1347. showButton = False
  1348. if showButton:
  1349. iconTheme = UserSettings.Get(
  1350. group='appearance', key='iconTheme', subkey='type')
  1351. bitmap = wx.Bitmap(
  1352. os.path.join(
  1353. globalvar.ICONDIR, iconTheme,
  1354. 'map-info.png'))
  1355. bb = BitmapButton(
  1356. parent=which_panel, bitmap=bitmap)
  1357. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1358. bb.SetToolTip(
  1359. _("Show graphical representation of temporal extent of dataset(s) ."))
  1360. p['wxId'].append(bb.GetId())
  1361. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1362. hSizer.Add(
  1363. selection,
  1364. proportion=0,
  1365. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1366. border=5)
  1367. hSizer.Add(
  1368. bb,
  1369. proportion=0,
  1370. flag=wx.EXPAND | wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1371. border=5)
  1372. which_sizer.Add(hSizer)
  1373. else:
  1374. which_sizer.Add(
  1375. selection,
  1376. proportion=0,
  1377. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1378. border=5)
  1379. # subgroup
  1380. elif prompt == 'subgroup':
  1381. selection = gselect.SubGroupSelect(parent=which_panel)
  1382. p['wxId'] = [selection.GetId()]
  1383. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1384. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1385. which_sizer.Add(
  1386. selection,
  1387. proportion=0,
  1388. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1389. border=5)
  1390. # sigrature file
  1391. elif prompt == 'sigfile':
  1392. selection = gselect.SignatureSelect(
  1393. parent=which_panel, element=p.get('element', 'sig'))
  1394. p['wxId'] = [selection.GetId()]
  1395. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1396. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1397. which_sizer.Add(
  1398. selection,
  1399. proportion=0,
  1400. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1401. border=5)
  1402. # separator
  1403. elif prompt == 'separator':
  1404. win = gselect.SeparatorSelect(parent=which_panel)
  1405. value = self._getValue(p)
  1406. win.SetValue(value)
  1407. p['wxId'] = [win.GetId()]
  1408. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1409. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1410. which_sizer.Add(
  1411. win,
  1412. proportion=0,
  1413. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1414. border=5)
  1415. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1416. elif prompt in ('dbdriver',
  1417. 'dbname',
  1418. 'dbtable',
  1419. 'dbcolumn',
  1420. 'layer',
  1421. 'location',
  1422. 'mapset',
  1423. 'dbase'):
  1424. if p.get('multiple', 'no') == 'yes':
  1425. win = TextCtrl(
  1426. parent=which_panel, value=p.get(
  1427. 'default', ''), size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1428. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1429. else:
  1430. value = self._getValue(p)
  1431. if prompt == 'layer':
  1432. if p.get('element', 'layer') == 'layer_all':
  1433. all = True
  1434. else:
  1435. all = False
  1436. if p.get('age', 'old') == 'old':
  1437. win = gselect.LayerSelect(parent=which_panel,
  1438. all=all,
  1439. default=p['default'])
  1440. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1441. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1442. win.SetValue(
  1443. str(value)) # default or previously set value
  1444. else:
  1445. win = SpinCtrl(
  1446. parent=which_panel, id=wx.ID_ANY, min=1,
  1447. max=100, initial=int(p['default']))
  1448. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1449. win.SetValue(
  1450. int(value)) # default or previously set value
  1451. p['wxId'] = [win.GetId()]
  1452. elif prompt == 'dbdriver':
  1453. win = gselect.DriverSelect(
  1454. parent=which_panel, choices=p.get(
  1455. 'values', []),
  1456. value=value)
  1457. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1458. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1459. elif prompt == 'dbname':
  1460. win = gselect.DatabaseSelect(parent=which_panel,
  1461. value=value)
  1462. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1463. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1464. elif prompt == 'dbtable':
  1465. if p.get('age', 'old') == 'old':
  1466. win = gselect.TableSelect(parent=which_panel)
  1467. win.Bind(
  1468. wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1469. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1470. else:
  1471. win = TextCtrl(
  1472. parent=which_panel, value=p.get(
  1473. 'default', ''),
  1474. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  1475. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1476. elif prompt == 'dbcolumn':
  1477. win = gselect.ColumnSelect(
  1478. parent=which_panel, value=value, param=p,
  1479. multiple=p.get('multiple', False))
  1480. # A gselect.ColumnSelect is a combobox
  1481. # with two children: a textctl and a
  1482. # popupwindow; we target the textctl here
  1483. textWin = win.GetTextCtrl()
  1484. p['wxId'] = [textWin.GetId(), ]
  1485. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1486. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1487. elif prompt == 'location':
  1488. win = gselect.LocationSelect(parent=which_panel,
  1489. value=value)
  1490. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1491. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1492. elif prompt == 'mapset':
  1493. if p.get('age', 'old') == 'old':
  1494. new = False
  1495. else:
  1496. new = True
  1497. win = gselect.MapsetSelect(
  1498. parent=which_panel, value=value, new=new,
  1499. multiple=p.get('multiple', False))
  1500. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1501. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1502. elif prompt == 'dbase':
  1503. win = gselect.DbaseSelect(
  1504. parent=which_panel, changeCallback=self.OnSetValue)
  1505. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1506. p['wxId'] = [win.GetChildren()[1].GetId()]
  1507. if 'wxId' not in p:
  1508. try:
  1509. p['wxId'] = [win.GetId(), ]
  1510. except AttributeError:
  1511. pass
  1512. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1513. if prompt == 'dbname':
  1514. flags |= wx.EXPAND
  1515. which_sizer.Add(win, proportion=0,
  1516. flag=flags, border=5)
  1517. # color entry
  1518. elif prompt == 'color':
  1519. default_color = (200, 200, 200)
  1520. label_color = _("Select Color")
  1521. if p.get('default', '') != '':
  1522. default_color, label_color = utils.color_resolve(p[
  1523. 'default'])
  1524. if p.get('value', '') != '' and p.get(
  1525. 'value', '') != 'none': # parameter previously set
  1526. if not p.get('multiple', False):
  1527. default_color, label_color = utils.color_resolve(p[
  1528. 'value'])
  1529. if p.get(
  1530. 'element', '') == 'color_none' or p.get(
  1531. 'multiple', False):
  1532. this_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  1533. else:
  1534. this_sizer = which_sizer
  1535. colorSize = 150
  1536. # For color selectors, this is a three-member array, holding the IDs of
  1537. # the color picker, the text control for multiple colors (or None),
  1538. # and either a "transparent" checkbox or None
  1539. p['wxId'] = [None] * 3
  1540. if p.get('multiple', False):
  1541. txt = TextCtrl(parent=which_panel, id=wx.ID_ANY)
  1542. this_sizer.Add(
  1543. txt,
  1544. proportion=1,
  1545. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP,
  1546. border=5)
  1547. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1548. if p.get('value', ''):
  1549. txt.SetValue(p['value'])
  1550. colorSize = 40
  1551. label_color = ''
  1552. p['wxId'][1] = txt.GetId()
  1553. which_sizer.Add(
  1554. this_sizer, flag=wx.EXPAND | wx.RIGHT, border=5)
  1555. btn_colour = csel.ColourSelect(
  1556. parent=which_panel, id=wx.ID_ANY, label=label_color,
  1557. colour=default_color, pos=wx.DefaultPosition,
  1558. size=(colorSize, 32))
  1559. this_sizer.Add(
  1560. btn_colour,
  1561. proportion=0,
  1562. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
  1563. border=5)
  1564. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1565. p['wxId'][0] = btn_colour.GetId()
  1566. if p.get('element', '') == 'color_none':
  1567. none_check = wx.CheckBox(
  1568. which_panel, wx.ID_ANY, _("Transparent"))
  1569. if p.get('value', '') == "none":
  1570. none_check.SetValue(True)
  1571. else:
  1572. none_check.SetValue(False)
  1573. this_sizer.Add(
  1574. none_check, proportion=0,
  1575. flag=wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP,
  1576. border=5)
  1577. which_sizer.Add(this_sizer)
  1578. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1579. p['wxId'][2] = none_check.GetId()
  1580. # file selector
  1581. elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'file':
  1582. if p.get('age', 'new') == 'new':
  1583. fmode = wx.FD_SAVE
  1584. else:
  1585. fmode = wx.FD_OPEN
  1586. # check wildcard
  1587. try:
  1588. fExt = os.path.splitext(
  1589. p.get('key_desc', ['*.*'])[0])[1]
  1590. except:
  1591. fExt = None
  1592. if not fExt:
  1593. fMask = '*'
  1594. else:
  1595. fMask = '%s files (*%s)|*%s|Files (*)|*' % (
  1596. fExt[1:].upper(), fExt, fExt)
  1597. fbb = filebrowse.FileBrowseButton(
  1598. parent=which_panel,
  1599. id=wx.ID_ANY,
  1600. fileMask=fMask,
  1601. size=globalvar.DIALOG_GSELECT_SIZE,
  1602. labelText='',
  1603. dialogTitle=_('Choose %s') %
  1604. p.get(
  1605. 'description',
  1606. _('file')).lower(),
  1607. buttonText=_('Browse'),
  1608. startDirectory=os.getcwd(),
  1609. fileMode=fmode,
  1610. changeCallback=self.OnSetValue)
  1611. value = self._getValue(p)
  1612. if value:
  1613. fbb.SetValue(value) # parameter previously set
  1614. which_sizer.Add(fbb, proportion=0,
  1615. flag=wx.EXPAND | wx.RIGHT, border=5)
  1616. # A file browse button is a combobox with two children:
  1617. # a textctl and a button;
  1618. # we have to target the button here
  1619. p['wxId'] = [fbb.GetChildren()[1].GetId()]
  1620. if p.get(
  1621. 'age', 'new') == 'old' and p.get(
  1622. 'prompt', '') == 'file' and p.get(
  1623. 'element', '') == 'file' and UserSettings.Get(
  1624. group='cmd', key='interactiveInput', subkey='enabled'):
  1625. # widget for interactive input
  1626. ifbb = TextCtrl(parent=which_panel, id=wx.ID_ANY,
  1627. style=wx.TE_MULTILINE,
  1628. size=(-1, 75))
  1629. if p.get('value', '') and os.path.isfile(p['value']):
  1630. ifbb.Clear()
  1631. enc = locale.getdefaultlocale()[1]
  1632. with codecs.open(p['value'], encoding=enc, errors='ignore') as f:
  1633. nonascii = bytearray(range(0x80, 0x100))
  1634. for line in f.readlines():
  1635. try:
  1636. ifbb.AppendText(line)
  1637. except UnicodeDecodeError:
  1638. # remove non-ascii characters on encoding mismatch (file vs OS)
  1639. ifbb.AppendText(line.translate(None, nonascii))
  1640. ifbb.SetInsertionPoint(0)
  1641. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1642. btnLoad = Button(
  1643. parent=which_panel, id=wx.ID_ANY, label=_("&Load"))
  1644. btnLoad.SetToolTip(
  1645. _("Load and edit content of a file"))
  1646. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1647. btnSave = Button(
  1648. parent=which_panel, id=wx.ID_ANY, label=_("&Save as"))
  1649. btnSave.SetToolTip(
  1650. _("Save content to a file for further use"))
  1651. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1652. fileContentLabel = StaticText(
  1653. parent=which_panel, id=wx.ID_ANY,
  1654. label=_('or enter values directly:'))
  1655. fileContentLabel.SetToolTip(
  1656. _("Enter file content directly instead of specifying"
  1657. " a file."
  1658. " Temporary file will be automatically created."))
  1659. which_sizer.Add(
  1660. fileContentLabel,
  1661. proportion=0,
  1662. flag=wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM,
  1663. border=5)
  1664. which_sizer.Add(
  1665. ifbb,
  1666. proportion=1,
  1667. flag=wx.EXPAND | wx.RIGHT | wx.LEFT,
  1668. border=5)
  1669. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1670. btnSizer.Add(btnLoad, proportion=0,
  1671. flag=wx.ALIGN_RIGHT | wx.RIGHT, border=10)
  1672. btnSizer.Add(btnSave, proportion=0,
  1673. flag=wx.ALIGN_RIGHT)
  1674. which_sizer.Add(
  1675. btnSizer,
  1676. proportion=0,
  1677. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP,
  1678. border=5)
  1679. p['wxId'].append(ifbb.GetId())
  1680. p['wxId'].append(btnLoad.GetId())
  1681. p['wxId'].append(btnSave.GetId())
  1682. # directory selector
  1683. elif p.get('prompt', '') != 'color' and p.get('prompt', '') == 'dir':
  1684. fbb = filebrowse.DirBrowseButton(
  1685. parent=which_panel,
  1686. id=wx.ID_ANY,
  1687. size=globalvar.DIALOG_GSELECT_SIZE,
  1688. labelText='',
  1689. dialogTitle=_('Choose %s') %
  1690. p.get(
  1691. 'description',
  1692. _('Directory')),
  1693. buttonText=_('Browse'),
  1694. startDirectory=os.getcwd(),
  1695. newDirectory=True,
  1696. changeCallback=self.OnSetValue)
  1697. value = self._getValue(p)
  1698. if value:
  1699. fbb.SetValue(value) # parameter previously set
  1700. which_sizer.Add(fbb, proportion=0,
  1701. flag=wx.EXPAND | wx.RIGHT, border=5)
  1702. # A file browse button is a combobox with two children:
  1703. # a textctl and a button;
  1704. # we have to target the button here
  1705. p['wxId'] = [fbb.GetChildren()[1].GetId()]
  1706. # interactive inserting of coordinates from map window
  1707. elif prompt == 'coords':
  1708. # interactive inserting if layer manager is accessible
  1709. if self._giface:
  1710. win = gselect.CoordinatesSelect(
  1711. parent=which_panel, giface=self._giface, multiple=p.get(
  1712. 'multiple', False), param=p)
  1713. p['wxId'] = [win.GetTextWin().GetId()]
  1714. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1715. # bind closing event because destructor is not working
  1716. # properly
  1717. if hasattr(self.parent, 'dialogClosing'):
  1718. self.parent.dialogClosing.connect(win.OnClose)
  1719. # normal text field
  1720. else:
  1721. win = TextCtrl(parent=which_panel)
  1722. p['wxId'] = [win.GetId()]
  1723. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1724. which_sizer.Add(
  1725. win,
  1726. proportion=0,
  1727. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1728. border=5)
  1729. elif prompt in ('cat', 'cats'):
  1730. # interactive selection of vector categories if layer
  1731. # manager is accessible
  1732. if self._giface:
  1733. win = gselect.VectorCategorySelect(
  1734. parent=which_panel, giface=self._giface, task=self.task)
  1735. p['wxId'] = [win.GetTextWin().GetId()]
  1736. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1737. # bind closing event because destructor is not working
  1738. # properly
  1739. if hasattr(self.parent, 'dialogClosing'):
  1740. self.parent.dialogClosing.connect(win.OnClose)
  1741. # normal text field
  1742. else:
  1743. win = TextCtrl(parent=which_panel)
  1744. value = self._getValue(p)
  1745. win.SetValue(value)
  1746. p['wxId'] = [win.GetId()]
  1747. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1748. which_sizer.Add(
  1749. win,
  1750. proportion=0,
  1751. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1752. border=5)
  1753. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1754. if prompt == 'colortable':
  1755. cb = ColorTablesComboBox(
  1756. parent=which_panel, value=p.get('default', ''),
  1757. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1758. choices=valuelist)
  1759. elif prompt == 'barscale':
  1760. cb = BarscalesComboBox(
  1761. parent=which_panel, value=p.get('default', ''),
  1762. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1763. choices=valuelist)
  1764. elif prompt == 'northarrow':
  1765. cb = NArrowsComboBox(
  1766. parent=which_panel, value=p.get('default', ''),
  1767. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1768. choices=valuelist)
  1769. value = self._getValue(p)
  1770. if value:
  1771. cb.SetValue(value) # parameter previously set
  1772. which_sizer.Add(
  1773. cb,
  1774. proportion=0,
  1775. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT,
  1776. border=5)
  1777. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1778. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1779. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1780. if p.get('guidependency', ''):
  1781. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1782. elif prompt == 'datasource':
  1783. win = gselect.GdalSelect(parent=parent, panel=which_panel,
  1784. ogr=True)
  1785. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1786. win.Bind(wx.EVT_CHOICE, self.OnSetValue)
  1787. p['wxId'] = [
  1788. win.GetId(),
  1789. win.fileWidgets['browse'].GetChildren()[1].GetId(),
  1790. win.dirWidgets['browse'].GetChildren()[1].GetId(),
  1791. win.dbWidgets['choice'].GetId()]
  1792. value = self._getValue(p)
  1793. if value:
  1794. win.fileWidgets['browse'].GetChildren()[1].SetValue(
  1795. value) # parameter previously set
  1796. which_sizer.Add(win, proportion=0,
  1797. flag=wx.EXPAND)
  1798. elif prompt == 'datasource_layer':
  1799. self.win1 = LayersList(
  1800. parent=which_panel,
  1801. columns=[
  1802. _('Layer id'),
  1803. _('Layer name'),
  1804. _('Feature type'),
  1805. _('Projection match')])
  1806. which_sizer.Add(self.win1, proportion=0,
  1807. flag=wx.EXPAND | wx.ALL, border=3)
  1808. porf = self.task.get_param(
  1809. 'input', element='name', raiseError=False)
  1810. if porf and 'wxId' in porf:
  1811. winDataSource = self.FindWindowById(porf['wxId'][0])
  1812. winDataSource.reloadDataRequired.connect(
  1813. lambda listData: self.win1.LoadData(
  1814. listData, False))
  1815. p['wxId'] = [self.win1.GetId()]
  1816. def OnCheckItem(index, flag):
  1817. layers = list()
  1818. geometry = None
  1819. for layer, match, listId in self.win1.GetLayers():
  1820. if '|' in layer:
  1821. layer, geometry = layer.split('|', 1)
  1822. layers.append(layer)
  1823. porf = self.task.get_param(
  1824. 'layer', element='name', raiseError=False)
  1825. porf['value'] = ','.join(layers)
  1826. # geometry is currently discarded
  1827. # TODO: v.import has no geometry option
  1828. self.OnUpdateValues() # TODO: replace by signal
  1829. self.win1.OnCheckItem = OnCheckItem
  1830. elif prompt == 'sql_query':
  1831. win = gselect.SqlWhereSelect(
  1832. parent=which_panel, param=p)
  1833. p['wxId'] = [win.GetTextWin().GetId()]
  1834. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1835. which_sizer.Add(
  1836. win,
  1837. proportion=0,
  1838. flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1839. border=5)
  1840. if self.parent.GetName() == 'MainFrame' and (
  1841. self._giface and hasattr(self._giface, "_model")):
  1842. parChk = wx.CheckBox(parent=which_panel, id=wx.ID_ANY,
  1843. label=_("Parameterized in model"))
  1844. parChk.SetName('ModelParam')
  1845. parChk.SetValue(p.get('parameterized', False))
  1846. if 'wxId' in p:
  1847. p['wxId'].append(parChk.GetId())
  1848. else:
  1849. p['wxId'] = [parChk.GetId()]
  1850. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1851. which_sizer.Add(parChk, proportion=0,
  1852. flag=wx.LEFT, border=20)
  1853. if title_txt is not None:
  1854. # create tooltip if given
  1855. if len(p['values_desc']) > 0:
  1856. if tooltip:
  1857. tooltip += 2 * os.linesep
  1858. else:
  1859. tooltip = ''
  1860. if len(p['values']) == len(p['values_desc']):
  1861. for i in range(len(p['values'])):
  1862. tooltip += p['values'][i] + ': ' + \
  1863. p['values_desc'][i] + os.linesep
  1864. tooltip.strip(os.linesep)
  1865. if tooltip:
  1866. title_txt.SetToolTip(tooltip)
  1867. if p == first_param:
  1868. if 'wxId' in p and len(p['wxId']) > 0:
  1869. win = self.FindWindowById(p['wxId'][0])
  1870. win.SetFocus()
  1871. #
  1872. # set widget relations for OnUpdateSelection
  1873. #
  1874. pMap = None
  1875. pLayer = []
  1876. pDriver = None
  1877. pDatabase = None
  1878. pTable = None
  1879. pColumn = []
  1880. pGroup = None
  1881. pSubGroup = None
  1882. pSigFile = []
  1883. pDbase = None
  1884. pLocation = None
  1885. pMapset = None
  1886. pSqlWhere = []
  1887. for p in self.task.params:
  1888. if self.task.blackList['enabled'] and self.task.get_name() in self.task.blackList['items'] and \
  1889. p.get('name', '') in self.task.blackList['items'][self.task.get_name()]['params']:
  1890. continue
  1891. guidep = p.get('guidependency', '')
  1892. if guidep:
  1893. # fixed options dependency defined
  1894. options = guidep.split(',')
  1895. for opt in options:
  1896. pOpt = self.task.get_param(
  1897. opt, element='name', raiseError=False)
  1898. if pOpt and id:
  1899. if 'wxId-bind' not in p:
  1900. p['wxId-bind'] = list()
  1901. p['wxId-bind'] += pOpt['wxId']
  1902. continue
  1903. if p.get('gisprompt', False) == False:
  1904. continue
  1905. prompt = p.get('prompt', '')
  1906. if prompt in ('raster', 'vector'):
  1907. name = p.get('name', '')
  1908. if name in ('map', 'input'):
  1909. pMap = p
  1910. elif prompt == 'layer':
  1911. pLayer.append(p)
  1912. elif prompt == 'dbcolumn':
  1913. pColumn.append(p)
  1914. elif prompt == 'dbdriver':
  1915. pDriver = p
  1916. elif prompt == 'dbname':
  1917. pDatabase = p
  1918. elif prompt == 'dbtable':
  1919. pTable = p
  1920. elif prompt == 'group':
  1921. pGroup = p
  1922. elif prompt == 'subgroup':
  1923. pSubGroup = p
  1924. elif prompt == 'sigfile':
  1925. pSigFile.append(p)
  1926. elif prompt == 'dbase':
  1927. pDbase = p
  1928. elif prompt == 'location':
  1929. pLocation = p
  1930. elif prompt == 'mapset':
  1931. pMapset = p
  1932. elif prompt == 'sql_query':
  1933. pSqlWhere.append(p)
  1934. # collect ids
  1935. pColumnIds = []
  1936. for p in pColumn:
  1937. pColumnIds += p['wxId']
  1938. pLayerIds = []
  1939. for p in pLayer:
  1940. pLayerIds += p['wxId']
  1941. pSigFileIds = []
  1942. for p in pSigFile:
  1943. pSigFileIds += p['wxId']
  1944. pSqlWhereIds = []
  1945. for p in pSqlWhere:
  1946. pSqlWhereIds += p['wxId']
  1947. # set wxId-bindings
  1948. if pMap:
  1949. pMap['wxId-bind'] = []
  1950. if pLayer:
  1951. pMap['wxId-bind'] += pLayerIds
  1952. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1953. pMap['wxId-bind'] += copy.copy(pSqlWhereIds)
  1954. if pLayer:
  1955. for p in pLayer:
  1956. p['wxId-bind'] = copy.copy(pColumnIds)
  1957. p['wxId-bind'] += copy.copy(pSqlWhereIds)
  1958. if pDriver and pTable:
  1959. pDriver['wxId-bind'] = pTable['wxId']
  1960. if pDatabase and pTable:
  1961. pDatabase['wxId-bind'] = pTable['wxId']
  1962. if pTable and pColumnIds:
  1963. pTable['wxId-bind'] = pColumnIds
  1964. if pGroup and pSubGroup:
  1965. if pSigFile:
  1966. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1967. pSubGroup['wxId-bind'] = pSigFileIds
  1968. else:
  1969. pGroup['wxId-bind'] = pSubGroup['wxId']
  1970. if pDbase and pLocation:
  1971. pDbase['wxId-bind'] = pLocation['wxId']
  1972. if pLocation and pMapset:
  1973. pLocation['wxId-bind'] = pMapset['wxId']
  1974. if pLocation and pMapset and pMap:
  1975. # pLocation['wxId-bind'] += pMap['wxId']
  1976. pMapset['wxId-bind'] = pMap['wxId']
  1977. #
  1978. # determine panel size
  1979. #
  1980. maxsizes = (0, 0)
  1981. for section in sections:
  1982. tab[section].SetSizer(tabsizer[section])
  1983. tabsizer[section].Fit(tab[section])
  1984. tab[section].Layout()
  1985. minsecsizes = tabsizer[section].GetSize()
  1986. maxsizes = list(map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1)))
  1987. # TODO: be less arbitrary with these 600
  1988. self.panelMinHeight = 100
  1989. self.constrained_size = (
  1990. min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1991. for section in sections:
  1992. tab[section].SetMinSize(
  1993. (self.constrained_size[0], self.panelMinHeight))
  1994. # add pages to notebook
  1995. imageList = wx.ImageList(16, 16)
  1996. self.notebook.AssignImageList(imageList)
  1997. for section in sections:
  1998. self.notebook.AddPage(
  1999. page=tab[section],
  2000. text=section, name=section)
  2001. index = self.AddBitmapToImageList(section, imageList)
  2002. if index >= 0:
  2003. self.notebook.SetPageImage(section, index)
  2004. # are we running from command line?
  2005. # add 'command output' tab regardless standalone dialog
  2006. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  2007. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  2008. from gui_core.goutput import GConsoleWindow
  2009. self._gconsole = GConsole(
  2010. guiparent=self.notebook, giface=self._giface)
  2011. self.goutput = GConsoleWindow(
  2012. parent=self.notebook,
  2013. gconsole=self._gconsole,
  2014. margin=False)
  2015. self._gconsole.Bind(
  2016. EVT_CMD_RUN, lambda event: self._switchPageHandler(
  2017. event=event, notification=Notification.MAKE_VISIBLE))
  2018. self._gconsole.Bind(
  2019. EVT_CMD_DONE, lambda event: self._switchPageHandler(
  2020. event=event, notification=Notification.RAISE_WINDOW))
  2021. self.outpage = self.notebook.AddPage(
  2022. page=self.goutput, text=_("Command output"), name='output')
  2023. else:
  2024. self.goutput = None
  2025. self._gconsole = None
  2026. self.manualTab = HelpPanel(
  2027. parent=self.notebook,
  2028. command=self.task.get_name())
  2029. if not self.manualTab.GetFile():
  2030. self.manualTab.Hide()
  2031. else:
  2032. self.notebook.AddPage(
  2033. page=self.manualTab,
  2034. text=_("Manual"),
  2035. name='manual')
  2036. index = self.AddBitmapToImageList(
  2037. section='manual', imageList=imageList)
  2038. if index >= 0:
  2039. self.notebook.SetPageImage('manual', index)
  2040. if self.manualTab.IsLoaded():
  2041. self.manualTab.SetMinSize(
  2042. (self.constrained_size[0], self.panelMinHeight))
  2043. self.notebook.SetSelection(0)
  2044. panelsizer.Add(self.notebook, proportion=1, flag=wx.EXPAND)
  2045. self.SetSizer(panelsizer)
  2046. panelsizer.Fit(self.notebook)
  2047. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  2048. def _getValue(self, p):
  2049. """Get value or default value of given parameter
  2050. :param p: parameter directory
  2051. """
  2052. if p.get('value', '') != '':
  2053. return p['value']
  2054. return p.get('default', '')
  2055. def OnFileLoad(self, event):
  2056. """Load file to interactive input"""
  2057. me = event.GetId()
  2058. win = dict()
  2059. for p in self.task.params:
  2060. if 'wxId' in p and me in p['wxId']:
  2061. win['file'] = self.FindWindowById(p['wxId'][0])
  2062. win['text'] = self.FindWindowById(p['wxId'][1])
  2063. break
  2064. if not win:
  2065. return
  2066. path = win['file'].GetValue()
  2067. if not path:
  2068. gcmd.GMessage(parent=self,
  2069. message=_("Nothing to load."))
  2070. return
  2071. data = ''
  2072. try:
  2073. f = open(path, "r")
  2074. except IOError as e:
  2075. gcmd.GError(parent=self, showTraceback=False,
  2076. message=_("Unable to load file.\n\nReason: %s") % e)
  2077. return
  2078. try:
  2079. data = f.read()
  2080. finally:
  2081. f.close()
  2082. win['text'].SetValue(data)
  2083. def OnFileSave(self, event):
  2084. """Save interactive input to the file"""
  2085. wId = event.GetId()
  2086. win = {}
  2087. for p in self.task.params:
  2088. if wId in p.get('wxId', []):
  2089. win['file'] = self.FindWindowById(p['wxId'][0])
  2090. win['text'] = self.FindWindowById(p['wxId'][1])
  2091. break
  2092. if not win:
  2093. return
  2094. text = win['text'].GetValue()
  2095. if not text:
  2096. gcmd.GMessage(parent=self,
  2097. message=_("Nothing to save."))
  2098. return
  2099. dlg = wx.FileDialog(parent=self,
  2100. message=_("Save input as..."),
  2101. defaultDir=os.getcwd(),
  2102. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  2103. if dlg.ShowModal() == wx.ID_OK:
  2104. path = dlg.GetPath()
  2105. enc = locale.getdefaultlocale()[1]
  2106. f = codecs.open(path, encoding=enc, mode='w', errors='replace')
  2107. try:
  2108. f.write(text + os.linesep)
  2109. finally:
  2110. f.close()
  2111. win['file'].SetValue(path)
  2112. dlg.Destroy()
  2113. def OnFileText(self, event):
  2114. """File input interactively entered"""
  2115. text = event.GetString()
  2116. p = self.task.get_param(
  2117. value=event.GetId(),
  2118. element='wxId',
  2119. raiseError=False)
  2120. if not p:
  2121. return # should not happen
  2122. win = self.FindWindowById(p['wxId'][0])
  2123. if text:
  2124. filename = win.GetValue()
  2125. if not filename or filename == p[
  2126. 'default']: # m.proj has - as default
  2127. filename = grass.tempfile()
  2128. win.SetValue(filename)
  2129. enc = locale.getdefaultlocale()[1]
  2130. f = codecs.open(filename, encoding=enc, mode='w', errors='replace')
  2131. try:
  2132. f.write(text)
  2133. if text[-1] != os.linesep:
  2134. f.write(os.linesep)
  2135. finally:
  2136. f.close()
  2137. else:
  2138. win.SetValue('')
  2139. def OnVectorFormat(self, event):
  2140. """Change vector format (native / ogr).
  2141. Currently unused.
  2142. """
  2143. sel = event.GetSelection()
  2144. idEvent = event.GetId()
  2145. p = self.task.get_param(
  2146. value=idEvent,
  2147. element='wxId',
  2148. raiseError=False)
  2149. if not p:
  2150. return # should not happen
  2151. # detect windows
  2152. winNative = None
  2153. winOgr = None
  2154. for id in p['wxId']:
  2155. if id == idEvent:
  2156. continue
  2157. name = self.FindWindowById(id).GetName()
  2158. if name == 'Select':
  2159. # fix the mystery (also in nviz_tools.py)
  2160. winNative = self.FindWindowById(id + 1)
  2161. elif name == 'OgrSelect':
  2162. winOgr = self.FindWindowById(id)
  2163. # enable / disable widgets & update values
  2164. rbox = self.FindWindowByName('VectorFormat')
  2165. self.hsizer.Remove(rbox)
  2166. if sel == 0: # -> native
  2167. winOgr.Hide()
  2168. self.hsizer.Remove(winOgr)
  2169. self.hsizer.Add(
  2170. winNative,
  2171. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  2172. border=5)
  2173. winNative.Show()
  2174. p['value'] = winNative.GetValue()
  2175. elif sel == 1: # -> OGR
  2176. sizer = wx.BoxSizer(wx.VERTICAL)
  2177. winNative.Hide()
  2178. self.hsizer.Remove(winNative)
  2179. sizer.Add(winOgr)
  2180. winOgr.Show()
  2181. p['value'] = winOgr.GetDsn()
  2182. self.hsizer.Add(
  2183. sizer,
  2184. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  2185. border=5)
  2186. self.hsizer.Add(rbox,
  2187. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  2188. wx.RIGHT | wx.ALIGN_TOP,
  2189. border=5)
  2190. self.hsizer.Layout()
  2191. self.Layout()
  2192. self.OnUpdateValues()
  2193. self.OnUpdateSelection(event)
  2194. def OnUpdateDialog(self, event):
  2195. for fn, kwargs in six.iteritems(event.data):
  2196. fn(**kwargs)
  2197. self.parent.updateValuesHook()
  2198. def OnVerbosity(self, event):
  2199. """Verbosity level changed"""
  2200. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  2201. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  2202. if event.IsChecked():
  2203. if event.GetId() == verbose.GetId():
  2204. if quiet.IsChecked():
  2205. quiet.SetValue(False)
  2206. self.task.get_flag('quiet')['value'] = False
  2207. else:
  2208. if verbose.IsChecked():
  2209. verbose.SetValue(False)
  2210. self.task.get_flag('verbose')['value'] = False
  2211. event.Skip()
  2212. def OnPageChange(self, event):
  2213. if not event:
  2214. sel = self.notebook.GetSelection()
  2215. else:
  2216. sel = event.GetSelection()
  2217. idx = self.notebook.GetPageIndexByName('manual')
  2218. if idx > -1 and sel == idx:
  2219. # calling LoadPage() is strangely time-consuming (only first call)
  2220. # FIXME: move to helpPage.__init__()
  2221. if not self.manualTab.IsLoaded():
  2222. wx.GetApp().Yield()
  2223. self.manualTab.LoadPage()
  2224. self.Layout()
  2225. if event:
  2226. # skip is needed for wx.Notebook on Windows
  2227. event.Skip()
  2228. # this is needed for dialogs launched from layer manager
  2229. # event is somehow propagated?
  2230. event.StopPropagation()
  2231. def _switchPageHandler(self, event, notification):
  2232. self._switchPage(notification=notification)
  2233. event.Skip()
  2234. def _switchPage(self, notification):
  2235. """Manages @c 'output' notebook page according to event notification."""
  2236. if notification == Notification.HIGHLIGHT:
  2237. self.notebook.HighlightPageByName('output')
  2238. if notification == Notification.MAKE_VISIBLE:
  2239. self.notebook.SetSelectionByName('output')
  2240. if notification == Notification.RAISE_WINDOW:
  2241. self.notebook.SetSelectionByName('output')
  2242. self.SetFocus()
  2243. self.Raise()
  2244. def OnColorChange(self, event):
  2245. myId = event.GetId()
  2246. for p in self.task.params:
  2247. if 'wxId' in p and myId in p['wxId']:
  2248. multiple = p['wxId'][1] is not None # multiple colors
  2249. hasTansp = p['wxId'][2] is not None
  2250. if multiple:
  2251. # selected color is added at the end of textCtrl
  2252. colorchooser = wx.FindWindowById(p['wxId'][0])
  2253. new_color = colorchooser.GetValue()[:]
  2254. new_label = utils.rgb2str.get(
  2255. new_color, ':'.join(list(map(str, new_color))))
  2256. textCtrl = wx.FindWindowById(p['wxId'][1])
  2257. val = textCtrl.GetValue()
  2258. sep = ','
  2259. if val and val[-1] != sep:
  2260. val += sep
  2261. val += new_label
  2262. textCtrl.SetValue(val)
  2263. p['value'] = val
  2264. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  2265. p['value'] = 'none'
  2266. else:
  2267. colorchooser = wx.FindWindowById(p['wxId'][0])
  2268. new_color = colorchooser.GetValue()[:]
  2269. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  2270. # under wx2.8.1
  2271. new_label = utils.rgb2str.get(
  2272. new_color, ':'.join(list(map(str, new_color))))
  2273. colorchooser.SetLabel(new_label)
  2274. colorchooser.SetColour(new_color)
  2275. colorchooser.Refresh()
  2276. p['value'] = colorchooser.GetLabel()
  2277. self.OnUpdateValues()
  2278. def OnUpdateValues(self, event=None):
  2279. """If we were part of a richer interface, report back the
  2280. current command being built.
  2281. This method should be set by the parent of this panel if
  2282. needed. It's a hook, actually. Beware of what is 'self' in
  2283. the method def, though. It will be called with no arguments.
  2284. """
  2285. pass
  2286. def OnCheckBoxMulti(self, event):
  2287. """Fill the values as a ','-separated string according to
  2288. current status of the checkboxes.
  2289. """
  2290. me = event.GetId()
  2291. theParam = None
  2292. for p in self.task.params:
  2293. if 'wxId' in p and me in p['wxId']:
  2294. theParam = p
  2295. myIndex = p['wxId'].index(me)
  2296. # Unpack current value list
  2297. currentValues = {}
  2298. for isThere in theParam.get('value', '').split(','):
  2299. currentValues[isThere] = 1
  2300. theValue = theParam['values'][myIndex]
  2301. if event.IsChecked():
  2302. currentValues[theValue] = 1
  2303. else:
  2304. del currentValues[theValue]
  2305. # Keep the original order, so that some defaults may be recovered
  2306. currentValueList = []
  2307. for v in theParam['values']:
  2308. if v in currentValues:
  2309. currentValueList.append(v)
  2310. # Pack it back
  2311. theParam['value'] = ','.join(currentValueList)
  2312. self.OnUpdateValues()
  2313. event.Skip()
  2314. def OnSetValue(self, event):
  2315. """Retrieve the widget value and set the task value field
  2316. accordingly.
  2317. Use for widgets that have a proper GetValue() method, i.e. not
  2318. for selectors.
  2319. """
  2320. myId = event.GetId()
  2321. me = wx.FindWindowById(myId)
  2322. name = me.GetName()
  2323. found = False
  2324. for porf in self.task.params + self.task.flags:
  2325. if 'wxId' not in porf:
  2326. continue
  2327. if myId in porf['wxId']:
  2328. found = True
  2329. break
  2330. if not found:
  2331. return
  2332. if name == 'GdalSelect':
  2333. porf['value'] = event.dsn
  2334. elif name == 'ModelParam':
  2335. porf['parameterized'] = me.IsChecked()
  2336. elif name == 'GdalSelectDataSource':
  2337. win = self.FindWindowById(porf['wxId'][0])
  2338. porf['value'] = win.GetDsn()
  2339. pLayer = self.task.get_param(
  2340. 'layer', element='name', raiseError=False)
  2341. if pLayer:
  2342. pLayer['value'] = ''
  2343. else:
  2344. if isinstance(me, SpinCtrl):
  2345. porf['value'] = str(me.GetValue())
  2346. elif isinstance(me, wx.ComboBox):
  2347. porf['value'] = me.GetValue()
  2348. elif isinstance(me, wx.Choice):
  2349. porf['value'] = me.GetStringSelection()
  2350. else:
  2351. porf['value'] = me.GetValue()
  2352. self.OnUpdateValues(event)
  2353. event.Skip()
  2354. def OnSetSymbol(self, event):
  2355. """Shows dialog for symbol selection"""
  2356. myId = event.GetId()
  2357. for p in self.task.params:
  2358. if 'wxId' in p and myId in p['wxId']:
  2359. from gui_core.dialogs import SymbolDialog
  2360. dlg = SymbolDialog(self, symbolPath=globalvar.SYMBDIR,
  2361. currentSymbol=p['value'])
  2362. if dlg.ShowModal() == wx.ID_OK:
  2363. img = dlg.GetSelectedSymbolPath()
  2364. p['value'] = dlg.GetSelectedSymbolName()
  2365. bitmapButton = wx.FindWindowById(p['wxId'][0])
  2366. label = wx.FindWindowById(p['wxId'][1])
  2367. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  2368. label.SetLabel(p['value'])
  2369. self.OnUpdateValues(event)
  2370. dlg.Destroy()
  2371. def OnTimelineTool(self, event):
  2372. """Show Timeline Tool with dataset(s) from gselect.
  2373. .. todo::
  2374. update from gselect automatically
  2375. """
  2376. myId = event.GetId()
  2377. for p in self.task.params:
  2378. if 'wxId' in p and myId in p['wxId']:
  2379. select = self.FindWindowById(p['wxId'][0])
  2380. if not select.GetValue():
  2381. gcmd.GMessage(parent=self, message=_("No dataset given."))
  2382. return
  2383. datasets = select.GetValue().split(',')
  2384. from timeline import frame
  2385. frame.run(parent=self, datasets=datasets)
  2386. def OnSelectFont(self, event):
  2387. """Select font using font dialog"""
  2388. myId = event.GetId()
  2389. for p in self.task.params:
  2390. if 'wxId' in p and myId in p['wxId']:
  2391. from gui_core.dialogs import DefaultFontDialog
  2392. dlg = DefaultFontDialog(parent=self,
  2393. title=_('Select font'),
  2394. style=wx.DEFAULT_DIALOG_STYLE,
  2395. type='font')
  2396. if dlg.ShowModal() == wx.ID_OK:
  2397. if dlg.font:
  2398. p['value'] = dlg.font
  2399. self.FindWindowById(p['wxId'][1]).SetValue(dlg.font)
  2400. self.OnUpdateValues(event)
  2401. dlg.Destroy()
  2402. def OnUpdateSelection(self, event):
  2403. """Update dialog (layers, tables, columns, etc.)
  2404. """
  2405. if not hasattr(self.parent, "updateThread"):
  2406. if event:
  2407. event.Skip()
  2408. return
  2409. if event:
  2410. self.parent.updateThread.Update(UpdateDialog,
  2411. self,
  2412. event,
  2413. event.GetId(),
  2414. self.task)
  2415. else:
  2416. self.parent.updateThread.Update(UpdateDialog,
  2417. self,
  2418. None,
  2419. None,
  2420. self.task)
  2421. def createCmd(self, ignoreErrors=False, ignoreRequired=False):
  2422. """Produce a command line string (list) or feeding into GRASS.
  2423. :param ignoreErrors: True then it will return whatever has been
  2424. built so far, even though it would not be
  2425. a correct command for GRASS
  2426. """
  2427. try:
  2428. cmd = self.task.get_cmd(ignoreErrors=ignoreErrors,
  2429. ignoreRequired=ignoreRequired)
  2430. except ValueError as err:
  2431. dlg = wx.MessageDialog(parent=self,
  2432. message=gcmd.DecodeString(str(err)),
  2433. caption=_("Error in %s") % self.task.name,
  2434. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  2435. dlg.ShowModal()
  2436. dlg.Destroy()
  2437. cmd = None
  2438. return cmd
  2439. def OnSize(self, event):
  2440. width = event.GetSize()[0]
  2441. fontsize = self.GetFont().GetPointSize()
  2442. text_width = max(width / (fontsize - 3), 70)
  2443. for id in self.label_id:
  2444. win = self.FindWindowById(id)
  2445. label = win.GetLabel()
  2446. label_new = '\n'.join(textwrap.wrap(label, text_width))
  2447. win.SetLabel(label_new)
  2448. event.Skip()
  2449. def AddBitmapToImageList(self, section, imageList):
  2450. iconTheme = UserSettings.Get(
  2451. group='appearance',
  2452. key='iconTheme',
  2453. subkey='type')
  2454. iconSectionDict = {
  2455. 'manual': os.path.join(
  2456. globalvar.ICONDIR,
  2457. iconTheme,
  2458. 'help.png')}
  2459. if section in iconSectionDict.keys():
  2460. image = wx.Image(
  2461. iconSectionDict[section]).Scale(
  2462. 16, 16, wx.IMAGE_QUALITY_HIGH)
  2463. idx = imageList.Add(BitmapFromImage(image))
  2464. return idx
  2465. return -1
  2466. class GUI:
  2467. def __init__(self, parent=None, giface=None, show=True, modal=False,
  2468. centreOnParent=False, checkError=False):
  2469. """Parses GRASS commands when module is imported and used from
  2470. Layer Manager.
  2471. """
  2472. self.parent = parent
  2473. self.show = show
  2474. self.modal = modal
  2475. self._giface = giface
  2476. self.centreOnParent = centreOnParent
  2477. self.checkError = checkError
  2478. self.grass_task = None
  2479. self.cmd = list()
  2480. global _blackList
  2481. if self.parent:
  2482. _blackList['enabled'] = True
  2483. else:
  2484. _blackList['enabled'] = False
  2485. def GetCmd(self):
  2486. """Get validated command"""
  2487. return self.cmd
  2488. def ParseCommand(self, cmd, completed=None):
  2489. """Parse command
  2490. Note: cmd is given as list
  2491. If command is given with options, return validated cmd list:
  2492. - add key name for first parameter if not given
  2493. - change mapname to mapname@mapset
  2494. """
  2495. dcmd_params = {}
  2496. if completed is None:
  2497. get_dcmd = None
  2498. layer = None
  2499. dcmd_params = None
  2500. else:
  2501. get_dcmd = completed[0]
  2502. layer = completed[1]
  2503. if completed[2]:
  2504. dcmd_params.update(completed[2])
  2505. # parse the interface decription
  2506. try:
  2507. global _blackList
  2508. self.grass_task = gtask.parse_interface(cmd[0],
  2509. blackList=_blackList)
  2510. except (grass.ScriptError, ValueError) as e:
  2511. raise gcmd.GException(e.value)
  2512. # if layer parameters previously set, re-insert them into dialog
  2513. if completed is not None:
  2514. if 'params' in dcmd_params:
  2515. self.grass_task.params = dcmd_params['params']
  2516. if 'flags' in dcmd_params:
  2517. self.grass_task.flags = dcmd_params['flags']
  2518. err = list()
  2519. # update parameters if needed && validate command
  2520. if len(cmd) > 1:
  2521. i = 0
  2522. cmd_validated = [cmd[0]]
  2523. for option in cmd[1:]:
  2524. if option[0] == '-': # flag
  2525. if len(option) == 1: # catch typo like 'g.proj - w'
  2526. raise gcmd.GException(
  2527. _("Unable to parse command '%s'") %
  2528. ' '.join(cmd))
  2529. if option[1] == '-':
  2530. self.grass_task.set_flag(option[2:], True)
  2531. else:
  2532. self.grass_task.set_flag(option[1], True)
  2533. cmd_validated.append(option)
  2534. else: # parameter
  2535. try:
  2536. key, value = option.split('=', 1)
  2537. except ValueError:
  2538. if self.grass_task.firstParam:
  2539. if i == 0: # add key name of first parameter if not given
  2540. key = self.grass_task.firstParam
  2541. value = option
  2542. else:
  2543. raise gcmd.GException(
  2544. _("Unable to parse command '%s'") % ' '.join(cmd))
  2545. else:
  2546. continue
  2547. task = self.grass_task.get_param(key, raiseError=False)
  2548. if not task:
  2549. err.append(
  2550. _("%(cmd)s: parameter '%(key)s' not available") % {
  2551. 'cmd': cmd[0],
  2552. 'key': key})
  2553. continue
  2554. self.grass_task.set_param(key, value)
  2555. cmd_validated.append(key + '=' + value)
  2556. i += 1
  2557. # update original command list
  2558. cmd = cmd_validated
  2559. if self.show is not None:
  2560. self.mf = TaskFrame(parent=self.parent, giface=self._giface,
  2561. task_description=self.grass_task,
  2562. get_dcmd=get_dcmd, layer=layer)
  2563. else:
  2564. self.mf = None
  2565. if get_dcmd is not None:
  2566. # update only propwin reference
  2567. get_dcmd(dcmd=None, layer=layer, params=None,
  2568. propwin=self.mf)
  2569. if self.show is not None:
  2570. self.mf.notebookpanel.OnUpdateSelection(None)
  2571. if self.show is True:
  2572. if self.parent and self.centreOnParent:
  2573. self.mf.CentreOnParent()
  2574. else:
  2575. self.mf.CenterOnScreen()
  2576. self.mf.Show(self.show)
  2577. self.mf.MakeModal(self.modal)
  2578. else:
  2579. self.mf.OnApply(None)
  2580. self.cmd = cmd
  2581. if self.checkError:
  2582. return self.grass_task, err
  2583. else:
  2584. return self.grass_task
  2585. def GetCommandInputMapParamKey(self, cmd):
  2586. """Get parameter key for input raster/vector map
  2587. :param cmd: module name
  2588. :return: parameter key
  2589. :return: None on failure
  2590. """
  2591. # parse the interface decription
  2592. if not self.grass_task:
  2593. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2594. self.grass_task = gtask.processTask(tree).get_task()
  2595. for p in self.grass_task.params:
  2596. if p.get('name', '') in ('input', 'map'):
  2597. age = p.get('age', '')
  2598. prompt = p.get('prompt', '')
  2599. element = p.get('element', '')
  2600. if age == 'old' and \
  2601. element in ('cell', 'grid3', 'vector') and \
  2602. prompt in ('raster', 'raster_3d', 'vector'):
  2603. return p.get('name', None)
  2604. return None
  2605. class GrassGUIApp(wx.App):
  2606. """Stand-alone GRASS command GUI
  2607. """
  2608. def __init__(self, grass_task):
  2609. self.grass_task = grass_task
  2610. wx.App.__init__(self, False)
  2611. def OnInit(self):
  2612. msg = self.grass_task.get_error_msg()
  2613. if msg:
  2614. gcmd.GError(
  2615. msg +
  2616. '\n\n' +
  2617. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2618. return True
  2619. self.mf = TaskFrame(
  2620. parent=None,
  2621. giface=None,
  2622. task_description=self.grass_task)
  2623. self.mf.CentreOnScreen()
  2624. self.mf.Show(True)
  2625. self.SetTopWindow(self.mf)
  2626. return True
  2627. USAGE_MESSAGE = """Usage:
  2628. {name} <grass module>
  2629. {name} <full path to file>
  2630. python {name} <grass module>
  2631. Test:
  2632. python {name} test
  2633. python {name} g.region
  2634. python {name} "g.region -p"
  2635. python {name} temporal/t.list/t.list.py"""
  2636. if __name__ == "__main__":
  2637. if len(sys.argv) == 1:
  2638. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2639. if sys.argv[1] != 'test':
  2640. q = wx.LogNull()
  2641. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2642. cmd = utils.split(sys.argv[1])
  2643. task = gtask.grassTask(cmd[0])
  2644. task.set_options(cmd[1:])
  2645. Debug.msg(1, "forms.py opening form for: %s" %
  2646. task.get_cmd(ignoreErrors=True, ignoreRequired=True))
  2647. app = GrassGUIApp(task)
  2648. app.MainLoop()
  2649. else: # Test
  2650. # Test grassTask from within a GRASS session
  2651. if os.getenv("GISBASE") is not None:
  2652. task = gtask.grassTask("d.vect")
  2653. task.get_param('map')['value'] = "map_name"
  2654. task.get_flag('i')['value'] = True
  2655. task.get_param('layer')['value'] = 1
  2656. task.get_param('label_bcolor')['value'] = "red"
  2657. # the default parameter display is added automatically
  2658. assert ' '.join(
  2659. task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
  2660. print("Creation of task successful")
  2661. # Test interface building with handmade grassTask,
  2662. # possibly outside of a GRASS session.
  2663. print("Now creating a module dialog (task frame)")
  2664. task = gtask.grassTask()
  2665. task.name = "TestTask"
  2666. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2667. task.keywords = ["grass", "test", "task"]
  2668. task.params = [
  2669. {
  2670. "name": "text",
  2671. "description": "Descriptions go into tooltips if labels are present, like this one",
  2672. "label": "Enter some text",
  2673. "key_desc": ["value"],
  2674. "values_desc": []
  2675. }, {
  2676. "name": "hidden_text",
  2677. "description": "This text should not appear in the form",
  2678. "hidden": True,
  2679. "key_desc": ["value"],
  2680. "values_desc": []
  2681. }, {
  2682. "name": "text_default",
  2683. "description": "Enter text to override the default",
  2684. "default": "default text",
  2685. "key_desc": ["value"],
  2686. "values_desc": []
  2687. }, {
  2688. "name": "text_prefilled",
  2689. "description": "You should see a friendly welcome message here",
  2690. "value": "hello, world",
  2691. "key_desc": ["value"],
  2692. "values_desc": []
  2693. }, {
  2694. "name": "plain_color",
  2695. "description": "This is a plain color, and it is a compulsory parameter",
  2696. "required": False,
  2697. "gisprompt": True,
  2698. "prompt": "color",
  2699. "key_desc": ["value"],
  2700. "values_desc": []
  2701. }, {
  2702. "name": "transparent_color",
  2703. "description": "This color becomes transparent when set to none",
  2704. "guisection": "tab",
  2705. "gisprompt": True,
  2706. "prompt": "color",
  2707. "key_desc": ["value"],
  2708. "values_desc": []
  2709. }, {
  2710. "name": "multi",
  2711. "description": "A multiple selection",
  2712. 'default': u'red,green,blue',
  2713. 'gisprompt': False,
  2714. 'guisection': 'tab',
  2715. 'multiple': u'yes',
  2716. 'type': u'string',
  2717. 'value': '',
  2718. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2719. "key_desc": ["value"],
  2720. "values_desc": []
  2721. }, {
  2722. "name": "single",
  2723. "description": "A single multiple-choice selection",
  2724. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2725. "guisection": "tab",
  2726. "key_desc": ["value"],
  2727. "values_desc": []
  2728. }, {
  2729. "name": "large_multi",
  2730. "description": "A large multiple selection",
  2731. "gisprompt": False,
  2732. "multiple": "yes",
  2733. # values must be an array of strings
  2734. "values": utils.str2rgb.keys() + list(map(str, utils.str2rgb.values())),
  2735. "key_desc": ["value"],
  2736. "values_desc": []
  2737. }, {
  2738. "name": "a_file",
  2739. "description": "A file selector",
  2740. "gisprompt": True,
  2741. "element": "file",
  2742. "key_desc": ["value"],
  2743. "values_desc": []
  2744. }
  2745. ]
  2746. task.flags = [{"name": "a",
  2747. "description": "Some flag, will appear in Main since it is required",
  2748. "required": True,
  2749. "value": False,
  2750. "suppress_required": False},
  2751. {"name": "b",
  2752. "description": "pre-filled flag, will appear in options since it is not required",
  2753. "value": True,
  2754. "suppress_required": False},
  2755. {"name": "hidden_flag",
  2756. "description": "hidden flag, should not be changeable",
  2757. "hidden": "yes",
  2758. "value": True,
  2759. "suppress_required": False}]
  2760. q = wx.LogNull()
  2761. GrassGUIApp(task).MainLoop()