forms.py 109 KB

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