menuform.py 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212
  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. pMap = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  217. if pMap:
  218. map = pMap.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.getCmd()
  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. def updateValuesHook(self, event = None):
  494. """!Update status bar data"""
  495. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  496. if event:
  497. event.Skip()
  498. def OnKeyUp(self, event):
  499. """!Key released (check hot-keys)"""
  500. try:
  501. kc = chr(event.GetKeyCode())
  502. except ValueError:
  503. event.Skip()
  504. return
  505. if not event.ControlDown():
  506. event.Skip()
  507. return
  508. if kc == 'Q':
  509. self.OnCancel(None)
  510. elif kc == 'S':
  511. self.OnAbort(None)
  512. elif kc == 'H':
  513. self.OnHelp(None)
  514. elif kc == 'R':
  515. self.OnRun(None)
  516. elif kc == 'C':
  517. self.OnCopy(None)
  518. event.Skip()
  519. def OnDone(self, cmd, returncode):
  520. """!This function is launched from OnRun() when command is
  521. finished
  522. @param returncode command's return code (0 for success)
  523. """
  524. if not self.parent or returncode != 0:
  525. return
  526. if self.parent.GetName() not in ('LayerTree', 'LayerManager'):
  527. return
  528. if self.parent.GetName() == 'LayerTree':
  529. display = self.parent.GetMapDisplay()
  530. else: # Layer Manager
  531. display = self.parent.GetLayerTree().GetMapDisplay()
  532. if not display or not display.IsAutoRendered():
  533. return
  534. mapLayers = map(lambda x: x.GetName(),
  535. display.GetRender().GetListOfLayers(l_type = 'raster') +
  536. display.GetRender().GetListOfLayers(l_type = 'vector'))
  537. task = GUI(show = None).ParseCommand(cmd)
  538. for p in task.get_options()['params']:
  539. if p.get('prompt', '') not in ('raster', 'vector'):
  540. continue
  541. mapName = p.get('value', '')
  542. if '@' not in mapName:
  543. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  544. if mapName in mapLayers:
  545. display.GetWindow().UpdateMap(render = True)
  546. return
  547. def OnOK(self, event):
  548. """!OK button pressed"""
  549. cmd = self.OnApply(event)
  550. if cmd is not None and self.get_dcmd is not None:
  551. self.OnCancel(event)
  552. def OnApply(self, event):
  553. """!Apply the command"""
  554. if self.modeler:
  555. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  556. else:
  557. cmd = self.createCmd()
  558. if cmd is not None and self.get_dcmd is not None:
  559. # return d.* command to layer tree for rendering
  560. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  561. "flags" : self.task.flags},
  562. self)
  563. # echo d.* command to output console
  564. # self.parent.writeDCommand(cmd)
  565. return cmd
  566. def OnRun(self, event):
  567. """!Run the command"""
  568. cmd = self.createCmd()
  569. if not cmd or len(cmd) < 1:
  570. return
  571. if self.standalone or cmd[0][0:2] != "d.":
  572. # Send any non-display command to parent window (probably wxgui.py)
  573. # put to parents switch to 'Command output'
  574. self.notebookpanel.notebook.SetSelectionByName('output')
  575. try:
  576. if self.task.path:
  577. cmd[0] = self.task.path # full path
  578. self.goutput.RunCmd(cmd, onDone = self.OnDone)
  579. except AttributeError, e:
  580. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  581. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  582. else:
  583. gcmd.Command(cmd)
  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. event = goutput.wxCmdAbort(aborted = True)
  593. wx.PostEvent(self.goutput, event)
  594. def OnCopy(self, event):
  595. """!Copy the command"""
  596. cmddata = wx.TextDataObject()
  597. # list -> string
  598. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  599. cmddata.SetText(cmdstring)
  600. if wx.TheClipboard.Open():
  601. # wx.TheClipboard.UsePrimarySelection(True)
  602. wx.TheClipboard.SetData(cmddata)
  603. wx.TheClipboard.Close()
  604. self.SetStatusText(_("'%s' copied to clipboard") % \
  605. (cmdstring))
  606. def OnCancel(self, event):
  607. """!Cancel button pressed"""
  608. self.MakeModal(False)
  609. if self.get_dcmd and \
  610. self.parent and \
  611. self.parent.GetName() in ('LayerTree',
  612. 'MapWindow'):
  613. # display decorations and
  614. # pressing OK or cancel after setting layer properties
  615. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  616. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  617. self.Hide()
  618. # canceled layer with nothing set
  619. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  620. self.parent.Delete(self.layer)
  621. self.Destroy()
  622. else:
  623. # cancel for non-display commands
  624. self.Destroy()
  625. def OnHelp(self, event):
  626. """!Show manual page (switch to the 'Manual' notebook page)"""
  627. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  628. self.notebookpanel.notebook.SetSelectionByName('manual')
  629. self.notebookpanel.OnPageChange(None)
  630. if event:
  631. event.Skip()
  632. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  633. """!Create command string (python list)"""
  634. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  635. ignoreRequired = ignoreRequired)
  636. class cmdPanel(wx.Panel):
  637. """!A panel containing a notebook dividing in tabs the different
  638. guisections of the GRASS cmd.
  639. """
  640. def __init__(self, parent, task, id = wx.ID_ANY, mainFrame = None, *args, **kwargs):
  641. if mainFrame:
  642. self.parent = mainFrame
  643. else:
  644. self.parent = parent
  645. self.task = task
  646. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  647. # Determine tab layout
  648. sections = []
  649. is_section = {}
  650. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  651. self.label_id = [] # wrap titles on resize
  652. self.Bind(wx.EVT_SIZE, self.OnSize)
  653. for task in not_hidden:
  654. if task.get('required', False):
  655. # All required go into Main, even if they had defined another guisection
  656. task['guisection'] = _('Required')
  657. if task.get('guisection','') == '':
  658. # Undefined guisections end up into Options
  659. task['guisection'] = _('Optional')
  660. if task['guisection'] not in is_section:
  661. # We do it like this to keep the original order, except for Main which goes first
  662. is_section[task['guisection']] = 1
  663. sections.append(task['guisection'])
  664. else:
  665. is_section[ task['guisection'] ] += 1
  666. del is_section
  667. # 'Required' tab goes first, 'Optional' as the last one
  668. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  669. if content in sections:
  670. idx = sections.index(content)
  671. sections[idx:idx+1] = []
  672. sections[newidx:newidx] = [content]
  673. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  674. # Build notebook
  675. self.notebook = GNotebook(self, style = globalvar.FNPageStyle)
  676. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  677. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  678. tab = {}
  679. tabsizer = {}
  680. for section in sections:
  681. tab[section] = scrolled.ScrolledPanel(parent = self.notebook)
  682. tab[section].SetScrollRate(10, 10)
  683. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  684. self.notebook.AddPage(page = tab[section], text = section)
  685. # are we running from command line?
  686. ### add 'command output' tab regardless standalone dialog
  687. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  688. self.goutput = goutput.GMConsole(parent = self, margin = False)
  689. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  690. else:
  691. self.goutput = None
  692. self.manual_tab = HelpPanel(parent = self, grass_command = self.task.name)
  693. if not self.manual_tab.IsFile():
  694. self.manual_tab.Hide()
  695. else:
  696. self.notebook.AddPage(page = self.manual_tab, text = _("Manual"), name = 'manual')
  697. self.notebook.SetSelection(0)
  698. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  699. #
  700. # flags
  701. #
  702. text_style = wx.FONTWEIGHT_NORMAL
  703. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  704. for f in visible_flags:
  705. which_sizer = tabsizer[ f['guisection'] ]
  706. which_panel = tab[ f['guisection'] ]
  707. # if label is given: description -> tooltip
  708. if f.get('label','') != '':
  709. title = text_beautify(f['label'])
  710. tooltip = text_beautify(f['description'], width = -1)
  711. else:
  712. title = text_beautify(f['description'])
  713. tooltip = None
  714. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  715. rtitle_txt = wx.StaticText(parent = which_panel,
  716. label = '(' + f['name'] + ')')
  717. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  718. self.label_id.append(chk.GetId())
  719. if tooltip:
  720. chk.SetToolTipString(tooltip)
  721. chk.SetValue(f.get('value', False))
  722. title_sizer.Add(item = chk, proportion = 1,
  723. flag = wx.EXPAND)
  724. title_sizer.Add(item = rtitle_txt, proportion = 0,
  725. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  726. which_sizer.Add(item = title_sizer, proportion = 0,
  727. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  728. f['wxId'] = [ chk.GetId(), ]
  729. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  730. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  731. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  732. label = _("Parameterized in model"))
  733. parChk.SetName('ModelParam')
  734. parChk.SetValue(f.get('parameterized', False))
  735. if 'wxId' in f:
  736. f['wxId'].append(parChk.GetId())
  737. else:
  738. f['wxId'] = [ parChk.GetId() ]
  739. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  740. which_sizer.Add(item = parChk, proportion = 0,
  741. flag = wx.LEFT, border = 20)
  742. if f['name'] in ('verbose', 'quiet'):
  743. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  744. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  745. if f['name'] == vq:
  746. chk.SetValue(True)
  747. f['value'] = True
  748. elif f['name'] == 'overwrite' and 'value' not in f:
  749. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  750. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  751. #
  752. # parameters
  753. #
  754. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  755. try:
  756. first_param = visible_params[0]
  757. except IndexError:
  758. first_param = None
  759. for p in visible_params:
  760. which_sizer = tabsizer[ p['guisection'] ]
  761. which_panel = tab[ p['guisection'] ]
  762. # if label is given -> label and description -> tooltip
  763. # otherwise description -> lavel
  764. if p.get('label','') != '':
  765. title = text_beautify(p['label'])
  766. tooltip = text_beautify(p['description'], width = -1)
  767. else:
  768. title = text_beautify(p['description'])
  769. tooltip = None
  770. txt = None
  771. # text style (required -> bold)
  772. if not p.get('required', False):
  773. text_style = wx.FONTWEIGHT_NORMAL
  774. else:
  775. text_style = wx.FONTWEIGHT_BOLD
  776. # title sizer (description, name, type)
  777. if (len(p.get('values', [])) > 0) and \
  778. p.get('multiple', False) and \
  779. p.get('gisprompt',False) == False and \
  780. p.get('type', '') == 'string':
  781. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  782. else:
  783. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  784. title_txt = wx.StaticText(parent = which_panel)
  785. if p['key_desc']:
  786. ltype = ','.join(p['key_desc'])
  787. else:
  788. ltype = p['type']
  789. rtitle_txt = wx.StaticText(parent = which_panel,
  790. label = '(' + p['name'] + '=' + ltype + ')')
  791. title_sizer.Add(item = title_txt, proportion = 1,
  792. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  793. title_sizer.Add(item = rtitle_txt, proportion = 0,
  794. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  795. which_sizer.Add(item = title_sizer, proportion = 0,
  796. flag = wx.EXPAND)
  797. self.label_id.append(title_txt.GetId())
  798. # title expansion
  799. if p.get('multiple', False) and len(p.get('values','')) == 0:
  800. title = _("[multiple]") + " " + title
  801. if p.get('value','') == '' :
  802. p['value'] = p.get('default','')
  803. if (len(p.get('values', [])) > 0):
  804. valuelist = map(str, p.get('values',[]))
  805. valuelist_desc = map(unicode, p.get('values_desc',[]))
  806. if p.get('multiple', False) and \
  807. p.get('gisprompt',False) == False and \
  808. p.get('type', '') == 'string':
  809. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  810. if valuelist_desc:
  811. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  812. else:
  813. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  814. isEnabled = {}
  815. # copy default values
  816. if p['value'] == '':
  817. p['value'] = p.get('default', '')
  818. for defval in p.get('value', '').split(','):
  819. isEnabled[ defval ] = 'yes'
  820. # for multi checkboxes, this is an array of all wx IDs
  821. # for each individual checkbox
  822. p[ 'wxId' ] = list()
  823. idx = 0
  824. for val in valuelist:
  825. try:
  826. label = valuelist_desc[idx]
  827. except IndexError:
  828. label = val
  829. chkbox = wx.CheckBox(parent = which_panel,
  830. label = text_beautify(label))
  831. p[ 'wxId' ].append(chkbox.GetId())
  832. if val in isEnabled:
  833. chkbox.SetValue(True)
  834. hSizer.Add(item = chkbox, proportion = 0,
  835. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  836. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  837. idx += 1
  838. which_sizer.Add(item = hSizer, proportion = 0,
  839. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  840. elif p.get('gisprompt', False) == False:
  841. if len(valuelist) == 1: # -> textctrl
  842. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  843. str(valuelist[0])))
  844. if p.get('type', '') == 'integer' and \
  845. not p.get('multiple', False):
  846. # for multiple integers use textctrl instead of spinsctrl
  847. try:
  848. minValue, maxValue = map(int, valuelist[0].split('-'))
  849. except ValueError:
  850. minValue = -1e6
  851. maxValue = 1e6
  852. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  853. min = minValue, max = maxValue)
  854. txt2.SetName("SpinCtrl")
  855. style = wx.BOTTOM | wx.LEFT
  856. else:
  857. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  858. txt2.SetName("TextCtrl")
  859. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  860. value = self._getValue(p)
  861. # parameter previously set
  862. if value:
  863. if txt2.GetName() == "SpinCtrl":
  864. txt2.SetValue(int(value))
  865. else:
  866. txt2.SetValue(value)
  867. which_sizer.Add(item = txt2, proportion = 0,
  868. flag = style, border = 5)
  869. p['wxId'] = [ txt2.GetId(), ]
  870. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  871. else:
  872. # list of values (combo)
  873. title_txt.SetLabel(title + ':')
  874. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  875. size = globalvar.DIALOG_COMBOBOX_SIZE,
  876. choices = valuelist, style = wx.CB_DROPDOWN)
  877. value = self._getValue(p)
  878. if value:
  879. cb.SetValue(value) # parameter previously set
  880. which_sizer.Add(item = cb, proportion = 0,
  881. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  882. p['wxId'] = [cb.GetId(),]
  883. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  884. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  885. # text entry
  886. if (p.get('type','string') in ('string','integer','float')
  887. and len(p.get('values',[])) == 0
  888. and p.get('gisprompt',False) == False
  889. and p.get('prompt','') != 'color'):
  890. title_txt.SetLabel(title + ':')
  891. if p.get('multiple', False) or \
  892. p.get('type', 'string') == 'string' or \
  893. len(p.get('key_desc', [])) > 1:
  894. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  895. value = self._getValue(p)
  896. if value:
  897. # parameter previously set
  898. txt3.SetValue(str(value))
  899. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  900. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  901. else:
  902. minValue = -1e9
  903. maxValue = 1e9
  904. if p.get('type', '') == 'integer':
  905. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  906. size = globalvar.DIALOG_SPIN_SIZE,
  907. min = minValue, max = maxValue)
  908. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  909. value = self._getValue(p)
  910. if value:
  911. txt3.SetValue(int(value)) # parameter previously set
  912. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  913. else:
  914. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  915. validator = FloatValidator())
  916. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  917. value = self._getValue(p)
  918. if value:
  919. txt3.SetValue(str(value)) # parameter previously set
  920. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  921. which_sizer.Add(item = txt3, proportion = 0,
  922. flag = style, border = 5)
  923. p['wxId'] = [ txt3.GetId(), ]
  924. #
  925. # element selection tree combobox (maps, icons, regions, etc.)
  926. #
  927. if p.get('gisprompt', False) == True:
  928. title_txt.SetLabel(title + ':')
  929. # GIS element entry
  930. if p.get('prompt','') not in ('color',
  931. 'color_none',
  932. 'subgroup',
  933. 'dbdriver',
  934. 'dbname',
  935. 'dbtable',
  936. 'dbcolumn',
  937. 'layer',
  938. 'layer_all',
  939. 'location',
  940. 'mapset',
  941. 'dbase') and \
  942. p.get('element', '') not in ('file', 'dir'):
  943. multiple = p.get('multiple', False)
  944. if p.get('age', '') == 'new':
  945. mapsets = [grass.gisenv()['MAPSET'],]
  946. else:
  947. mapsets = None
  948. if self.task.name in ('r.proj', 'v.proj') \
  949. and p.get('name', '') == 'input':
  950. if self.task.name == 'r.proj':
  951. isRaster = True
  952. else:
  953. isRaster = False
  954. selection = gselect.ProjSelect(parent = which_panel,
  955. isRaster = isRaster)
  956. p['wxId'] = [ selection.GetId(), ]
  957. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  958. formatSelector = False
  959. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  960. else:
  961. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  962. size = globalvar.DIALOG_GSELECT_SIZE,
  963. type = p.get('element', ''),
  964. multiple = multiple, mapsets = mapsets)
  965. value = self._getValue(p)
  966. if value:
  967. selection.SetValue(value)
  968. formatSelector = True
  969. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  970. # we target the textctl here
  971. textWin = selection.GetTextCtrl()
  972. p['wxId'] = [ textWin.GetId(), ]
  973. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  974. if p.get('prompt', '') == 'vector':
  975. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  976. # if formatSelector and p.get('age', 'old') == 'old':
  977. # # OGR supported (read-only)
  978. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  979. # self.hsizer.Add(item = selection,
  980. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  981. # border = 5)
  982. # # format (native / ogr)
  983. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  984. # label = " %s " % _("Format"),
  985. # style = wx.RA_SPECIFY_ROWS,
  986. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  987. # if p.get('value', '').lower().rfind('@ogr') > -1:
  988. # rbox.SetSelection(1)
  989. # rbox.SetName('VectorFormat')
  990. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  991. # self.hsizer.Add(item = rbox,
  992. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  993. # wx.RIGHT | wx.ALIGN_TOP,
  994. # border = 5)
  995. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  996. # default = 'dir',
  997. # exclude = ['file'])
  998. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  999. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1000. # ogrSelection.SetName('OgrSelect')
  1001. # ogrSelection.Hide()
  1002. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1003. # p['wxId'].append(rbox.GetId())
  1004. # p['wxId'].append(ogrSelection.GetId())
  1005. # for win in ogrSelection.GetDsnWin():
  1006. # p['wxId'].append(win.GetId())
  1007. # else:
  1008. which_sizer.Add(item = selection, proportion = 0,
  1009. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1010. border = 5)
  1011. elif p.get('prompt', '') == 'group':
  1012. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1013. which_sizer.Add(item = selection, proportion = 0,
  1014. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1015. border = 5)
  1016. else:
  1017. which_sizer.Add(item = selection, proportion = 0,
  1018. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1019. border = 5)
  1020. # subgroup
  1021. elif p.get('prompt', '') == 'subgroup':
  1022. selection = gselect.SubGroupSelect(parent = which_panel)
  1023. p['wxId'] = [ selection.GetId() ]
  1024. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  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. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1029. elif p.get('prompt', '') in ('dbdriver',
  1030. 'dbname',
  1031. 'dbtable',
  1032. 'dbcolumn',
  1033. 'layer',
  1034. 'layer_all',
  1035. 'location',
  1036. 'mapset',
  1037. 'dbase'):
  1038. if p.get('multiple', 'no') == 'yes':
  1039. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1040. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1041. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1042. else:
  1043. value = self._getValue(p)
  1044. if p.get('prompt', '') in ('layer',
  1045. 'layer_all'):
  1046. if p.get('prompt', '') == 'layer_all':
  1047. all = True
  1048. else:
  1049. all = False
  1050. if p.get('age', 'old') == 'old':
  1051. win = gselect.LayerSelect(parent = which_panel,
  1052. all = all,
  1053. default = p['default'])
  1054. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1055. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1056. win.SetValue(str(value)) # default or previously set value
  1057. else:
  1058. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1059. min = 1, max = 100, initial = int(p['default']))
  1060. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1061. win.SetValue(int(value)) # default or previously set value
  1062. p['wxId'] = [ win.GetId() ]
  1063. elif p.get('prompt', '') == 'dbdriver':
  1064. win = gselect.DriverSelect(parent = which_panel,
  1065. choices = p.get('values', []),
  1066. value = value)
  1067. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1068. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1069. elif p.get('prompt', '') == 'dbname':
  1070. win = gselect.DatabaseSelect(parent = which_panel,
  1071. value = value)
  1072. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1073. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1074. elif p.get('prompt', '') == 'dbtable':
  1075. if p.get('age', 'old') == 'old':
  1076. win = gselect.TableSelect(parent = which_panel)
  1077. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1078. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1079. else:
  1080. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1081. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1082. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1083. elif p.get('prompt', '') == 'dbcolumn':
  1084. win = gselect.ColumnSelect(parent = which_panel,
  1085. value = value,
  1086. param = p)
  1087. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1088. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1089. elif p.get('prompt', '') == 'location':
  1090. win = gselect.LocationSelect(parent = which_panel,
  1091. value = value)
  1092. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1093. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1094. elif p.get('prompt', '') == 'mapset':
  1095. if p.get('age', 'old') == 'old':
  1096. new = False
  1097. else:
  1098. new = True
  1099. win = gselect.MapsetSelect(parent = which_panel,
  1100. value = value, new = new)
  1101. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1102. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1103. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1104. elif p.get('prompt', '') == 'dbase':
  1105. win = gselect.DbaseSelect(parent = which_panel,
  1106. changeCallback = self.OnSetValue)
  1107. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1108. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1109. if 'wxId' not in p:
  1110. try:
  1111. p['wxId'] = [ win.GetId(), ]
  1112. except AttributeError:
  1113. pass
  1114. which_sizer.Add(item = win, proportion = 0,
  1115. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1116. # color entry
  1117. elif p.get('prompt', '') in ('color',
  1118. 'color_none'):
  1119. default_color = (200,200,200)
  1120. label_color = _("Select Color")
  1121. if p.get('default','') != '':
  1122. default_color, label_color = color_resolve(p['default'])
  1123. if p.get('value','') != '': # parameter previously set
  1124. default_color, label_color = color_resolve(p['value'])
  1125. if p.get('prompt', '') == 'color_none':
  1126. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1127. else:
  1128. this_sizer = which_sizer
  1129. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1130. label = label_color, colour = default_color,
  1131. pos = wx.DefaultPosition, size = (150,-1))
  1132. this_sizer.Add(item = btn_colour, proportion = 0,
  1133. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1134. # For color selectors, this is a two-member array, holding the IDs of
  1135. # the selector proper and either a "transparent" button or None
  1136. p['wxId'] = [btn_colour.GetId(),]
  1137. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1138. if p.get('prompt', '') == 'color_none':
  1139. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1140. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1141. none_check.SetValue(True)
  1142. else:
  1143. none_check.SetValue(False)
  1144. this_sizer.Add(item = none_check, proportion = 0,
  1145. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1146. which_sizer.Add(this_sizer)
  1147. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1148. p['wxId'].append(none_check.GetId())
  1149. else:
  1150. p['wxId'].append(None)
  1151. # file selector
  1152. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1153. if p.get('age', 'new') == 'new':
  1154. fmode = wx.SAVE
  1155. else:
  1156. fmode = wx.OPEN
  1157. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1158. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1159. dialogTitle = _('Choose %s') % \
  1160. p.get('description',_('File')),
  1161. buttonText = _('Browse'),
  1162. startDirectory = os.getcwd(), fileMode = fmode,
  1163. changeCallback = self.OnSetValue)
  1164. value = self._getValue(p)
  1165. if value:
  1166. fbb.SetValue(value) # parameter previously set
  1167. which_sizer.Add(item = fbb, proportion = 0,
  1168. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1169. # A file browse button is a combobox with two children:
  1170. # a textctl and a button;
  1171. # we have to target the button here
  1172. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1173. if p.get('age', 'new') == 'old' and \
  1174. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1175. # widget for interactive input
  1176. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1177. style = wx.TE_MULTILINE,
  1178. size = (-1, 75))
  1179. if p.get('value', '') and os.path.isfile(p['value']):
  1180. f = open(p['value'])
  1181. ifbb.SetValue(''.join(f.readlines()))
  1182. f.close()
  1183. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1184. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1185. label = _('or enter values interactively')),
  1186. proportion = 0,
  1187. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1188. which_sizer.Add(item = ifbb, proportion = 1,
  1189. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1190. p['wxId'].append(ifbb.GetId())
  1191. # directory selector
  1192. elif p.get('prompt','') != 'color' and p.get('element', '') == 'dir':
  1193. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1194. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1195. dialogTitle = _('Choose %s') % \
  1196. p.get('description', _('Directory')),
  1197. buttonText = _('Browse'),
  1198. startDirectory = os.getcwd(),
  1199. changeCallback = self.OnSetValue)
  1200. value = self._getValue(p)
  1201. if value:
  1202. fbb.SetValue(value) # parameter previously set
  1203. which_sizer.Add(item = fbb, proportion = 0,
  1204. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1205. # A file browse button is a combobox with two children:
  1206. # a textctl and a button;
  1207. # we have to target the button here
  1208. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1209. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1210. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1211. label = _("Parameterized in model"))
  1212. parChk.SetName('ModelParam')
  1213. parChk.SetValue(p.get('parameterized', False))
  1214. if 'wxId' in p:
  1215. p['wxId'].append(parChk.GetId())
  1216. else:
  1217. p['wxId'] = [ parChk.GetId() ]
  1218. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1219. which_sizer.Add(item = parChk, proportion = 0,
  1220. flag = wx.LEFT, border = 20)
  1221. if title_txt is not None:
  1222. # create tooltip if given
  1223. if len(p['values_desc']) > 0:
  1224. if tooltip:
  1225. tooltip += 2 * os.linesep
  1226. else:
  1227. tooltip = ''
  1228. if len(p['values']) == len(p['values_desc']):
  1229. for i in range(len(p['values'])):
  1230. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1231. tooltip.strip(os.linesep)
  1232. if tooltip:
  1233. title_txt.SetToolTipString(tooltip)
  1234. if p == first_param:
  1235. if 'wxId' in p and len(p['wxId']) > 0:
  1236. win = self.FindWindowById(p['wxId'][0])
  1237. win.SetFocus()
  1238. #
  1239. # set widget relations for OnUpdateSelection
  1240. #
  1241. pMap = None
  1242. pLayer = []
  1243. pDriver = None
  1244. pDatabase = None
  1245. pTable = None
  1246. pColumn = []
  1247. pGroup = None
  1248. pSubGroup = None
  1249. pDbase = None
  1250. pLocation = None
  1251. pMapset = None
  1252. for p in self.task.params:
  1253. if p.get('gisprompt', False) == False:
  1254. continue
  1255. guidep = p.get('guidependency', '')
  1256. if guidep:
  1257. # fixed options dependency defined
  1258. options = guidep.split(',')
  1259. for opt in options:
  1260. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1261. if id:
  1262. if 'wxId-bind' not in p:
  1263. p['wxId-bind'] = list()
  1264. p['wxId-bind'] += pOpt['wxId']
  1265. continue
  1266. prompt = p.get('element', '')
  1267. if prompt in ('cell', 'vector'):
  1268. name = p.get('name', '')
  1269. if name in ('map', 'input'):
  1270. pMap = p
  1271. elif prompt == 'layer':
  1272. pLayer.append(p)
  1273. elif prompt == 'dbcolumn':
  1274. pColumn.append(p)
  1275. elif prompt == 'dbdriver':
  1276. pDriver = p
  1277. elif prompt == 'dbname':
  1278. pDatabase = p
  1279. elif prompt == 'dbtable':
  1280. pTable = p
  1281. elif prompt == 'group':
  1282. pGroup = p
  1283. elif prompt == 'subgroup':
  1284. pSubGroup = p
  1285. elif prompt == 'dbase':
  1286. pDbase = p
  1287. elif prompt == 'location':
  1288. pLocation = p
  1289. elif prompt == 'mapset':
  1290. pMapset = p
  1291. # collect ids
  1292. pColumnIds = []
  1293. for p in pColumn:
  1294. pColumnIds += p['wxId']
  1295. pLayerIds = []
  1296. for p in pLayer:
  1297. pLayerIds += p['wxId']
  1298. # set wxId-bindings
  1299. if pMap:
  1300. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1301. if pLayer:
  1302. pMap['wxId-bind'] += pLayerIds
  1303. if pLayer:
  1304. for p in pLayer:
  1305. p['wxId-bind'] = copy.copy(pColumnIds)
  1306. if pDriver and pTable:
  1307. pDriver['wxId-bind'] = pTable['wxId']
  1308. if pDatabase and pTable:
  1309. pDatabase['wxId-bind'] = pTable['wxId']
  1310. if pTable and pColumnIds:
  1311. pTable['wxId-bind'] = pColumnIds
  1312. if pGroup and pSubGroup:
  1313. pGroup['wxId-bind'] = pSubGroup['wxId']
  1314. if pDbase and pLocation:
  1315. pDbase['wxId-bind'] = pLocation['wxId']
  1316. if pLocation and pMapset:
  1317. pLocation['wxId-bind'] = pMapset['wxId']
  1318. if pLocation and pMapset and pMap:
  1319. pLocation['wxId-bind'] += pMap['wxId']
  1320. pMapset['wxId-bind'] = pMap['wxId']
  1321. #
  1322. # determine panel size
  1323. #
  1324. maxsizes = (0, 0)
  1325. for section in sections:
  1326. tab[section].SetSizer(tabsizer[section])
  1327. tabsizer[section].Fit(tab[section])
  1328. tab[section].Layout()
  1329. minsecsizes = tabsizer[section].GetSize()
  1330. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1331. # TODO: be less arbitrary with these 600
  1332. self.panelMinHeight = 100
  1333. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1334. for section in sections:
  1335. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1336. if self.manual_tab.IsLoaded():
  1337. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1338. self.SetSizer(panelsizer)
  1339. panelsizer.Fit(self.notebook)
  1340. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1341. def _getValue(self, p):
  1342. """!Get value or default value of given parameter
  1343. @param p parameter directory
  1344. """
  1345. if p.get('value', '') != '':
  1346. return p['value']
  1347. return p.get('default', '')
  1348. def OnFileText(self, event):
  1349. """File input interactively entered"""
  1350. text = event.GetString()
  1351. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1352. if not p:
  1353. return # should not happen
  1354. win = self.FindWindowById(p['wxId'][0])
  1355. if text:
  1356. filename = win.GetValue()
  1357. if not filename:
  1358. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1359. filename = grass.tempfile()
  1360. win.SetValue(filename)
  1361. f = open(filename, "w")
  1362. try:
  1363. f.write(text)
  1364. finally:
  1365. f.close()
  1366. else:
  1367. win.SetValue('')
  1368. def OnVectorFormat(self, event):
  1369. """!Change vector format (native / ogr)"""
  1370. sel = event.GetSelection()
  1371. idEvent = event.GetId()
  1372. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1373. if not p:
  1374. return # should not happen
  1375. # detect windows
  1376. winNative = None
  1377. winOgr = None
  1378. for id in p['wxId']:
  1379. if id == idEvent:
  1380. continue
  1381. name = self.FindWindowById(id).GetName()
  1382. if name == 'Select':
  1383. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1384. elif name == 'OgrSelect':
  1385. winOgr = self.FindWindowById(id)
  1386. # enable / disable widgets & update values
  1387. rbox = self.FindWindowByName('VectorFormat')
  1388. self.hsizer.Remove(rbox)
  1389. if sel == 0: # -> native
  1390. winOgr.Hide()
  1391. self.hsizer.Remove(winOgr)
  1392. self.hsizer.Add(item = winNative,
  1393. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1394. border = 5)
  1395. winNative.Show()
  1396. p['value'] = winNative.GetValue()
  1397. elif sel == 1: # -> OGR
  1398. sizer = wx.BoxSizer(wx.VERTICAL)
  1399. winNative.Hide()
  1400. self.hsizer.Remove(winNative)
  1401. sizer.Add(item = winOgr)
  1402. winOgr.Show()
  1403. p['value'] = winOgr.GetDsn()
  1404. self.hsizer.Add(item = sizer,
  1405. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1406. border = 5)
  1407. self.hsizer.Add(item = rbox,
  1408. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1409. wx.RIGHT | wx.ALIGN_TOP,
  1410. border = 5)
  1411. self.hsizer.Layout()
  1412. self.Layout()
  1413. self.OnUpdateValues()
  1414. self.OnUpdateSelection(event)
  1415. def OnUpdateDialog(self, event):
  1416. for fn, kwargs in event.data.iteritems():
  1417. fn(**kwargs)
  1418. self.parent.updateValuesHook()
  1419. def OnVerbosity(self, event):
  1420. """!Verbosity level changed"""
  1421. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1422. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1423. if event.IsChecked():
  1424. if event.GetId() == verbose.GetId():
  1425. if quiet.IsChecked():
  1426. quiet.SetValue(False)
  1427. self.task.get_flag('quiet')['value'] = False
  1428. else:
  1429. if verbose.IsChecked():
  1430. verbose.SetValue(False)
  1431. self.task.get_flag('verbose')['value'] = False
  1432. event.Skip()
  1433. def OnPageChange(self, event):
  1434. if not event:
  1435. sel = self.notebook.GetSelection()
  1436. else:
  1437. sel = event.GetSelection()
  1438. idx = self.notebook.GetPageIndexByName('manual')
  1439. if idx > -1 and sel == idx:
  1440. # calling LoadPage() is strangely time-consuming (only first call)
  1441. # FIXME: move to helpPage.__init__()
  1442. if not self.manual_tab.IsLoaded():
  1443. wx.Yield()
  1444. self.manual_tab.LoadPage()
  1445. self.Layout()
  1446. def OnColorChange(self, event):
  1447. myId = event.GetId()
  1448. for p in self.task.params:
  1449. if 'wxId' in p and myId in p['wxId']:
  1450. has_button = p['wxId'][1] is not None
  1451. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1452. p[ 'value' ] = 'none'
  1453. else:
  1454. colorchooser = wx.FindWindowById(p['wxId'][0])
  1455. new_color = colorchooser.GetValue()[:]
  1456. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1457. # under wx2.8.1
  1458. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1459. colorchooser.SetLabel(new_label)
  1460. colorchooser.SetColour(new_color)
  1461. colorchooser.Refresh()
  1462. p[ 'value' ] = colorchooser.GetLabel()
  1463. self.OnUpdateValues()
  1464. def OnUpdateValues(self, event = None):
  1465. """!If we were part of a richer interface, report back the
  1466. current command being built.
  1467. This method should be set by the parent of this panel if
  1468. needed. It's a hook, actually. Beware of what is 'self' in
  1469. the method def, though. It will be called with no arguments.
  1470. """
  1471. pass
  1472. def OnCheckBoxMulti(self, event):
  1473. """!Fill the values as a ','-separated string according to
  1474. current status of the checkboxes.
  1475. """
  1476. me = event.GetId()
  1477. theParam = None
  1478. for p in self.task.params:
  1479. if 'wxId' in p and me in p['wxId']:
  1480. theParam = p
  1481. myIndex = p['wxId'].index(me)
  1482. # Unpack current value list
  1483. currentValues = {}
  1484. for isThere in theParam.get('value', '').split(','):
  1485. currentValues[isThere] = 1
  1486. theValue = theParam['values'][myIndex]
  1487. if event.Checked():
  1488. currentValues[ theValue ] = 1
  1489. else:
  1490. del currentValues[ theValue ]
  1491. # Keep the original order, so that some defaults may be recovered
  1492. currentValueList = []
  1493. for v in theParam['values']:
  1494. if v in currentValues:
  1495. currentValueList.append(v)
  1496. # Pack it back
  1497. theParam['value'] = ','.join(currentValueList)
  1498. self.OnUpdateValues()
  1499. def OnSetValue(self, event):
  1500. """!Retrieve the widget value and set the task value field
  1501. accordingly.
  1502. Use for widgets that have a proper GetValue() method, i.e. not
  1503. for selectors.
  1504. """
  1505. myId = event.GetId()
  1506. me = wx.FindWindowById(myId)
  1507. name = me.GetName()
  1508. found = False
  1509. for porf in self.task.params + self.task.flags:
  1510. if 'wxId' not in porf:
  1511. continue
  1512. if myId in porf['wxId']:
  1513. found = True
  1514. break
  1515. if not found:
  1516. return
  1517. if name == 'GdalSelect':
  1518. porf['value'] = event.dsn
  1519. elif name == 'ModelParam':
  1520. porf['parameterized'] = me.IsChecked()
  1521. else:
  1522. porf['value'] = me.GetValue()
  1523. self.OnUpdateValues(event)
  1524. event.Skip()
  1525. def OnUpdateSelection(self, event):
  1526. """!Update dialog (layers, tables, columns, etc.)
  1527. """
  1528. if not hasattr(self.parent, "updateThread"):
  1529. if event:
  1530. event.Skip()
  1531. return
  1532. if event:
  1533. self.parent.updateThread.Update(UpdateDialog,
  1534. self,
  1535. event,
  1536. event.GetId(),
  1537. self.task)
  1538. else:
  1539. self.parent.updateThread.Update(UpdateDialog,
  1540. self,
  1541. None,
  1542. None,
  1543. self.task)
  1544. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1545. """!Produce a command line string (list) or feeding into GRASS.
  1546. @param ignoreErrors True then it will return whatever has been
  1547. built so far, even though it would not be a correct command
  1548. for GRASS
  1549. """
  1550. try:
  1551. cmd = self.task.getCmd(ignoreErrors = ignoreErrors,
  1552. ignoreRequired = ignoreRequired)
  1553. except ValueError, err:
  1554. dlg = wx.MessageDialog(parent = self,
  1555. message = unicode(err),
  1556. caption = _("Error in %s") % self.task.name,
  1557. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1558. dlg.ShowModal()
  1559. dlg.Destroy()
  1560. cmd = None
  1561. return cmd
  1562. def OnSize(self, event):
  1563. width = event.GetSize()[0]
  1564. fontsize = self.GetFont().GetPointSize()
  1565. text_width = max(width / (fontsize - 3), 70)
  1566. for id in self.label_id:
  1567. win = self.FindWindowById(id)
  1568. label = win.GetLabel()
  1569. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1570. win.SetLabel(label_new)
  1571. event.Skip()
  1572. class GrassGUIApp(wx.App):
  1573. """!Stand-alone GRASS command GUI
  1574. """
  1575. def __init__(self, grass_task):
  1576. self.grass_task = grass_task
  1577. wx.App.__init__(self, False)
  1578. def OnInit(self):
  1579. msg = self.grass_task.get_error_msg()
  1580. if msg:
  1581. gcmd.GError(msg + '\n\nTry to set up GRASS_ADDON_PATH variable.')
  1582. return True
  1583. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1584. self.mf.CentreOnScreen()
  1585. self.mf.Show(True)
  1586. self.SetTopWindow(self.mf)
  1587. return True
  1588. class GUI:
  1589. def __init__(self, parent = None, show = True, modal = False,
  1590. centreOnParent = False, checkError = False):
  1591. """!Parses GRASS commands when module is imported and used from
  1592. Layer Manager.
  1593. """
  1594. self.parent = parent
  1595. self.show = show
  1596. self.modal = modal
  1597. self.centreOnParent = centreOnParent
  1598. self.checkError = checkError
  1599. self.grass_task = None
  1600. self.cmd = list()
  1601. global _blackList
  1602. if self.parent:
  1603. _blackList['enabled'] = True
  1604. else:
  1605. _blackList['enabled'] = False
  1606. def GetCmd(self):
  1607. """!Get validated command"""
  1608. return self.cmd
  1609. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1610. """!Parse command
  1611. Note: cmd is given as list
  1612. If command is given with options, return validated cmd list:
  1613. - add key name for first parameter if not given
  1614. - change mapname to mapname@mapset
  1615. """
  1616. start = time.time()
  1617. dcmd_params = {}
  1618. if completed == None:
  1619. get_dcmd = None
  1620. layer = None
  1621. dcmd_params = None
  1622. else:
  1623. get_dcmd = completed[0]
  1624. layer = completed[1]
  1625. if completed[2]:
  1626. dcmd_params.update(completed[2])
  1627. # parse the interface decription
  1628. try:
  1629. global _blackList
  1630. self.grass_task = gtask.parse_interface(cmd[0],
  1631. blackList = _blackList)
  1632. except ValueError, e: #grass.ScriptError, e:
  1633. gcmd.GError(e.value)
  1634. return
  1635. # if layer parameters previously set, re-insert them into dialog
  1636. if completed is not None:
  1637. if 'params' in dcmd_params:
  1638. self.grass_task.params = dcmd_params['params']
  1639. if 'flags' in dcmd_params:
  1640. self.grass_task.flags = dcmd_params['flags']
  1641. err = list()
  1642. # update parameters if needed && validate command
  1643. if len(cmd) > 1:
  1644. i = 0
  1645. cmd_validated = [cmd[0]]
  1646. for option in cmd[1:]:
  1647. if option[0] == '-': # flag
  1648. if option[1] == '-':
  1649. self.grass_task.set_flag(option[2:], True)
  1650. else:
  1651. self.grass_task.set_flag(option[1], True)
  1652. cmd_validated.append(option)
  1653. else: # parameter
  1654. try:
  1655. key, value = option.split('=', 1)
  1656. except:
  1657. if i == 0: # add key name of first parameter if not given
  1658. key = self.grass_task.firstParam
  1659. value = option
  1660. else:
  1661. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1662. element = self.grass_task.get_param(key, raiseError = False)
  1663. if not element:
  1664. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1665. { 'cmd' : cmd[0],
  1666. 'key' : key })
  1667. continue
  1668. element = element['element']
  1669. if element in ['cell', 'vector']:
  1670. # mapname -> mapname@mapset
  1671. try:
  1672. name, mapset = value.split('@')
  1673. except ValueError:
  1674. mapset = grass.find_file(value, element)['mapset']
  1675. curr_mapset = grass.gisenv()['MAPSET']
  1676. if mapset and mapset != curr_mapset:
  1677. value = value + '@' + mapset
  1678. self.grass_task.set_param(key, value)
  1679. cmd_validated.append(key + '=' + value)
  1680. i += 1
  1681. # update original command list
  1682. cmd = cmd_validated
  1683. if self.show is not None:
  1684. self.mf = mainFrame(parent = self.parent, ID = wx.ID_ANY,
  1685. task_description = self.grass_task,
  1686. get_dcmd = get_dcmd, layer = layer)
  1687. else:
  1688. self.mf = None
  1689. if get_dcmd is not None:
  1690. # update only propwin reference
  1691. get_dcmd(dcmd = None, layer = layer, params = None,
  1692. propwin = self.mf)
  1693. if self.show is not None:
  1694. self.mf.notebookpanel.OnUpdateSelection(None)
  1695. if self.show is True:
  1696. if self.parent and self.centreOnParent:
  1697. self.mf.CentreOnParent()
  1698. else:
  1699. self.mf.CenterOnScreen()
  1700. self.mf.Show(self.show)
  1701. self.mf.MakeModal(self.modal)
  1702. else:
  1703. self.mf.OnApply(None)
  1704. self.cmd = cmd
  1705. if self.checkError:
  1706. return self.grass_task, err
  1707. else:
  1708. return self.grass_task
  1709. def GetCommandInputMapParamKey(self, cmd):
  1710. """!Get parameter key for input raster/vector map
  1711. @param cmd module name
  1712. @return parameter key
  1713. @return None on failure
  1714. """
  1715. # parse the interface decription
  1716. if not self.grass_task:
  1717. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1718. self.grass_task = gtask.processTask(tree).get_task()
  1719. for p in self.grass_task.params:
  1720. if p.get('name', '') in ('input', 'map'):
  1721. age = p.get('age', '')
  1722. prompt = p.get('prompt', '')
  1723. element = p.get('element', '')
  1724. if age == 'old' and \
  1725. element in ('cell', 'grid3', 'vector') and \
  1726. prompt in ('raster', '3d-raster', 'vector'):
  1727. return p.get('name', None)
  1728. return None
  1729. class FloatValidator(wx.PyValidator):
  1730. """!Validator for floating-point input"""
  1731. def __init__(self):
  1732. wx.PyValidator.__init__(self)
  1733. self.Bind(wx.EVT_TEXT, self.OnText)
  1734. def Clone(self):
  1735. """!Clone validator"""
  1736. return FloatValidator()
  1737. def Validate(self):
  1738. """Validate input"""
  1739. textCtrl = self.GetWindow()
  1740. text = textCtrl.GetValue()
  1741. if text:
  1742. try:
  1743. float(text)
  1744. except ValueError:
  1745. textCtrl.SetBackgroundColour("grey")
  1746. textCtrl.SetFocus()
  1747. textCtrl.Refresh()
  1748. return False
  1749. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  1750. textCtrl.SetBackgroundColour(sysColor)
  1751. textCtrl.Refresh()
  1752. return True
  1753. def OnText(self, event):
  1754. """!Do validation"""
  1755. self.Validate()
  1756. event.Skip()
  1757. def TransferToWindow(self):
  1758. return True # Prevent wxDialog from complaining.
  1759. def TransferFromWindow(self):
  1760. return True # Prevent wxDialog from complaining.
  1761. class GNotebook(FN.FlatNotebook):
  1762. """!Generic notebook widget
  1763. """
  1764. def __init__(self, parent, style, **kwargs):
  1765. if globalvar.hasAgw:
  1766. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
  1767. else:
  1768. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  1769. self.notebookPages = {}
  1770. def AddPage(self, **kwargs):
  1771. """!Add a new page
  1772. """
  1773. if 'name' in kwargs:
  1774. self.notebookPages[kwargs['name']] = kwargs['page']
  1775. del kwargs['name']
  1776. super(GNotebook, self).AddPage(**kwargs)
  1777. def InsertPage(self, **kwargs):
  1778. """!Insert a new page
  1779. """
  1780. if 'name' in kwargs:
  1781. self.notebookPages[kwargs['name']] = kwargs['page']
  1782. del kwargs['name']
  1783. super(GNotebook, self).InsertPage(**kwargs)
  1784. def SetSelectionByName(self, page):
  1785. """!Set notebook
  1786. @param page names, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
  1787. """
  1788. if self.GetSelection() != self.GetPageIndexByName('output'):
  1789. self.SetSelection(self.GetPageIndexByName(page))
  1790. def GetPageIndexByName(self, page):
  1791. """!Get notebook page index
  1792. @param page name
  1793. """
  1794. if page not in self.notebookPages:
  1795. return -1
  1796. return self.GetPageIndex(self.notebookPages[page])
  1797. if __name__ == "__main__":
  1798. import gettext
  1799. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1800. if len(sys.argv) == 1:
  1801. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1802. if sys.argv[1] != 'test':
  1803. q = wx.LogNull()
  1804. cmd = utils.split(sys.argv[1])
  1805. task = gtask.grassTask(cmd[0], blackList = _blackList)
  1806. task.set_options(cmd[1:])
  1807. app = GrassGUIApp(task)
  1808. app.MainLoop()
  1809. else: #Test
  1810. # Test grassTask from within a GRASS session
  1811. if os.getenv("GISBASE") is not None:
  1812. task = gtask.grassTask("d.vect")
  1813. task.get_param('map')['value'] = "map_name"
  1814. task.get_flag('v')['value'] = True
  1815. task.get_param('layer')['value'] = 1
  1816. task.get_param('bcolor')['value'] = "red"
  1817. assert ' '.join(task.getCmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1818. # Test interface building with handmade grassTask,
  1819. # possibly outside of a GRASS session.
  1820. task = gtask.grassTask()
  1821. task.name = "TestTask"
  1822. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1823. task.keywords = ["grass","test","task"]
  1824. task.params = [
  1825. {
  1826. "name" : "text",
  1827. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1828. "label" : "Enter some text",
  1829. },{
  1830. "name" : "hidden_text",
  1831. "description" : "This text should not appear in the form",
  1832. "hidden" : True
  1833. },{
  1834. "name" : "text_default",
  1835. "description" : "Enter text to override the default",
  1836. "default" : "default text"
  1837. },{
  1838. "name" : "text_prefilled",
  1839. "description" : "You should see a friendly welcome message here",
  1840. "value" : "hello, world"
  1841. },{
  1842. "name" : "plain_color",
  1843. "description" : "This is a plain color, and it is a compulsory parameter",
  1844. "required" : False,
  1845. "gisprompt" : True,
  1846. "prompt" : "color"
  1847. },{
  1848. "name" : "transparent_color",
  1849. "description" : "This color becomes transparent when set to none",
  1850. "guisection" : "tab",
  1851. "gisprompt" : True,
  1852. "prompt" : "color"
  1853. },{
  1854. "name" : "multi",
  1855. "description" : "A multiple selection",
  1856. 'default': u'red,green,blue',
  1857. 'gisprompt': False,
  1858. 'guisection': 'tab',
  1859. 'multiple': u'yes',
  1860. 'type': u'string',
  1861. 'value': '',
  1862. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1863. },{
  1864. "name" : "single",
  1865. "description" : "A single multiple-choice selection",
  1866. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1867. "guisection" : "tab"
  1868. },{
  1869. "name" : "large_multi",
  1870. "description" : "A large multiple selection",
  1871. "gisprompt" : False,
  1872. "multiple" : "yes",
  1873. # values must be an array of strings
  1874. "values" : str2rgb.keys() + map(str, str2rgb.values())
  1875. },{
  1876. "name" : "a_file",
  1877. "description" : "A file selector",
  1878. "gisprompt" : True,
  1879. "element" : "file"
  1880. }
  1881. ]
  1882. task.flags = [
  1883. {
  1884. "name" : "a",
  1885. "description" : "Some flag, will appear in Main since it is required",
  1886. "required" : True
  1887. },{
  1888. "name" : "b",
  1889. "description" : "pre-filled flag, will appear in options since it is not required",
  1890. "value" : True
  1891. },{
  1892. "name" : "hidden_flag",
  1893. "description" : "hidden flag, should not be changeable",
  1894. "hidden" : "yes",
  1895. "value" : True
  1896. }
  1897. ]
  1898. q = wx.LogNull()
  1899. GrassGUIApp(task).MainLoop()