forms.py 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  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. # we don't want another help (checkbox appeared in r58783)
  709. if f['name'] == 'help':
  710. continue
  711. which_sizer = tabsizer[ f['guisection'] ]
  712. which_panel = tab[ f['guisection'] ]
  713. # if label is given: description -> tooltip
  714. if f.get('label','') != '':
  715. title = text_beautify(f['label'])
  716. tooltip = text_beautify(f['description'], width = -1)
  717. else:
  718. title = text_beautify(f['description'])
  719. tooltip = None
  720. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  721. rtitle_txt = wx.StaticText(parent = which_panel,
  722. label = '(' + f['name'] + ')')
  723. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  724. self.label_id.append(chk.GetId())
  725. if tooltip:
  726. chk.SetToolTipString(tooltip)
  727. chk.SetValue(f.get('value', False))
  728. title_sizer.Add(item = chk, proportion = 1,
  729. flag = wx.EXPAND)
  730. title_sizer.Add(item = rtitle_txt, proportion = 0,
  731. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  732. which_sizer.Add(item = title_sizer, proportion = 0,
  733. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  734. f['wxId'] = [ chk.GetId(), ]
  735. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  736. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  737. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  738. label = _("Parameterized in model"))
  739. parChk.SetName('ModelParam')
  740. parChk.SetValue(f.get('parameterized', False))
  741. if 'wxId' in f:
  742. f['wxId'].append(parChk.GetId())
  743. else:
  744. f['wxId'] = [ parChk.GetId() ]
  745. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  746. which_sizer.Add(item = parChk, proportion = 0,
  747. flag = wx.LEFT, border = 20)
  748. if f['name'] in ('verbose', 'quiet'):
  749. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  750. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  751. if f['name'] == vq:
  752. chk.SetValue(True)
  753. f['value'] = True
  754. if f['name'] == 'overwrite':
  755. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  756. chk.SetValue(f['value'])
  757. #
  758. # parameters
  759. #
  760. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  761. try:
  762. first_param = visible_params[0]
  763. except IndexError:
  764. first_param = None
  765. for p in visible_params:
  766. which_sizer = tabsizer[p['guisection']]
  767. which_panel = tab[p['guisection']]
  768. # if label is given -> label and description -> tooltip
  769. # otherwise description -> lavel
  770. if p.get('label','') != '':
  771. title = text_beautify(p['label'])
  772. tooltip = text_beautify(p['description'], width = -1)
  773. else:
  774. title = text_beautify(p['description'])
  775. tooltip = None
  776. prompt = p.get('prompt', '')
  777. # text style (required -> bold)
  778. if not p.get('required', False):
  779. text_style = wx.FONTWEIGHT_NORMAL
  780. else:
  781. text_style = wx.FONTWEIGHT_BOLD
  782. # title sizer (description, name, type)
  783. if (len(p.get('values', [])) > 0) and \
  784. p.get('multiple', False) and \
  785. p.get('gisprompt', False) == False and \
  786. p.get('type', '') == 'string':
  787. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  788. else:
  789. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  790. title_txt = wx.StaticText(parent = which_panel)
  791. if p['key_desc']:
  792. ltype = ','.join(p['key_desc'])
  793. else:
  794. ltype = p['type']
  795. rtitle_txt = wx.StaticText(parent = which_panel,
  796. label = '(' + p['name'] + '=' + ltype + ')')
  797. title_sizer.Add(item = title_txt, proportion = 1,
  798. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  799. title_sizer.Add(item = rtitle_txt, proportion = 0,
  800. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  801. which_sizer.Add(item = title_sizer, proportion = 0,
  802. flag = wx.EXPAND)
  803. self.label_id.append(title_txt.GetId())
  804. # title expansion
  805. if p.get('multiple', False) and len(p.get('values','')) == 0:
  806. title = _("[multiple]") + " " + title
  807. if p.get('value','') == '' :
  808. p['value'] = p.get('default','')
  809. if (len(p.get('values', [])) > 0):
  810. valuelist = map(str, p.get('values',[]))
  811. valuelist_desc = map(unicode, p.get('values_desc',[]))
  812. if p.get('multiple', False) and \
  813. p.get('gisprompt',False) == False and \
  814. p.get('type', '') == 'string':
  815. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  816. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  817. if valuelist_desc:
  818. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  819. else:
  820. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  821. isEnabled = {}
  822. # copy default values
  823. if p['value'] == '':
  824. p['value'] = p.get('default', '')
  825. for defval in p.get('value', '').split(','):
  826. isEnabled[ defval ] = 'yes'
  827. # for multi checkboxes, this is an array of all wx IDs
  828. # for each individual checkbox
  829. p[ 'wxId' ] = list()
  830. idx = 0
  831. for val in valuelist:
  832. try:
  833. label = valuelist_desc[idx]
  834. except IndexError:
  835. label = val
  836. chkbox = wx.CheckBox(parent = which_panel,
  837. label = text_beautify(label))
  838. p[ 'wxId' ].append(chkbox.GetId())
  839. if val in isEnabled:
  840. chkbox.SetValue(True)
  841. hSizer.Add(item = chkbox, proportion = 0)
  842. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  843. idx += 1
  844. stSizer.Add(item = hSizer, proportion = 0,
  845. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  846. which_sizer.Add(item = stSizer, proportion = 0,
  847. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  848. elif p.get('gisprompt', False) is False:
  849. if len(valuelist) == 1: # -> textctrl
  850. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  851. str(valuelist[0])))
  852. if p.get('type', '') == 'integer' and \
  853. not p.get('multiple', False):
  854. # for multiple integers use textctrl instead of spinsctrl
  855. try:
  856. minValue, maxValue = map(int, valuelist[0].rsplit('-', 1))
  857. except ValueError:
  858. minValue = -1e6
  859. maxValue = 1e6
  860. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  861. min = minValue, max = maxValue)
  862. style = wx.BOTTOM | wx.LEFT
  863. else:
  864. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  865. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  866. value = self._getValue(p)
  867. # parameter previously set
  868. if value:
  869. if isinstance(txt2, wx.SpinCtrl):
  870. txt2.SetValue(int(value))
  871. else:
  872. txt2.SetValue(value)
  873. which_sizer.Add(item = txt2, proportion = 0,
  874. flag = style, border = 5)
  875. p['wxId'] = [ txt2.GetId(), ]
  876. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  877. else:
  878. title_txt.SetLabel(title + ':')
  879. value = self._getValue(p)
  880. if p['name'] == 'icon': # symbols
  881. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  882. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  883. bitmap = bitmap)
  884. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  885. iconLabel.SetLabel(value)
  886. p['value'] = value
  887. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  888. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  889. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  890. this_sizer.Add(item = bb, proportion = 0,
  891. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  892. this_sizer.Add(item = iconLabel, proportion = 0,
  893. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  894. which_sizer.Add(item = this_sizer, proportion = 0,
  895. flag = wx.ADJUST_MINSIZE, border = 0)
  896. else:
  897. # list of values (combo)
  898. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  899. size=globalvar.DIALOG_COMBOBOX_SIZE,
  900. choices=valuelist, style=wx.CB_DROPDOWN)
  901. if value:
  902. cb.SetValue(value) # parameter previously set
  903. which_sizer.Add(item = cb, proportion = 0,
  904. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  905. p['wxId'] = [cb.GetId(),]
  906. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  907. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  908. if p.get('guidependency', ''):
  909. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  910. # text entry
  911. if (p.get('type','string') in ('string','integer','float')
  912. and len(p.get('values',[])) == 0
  913. and p.get('gisprompt',False) == False
  914. and p.get('prompt','') != 'color'):
  915. title_txt.SetLabel(title + ':')
  916. if p.get('multiple', False) or \
  917. p.get('type', 'string') == 'string' or \
  918. len(p.get('key_desc', [])) > 1:
  919. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  920. value = self._getValue(p)
  921. if value:
  922. # parameter previously set
  923. txt3.SetValue(str(value))
  924. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  925. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  926. elif p.get('type', '') == 'integer':
  927. minValue = -1e9
  928. maxValue = 1e9
  929. value = self._getValue(p)
  930. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
  931. size = globalvar.DIALOG_SPIN_SIZE,
  932. min = minValue, max = maxValue)
  933. if value:
  934. txt3.SetValue(int(value)) # parameter previously set
  935. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  936. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  937. else: # float
  938. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  939. validator = FloatValidator())
  940. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  941. value = self._getValue(p)
  942. if value:
  943. txt3.SetValue(str(value)) # parameter previously set
  944. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  945. which_sizer.Add(item = txt3, proportion = 0,
  946. flag = style, border = 5)
  947. p['wxId'] = [ txt3.GetId(), ]
  948. #
  949. # element selection tree combobox (maps, icons, regions, etc.)
  950. #
  951. if p.get('gisprompt', False):
  952. title_txt.SetLabel(title + ':')
  953. # GIS element entry
  954. if p.get('prompt','') not in ('color',
  955. 'subgroup',
  956. 'sigfile',
  957. 'dbdriver',
  958. 'dbname',
  959. 'dbtable',
  960. 'dbcolumn',
  961. 'layer',
  962. 'location',
  963. 'mapset',
  964. 'dbase',
  965. 'coords',
  966. 'file',
  967. 'dir',
  968. 'colortable',
  969. 'barscale',
  970. 'northarrow'):
  971. multiple = p.get('multiple', False)
  972. if p.get('age', '') == 'new':
  973. mapsets = [grass.gisenv()['MAPSET'],]
  974. else:
  975. mapsets = None
  976. if self.task.name in ('r.proj', 'v.proj') \
  977. and p.get('name', '') == 'input':
  978. if self.task.name == 'r.proj':
  979. isRaster = True
  980. else:
  981. isRaster = False
  982. selection = gselect.ProjSelect(parent = which_panel,
  983. isRaster = isRaster)
  984. p['wxId'] = [ selection.GetId(), ]
  985. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  986. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  987. else:
  988. elem = p.get('element', None)
  989. # hack for t.* modules
  990. if elem in ('stds', 'map'):
  991. orig_elem = elem
  992. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  993. if type_param:
  994. elem = type_param.get('default', None)
  995. # for t.(un)register:
  996. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  997. if maps_param and orig_elem == 'stds':
  998. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  999. elem = element_dict[type_param.get('default')]
  1000. if self._giface and hasattr(self._giface, "_model"):
  1001. extraItems = {_('Graphical Modeler') : self._giface.GetLayerList(p.get('prompt'))}
  1002. else:
  1003. extraItems = None
  1004. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  1005. size = globalvar.DIALOG_GSELECT_SIZE,
  1006. type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
  1007. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
  1008. extraItems = extraItems)
  1009. value = self._getValue(p)
  1010. if value:
  1011. selection.SetValue(value)
  1012. formatSelector = True
  1013. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1014. # we target the textctl here
  1015. textWin = selection.GetTextCtrl()
  1016. p['wxId'] = [ textWin.GetId(), ]
  1017. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1018. if prompt == 'vector':
  1019. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1020. # if formatSelector and p.get('age', 'old') == 'old':
  1021. # # OGR supported (read-only)
  1022. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1023. # self.hsizer.Add(item = selection,
  1024. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1025. # border = 5)
  1026. # # format (native / ogr)
  1027. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1028. # label = " %s " % _("Format"),
  1029. # style = wx.RA_SPECIFY_ROWS,
  1030. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1031. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1032. # rbox.SetSelection(1)
  1033. # rbox.SetName('VectorFormat')
  1034. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1035. # self.hsizer.Add(item = rbox,
  1036. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1037. # wx.RIGHT | wx.ALIGN_TOP,
  1038. # border = 5)
  1039. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1040. # default = 'dir',
  1041. # exclude = ['file'])
  1042. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1043. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1044. # ogrSelection.SetName('OgrSelect')
  1045. # ogrSelection.Hide()
  1046. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1047. # p['wxId'].append(rbox.GetId())
  1048. # p['wxId'].append(ogrSelection.GetId())
  1049. # for win in ogrSelection.GetDsnWin():
  1050. # p['wxId'].append(win.GetId())
  1051. # else:
  1052. which_sizer.Add(item = selection, proportion = 0,
  1053. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1054. border = 5)
  1055. elif prompt == 'group':
  1056. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1057. which_sizer.Add(item = selection, proportion = 0,
  1058. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1059. border = 5)
  1060. else:
  1061. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1062. showButton = True
  1063. try:
  1064. # if matplotlib is there
  1065. from timeline import frame
  1066. showButton = True
  1067. except ImportError:
  1068. showButton = False
  1069. else:
  1070. showButton = False
  1071. if showButton:
  1072. iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
  1073. bitmap = wx.Bitmap(os.path.join(globalvar.ETCICONDIR, iconTheme, 'map-info.png'))
  1074. bb = wx.BitmapButton(parent=which_panel, bitmap=bitmap)
  1075. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1076. bb.SetToolTipString(_("Show graphical representation of temporal extent of dataset(s) ."))
  1077. p['wxId'].append(bb.GetId())
  1078. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1079. hSizer.Add(item=selection, proportion=0,
  1080. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1081. border=5)
  1082. hSizer.Add(item=bb, proportion=0,
  1083. flag=wx.EXPAND|wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1084. border=5)
  1085. which_sizer.Add(hSizer)
  1086. else:
  1087. which_sizer.Add(item=selection, proportion=0,
  1088. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1089. border=5)
  1090. # subgroup
  1091. elif prompt == 'subgroup':
  1092. selection = gselect.SubGroupSelect(parent = which_panel)
  1093. p['wxId'] = [ selection.GetId() ]
  1094. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1095. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1096. which_sizer.Add(item = selection, proportion = 0,
  1097. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1098. border = 5)
  1099. # sigrature file
  1100. elif prompt == 'sigfile':
  1101. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1102. p['wxId'] = [ selection.GetId() ]
  1103. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1104. which_sizer.Add(item = selection, proportion = 0,
  1105. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1106. border = 5)
  1107. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1108. elif prompt in ('dbdriver',
  1109. 'dbname',
  1110. 'dbtable',
  1111. 'dbcolumn',
  1112. 'layer',
  1113. 'location',
  1114. 'mapset',
  1115. 'dbase'):
  1116. if p.get('multiple', 'no') == 'yes':
  1117. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1118. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1119. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1120. else:
  1121. value = self._getValue(p)
  1122. if prompt == 'layer':
  1123. if p.get('element', 'layer') == 'layer_all':
  1124. all = True
  1125. else:
  1126. all = False
  1127. if p.get('age', 'old') == 'old':
  1128. win = gselect.LayerSelect(parent = which_panel,
  1129. all = all,
  1130. default = p['default'])
  1131. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1132. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1133. win.SetValue(str(value)) # default or previously set value
  1134. else:
  1135. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1136. min = 1, max = 100, initial = int(p['default']))
  1137. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1138. win.SetValue(int(value)) # default or previously set value
  1139. p['wxId'] = [ win.GetId() ]
  1140. elif prompt == 'dbdriver':
  1141. win = gselect.DriverSelect(parent = which_panel,
  1142. choices = p.get('values', []),
  1143. value = value)
  1144. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1145. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1146. elif prompt == 'dbname':
  1147. win = gselect.DatabaseSelect(parent = which_panel,
  1148. value = value)
  1149. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1150. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1151. elif prompt == 'dbtable':
  1152. if p.get('age', 'old') == 'old':
  1153. win = gselect.TableSelect(parent = which_panel)
  1154. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1155. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1156. else:
  1157. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1158. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1159. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1160. elif prompt == 'dbcolumn':
  1161. win = gselect.ColumnSelect(parent = which_panel,
  1162. value = value,
  1163. param = p,
  1164. multiple = p.get('multiple', False))
  1165. # A gselect.ColumnSelect is a combobox
  1166. # with two children: a textctl and a
  1167. # popupwindow; we target the textctl here
  1168. textWin = win.GetTextCtrl()
  1169. p['wxId'] = [ textWin.GetId(), ]
  1170. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1171. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1172. elif prompt == 'location':
  1173. win = gselect.LocationSelect(parent = which_panel,
  1174. value = value)
  1175. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1176. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1177. elif prompt == 'mapset':
  1178. if p.get('age', 'old') == 'old':
  1179. new = False
  1180. else:
  1181. new = True
  1182. win = gselect.MapsetSelect(parent = which_panel,
  1183. value = value, new = new,
  1184. multiple = p.get('multiple', False))
  1185. textWin = win.GetTextCtrl()
  1186. p['wxId'] = [ textWin.GetId(), win.GetId() ]
  1187. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1188. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1189. elif prompt == 'dbase':
  1190. win = gselect.DbaseSelect(parent = which_panel,
  1191. changeCallback = self.OnSetValue)
  1192. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1193. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1194. if 'wxId' not in p:
  1195. try:
  1196. p['wxId'] = [ win.GetId(), ]
  1197. except AttributeError:
  1198. pass
  1199. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1200. if prompt == 'dbname':
  1201. flags |= wx.EXPAND
  1202. which_sizer.Add(item = win, proportion = 0,
  1203. flag = flags, border = 5)
  1204. # color entry
  1205. elif prompt == 'color':
  1206. default_color = (200,200,200)
  1207. label_color = _("Select Color")
  1208. if p.get('default','') != '':
  1209. default_color, label_color = utils.color_resolve(p['default'])
  1210. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1211. default_color, label_color = utils.color_resolve(p['value'])
  1212. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1213. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1214. else:
  1215. this_sizer = which_sizer
  1216. colorSize = 150
  1217. # For color selectors, this is a three-member array, holding the IDs of
  1218. # the color picker, the text control for multiple colors (or None),
  1219. # and either a "transparent" checkbox or None
  1220. p['wxId'] = [None] * 3
  1221. if p.get('multiple', False):
  1222. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1223. this_sizer.Add(item = txt, proportion = 1,
  1224. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1225. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1226. colorSize = 40
  1227. label_color = ''
  1228. p['wxId'][1] = txt.GetId()
  1229. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1230. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1231. label = label_color, colour = default_color,
  1232. pos = wx.DefaultPosition, size = (colorSize,-1))
  1233. this_sizer.Add(item = btn_colour, proportion = 0,
  1234. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1235. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1236. p['wxId'][0] = btn_colour.GetId()
  1237. if p.get('element', '') == 'color_none':
  1238. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1239. if p.get('value','') == "none":
  1240. none_check.SetValue(True)
  1241. else:
  1242. none_check.SetValue(False)
  1243. this_sizer.Add(item = none_check, proportion = 0,
  1244. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1245. which_sizer.Add(this_sizer)
  1246. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1247. p['wxId'][2] = none_check.GetId()
  1248. # file selector
  1249. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1250. if p.get('age', 'new') == 'new':
  1251. fmode = wx.SAVE
  1252. else:
  1253. fmode = wx.OPEN
  1254. # check wildcard
  1255. try:
  1256. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1257. except:
  1258. fExt = None
  1259. if not fExt:
  1260. fMask = '*'
  1261. else:
  1262. fMask = '%s files (*%s)|*%s|Files (*)|*' % (fExt[1:].upper(), fExt, fExt)
  1263. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1264. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1265. dialogTitle = _('Choose %s') % \
  1266. p.get('description', _('file')).lower(),
  1267. buttonText = _('Browse'),
  1268. startDirectory = os.getcwd(), fileMode = fmode,
  1269. changeCallback = self.OnSetValue)
  1270. value = self._getValue(p)
  1271. if value:
  1272. fbb.SetValue(value) # parameter previously set
  1273. which_sizer.Add(item = fbb, proportion = 0,
  1274. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1275. # A file browse button is a combobox with two children:
  1276. # a textctl and a button;
  1277. # we have to target the button here
  1278. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1279. if p.get('age', 'new') == 'old' and \
  1280. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1281. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1282. # widget for interactive input
  1283. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1284. style = wx.TE_MULTILINE,
  1285. size = (-1, 75))
  1286. if p.get('value', '') and os.path.isfile(p['value']):
  1287. f = open(p['value'])
  1288. ifbb.SetValue(''.join(f.readlines()))
  1289. f.close()
  1290. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1291. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1292. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1293. btnSave = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Save as"))
  1294. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1295. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1296. label = _('or enter values interactively')),
  1297. proportion = 0,
  1298. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1299. which_sizer.Add(item = ifbb, proportion = 1,
  1300. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1301. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1302. btnSizer.Add(item = btnLoad, proportion = 0,
  1303. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1304. btnSizer.Add(item = btnSave, proportion = 0,
  1305. flag = wx.ALIGN_RIGHT)
  1306. which_sizer.Add(item = btnSizer, proportion = 0,
  1307. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1308. p['wxId'].append(ifbb.GetId())
  1309. p['wxId'].append(btnLoad.GetId())
  1310. p['wxId'].append(btnSave.GetId())
  1311. # directory selector
  1312. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1313. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1314. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1315. dialogTitle = _('Choose %s') % \
  1316. p.get('description', _('Directory')),
  1317. buttonText = _('Browse'),
  1318. startDirectory = os.getcwd(),
  1319. changeCallback = self.OnSetValue)
  1320. value = self._getValue(p)
  1321. if value:
  1322. fbb.SetValue(value) # parameter previously set
  1323. which_sizer.Add(item = fbb, proportion = 0,
  1324. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1325. # A file browse button is a combobox with two children:
  1326. # a textctl and a button;
  1327. # we have to target the button here
  1328. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1329. # interactive inserting of coordinates from map window
  1330. elif prompt == 'coords':
  1331. # interactive inserting if layer manager is accessible
  1332. if self._giface:
  1333. win = gselect.CoordinatesSelect(parent = which_panel,
  1334. giface = self._giface,
  1335. multiple = p.get('multiple', False),
  1336. param = p)
  1337. p['wxId'] = [win.GetTextWin().GetId()]
  1338. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1339. # bind closing event because destructor is not working properly
  1340. if hasattr(self.parent, 'dialogClosing'):
  1341. self.parent.dialogClosing.connect(win.OnClose)
  1342. # normal text field
  1343. else:
  1344. win = wx.TextCtrl(parent = which_panel)
  1345. p['wxId'] = [win.GetId()]
  1346. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1347. which_sizer.Add(item = win,
  1348. proportion = 0,
  1349. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1350. border = 5)
  1351. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1352. if prompt == 'colortable':
  1353. cb = ColorTablesComboBox(parent=which_panel, value=p.get('default',''),
  1354. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1355. choices=valuelist)
  1356. elif prompt == 'barscale':
  1357. cb = BarscalesComboBox(parent=which_panel, value=p.get('default',''),
  1358. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1359. choices=valuelist)
  1360. elif prompt == 'northarrow':
  1361. cb = NArrowsComboBox(parent=which_panel, value=p.get('default',''),
  1362. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1363. choices=valuelist)
  1364. value = self._getValue(p)
  1365. if value:
  1366. cb.SetValue(value) # parameter previously set
  1367. which_sizer.Add(item = cb, proportion = 0,
  1368. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1369. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1370. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1371. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1372. if p.get('guidependency', ''):
  1373. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1374. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  1375. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1376. label = _("Parameterized in model"))
  1377. parChk.SetName('ModelParam')
  1378. parChk.SetValue(p.get('parameterized', False))
  1379. if 'wxId' in p:
  1380. p['wxId'].append(parChk.GetId())
  1381. else:
  1382. p['wxId'] = [ parChk.GetId() ]
  1383. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1384. which_sizer.Add(item = parChk, proportion = 0,
  1385. flag = wx.LEFT, border = 20)
  1386. if title_txt is not None:
  1387. # create tooltip if given
  1388. if len(p['values_desc']) > 0:
  1389. if tooltip:
  1390. tooltip += 2 * os.linesep
  1391. else:
  1392. tooltip = ''
  1393. if len(p['values']) == len(p['values_desc']):
  1394. for i in range(len(p['values'])):
  1395. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1396. tooltip.strip(os.linesep)
  1397. if tooltip:
  1398. title_txt.SetToolTipString(tooltip)
  1399. if p == first_param:
  1400. if 'wxId' in p and len(p['wxId']) > 0:
  1401. win = self.FindWindowById(p['wxId'][0])
  1402. win.SetFocus()
  1403. #
  1404. # set widget relations for OnUpdateSelection
  1405. #
  1406. pMap = None
  1407. pLayer = []
  1408. pDriver = None
  1409. pDatabase = None
  1410. pTable = None
  1411. pColumn = []
  1412. pGroup = None
  1413. pSubGroup = None
  1414. pSigFile = []
  1415. pDbase = None
  1416. pLocation = None
  1417. pMapset = None
  1418. for p in self.task.params:
  1419. guidep = p.get('guidependency', '')
  1420. if guidep:
  1421. # fixed options dependency defined
  1422. options = guidep.split(',')
  1423. for opt in options:
  1424. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1425. if pOpt and id:
  1426. if 'wxId-bind' not in p:
  1427. p['wxId-bind'] = list()
  1428. p['wxId-bind'] += pOpt['wxId']
  1429. continue
  1430. if p.get('gisprompt', False) == False:
  1431. continue
  1432. prompt = p.get('prompt', '')
  1433. if prompt in ('raster', 'vector'):
  1434. name = p.get('name', '')
  1435. if name in ('map', 'input'):
  1436. pMap = p
  1437. elif prompt == 'layer':
  1438. pLayer.append(p)
  1439. elif prompt == 'dbcolumn':
  1440. pColumn.append(p)
  1441. elif prompt == 'dbdriver':
  1442. pDriver = p
  1443. elif prompt == 'dbname':
  1444. pDatabase = p
  1445. elif prompt == 'dbtable':
  1446. pTable = p
  1447. elif prompt == 'group':
  1448. pGroup = p
  1449. elif prompt == 'subgroup':
  1450. pSubGroup = p
  1451. elif prompt == 'sigfile':
  1452. pSigFile.append(p)
  1453. elif prompt == 'dbase':
  1454. pDbase = p
  1455. elif prompt == 'location':
  1456. pLocation = p
  1457. elif prompt == 'mapset':
  1458. pMapset = p
  1459. # collect ids
  1460. pColumnIds = []
  1461. for p in pColumn:
  1462. pColumnIds += p['wxId']
  1463. pLayerIds = []
  1464. for p in pLayer:
  1465. pLayerIds += p['wxId']
  1466. pSigFileIds = []
  1467. for p in pSigFile:
  1468. pSigFileIds += p['wxId']
  1469. # set wxId-bindings
  1470. if pMap:
  1471. pMap['wxId-bind'] = []
  1472. if pLayer:
  1473. pMap['wxId-bind'] += pLayerIds
  1474. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1475. if pLayer:
  1476. for p in pLayer:
  1477. p['wxId-bind'] = copy.copy(pColumnIds)
  1478. if pDriver and pTable:
  1479. pDriver['wxId-bind'] = pTable['wxId']
  1480. if pDatabase and pTable:
  1481. pDatabase['wxId-bind'] = pTable['wxId']
  1482. if pTable and pColumnIds:
  1483. pTable['wxId-bind'] = pColumnIds
  1484. if pGroup and pSubGroup:
  1485. if pSigFile:
  1486. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1487. pSubGroup['wxId-bind'] = pSigFileIds
  1488. else:
  1489. pGroup['wxId-bind'] = pSubGroup['wxId']
  1490. if pDbase and pLocation:
  1491. pDbase['wxId-bind'] = pLocation['wxId']
  1492. if pLocation and pMapset:
  1493. pLocation['wxId-bind'] = pMapset['wxId']
  1494. if pLocation and pMapset and pMap:
  1495. pLocation['wxId-bind'] += pMap['wxId']
  1496. pMapset['wxId-bind'] = pMap['wxId']
  1497. #
  1498. # determine panel size
  1499. #
  1500. maxsizes = (0, 0)
  1501. for section in sections:
  1502. tab[section].SetSizer(tabsizer[section])
  1503. tabsizer[section].Fit(tab[section])
  1504. tab[section].Layout()
  1505. minsecsizes = tabsizer[section].GetSize()
  1506. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1507. # TODO: be less arbitrary with these 600
  1508. self.panelMinHeight = 100
  1509. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1510. for section in sections:
  1511. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1512. # add pages to notebook
  1513. imageList = wx.ImageList(16, 16)
  1514. self.notebook.AssignImageList(imageList)
  1515. for section in sections:
  1516. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1517. index = self.AddBitmapToImageList(section, imageList)
  1518. if index >= 0:
  1519. self.notebook.SetPageImage(section, index)
  1520. # are we running from command line?
  1521. ### add 'command output' tab regardless standalone dialog
  1522. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1523. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1524. from gui_core.goutput import GConsoleWindow
  1525. self._gconsole = GConsole(guiparent = self.notebook, giface = self._giface)
  1526. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1527. self._gconsole.Bind(EVT_CMD_RUN,
  1528. lambda event:
  1529. self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
  1530. self._gconsole.Bind(EVT_CMD_DONE,
  1531. lambda event:
  1532. self._switchPageHandler(event = event, notification=Notification.RAISE_WINDOW))
  1533. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1534. else:
  1535. self.goutput = None
  1536. self._gconsole = None
  1537. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.name)
  1538. if not self.manualTab.GetFile():
  1539. self.manualTab.Hide()
  1540. else:
  1541. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1542. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1543. if index >= 0:
  1544. self.notebook.SetPageImage('manual', index)
  1545. if self.manualTab.IsLoaded():
  1546. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1547. self.notebook.SetSelection(0)
  1548. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1549. self.SetSizer(panelsizer)
  1550. panelsizer.Fit(self.notebook)
  1551. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1552. def _getValue(self, p):
  1553. """!Get value or default value of given parameter
  1554. @param p parameter directory
  1555. """
  1556. if p.get('value', '') != '':
  1557. return p['value']
  1558. return p.get('default', '')
  1559. def OnFileLoad(self, event):
  1560. """!Load file to interactive input"""
  1561. me = event.GetId()
  1562. win = dict()
  1563. for p in self.task.params:
  1564. if 'wxId' in p and me in p['wxId']:
  1565. win['file'] = self.FindWindowById(p['wxId'][0])
  1566. win['text'] = self.FindWindowById(p['wxId'][1])
  1567. break
  1568. if not win:
  1569. return
  1570. path = win['file'].GetValue()
  1571. if not path:
  1572. gcmd.GMessage(parent = self,
  1573. message = _("Nothing to load."))
  1574. return
  1575. data = ''
  1576. try:
  1577. f = open(path, "r")
  1578. except IOError, e:
  1579. gcmd.GError(parent = self, showTraceback = False,
  1580. message = _("Unable to load file.\n\nReason: %s") % e)
  1581. return
  1582. try:
  1583. data = f.read()
  1584. finally:
  1585. f.close()
  1586. win['text'].SetValue(data)
  1587. def OnFileSave(self, event):
  1588. """!Save interactive input to the file"""
  1589. wId = event.GetId()
  1590. win = {}
  1591. for p in self.task.params:
  1592. if wId in p.get('wxId', []):
  1593. win['file'] = self.FindWindowById(p['wxId'][0])
  1594. win['text'] = self.FindWindowById(p['wxId'][1])
  1595. break
  1596. if not win:
  1597. return
  1598. text = win['text'].GetValue()
  1599. if not text:
  1600. gcmd.GMessage(parent = self,
  1601. message = _("Nothing to save."))
  1602. return
  1603. dlg = wx.FileDialog(parent = self,
  1604. message = _("Save input as..."),
  1605. defaultDir = os.getcwd(),
  1606. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1607. if dlg.ShowModal() == wx.ID_OK:
  1608. path = dlg.GetPath()
  1609. enc = locale.getdefaultlocale()[1]
  1610. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1611. try:
  1612. f.write(text + os.linesep)
  1613. finally:
  1614. f.close()
  1615. win['file'].SetValue(path)
  1616. dlg.Destroy()
  1617. def OnFileText(self, event):
  1618. """File input interactively entered"""
  1619. text = event.GetString()
  1620. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1621. if not p:
  1622. return # should not happen
  1623. win = self.FindWindowById(p['wxId'][0])
  1624. if text:
  1625. filename = win.GetValue()
  1626. if not filename or filename == p['default']: # m.proj has - as default
  1627. filename = grass.tempfile()
  1628. win.SetValue(filename)
  1629. enc = locale.getdefaultlocale()[1]
  1630. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1631. try:
  1632. f.write(text)
  1633. if text[-1] != os.linesep:
  1634. f.write(os.linesep)
  1635. finally:
  1636. f.close()
  1637. else:
  1638. win.SetValue('')
  1639. def OnVectorFormat(self, event):
  1640. """!Change vector format (native / ogr).
  1641. Currently unused.
  1642. """
  1643. sel = event.GetSelection()
  1644. idEvent = event.GetId()
  1645. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1646. if not p:
  1647. return # should not happen
  1648. # detect windows
  1649. winNative = None
  1650. winOgr = None
  1651. for id in p['wxId']:
  1652. if id == idEvent:
  1653. continue
  1654. name = self.FindWindowById(id).GetName()
  1655. if name == 'Select':
  1656. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1657. elif name == 'OgrSelect':
  1658. winOgr = self.FindWindowById(id)
  1659. # enable / disable widgets & update values
  1660. rbox = self.FindWindowByName('VectorFormat')
  1661. self.hsizer.Remove(rbox)
  1662. if sel == 0: # -> native
  1663. winOgr.Hide()
  1664. self.hsizer.Remove(winOgr)
  1665. self.hsizer.Add(item = winNative,
  1666. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1667. border = 5)
  1668. winNative.Show()
  1669. p['value'] = winNative.GetValue()
  1670. elif sel == 1: # -> OGR
  1671. sizer = wx.BoxSizer(wx.VERTICAL)
  1672. winNative.Hide()
  1673. self.hsizer.Remove(winNative)
  1674. sizer.Add(item = winOgr)
  1675. winOgr.Show()
  1676. p['value'] = winOgr.GetDsn()
  1677. self.hsizer.Add(item = sizer,
  1678. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1679. border = 5)
  1680. self.hsizer.Add(item = rbox,
  1681. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1682. wx.RIGHT | wx.ALIGN_TOP,
  1683. border = 5)
  1684. self.hsizer.Layout()
  1685. self.Layout()
  1686. self.OnUpdateValues()
  1687. self.OnUpdateSelection(event)
  1688. def OnUpdateDialog(self, event):
  1689. for fn, kwargs in event.data.iteritems():
  1690. fn(**kwargs)
  1691. self.parent.updateValuesHook()
  1692. def OnVerbosity(self, event):
  1693. """!Verbosity level changed"""
  1694. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1695. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1696. if event.IsChecked():
  1697. if event.GetId() == verbose.GetId():
  1698. if quiet.IsChecked():
  1699. quiet.SetValue(False)
  1700. self.task.get_flag('quiet')['value'] = False
  1701. else:
  1702. if verbose.IsChecked():
  1703. verbose.SetValue(False)
  1704. self.task.get_flag('verbose')['value'] = False
  1705. event.Skip()
  1706. def OnPageChange(self, event):
  1707. if not event:
  1708. sel = self.notebook.GetSelection()
  1709. else:
  1710. sel = event.GetSelection()
  1711. idx = self.notebook.GetPageIndexByName('manual')
  1712. if idx > -1 and sel == idx:
  1713. # calling LoadPage() is strangely time-consuming (only first call)
  1714. # FIXME: move to helpPage.__init__()
  1715. if not self.manualTab.IsLoaded():
  1716. wx.Yield()
  1717. self.manualTab.LoadPage()
  1718. self.Layout()
  1719. if event:
  1720. # skip is needed for wx.Notebook on Windows
  1721. event.Skip()
  1722. # this is needed for dialogs launched from layer manager
  1723. # event is somehow propagated?
  1724. event.StopPropagation()
  1725. def _switchPageHandler(self, event, notification):
  1726. self._switchPage(notification=notification)
  1727. event.Skip()
  1728. def _switchPage(self, notification):
  1729. """!Manages @c 'output' notebook page according to event notification."""
  1730. if notification == Notification.HIGHLIGHT:
  1731. self.notebook.HighlightPageByName('output')
  1732. if notification == Notification.MAKE_VISIBLE:
  1733. self.notebook.SetSelectionByName('output')
  1734. if notification == Notification.RAISE_WINDOW:
  1735. self.notebook.SetSelectionByName('output')
  1736. self.SetFocus()
  1737. self.Raise()
  1738. def OnColorChange(self, event):
  1739. myId = event.GetId()
  1740. for p in self.task.params:
  1741. if 'wxId' in p and myId in p['wxId']:
  1742. multiple = p['wxId'][1] is not None # multiple colors
  1743. hasTansp = p['wxId'][2] is not None
  1744. if multiple:
  1745. # selected color is added at the end of textCtrl
  1746. colorchooser = wx.FindWindowById(p['wxId'][0])
  1747. new_color = colorchooser.GetValue()[:]
  1748. new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
  1749. textCtrl = wx.FindWindowById(p['wxId'][1])
  1750. val = textCtrl.GetValue()
  1751. sep = ','
  1752. if val and val[-1] != sep:
  1753. val += sep
  1754. val += new_label
  1755. textCtrl.SetValue(val)
  1756. p[ 'value' ] = val
  1757. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  1758. p[ 'value' ] = 'none'
  1759. else:
  1760. colorchooser = wx.FindWindowById(p['wxId'][0])
  1761. new_color = colorchooser.GetValue()[:]
  1762. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1763. # under wx2.8.1
  1764. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1765. colorchooser.SetLabel(new_label)
  1766. colorchooser.SetColour(new_color)
  1767. colorchooser.Refresh()
  1768. p[ 'value' ] = colorchooser.GetLabel()
  1769. self.OnUpdateValues()
  1770. def OnUpdateValues(self, event = None):
  1771. """!If we were part of a richer interface, report back the
  1772. current command being built.
  1773. This method should be set by the parent of this panel if
  1774. needed. It's a hook, actually. Beware of what is 'self' in
  1775. the method def, though. It will be called with no arguments.
  1776. """
  1777. pass
  1778. def OnCheckBoxMulti(self, event):
  1779. """!Fill the values as a ','-separated string according to
  1780. current status of the checkboxes.
  1781. """
  1782. me = event.GetId()
  1783. theParam = None
  1784. for p in self.task.params:
  1785. if 'wxId' in p and me in p['wxId']:
  1786. theParam = p
  1787. myIndex = p['wxId'].index(me)
  1788. # Unpack current value list
  1789. currentValues = {}
  1790. for isThere in theParam.get('value', '').split(','):
  1791. currentValues[isThere] = 1
  1792. theValue = theParam['values'][myIndex]
  1793. if event.Checked():
  1794. currentValues[ theValue ] = 1
  1795. else:
  1796. del currentValues[ theValue ]
  1797. # Keep the original order, so that some defaults may be recovered
  1798. currentValueList = []
  1799. for v in theParam['values']:
  1800. if v in currentValues:
  1801. currentValueList.append(v)
  1802. # Pack it back
  1803. theParam['value'] = ','.join(currentValueList)
  1804. self.OnUpdateValues()
  1805. def OnSetValue(self, event):
  1806. """!Retrieve the widget value and set the task value field
  1807. accordingly.
  1808. Use for widgets that have a proper GetValue() method, i.e. not
  1809. for selectors.
  1810. """
  1811. myId = event.GetId()
  1812. me = wx.FindWindowById(myId)
  1813. name = me.GetName()
  1814. found = False
  1815. for porf in self.task.params + self.task.flags:
  1816. if 'wxId' not in porf:
  1817. continue
  1818. if myId in porf['wxId']:
  1819. found = True
  1820. break
  1821. if not found:
  1822. return
  1823. if name == 'GdalSelect':
  1824. porf['value'] = event.dsn
  1825. elif name == 'ModelParam':
  1826. porf['parameterized'] = me.IsChecked()
  1827. else:
  1828. if isinstance(me, wx.SpinCtrl):
  1829. porf['value'] = str(me.GetValue())
  1830. else:
  1831. porf['value'] = me.GetValue()
  1832. self.OnUpdateValues(event)
  1833. event.Skip()
  1834. def OnSetSymbol(self, event):
  1835. """!Shows dialog for symbol selection"""
  1836. myId = event.GetId()
  1837. for p in self.task.params:
  1838. if 'wxId' in p and myId in p['wxId']:
  1839. from gui_core.dialogs import SymbolDialog
  1840. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1841. currentSymbol = p['value'])
  1842. if dlg.ShowModal() == wx.ID_OK:
  1843. img = dlg.GetSelectedSymbolPath()
  1844. p['value'] = dlg.GetSelectedSymbolName()
  1845. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1846. label = wx.FindWindowById(p['wxId'][1])
  1847. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1848. label.SetLabel(p['value'])
  1849. self.OnUpdateValues(event)
  1850. dlg.Destroy()
  1851. def OnTimelineTool(self, event):
  1852. """!Show Timeline Tool with dataset(s) from gselect.
  1853. TODO: update from gselect automatically
  1854. """
  1855. myId = event.GetId()
  1856. for p in self.task.params:
  1857. if 'wxId' in p and myId in p['wxId']:
  1858. select = self.FindWindowById(p['wxId'][0])
  1859. if not select.GetValue():
  1860. gcmd.GMessage(parent=self, message=_("No dataset given."))
  1861. return
  1862. datasets = select.GetValue().split(',')
  1863. from timeline import frame
  1864. frame.run(parent=self, datasets=datasets)
  1865. def OnUpdateSelection(self, event):
  1866. """!Update dialog (layers, tables, columns, etc.)
  1867. """
  1868. if not hasattr(self.parent, "updateThread"):
  1869. if event:
  1870. event.Skip()
  1871. return
  1872. if event:
  1873. self.parent.updateThread.Update(UpdateDialog,
  1874. self,
  1875. event,
  1876. event.GetId(),
  1877. self.task)
  1878. else:
  1879. self.parent.updateThread.Update(UpdateDialog,
  1880. self,
  1881. None,
  1882. None,
  1883. self.task)
  1884. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1885. """!Produce a command line string (list) or feeding into GRASS.
  1886. @param ignoreErrors True then it will return whatever has been
  1887. built so far, even though it would not be a correct command
  1888. for GRASS
  1889. """
  1890. try:
  1891. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1892. ignoreRequired = ignoreRequired)
  1893. except ValueError, err:
  1894. dlg = wx.MessageDialog(parent = self,
  1895. message = unicode(err),
  1896. caption = _("Error in %s") % self.task.name,
  1897. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1898. dlg.ShowModal()
  1899. dlg.Destroy()
  1900. cmd = None
  1901. return cmd
  1902. def OnSize(self, event):
  1903. width = event.GetSize()[0]
  1904. fontsize = self.GetFont().GetPointSize()
  1905. text_width = max(width / (fontsize - 3), 70)
  1906. for id in self.label_id:
  1907. win = self.FindWindowById(id)
  1908. label = win.GetLabel()
  1909. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1910. win.SetLabel(label_new)
  1911. event.Skip()
  1912. def AddBitmapToImageList(self, section, imageList):
  1913. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1914. iconSectionDict = {'manual': os.path.join(globalvar.ETCICONDIR, iconTheme, 'help.png')}
  1915. if section in iconSectionDict.keys():
  1916. image = wx.Image(iconSectionDict[section]).Scale(16, 16, wx.IMAGE_QUALITY_HIGH)
  1917. idx = imageList.Add(wx.BitmapFromImage(image))
  1918. return idx
  1919. return -1
  1920. class GUI:
  1921. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1922. centreOnParent = False, checkError = False):
  1923. """!Parses GRASS commands when module is imported and used from
  1924. Layer Manager.
  1925. """
  1926. self.parent = parent
  1927. self.show = show
  1928. self.modal = modal
  1929. self._giface = giface
  1930. self.centreOnParent = centreOnParent
  1931. self.checkError = checkError
  1932. self.grass_task = None
  1933. self.cmd = list()
  1934. global _blackList
  1935. if self.parent:
  1936. _blackList['enabled'] = True
  1937. else:
  1938. _blackList['enabled'] = False
  1939. def GetCmd(self):
  1940. """!Get validated command"""
  1941. return self.cmd
  1942. def ParseCommand(self, cmd, completed = None):
  1943. """!Parse command
  1944. Note: cmd is given as list
  1945. If command is given with options, return validated cmd list:
  1946. - add key name for first parameter if not given
  1947. - change mapname to mapname@mapset
  1948. """
  1949. dcmd_params = {}
  1950. if completed == None:
  1951. get_dcmd = None
  1952. layer = None
  1953. dcmd_params = None
  1954. else:
  1955. get_dcmd = completed[0]
  1956. layer = completed[1]
  1957. if completed[2]:
  1958. dcmd_params.update(completed[2])
  1959. # parse the interface decription
  1960. try:
  1961. global _blackList
  1962. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1963. blackList = _blackList)
  1964. except (grass.ScriptError, ValueError), e:
  1965. raise gcmd.GException(e.value)
  1966. # if layer parameters previously set, re-insert them into dialog
  1967. if completed is not None:
  1968. if 'params' in dcmd_params:
  1969. self.grass_task.params = dcmd_params['params']
  1970. if 'flags' in dcmd_params:
  1971. self.grass_task.flags = dcmd_params['flags']
  1972. err = list()
  1973. # update parameters if needed && validate command
  1974. if len(cmd) > 1:
  1975. i = 0
  1976. cmd_validated = [cmd[0]]
  1977. for option in cmd[1:]:
  1978. if option[0] == '-': # flag
  1979. if option[1] == '-':
  1980. self.grass_task.set_flag(option[2:], True)
  1981. else:
  1982. self.grass_task.set_flag(option[1], True)
  1983. cmd_validated.append(option)
  1984. else: # parameter
  1985. try:
  1986. key, value = option.split('=', 1)
  1987. except ValueError:
  1988. if self.grass_task.firstParam:
  1989. if i == 0: # add key name of first parameter if not given
  1990. key = self.grass_task.firstParam
  1991. value = option
  1992. else:
  1993. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1994. else:
  1995. continue
  1996. element = self.grass_task.get_param(key, raiseError = False)
  1997. if not element:
  1998. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1999. { 'cmd' : cmd[0],
  2000. 'key' : key })
  2001. continue
  2002. multiple = element['multiple']
  2003. element = element['element']
  2004. # do we need to find mapset for each of multiple maps?
  2005. if element in ['cell', 'vector'] and not multiple:
  2006. # mapname -> mapname@mapset
  2007. try:
  2008. name, mapset = value.split('@')
  2009. except ValueError:
  2010. mapset = grass.find_file(value, element)['mapset']
  2011. curr_mapset = grass.gisenv()['MAPSET']
  2012. if mapset and mapset != curr_mapset:
  2013. value = value + '@' + mapset
  2014. self.grass_task.set_param(key, value)
  2015. cmd_validated.append(key + '=' + value)
  2016. i += 1
  2017. # update original command list
  2018. cmd = cmd_validated
  2019. if self.show is not None:
  2020. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  2021. task_description = self.grass_task,
  2022. get_dcmd = get_dcmd, layer = layer)
  2023. else:
  2024. self.mf = None
  2025. if get_dcmd is not None:
  2026. # update only propwin reference
  2027. get_dcmd(dcmd = None, layer = layer, params = None,
  2028. propwin = self.mf)
  2029. if self.show is not None:
  2030. self.mf.notebookpanel.OnUpdateSelection(None)
  2031. if self.show is True:
  2032. if self.parent and self.centreOnParent:
  2033. self.mf.CentreOnParent()
  2034. else:
  2035. self.mf.CenterOnScreen()
  2036. self.mf.Show(self.show)
  2037. self.mf.MakeModal(self.modal)
  2038. else:
  2039. self.mf.OnApply(None)
  2040. self.cmd = cmd
  2041. if self.checkError:
  2042. return self.grass_task, err
  2043. else:
  2044. return self.grass_task
  2045. def GetCommandInputMapParamKey(self, cmd):
  2046. """!Get parameter key for input raster/vector map
  2047. @param cmd module name
  2048. @return parameter key
  2049. @return None on failure
  2050. """
  2051. # parse the interface decription
  2052. if not self.grass_task:
  2053. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2054. self.grass_task = gtask.processTask(tree).get_task()
  2055. for p in self.grass_task.params:
  2056. if p.get('name', '') in ('input', 'map'):
  2057. age = p.get('age', '')
  2058. prompt = p.get('prompt', '')
  2059. element = p.get('element', '')
  2060. if age == 'old' and \
  2061. element in ('cell', 'grid3', 'vector') and \
  2062. prompt in ('raster', '3d-raster', 'vector'):
  2063. return p.get('name', None)
  2064. return None
  2065. class GrassGUIApp(wx.App):
  2066. """!Stand-alone GRASS command GUI
  2067. """
  2068. def __init__(self, grass_task):
  2069. self.grass_task = grass_task
  2070. wx.App.__init__(self, False)
  2071. def OnInit(self):
  2072. msg = self.grass_task.get_error_msg()
  2073. if msg:
  2074. gcmd.GError(msg + '\n\n' +
  2075. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2076. return True
  2077. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  2078. self.mf.CentreOnScreen()
  2079. self.mf.Show(True)
  2080. self.SetTopWindow(self.mf)
  2081. return True
  2082. USAGE_MESSAGE = """Usage:
  2083. {name} <grass module>
  2084. {name} <full path to file>
  2085. python {name} <grass module>
  2086. Test:
  2087. python {name} test
  2088. python {name} g.region
  2089. python {name} "g.region -p"
  2090. python {name} temporal/t.list/t.list.py"""
  2091. if __name__ == "__main__":
  2092. if len(sys.argv) == 1:
  2093. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2094. if sys.argv[1] != 'test':
  2095. q = wx.LogNull()
  2096. from core.debug import Debug
  2097. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2098. cmd = utils.split(sys.argv[1])
  2099. task = gtask.grassTask(gcmd.GetRealCmd(cmd[0]))
  2100. task.set_options(cmd[1:])
  2101. Debug.msg(1, "forms.py opening form for: %s" % task.get_cmd(ignoreErrors=True))
  2102. app = GrassGUIApp(task)
  2103. app.MainLoop()
  2104. else: #Test
  2105. # Test grassTask from within a GRASS session
  2106. if os.getenv("GISBASE") is not None:
  2107. task = gtask.grassTask("d.vect")
  2108. task.get_param('map')['value'] = "map_name"
  2109. task.get_flag('i')['value'] = True
  2110. task.get_param('layer')['value'] = 1
  2111. task.get_param('bcolor')['value'] = "red"
  2112. # the default parameter display is added automatically
  2113. assert ' '.join(task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape bcolor=red"
  2114. print "Creation of task successful"
  2115. # Test interface building with handmade grassTask,
  2116. # possibly outside of a GRASS session.
  2117. print "Now creating a module dialog (task frame)"
  2118. task = gtask.grassTask()
  2119. task.name = "TestTask"
  2120. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2121. task.keywords = ["grass","test","task"]
  2122. task.params = [
  2123. {
  2124. "name" : "text",
  2125. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2126. "label" : "Enter some text",
  2127. "key_desc": ["value"],
  2128. "values_desc": []
  2129. },{
  2130. "name" : "hidden_text",
  2131. "description" : "This text should not appear in the form",
  2132. "hidden" : True,
  2133. "key_desc": ["value"],
  2134. "values_desc": []
  2135. },{
  2136. "name" : "text_default",
  2137. "description" : "Enter text to override the default",
  2138. "default" : "default text",
  2139. "key_desc": ["value"],
  2140. "values_desc": []
  2141. },{
  2142. "name" : "text_prefilled",
  2143. "description" : "You should see a friendly welcome message here",
  2144. "value" : "hello, world",
  2145. "key_desc": ["value"],
  2146. "values_desc": []
  2147. },{
  2148. "name" : "plain_color",
  2149. "description" : "This is a plain color, and it is a compulsory parameter",
  2150. "required" : False,
  2151. "gisprompt" : True,
  2152. "prompt" : "color",
  2153. "key_desc": ["value"],
  2154. "values_desc": []
  2155. },{
  2156. "name" : "transparent_color",
  2157. "description" : "This color becomes transparent when set to none",
  2158. "guisection" : "tab",
  2159. "gisprompt" : True,
  2160. "prompt" : "color",
  2161. "key_desc": ["value"],
  2162. "values_desc": []
  2163. },{
  2164. "name" : "multi",
  2165. "description" : "A multiple selection",
  2166. 'default': u'red,green,blue',
  2167. 'gisprompt': False,
  2168. 'guisection': 'tab',
  2169. 'multiple': u'yes',
  2170. 'type': u'string',
  2171. 'value': '',
  2172. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2173. "key_desc": ["value"],
  2174. "values_desc": []
  2175. },{
  2176. "name" : "single",
  2177. "description" : "A single multiple-choice selection",
  2178. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2179. "guisection" : "tab",
  2180. "key_desc": ["value"],
  2181. "values_desc": []
  2182. },{
  2183. "name" : "large_multi",
  2184. "description" : "A large multiple selection",
  2185. "gisprompt" : False,
  2186. "multiple" : "yes",
  2187. # values must be an array of strings
  2188. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
  2189. "key_desc": ["value"],
  2190. "values_desc": []
  2191. },{
  2192. "name" : "a_file",
  2193. "description" : "A file selector",
  2194. "gisprompt" : True,
  2195. "element" : "file",
  2196. "key_desc": ["value"],
  2197. "values_desc": []
  2198. }
  2199. ]
  2200. task.flags = [
  2201. {
  2202. "name" : "a",
  2203. "description" : "Some flag, will appear in Main since it is required",
  2204. "required" : True,
  2205. "value" : False,
  2206. "suppress_required": False
  2207. },{
  2208. "name" : "b",
  2209. "description" : "pre-filled flag, will appear in options since it is not required",
  2210. "value" : True,
  2211. "suppress_required": False
  2212. },{
  2213. "name" : "hidden_flag",
  2214. "description" : "hidden flag, should not be changeable",
  2215. "hidden" : "yes",
  2216. "value" : True,
  2217. "suppress_required": False
  2218. }
  2219. ]
  2220. q = wx.LogNull()
  2221. GrassGUIApp(task).MainLoop()