menuform.py 90 KB

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