forms.py 110 KB

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