forms.py 105 KB

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