forms.py 114 KB

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