forms.py 110 KB

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