forms.py 125 KB

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