forms.py 95 KB

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