forms.py 115 KB

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