forms.py 115 KB

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