forms.py 94 KB

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