forms.py 103 KB

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