forms.py 111 KB

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