forms.py 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  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. self.dialogClosing = Signal('TaskFrame.dialogClosing')
  323. # module name + keywords
  324. title = self.task.get_name()
  325. try:
  326. if self.task.keywords != ['']:
  327. title += " [" + ', '.join(self.task.keywords) + "]"
  328. except ValueError:
  329. pass
  330. wx.Frame.__init__(self, parent = parent, id = id, title = title,
  331. name = "MainFrame", style = style, **kwargs)
  332. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  333. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  334. # statusbar
  335. self.CreateStatusBar()
  336. # icon
  337. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  338. guisizer = wx.BoxSizer(wx.VERTICAL)
  339. # set apropriate output window
  340. if self.parent:
  341. self.standalone = False
  342. else:
  343. self.standalone = True
  344. # logo + description
  345. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  346. # GRASS logo
  347. self.logo = wx.StaticBitmap(parent = self.panel,
  348. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  349. 'grass_form.png'),
  350. type = wx.BITMAP_TYPE_PNG))
  351. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  352. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  353. # add module description
  354. if self.task.label:
  355. module_desc = self.task.label + ' ' + self.task.description
  356. else:
  357. module_desc = self.task.description
  358. self.description = StaticWrapText(parent = self.panel,
  359. label = module_desc)
  360. topsizer.Add(item = self.description, proportion = 1, border = 5,
  361. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  362. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  363. self.panel.SetSizerAndFit(guisizer)
  364. self.Layout()
  365. # notebooks
  366. self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
  367. frame = self)
  368. self._gconsole = self.notebookpanel._gconsole
  369. if self._gconsole:
  370. self._gconsole.mapCreated.connect(self.OnMapCreated)
  371. self._gconsole.updateMap.connect(lambda: self._giface.updateMap.emit())
  372. self.goutput = self.notebookpanel.goutput
  373. if self.goutput:
  374. self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
  375. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  376. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  377. # status bar
  378. status_text = _("Enter parameters for '") + self.task.name + "'"
  379. try:
  380. self.task.get_cmd()
  381. self.updateValuesHook()
  382. except ValueError:
  383. self.SetStatusText(status_text)
  384. # buttons
  385. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  386. # cancel
  387. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  388. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  389. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  390. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  391. # bind closing to ESC and CTRL+Q
  392. self.Bind(wx.EVT_MENU, self.OnCancel, id=wx.ID_CLOSE)
  393. accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)]
  394. accelTableList = [(wx.ACCEL_CTRL, ord('Q'), wx.ID_CLOSE)]
  395. # TODO: bind Ctrl-t for tile windows here (trac #2004)
  396. if self.get_dcmd is not None: # A callback has been set up
  397. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  398. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  399. btn_ok.SetDefault()
  400. btnsizer.Add(item = btn_apply, proportion = 0,
  401. flag = wx.ALL | wx.ALIGN_CENTER,
  402. border = 10)
  403. btnsizer.Add(item = btn_ok, proportion = 0,
  404. flag = wx.ALL | wx.ALIGN_CENTER,
  405. border = 10)
  406. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  407. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  408. else: # We're standalone
  409. # run
  410. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  411. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  412. self.btn_run.SetDefault()
  413. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  414. # copy
  415. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY)
  416. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
  417. btnsizer.Add(item = self.btn_run, proportion = 0,
  418. flag = wx.ALL | wx.ALIGN_CENTER,
  419. border = 10)
  420. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  421. flag = wx.ALL | wx.ALIGN_CENTER,
  422. border = 10)
  423. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  424. self.Bind(wx.EVT_MENU, self.OnRun, id=wx.ID_OK)
  425. accelTableList.append((wx.ACCEL_CTRL, ord('R'), wx.ID_OK))
  426. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  427. # help
  428. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  429. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  430. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  431. self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
  432. accelTableList.append((wx.ACCEL_CTRL, ord('H'), wx.ID_HELP))
  433. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  434. self.btn_help.Hide()
  435. # add help button
  436. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  437. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  438. border = 30)
  439. # abort key bindings
  440. abortId = wx.NewId()
  441. self.Bind(wx.EVT_MENU, self.OnAbort, id=abortId)
  442. accelTableList.append((wx.ACCEL_CTRL, ord('S'), abortId))
  443. # set accelerator table
  444. accelTable = wx.AcceleratorTable(accelTableList)
  445. self.SetAcceleratorTable(accelTable)
  446. if self._giface and self._giface.GetLayerTree():
  447. addLayer = False
  448. for p in self.task.params:
  449. if p.get('age', 'old') == 'new' and \
  450. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  451. addLayer = True
  452. if addLayer:
  453. # add newly created map into layer tree
  454. self.addbox = wx.CheckBox(parent = self.panel,
  455. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  456. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  457. guisizer.Add(item = self.addbox, proportion = 0,
  458. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  459. border = 5)
  460. hasNew = False
  461. for p in self.task.params:
  462. if p.get('age', 'old') == 'new':
  463. hasNew = True
  464. break
  465. if self.get_dcmd is None and hasNew:
  466. # close dialog when command is terminated
  467. self.closebox = wx.CheckBox(parent = self.panel,
  468. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  469. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  470. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  471. "Change this settings in Preferences dialog ('Command' tab)."))
  472. guisizer.Add(item = self.closebox, proportion = 0,
  473. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  474. border = 5)
  475. # bindings
  476. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  477. # do layout
  478. # called automatically by SetSizer()
  479. self.panel.SetAutoLayout(True)
  480. self.panel.SetSizerAndFit(guisizer)
  481. sizeFrame = self.GetBestSize()
  482. self.SetMinSize(sizeFrame)
  483. if hasattr(self, "closebox"):
  484. scale = 0.33
  485. else:
  486. scale = 0.50
  487. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  488. self.notebookpanel.constrained_size[1])))
  489. # thread to update dialog
  490. # create queues
  491. self.requestQ = Queue.Queue()
  492. self.resultQ = Queue.Queue()
  493. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  494. self.Layout()
  495. # keep initial window size limited for small screens
  496. width, height = self.GetSizeTuple()
  497. self.SetSize(wx.Size(min(width, 650),
  498. min(height, 500)))
  499. # fix goutput's pane size (required for Mac OSX)
  500. if self.goutput:
  501. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  502. def updateValuesHook(self, event = None):
  503. """!Update status bar data"""
  504. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  505. if event:
  506. event.Skip()
  507. def OnDone(self, cmd, returncode):
  508. """!This function is launched from OnRun() when command is
  509. finished
  510. @param returncode command's return code (0 for success)
  511. """
  512. if hasattr(self, "btn_cancel"):
  513. self.btn_cancel.Enable(True)
  514. if hasattr(self, "btn_clipboard"):
  515. self.btn_clipboard.Enable(True)
  516. if hasattr(self, "btn_help"):
  517. self.btn_help.Enable(True)
  518. if hasattr(self, "btn_run"):
  519. self.btn_run.Enable(True)
  520. if hasattr(self, "get_dcmd") and \
  521. self.get_dcmd is None and \
  522. hasattr(self, "closebox") and \
  523. self.closebox.IsChecked() and \
  524. (returncode == 0):
  525. # was closed also when aborted but better is leave it open
  526. wx.FutureCall(2000, self.Close)
  527. def OnMapCreated(self, name, ltype):
  528. """!Map created or changed
  529. @param name map name
  530. @param ltype layer type (prompt value)
  531. """
  532. if hasattr(self, "addbox") and self.addbox.IsChecked():
  533. add = True
  534. else:
  535. add = False
  536. if self._giface:
  537. self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
  538. def OnOK(self, event):
  539. """!OK button pressed"""
  540. cmd = self.OnApply(event)
  541. if cmd is not None and self.get_dcmd is not None:
  542. self.OnCancel(event)
  543. def OnApply(self, event):
  544. """!Apply the command"""
  545. if self._giface and hasattr(self._giface, "_model"):
  546. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  547. else:
  548. cmd = self.createCmd()
  549. if cmd is not None and self.get_dcmd is not None:
  550. # return d.* command to layer tree for rendering
  551. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  552. "flags" : self.task.flags},
  553. self)
  554. # echo d.* command to output console
  555. # self.parent.writeDCommand(cmd)
  556. return cmd
  557. def OnRun(self, event):
  558. """!Run the command"""
  559. cmd = self.createCmd()
  560. if not cmd or len(cmd) < 1:
  561. return
  562. ret = 0
  563. if self.standalone or cmd[0][0:2] != "d.":
  564. # Send any non-display command to parent window (probably wxgui.py)
  565. # put to parents switch to 'Command output'
  566. self.notebookpanel.notebook.SetSelectionByName('output')
  567. try:
  568. if self.task.path:
  569. cmd[0] = self.task.path # full path
  570. ret = self._gconsole.RunCmd(cmd, onDone = self.OnDone)
  571. except AttributeError, e:
  572. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  573. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  574. else:
  575. gcmd.Command(cmd)
  576. if ret != 0:
  577. self.notebookpanel.notebook.SetSelection(0)
  578. return
  579. # update buttons status
  580. for btn in (self.btn_run,
  581. self.btn_cancel,
  582. self.btn_clipboard,
  583. self.btn_help):
  584. btn.Enable(False)
  585. def OnAbort(self, event):
  586. """!Abort running command"""
  587. from core.gconsole import wxCmdAbort
  588. event = wxCmdAbort(aborted = True)
  589. wx.PostEvent(self._gconsole, event)
  590. def OnCopy(self, event):
  591. """!Copy the command"""
  592. cmddata = wx.TextDataObject()
  593. # list -> string
  594. cmdlist = self.createCmd(ignoreErrors = True)
  595. # TODO: better protect whitespace with quotes
  596. for i in range(1, len(cmdlist)):
  597. if ' ' in cmdlist[i]:
  598. optname, val = cmdlist[i].split("=")
  599. cmdlist[i] = '%s="%s"' % (optname, val)
  600. cmdstring = ' '.join(cmdlist)
  601. cmddata.SetText(cmdstring)
  602. if wx.TheClipboard.Open():
  603. # wx.TheClipboard.UsePrimarySelection(True)
  604. wx.TheClipboard.SetData(cmddata)
  605. wx.TheClipboard.Close()
  606. self.SetStatusText(_("'%s' copied to clipboard") % \
  607. (cmdstring))
  608. def OnCancel(self, event):
  609. """!Cancel button pressed"""
  610. self.MakeModal(False)
  611. self.dialogClosing.emit()
  612. if self.get_dcmd and \
  613. self.parent and \
  614. self.parent.GetName() in ('LayerTree',
  615. 'MapWindow'):
  616. # display decorations and
  617. # pressing OK or cancel after setting layer properties
  618. if self.task.name in ['d.barscale','d.legend', 'd.northarrow', 'd.histogram'] \
  619. or len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) >= 1:
  620. self.Hide()
  621. # canceled layer with nothing set
  622. elif len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) < 1:
  623. self.parent.Delete(self.layer)
  624. self.Destroy()
  625. else:
  626. # cancel for non-display commands
  627. self.Destroy()
  628. def OnHelp(self, event):
  629. """!Show manual page (switch to the 'Manual' notebook page)"""
  630. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  631. self.notebookpanel.notebook.SetSelectionByName('manual')
  632. self.notebookpanel.OnPageChange(None)
  633. if event:
  634. event.Skip()
  635. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  636. """!Create command string (python list)"""
  637. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  638. ignoreRequired = ignoreRequired)
  639. class CmdPanel(wx.Panel):
  640. """!A panel containing a notebook dividing in tabs the different
  641. guisections of the GRASS cmd.
  642. """
  643. def __init__(self, parent, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
  644. if frame:
  645. self.parent = frame
  646. else:
  647. self.parent = parent
  648. self.task = task
  649. self._giface = giface
  650. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  651. self.mapCreated = Signal
  652. self.updateMap = Signal
  653. # Determine tab layout
  654. sections = []
  655. is_section = {}
  656. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  657. self.label_id = [] # wrap titles on resize
  658. self.Bind(wx.EVT_SIZE, self.OnSize)
  659. for task in not_hidden:
  660. if task.get('required', False):
  661. # All required go into Main, even if they had defined another guisection
  662. task['guisection'] = _('Required')
  663. if task.get('guisection','') == '':
  664. # Undefined guisections end up into Options
  665. task['guisection'] = _('Optional')
  666. if task['guisection'] not in is_section:
  667. # We do it like this to keep the original order, except for Main which goes first
  668. is_section[task['guisection']] = 1
  669. sections.append(task['guisection'])
  670. else:
  671. is_section[ task['guisection'] ] += 1
  672. del is_section
  673. # 'Required' tab goes first, 'Optional' as the last one
  674. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  675. if content in sections:
  676. idx = sections.index(content)
  677. sections[idx:idx+1] = []
  678. sections[newidx:newidx] = [content]
  679. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  680. # build notebook
  681. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  682. if style == 0: # basic top
  683. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  684. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  685. elif style == 1: # basic left
  686. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  687. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  688. elif style == 2: # fancy green
  689. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  690. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  691. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  692. elif style == 3:
  693. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  694. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  695. self.notebook.Refresh()
  696. tab = {}
  697. tabsizer = {}
  698. for section in sections:
  699. tab[section] = ScrolledPanel(parent = self.notebook)
  700. tab[section].SetScrollRate(10, 10)
  701. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  702. #
  703. # flags
  704. #
  705. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  706. for f in visible_flags:
  707. which_sizer = tabsizer[ f['guisection'] ]
  708. which_panel = tab[ f['guisection'] ]
  709. # if label is given: description -> tooltip
  710. if f.get('label','') != '':
  711. title = text_beautify(f['label'])
  712. tooltip = text_beautify(f['description'], width = -1)
  713. else:
  714. title = text_beautify(f['description'])
  715. tooltip = None
  716. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  717. rtitle_txt = wx.StaticText(parent = which_panel,
  718. label = '(' + f['name'] + ')')
  719. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  720. self.label_id.append(chk.GetId())
  721. if tooltip:
  722. chk.SetToolTipString(tooltip)
  723. chk.SetValue(f.get('value', False))
  724. title_sizer.Add(item = chk, proportion = 1,
  725. flag = wx.EXPAND)
  726. title_sizer.Add(item = rtitle_txt, proportion = 0,
  727. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  728. which_sizer.Add(item = title_sizer, proportion = 0,
  729. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  730. f['wxId'] = [ chk.GetId(), ]
  731. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  732. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  733. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  734. label = _("Parameterized in model"))
  735. parChk.SetName('ModelParam')
  736. parChk.SetValue(f.get('parameterized', False))
  737. if 'wxId' in f:
  738. f['wxId'].append(parChk.GetId())
  739. else:
  740. f['wxId'] = [ parChk.GetId() ]
  741. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  742. which_sizer.Add(item = parChk, proportion = 0,
  743. flag = wx.LEFT, border = 20)
  744. if f['name'] in ('verbose', 'quiet'):
  745. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  746. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  747. if f['name'] == vq:
  748. chk.SetValue(True)
  749. f['value'] = True
  750. if f['name'] == 'overwrite':
  751. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  752. chk.SetValue(f['value'])
  753. #
  754. # parameters
  755. #
  756. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  757. try:
  758. first_param = visible_params[0]
  759. except IndexError:
  760. first_param = None
  761. for p in visible_params:
  762. which_sizer = tabsizer[p['guisection']]
  763. which_panel = tab[p['guisection']]
  764. # if label is given -> label and description -> tooltip
  765. # otherwise description -> lavel
  766. if p.get('label','') != '':
  767. title = text_beautify(p['label'])
  768. tooltip = text_beautify(p['description'], width = -1)
  769. else:
  770. title = text_beautify(p['description'])
  771. tooltip = None
  772. prompt = p.get('prompt', '')
  773. # text style (required -> bold)
  774. if not p.get('required', False):
  775. text_style = wx.FONTWEIGHT_NORMAL
  776. else:
  777. text_style = wx.FONTWEIGHT_BOLD
  778. # title sizer (description, name, type)
  779. if (len(p.get('values', [])) > 0) and \
  780. p.get('multiple', False) and \
  781. p.get('gisprompt', False) == False and \
  782. p.get('type', '') == 'string':
  783. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  784. else:
  785. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  786. title_txt = wx.StaticText(parent = which_panel)
  787. if p['key_desc']:
  788. ltype = ','.join(p['key_desc'])
  789. else:
  790. ltype = p['type']
  791. rtitle_txt = wx.StaticText(parent = which_panel,
  792. label = '(' + p['name'] + '=' + ltype + ')')
  793. title_sizer.Add(item = title_txt, proportion = 1,
  794. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  795. title_sizer.Add(item = rtitle_txt, proportion = 0,
  796. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  797. which_sizer.Add(item = title_sizer, proportion = 0,
  798. flag = wx.EXPAND)
  799. self.label_id.append(title_txt.GetId())
  800. # title expansion
  801. if p.get('multiple', False) and len(p.get('values','')) == 0:
  802. title = _("[multiple]") + " " + title
  803. if p.get('value','') == '' :
  804. p['value'] = p.get('default','')
  805. if (len(p.get('values', [])) > 0):
  806. valuelist = map(str, p.get('values',[]))
  807. valuelist_desc = map(unicode, p.get('values_desc',[]))
  808. if p.get('multiple', False) and \
  809. p.get('gisprompt',False) == False and \
  810. p.get('type', '') == 'string':
  811. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  812. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  813. if valuelist_desc:
  814. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  815. else:
  816. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  817. isEnabled = {}
  818. # copy default values
  819. if p['value'] == '':
  820. p['value'] = p.get('default', '')
  821. for defval in p.get('value', '').split(','):
  822. isEnabled[ defval ] = 'yes'
  823. # for multi checkboxes, this is an array of all wx IDs
  824. # for each individual checkbox
  825. p[ 'wxId' ] = list()
  826. idx = 0
  827. for val in valuelist:
  828. try:
  829. label = valuelist_desc[idx]
  830. except IndexError:
  831. label = val
  832. chkbox = wx.CheckBox(parent = which_panel,
  833. label = text_beautify(label))
  834. p[ 'wxId' ].append(chkbox.GetId())
  835. if val in isEnabled:
  836. chkbox.SetValue(True)
  837. hSizer.Add(item = chkbox, proportion = 0)
  838. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  839. idx += 1
  840. stSizer.Add(item = hSizer, proportion = 0,
  841. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  842. which_sizer.Add(item = stSizer, proportion = 0,
  843. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  844. elif p.get('gisprompt', False) is False:
  845. if len(valuelist) == 1: # -> textctrl
  846. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  847. str(valuelist[0])))
  848. if p.get('type', '') == 'integer' and \
  849. not p.get('multiple', False):
  850. # for multiple integers use textctrl instead of spinsctrl
  851. try:
  852. minValue, maxValue = map(int, valuelist[0].split('-'))
  853. except ValueError:
  854. minValue = -1e6
  855. maxValue = 1e6
  856. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  857. min = minValue, max = maxValue)
  858. style = wx.BOTTOM | wx.LEFT
  859. else:
  860. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  861. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  862. value = self._getValue(p)
  863. # parameter previously set
  864. if value:
  865. if isinstance(txt2, wx.SpinCtrl):
  866. txt2.SetValue(int(value))
  867. else:
  868. txt2.SetValue(value)
  869. which_sizer.Add(item = txt2, proportion = 0,
  870. flag = style, border = 5)
  871. p['wxId'] = [ txt2.GetId(), ]
  872. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  873. else:
  874. title_txt.SetLabel(title + ':')
  875. value = self._getValue(p)
  876. if p['name'] == 'icon': # symbols
  877. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  878. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  879. bitmap = bitmap)
  880. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  881. iconLabel.SetLabel(value)
  882. p['value'] = value
  883. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  884. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  885. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  886. this_sizer.Add(item = bb, proportion = 0,
  887. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  888. this_sizer.Add(item = iconLabel, proportion = 0,
  889. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  890. which_sizer.Add(item = this_sizer, proportion = 0,
  891. flag = wx.ADJUST_MINSIZE, border = 0)
  892. else:
  893. # list of values (combo)
  894. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  895. size=globalvar.DIALOG_COMBOBOX_SIZE,
  896. choices=valuelist, style=wx.CB_DROPDOWN)
  897. if value:
  898. cb.SetValue(value) # parameter previously set
  899. which_sizer.Add(item = cb, proportion = 0,
  900. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  901. p['wxId'] = [cb.GetId(),]
  902. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  903. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  904. if p.get('guidependency', ''):
  905. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  906. # text entry
  907. if (p.get('type','string') in ('string','integer','float')
  908. and len(p.get('values',[])) == 0
  909. and p.get('gisprompt',False) == False
  910. and p.get('prompt','') != 'color'):
  911. title_txt.SetLabel(title + ':')
  912. if p.get('multiple', False) or \
  913. p.get('type', 'string') == 'string' or \
  914. len(p.get('key_desc', [])) > 1:
  915. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  916. value = self._getValue(p)
  917. if value:
  918. # parameter previously set
  919. txt3.SetValue(str(value))
  920. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  921. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  922. elif p.get('type', '') == 'integer':
  923. minValue = -1e9
  924. maxValue = 1e9
  925. value = self._getValue(p)
  926. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
  927. size = globalvar.DIALOG_SPIN_SIZE,
  928. min = minValue, max = maxValue)
  929. if value:
  930. txt3.SetValue(int(value)) # parameter previously set
  931. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  932. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  933. else: # float
  934. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  935. validator = FloatValidator())
  936. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  937. value = self._getValue(p)
  938. if value:
  939. txt3.SetValue(str(value)) # parameter previously set
  940. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  941. which_sizer.Add(item = txt3, proportion = 0,
  942. flag = style, border = 5)
  943. p['wxId'] = [ txt3.GetId(), ]
  944. #
  945. # element selection tree combobox (maps, icons, regions, etc.)
  946. #
  947. if p.get('gisprompt', False):
  948. title_txt.SetLabel(title + ':')
  949. # GIS element entry
  950. if p.get('prompt','') not in ('color',
  951. 'subgroup',
  952. 'sigfile',
  953. 'dbdriver',
  954. 'dbname',
  955. 'dbtable',
  956. 'dbcolumn',
  957. 'layer',
  958. 'location',
  959. 'mapset',
  960. 'dbase',
  961. 'coords',
  962. 'file',
  963. 'dir',
  964. 'colortable',
  965. 'barscale',
  966. 'northarrow'):
  967. multiple = p.get('multiple', False)
  968. if p.get('age', '') == 'new':
  969. mapsets = [grass.gisenv()['MAPSET'],]
  970. else:
  971. mapsets = None
  972. if self.task.name in ('r.proj', 'v.proj') \
  973. and p.get('name', '') == 'input':
  974. if self.task.name == 'r.proj':
  975. isRaster = True
  976. else:
  977. isRaster = False
  978. selection = gselect.ProjSelect(parent = which_panel,
  979. isRaster = isRaster)
  980. p['wxId'] = [ selection.GetId(), ]
  981. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  982. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  983. else:
  984. elem = p.get('element', None)
  985. # hack for t.* modules
  986. if elem in ('stds', 'map'):
  987. orig_elem = elem
  988. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  989. if type_param:
  990. elem = type_param.get('default', None)
  991. # for t.(un)register:
  992. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  993. if maps_param and orig_elem == 'stds':
  994. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  995. elem = element_dict[type_param.get('default')]
  996. if self._giface and hasattr(self._giface, "_model"):
  997. extraItems = {_('Graphical Modeler') : self._giface.GetLayerList(p.get('prompt'))}
  998. else:
  999. extraItems = None
  1000. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  1001. size = globalvar.DIALOG_GSELECT_SIZE,
  1002. type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
  1003. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
  1004. extraItems = extraItems)
  1005. value = self._getValue(p)
  1006. if value:
  1007. selection.SetValue(value)
  1008. formatSelector = True
  1009. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1010. # we target the textctl here
  1011. textWin = selection.GetTextCtrl()
  1012. p['wxId'] = [ textWin.GetId(), ]
  1013. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1014. if prompt == 'vector':
  1015. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1016. # if formatSelector and p.get('age', 'old') == 'old':
  1017. # # OGR supported (read-only)
  1018. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1019. # self.hsizer.Add(item = selection,
  1020. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1021. # border = 5)
  1022. # # format (native / ogr)
  1023. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1024. # label = " %s " % _("Format"),
  1025. # style = wx.RA_SPECIFY_ROWS,
  1026. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1027. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1028. # rbox.SetSelection(1)
  1029. # rbox.SetName('VectorFormat')
  1030. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1031. # self.hsizer.Add(item = rbox,
  1032. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1033. # wx.RIGHT | wx.ALIGN_TOP,
  1034. # border = 5)
  1035. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1036. # default = 'dir',
  1037. # exclude = ['file'])
  1038. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1039. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1040. # ogrSelection.SetName('OgrSelect')
  1041. # ogrSelection.Hide()
  1042. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1043. # p['wxId'].append(rbox.GetId())
  1044. # p['wxId'].append(ogrSelection.GetId())
  1045. # for win in ogrSelection.GetDsnWin():
  1046. # p['wxId'].append(win.GetId())
  1047. # else:
  1048. which_sizer.Add(item = selection, proportion = 0,
  1049. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1050. border = 5)
  1051. elif prompt == 'group':
  1052. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1053. which_sizer.Add(item = selection, proportion = 0,
  1054. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1055. border = 5)
  1056. else:
  1057. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1058. showButton = True
  1059. try:
  1060. # if matplotlib is there
  1061. from timeline import frame
  1062. showButton = True
  1063. except ImportError:
  1064. showButton = False
  1065. else:
  1066. showButton = False
  1067. if showButton:
  1068. iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
  1069. bitmap = wx.Bitmap(os.path.join(globalvar.ETCICONDIR, iconTheme, 'map-info.png'))
  1070. bb = wx.BitmapButton(parent=which_panel, bitmap=bitmap)
  1071. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1072. bb.SetToolTipString(_("Show graphical representation of temporal extent of dataset(s) ."))
  1073. p['wxId'].append(bb.GetId())
  1074. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1075. hSizer.Add(item=selection, proportion=0,
  1076. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1077. border=5)
  1078. hSizer.Add(item=bb, proportion=0,
  1079. flag=wx.EXPAND|wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1080. border=5)
  1081. which_sizer.Add(hSizer)
  1082. else:
  1083. which_sizer.Add(item=selection, proportion=0,
  1084. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1085. border=5)
  1086. # subgroup
  1087. elif prompt == 'subgroup':
  1088. selection = gselect.SubGroupSelect(parent = which_panel)
  1089. p['wxId'] = [ selection.GetId() ]
  1090. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1091. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1092. which_sizer.Add(item = selection, proportion = 0,
  1093. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1094. border = 5)
  1095. # sigrature file
  1096. elif prompt == 'sigfile':
  1097. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1098. p['wxId'] = [ selection.GetId() ]
  1099. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1100. which_sizer.Add(item = selection, proportion = 0,
  1101. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1102. border = 5)
  1103. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1104. elif prompt in ('dbdriver',
  1105. 'dbname',
  1106. 'dbtable',
  1107. 'dbcolumn',
  1108. 'layer',
  1109. 'location',
  1110. 'mapset',
  1111. 'dbase'):
  1112. if p.get('multiple', 'no') == 'yes':
  1113. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1114. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1115. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1116. else:
  1117. value = self._getValue(p)
  1118. if prompt == 'layer':
  1119. if p.get('element', 'layer') == 'layer_all':
  1120. all = True
  1121. else:
  1122. all = False
  1123. if p.get('age', 'old') == 'old':
  1124. win = gselect.LayerSelect(parent = which_panel,
  1125. all = all,
  1126. default = p['default'])
  1127. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1128. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1129. win.SetValue(str(value)) # default or previously set value
  1130. else:
  1131. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1132. min = 1, max = 100, initial = int(p['default']))
  1133. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1134. win.SetValue(int(value)) # default or previously set value
  1135. p['wxId'] = [ win.GetId() ]
  1136. elif prompt == 'dbdriver':
  1137. win = gselect.DriverSelect(parent = which_panel,
  1138. choices = p.get('values', []),
  1139. value = value)
  1140. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1141. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1142. elif prompt == 'dbname':
  1143. win = gselect.DatabaseSelect(parent = which_panel,
  1144. value = value)
  1145. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1146. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1147. elif prompt == 'dbtable':
  1148. if p.get('age', 'old') == 'old':
  1149. win = gselect.TableSelect(parent = which_panel)
  1150. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1151. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1152. else:
  1153. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1154. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1155. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1156. elif prompt == 'dbcolumn':
  1157. win = gselect.ColumnSelect(parent = which_panel,
  1158. value = value,
  1159. param = p,
  1160. multiple = p.get('multiple', False))
  1161. # A gselect.ColumnSelect is a combobox with two children: a textctl and a popupwindow;
  1162. # we target the textctl here
  1163. textWin = win.GetTextCtrl()
  1164. p['wxId'] = [ textWin.GetId(), ]
  1165. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1166. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1167. elif prompt == 'location':
  1168. win = gselect.LocationSelect(parent = which_panel,
  1169. value = value)
  1170. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1171. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1172. elif prompt == 'mapset':
  1173. if p.get('age', 'old') == 'old':
  1174. new = False
  1175. else:
  1176. new = True
  1177. win = gselect.MapsetSelect(parent = which_panel,
  1178. value = value, new = new,
  1179. multiple = p.get('multiple', False))
  1180. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1181. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1182. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1183. elif prompt == 'dbase':
  1184. win = gselect.DbaseSelect(parent = which_panel,
  1185. changeCallback = self.OnSetValue)
  1186. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1187. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1188. if 'wxId' not in p:
  1189. try:
  1190. p['wxId'] = [ win.GetId(), ]
  1191. except AttributeError:
  1192. pass
  1193. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1194. if prompt == 'dbname':
  1195. flags |= wx.EXPAND
  1196. which_sizer.Add(item = win, proportion = 0,
  1197. flag = flags, border = 5)
  1198. # color entry
  1199. elif prompt == 'color':
  1200. default_color = (200,200,200)
  1201. label_color = _("Select Color")
  1202. if p.get('default','') != '':
  1203. default_color, label_color = utils.color_resolve(p['default'])
  1204. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1205. default_color, label_color = utils.color_resolve(p['value'])
  1206. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1207. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1208. else:
  1209. this_sizer = which_sizer
  1210. colorSize = 150
  1211. # For color selectors, this is a three-member array, holding the IDs of
  1212. # the color picker, the text control for multiple colors (or None),
  1213. # and either a "transparent" checkbox or None
  1214. p['wxId'] = [None] * 3
  1215. if p.get('multiple', False):
  1216. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1217. this_sizer.Add(item = txt, proportion = 1,
  1218. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1219. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1220. colorSize = 40
  1221. label_color = ''
  1222. p['wxId'][1] = txt.GetId()
  1223. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1224. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1225. label = label_color, colour = default_color,
  1226. pos = wx.DefaultPosition, size = (colorSize,-1))
  1227. this_sizer.Add(item = btn_colour, proportion = 0,
  1228. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1229. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1230. p['wxId'][0] = btn_colour.GetId()
  1231. if p.get('element', '') == 'color_none':
  1232. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1233. if p.get('value','') == "none":
  1234. none_check.SetValue(True)
  1235. else:
  1236. none_check.SetValue(False)
  1237. this_sizer.Add(item = none_check, proportion = 0,
  1238. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1239. which_sizer.Add(this_sizer)
  1240. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1241. p['wxId'][2] = none_check.GetId()
  1242. # file selector
  1243. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1244. if p.get('age', 'new') == 'new':
  1245. fmode = wx.SAVE
  1246. else:
  1247. fmode = wx.OPEN
  1248. # check wildcard
  1249. try:
  1250. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1251. except:
  1252. fExt = None
  1253. if not fExt:
  1254. fMask = '*'
  1255. else:
  1256. fMask = '%s files (*%s)|*%s|Files (*)|*' % (fExt[1:].upper(), fExt, fExt)
  1257. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1258. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1259. dialogTitle = _('Choose %s') % \
  1260. p.get('description', _('file')).lower(),
  1261. buttonText = _('Browse'),
  1262. startDirectory = os.getcwd(), fileMode = fmode,
  1263. changeCallback = self.OnSetValue)
  1264. value = self._getValue(p)
  1265. if value:
  1266. fbb.SetValue(value) # parameter previously set
  1267. which_sizer.Add(item = fbb, proportion = 0,
  1268. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1269. # A file browse button is a combobox with two children:
  1270. # a textctl and a button;
  1271. # we have to target the button here
  1272. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1273. if p.get('age', 'new') == 'old' and \
  1274. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1275. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1276. # widget for interactive input
  1277. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1278. style = wx.TE_MULTILINE,
  1279. size = (-1, 75))
  1280. if p.get('value', '') and os.path.isfile(p['value']):
  1281. f = open(p['value'])
  1282. ifbb.SetValue(''.join(f.readlines()))
  1283. f.close()
  1284. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1285. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1286. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1287. btnSave = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Save as"))
  1288. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1289. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1290. label = _('or enter values interactively')),
  1291. proportion = 0,
  1292. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1293. which_sizer.Add(item = ifbb, proportion = 1,
  1294. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1295. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1296. btnSizer.Add(item = btnLoad, proportion = 0,
  1297. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1298. btnSizer.Add(item = btnSave, proportion = 0,
  1299. flag = wx.ALIGN_RIGHT)
  1300. which_sizer.Add(item = btnSizer, proportion = 0,
  1301. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1302. p['wxId'].append(ifbb.GetId())
  1303. p['wxId'].append(btnLoad.GetId())
  1304. p['wxId'].append(btnSave.GetId())
  1305. # directory selector
  1306. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1307. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1308. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1309. dialogTitle = _('Choose %s') % \
  1310. p.get('description', _('Directory')),
  1311. buttonText = _('Browse'),
  1312. startDirectory = os.getcwd(),
  1313. changeCallback = self.OnSetValue)
  1314. value = self._getValue(p)
  1315. if value:
  1316. fbb.SetValue(value) # parameter previously set
  1317. which_sizer.Add(item = fbb, proportion = 0,
  1318. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1319. # A file browse button is a combobox with two children:
  1320. # a textctl and a button;
  1321. # we have to target the button here
  1322. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1323. # interactive inserting of coordinates from map window
  1324. elif prompt == 'coords':
  1325. # interactive inserting if layer manager is accessible
  1326. if self._giface:
  1327. win = gselect.CoordinatesSelect(parent = which_panel,
  1328. giface = self._giface,
  1329. multiple = p.get('multiple', False),
  1330. param = p)
  1331. p['wxId'] = [win.GetTextWin().GetId()]
  1332. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1333. # bind closing event because destructor is not working properly
  1334. if hasattr(self.parent, 'dialogClosing'):
  1335. self.parent.dialogClosing.connect(win.OnClose)
  1336. # normal text field
  1337. else:
  1338. win = wx.TextCtrl(parent = which_panel)
  1339. p['wxId'] = [win.GetId()]
  1340. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1341. which_sizer.Add(item = win,
  1342. proportion = 0,
  1343. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1344. border = 5)
  1345. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1346. if prompt == 'colortable':
  1347. cb = ColorTablesComboBox(parent=which_panel, value=p.get('default',''),
  1348. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1349. choices=valuelist)
  1350. elif prompt == 'barscale':
  1351. cb = BarscalesComboBox(parent=which_panel, value=p.get('default',''),
  1352. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1353. choices=valuelist)
  1354. elif prompt == 'northarrow':
  1355. cb = NArrowsComboBox(parent=which_panel, value=p.get('default',''),
  1356. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1357. choices=valuelist)
  1358. value = self._getValue(p)
  1359. if value:
  1360. cb.SetValue(value) # parameter previously set
  1361. which_sizer.Add(item = cb, proportion = 0,
  1362. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1363. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1364. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1365. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1366. if p.get('guidependency', ''):
  1367. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1368. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  1369. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1370. label = _("Parameterized in model"))
  1371. parChk.SetName('ModelParam')
  1372. parChk.SetValue(p.get('parameterized', False))
  1373. if 'wxId' in p:
  1374. p['wxId'].append(parChk.GetId())
  1375. else:
  1376. p['wxId'] = [ parChk.GetId() ]
  1377. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1378. which_sizer.Add(item = parChk, proportion = 0,
  1379. flag = wx.LEFT, border = 20)
  1380. if title_txt is not None:
  1381. # create tooltip if given
  1382. if len(p['values_desc']) > 0:
  1383. if tooltip:
  1384. tooltip += 2 * os.linesep
  1385. else:
  1386. tooltip = ''
  1387. if len(p['values']) == len(p['values_desc']):
  1388. for i in range(len(p['values'])):
  1389. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1390. tooltip.strip(os.linesep)
  1391. if tooltip:
  1392. title_txt.SetToolTipString(tooltip)
  1393. if p == first_param:
  1394. if 'wxId' in p and len(p['wxId']) > 0:
  1395. win = self.FindWindowById(p['wxId'][0])
  1396. win.SetFocus()
  1397. #
  1398. # set widget relations for OnUpdateSelection
  1399. #
  1400. pMap = None
  1401. pLayer = []
  1402. pDriver = None
  1403. pDatabase = None
  1404. pTable = None
  1405. pColumn = []
  1406. pGroup = None
  1407. pSubGroup = None
  1408. pSigFile = []
  1409. pDbase = None
  1410. pLocation = None
  1411. pMapset = None
  1412. for p in self.task.params:
  1413. guidep = p.get('guidependency', '')
  1414. if guidep:
  1415. # fixed options dependency defined
  1416. options = guidep.split(',')
  1417. for opt in options:
  1418. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1419. if id:
  1420. if 'wxId-bind' not in p:
  1421. p['wxId-bind'] = list()
  1422. p['wxId-bind'] += pOpt['wxId']
  1423. continue
  1424. if p.get('gisprompt', False) == False:
  1425. continue
  1426. prompt = p.get('prompt', '')
  1427. if prompt in ('raster', 'vector'):
  1428. name = p.get('name', '')
  1429. if name in ('map', 'input'):
  1430. pMap = p
  1431. elif prompt == 'layer':
  1432. pLayer.append(p)
  1433. elif prompt == 'dbcolumn':
  1434. pColumn.append(p)
  1435. elif prompt == 'dbdriver':
  1436. pDriver = p
  1437. elif prompt == 'dbname':
  1438. pDatabase = p
  1439. elif prompt == 'dbtable':
  1440. pTable = p
  1441. elif prompt == 'group':
  1442. pGroup = p
  1443. elif prompt == 'subgroup':
  1444. pSubGroup = p
  1445. elif prompt == 'sigfile':
  1446. pSigFile.append(p)
  1447. elif prompt == 'dbase':
  1448. pDbase = p
  1449. elif prompt == 'location':
  1450. pLocation = p
  1451. elif prompt == 'mapset':
  1452. pMapset = p
  1453. # collect ids
  1454. pColumnIds = []
  1455. for p in pColumn:
  1456. pColumnIds += p['wxId']
  1457. pLayerIds = []
  1458. for p in pLayer:
  1459. pLayerIds += p['wxId']
  1460. pSigFileIds = []
  1461. for p in pSigFile:
  1462. pSigFileIds += 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'] = pSigFileIds + pSubGroup['wxId']
  1481. pSubGroup['wxId-bind'] = pSigFileIds
  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()