forms.py 93 KB

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