menuform.py 96 KB

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