forms.py 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  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-2012 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.script import core as grass
  68. from grass.script import task as gtask
  69. from gui_core.widgets import StaticWrapText, ScrolledPanel
  70. from gui_core.ghelp import HelpPanel
  71. from gui_core import gselect
  72. from core import gcmd
  73. from core import utils
  74. from core.settings import UserSettings
  75. from core.events import EVT_MAP_CREATED
  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', '') == 'layer':
  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', '') == 'layer': # -> 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.InsertColumns] = { 'vector' : map, 'layer' : layer,
  230. 'dbInfo' : cparams[map]['dbInfo'] }
  231. else: # table
  232. if driver and db:
  233. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  234. 'driver' : driver,
  235. 'database' : db }
  236. elif pTable:
  237. self.data[win.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. if self.task.name.split('.')[-1] in ('py', 'sh'):
  324. title = str(self.task.name.rsplit('.',1)[0])
  325. else:
  326. title = self.task.name
  327. try:
  328. if self.task.keywords != ['']:
  329. title += " [" + ', '.join(self.task.keywords) + "]"
  330. except ValueError:
  331. pass
  332. wx.Frame.__init__(self, parent = parent, id = id, title = title,
  333. name = "MainFrame", style = style, **kwargs)
  334. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  335. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  336. # statusbar
  337. self.CreateStatusBar()
  338. # icon
  339. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  340. guisizer = wx.BoxSizer(wx.VERTICAL)
  341. # set apropriate output window
  342. if self.parent:
  343. self.standalone = False
  344. else:
  345. self.standalone = True
  346. # logo + description
  347. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  348. # GRASS logo
  349. self.logo = wx.StaticBitmap(parent = self.panel,
  350. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  351. 'grass_form.png'),
  352. type = wx.BITMAP_TYPE_PNG))
  353. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  354. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  355. # add module description
  356. if self.task.label:
  357. module_desc = self.task.label + ' ' + self.task.description
  358. else:
  359. module_desc = self.task.description
  360. self.description = StaticWrapText(parent = self.panel,
  361. label = module_desc)
  362. topsizer.Add(item = self.description, proportion = 1, border = 5,
  363. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  364. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  365. self.panel.SetSizerAndFit(guisizer)
  366. self.Layout()
  367. # notebooks
  368. self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
  369. frame = self)
  370. self._gconsole = self.notebookpanel._gconsole
  371. self.goutput = self.notebookpanel.goutput
  372. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  373. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  374. # status bar
  375. status_text = _("Enter parameters for '") + self.task.name + "'"
  376. try:
  377. self.task.get_cmd()
  378. self.updateValuesHook()
  379. except ValueError:
  380. self.SetStatusText(status_text)
  381. # buttons
  382. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  383. # cancel
  384. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  385. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  386. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  387. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  388. if self.get_dcmd is not None: # A callback has been set up
  389. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  390. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  391. btn_ok.SetDefault()
  392. btnsizer.Add(item = btn_apply, proportion = 0,
  393. flag = wx.ALL | wx.ALIGN_CENTER,
  394. border = 10)
  395. btnsizer.Add(item = btn_ok, proportion = 0,
  396. flag = wx.ALL | wx.ALIGN_CENTER,
  397. border = 10)
  398. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  399. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  400. else: # We're standalone
  401. # run
  402. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  403. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  404. self.btn_run.SetDefault()
  405. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  406. # copy
  407. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY)
  408. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  409. btnsizer.Add(item = self.btn_run, proportion = 0,
  410. flag = wx.ALL | wx.ALIGN_CENTER,
  411. border = 10)
  412. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  413. flag = wx.ALL | wx.ALIGN_CENTER,
  414. border = 10)
  415. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  416. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  417. # help
  418. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  419. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  420. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  421. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  422. self.btn_help.Hide()
  423. # add help button
  424. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  425. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  426. border = 30)
  427. if self.parent and not self.modeler:
  428. addLayer = False
  429. for p in self.task.params:
  430. if p.get('age', 'old') == 'new' and \
  431. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  432. addLayer = True
  433. if addLayer:
  434. # add newly created map into layer tree
  435. self.addbox = wx.CheckBox(parent = self.panel,
  436. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  437. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  438. guisizer.Add(item = self.addbox, proportion = 0,
  439. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  440. border = 5)
  441. hasNew = False
  442. for p in self.task.params:
  443. if p.get('age', 'old') == 'new':
  444. hasNew = True
  445. break
  446. if self.get_dcmd is None and hasNew:
  447. # close dialog when command is terminated
  448. self.closebox = wx.CheckBox(parent = self.panel,
  449. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  450. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  451. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  452. "Change this settings in Preferences dialog ('Command' tab)."))
  453. guisizer.Add(item = self.closebox, proportion = 0,
  454. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  455. border = 5)
  456. # bindings
  457. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  458. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  459. self.Bind(EVT_MAP_CREATED, self.OnMapCreated)
  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, event):
  532. if hasattr(self, "addbox") and self.addbox.IsChecked():
  533. event.add = True
  534. else:
  535. event.add = False
  536. event.Skip()
  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. # Determine tab layout
  644. sections = []
  645. is_section = {}
  646. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  647. self.label_id = [] # wrap titles on resize
  648. self.Bind(wx.EVT_SIZE, self.OnSize)
  649. for task in not_hidden:
  650. if task.get('required', False):
  651. # All required go into Main, even if they had defined another guisection
  652. task['guisection'] = _('Required')
  653. if task.get('guisection','') == '':
  654. # Undefined guisections end up into Options
  655. task['guisection'] = _('Optional')
  656. if task['guisection'] not in is_section:
  657. # We do it like this to keep the original order, except for Main which goes first
  658. is_section[task['guisection']] = 1
  659. sections.append(task['guisection'])
  660. else:
  661. is_section[ task['guisection'] ] += 1
  662. del is_section
  663. # 'Required' tab goes first, 'Optional' as the last one
  664. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  665. if content in sections:
  666. idx = sections.index(content)
  667. sections[idx:idx+1] = []
  668. sections[newidx:newidx] = [content]
  669. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  670. # build notebook
  671. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  672. if style == 0: # basic top
  673. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  674. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  675. elif style == 1: # basic left
  676. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  677. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  678. elif style == 2: # fancy green
  679. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  680. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  681. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  682. elif style == 3:
  683. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  684. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  685. self.notebook.Refresh()
  686. tab = {}
  687. tabsizer = {}
  688. for section in sections:
  689. tab[section] = ScrolledPanel(parent = self.notebook)
  690. tab[section].SetScrollRate(10, 10)
  691. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  692. #
  693. # flags
  694. #
  695. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  696. for f in visible_flags:
  697. which_sizer = tabsizer[ f['guisection'] ]
  698. which_panel = tab[ f['guisection'] ]
  699. # if label is given: description -> tooltip
  700. if f.get('label','') != '':
  701. title = text_beautify(f['label'])
  702. tooltip = text_beautify(f['description'], width = -1)
  703. else:
  704. title = text_beautify(f['description'])
  705. tooltip = None
  706. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  707. rtitle_txt = wx.StaticText(parent = which_panel,
  708. label = '(' + f['name'] + ')')
  709. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  710. self.label_id.append(chk.GetId())
  711. if tooltip:
  712. chk.SetToolTipString(tooltip)
  713. chk.SetValue(f.get('value', False))
  714. title_sizer.Add(item = chk, proportion = 1,
  715. flag = wx.EXPAND)
  716. title_sizer.Add(item = rtitle_txt, proportion = 0,
  717. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  718. which_sizer.Add(item = title_sizer, proportion = 0,
  719. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  720. f['wxId'] = [ chk.GetId(), ]
  721. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  722. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  723. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  724. label = _("Parameterized in model"))
  725. parChk.SetName('ModelParam')
  726. parChk.SetValue(f.get('parameterized', False))
  727. if 'wxId' in f:
  728. f['wxId'].append(parChk.GetId())
  729. else:
  730. f['wxId'] = [ parChk.GetId() ]
  731. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  732. which_sizer.Add(item = parChk, proportion = 0,
  733. flag = wx.LEFT, border = 20)
  734. if f['name'] in ('verbose', 'quiet'):
  735. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  736. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  737. if f['name'] == vq:
  738. chk.SetValue(True)
  739. f['value'] = True
  740. elif f['name'] == 'overwrite' and 'value' not in f:
  741. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  742. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  743. #
  744. # parameters
  745. #
  746. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  747. try:
  748. first_param = visible_params[0]
  749. except IndexError:
  750. first_param = None
  751. for p in visible_params:
  752. which_sizer = tabsizer[p['guisection']]
  753. which_panel = tab[p['guisection']]
  754. # if label is given -> label and description -> tooltip
  755. # otherwise description -> lavel
  756. if p.get('label','') != '':
  757. title = text_beautify(p['label'])
  758. tooltip = text_beautify(p['description'], width = -1)
  759. else:
  760. title = text_beautify(p['description'])
  761. tooltip = None
  762. prompt = p.get('prompt', '')
  763. # text style (required -> bold)
  764. if not p.get('required', False):
  765. text_style = wx.FONTWEIGHT_NORMAL
  766. else:
  767. text_style = wx.FONTWEIGHT_BOLD
  768. # title sizer (description, name, type)
  769. if (len(p.get('values', [])) > 0) and \
  770. p.get('multiple', False) and \
  771. p.get('gisprompt', False) == False and \
  772. p.get('type', '') == 'string':
  773. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  774. else:
  775. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  776. title_txt = wx.StaticText(parent = which_panel)
  777. if p['key_desc']:
  778. ltype = ','.join(p['key_desc'])
  779. else:
  780. ltype = p['type']
  781. rtitle_txt = wx.StaticText(parent = which_panel,
  782. label = '(' + p['name'] + '=' + ltype + ')')
  783. title_sizer.Add(item = title_txt, proportion = 1,
  784. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  785. title_sizer.Add(item = rtitle_txt, proportion = 0,
  786. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  787. which_sizer.Add(item = title_sizer, proportion = 0,
  788. flag = wx.EXPAND)
  789. self.label_id.append(title_txt.GetId())
  790. # title expansion
  791. if p.get('multiple', False) and len(p.get('values','')) == 0:
  792. title = _("[multiple]") + " " + title
  793. if p.get('value','') == '' :
  794. p['value'] = p.get('default','')
  795. if (len(p.get('values', [])) > 0):
  796. valuelist = map(str, p.get('values',[]))
  797. valuelist_desc = map(unicode, p.get('values_desc',[]))
  798. if p.get('multiple', False) and \
  799. p.get('gisprompt',False) == False and \
  800. p.get('type', '') == 'string':
  801. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  802. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  803. if valuelist_desc:
  804. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  805. else:
  806. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  807. isEnabled = {}
  808. # copy default values
  809. if p['value'] == '':
  810. p['value'] = p.get('default', '')
  811. for defval in p.get('value', '').split(','):
  812. isEnabled[ defval ] = 'yes'
  813. # for multi checkboxes, this is an array of all wx IDs
  814. # for each individual checkbox
  815. p[ 'wxId' ] = list()
  816. idx = 0
  817. for val in valuelist:
  818. try:
  819. label = valuelist_desc[idx]
  820. except IndexError:
  821. label = val
  822. chkbox = wx.CheckBox(parent = which_panel,
  823. label = text_beautify(label))
  824. p[ 'wxId' ].append(chkbox.GetId())
  825. if val in isEnabled:
  826. chkbox.SetValue(True)
  827. hSizer.Add(item = chkbox, proportion = 0)
  828. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  829. idx += 1
  830. stSizer.Add(item = hSizer, proportion = 0,
  831. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  832. which_sizer.Add(item = stSizer, proportion = 0,
  833. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  834. elif p.get('gisprompt', False) == False:
  835. if len(valuelist) == 1: # -> textctrl
  836. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  837. str(valuelist[0])))
  838. if p.get('type', '') == 'integer' and \
  839. not p.get('multiple', False):
  840. # for multiple integers use textctrl instead of spinsctrl
  841. try:
  842. minValue, maxValue = map(int, valuelist[0].split('-'))
  843. except ValueError:
  844. minValue = -1e6
  845. maxValue = 1e6
  846. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  847. min = minValue, max = maxValue)
  848. txt2.SetName("SpinCtrl")
  849. style = wx.BOTTOM | wx.LEFT
  850. else:
  851. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  852. txt2.SetName("TextCtrl")
  853. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  854. value = self._getValue(p)
  855. # parameter previously set
  856. if value:
  857. if txt2.GetName() == "SpinCtrl":
  858. txt2.SetValue(int(value))
  859. else:
  860. txt2.SetValue(value)
  861. which_sizer.Add(item = txt2, proportion = 0,
  862. flag = style, border = 5)
  863. p['wxId'] = [ txt2.GetId(), ]
  864. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  865. else:
  866. title_txt.SetLabel(title + ':')
  867. value = self._getValue(p)
  868. if p['name'] == 'icon': # symbols
  869. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  870. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  871. bitmap = bitmap)
  872. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  873. iconLabel.SetLabel(value)
  874. p['value'] = value
  875. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  876. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  877. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  878. this_sizer.Add(item = bb, proportion = 0,
  879. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  880. this_sizer.Add(item = iconLabel, proportion = 0,
  881. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  882. which_sizer.Add(item = this_sizer, proportion = 0,
  883. flag = wx.ADJUST_MINSIZE, border = 0)
  884. else:
  885. # list of values (combo)
  886. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  887. size = globalvar.DIALOG_COMBOBOX_SIZE,
  888. choices = valuelist, style = wx.CB_DROPDOWN)
  889. if value:
  890. cb.SetValue(value) # parameter previously set
  891. which_sizer.Add(item = cb, proportion = 0,
  892. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  893. p['wxId'] = [cb.GetId(),]
  894. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  895. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  896. if p.get('guidependency', ''):
  897. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  898. # text entry
  899. if (p.get('type','string') in ('string','integer','float')
  900. and len(p.get('values',[])) == 0
  901. and p.get('gisprompt',False) == False
  902. and p.get('prompt','') != 'color'):
  903. title_txt.SetLabel(title + ':')
  904. if p.get('multiple', False) or \
  905. p.get('type', 'string') == 'string' or \
  906. len(p.get('key_desc', [])) > 1:
  907. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  908. value = self._getValue(p)
  909. if value:
  910. # parameter previously set
  911. txt3.SetValue(str(value))
  912. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  913. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  914. else:
  915. minValue = -1e9
  916. maxValue = 1e9
  917. if p.get('type', '') == 'integer':
  918. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  919. size = globalvar.DIALOG_SPIN_SIZE,
  920. min = minValue, max = maxValue)
  921. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  922. value = self._getValue(p)
  923. if value:
  924. txt3.SetValue(int(value)) # parameter previously set
  925. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  926. else:
  927. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  928. validator = FloatValidator())
  929. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  930. value = self._getValue(p)
  931. if value:
  932. txt3.SetValue(str(value)) # parameter previously set
  933. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  934. which_sizer.Add(item = txt3, proportion = 0,
  935. flag = style, border = 5)
  936. p['wxId'] = [ txt3.GetId(), ]
  937. #
  938. # element selection tree combobox (maps, icons, regions, etc.)
  939. #
  940. if p.get('gisprompt', False):
  941. title_txt.SetLabel(title + ':')
  942. # GIS element entry
  943. if p.get('prompt','') not in ('color',
  944. 'color_none',
  945. 'subgroup',
  946. 'sigfile',
  947. 'dbdriver',
  948. 'dbname',
  949. 'dbtable',
  950. 'dbcolumn',
  951. 'layer',
  952. 'layer_all',
  953. 'location',
  954. 'mapset',
  955. 'dbase',
  956. 'coords') and \
  957. p.get('element', '') not in ('file', 'dir'):
  958. multiple = p.get('multiple', False)
  959. if p.get('age', '') == 'new':
  960. mapsets = [grass.gisenv()['MAPSET'],]
  961. else:
  962. mapsets = None
  963. if self.task.name in ('r.proj', 'v.proj') \
  964. and p.get('name', '') == 'input':
  965. if self.task.name == 'r.proj':
  966. isRaster = True
  967. else:
  968. isRaster = False
  969. selection = gselect.ProjSelect(parent = which_panel,
  970. isRaster = isRaster)
  971. p['wxId'] = [ selection.GetId(), ]
  972. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  973. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  974. else:
  975. elem = p.get('element', None)
  976. # hack for t.* modules
  977. if elem in ('stds', 'map'):
  978. orig_elem = elem
  979. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  980. if type_param:
  981. elem = type_param.get('default', None)
  982. # for t.(un)register:
  983. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  984. if maps_param and orig_elem == 'stds':
  985. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  986. elem = element_dict[type_param.get('default')]
  987. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  988. size = globalvar.DIALOG_GSELECT_SIZE,
  989. type = elem,
  990. multiple = multiple, nmaps = len(p.get('key_desc', [])),
  991. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old')
  992. value = self._getValue(p)
  993. if value:
  994. selection.SetValue(value)
  995. formatSelector = True
  996. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  997. # we target the textctl here
  998. textWin = selection.GetTextCtrl()
  999. p['wxId'] = [ textWin.GetId(), ]
  1000. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1001. if prompt == 'vector':
  1002. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1003. # if formatSelector and p.get('age', 'old') == 'old':
  1004. # # OGR supported (read-only)
  1005. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1006. # self.hsizer.Add(item = selection,
  1007. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1008. # border = 5)
  1009. # # format (native / ogr)
  1010. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1011. # label = " %s " % _("Format"),
  1012. # style = wx.RA_SPECIFY_ROWS,
  1013. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1014. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1015. # rbox.SetSelection(1)
  1016. # rbox.SetName('VectorFormat')
  1017. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1018. # self.hsizer.Add(item = rbox,
  1019. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1020. # wx.RIGHT | wx.ALIGN_TOP,
  1021. # border = 5)
  1022. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1023. # default = 'dir',
  1024. # exclude = ['file'])
  1025. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1026. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1027. # ogrSelection.SetName('OgrSelect')
  1028. # ogrSelection.Hide()
  1029. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1030. # p['wxId'].append(rbox.GetId())
  1031. # p['wxId'].append(ogrSelection.GetId())
  1032. # for win in ogrSelection.GetDsnWin():
  1033. # p['wxId'].append(win.GetId())
  1034. # else:
  1035. which_sizer.Add(item = selection, proportion = 0,
  1036. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1037. border = 5)
  1038. elif prompt == 'group':
  1039. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1040. which_sizer.Add(item = selection, proportion = 0,
  1041. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1042. border = 5)
  1043. else:
  1044. which_sizer.Add(item = selection, proportion = 0,
  1045. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1046. border = 5)
  1047. # subgroup
  1048. elif prompt == 'subgroup':
  1049. selection = gselect.SubGroupSelect(parent = which_panel)
  1050. p['wxId'] = [ selection.GetId() ]
  1051. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1052. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1053. which_sizer.Add(item = selection, proportion = 0,
  1054. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1055. border = 5)
  1056. # sigrature file
  1057. elif prompt == 'sigfile':
  1058. selection = gselect.SignatureSelect(parent = which_panel)
  1059. p['wxId'] = [ selection.GetId() ]
  1060. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1061. which_sizer.Add(item = selection, proportion = 0,
  1062. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1063. border = 5)
  1064. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1065. elif prompt in ('dbdriver',
  1066. 'dbname',
  1067. 'dbtable',
  1068. 'dbcolumn',
  1069. 'layer',
  1070. 'layer_all',
  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 in ('layer', 'layer_all'):
  1081. if prompt == '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. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1123. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1124. elif prompt == 'location':
  1125. win = gselect.LocationSelect(parent = which_panel,
  1126. value = value)
  1127. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1128. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1129. elif prompt == 'mapset':
  1130. if p.get('age', 'old') == 'old':
  1131. new = False
  1132. else:
  1133. new = True
  1134. win = gselect.MapsetSelect(parent = which_panel,
  1135. value = value, new = new)
  1136. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1137. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1138. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1139. elif prompt == 'dbase':
  1140. win = gselect.DbaseSelect(parent = which_panel,
  1141. changeCallback = self.OnSetValue)
  1142. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1143. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1144. if 'wxId' not in p:
  1145. try:
  1146. p['wxId'] = [ win.GetId(), ]
  1147. except AttributeError:
  1148. pass
  1149. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1150. if prompt == 'dbname':
  1151. flags |= wx.EXPAND
  1152. which_sizer.Add(item = win, proportion = 0,
  1153. flag = flags, border = 5)
  1154. # color entry
  1155. elif prompt in ('color',
  1156. 'color_none'):
  1157. default_color = (200,200,200)
  1158. label_color = _("Select Color")
  1159. if p.get('default','') != '':
  1160. default_color, label_color = utils.color_resolve(p['default'])
  1161. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1162. default_color, label_color = utils.color_resolve(p['value'])
  1163. if prompt == 'color_none':
  1164. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1165. else:
  1166. this_sizer = which_sizer
  1167. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1168. label = label_color, colour = default_color,
  1169. pos = wx.DefaultPosition, size = (150,-1))
  1170. this_sizer.Add(item = btn_colour, proportion = 0,
  1171. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1172. # For color selectors, this is a two-member array, holding the IDs of
  1173. # the selector proper and either a "transparent" button or None
  1174. p['wxId'] = [btn_colour.GetId(),]
  1175. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1176. if prompt == 'color_none':
  1177. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1178. if p.get('value','') == "none":
  1179. none_check.SetValue(True)
  1180. else:
  1181. none_check.SetValue(False)
  1182. this_sizer.Add(item = none_check, proportion = 0,
  1183. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1184. which_sizer.Add(this_sizer)
  1185. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1186. p['wxId'].append(none_check.GetId())
  1187. else:
  1188. p['wxId'].append(None)
  1189. # file selector
  1190. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1191. if p.get('age', 'new') == 'new':
  1192. fmode = wx.SAVE
  1193. else:
  1194. fmode = wx.OPEN
  1195. # check wildcard
  1196. try:
  1197. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1198. except:
  1199. fExt = None
  1200. if not fExt:
  1201. fMask = '*.*'
  1202. else:
  1203. fMask = '%s files (*%s)|*%s|Files (*.*)|*.*' % (fExt[1:].upper(), fExt, fExt)
  1204. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1205. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1206. dialogTitle = _('Choose %s') % \
  1207. p.get('description', _('file')).lower(),
  1208. buttonText = _('Browse'),
  1209. startDirectory = os.getcwd(), fileMode = fmode,
  1210. changeCallback = self.OnSetValue)
  1211. value = self._getValue(p)
  1212. if value:
  1213. fbb.SetValue(value) # parameter previously set
  1214. which_sizer.Add(item = fbb, proportion = 0,
  1215. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1216. # A file browse button is a combobox with two children:
  1217. # a textctl and a button;
  1218. # we have to target the button here
  1219. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1220. if p.get('age', 'new') == 'old' and \
  1221. p.get('prompt', 'input') == 'input' and \
  1222. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1223. # widget for interactive input
  1224. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1225. style = wx.TE_MULTILINE,
  1226. size = (-1, 75))
  1227. if p.get('value', '') and os.path.isfile(p['value']):
  1228. f = open(p['value'])
  1229. ifbb.SetValue(''.join(f.readlines()))
  1230. f.close()
  1231. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1232. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1233. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1234. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVEAS)
  1235. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1236. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1237. label = _('or enter values interactively')),
  1238. proportion = 0,
  1239. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1240. which_sizer.Add(item = ifbb, proportion = 1,
  1241. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1242. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1243. btnSizer.Add(item = btnLoad, proportion = 0,
  1244. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1245. btnSizer.Add(item = btnSave, proportion = 0,
  1246. flag = wx.ALIGN_RIGHT)
  1247. which_sizer.Add(item = btnSizer, proportion = 0,
  1248. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1249. p['wxId'].append(ifbb.GetId())
  1250. p['wxId'].append(btnLoad.GetId())
  1251. p['wxId'].append(btnSave.GetId())
  1252. # directory selector
  1253. elif p.get('prompt','') != 'color' and p.get('element', '') == 'dir':
  1254. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1255. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1256. dialogTitle = _('Choose %s') % \
  1257. p.get('description', _('Directory')),
  1258. buttonText = _('Browse'),
  1259. startDirectory = os.getcwd(),
  1260. changeCallback = self.OnSetValue)
  1261. value = self._getValue(p)
  1262. if value:
  1263. fbb.SetValue(value) # parameter previously set
  1264. which_sizer.Add(item = fbb, proportion = 0,
  1265. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1266. # A file browse button is a combobox with two children:
  1267. # a textctl and a button;
  1268. # we have to target the button here
  1269. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1270. # interactive inserting of coordinates from map window
  1271. elif prompt == 'coords':
  1272. # interactive inserting if layer manager is accessible
  1273. if self._giface:
  1274. win = gselect.CoordinatesSelect(parent = which_panel,
  1275. giface = self._giface,
  1276. multiple = p.get('multiple', False),
  1277. param = p)
  1278. p['wxId'] = [win.GetTextWin().GetId()]
  1279. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1280. # normal text field
  1281. else:
  1282. win = wx.TextCtrl(parent = which_panel)
  1283. p['wxId'] = [win.GetId()]
  1284. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1285. which_sizer.Add(item = win,
  1286. proportion = 0,
  1287. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1288. border = 5)
  1289. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1290. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1291. label = _("Parameterized in model"))
  1292. parChk.SetName('ModelParam')
  1293. parChk.SetValue(p.get('parameterized', False))
  1294. if 'wxId' in p:
  1295. p['wxId'].append(parChk.GetId())
  1296. else:
  1297. p['wxId'] = [ parChk.GetId() ]
  1298. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1299. which_sizer.Add(item = parChk, proportion = 0,
  1300. flag = wx.LEFT, border = 20)
  1301. if title_txt is not None:
  1302. # create tooltip if given
  1303. if len(p['values_desc']) > 0:
  1304. if tooltip:
  1305. tooltip += 2 * os.linesep
  1306. else:
  1307. tooltip = ''
  1308. if len(p['values']) == len(p['values_desc']):
  1309. for i in range(len(p['values'])):
  1310. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1311. tooltip.strip(os.linesep)
  1312. if tooltip:
  1313. title_txt.SetToolTipString(tooltip)
  1314. if p == first_param:
  1315. if 'wxId' in p and len(p['wxId']) > 0:
  1316. win = self.FindWindowById(p['wxId'][0])
  1317. win.SetFocus()
  1318. #
  1319. # set widget relations for OnUpdateSelection
  1320. #
  1321. pMap = None
  1322. pLayer = []
  1323. pDriver = None
  1324. pDatabase = None
  1325. pTable = None
  1326. pColumn = []
  1327. pGroup = None
  1328. pSubGroup = None
  1329. pSigFile = None
  1330. pDbase = None
  1331. pLocation = None
  1332. pMapset = None
  1333. for p in self.task.params:
  1334. guidep = p.get('guidependency', '')
  1335. if guidep:
  1336. # fixed options dependency defined
  1337. options = guidep.split(',')
  1338. for opt in options:
  1339. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1340. if id:
  1341. if 'wxId-bind' not in p:
  1342. p['wxId-bind'] = list()
  1343. p['wxId-bind'] += pOpt['wxId']
  1344. continue
  1345. if p.get('gisprompt', False) == False:
  1346. continue
  1347. prompt = p.get('element', '')
  1348. if prompt in ('cell', 'vector'):
  1349. name = p.get('name', '')
  1350. if name in ('map', 'input'):
  1351. pMap = p
  1352. elif prompt == 'layer':
  1353. pLayer.append(p)
  1354. elif prompt == 'dbcolumn':
  1355. pColumn.append(p)
  1356. elif prompt == 'dbdriver':
  1357. pDriver = p
  1358. elif prompt == 'dbname':
  1359. pDatabase = p
  1360. elif prompt == 'dbtable':
  1361. pTable = p
  1362. elif prompt == 'group':
  1363. pGroup = p
  1364. elif prompt == 'subgroup':
  1365. pSubGroup = p
  1366. elif prompt == 'sigfile':
  1367. pSigFile = p
  1368. elif prompt == 'dbase':
  1369. pDbase = p
  1370. elif prompt == 'location':
  1371. pLocation = p
  1372. elif prompt == 'mapset':
  1373. pMapset = p
  1374. # collect ids
  1375. pColumnIds = []
  1376. for p in pColumn:
  1377. pColumnIds += p['wxId']
  1378. pLayerIds = []
  1379. for p in pLayer:
  1380. pLayerIds += p['wxId']
  1381. # set wxId-bindings
  1382. if pMap:
  1383. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1384. if pLayer:
  1385. pMap['wxId-bind'] += pLayerIds
  1386. if pLayer:
  1387. for p in pLayer:
  1388. p['wxId-bind'] = copy.copy(pColumnIds)
  1389. if pDriver and pTable:
  1390. pDriver['wxId-bind'] = pTable['wxId']
  1391. if pDatabase and pTable:
  1392. pDatabase['wxId-bind'] = pTable['wxId']
  1393. if pTable and pColumnIds:
  1394. pTable['wxId-bind'] = pColumnIds
  1395. if pGroup and pSubGroup:
  1396. if pSigFile:
  1397. pGroup['wxId-bind'] = copy.copy(pSigFile['wxId']) + pSubGroup['wxId']
  1398. pSubGroup['wxId-bind'] = pSigFile['wxId']
  1399. else:
  1400. pGroup['wxId-bind'] = pSubGroup['wxId']
  1401. if pDbase and pLocation:
  1402. pDbase['wxId-bind'] = pLocation['wxId']
  1403. if pLocation and pMapset:
  1404. pLocation['wxId-bind'] = pMapset['wxId']
  1405. if pLocation and pMapset and pMap:
  1406. pLocation['wxId-bind'] += pMap['wxId']
  1407. pMapset['wxId-bind'] = pMap['wxId']
  1408. #
  1409. # determine panel size
  1410. #
  1411. maxsizes = (0, 0)
  1412. for section in sections:
  1413. tab[section].SetSizer(tabsizer[section])
  1414. tabsizer[section].Fit(tab[section])
  1415. tab[section].Layout()
  1416. minsecsizes = tabsizer[section].GetSize()
  1417. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1418. # TODO: be less arbitrary with these 600
  1419. self.panelMinHeight = 100
  1420. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1421. for section in sections:
  1422. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1423. # add pages to notebook
  1424. imageList = wx.ImageList(16, 16)
  1425. self.notebook.AssignImageList(imageList)
  1426. for section in sections:
  1427. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1428. index = self.AddBitmapToImageList(section, imageList)
  1429. if index >= 0:
  1430. self.notebook.SetPageImage(section, index)
  1431. # are we running from command line?
  1432. ### add 'command output' tab regardless standalone dialog
  1433. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1434. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1435. from gui_core.goutput import GConsoleWindow
  1436. self._gconsole = GConsole(guiparent = self.notebook)
  1437. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1438. self._gconsole.Bind(EVT_CMD_RUN,
  1439. lambda event:
  1440. self._switchPageHandler(event = event, priority = 2))
  1441. self._gconsole.Bind(EVT_CMD_DONE,
  1442. lambda event:
  1443. self._switchPageHandler(event = event, priority = 3))
  1444. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1445. index = self.AddBitmapToImageList(section = 'output', imageList = imageList)
  1446. if index >= 0:
  1447. self.notebook.SetPageImage('output', index)
  1448. else:
  1449. self.goutput = None
  1450. self._gconsole = None
  1451. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.name)
  1452. if not self.manualTab.GetFile():
  1453. self.manualTab.Hide()
  1454. else:
  1455. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1456. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1457. if index >= 0:
  1458. self.notebook.SetPageImage('manual', index)
  1459. if self.manualTab.IsLoaded():
  1460. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1461. self.notebook.SetSelection(0)
  1462. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1463. self.SetSizer(panelsizer)
  1464. panelsizer.Fit(self.notebook)
  1465. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1466. def _getValue(self, p):
  1467. """!Get value or default value of given parameter
  1468. @param p parameter directory
  1469. """
  1470. if p.get('value', '') != '':
  1471. return p['value']
  1472. return p.get('default', '')
  1473. def OnFileLoad(self, event):
  1474. """!Load file to interactive input"""
  1475. me = event.GetId()
  1476. win = dict()
  1477. for p in self.task.params:
  1478. if 'wxId' in p and me in p['wxId']:
  1479. win['file'] = self.FindWindowById(p['wxId'][0])
  1480. win['text'] = self.FindWindowById(p['wxId'][1])
  1481. break
  1482. if not win:
  1483. return
  1484. path = win['file'].GetValue()
  1485. if not path:
  1486. gcmd.GMessage(parent = self,
  1487. message = _("Nothing to load."))
  1488. return
  1489. data = ''
  1490. f = open(path, "r")
  1491. try:
  1492. data = f.read()
  1493. finally:
  1494. f.close()
  1495. win['text'].SetValue(data)
  1496. def OnFileSave(self, event):
  1497. """!Save interactive input to the file"""
  1498. wId = event.GetId()
  1499. win = {}
  1500. for p in self.task.params:
  1501. if wId in p.get('wxId', []):
  1502. win['file'] = self.FindWindowById(p['wxId'][0])
  1503. win['text'] = self.FindWindowById(p['wxId'][1])
  1504. break
  1505. if not win:
  1506. return
  1507. text = win['text'].GetValue()
  1508. if not text:
  1509. gcmd.GMessage(parent = self,
  1510. message = _("Nothing to save."))
  1511. return
  1512. dlg = wx.FileDialog(parent = self,
  1513. message = _("Save input as..."),
  1514. defaultDir = os.getcwd(),
  1515. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1516. if dlg.ShowModal() == wx.ID_OK:
  1517. path = dlg.GetPath()
  1518. enc = locale.getdefaultlocale()[1]
  1519. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1520. try:
  1521. f.write(text + os.linesep)
  1522. finally:
  1523. f.close()
  1524. win['file'].SetValue(path)
  1525. dlg.Destroy()
  1526. def OnFileText(self, event):
  1527. """File input interactively entered"""
  1528. text = event.GetString()
  1529. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1530. if not p:
  1531. return # should not happen
  1532. win = self.FindWindowById(p['wxId'][0])
  1533. if text:
  1534. filename = win.GetValue()
  1535. if not filename:
  1536. filename = grass.tempfile()
  1537. win.SetValue(filename)
  1538. enc = locale.getdefaultlocale()[1]
  1539. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1540. try:
  1541. f.write(text)
  1542. if text[-1] != os.linesep:
  1543. f.write(os.linesep)
  1544. finally:
  1545. f.close()
  1546. else:
  1547. win.SetValue('')
  1548. def OnVectorFormat(self, event):
  1549. """!Change vector format (native / ogr).
  1550. Currently unused.
  1551. """
  1552. sel = event.GetSelection()
  1553. idEvent = event.GetId()
  1554. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1555. if not p:
  1556. return # should not happen
  1557. # detect windows
  1558. winNative = None
  1559. winOgr = None
  1560. for id in p['wxId']:
  1561. if id == idEvent:
  1562. continue
  1563. name = self.FindWindowById(id).GetName()
  1564. if name == 'Select':
  1565. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1566. elif name == 'OgrSelect':
  1567. winOgr = self.FindWindowById(id)
  1568. # enable / disable widgets & update values
  1569. rbox = self.FindWindowByName('VectorFormat')
  1570. self.hsizer.Remove(rbox)
  1571. if sel == 0: # -> native
  1572. winOgr.Hide()
  1573. self.hsizer.Remove(winOgr)
  1574. self.hsizer.Add(item = winNative,
  1575. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1576. border = 5)
  1577. winNative.Show()
  1578. p['value'] = winNative.GetValue()
  1579. elif sel == 1: # -> OGR
  1580. sizer = wx.BoxSizer(wx.VERTICAL)
  1581. winNative.Hide()
  1582. self.hsizer.Remove(winNative)
  1583. sizer.Add(item = winOgr)
  1584. winOgr.Show()
  1585. p['value'] = winOgr.GetDsn()
  1586. self.hsizer.Add(item = sizer,
  1587. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1588. border = 5)
  1589. self.hsizer.Add(item = rbox,
  1590. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1591. wx.RIGHT | wx.ALIGN_TOP,
  1592. border = 5)
  1593. self.hsizer.Layout()
  1594. self.Layout()
  1595. self.OnUpdateValues()
  1596. self.OnUpdateSelection(event)
  1597. def OnUpdateDialog(self, event):
  1598. for fn, kwargs in event.data.iteritems():
  1599. fn(**kwargs)
  1600. self.parent.updateValuesHook()
  1601. def OnVerbosity(self, event):
  1602. """!Verbosity level changed"""
  1603. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1604. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1605. if event.IsChecked():
  1606. if event.GetId() == verbose.GetId():
  1607. if quiet.IsChecked():
  1608. quiet.SetValue(False)
  1609. self.task.get_flag('quiet')['value'] = False
  1610. else:
  1611. if verbose.IsChecked():
  1612. verbose.SetValue(False)
  1613. self.task.get_flag('verbose')['value'] = False
  1614. event.Skip()
  1615. def OnPageChange(self, event):
  1616. if not event:
  1617. sel = self.notebook.GetSelection()
  1618. else:
  1619. sel = event.GetSelection()
  1620. idx = self.notebook.GetPageIndexByName('manual')
  1621. if idx > -1 and sel == idx:
  1622. # calling LoadPage() is strangely time-consuming (only first call)
  1623. # FIXME: move to helpPage.__init__()
  1624. if not self.manualTab.IsLoaded():
  1625. wx.Yield()
  1626. self.manualTab.LoadPage()
  1627. self.Layout()
  1628. if event:
  1629. # skip is needed for wx.Notebook on Windows
  1630. event.Skip()
  1631. # this is needed for dialogs launched from layer manager
  1632. # event is somehow propagated?
  1633. event.StopPropagation()
  1634. def _switchPageHandler(self, event, priority):
  1635. self._switchPage(priority = priority)
  1636. event.Skip()
  1637. def _switchPage(self, priority):
  1638. """!Manages @c 'output' notebook page according to event priority."""
  1639. if priority == 1:
  1640. self.notebook.HighlightPageByName('output')
  1641. if priority >= 2:
  1642. self.notebook.SetSelectionByName('output')
  1643. if priority >= 3:
  1644. self.SetFocus()
  1645. self.Raise()
  1646. def OnColorChange(self, event):
  1647. myId = event.GetId()
  1648. for p in self.task.params:
  1649. if 'wxId' in p and myId in p['wxId']:
  1650. has_button = p['wxId'][1] is not None
  1651. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1652. p[ 'value' ] = 'none'
  1653. else:
  1654. colorchooser = wx.FindWindowById(p['wxId'][0])
  1655. new_color = colorchooser.GetValue()[:]
  1656. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1657. # under wx2.8.1
  1658. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1659. colorchooser.SetLabel(new_label)
  1660. colorchooser.SetColour(new_color)
  1661. colorchooser.Refresh()
  1662. p[ 'value' ] = colorchooser.GetLabel()
  1663. self.OnUpdateValues()
  1664. def OnUpdateValues(self, event = None):
  1665. """!If we were part of a richer interface, report back the
  1666. current command being built.
  1667. This method should be set by the parent of this panel if
  1668. needed. It's a hook, actually. Beware of what is 'self' in
  1669. the method def, though. It will be called with no arguments.
  1670. """
  1671. pass
  1672. def OnCheckBoxMulti(self, event):
  1673. """!Fill the values as a ','-separated string according to
  1674. current status of the checkboxes.
  1675. """
  1676. me = event.GetId()
  1677. theParam = None
  1678. for p in self.task.params:
  1679. if 'wxId' in p and me in p['wxId']:
  1680. theParam = p
  1681. myIndex = p['wxId'].index(me)
  1682. # Unpack current value list
  1683. currentValues = {}
  1684. for isThere in theParam.get('value', '').split(','):
  1685. currentValues[isThere] = 1
  1686. theValue = theParam['values'][myIndex]
  1687. if event.Checked():
  1688. currentValues[ theValue ] = 1
  1689. else:
  1690. del currentValues[ theValue ]
  1691. # Keep the original order, so that some defaults may be recovered
  1692. currentValueList = []
  1693. for v in theParam['values']:
  1694. if v in currentValues:
  1695. currentValueList.append(v)
  1696. # Pack it back
  1697. theParam['value'] = ','.join(currentValueList)
  1698. self.OnUpdateValues()
  1699. def OnSetValue(self, event):
  1700. """!Retrieve the widget value and set the task value field
  1701. accordingly.
  1702. Use for widgets that have a proper GetValue() method, i.e. not
  1703. for selectors.
  1704. """
  1705. myId = event.GetId()
  1706. me = wx.FindWindowById(myId)
  1707. name = me.GetName()
  1708. found = False
  1709. for porf in self.task.params + self.task.flags:
  1710. if 'wxId' not in porf:
  1711. continue
  1712. if myId in porf['wxId']:
  1713. found = True
  1714. break
  1715. if not found:
  1716. return
  1717. if name == 'GdalSelect':
  1718. porf['value'] = event.dsn
  1719. elif name == 'ModelParam':
  1720. porf['parameterized'] = me.IsChecked()
  1721. else:
  1722. porf['value'] = me.GetValue()
  1723. self.OnUpdateValues(event)
  1724. event.Skip()
  1725. def OnSetSymbol(self, event):
  1726. """!Shows dialog for symbol selection"""
  1727. myId = event.GetId()
  1728. for p in self.task.params:
  1729. if 'wxId' in p and myId in p['wxId']:
  1730. from gui_core.dialogs import SymbolDialog
  1731. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1732. currentSymbol = p['value'])
  1733. if dlg.ShowModal() == wx.ID_OK:
  1734. img = dlg.GetSelectedSymbolPath()
  1735. p['value'] = dlg.GetSelectedSymbolName()
  1736. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1737. label = wx.FindWindowById(p['wxId'][1])
  1738. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1739. label.SetLabel(p['value'])
  1740. self.OnUpdateValues(event)
  1741. dlg.Destroy()
  1742. def OnUpdateSelection(self, event):
  1743. """!Update dialog (layers, tables, columns, etc.)
  1744. """
  1745. if not hasattr(self.parent, "updateThread"):
  1746. if event:
  1747. event.Skip()
  1748. return
  1749. if event:
  1750. self.parent.updateThread.Update(UpdateDialog,
  1751. self,
  1752. event,
  1753. event.GetId(),
  1754. self.task)
  1755. else:
  1756. self.parent.updateThread.Update(UpdateDialog,
  1757. self,
  1758. None,
  1759. None,
  1760. self.task)
  1761. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1762. """!Produce a command line string (list) or feeding into GRASS.
  1763. @param ignoreErrors True then it will return whatever has been
  1764. built so far, even though it would not be a correct command
  1765. for GRASS
  1766. """
  1767. try:
  1768. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1769. ignoreRequired = ignoreRequired)
  1770. except ValueError, err:
  1771. dlg = wx.MessageDialog(parent = self,
  1772. message = unicode(err),
  1773. caption = _("Error in %s") % self.task.name,
  1774. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1775. dlg.ShowModal()
  1776. dlg.Destroy()
  1777. cmd = None
  1778. return cmd
  1779. def OnSize(self, event):
  1780. width = event.GetSize()[0]
  1781. fontsize = self.GetFont().GetPointSize()
  1782. text_width = max(width / (fontsize - 3), 70)
  1783. for id in self.label_id:
  1784. win = self.FindWindowById(id)
  1785. label = win.GetLabel()
  1786. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1787. win.SetLabel(label_new)
  1788. event.Skip()
  1789. def AddBitmapToImageList(self, section, imageList):
  1790. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1791. iconSectionDict = {'manual': os.path.join(globalvar.ETCICONDIR, iconTheme, 'help.png'),
  1792. _("Optional"): os.path.join(globalvar.ETCICONDIR, iconTheme, 'settings.png')}
  1793. if section in iconSectionDict.keys():
  1794. bitmap = wx.Bitmap(iconSectionDict[section])
  1795. bitmap.SetSize((16, 16))
  1796. idx = imageList.Add(bitmap)
  1797. return idx
  1798. return -1
  1799. class GUI:
  1800. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1801. centreOnParent = False, checkError = False):
  1802. """!Parses GRASS commands when module is imported and used from
  1803. Layer Manager.
  1804. """
  1805. self.parent = parent
  1806. self.show = show
  1807. self.modal = modal
  1808. self._giface = giface
  1809. self.centreOnParent = centreOnParent
  1810. self.checkError = checkError
  1811. self.grass_task = None
  1812. self.cmd = list()
  1813. global _blackList
  1814. if self.parent:
  1815. _blackList['enabled'] = True
  1816. else:
  1817. _blackList['enabled'] = False
  1818. def GetCmd(self):
  1819. """!Get validated command"""
  1820. return self.cmd
  1821. def ParseCommand(self, cmd, completed = None):
  1822. """!Parse command
  1823. Note: cmd is given as list
  1824. If command is given with options, return validated cmd list:
  1825. - add key name for first parameter if not given
  1826. - change mapname to mapname@mapset
  1827. """
  1828. dcmd_params = {}
  1829. if completed == None:
  1830. get_dcmd = None
  1831. layer = None
  1832. dcmd_params = None
  1833. else:
  1834. get_dcmd = completed[0]
  1835. layer = completed[1]
  1836. if completed[2]:
  1837. dcmd_params.update(completed[2])
  1838. # parse the interface decription
  1839. try:
  1840. global _blackList
  1841. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1842. blackList = _blackList)
  1843. except (grass.ScriptError, ValueError), e:
  1844. raise gcmd.GException(e.value)
  1845. # if layer parameters previously set, re-insert them into dialog
  1846. if completed is not None:
  1847. if 'params' in dcmd_params:
  1848. self.grass_task.params = dcmd_params['params']
  1849. if 'flags' in dcmd_params:
  1850. self.grass_task.flags = dcmd_params['flags']
  1851. err = list()
  1852. # update parameters if needed && validate command
  1853. if len(cmd) > 1:
  1854. i = 0
  1855. cmd_validated = [cmd[0]]
  1856. for option in cmd[1:]:
  1857. if option[0] == '-': # flag
  1858. if option[1] == '-':
  1859. self.grass_task.set_flag(option[2:], True)
  1860. else:
  1861. self.grass_task.set_flag(option[1], True)
  1862. cmd_validated.append(option)
  1863. else: # parameter
  1864. try:
  1865. key, value = option.split('=', 1)
  1866. except ValueError:
  1867. if self.grass_task.firstParam:
  1868. if i == 0: # add key name of first parameter if not given
  1869. key = self.grass_task.firstParam
  1870. value = option
  1871. else:
  1872. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1873. else:
  1874. continue
  1875. element = self.grass_task.get_param(key, raiseError = False)
  1876. if not element:
  1877. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1878. { 'cmd' : cmd[0],
  1879. 'key' : key })
  1880. continue
  1881. element = element['element']
  1882. if element in ['cell', 'vector']:
  1883. # mapname -> mapname@mapset
  1884. try:
  1885. name, mapset = value.split('@')
  1886. except ValueError:
  1887. mapset = grass.find_file(value, element)['mapset']
  1888. curr_mapset = grass.gisenv()['MAPSET']
  1889. if mapset and mapset != curr_mapset:
  1890. value = value + '@' + mapset
  1891. self.grass_task.set_param(key, value)
  1892. cmd_validated.append(key + '=' + value)
  1893. i += 1
  1894. # update original command list
  1895. cmd = cmd_validated
  1896. if self.show is not None:
  1897. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  1898. task_description = self.grass_task,
  1899. get_dcmd = get_dcmd, layer = layer)
  1900. else:
  1901. self.mf = None
  1902. if get_dcmd is not None:
  1903. # update only propwin reference
  1904. get_dcmd(dcmd = None, layer = layer, params = None,
  1905. propwin = self.mf)
  1906. if self.show is not None:
  1907. self.mf.notebookpanel.OnUpdateSelection(None)
  1908. if self.show is True:
  1909. if self.parent and self.centreOnParent:
  1910. self.mf.CentreOnParent()
  1911. else:
  1912. self.mf.CenterOnScreen()
  1913. self.mf.Show(self.show)
  1914. self.mf.MakeModal(self.modal)
  1915. else:
  1916. self.mf.OnApply(None)
  1917. self.cmd = cmd
  1918. if self.checkError:
  1919. return self.grass_task, err
  1920. else:
  1921. return self.grass_task
  1922. def GetCommandInputMapParamKey(self, cmd):
  1923. """!Get parameter key for input raster/vector map
  1924. @param cmd module name
  1925. @return parameter key
  1926. @return None on failure
  1927. """
  1928. # parse the interface decription
  1929. if not self.grass_task:
  1930. enc = locale.getdefaultlocale()[1]
  1931. if enc and enc.lower() == "cp932":
  1932. p = re.compile('encoding="' + enc + '"', re.IGNORECASE)
  1933. tree = etree.fromstring(p.sub('encoding="utf-8"',
  1934. gtask.get_interface_description(cmd).decode(enc).encode('utf-8')))
  1935. else:
  1936. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1937. self.grass_task = gtask.processTask(tree).get_task()
  1938. for p in self.grass_task.params:
  1939. if p.get('name', '') in ('input', 'map'):
  1940. age = p.get('age', '')
  1941. prompt = p.get('prompt', '')
  1942. element = p.get('element', '')
  1943. if age == 'old' and \
  1944. element in ('cell', 'grid3', 'vector') and \
  1945. prompt in ('raster', '3d-raster', 'vector'):
  1946. return p.get('name', None)
  1947. return None
  1948. class GrassGUIApp(wx.App):
  1949. """!Stand-alone GRASS command GUI
  1950. """
  1951. def __init__(self, grass_task):
  1952. self.grass_task = grass_task
  1953. wx.App.__init__(self, False)
  1954. def OnInit(self):
  1955. msg = self.grass_task.get_error_msg()
  1956. if msg:
  1957. gcmd.GError(msg + '\n\n' +
  1958. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  1959. return True
  1960. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  1961. self.mf.CentreOnScreen()
  1962. self.mf.Show(True)
  1963. self.SetTopWindow(self.mf)
  1964. return True
  1965. if __name__ == "__main__":
  1966. import gettext
  1967. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1968. if len(sys.argv) == 1:
  1969. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1970. if sys.argv[1] != 'test':
  1971. q = wx.LogNull()
  1972. cmd = utils.split(sys.argv[1])
  1973. task = gtask.grassTask(gcmd.GetRealCmd(cmd[0]))
  1974. task.set_options(cmd[1:])
  1975. app = GrassGUIApp(task)
  1976. app.MainLoop()
  1977. else: #Test
  1978. # Test grassTask from within a GRASS session
  1979. if os.getenv("GISBASE") is not None:
  1980. task = gtask.grassTask("d.vect")
  1981. task.get_param('map')['value'] = "map_name"
  1982. task.get_flag('v')['value'] = True
  1983. task.get_param('layer')['value'] = 1
  1984. task.get_param('bcolor')['value'] = "red"
  1985. assert ' '.join(task.get_cmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1986. # Test interface building with handmade grassTask,
  1987. # possibly outside of a GRASS session.
  1988. task = gtask.grassTask()
  1989. task.name = "TestTask"
  1990. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1991. task.keywords = ["grass","test","task"]
  1992. task.params = [
  1993. {
  1994. "name" : "text",
  1995. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1996. "label" : "Enter some text",
  1997. },{
  1998. "name" : "hidden_text",
  1999. "description" : "This text should not appear in the form",
  2000. "hidden" : True
  2001. },{
  2002. "name" : "text_default",
  2003. "description" : "Enter text to override the default",
  2004. "default" : "default text"
  2005. },{
  2006. "name" : "text_prefilled",
  2007. "description" : "You should see a friendly welcome message here",
  2008. "value" : "hello, world"
  2009. },{
  2010. "name" : "plain_color",
  2011. "description" : "This is a plain color, and it is a compulsory parameter",
  2012. "required" : False,
  2013. "gisprompt" : True,
  2014. "prompt" : "color"
  2015. },{
  2016. "name" : "transparent_color",
  2017. "description" : "This color becomes transparent when set to none",
  2018. "guisection" : "tab",
  2019. "gisprompt" : True,
  2020. "prompt" : "color"
  2021. },{
  2022. "name" : "multi",
  2023. "description" : "A multiple selection",
  2024. 'default': u'red,green,blue',
  2025. 'gisprompt': False,
  2026. 'guisection': 'tab',
  2027. 'multiple': u'yes',
  2028. 'type': u'string',
  2029. 'value': '',
  2030. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  2031. },{
  2032. "name" : "single",
  2033. "description" : "A single multiple-choice selection",
  2034. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2035. "guisection" : "tab"
  2036. },{
  2037. "name" : "large_multi",
  2038. "description" : "A large multiple selection",
  2039. "gisprompt" : False,
  2040. "multiple" : "yes",
  2041. # values must be an array of strings
  2042. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values())
  2043. },{
  2044. "name" : "a_file",
  2045. "description" : "A file selector",
  2046. "gisprompt" : True,
  2047. "element" : "file"
  2048. }
  2049. ]
  2050. task.flags = [
  2051. {
  2052. "name" : "a",
  2053. "description" : "Some flag, will appear in Main since it is required",
  2054. "required" : True
  2055. },{
  2056. "name" : "b",
  2057. "description" : "pre-filled flag, will appear in options since it is not required",
  2058. "value" : True
  2059. },{
  2060. "name" : "hidden_flag",
  2061. "description" : "hidden flag, should not be changeable",
  2062. "hidden" : "yes",
  2063. "value" : True
  2064. }
  2065. ]
  2066. q = wx.LogNull()
  2067. GrassGUIApp(task).MainLoop()