forms.py 112 KB

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