forms.py 126 KB

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