forms.py 101 KB

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