forms.py 105 KB

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