forms.py 105 KB

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