forms.py 126 KB

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