forms.py 126 KB

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