forms.py 115 KB

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