menuform.py 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. @brief Construct simple wxPython GUI from a GRASS command interface
  5. description.
  6. Classes:
  7. - helpPanel
  8. - mainFrame
  9. - cmdPanel
  10. - GrassGUIApp
  11. - GUI
  12. - FloatValidator
  13. - GNotebook
  14. This program is just a coarse approach to automatically build a GUI
  15. from a xml-based GRASS user interface description.
  16. You need to have Python 2.4, wxPython 2.8 and python-xml.
  17. The XML stream is read from executing the command given in the
  18. command line, thus you may call it for instance this way:
  19. python <this file.py> r.basins.fill
  20. Or you set an alias or wrap the call up in a nice shell script, GUI
  21. environment ... please contribute your idea.
  22. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  23. make it callable by gui. Method added to automatically re-run with
  24. pythonw on a Mac.
  25. @todo
  26. - verify option value types
  27. Copyright(C) 2000-2011 by the GRASS Development Team
  28. This program is free software under the GPL(>=v2) Read the file
  29. COPYING coming with GRASS for details.
  30. @author Jan-Oliver Wagner <jan@intevation.de>
  31. @author Bernhard Reiter <bernhard@intevation.de>
  32. @author Michael Barton, Arizona State University
  33. @author Daniel Calvelo <dca.gis@gmail.com>
  34. @author Martin Landa <landa.martin@gmail.com>
  35. @author Luca Delucchi <lucadeluge@gmail.com>
  36. """
  37. import sys
  38. import re
  39. import string
  40. import textwrap
  41. import os
  42. import time
  43. import types
  44. import copy
  45. import locale
  46. import types
  47. from threading import Thread
  48. import Queue
  49. import tempfile
  50. import globalvar
  51. import wx
  52. import wx.html
  53. try:
  54. import wx.lib.agw.flatnotebook as FN
  55. except ImportError:
  56. import wx.lib.flatnotebook as FN
  57. import wx.lib.colourselect as csel
  58. import wx.lib.filebrowsebutton as filebrowse
  59. import wx.lib.scrolledpanel as scrolled
  60. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  61. from wx.lib.newevent import NewEvent
  62. try:
  63. import xml.etree.ElementTree as etree
  64. except ImportError:
  65. import elementtree.ElementTree as etree # Python <= 2.4
  66. import gdialogs
  67. from ghelp import HelpPanel
  68. gisbase = os.getenv("GISBASE")
  69. if gisbase is None:
  70. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  71. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  72. wxbase = gisbase
  73. else:
  74. wxbase = os.path.join(globalvar.ETCWXDIR)
  75. sys.path.append(wxbase)
  76. from grass.script import core as grass
  77. from grass.script import task as gtask
  78. import gselect
  79. import gcmd
  80. import goutput
  81. import utils
  82. from preferences import globalSettings as UserSettings
  83. try:
  84. import subprocess
  85. except:
  86. from compat import subprocess
  87. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  88. # From lib/gis/col_str.c, except purple which is mentioned
  89. # there but not given RGB values
  90. str2rgb = {'aqua': (100, 128, 255),
  91. 'black': (0, 0, 0),
  92. 'blue': (0, 0, 255),
  93. 'brown': (180, 77, 25),
  94. 'cyan': (0, 255, 255),
  95. 'gray': (128, 128, 128),
  96. 'green': (0, 255, 0),
  97. 'grey': (128, 128, 128),
  98. 'indigo': (0, 128, 255),
  99. 'magenta': (255, 0, 255),
  100. 'orange': (255, 128, 0),
  101. 'purple': (128, 0, 128),
  102. 'red': (255, 0, 0),
  103. 'violet': (128, 0, 255),
  104. 'white': (255, 255, 255),
  105. 'yellow': (255, 255, 0)}
  106. rgb2str = {}
  107. for (s,r) in str2rgb.items():
  108. rgb2str[ r ] = s
  109. """!Hide some options in the GUI"""
  110. #_blackList = { 'enabled' : False,
  111. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  112. # 'flags' : ['z', 'overwrite']}}}
  113. _blackList = { 'enabled' : False,
  114. 'items' : {} }
  115. def color_resolve(color):
  116. if len(color) > 0 and color[0] in "0123456789":
  117. rgb = tuple(map(int, color.split(':')))
  118. label = color
  119. else:
  120. # Convert color names to RGB
  121. try:
  122. rgb = str2rgb[color]
  123. label = color
  124. except KeyError:
  125. rgb = (200, 200, 200)
  126. label = _('Select Color')
  127. return (rgb, label)
  128. def text_beautify(someString , width = 70):
  129. """!Make really long texts shorter, clean up whitespace and remove
  130. trailing punctuation.
  131. """
  132. if width > 0:
  133. return escape_ampersand(string.strip(
  134. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  135. ".,;:"))
  136. else:
  137. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  138. def escape_ampersand(text):
  139. """!Escapes ampersands with additional ampersand for GUI"""
  140. return string.replace(text, "&", "&&")
  141. class UpdateThread(Thread):
  142. """!Update dialog widgets in the thread"""
  143. def __init__(self, parent, event, eventId, task):
  144. Thread.__init__(self)
  145. self.parent = parent
  146. self.event = event
  147. self.eventId = eventId
  148. self.task = task
  149. self.setDaemon(True)
  150. # list of functions which updates the dialog
  151. self.data = {}
  152. def run(self):
  153. # get widget id
  154. if not self.eventId:
  155. for p in self.task.params:
  156. if p.get('gisprompt', False) == False:
  157. continue
  158. prompt = p.get('element', '')
  159. if prompt == 'vector':
  160. name = p.get('name', '')
  161. if name in ('map', 'input'):
  162. self.eventId = p['wxId'][0]
  163. if self.eventId is None:
  164. return
  165. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  166. if not p or 'wxId-bind' not in p:
  167. return
  168. # get widget prompt
  169. pType = p.get('prompt', '')
  170. if not pType:
  171. return
  172. # check for map/input parameter
  173. pMap = self.task.get_param('map', raiseError = False)
  174. if not pMap:
  175. pMap = self.task.get_param('input', raiseError = False)
  176. if pMap:
  177. map = pMap.get('value', '')
  178. else:
  179. map = None
  180. # avoid running db.describe several times
  181. cparams = dict()
  182. cparams[map] = { 'dbInfo' : None,
  183. 'layers' : None, }
  184. # update reference widgets
  185. for uid in p['wxId-bind']:
  186. win = self.parent.FindWindowById(uid)
  187. if not win:
  188. continue
  189. name = win.GetName()
  190. map = layer = None
  191. driver = db = table = None
  192. if name in ('LayerSelect', 'ColumnSelect'):
  193. if p.get('element', '') == 'vector': # -> vector
  194. # get map name
  195. map = p.get('value', '')
  196. # get layer
  197. for bid in p['wxId-bind']:
  198. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  199. if not p:
  200. continue
  201. if p.get('element', '') == 'layer':
  202. layer = p.get('value', '')
  203. if layer != '':
  204. layer = p.get('value', '')
  205. else:
  206. layer = p.get('default', '')
  207. break
  208. elif p.get('element', '') == 'layer': # -> layer
  209. # get layer
  210. layer = p.get('value', '')
  211. if layer != '':
  212. layer = p.get('value', '')
  213. else:
  214. layer = p.get('default', '')
  215. # get map name
  216. pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  217. if pMapL:
  218. map = pMapL.get('value', '')
  219. if name == 'TableSelect' or \
  220. (name == 'ColumnSelect' and not map):
  221. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  222. if pDriver:
  223. driver = pDriver.get('value', '')
  224. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  225. if pDb:
  226. db = pDb.get('value', '')
  227. if name == 'ColumnSelect':
  228. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  229. if pTable:
  230. table = pTable.get('value', '')
  231. if name == 'LayerSelect':
  232. # determine format
  233. native = True
  234. for id in pMap['wxId']:
  235. winVec = self.parent.FindWindowById(id)
  236. if winVec.GetName() == 'VectorFormat' and \
  237. winVec.GetSelection() != 0:
  238. native = False
  239. break
  240. # TODO: update only if needed
  241. if native:
  242. if map:
  243. self.data[win.InsertLayers] = { 'vector' : map }
  244. else:
  245. self.data[win.InsertLayers] = { }
  246. else:
  247. if map:
  248. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  249. else:
  250. self.data[win.InsertLayers] = { }
  251. elif name == 'TableSelect':
  252. self.data[win.InsertTables] = { 'driver' : driver,
  253. 'database' : db }
  254. elif name == 'ColumnSelect':
  255. if map:
  256. if map in cparams:
  257. if not cparams[map]['dbInfo']:
  258. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  259. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  260. 'dbInfo' : cparams[map]['dbInfo'] }
  261. else: # table
  262. if driver and db:
  263. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  264. 'driver' : driver,
  265. 'database' : db }
  266. elif pTable:
  267. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  268. elif name == 'SubGroupSelect':
  269. pGroup = self.task.get_param('group', element = 'element', raiseError = False)
  270. if pGroup:
  271. self.data[win.Insert] = { 'group' : pGroup.get('value', '')}
  272. elif name == 'LocationSelect':
  273. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  274. if pDbase:
  275. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  276. elif name == 'MapsetSelect':
  277. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  278. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  279. if pDbase and pLocation:
  280. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  281. 'location' : pLocation.get('value', '')}
  282. elif name == 'ProjSelect':
  283. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  284. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  285. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  286. if pDbase and pLocation and pMapset:
  287. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  288. 'location' : pLocation.get('value', ''),
  289. 'mapset' : pMapset.get('value', '')}
  290. def UpdateDialog(parent, event, eventId, task):
  291. return UpdateThread(parent, event, eventId, task)
  292. class UpdateQThread(Thread):
  293. """!Update dialog widgets in the thread"""
  294. requestId = 0
  295. def __init__(self, parent, requestQ, resultQ, **kwds):
  296. Thread.__init__(self, **kwds)
  297. self.parent = parent # cmdPanel
  298. self.setDaemon(True)
  299. self.requestQ = requestQ
  300. self.resultQ = resultQ
  301. self.start()
  302. def Update(self, callable, *args, **kwds):
  303. UpdateQThread.requestId += 1
  304. self.request = None
  305. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  306. return UpdateQThread.requestId
  307. def run(self):
  308. while True:
  309. requestId, callable, args, kwds = self.requestQ.get()
  310. requestTime = time.time()
  311. self.request = callable(*args, **kwds)
  312. self.resultQ.put((requestId, self.request.run()))
  313. if self.request:
  314. event = wxUpdateDialog(data = self.request.data)
  315. wx.PostEvent(self.parent, event)
  316. class mainFrame(wx.Frame):
  317. """!This is the Frame containing the dialog for options input.
  318. The dialog is organized in a notebook according to the guisections
  319. defined by each GRASS command.
  320. If run with a parent, it may Apply, Ok or Cancel; the latter two
  321. close the dialog. The former two trigger a callback.
  322. If run standalone, it will allow execution of the command.
  323. The command is checked and sent to the clipboard when clicking
  324. 'Copy'.
  325. """
  326. def __init__(self, parent, ID, task_description,
  327. get_dcmd = None, layer = None):
  328. self.get_dcmd = get_dcmd
  329. self.layer = layer
  330. self.task = task_description
  331. self.parent = parent # LayerTree | Modeler | None | ...
  332. if parent and parent.GetName() == 'Modeler':
  333. self.modeler = self.parent
  334. else:
  335. self.modeler = None
  336. # module name + keywords
  337. if self.task.name.split('.')[-1] in ('py', 'sh'):
  338. title = str(self.task.name.rsplit('.',1)[0])
  339. else:
  340. title = self.task.name
  341. try:
  342. if self.task.keywords != ['']:
  343. title += " [" + ', '.join(self.task.keywords) + "]"
  344. except ValueError:
  345. pass
  346. wx.Frame.__init__(self, parent = parent, id = ID, title = title,
  347. pos = wx.DefaultPosition, style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
  348. name = "MainFrame")
  349. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  350. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  351. # statusbar
  352. self.CreateStatusBar()
  353. # icon
  354. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  355. guisizer = wx.BoxSizer(wx.VERTICAL)
  356. # set apropriate output window
  357. if self.parent:
  358. self.standalone = False
  359. else:
  360. self.standalone = True
  361. # logo + description
  362. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  363. # GRASS logo
  364. self.logo = wx.StaticBitmap(parent = self.panel,
  365. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  366. 'grass_form.png'),
  367. type = wx.BITMAP_TYPE_PNG))
  368. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  369. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  370. # add module description
  371. if self.task.label:
  372. module_desc = self.task.label + ' ' + self.task.description
  373. else:
  374. module_desc = self.task.description
  375. self.description = gdialogs.StaticWrapText(parent = self.panel,
  376. label = module_desc)
  377. topsizer.Add(item = self.description, proportion = 1, border = 5,
  378. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  379. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  380. self.panel.SetSizerAndFit(guisizer)
  381. self.Layout()
  382. # notebooks
  383. self.notebookpanel = cmdPanel(parent = self.panel, task = self.task,
  384. mainFrame = self)
  385. self.goutput = self.notebookpanel.goutput
  386. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  387. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  388. # status bar
  389. status_text = _("Enter parameters for '") + self.task.name + "'"
  390. try:
  391. self.task.get_cmd()
  392. self.updateValuesHook()
  393. except ValueError:
  394. self.SetStatusText(status_text)
  395. # buttons
  396. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  397. # cancel
  398. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  399. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  400. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  401. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  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. # copy
  420. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY, label = _("C&opy"))
  421. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  422. btnsizer.Add(item = self.btn_run, proportion = 0,
  423. flag = wx.ALL | wx.ALIGN_CENTER,
  424. border = 10)
  425. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  426. flag = wx.ALL | wx.ALIGN_CENTER,
  427. border = 10)
  428. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  429. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  430. # help
  431. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  432. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  433. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  434. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  435. self.btn_help.Hide()
  436. # add help button
  437. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  438. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  439. border = 30)
  440. if self.parent and not self.modeler:
  441. addLayer = False
  442. for p in self.task.params:
  443. if p.get('age', 'old') == 'new' and \
  444. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  445. addLayer = True
  446. if addLayer:
  447. # add newly created map into layer tree
  448. self.addbox = wx.CheckBox(parent = self.panel,
  449. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  450. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  451. guisizer.Add(item = self.addbox, proportion = 0,
  452. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  453. border = 5)
  454. hasNew = False
  455. for p in self.task.params:
  456. if p.get('age', 'old') == 'new':
  457. hasNew = True
  458. break
  459. if self.get_dcmd is None and hasNew:
  460. # close dialog when command is terminated
  461. self.closebox = wx.CheckBox(parent = self.panel,
  462. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  463. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  464. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  465. "Change this settings in Preferences dialog ('Command' tab)."))
  466. guisizer.Add(item = self.closebox, proportion = 0,
  467. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  468. border = 5)
  469. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  470. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  471. # do layout
  472. # called automatically by SetSizer()
  473. self.panel.SetAutoLayout(True)
  474. self.panel.SetSizerAndFit(guisizer)
  475. sizeFrame = self.GetBestSize()
  476. self.SetMinSize(sizeFrame)
  477. if hasattr(self, "closebox"):
  478. scale = 0.33
  479. else:
  480. scale = 0.50
  481. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  482. self.notebookpanel.constrained_size[1])))
  483. # thread to update dialog
  484. # create queues
  485. self.requestQ = Queue.Queue()
  486. self.resultQ = Queue.Queue()
  487. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  488. self.Layout()
  489. # keep initial window size limited for small screens
  490. width, height = self.GetSizeTuple()
  491. self.SetSize(wx.Size(min(width, 650),
  492. min(height, 500)))
  493. # fix goutput's pane size (required for Mac OSX)
  494. if self.goutput:
  495. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  496. def updateValuesHook(self, event = None):
  497. """!Update status bar data"""
  498. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  499. if event:
  500. event.Skip()
  501. def OnKeyUp(self, event):
  502. """!Key released (check hot-keys)"""
  503. try:
  504. kc = chr(event.GetKeyCode())
  505. except ValueError:
  506. event.Skip()
  507. return
  508. if not event.ControlDown():
  509. event.Skip()
  510. return
  511. if kc == 'Q':
  512. self.OnCancel(None)
  513. elif kc == 'S':
  514. self.OnAbort(None)
  515. elif kc == 'H':
  516. self.OnHelp(None)
  517. elif kc == 'R':
  518. self.OnRun(None)
  519. elif kc == 'C':
  520. self.OnCopy(None)
  521. event.Skip()
  522. def OnDone(self, cmd, returncode):
  523. """!This function is launched from OnRun() when command is
  524. finished
  525. @param returncode command's return code (0 for success)
  526. """
  527. if not self.parent or returncode != 0:
  528. return
  529. if self.parent.GetName() not in ('LayerTree', 'LayerManager'):
  530. return
  531. if self.parent.GetName() == 'LayerTree':
  532. display = self.parent.GetMapDisplay()
  533. else: # Layer Manager
  534. display = self.parent.GetLayerTree().GetMapDisplay()
  535. if not display or not display.IsAutoRendered():
  536. return
  537. mapLayers = map(lambda x: x.GetName(),
  538. display.GetMap().GetListOfLayers(l_type = 'raster') +
  539. display.GetMap().GetListOfLayers(l_type = 'vector'))
  540. task = GUI(show = None).ParseCommand(cmd)
  541. for p in task.get_options()['params']:
  542. if p.get('prompt', '') not in ('raster', 'vector'):
  543. continue
  544. mapName = p.get('value', '')
  545. if '@' not in mapName:
  546. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  547. if mapName in mapLayers:
  548. display.GetWindow().UpdateMap(render = True)
  549. return
  550. def OnOK(self, event):
  551. """!OK button pressed"""
  552. cmd = self.OnApply(event)
  553. if cmd is not None and self.get_dcmd is not None:
  554. self.OnCancel(event)
  555. def OnApply(self, event):
  556. """!Apply the command"""
  557. if self.modeler:
  558. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  559. else:
  560. cmd = self.createCmd()
  561. if cmd is not None and self.get_dcmd is not None:
  562. # return d.* command to layer tree for rendering
  563. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  564. "flags" : self.task.flags},
  565. self)
  566. # echo d.* command to output console
  567. # self.parent.writeDCommand(cmd)
  568. return cmd
  569. def OnRun(self, event):
  570. """!Run the command"""
  571. cmd = self.createCmd()
  572. if not cmd or len(cmd) < 1:
  573. return
  574. ret = 0
  575. if self.standalone or cmd[0][0:2] != "d.":
  576. # Send any non-display command to parent window (probably wxgui.py)
  577. # put to parents switch to 'Command output'
  578. self.notebookpanel.notebook.SetSelectionByName('output')
  579. try:
  580. if self.task.path:
  581. cmd[0] = self.task.path # full path
  582. ret = self.goutput.RunCmd(cmd, onDone = self.OnDone)
  583. except AttributeError, e:
  584. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  585. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  586. else:
  587. gcmd.Command(cmd)
  588. if ret != 0:
  589. self.notebookpanel.notebook.SetSelection(0)
  590. return
  591. # update buttons status
  592. for btn in (self.btn_run,
  593. self.btn_cancel,
  594. self.btn_clipboard,
  595. self.btn_help):
  596. btn.Enable(False)
  597. def OnAbort(self, event):
  598. """!Abort running command"""
  599. event = goutput.wxCmdAbort(aborted = True)
  600. wx.PostEvent(self.goutput, event)
  601. def OnCopy(self, event):
  602. """!Copy the command"""
  603. cmddata = wx.TextDataObject()
  604. # list -> string
  605. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  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. if self.get_dcmd and \
  617. self.parent and \
  618. self.parent.GetName() in ('LayerTree',
  619. 'MapWindow'):
  620. # display decorations and
  621. # pressing OK or cancel after setting layer properties
  622. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  623. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  624. self.Hide()
  625. # canceled layer with nothing set
  626. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  627. self.parent.Delete(self.layer)
  628. self.Destroy()
  629. else:
  630. # cancel for non-display commands
  631. self.Destroy()
  632. def OnHelp(self, event):
  633. """!Show manual page (switch to the 'Manual' notebook page)"""
  634. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  635. self.notebookpanel.notebook.SetSelectionByName('manual')
  636. self.notebookpanel.OnPageChange(None)
  637. if event:
  638. event.Skip()
  639. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  640. """!Create command string (python list)"""
  641. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  642. ignoreRequired = ignoreRequired)
  643. class cmdPanel(wx.Panel):
  644. """!A panel containing a notebook dividing in tabs the different
  645. guisections of the GRASS cmd.
  646. """
  647. def __init__(self, parent, task, id = wx.ID_ANY, mainFrame = None, *args, **kwargs):
  648. if mainFrame:
  649. self.parent = mainFrame
  650. else:
  651. self.parent = parent
  652. self.task = task
  653. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  654. # Determine tab layout
  655. sections = []
  656. is_section = {}
  657. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  658. self.label_id = [] # wrap titles on resize
  659. self.Bind(wx.EVT_SIZE, self.OnSize)
  660. for task in not_hidden:
  661. if task.get('required', False):
  662. # All required go into Main, even if they had defined another guisection
  663. task['guisection'] = _('Required')
  664. if task.get('guisection','') == '':
  665. # Undefined guisections end up into Options
  666. task['guisection'] = _('Optional')
  667. if task['guisection'] not in is_section:
  668. # We do it like this to keep the original order, except for Main which goes first
  669. is_section[task['guisection']] = 1
  670. sections.append(task['guisection'])
  671. else:
  672. is_section[ task['guisection'] ] += 1
  673. del is_section
  674. # 'Required' tab goes first, 'Optional' as the last one
  675. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  676. if content in sections:
  677. idx = sections.index(content)
  678. sections[idx:idx+1] = []
  679. sections[newidx:newidx] = [content]
  680. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  681. # Build notebook
  682. self.notebook = GNotebook(self, style = globalvar.FNPageStyle)
  683. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  684. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  685. tab = {}
  686. tabsizer = {}
  687. for section in sections:
  688. tab[section] = scrolled.ScrolledPanel(parent = self.notebook)
  689. tab[section].SetScrollRate(10, 10)
  690. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  691. self.notebook.AddPage(page = tab[section], text = section)
  692. # are we running from command line?
  693. ### add 'command output' tab regardless standalone dialog
  694. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  695. self.goutput = goutput.GMConsole(parent = self, margin = False)
  696. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  697. else:
  698. self.goutput = None
  699. self.manual_tab = HelpPanel(parent = self, grass_command = self.task.name)
  700. if not self.manual_tab.IsFile():
  701. self.manual_tab.Hide()
  702. else:
  703. self.notebook.AddPage(page = self.manual_tab, text = _("Manual"), name = 'manual')
  704. self.notebook.SetSelection(0)
  705. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  706. #
  707. # flags
  708. #
  709. text_style = wx.FONTWEIGHT_NORMAL
  710. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  711. for f in visible_flags:
  712. which_sizer = tabsizer[ f['guisection'] ]
  713. which_panel = tab[ f['guisection'] ]
  714. # if label is given: description -> tooltip
  715. if f.get('label','') != '':
  716. title = text_beautify(f['label'])
  717. tooltip = text_beautify(f['description'], width = -1)
  718. else:
  719. title = text_beautify(f['description'])
  720. tooltip = None
  721. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  722. rtitle_txt = wx.StaticText(parent = which_panel,
  723. label = '(' + f['name'] + ')')
  724. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  725. self.label_id.append(chk.GetId())
  726. if tooltip:
  727. chk.SetToolTipString(tooltip)
  728. chk.SetValue(f.get('value', False))
  729. title_sizer.Add(item = chk, proportion = 1,
  730. flag = wx.EXPAND)
  731. title_sizer.Add(item = rtitle_txt, proportion = 0,
  732. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  733. which_sizer.Add(item = title_sizer, proportion = 0,
  734. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  735. f['wxId'] = [ chk.GetId(), ]
  736. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  737. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  738. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  739. label = _("Parameterized in model"))
  740. parChk.SetName('ModelParam')
  741. parChk.SetValue(f.get('parameterized', False))
  742. if 'wxId' in f:
  743. f['wxId'].append(parChk.GetId())
  744. else:
  745. f['wxId'] = [ parChk.GetId() ]
  746. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  747. which_sizer.Add(item = parChk, proportion = 0,
  748. flag = wx.LEFT, border = 20)
  749. if f['name'] in ('verbose', 'quiet'):
  750. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  751. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  752. if f['name'] == vq:
  753. chk.SetValue(True)
  754. f['value'] = True
  755. elif f['name'] == 'overwrite' and 'value' not in f:
  756. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  757. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  758. #
  759. # parameters
  760. #
  761. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  762. try:
  763. first_param = visible_params[0]
  764. except IndexError:
  765. first_param = None
  766. for p in visible_params:
  767. which_sizer = tabsizer[ p['guisection'] ]
  768. which_panel = tab[ p['guisection'] ]
  769. # if label is given -> label and description -> tooltip
  770. # otherwise description -> lavel
  771. if p.get('label','') != '':
  772. title = text_beautify(p['label'])
  773. tooltip = text_beautify(p['description'], width = -1)
  774. else:
  775. title = text_beautify(p['description'])
  776. tooltip = None
  777. txt = None
  778. # text style (required -> bold)
  779. if not p.get('required', False):
  780. text_style = wx.FONTWEIGHT_NORMAL
  781. else:
  782. text_style = wx.FONTWEIGHT_BOLD
  783. # title sizer (description, name, type)
  784. if (len(p.get('values', [])) > 0) and \
  785. p.get('multiple', False) and \
  786. p.get('gisprompt',False) == False and \
  787. p.get('type', '') == 'string':
  788. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  789. else:
  790. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  791. title_txt = wx.StaticText(parent = which_panel)
  792. if p['key_desc']:
  793. ltype = ','.join(p['key_desc'])
  794. else:
  795. ltype = p['type']
  796. rtitle_txt = wx.StaticText(parent = which_panel,
  797. label = '(' + p['name'] + '=' + ltype + ')')
  798. title_sizer.Add(item = title_txt, proportion = 1,
  799. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  800. title_sizer.Add(item = rtitle_txt, proportion = 0,
  801. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  802. which_sizer.Add(item = title_sizer, proportion = 0,
  803. flag = wx.EXPAND)
  804. self.label_id.append(title_txt.GetId())
  805. # title expansion
  806. if p.get('multiple', False) and len(p.get('values','')) == 0:
  807. title = _("[multiple]") + " " + title
  808. if p.get('value','') == '' :
  809. p['value'] = p.get('default','')
  810. if (len(p.get('values', [])) > 0):
  811. valuelist = map(str, p.get('values',[]))
  812. valuelist_desc = map(unicode, p.get('values_desc',[]))
  813. if p.get('multiple', False) and \
  814. p.get('gisprompt',False) == False and \
  815. p.get('type', '') == 'string':
  816. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  817. if valuelist_desc:
  818. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  819. else:
  820. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  821. isEnabled = {}
  822. # copy default values
  823. if p['value'] == '':
  824. p['value'] = p.get('default', '')
  825. for defval in p.get('value', '').split(','):
  826. isEnabled[ defval ] = 'yes'
  827. # for multi checkboxes, this is an array of all wx IDs
  828. # for each individual checkbox
  829. p[ 'wxId' ] = list()
  830. idx = 0
  831. for val in valuelist:
  832. try:
  833. label = valuelist_desc[idx]
  834. except IndexError:
  835. label = val
  836. chkbox = wx.CheckBox(parent = which_panel,
  837. label = text_beautify(label))
  838. p[ 'wxId' ].append(chkbox.GetId())
  839. if val in isEnabled:
  840. chkbox.SetValue(True)
  841. hSizer.Add(item = chkbox, proportion = 0,
  842. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  843. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  844. idx += 1
  845. which_sizer.Add(item = hSizer, proportion = 0,
  846. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  847. elif p.get('gisprompt', False) == False:
  848. if len(valuelist) == 1: # -> textctrl
  849. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  850. str(valuelist[0])))
  851. if p.get('type', '') == 'integer' and \
  852. not p.get('multiple', False):
  853. # for multiple integers use textctrl instead of spinsctrl
  854. try:
  855. minValue, maxValue = map(int, valuelist[0].split('-'))
  856. except ValueError:
  857. minValue = -1e6
  858. maxValue = 1e6
  859. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  860. min = minValue, max = maxValue)
  861. txt2.SetName("SpinCtrl")
  862. style = wx.BOTTOM | wx.LEFT
  863. else:
  864. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  865. txt2.SetName("TextCtrl")
  866. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  867. value = self._getValue(p)
  868. # parameter previously set
  869. if value:
  870. if txt2.GetName() == "SpinCtrl":
  871. txt2.SetValue(int(value))
  872. else:
  873. txt2.SetValue(value)
  874. which_sizer.Add(item = txt2, proportion = 0,
  875. flag = style, border = 5)
  876. p['wxId'] = [ txt2.GetId(), ]
  877. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  878. else:
  879. # list of values (combo)
  880. title_txt.SetLabel(title + ':')
  881. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  882. size = globalvar.DIALOG_COMBOBOX_SIZE,
  883. choices = valuelist, style = wx.CB_DROPDOWN)
  884. value = self._getValue(p)
  885. if value:
  886. cb.SetValue(value) # parameter previously set
  887. which_sizer.Add(item = cb, proportion = 0,
  888. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  889. p['wxId'] = [cb.GetId(),]
  890. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  891. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  892. # text entry
  893. if (p.get('type','string') in ('string','integer','float')
  894. and len(p.get('values',[])) == 0
  895. and p.get('gisprompt',False) == False
  896. and p.get('prompt','') != 'color'):
  897. title_txt.SetLabel(title + ':')
  898. if p.get('multiple', False) or \
  899. p.get('type', 'string') == 'string' or \
  900. len(p.get('key_desc', [])) > 1:
  901. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  902. value = self._getValue(p)
  903. if value:
  904. # parameter previously set
  905. txt3.SetValue(str(value))
  906. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  907. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  908. else:
  909. minValue = -1e9
  910. maxValue = 1e9
  911. if p.get('type', '') == 'integer':
  912. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  913. size = globalvar.DIALOG_SPIN_SIZE,
  914. min = minValue, max = maxValue)
  915. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  916. value = self._getValue(p)
  917. if value:
  918. txt3.SetValue(int(value)) # parameter previously set
  919. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  920. else:
  921. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  922. validator = FloatValidator())
  923. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  924. value = self._getValue(p)
  925. if value:
  926. txt3.SetValue(str(value)) # parameter previously set
  927. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  928. which_sizer.Add(item = txt3, proportion = 0,
  929. flag = style, border = 5)
  930. p['wxId'] = [ txt3.GetId(), ]
  931. #
  932. # element selection tree combobox (maps, icons, regions, etc.)
  933. #
  934. if p.get('gisprompt', False) == True:
  935. title_txt.SetLabel(title + ':')
  936. # GIS element entry
  937. if p.get('prompt','') not in ('color',
  938. 'color_none',
  939. 'subgroup',
  940. 'dbdriver',
  941. 'dbname',
  942. 'dbtable',
  943. 'dbcolumn',
  944. 'layer',
  945. 'layer_all',
  946. 'location',
  947. 'mapset',
  948. 'dbase') and \
  949. p.get('element', '') not in ('file', 'dir'):
  950. multiple = p.get('multiple', False)
  951. if p.get('age', '') == 'new':
  952. mapsets = [grass.gisenv()['MAPSET'],]
  953. else:
  954. mapsets = None
  955. if self.task.name in ('r.proj', 'v.proj') \
  956. and p.get('name', '') == 'input':
  957. if self.task.name == 'r.proj':
  958. isRaster = True
  959. else:
  960. isRaster = False
  961. selection = gselect.ProjSelect(parent = which_panel,
  962. isRaster = isRaster)
  963. p['wxId'] = [ selection.GetId(), ]
  964. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  965. formatSelector = False
  966. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  967. else:
  968. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  969. size = globalvar.DIALOG_GSELECT_SIZE,
  970. type = p.get('element', ''),
  971. multiple = multiple, mapsets = mapsets,
  972. fullyQualified = p.get('age', 'old') == 'old')
  973. value = self._getValue(p)
  974. if value:
  975. selection.SetValue(value)
  976. formatSelector = True
  977. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  978. # we target the textctl here
  979. textWin = selection.GetTextCtrl()
  980. p['wxId'] = [ textWin.GetId(), ]
  981. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  982. if p.get('prompt', '') == 'vector':
  983. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  984. # if formatSelector and p.get('age', 'old') == 'old':
  985. # # OGR supported (read-only)
  986. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  987. # self.hsizer.Add(item = selection,
  988. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  989. # border = 5)
  990. # # format (native / ogr)
  991. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  992. # label = " %s " % _("Format"),
  993. # style = wx.RA_SPECIFY_ROWS,
  994. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  995. # if p.get('value', '').lower().rfind('@ogr') > -1:
  996. # rbox.SetSelection(1)
  997. # rbox.SetName('VectorFormat')
  998. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  999. # self.hsizer.Add(item = rbox,
  1000. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1001. # wx.RIGHT | wx.ALIGN_TOP,
  1002. # border = 5)
  1003. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1004. # default = 'dir',
  1005. # exclude = ['file'])
  1006. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1007. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1008. # ogrSelection.SetName('OgrSelect')
  1009. # ogrSelection.Hide()
  1010. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1011. # p['wxId'].append(rbox.GetId())
  1012. # p['wxId'].append(ogrSelection.GetId())
  1013. # for win in ogrSelection.GetDsnWin():
  1014. # p['wxId'].append(win.GetId())
  1015. # else:
  1016. which_sizer.Add(item = selection, proportion = 0,
  1017. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1018. border = 5)
  1019. elif p.get('prompt', '') == 'group':
  1020. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1021. which_sizer.Add(item = selection, proportion = 0,
  1022. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1023. border = 5)
  1024. else:
  1025. which_sizer.Add(item = selection, proportion = 0,
  1026. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1027. border = 5)
  1028. # subgroup
  1029. elif p.get('prompt', '') == 'subgroup':
  1030. selection = gselect.SubGroupSelect(parent = which_panel)
  1031. p['wxId'] = [ selection.GetId() ]
  1032. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1033. which_sizer.Add(item = selection, proportion = 0,
  1034. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1035. border = 5)
  1036. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1037. elif p.get('prompt', '') in ('dbdriver',
  1038. 'dbname',
  1039. 'dbtable',
  1040. 'dbcolumn',
  1041. 'layer',
  1042. 'layer_all',
  1043. 'location',
  1044. 'mapset',
  1045. 'dbase'):
  1046. if p.get('multiple', 'no') == 'yes':
  1047. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1048. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1049. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1050. else:
  1051. value = self._getValue(p)
  1052. if p.get('prompt', '') in ('layer',
  1053. 'layer_all'):
  1054. if p.get('prompt', '') == 'layer_all':
  1055. all = True
  1056. else:
  1057. all = False
  1058. if p.get('age', 'old') == 'old':
  1059. win = gselect.LayerSelect(parent = which_panel,
  1060. all = all,
  1061. default = p['default'])
  1062. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1063. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1064. win.SetValue(str(value)) # default or previously set value
  1065. else:
  1066. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1067. min = 1, max = 100, initial = int(p['default']))
  1068. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1069. win.SetValue(int(value)) # default or previously set value
  1070. p['wxId'] = [ win.GetId() ]
  1071. elif p.get('prompt', '') == 'dbdriver':
  1072. win = gselect.DriverSelect(parent = which_panel,
  1073. choices = p.get('values', []),
  1074. value = value)
  1075. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1076. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1077. elif p.get('prompt', '') == 'dbname':
  1078. win = gselect.DatabaseSelect(parent = which_panel,
  1079. value = value)
  1080. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1081. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1082. elif p.get('prompt', '') == 'dbtable':
  1083. if p.get('age', 'old') == 'old':
  1084. win = gselect.TableSelect(parent = which_panel)
  1085. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1086. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1087. else:
  1088. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1089. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1090. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1091. elif p.get('prompt', '') == 'dbcolumn':
  1092. win = gselect.ColumnSelect(parent = which_panel,
  1093. value = value,
  1094. param = p)
  1095. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1096. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1097. elif p.get('prompt', '') == 'location':
  1098. win = gselect.LocationSelect(parent = which_panel,
  1099. value = value)
  1100. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1101. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1102. elif p.get('prompt', '') == 'mapset':
  1103. if p.get('age', 'old') == 'old':
  1104. new = False
  1105. else:
  1106. new = True
  1107. win = gselect.MapsetSelect(parent = which_panel,
  1108. value = value, new = new)
  1109. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1110. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1111. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1112. elif p.get('prompt', '') == 'dbase':
  1113. win = gselect.DbaseSelect(parent = which_panel,
  1114. changeCallback = self.OnSetValue)
  1115. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1116. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1117. if 'wxId' not in p:
  1118. try:
  1119. p['wxId'] = [ win.GetId(), ]
  1120. except AttributeError:
  1121. pass
  1122. which_sizer.Add(item = win, proportion = 0,
  1123. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1124. # color entry
  1125. elif p.get('prompt', '') in ('color',
  1126. 'color_none'):
  1127. default_color = (200,200,200)
  1128. label_color = _("Select Color")
  1129. if p.get('default','') != '':
  1130. default_color, label_color = color_resolve(p['default'])
  1131. if p.get('value','') != '': # parameter previously set
  1132. default_color, label_color = color_resolve(p['value'])
  1133. if p.get('prompt', '') == 'color_none':
  1134. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1135. else:
  1136. this_sizer = which_sizer
  1137. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1138. label = label_color, colour = default_color,
  1139. pos = wx.DefaultPosition, size = (150,-1))
  1140. this_sizer.Add(item = btn_colour, proportion = 0,
  1141. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1142. # For color selectors, this is a two-member array, holding the IDs of
  1143. # the selector proper and either a "transparent" button or None
  1144. p['wxId'] = [btn_colour.GetId(),]
  1145. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1146. if p.get('prompt', '') == 'color_none':
  1147. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1148. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1149. none_check.SetValue(True)
  1150. else:
  1151. none_check.SetValue(False)
  1152. this_sizer.Add(item = none_check, proportion = 0,
  1153. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1154. which_sizer.Add(this_sizer)
  1155. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1156. p['wxId'].append(none_check.GetId())
  1157. else:
  1158. p['wxId'].append(None)
  1159. # file selector
  1160. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1161. if p.get('age', 'new') == 'new':
  1162. fmode = wx.SAVE
  1163. else:
  1164. fmode = wx.OPEN
  1165. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1166. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1167. dialogTitle = _('Choose %s') % \
  1168. p.get('description',_('File')),
  1169. buttonText = _('Browse'),
  1170. startDirectory = os.getcwd(), fileMode = fmode,
  1171. changeCallback = self.OnSetValue)
  1172. value = self._getValue(p)
  1173. if value:
  1174. fbb.SetValue(value) # parameter previously set
  1175. which_sizer.Add(item = fbb, proportion = 0,
  1176. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1177. # A file browse button is a combobox with two children:
  1178. # a textctl and a button;
  1179. # we have to target the button here
  1180. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1181. if p.get('age', 'new') == 'old' and \
  1182. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1183. # widget for interactive input
  1184. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1185. style = wx.TE_MULTILINE,
  1186. size = (-1, 75))
  1187. if p.get('value', '') and os.path.isfile(p['value']):
  1188. f = open(p['value'])
  1189. ifbb.SetValue(''.join(f.readlines()))
  1190. f.close()
  1191. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1192. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVE)
  1193. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1194. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1195. label = _('or enter values interactively')),
  1196. proportion = 0,
  1197. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1198. which_sizer.Add(item = ifbb, proportion = 1,
  1199. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1200. which_sizer.Add(item = btnSave, proportion = 0,
  1201. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1202. p['wxId'].append(ifbb.GetId())
  1203. p['wxId'].append(btnSave.GetId())
  1204. # directory selector
  1205. elif p.get('prompt','') != 'color' and p.get('element', '') == 'dir':
  1206. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1207. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1208. dialogTitle = _('Choose %s') % \
  1209. p.get('description', _('Directory')),
  1210. buttonText = _('Browse'),
  1211. startDirectory = os.getcwd(),
  1212. changeCallback = self.OnSetValue)
  1213. value = self._getValue(p)
  1214. if value:
  1215. fbb.SetValue(value) # parameter previously set
  1216. which_sizer.Add(item = fbb, proportion = 0,
  1217. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1218. # A file browse button is a combobox with two children:
  1219. # a textctl and a button;
  1220. # we have to target the button here
  1221. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1222. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1223. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1224. label = _("Parameterized in model"))
  1225. parChk.SetName('ModelParam')
  1226. parChk.SetValue(p.get('parameterized', False))
  1227. if 'wxId' in p:
  1228. p['wxId'].append(parChk.GetId())
  1229. else:
  1230. p['wxId'] = [ parChk.GetId() ]
  1231. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1232. which_sizer.Add(item = parChk, proportion = 0,
  1233. flag = wx.LEFT, border = 20)
  1234. if title_txt is not None:
  1235. # create tooltip if given
  1236. if len(p['values_desc']) > 0:
  1237. if tooltip:
  1238. tooltip += 2 * os.linesep
  1239. else:
  1240. tooltip = ''
  1241. if len(p['values']) == len(p['values_desc']):
  1242. for i in range(len(p['values'])):
  1243. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1244. tooltip.strip(os.linesep)
  1245. if tooltip:
  1246. title_txt.SetToolTipString(tooltip)
  1247. if p == first_param:
  1248. if 'wxId' in p and len(p['wxId']) > 0:
  1249. win = self.FindWindowById(p['wxId'][0])
  1250. win.SetFocus()
  1251. #
  1252. # set widget relations for OnUpdateSelection
  1253. #
  1254. pMap = None
  1255. pLayer = []
  1256. pDriver = None
  1257. pDatabase = None
  1258. pTable = None
  1259. pColumn = []
  1260. pGroup = None
  1261. pSubGroup = None
  1262. pDbase = None
  1263. pLocation = None
  1264. pMapset = None
  1265. for p in self.task.params:
  1266. if p.get('gisprompt', False) == False:
  1267. continue
  1268. guidep = p.get('guidependency', '')
  1269. if guidep:
  1270. # fixed options dependency defined
  1271. options = guidep.split(',')
  1272. for opt in options:
  1273. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1274. if id:
  1275. if 'wxId-bind' not in p:
  1276. p['wxId-bind'] = list()
  1277. p['wxId-bind'] += pOpt['wxId']
  1278. continue
  1279. prompt = p.get('element', '')
  1280. if prompt in ('cell', 'vector'):
  1281. name = p.get('name', '')
  1282. if name in ('map', 'input'):
  1283. pMap = p
  1284. elif prompt == 'layer':
  1285. pLayer.append(p)
  1286. elif prompt == 'dbcolumn':
  1287. pColumn.append(p)
  1288. elif prompt == 'dbdriver':
  1289. pDriver = p
  1290. elif prompt == 'dbname':
  1291. pDatabase = p
  1292. elif prompt == 'dbtable':
  1293. pTable = p
  1294. elif prompt == 'group':
  1295. pGroup = p
  1296. elif prompt == 'subgroup':
  1297. pSubGroup = p
  1298. elif prompt == 'dbase':
  1299. pDbase = p
  1300. elif prompt == 'location':
  1301. pLocation = p
  1302. elif prompt == 'mapset':
  1303. pMapset = p
  1304. # collect ids
  1305. pColumnIds = []
  1306. for p in pColumn:
  1307. pColumnIds += p['wxId']
  1308. pLayerIds = []
  1309. for p in pLayer:
  1310. pLayerIds += p['wxId']
  1311. # set wxId-bindings
  1312. if pMap:
  1313. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1314. if pLayer:
  1315. pMap['wxId-bind'] += pLayerIds
  1316. if pLayer:
  1317. for p in pLayer:
  1318. p['wxId-bind'] = copy.copy(pColumnIds)
  1319. if pDriver and pTable:
  1320. pDriver['wxId-bind'] = pTable['wxId']
  1321. if pDatabase and pTable:
  1322. pDatabase['wxId-bind'] = pTable['wxId']
  1323. if pTable and pColumnIds:
  1324. pTable['wxId-bind'] = pColumnIds
  1325. if pGroup and pSubGroup:
  1326. pGroup['wxId-bind'] = pSubGroup['wxId']
  1327. if pDbase and pLocation:
  1328. pDbase['wxId-bind'] = pLocation['wxId']
  1329. if pLocation and pMapset:
  1330. pLocation['wxId-bind'] = pMapset['wxId']
  1331. if pLocation and pMapset and pMap:
  1332. pLocation['wxId-bind'] += pMap['wxId']
  1333. pMapset['wxId-bind'] = pMap['wxId']
  1334. #
  1335. # determine panel size
  1336. #
  1337. maxsizes = (0, 0)
  1338. for section in sections:
  1339. tab[section].SetSizer(tabsizer[section])
  1340. tabsizer[section].Fit(tab[section])
  1341. tab[section].Layout()
  1342. minsecsizes = tabsizer[section].GetSize()
  1343. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1344. # TODO: be less arbitrary with these 600
  1345. self.panelMinHeight = 100
  1346. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1347. for section in sections:
  1348. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1349. if self.manual_tab.IsLoaded():
  1350. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1351. self.SetSizer(panelsizer)
  1352. panelsizer.Fit(self.notebook)
  1353. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1354. def _getValue(self, p):
  1355. """!Get value or default value of given parameter
  1356. @param p parameter directory
  1357. """
  1358. if p.get('value', '') != '':
  1359. return p['value']
  1360. return p.get('default', '')
  1361. def OnFileSave(self, event):
  1362. """!Save interactive input to the file"""
  1363. wId = event.GetId()
  1364. win = {}
  1365. for p in self.task.params:
  1366. if wId in p.get('wxId', []):
  1367. win['file'] = self.FindWindowById(p['wxId'][0])
  1368. win['text'] = self.FindWindowById(p['wxId'][1])
  1369. break
  1370. if not win:
  1371. return
  1372. text = win['text'].GetValue()
  1373. if not text:
  1374. gcmd.GMessage(parent = self,
  1375. message = _("Nothing to save."))
  1376. return
  1377. dlg = wx.FileDialog(parent = self,
  1378. message = _("Save input as..."),
  1379. defaultDir = os.getcwd(),
  1380. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1381. if dlg.ShowModal() == wx.ID_OK:
  1382. path = dlg.GetPath()
  1383. f = open(path, "w")
  1384. try:
  1385. f.write(text + os.linesep)
  1386. finally:
  1387. f.close()
  1388. win['file'].SetValue(path)
  1389. dlg.Destroy()
  1390. def OnFileText(self, event):
  1391. """File input interactively entered"""
  1392. text = event.GetString()
  1393. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1394. if not p:
  1395. return # should not happen
  1396. win = self.FindWindowById(p['wxId'][0])
  1397. if text:
  1398. filename = win.GetValue()
  1399. if not filename:
  1400. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1401. filename = grass.tempfile()
  1402. win.SetValue(filename)
  1403. f = open(filename, "w")
  1404. try:
  1405. f.write(text)
  1406. finally:
  1407. f.close()
  1408. else:
  1409. win.SetValue('')
  1410. def OnVectorFormat(self, event):
  1411. """!Change vector format (native / ogr)"""
  1412. sel = event.GetSelection()
  1413. idEvent = event.GetId()
  1414. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1415. if not p:
  1416. return # should not happen
  1417. # detect windows
  1418. winNative = None
  1419. winOgr = None
  1420. for id in p['wxId']:
  1421. if id == idEvent:
  1422. continue
  1423. name = self.FindWindowById(id).GetName()
  1424. if name == 'Select':
  1425. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1426. elif name == 'OgrSelect':
  1427. winOgr = self.FindWindowById(id)
  1428. # enable / disable widgets & update values
  1429. rbox = self.FindWindowByName('VectorFormat')
  1430. self.hsizer.Remove(rbox)
  1431. if sel == 0: # -> native
  1432. winOgr.Hide()
  1433. self.hsizer.Remove(winOgr)
  1434. self.hsizer.Add(item = winNative,
  1435. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1436. border = 5)
  1437. winNative.Show()
  1438. p['value'] = winNative.GetValue()
  1439. elif sel == 1: # -> OGR
  1440. sizer = wx.BoxSizer(wx.VERTICAL)
  1441. winNative.Hide()
  1442. self.hsizer.Remove(winNative)
  1443. sizer.Add(item = winOgr)
  1444. winOgr.Show()
  1445. p['value'] = winOgr.GetDsn()
  1446. self.hsizer.Add(item = sizer,
  1447. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1448. border = 5)
  1449. self.hsizer.Add(item = rbox,
  1450. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1451. wx.RIGHT | wx.ALIGN_TOP,
  1452. border = 5)
  1453. self.hsizer.Layout()
  1454. self.Layout()
  1455. self.OnUpdateValues()
  1456. self.OnUpdateSelection(event)
  1457. def OnUpdateDialog(self, event):
  1458. for fn, kwargs in event.data.iteritems():
  1459. fn(**kwargs)
  1460. self.parent.updateValuesHook()
  1461. def OnVerbosity(self, event):
  1462. """!Verbosity level changed"""
  1463. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1464. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1465. if event.IsChecked():
  1466. if event.GetId() == verbose.GetId():
  1467. if quiet.IsChecked():
  1468. quiet.SetValue(False)
  1469. self.task.get_flag('quiet')['value'] = False
  1470. else:
  1471. if verbose.IsChecked():
  1472. verbose.SetValue(False)
  1473. self.task.get_flag('verbose')['value'] = False
  1474. event.Skip()
  1475. def OnPageChange(self, event):
  1476. if not event:
  1477. sel = self.notebook.GetSelection()
  1478. else:
  1479. sel = event.GetSelection()
  1480. idx = self.notebook.GetPageIndexByName('manual')
  1481. if idx > -1 and sel == idx:
  1482. # calling LoadPage() is strangely time-consuming (only first call)
  1483. # FIXME: move to helpPage.__init__()
  1484. if not self.manual_tab.IsLoaded():
  1485. wx.Yield()
  1486. self.manual_tab.LoadPage()
  1487. self.Layout()
  1488. def OnColorChange(self, event):
  1489. myId = event.GetId()
  1490. for p in self.task.params:
  1491. if 'wxId' in p and myId in p['wxId']:
  1492. has_button = p['wxId'][1] is not None
  1493. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1494. p[ 'value' ] = 'none'
  1495. else:
  1496. colorchooser = wx.FindWindowById(p['wxId'][0])
  1497. new_color = colorchooser.GetValue()[:]
  1498. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1499. # under wx2.8.1
  1500. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1501. colorchooser.SetLabel(new_label)
  1502. colorchooser.SetColour(new_color)
  1503. colorchooser.Refresh()
  1504. p[ 'value' ] = colorchooser.GetLabel()
  1505. self.OnUpdateValues()
  1506. def OnUpdateValues(self, event = None):
  1507. """!If we were part of a richer interface, report back the
  1508. current command being built.
  1509. This method should be set by the parent of this panel if
  1510. needed. It's a hook, actually. Beware of what is 'self' in
  1511. the method def, though. It will be called with no arguments.
  1512. """
  1513. pass
  1514. def OnCheckBoxMulti(self, event):
  1515. """!Fill the values as a ','-separated string according to
  1516. current status of the checkboxes.
  1517. """
  1518. me = event.GetId()
  1519. theParam = None
  1520. for p in self.task.params:
  1521. if 'wxId' in p and me in p['wxId']:
  1522. theParam = p
  1523. myIndex = p['wxId'].index(me)
  1524. # Unpack current value list
  1525. currentValues = {}
  1526. for isThere in theParam.get('value', '').split(','):
  1527. currentValues[isThere] = 1
  1528. theValue = theParam['values'][myIndex]
  1529. if event.Checked():
  1530. currentValues[ theValue ] = 1
  1531. else:
  1532. del currentValues[ theValue ]
  1533. # Keep the original order, so that some defaults may be recovered
  1534. currentValueList = []
  1535. for v in theParam['values']:
  1536. if v in currentValues:
  1537. currentValueList.append(v)
  1538. # Pack it back
  1539. theParam['value'] = ','.join(currentValueList)
  1540. self.OnUpdateValues()
  1541. def OnSetValue(self, event):
  1542. """!Retrieve the widget value and set the task value field
  1543. accordingly.
  1544. Use for widgets that have a proper GetValue() method, i.e. not
  1545. for selectors.
  1546. """
  1547. myId = event.GetId()
  1548. me = wx.FindWindowById(myId)
  1549. name = me.GetName()
  1550. found = False
  1551. for porf in self.task.params + self.task.flags:
  1552. if 'wxId' not in porf:
  1553. continue
  1554. if myId in porf['wxId']:
  1555. found = True
  1556. break
  1557. if not found:
  1558. return
  1559. if name == 'GdalSelect':
  1560. porf['value'] = event.dsn
  1561. elif name == 'ModelParam':
  1562. porf['parameterized'] = me.IsChecked()
  1563. else:
  1564. porf['value'] = me.GetValue()
  1565. self.OnUpdateValues(event)
  1566. event.Skip()
  1567. def OnUpdateSelection(self, event):
  1568. """!Update dialog (layers, tables, columns, etc.)
  1569. """
  1570. if not hasattr(self.parent, "updateThread"):
  1571. if event:
  1572. event.Skip()
  1573. return
  1574. if event:
  1575. self.parent.updateThread.Update(UpdateDialog,
  1576. self,
  1577. event,
  1578. event.GetId(),
  1579. self.task)
  1580. else:
  1581. self.parent.updateThread.Update(UpdateDialog,
  1582. self,
  1583. None,
  1584. None,
  1585. self.task)
  1586. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1587. """!Produce a command line string (list) or feeding into GRASS.
  1588. @param ignoreErrors True then it will return whatever has been
  1589. built so far, even though it would not be a correct command
  1590. for GRASS
  1591. """
  1592. try:
  1593. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1594. ignoreRequired = ignoreRequired)
  1595. except ValueError, err:
  1596. dlg = wx.MessageDialog(parent = self,
  1597. message = unicode(err),
  1598. caption = _("Error in %s") % self.task.name,
  1599. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1600. dlg.ShowModal()
  1601. dlg.Destroy()
  1602. cmd = None
  1603. return cmd
  1604. def OnSize(self, event):
  1605. width = event.GetSize()[0]
  1606. fontsize = self.GetFont().GetPointSize()
  1607. text_width = max(width / (fontsize - 3), 70)
  1608. for id in self.label_id:
  1609. win = self.FindWindowById(id)
  1610. label = win.GetLabel()
  1611. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1612. win.SetLabel(label_new)
  1613. event.Skip()
  1614. class GrassGUIApp(wx.App):
  1615. """!Stand-alone GRASS command GUI
  1616. """
  1617. def __init__(self, grass_task):
  1618. self.grass_task = grass_task
  1619. wx.App.__init__(self, False)
  1620. def OnInit(self):
  1621. msg = self.grass_task.get_error_msg()
  1622. if msg:
  1623. gcmd.GError(msg + '\n\nTry to set up GRASS_ADDON_PATH variable.')
  1624. return True
  1625. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1626. self.mf.CentreOnScreen()
  1627. self.mf.Show(True)
  1628. self.SetTopWindow(self.mf)
  1629. return True
  1630. class GUI:
  1631. def __init__(self, parent = None, show = True, modal = False,
  1632. centreOnParent = False, checkError = False):
  1633. """!Parses GRASS commands when module is imported and used from
  1634. Layer Manager.
  1635. """
  1636. self.parent = parent
  1637. self.show = show
  1638. self.modal = modal
  1639. self.centreOnParent = centreOnParent
  1640. self.checkError = checkError
  1641. self.grass_task = None
  1642. self.cmd = list()
  1643. global _blackList
  1644. if self.parent:
  1645. _blackList['enabled'] = True
  1646. else:
  1647. _blackList['enabled'] = False
  1648. def GetCmd(self):
  1649. """!Get validated command"""
  1650. return self.cmd
  1651. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1652. """!Parse command
  1653. Note: cmd is given as list
  1654. If command is given with options, return validated cmd list:
  1655. - add key name for first parameter if not given
  1656. - change mapname to mapname@mapset
  1657. """
  1658. start = time.time()
  1659. dcmd_params = {}
  1660. if completed == None:
  1661. get_dcmd = None
  1662. layer = None
  1663. dcmd_params = None
  1664. else:
  1665. get_dcmd = completed[0]
  1666. layer = completed[1]
  1667. if completed[2]:
  1668. dcmd_params.update(completed[2])
  1669. # parse the interface decription
  1670. try:
  1671. global _blackList
  1672. self.grass_task = gtask.parse_interface(cmd[0],
  1673. blackList = _blackList)
  1674. except ValueError, e: #grass.ScriptError, e:
  1675. gcmd.GError(e.value)
  1676. return
  1677. # if layer parameters previously set, re-insert them into dialog
  1678. if completed is not None:
  1679. if 'params' in dcmd_params:
  1680. self.grass_task.params = dcmd_params['params']
  1681. if 'flags' in dcmd_params:
  1682. self.grass_task.flags = dcmd_params['flags']
  1683. err = list()
  1684. # update parameters if needed && validate command
  1685. if len(cmd) > 1:
  1686. i = 0
  1687. cmd_validated = [cmd[0]]
  1688. for option in cmd[1:]:
  1689. if option[0] == '-': # flag
  1690. if option[1] == '-':
  1691. self.grass_task.set_flag(option[2:], True)
  1692. else:
  1693. self.grass_task.set_flag(option[1], True)
  1694. cmd_validated.append(option)
  1695. else: # parameter
  1696. try:
  1697. key, value = option.split('=', 1)
  1698. except:
  1699. if self.grass_task.firstParam:
  1700. if i == 0: # add key name of first parameter if not given
  1701. key = self.grass_task.firstParam
  1702. value = option
  1703. else:
  1704. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1705. else:
  1706. continue
  1707. element = self.grass_task.get_param(key, raiseError = False)
  1708. if not element:
  1709. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1710. { 'cmd' : cmd[0],
  1711. 'key' : key })
  1712. continue
  1713. element = element['element']
  1714. if element in ['cell', 'vector']:
  1715. # mapname -> mapname@mapset
  1716. try:
  1717. name, mapset = value.split('@')
  1718. except ValueError:
  1719. mapset = grass.find_file(value, element)['mapset']
  1720. curr_mapset = grass.gisenv()['MAPSET']
  1721. if mapset and mapset != curr_mapset:
  1722. value = value + '@' + mapset
  1723. self.grass_task.set_param(key, value)
  1724. cmd_validated.append(key + '=' + value)
  1725. i += 1
  1726. # update original command list
  1727. cmd = cmd_validated
  1728. if self.show is not None:
  1729. self.mf = mainFrame(parent = self.parent, ID = wx.ID_ANY,
  1730. task_description = self.grass_task,
  1731. get_dcmd = get_dcmd, layer = layer)
  1732. else:
  1733. self.mf = None
  1734. if get_dcmd is not None:
  1735. # update only propwin reference
  1736. get_dcmd(dcmd = None, layer = layer, params = None,
  1737. propwin = self.mf)
  1738. if self.show is not None:
  1739. self.mf.notebookpanel.OnUpdateSelection(None)
  1740. if self.show is True:
  1741. if self.parent and self.centreOnParent:
  1742. self.mf.CentreOnParent()
  1743. else:
  1744. self.mf.CenterOnScreen()
  1745. self.mf.Show(self.show)
  1746. self.mf.MakeModal(self.modal)
  1747. else:
  1748. self.mf.OnApply(None)
  1749. self.cmd = cmd
  1750. if self.checkError:
  1751. return self.grass_task, err
  1752. else:
  1753. return self.grass_task
  1754. def GetCommandInputMapParamKey(self, cmd):
  1755. """!Get parameter key for input raster/vector map
  1756. @param cmd module name
  1757. @return parameter key
  1758. @return None on failure
  1759. """
  1760. # parse the interface decription
  1761. if not self.grass_task:
  1762. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1763. self.grass_task = gtask.processTask(tree).get_task()
  1764. for p in self.grass_task.params:
  1765. if p.get('name', '') in ('input', 'map'):
  1766. age = p.get('age', '')
  1767. prompt = p.get('prompt', '')
  1768. element = p.get('element', '')
  1769. if age == 'old' and \
  1770. element in ('cell', 'grid3', 'vector') and \
  1771. prompt in ('raster', '3d-raster', 'vector'):
  1772. return p.get('name', None)
  1773. return None
  1774. class FloatValidator(wx.PyValidator):
  1775. """!Validator for floating-point input"""
  1776. def __init__(self):
  1777. wx.PyValidator.__init__(self)
  1778. self.Bind(wx.EVT_TEXT, self.OnText)
  1779. def Clone(self):
  1780. """!Clone validator"""
  1781. return FloatValidator()
  1782. def Validate(self):
  1783. """Validate input"""
  1784. textCtrl = self.GetWindow()
  1785. text = textCtrl.GetValue()
  1786. if text:
  1787. try:
  1788. float(text)
  1789. except ValueError:
  1790. textCtrl.SetBackgroundColour("grey")
  1791. textCtrl.SetFocus()
  1792. textCtrl.Refresh()
  1793. return False
  1794. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  1795. textCtrl.SetBackgroundColour(sysColor)
  1796. textCtrl.Refresh()
  1797. return True
  1798. def OnText(self, event):
  1799. """!Do validation"""
  1800. self.Validate()
  1801. event.Skip()
  1802. def TransferToWindow(self):
  1803. return True # Prevent wxDialog from complaining.
  1804. def TransferFromWindow(self):
  1805. return True # Prevent wxDialog from complaining.
  1806. class GNotebook(FN.FlatNotebook):
  1807. """!Generic notebook widget
  1808. """
  1809. def __init__(self, parent, style, **kwargs):
  1810. if globalvar.hasAgw:
  1811. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
  1812. else:
  1813. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  1814. self.notebookPages = {}
  1815. def AddPage(self, **kwargs):
  1816. """!Add a new page
  1817. """
  1818. if 'name' in kwargs:
  1819. self.notebookPages[kwargs['name']] = kwargs['page']
  1820. del kwargs['name']
  1821. super(GNotebook, self).AddPage(**kwargs)
  1822. def InsertPage(self, **kwargs):
  1823. """!Insert a new page
  1824. """
  1825. if 'name' in kwargs:
  1826. self.notebookPages[kwargs['name']] = kwargs['page']
  1827. del kwargs['name']
  1828. super(GNotebook, self).InsertPage(**kwargs)
  1829. def SetSelectionByName(self, page):
  1830. """!Set notebook
  1831. @param page names, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
  1832. """
  1833. idx = self.GetPageIndexByName(page)
  1834. if self.GetSelection() != idx:
  1835. self.SetSelection(idx)
  1836. def GetPageIndexByName(self, page):
  1837. """!Get notebook page index
  1838. @param page name
  1839. """
  1840. if page not in self.notebookPages:
  1841. return -1
  1842. return self.GetPageIndex(self.notebookPages[page])
  1843. if __name__ == "__main__":
  1844. import gettext
  1845. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1846. if len(sys.argv) == 1:
  1847. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1848. if sys.argv[1] != 'test':
  1849. q = wx.LogNull()
  1850. cmd = utils.split(sys.argv[1])
  1851. task = gtask.grassTask(cmd[0], blackList = _blackList)
  1852. task.set_options(cmd[1:])
  1853. app = GrassGUIApp(task)
  1854. app.MainLoop()
  1855. else: #Test
  1856. # Test grassTask from within a GRASS session
  1857. if os.getenv("GISBASE") is not None:
  1858. task = gtask.grassTask("d.vect")
  1859. task.get_param('map')['value'] = "map_name"
  1860. task.get_flag('v')['value'] = True
  1861. task.get_param('layer')['value'] = 1
  1862. task.get_param('bcolor')['value'] = "red"
  1863. assert ' '.join(task.get_cmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1864. # Test interface building with handmade grassTask,
  1865. # possibly outside of a GRASS session.
  1866. task = gtask.grassTask()
  1867. task.name = "TestTask"
  1868. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1869. task.keywords = ["grass","test","task"]
  1870. task.params = [
  1871. {
  1872. "name" : "text",
  1873. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1874. "label" : "Enter some text",
  1875. },{
  1876. "name" : "hidden_text",
  1877. "description" : "This text should not appear in the form",
  1878. "hidden" : True
  1879. },{
  1880. "name" : "text_default",
  1881. "description" : "Enter text to override the default",
  1882. "default" : "default text"
  1883. },{
  1884. "name" : "text_prefilled",
  1885. "description" : "You should see a friendly welcome message here",
  1886. "value" : "hello, world"
  1887. },{
  1888. "name" : "plain_color",
  1889. "description" : "This is a plain color, and it is a compulsory parameter",
  1890. "required" : False,
  1891. "gisprompt" : True,
  1892. "prompt" : "color"
  1893. },{
  1894. "name" : "transparent_color",
  1895. "description" : "This color becomes transparent when set to none",
  1896. "guisection" : "tab",
  1897. "gisprompt" : True,
  1898. "prompt" : "color"
  1899. },{
  1900. "name" : "multi",
  1901. "description" : "A multiple selection",
  1902. 'default': u'red,green,blue',
  1903. 'gisprompt': False,
  1904. 'guisection': 'tab',
  1905. 'multiple': u'yes',
  1906. 'type': u'string',
  1907. 'value': '',
  1908. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1909. },{
  1910. "name" : "single",
  1911. "description" : "A single multiple-choice selection",
  1912. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1913. "guisection" : "tab"
  1914. },{
  1915. "name" : "large_multi",
  1916. "description" : "A large multiple selection",
  1917. "gisprompt" : False,
  1918. "multiple" : "yes",
  1919. # values must be an array of strings
  1920. "values" : str2rgb.keys() + map(str, str2rgb.values())
  1921. },{
  1922. "name" : "a_file",
  1923. "description" : "A file selector",
  1924. "gisprompt" : True,
  1925. "element" : "file"
  1926. }
  1927. ]
  1928. task.flags = [
  1929. {
  1930. "name" : "a",
  1931. "description" : "Some flag, will appear in Main since it is required",
  1932. "required" : True
  1933. },{
  1934. "name" : "b",
  1935. "description" : "pre-filled flag, will appear in options since it is not required",
  1936. "value" : True
  1937. },{
  1938. "name" : "hidden_flag",
  1939. "description" : "hidden flag, should not be changeable",
  1940. "hidden" : "yes",
  1941. "value" : True
  1942. }
  1943. ]
  1944. q = wx.LogNull()
  1945. GrassGUIApp(task).MainLoop()