forms.py 114 KB

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