dialogs.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588
  1. """
  2. @package gui_core.dialogs
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - :class:`SimpleDialog`
  6. - :class:`LocationDialog`
  7. - :class:`MapsetDialog`
  8. - :class:`VectorDialog`
  9. - :class:`NewVectorDialog`
  10. - :class:`SavedRegion`
  11. - :class:`GroupDialog`
  12. - :class:`MapLayersDialog`
  13. - :class:`SetOpacityDialog`
  14. - :class:`ImageSizeDialog`
  15. - :class:`SqlQueryFrame`
  16. - :class:`SymbolDialog`
  17. - :class:`QuitDialog`
  18. - :class:`DefaultFontDialog`
  19. (C) 2008-2016 by the GRASS Development Team
  20. This program is free software under the GNU General Public License
  21. (>=v2). Read the file COPYING that comes with GRASS for details.
  22. @author Martin Landa <landa.martin gmail.com>
  23. @author Anna Kratochvilova <kratochanna gmail.com> (GroupDialog, SymbolDialog)
  24. """
  25. import os
  26. import sys
  27. import re
  28. import wx
  29. from grass.script import core as grass
  30. from grass.script.utils import natural_sort, try_remove
  31. from grass.pydispatch.signal import Signal
  32. from core import globalvar
  33. from core.gcmd import GError, RunCommand, GMessage
  34. from gui_core.gselect import LocationSelect, MapsetSelect, Select, \
  35. OgrTypeSelect, SubGroupSelect
  36. from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator, MapValidator
  37. from core.utils import _
  38. from core.settings import UserSettings
  39. from core.debug import Debug
  40. from gui_core.wrap import SpinCtrl
  41. class SimpleDialog(wx.Dialog):
  42. def __init__(self, parent, title, id=wx.ID_ANY,
  43. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  44. **kwargs):
  45. """General dialog to choose given element (location, mapset, vector map, etc.)
  46. :param parent: window
  47. :param title: window title
  48. """
  49. wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
  50. self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
  51. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  52. self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  53. self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
  54. self.btnOK.SetDefault()
  55. self.__layout()
  56. self.warning = _("Required item is not set.")
  57. def __layout(self):
  58. """Do layout"""
  59. self.sizer = wx.BoxSizer(wx.VERTICAL)
  60. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  61. # self.informLabel = wx.StaticText(self.panel, id = wx.ID_ANY)
  62. # buttons
  63. btnSizer = wx.StdDialogButtonSizer()
  64. btnSizer.AddButton(self.btnCancel)
  65. btnSizer.AddButton(self.btnOK)
  66. btnSizer.Realize()
  67. self.sizer.Add(self.dataSizer, proportion=1,
  68. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  69. # self.sizer.Add(item = self.informLabel, proportion = 0, flag = wx.ALL, border = 5)
  70. self.sizer.Add(btnSizer, proportion=0,
  71. flag=wx.EXPAND | wx.ALL, border=5)
  72. def ValidatorCallback(self, win):
  73. GMessage(parent=self, message=self.warning)
  74. # self.informLabel.SetForegroundColour(wx.Colour(255, 0, 0))
  75. # self.informLabel.SetLabel(self.warning)
  76. class LocationDialog(SimpleDialog):
  77. """Dialog used to select location"""
  78. def __init__(self, parent, title=_("Select GRASS location and mapset")):
  79. SimpleDialog.__init__(self, parent, title)
  80. self.element1 = LocationSelect(
  81. parent=self.panel,
  82. id=wx.ID_ANY,
  83. size=globalvar.DIALOG_GSELECT_SIZE,
  84. validator=SimpleValidator(
  85. callback=self.ValidatorCallback))
  86. self.element1.Bind(wx.EVT_TEXT, self.OnLocation)
  87. self.element2 = MapsetSelect(
  88. parent=self.panel,
  89. id=wx.ID_ANY,
  90. size=globalvar.DIALOG_GSELECT_SIZE,
  91. setItems=False,
  92. skipCurrent=True,
  93. validator=SimpleValidator(
  94. callback=self.ValidatorCallback))
  95. self.element1.SetFocus()
  96. self.warning = _("Location or mapset is not defined.")
  97. self._layout()
  98. self.SetMinSize(self.GetSize())
  99. def _layout(self):
  100. """Do layout"""
  101. self.dataSizer.Add(
  102. wx.StaticText(
  103. parent=self.panel,
  104. id=wx.ID_ANY,
  105. label=_("Name of GRASS location:")),
  106. proportion=0,
  107. flag=wx.ALL,
  108. border=1)
  109. self.dataSizer.Add(self.element1, proportion=0,
  110. flag=wx.EXPAND | wx.ALL, border=1)
  111. self.dataSizer.Add(
  112. wx.StaticText(
  113. parent=self.panel,
  114. id=wx.ID_ANY,
  115. label=_("Name of mapset:")),
  116. proportion=0,
  117. flag=wx.EXPAND | wx.ALL,
  118. border=1)
  119. self.dataSizer.Add(self.element2, proportion=0,
  120. flag=wx.EXPAND | wx.ALL, border=1)
  121. self.panel.SetSizer(self.sizer)
  122. self.sizer.Fit(self)
  123. def OnLocation(self, event):
  124. """Select mapset given location name"""
  125. location = event.GetString()
  126. if location:
  127. dbase = grass.gisenv()['GISDBASE']
  128. self.element2.UpdateItems(dbase=dbase, location=location)
  129. self.element2.SetSelection(0)
  130. mapset = self.element2.GetStringSelection()
  131. def GetValues(self):
  132. """Get location, mapset"""
  133. return (self.element1.GetValue(), self.element2.GetValue())
  134. class MapsetDialog(SimpleDialog):
  135. """Dialog used to select mapset"""
  136. def __init__(self, parent, title=_("Select mapset in GRASS location"),
  137. location=None):
  138. SimpleDialog.__init__(self, parent, title)
  139. if location:
  140. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  141. else:
  142. self.SetTitle(
  143. self.GetTitle() + ' <%s>' %
  144. grass.gisenv()['LOCATION_NAME'])
  145. self.element = MapsetSelect(
  146. parent=self.panel,
  147. id=wx.ID_ANY,
  148. skipCurrent=True,
  149. size=globalvar.DIALOG_GSELECT_SIZE,
  150. validator=SimpleValidator(
  151. callback=self.ValidatorCallback))
  152. self.element.SetFocus()
  153. self.warning = _("Name of mapset is missing.")
  154. self._layout()
  155. self.SetMinSize(self.GetSize())
  156. def _layout(self):
  157. """Do layout"""
  158. self.dataSizer.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  159. label=_("Name of mapset:")),
  160. proportion=0, flag=wx.ALL, border=1)
  161. self.dataSizer.Add(self.element, proportion=0,
  162. flag=wx.EXPAND | wx.ALL, border=1)
  163. self.panel.SetSizer(self.sizer)
  164. self.sizer.Fit(self)
  165. def GetMapset(self):
  166. return self.element.GetValue()
  167. class VectorDialog(SimpleDialog):
  168. def __init__(self, parent, title=_("Select vector map"), layerTree=None):
  169. """Dialog for selecting existing vector map
  170. :param parent: parent window
  171. :param title: window title
  172. :param layerTree: show only vector maps in given layer tree if not None
  173. :return: dialog instance
  174. """
  175. SimpleDialog.__init__(self, parent, title)
  176. self.element = Select(
  177. parent=self.panel,
  178. id=wx.ID_ANY,
  179. size=globalvar.DIALOG_GSELECT_SIZE,
  180. type='vector',
  181. layerTree=layerTree,
  182. validator=MapValidator())
  183. self.element.SetFocus()
  184. self.warning = _("Name of vector map is missing.")
  185. wx.CallAfter(self._layout)
  186. def _layout(self):
  187. """Do layout"""
  188. self.dataSizer.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  189. label=_("Name of vector map:")),
  190. proportion=0, flag=wx.ALL, border=1)
  191. self.dataSizer.Add(self.element, proportion=0,
  192. flag=wx.EXPAND | wx.ALL, border=1)
  193. self.panel.SetSizer(self.sizer)
  194. self.sizer.Fit(self)
  195. def GetName(self, full=False):
  196. """Get name of vector map to be created
  197. :param full: True to get fully qualified name
  198. """
  199. name = self.element.GetValue()
  200. if full:
  201. if '@' in name:
  202. return name
  203. else:
  204. return name + '@' + grass.gisenv()['MAPSET']
  205. return name.split('@', 1)[0]
  206. class NewVectorDialog(VectorDialog):
  207. def __init__(self, parent, title=_("Create new vector map"),
  208. disableAdd=False, disableTable=False, showType=False):
  209. """Dialog for creating new vector map
  210. :param parent: parent window
  211. :param title: window title
  212. :param disableAdd: disable 'add layer' checkbox
  213. :param disableTable: disable 'create table' checkbox
  214. :param showType: True to show feature type selector (used for creating new empty OGR layers)
  215. :return: dialog instance
  216. """
  217. VectorDialog.__init__(self, parent, title)
  218. # determine output format
  219. if showType:
  220. self.ftype = OgrTypeSelect(parent=self, panel=self.panel)
  221. else:
  222. self.ftype = None
  223. # create attribute table
  224. self.table = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
  225. label=_("Create attribute table"))
  226. self.table.SetValue(True)
  227. if disableTable:
  228. self.table.Enable(False)
  229. if showType:
  230. self.keycol = None
  231. else:
  232. self.keycol = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
  233. size=globalvar.DIALOG_SPIN_SIZE)
  234. self.keycol.SetValue(
  235. UserSettings.Get(
  236. group='atm',
  237. key='keycolumn',
  238. subkey='value'))
  239. if disableTable:
  240. self.keycol.Enable(False)
  241. self.addbox = wx.CheckBox(
  242. parent=self.panel,
  243. label=_('Add created map into layer tree'),
  244. style=wx.NO_BORDER)
  245. if disableAdd:
  246. self.addbox.SetValue(True)
  247. self.addbox.Enable(False)
  248. else:
  249. self.addbox.SetValue(
  250. UserSettings.Get(
  251. group='cmd',
  252. key='addNewLayer',
  253. subkey='enabled'))
  254. self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
  255. self.warning = _("Name of new vector map is missing.")
  256. def OnTable(self, event):
  257. if self.keycol:
  258. self.keycol.Enable(event.IsChecked())
  259. def _layout(self):
  260. """Do layout"""
  261. self.dataSizer.Add(
  262. wx.StaticText(
  263. parent=self.panel,
  264. id=wx.ID_ANY,
  265. label=_("Name for new vector map:")),
  266. proportion=0,
  267. flag=wx.ALL,
  268. border=1)
  269. self.dataSizer.Add(self.element, proportion=0,
  270. flag=wx.EXPAND | wx.ALL, border=1)
  271. if self.ftype:
  272. self.dataSizer.AddSpacer(1)
  273. self.dataSizer.Add(self.ftype, proportion=0,
  274. flag=wx.EXPAND | wx.ALL, border=1)
  275. self.dataSizer.Add(self.table, proportion=0,
  276. flag=wx.EXPAND | wx.ALL, border=1)
  277. if self.keycol:
  278. keySizer = wx.BoxSizer(wx.HORIZONTAL)
  279. keySizer.Add(
  280. wx.StaticText(
  281. parent=self.panel,
  282. label=_("Key column:")),
  283. proportion=0,
  284. flag=wx.ALIGN_CENTER_VERTICAL)
  285. keySizer.AddSpacer(10)
  286. keySizer.Add(self.keycol, proportion=0,
  287. flag=wx.ALIGN_RIGHT)
  288. self.dataSizer.Add(keySizer, proportion=1,
  289. flag=wx.EXPAND | wx.ALL, border=1)
  290. self.dataSizer.AddSpacer(5)
  291. self.dataSizer.Add(self.addbox, proportion=0,
  292. flag=wx.EXPAND | wx.ALL, border=1)
  293. self.panel.SetSizer(self.sizer)
  294. self.sizer.Fit(self)
  295. self.SetMinSize(self.GetSize())
  296. def GetKey(self):
  297. """Get key column name"""
  298. if self.keycol:
  299. return self.keycol.GetValue()
  300. return UserSettings.Get(group='atm', key='keycolumn', subkey='value')
  301. def IsChecked(self, key):
  302. """Get dialog properties
  303. :param key: window key ('add', 'table')
  304. :return: True/False
  305. :return: None on error
  306. """
  307. if key == 'add':
  308. return self.addbox.IsChecked()
  309. elif key == 'table':
  310. return self.table.IsChecked()
  311. return None
  312. def GetFeatureType(self):
  313. """Get feature type for OGR
  314. :return: feature type as string
  315. :return: None for native format
  316. """
  317. if self.ftype:
  318. return self.ftype.GetType()
  319. return None
  320. def CreateNewVector(parent, cmd, title=_('Create new vector map'),
  321. exceptMap=None, giface=None,
  322. disableAdd=False, disableTable=False):
  323. """Create new vector map layer
  324. :param cmd: (prog, \*\*kwargs)
  325. :param title: window title
  326. :param exceptMap: list of maps to be excepted
  327. :param log:
  328. :param disableAdd: disable 'add layer' checkbox
  329. :param disableTable: disable 'create table' checkbox
  330. :return: dialog instance
  331. :return: None on error
  332. """
  333. vExternalOut = grass.parse_command('v.external.out', flags='g')
  334. isNative = vExternalOut['format'] == 'native'
  335. if cmd[0] == 'v.edit' and not isNative:
  336. showType = True
  337. else:
  338. showType = False
  339. dlg = NewVectorDialog(parent, title=title,
  340. disableAdd=disableAdd, disableTable=disableTable,
  341. showType=showType)
  342. if dlg.ShowModal() != wx.ID_OK:
  343. dlg.Destroy()
  344. return None
  345. outmap = dlg.GetName()
  346. key = dlg.GetKey()
  347. if outmap == exceptMap:
  348. GError(parent=parent,
  349. message=_("Unable to create vector map <%s>.") % outmap)
  350. dlg.Destroy()
  351. return None
  352. if dlg.table.IsEnabled() and not key:
  353. GError(parent=parent,
  354. message=_("Invalid or empty key column.\n"
  355. "Unable to create vector map <%s>.") % outmap)
  356. dlg.Destroy()
  357. return
  358. if outmap == '': # should not happen
  359. dlg.Destroy()
  360. return None
  361. # update cmd -> output name defined
  362. cmd[1][cmd[2]] = outmap
  363. if showType:
  364. cmd[1]['type'] = dlg.GetFeatureType()
  365. curMapset = grass.gisenv()['MAPSET']
  366. if isNative:
  367. listOfVectors = grass.list_grouped('vector')[curMapset]
  368. else:
  369. listOfVectors = RunCommand('v.external',
  370. quiet=True,
  371. parent=parent,
  372. read=True,
  373. flags='l',
  374. input=vExternalOut['dsn']).splitlines()
  375. overwrite = False
  376. if not UserSettings.Get(group='cmd', key='overwrite',
  377. subkey='enabled') and outmap in listOfVectors:
  378. dlgOw = wx.MessageDialog(
  379. parent,
  380. message=_(
  381. "Vector map <%s> already exists "
  382. "in the current mapset. "
  383. "Do you want to overwrite it?") %
  384. outmap,
  385. caption=_("Overwrite?"),
  386. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  387. if dlgOw.ShowModal() == wx.ID_YES:
  388. overwrite = True
  389. else:
  390. dlgOw.Destroy()
  391. dlg.Destroy()
  392. return None
  393. if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
  394. overwrite = True
  395. ret = RunCommand(prog=cmd[0],
  396. parent=parent,
  397. overwrite=overwrite,
  398. **cmd[1])
  399. if ret != 0:
  400. dlg.Destroy()
  401. return None
  402. if not isNative and not grass.find_file(
  403. outmap, element='vector', mapset=curMapset)['fullname']:
  404. # create link for OGR layers
  405. RunCommand('v.external',
  406. overwrite=overwrite,
  407. parent=parent,
  408. input=vExternalOut['dsn'],
  409. layer=outmap)
  410. # create attribute table
  411. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  412. if isNative:
  413. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  414. RunCommand('db.connect',
  415. flags='c')
  416. Debug.msg(1, "SQL: %s" % sql)
  417. RunCommand('db.execute',
  418. quiet=True,
  419. parent=parent,
  420. input='-',
  421. stdin=sql)
  422. RunCommand('v.db.connect',
  423. quiet=True,
  424. parent=parent,
  425. map=outmap,
  426. table=outmap,
  427. key=key,
  428. layer='1')
  429. # TODO: how to deal with attribute tables for OGR layers?
  430. # return fully qualified map name
  431. if '@' not in outmap:
  432. outmap += '@' + grass.gisenv()['MAPSET']
  433. # if giface:
  434. # giface.WriteLog(_("New vector map <%s> created") % outmap)
  435. return dlg
  436. class SavedRegion(wx.Dialog):
  437. def __init__(self, parent, title, id=wx.ID_ANY, loadsave='load',
  438. **kwargs):
  439. """Loading or saving of display extents to saved region file
  440. :param loadsave: load or save region?
  441. """
  442. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  443. self.loadsave = loadsave
  444. self.wind = ''
  445. sizer = wx.BoxSizer(wx.VERTICAL)
  446. box = wx.BoxSizer(wx.HORIZONTAL)
  447. label = wx.StaticText(parent=self, id=wx.ID_ANY)
  448. box.Add(
  449. label,
  450. proportion=0,
  451. flag=wx.ALIGN_CENTRE | wx.ALL,
  452. border=5)
  453. if loadsave == 'load':
  454. label.SetLabel(_("Load region:"))
  455. self._selection = Select(
  456. parent=self,
  457. size=globalvar.DIALOG_GSELECT_SIZE,
  458. type='windows')
  459. elif loadsave == 'save':
  460. label.SetLabel(_("Save region:"))
  461. self._selection = Select(
  462. parent=self,
  463. size=globalvar.DIALOG_GSELECT_SIZE,
  464. type='windows',
  465. mapsets=[
  466. grass.gisenv()['MAPSET']],
  467. fullyQualified=False)
  468. box.Add(
  469. self._selection,
  470. proportion=0,
  471. flag=wx.ALIGN_CENTRE | wx.ALL,
  472. border=5)
  473. self._selection.SetFocus()
  474. self._selection.Bind(wx.EVT_TEXT, self.OnRegion)
  475. sizer.Add(box, proportion=0, flag=wx.GROW |
  476. wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  477. line = wx.StaticLine(
  478. parent=self, id=wx.ID_ANY, size=(
  479. 20, -1), style=wx.LI_HORIZONTAL)
  480. sizer.Add(line, proportion=0, flag=wx.GROW |
  481. wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5)
  482. btnsizer = wx.StdDialogButtonSizer()
  483. btn = wx.Button(parent=self, id=wx.ID_OK)
  484. btn.SetDefault()
  485. btnsizer.AddButton(btn)
  486. btn = wx.Button(parent=self, id=wx.ID_CANCEL)
  487. btnsizer.AddButton(btn)
  488. btnsizer.Realize()
  489. sizer.Add(
  490. btnsizer,
  491. proportion=0,
  492. flag=wx.ALIGN_RIGHT | wx.ALL,
  493. border=5)
  494. self.SetSizer(sizer)
  495. sizer.Fit(self)
  496. self.Layout()
  497. def OnRegion(self, event):
  498. value = self._selection.GetValue()
  499. if '@' in value:
  500. value = value.rsplit('@', 1)[0]
  501. if not grass.legal_name(value):
  502. GMessage(parent=self,
  503. message=_("Name cannot begin with '.' "
  504. "and must not contain space, quotes, "
  505. "'/', '\'', '@', ',', '=', '*', "
  506. "and all other non-alphanumeric characters."))
  507. else:
  508. self.wind = value
  509. def GetName(self):
  510. """Return region name"""
  511. return self.wind
  512. class GroupDialog(wx.Dialog):
  513. """Dialog for creating/editing groups"""
  514. def __init__(self, parent=None, defaultGroup=None, defaultSubgroup=None,
  515. title=_("Create or edit imagery groups"),
  516. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  517. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  518. style=style, **kwargs)
  519. self.parent = parent
  520. self.defaultGroup = defaultGroup
  521. self.defaultSubgroup = defaultSubgroup
  522. self.currentGroup = self.defaultGroup
  523. self.currentSubgroup = self.defaultGroup
  524. self.dataChanged = False
  525. # signaling edit subgroup / group mode
  526. self.edit_subg = False
  527. # sungroup maps dict value - ischecked
  528. self.subgmaps = {}
  529. # list of group maps
  530. self.gmaps = []
  531. # pattern chosen for filtering
  532. self.flt_pattern = ''
  533. self.bodySizer = self._createDialogBody()
  534. # buttons
  535. btnOk = wx.Button(parent=self, id=wx.ID_OK)
  536. btnApply = wx.Button(parent=self, id=wx.ID_APPLY)
  537. btnClose = wx.Button(parent=self, id=wx.ID_CANCEL)
  538. btnOk.SetToolTipString(
  539. _("Apply changes to selected group and close dialog"))
  540. btnApply.SetToolTipString(_("Apply changes to selected group"))
  541. btnClose.SetToolTipString(_("Close dialog, changes are not applied"))
  542. # btnOk.SetDefault()
  543. # sizers & do layout
  544. # btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  545. # btnSizer.Add(item = btnClose, proportion = 0,
  546. # flag = wx.RIGHT | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
  547. # btnSizer.Add(item = btnApply, proportion = 0,
  548. # flag = wx.LEFT, border = 5)
  549. btnSizer = wx.StdDialogButtonSizer()
  550. btnSizer.AddButton(btnOk)
  551. btnSizer.AddButton(btnApply)
  552. btnSizer.AddButton(btnClose)
  553. btnSizer.Realize()
  554. mainSizer = wx.BoxSizer(wx.VERTICAL)
  555. mainSizer.Add(self.bodySizer, proportion=1,
  556. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  557. mainSizer.Add(wx.StaticLine(parent=self, id=wx.ID_ANY,
  558. style=wx.LI_HORIZONTAL), proportion=0,
  559. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  560. mainSizer.Add(btnSizer, proportion=0, flag=wx.LEFT |
  561. wx.RIGHT | wx.BOTTOM | wx.ALIGN_RIGHT, border=10)
  562. self.SetSizer(mainSizer)
  563. mainSizer.Fit(self)
  564. btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  565. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  566. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  567. # set dialog min size
  568. self.SetMinSize(self.GetSize())
  569. self.SetSize((-1, 400))
  570. def _createDialogBody(self):
  571. bodySizer = wx.BoxSizer(wx.VERTICAL)
  572. # TODO same text in MapLayersDialogBase
  573. filter_tooltip = _("Put here a regular expression."
  574. " Characters '.*' stand for anything,"
  575. " character '^' stands for the beginning"
  576. " and '$' for the end.")
  577. # group selection
  578. bodySizer.Add(wx.StaticText(parent=self, id=wx.ID_ANY,
  579. label=_("Select existing group or "
  580. "enter name of new group:")),
  581. flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP, border=10)
  582. self.groupSelect = Select(parent=self, type='group',
  583. mapsets=[grass.gisenv()['MAPSET']],
  584. size=globalvar.DIALOG_GSELECT_SIZE,
  585. fullyQualified=False) # searchpath?
  586. bodySizer.Add(self.groupSelect, flag=wx.TOP | wx.EXPAND, border=5)
  587. self.subg_chbox = wx.CheckBox(parent=self, id=wx.ID_ANY,
  588. label=_("Edit/create subgroup"))
  589. bodySizer.Add(self.subg_chbox,
  590. flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP, border=10)
  591. self.subg_panel = wx.Panel(self)
  592. subg_sizer = wx.BoxSizer(wx.VERTICAL)
  593. subg_sizer.Add(
  594. wx.StaticText(
  595. parent=self.subg_panel,
  596. id=wx.ID_ANY,
  597. label=_(
  598. "Select existing subgroup or "
  599. "enter name of new subgroup:")),
  600. flag=wx.ALIGN_CENTER_VERTICAL)
  601. self.subGroupSelect = SubGroupSelect(parent=self.subg_panel)
  602. subg_sizer.Add(
  603. self.subGroupSelect,
  604. flag=wx.EXPAND | wx.TOP,
  605. border=5)
  606. self.subg_panel.SetSizer(subg_sizer)
  607. bodySizer.Add(self.subg_panel, flag=wx.TOP | wx.EXPAND, border=5)
  608. bodySizer.AddSpacer(10)
  609. buttonSizer = wx.BoxSizer(wx.VERTICAL)
  610. # layers in group
  611. self.gListPanel = wx.Panel(self)
  612. gListSizer = wx.GridBagSizer(vgap=3, hgap=2)
  613. self.g_sel_all = wx.CheckBox(parent=self.gListPanel, id=wx.ID_ANY,
  614. label=_("Select all"))
  615. gListSizer.Add(self.g_sel_all,
  616. flag=wx.ALIGN_CENTER_VERTICAL,
  617. pos=(0, 1))
  618. gListSizer.Add(
  619. wx.StaticText(
  620. parent=self.gListPanel,
  621. label=_("Pattern:")),
  622. flag=wx.ALIGN_CENTER_VERTICAL,
  623. pos=(
  624. 1,
  625. 0))
  626. self.gfilter = wx.TextCtrl(parent=self.gListPanel, id=wx.ID_ANY,
  627. value="",
  628. size=(250, -1))
  629. self.gfilter.SetToolTipString(filter_tooltip)
  630. gListSizer.Add(self.gfilter,
  631. flag=wx.EXPAND,
  632. pos=(1, 1))
  633. gListSizer.Add(
  634. wx.StaticText(
  635. parent=self.gListPanel,
  636. label=_("List of maps:")),
  637. flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM,
  638. border=5,
  639. pos=(
  640. 2,
  641. 0))
  642. sizer = wx.BoxSizer(wx.HORIZONTAL)
  643. self.gLayerBox = wx.ListBox(
  644. parent=self.gListPanel, id=wx.ID_ANY, size=(-1, 150),
  645. style=wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
  646. sizer.Add(self.gLayerBox, proportion=1, flag=wx.EXPAND)
  647. self.addLayer = wx.Button(self.gListPanel, id=wx.ID_ADD)
  648. self.addLayer.SetToolTipString(
  649. _("Select map layers and add them to the list."))
  650. buttonSizer.Add(self.addLayer, flag=wx.BOTTOM, border=10)
  651. self.removeLayer = wx.Button(self.gListPanel, id=wx.ID_REMOVE)
  652. self.removeLayer.SetToolTipString(
  653. _("Remove selected layer(s) from list."))
  654. buttonSizer.Add(self.removeLayer)
  655. sizer.Add(buttonSizer, flag=wx.LEFT, border=5)
  656. gListSizer.Add(sizer, flag=wx.EXPAND, pos=(2, 1))
  657. gListSizer.AddGrowableCol(1)
  658. gListSizer.AddGrowableRow(2)
  659. self.gListPanel.SetSizer(gListSizer)
  660. bodySizer.Add(self.gListPanel, proportion=1, flag=wx.EXPAND)
  661. # layers in subgroup
  662. self.subgListPanel = wx.Panel(self)
  663. subgListSizer = wx.GridBagSizer(vgap=3, hgap=2)
  664. # select toggle
  665. self.subg_sel_all = wx.CheckBox(
  666. parent=self.subgListPanel,
  667. id=wx.ID_ANY,
  668. label=_("Select all"))
  669. subgListSizer.Add(self.subg_sel_all,
  670. flag=wx.ALIGN_CENTER_VERTICAL,
  671. pos=(0, 1))
  672. subgListSizer.Add(
  673. wx.StaticText(
  674. parent=self.subgListPanel,
  675. label=_("Pattern:")),
  676. flag=wx.ALIGN_CENTER_VERTICAL,
  677. pos=(
  678. 1,
  679. 0))
  680. self.subgfilter = wx.TextCtrl(parent=self.subgListPanel, id=wx.ID_ANY,
  681. value="",
  682. size=(250, -1))
  683. self.subgfilter.SetToolTipString(filter_tooltip)
  684. subgListSizer.Add(self.subgfilter,
  685. flag=wx.EXPAND,
  686. pos=(1, 1))
  687. subgListSizer.Add(
  688. wx.StaticText(
  689. parent=self.subgListPanel,
  690. label=_("List of maps:")),
  691. flag=wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM,
  692. border=5,
  693. pos=(
  694. 2,
  695. 0))
  696. self.subgListBox = wx.CheckListBox(
  697. parent=self.subgListPanel, id=wx.ID_ANY, size=(250, 100))
  698. self.subgListBox.SetToolTipString(
  699. _("Check maps from group to be included into subgroup."))
  700. subgListSizer.Add(self.subgListBox, flag=wx.EXPAND, pos=(2, 1))
  701. subgListSizer.AddGrowableCol(1)
  702. subgListSizer.AddGrowableRow(2)
  703. self.subgListPanel.SetSizer(subgListSizer)
  704. bodySizer.Add(self.subgListPanel, proportion=1, flag=wx.EXPAND)
  705. self.infoLabel = wx.StaticText(parent=self, id=wx.ID_ANY)
  706. bodySizer.Add(
  707. self.infoLabel,
  708. flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM,
  709. border=5)
  710. # bindings
  711. self.gfilter.Bind(wx.EVT_TEXT, self.OnGroupFilter)
  712. self.subgfilter.Bind(wx.EVT_TEXT, self.OnSubgroupFilter)
  713. self.gLayerBox.Bind(wx.EVT_LISTBOX, self.OnGLayerCheck)
  714. self.subgListBox.Bind(wx.EVT_CHECKLISTBOX, self.OnSubgLayerCheck)
  715. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnGroupSelected)
  716. self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  717. self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
  718. self.subg_chbox.Bind(wx.EVT_CHECKBOX, self.OnSubgChbox)
  719. self.subGroupSelect.Bind(
  720. wx.EVT_TEXT, lambda event: self.SubGroupSelected())
  721. self.subg_sel_all.Bind(wx.EVT_CHECKBOX, self.OnSubgSelAll)
  722. self.g_sel_all.Bind(wx.EVT_CHECKBOX, self.OnGSelAll)
  723. if self.defaultGroup:
  724. self.groupSelect.SetValue(self.defaultGroup)
  725. if self.defaultSubgroup is not None:
  726. self.subGroupSelect.SetValue(self.defaultSubgroup)
  727. self.subg_chbox.SetValue(1)
  728. self.SubgChbox(True)
  729. else:
  730. self.subg_chbox.SetValue(0)
  731. self.SubgChbox(False)
  732. return bodySizer
  733. def OnGLayerCheck(self, event):
  734. self._checkGSellAll()
  735. def OnSubgSelAll(self, event):
  736. check = event.Checked()
  737. for item in range(self.subgListBox.GetCount()):
  738. self.CheckSubgItem(item, check)
  739. self.dataChanged = True
  740. event.Skip()
  741. def OnGSelAll(self, event):
  742. check = event.Checked()
  743. if not check:
  744. self.gLayerBox.DeselectAll()
  745. else:
  746. for item in range(self.subgListBox.GetCount()):
  747. self.gLayerBox.Select(item)
  748. event.Skip()
  749. def _checkGSellAll(self):
  750. check = False
  751. nsel = len(self.gLayerBox.GetSelections())
  752. if self.gLayerBox.GetCount() == nsel and \
  753. self.gLayerBox.GetCount() != 0:
  754. check = True
  755. self.g_sel_all.SetValue(check)
  756. def _checkSubGSellAll(self):
  757. not_all_checked = False
  758. if self.subgListBox.GetCount() == 0:
  759. not_all_checked = True
  760. else:
  761. for item in range(self.subgListBox.GetCount()):
  762. if not self.subgListBox.IsChecked(item):
  763. not_all_checked = True
  764. self.subg_sel_all.SetValue(not not_all_checked)
  765. def OnSubgroupFilter(self, event):
  766. text = event.GetString()
  767. self.gfilter.ChangeValue(text)
  768. self.flt_pattern = text
  769. self.FilterGroup()
  770. self.FilterSubgroup()
  771. event.Skip()
  772. def OnGroupFilter(self, event):
  773. text = event.GetString()
  774. self.subgfilter.ChangeValue(text)
  775. self.flt_pattern = text
  776. self.FilterGroup()
  777. self.FilterSubgroup()
  778. event.Skip()
  779. def OnSubgLayerCheck(self, event):
  780. idx = event.GetInt()
  781. m = self.subgListBox.GetString(idx)
  782. self.subgmaps[m] = self.subgListBox.IsChecked(idx)
  783. self.dataChanged = True
  784. self._checkSubGSellAll()
  785. def CheckSubgItem(self, idx, val):
  786. m = self.subgListBox.GetString(idx)
  787. self.subgListBox.Check(idx, val)
  788. self.subgmaps[m] = val
  789. self.dataChanged = val
  790. def DisableSubgroupEdit(self):
  791. """Disable editation of subgroups in the dialog
  792. .. todo::
  793. used by gcp manager, maybe the gcp m should also support subgroups
  794. """
  795. self.edit_subg = False
  796. self.subg_panel.Hide()
  797. self.subg_chbox.Hide()
  798. self.subgListBox.Hide()
  799. self.Layout()
  800. def OnSubgChbox(self, event):
  801. edit_subg = self.subg_chbox.GetValue()
  802. self.SubgChbox(edit_subg)
  803. def SubgChbox(self, edit_subg):
  804. self._checkChange()
  805. if edit_subg:
  806. self.edit_subg = edit_subg
  807. self.SubGroupSelected()
  808. self._subgroupLayout()
  809. else:
  810. self.edit_subg = edit_subg
  811. self.GroupSelected()
  812. self._groupLayout()
  813. self.SetMinSize(self.GetBestSize())
  814. def _groupLayout(self):
  815. self.subg_panel.Hide()
  816. self.subgListPanel.Hide()
  817. self.gListPanel.Show()
  818. self.Layout()
  819. def _subgroupLayout(self):
  820. self.subg_panel.Show()
  821. self.subgListPanel.Show()
  822. self.gListPanel.Hide()
  823. self.Layout()
  824. def OnAddLayer(self, event):
  825. """Add new layer to listbox"""
  826. dlg = MapLayersDialogForGroups(
  827. parent=self, title=_("Add selected map layers into group"))
  828. if dlg.ShowModal() != wx.ID_OK:
  829. dlg.Destroy()
  830. return
  831. layers = dlg.GetMapLayers()
  832. for layer in layers:
  833. if layer not in self.gmaps:
  834. self.gLayerBox.Append(layer)
  835. self.gmaps.append(layer)
  836. self.dataChanged = True
  837. def OnRemoveLayer(self, event):
  838. """Remove layer from listbox"""
  839. while self.gLayerBox.GetSelections():
  840. sel = self.gLayerBox.GetSelections()[0]
  841. m = self.gLayerBox.GetString(sel)
  842. self.gLayerBox.Delete(sel)
  843. self.gmaps.remove(m)
  844. self.dataChanged = True
  845. def GetLayers(self):
  846. """Get layers"""
  847. if self.edit_subg:
  848. layers = []
  849. for maps, sel in self.subgmaps.iteritems():
  850. if sel:
  851. layers.append(maps)
  852. else:
  853. layers = self.gmaps[:]
  854. return layers
  855. def OnGroupSelected(self, event):
  856. """Text changed in group selector"""
  857. # callAfter must be called to close popup before other actions
  858. wx.CallAfter(self.GroupSelected)
  859. def GroupSelected(self):
  860. """Group was selected, check if changes were apllied"""
  861. self._checkChange()
  862. group, s = self.GetSelectedGroup()
  863. maps = list()
  864. groups = self.GetExistGroups()
  865. if group in groups:
  866. maps = self.GetGroupLayers(group)
  867. self.subGroupSelect.Insert(group)
  868. self.gmaps = maps
  869. maps = self._filter(maps)
  870. self.ShowGroupLayers(maps)
  871. self.currentGroup = group
  872. self.SubGroupSelected()
  873. self.ClearNotification()
  874. self._checkGSellAll()
  875. def FilterGroup(self):
  876. maps = self._filter(self.gmaps)
  877. self.ShowGroupLayers(maps)
  878. self._checkGSellAll()
  879. def FilterSubgroup(self):
  880. maps = self._filter(self.gmaps)
  881. self.subgListBox.Set(maps)
  882. for i, m in enumerate(maps):
  883. if m in self.subgmaps.iterkeys() and self.subgmaps[m]:
  884. self.subgListBox.Check(i)
  885. self._checkSubGSellAll()
  886. def SubGroupSelected(self):
  887. """Subgroup was selected, check if changes were apllied"""
  888. self._checkChange()
  889. subgroup = self.subGroupSelect.GetValue().strip()
  890. group = self.currentGroup
  891. gmaps = list()
  892. groups = self.GetExistGroups()
  893. self.subgmaps = {}
  894. if group in groups:
  895. gmaps = self.GetGroupLayers(group)
  896. if subgroup:
  897. maps = self.GetGroupLayers(group, subgroup)
  898. for m in maps:
  899. if m in gmaps:
  900. self.subgmaps[m] = True
  901. else:
  902. self.subgmaps[m] = False
  903. gmaps = self._filter(gmaps)
  904. self.subgListBox.Set(gmaps)
  905. for i, m in enumerate(gmaps):
  906. if m in self.subgmaps:
  907. self.subgListBox.Check(i)
  908. else:
  909. self.subgListBox.Check(i, False)
  910. self._checkSubGSellAll()
  911. self.currentSubgroup = subgroup
  912. self.ClearNotification()
  913. def _filter(self, data):
  914. """Apply filter for strings in data list"""
  915. flt_data = []
  916. if len(self.flt_pattern) == 0:
  917. flt_data = data[:]
  918. return flt_data
  919. for dt in data:
  920. try:
  921. if re.compile(self.flt_pattern).search(dt):
  922. flt_data.append(dt)
  923. except:
  924. pass
  925. return flt_data
  926. def _checkChange(self):
  927. if self.edit_subg:
  928. self._checkSubgroupChange()
  929. else:
  930. self._checkGroupChange()
  931. def _checkGroupChange(self):
  932. if self.currentGroup and self.dataChanged:
  933. dlg = wx.MessageDialog(
  934. self,
  935. message=_(
  936. "Group <%s> was changed, "
  937. "do you want to apply changes?") %
  938. self.currentGroup,
  939. caption=_("Unapplied changes"),
  940. style=wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  941. if dlg.ShowModal() == wx.ID_YES:
  942. self.ApplyChanges()
  943. dlg.Destroy()
  944. self.dataChanged = False
  945. def _checkSubgroupChange(self):
  946. if self.currentSubgroup and self.dataChanged:
  947. dlg = wx.MessageDialog(
  948. self,
  949. message=_(
  950. "Subgroup <%s> was changed, "
  951. "do you want to apply changes?") %
  952. self.currentSubgroup,
  953. caption=_("Unapplied changes"),
  954. style=wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  955. if dlg.ShowModal() == wx.ID_YES:
  956. self.ApplyChanges()
  957. dlg.Destroy()
  958. self.dataChanged = False
  959. def ShowGroupLayers(self, mapList):
  960. """Show map layers in currently selected group"""
  961. self.gLayerBox.Set(mapList)
  962. def EditGroup(self, group, subgroup=None):
  963. """Edit selected group"""
  964. layersNew = self.GetLayers()
  965. layersOld = self.GetGroupLayers(group, subgroup)
  966. add = []
  967. remove = []
  968. for layerNew in layersNew:
  969. if layerNew not in layersOld:
  970. add.append(layerNew)
  971. for layerOld in layersOld:
  972. if layerOld not in layersNew:
  973. remove.append(layerOld)
  974. kwargs = {}
  975. if subgroup:
  976. kwargs["subgroup"] = subgroup
  977. ret = None
  978. if remove:
  979. ret = RunCommand('i.group',
  980. parent=self,
  981. group=group,
  982. flags='r',
  983. input=','.join(remove),
  984. **kwargs)
  985. if add:
  986. ret = RunCommand('i.group',
  987. parent=self,
  988. group=group,
  989. input=','.join(add),
  990. **kwargs)
  991. return ret
  992. def CreateNewGroup(self, group, subgroup):
  993. """Create new group"""
  994. layers = self.GetLayers()
  995. if not layers:
  996. GMessage(parent=self,
  997. message=_("No raster maps selected."))
  998. return 1
  999. kwargs = {}
  1000. if subgroup:
  1001. kwargs["subgroup"] = subgroup
  1002. ret = RunCommand('i.group',
  1003. parent=self,
  1004. group=group,
  1005. input=layers,
  1006. **kwargs)
  1007. # update subgroup select
  1008. self.SubGroupSelected()
  1009. return ret
  1010. def GetExistGroups(self):
  1011. """Returns existing groups in current mapset"""
  1012. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  1013. def GetExistSubgroups(self, group):
  1014. """Returns existing subgroups in a group"""
  1015. return RunCommand('i.group', group=group,
  1016. read=True, flags='sg').splitlines()
  1017. def ShowResult(self, group, returnCode, create):
  1018. """Show if operation was successfull."""
  1019. group += '@' + grass.gisenv()['MAPSET']
  1020. if returnCode is None:
  1021. label = _("No changes to apply in group <%s>.") % group
  1022. elif returnCode == 0:
  1023. if create:
  1024. label = _("Group <%s> was successfully created.") % group
  1025. else:
  1026. label = _("Group <%s> was successfully changed.") % group
  1027. else:
  1028. if create:
  1029. label = _("Creating of new group <%s> failed.") % group
  1030. else:
  1031. label = _("Changing of group <%s> failed.") % group
  1032. self.infoLabel.SetLabel(label)
  1033. wx.FutureCall(4000, self.ClearNotification)
  1034. def GetSelectedGroup(self):
  1035. """Return currently selected group (without mapset)"""
  1036. g = self.groupSelect.GetValue().split('@')[0]
  1037. if self.edit_subg:
  1038. s = self.subGroupSelect.GetValue()
  1039. else:
  1040. s = None
  1041. return g, s
  1042. def GetGroupLayers(self, group, subgroup=None):
  1043. """Get layers in group"""
  1044. kwargs = dict()
  1045. kwargs['group'] = group
  1046. if subgroup:
  1047. kwargs['subgroup'] = subgroup
  1048. res = RunCommand('i.group',
  1049. parent=self,
  1050. flags='g',
  1051. read=True, **kwargs)
  1052. if not res:
  1053. return []
  1054. return res.splitlines()
  1055. def ClearNotification(self):
  1056. """Clear notification string"""
  1057. self.infoLabel.SetLabel("")
  1058. def ApplyChanges(self):
  1059. """Create or edit group"""
  1060. group = self.currentGroup
  1061. if not group:
  1062. GMessage(parent=self,
  1063. message=_("No group selected."))
  1064. return False
  1065. if self.edit_subg and not self.currentSubgroup:
  1066. GMessage(parent=self,
  1067. message=_("No subgroup selected."))
  1068. return 0
  1069. if self.edit_subg:
  1070. subgroup = self.currentSubgroup
  1071. else:
  1072. subgroup = None
  1073. groups = self.GetExistGroups()
  1074. if group in groups:
  1075. ret = self.EditGroup(group, subgroup)
  1076. self.ShowResult(group=group, returnCode=ret, create=False)
  1077. else:
  1078. ret = self.CreateNewGroup(group, subgroup)
  1079. self.ShowResult(group=group, returnCode=ret, create=True)
  1080. self.dataChanged = False
  1081. return True
  1082. def OnApply(self, event):
  1083. """Apply changes"""
  1084. self.ApplyChanges()
  1085. def OnOk(self, event):
  1086. """Apply changes and close dialog"""
  1087. if self.ApplyChanges():
  1088. self.OnClose(event)
  1089. def OnClose(self, event):
  1090. """Close dialog"""
  1091. if not self.IsModal():
  1092. self.Destroy()
  1093. event.Skip()
  1094. class MapLayersDialogBase(wx.Dialog):
  1095. """Base dialog for selecting map layers (raster, vector).
  1096. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  1097. MapLayersDialog. Base class contains core functionality.
  1098. """
  1099. def __init__(self, parent, title,
  1100. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  1101. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  1102. style=style, **kwargs)
  1103. self.parent = parent # GMFrame or ?
  1104. self.applyAddingMapLayers = Signal(
  1105. 'MapLayersDialogBase.applyAddingMapLayers')
  1106. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  1107. # dialog body
  1108. self.bodySizer = self._createDialogBody()
  1109. self.mainSizer.Add(self.bodySizer, proportion=1,
  1110. flag=wx.EXPAND | wx.ALL, border=5)
  1111. # update list of layer to be loaded
  1112. self.map_layers = [] # list of map layers (full list type/mapset)
  1113. self.LoadMapLayers(self.GetLayerType(cmd=True),
  1114. self.mapset.GetStringSelection())
  1115. self._fullyQualifiedNames()
  1116. self._modelerDSeries()
  1117. # buttons
  1118. btnCancel = wx.Button(parent=self, id=wx.ID_CANCEL)
  1119. btnOk = wx.Button(parent=self, id=wx.ID_OK)
  1120. btnOk.SetDefault()
  1121. # sizers & do layout
  1122. self.btnSizer = wx.StdDialogButtonSizer()
  1123. self.btnSizer.AddButton(btnCancel)
  1124. self.btnSizer.AddButton(btnOk)
  1125. self._addApplyButton()
  1126. self.btnSizer.Realize()
  1127. self.mainSizer.Add(self.btnSizer, proportion=0,
  1128. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  1129. self.SetSizer(self.mainSizer)
  1130. self.mainSizer.Fit(self)
  1131. # set dialog min size
  1132. self.SetMinSize(self.GetSize())
  1133. def _modelerDSeries(self):
  1134. """Method used only by MapLayersDialogForModeler,
  1135. for other subclasses does nothing.
  1136. """
  1137. pass
  1138. def _addApplyButton(self):
  1139. """Method used only by MapLayersDialog,
  1140. for other subclasses does nothing.
  1141. """
  1142. pass
  1143. def _fullyQualifiedNames(self):
  1144. """Adds CheckBox which determines is fully qualified names are retuned.
  1145. """
  1146. self.fullyQualified = wx.CheckBox(
  1147. parent=self, id=wx.ID_ANY,
  1148. label=_("Use fully-qualified map names"))
  1149. self.fullyQualified.SetValue(True)
  1150. self.mainSizer.Add(self.fullyQualified, proportion=0,
  1151. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
  1152. def _useFullyQualifiedNames(self):
  1153. return self.fullyQualified.IsChecked()
  1154. def _layerTypes(self):
  1155. """Determines which layer types can be chosen.
  1156. Valid values:
  1157. - raster
  1158. - raster3d
  1159. - vector
  1160. """
  1161. return [_('raster'), _('3D raster'), _('vector')]
  1162. def _selectAll(self):
  1163. """Check all layers by default"""
  1164. return True
  1165. def _createDialogBody(self):
  1166. bodySizer = wx.GridBagSizer(vgap=3, hgap=3)
  1167. # layer type
  1168. bodySizer.Add(wx.StaticText(parent=self, label=_("Map type:")),
  1169. flag=wx.ALIGN_CENTER_VERTICAL,
  1170. pos=(0, 0))
  1171. self.layerType = wx.Choice(parent=self, id=wx.ID_ANY,
  1172. choices=self._layerTypes(), size=(100, -1))
  1173. self.layerType.SetSelection(0)
  1174. bodySizer.Add(self.layerType,
  1175. pos=(0, 1))
  1176. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  1177. # select toggle
  1178. self.toggle = wx.CheckBox(parent=self, id=wx.ID_ANY,
  1179. label=_("Select toggle"))
  1180. self.toggle.SetValue(self._selectAll())
  1181. bodySizer.Add(self.toggle,
  1182. flag=wx.ALIGN_CENTER_VERTICAL,
  1183. pos=(0, 2))
  1184. # mapset filter
  1185. bodySizer.Add(wx.StaticText(parent=self, label=_("Mapset:")),
  1186. flag=wx.ALIGN_CENTER_VERTICAL,
  1187. pos=(1, 0))
  1188. self.mapset = MapsetSelect(parent=self, searchPath=True)
  1189. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  1190. bodySizer.Add(self.mapset,
  1191. pos=(1, 1), span=(1, 2))
  1192. # map name filter
  1193. bodySizer.Add(wx.StaticText(parent=self, label=_("Pattern:")),
  1194. flag=wx.ALIGN_CENTER_VERTICAL,
  1195. pos=(2, 0))
  1196. self.filter = wx.TextCtrl(parent=self, id=wx.ID_ANY,
  1197. value="",
  1198. size=(250, -1))
  1199. bodySizer.Add(self.filter,
  1200. flag=wx.EXPAND,
  1201. pos=(2, 1), span=(1, 2))
  1202. self.filter.SetFocus()
  1203. # TODO same text in GroupDialog
  1204. self.filter.SetToolTipString(
  1205. _(
  1206. "Put here a regular expression."
  1207. " Characters '.*' stand for anything,"
  1208. " character '^' stands for the beginning"
  1209. " and '$' for the end."))
  1210. # layer list
  1211. bodySizer.Add(
  1212. wx.StaticText(
  1213. parent=self,
  1214. label=_("List of maps:")),
  1215. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  1216. pos=(
  1217. 3,
  1218. 0))
  1219. self.layers = wx.CheckListBox(parent=self, id=wx.ID_ANY,
  1220. size=(250, 100),
  1221. choices=[])
  1222. bodySizer.Add(self.layers,
  1223. flag=wx.EXPAND,
  1224. pos=(3, 1), span=(1, 2))
  1225. bodySizer.AddGrowableCol(1)
  1226. bodySizer.AddGrowableRow(3)
  1227. # bindings
  1228. self.mapset.Bind(wx.EVT_TEXT, self.OnChangeParams)
  1229. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  1230. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  1231. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  1232. return bodySizer
  1233. def LoadMapLayers(self, type, mapset):
  1234. """Load list of map layers
  1235. :param str type: layer type ('raster' or 'vector')
  1236. :param str mapset: mapset name
  1237. """
  1238. self.map_layers = grass.list_grouped(type=type)[mapset]
  1239. self.layers.Set(natural_sort(self.map_layers))
  1240. # check all items by default
  1241. for item in range(self.layers.GetCount()):
  1242. self.layers.Check(item, check=self._selectAll())
  1243. def OnChangeParams(self, event):
  1244. """Filter parameters changed by user"""
  1245. # update list of layer to be loaded
  1246. self.LoadMapLayers(self.GetLayerType(cmd=True),
  1247. self.mapset.GetStringSelection())
  1248. event.Skip()
  1249. def OnMenu(self, event):
  1250. """Table description area, context menu"""
  1251. if not hasattr(self, "popupID1"):
  1252. self.popupDataID1 = wx.NewId()
  1253. self.popupDataID2 = wx.NewId()
  1254. self.popupDataID3 = wx.NewId()
  1255. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  1256. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id=self.popupDataID2)
  1257. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id=self.popupDataID3)
  1258. # generate popup-menu
  1259. menu = wx.Menu()
  1260. menu.Append(self.popupDataID1, _("Select all"))
  1261. menu.Append(self.popupDataID2, _("Invert selection"))
  1262. menu.Append(self.popupDataID3, _("Deselect all"))
  1263. self.PopupMenu(menu)
  1264. menu.Destroy()
  1265. def OnSelectAll(self, event):
  1266. """Select all map layer from list"""
  1267. for item in range(self.layers.GetCount()):
  1268. self.layers.Check(item, True)
  1269. def OnSelectInvert(self, event):
  1270. """Invert current selection"""
  1271. for item in range(self.layers.GetCount()):
  1272. if self.layers.IsChecked(item):
  1273. self.layers.Check(item, False)
  1274. else:
  1275. self.layers.Check(item, True)
  1276. def OnDeselectAll(self, event):
  1277. """Select all map layer from list"""
  1278. for item in range(self.layers.GetCount()):
  1279. self.layers.Check(item, False)
  1280. def OnFilter(self, event):
  1281. """Apply filter for map names"""
  1282. if len(event.GetString()) == 0:
  1283. self.layers.Set(self.map_layers)
  1284. return
  1285. list = []
  1286. for layer in self.map_layers:
  1287. try:
  1288. if re.compile(event.GetString()).search(layer):
  1289. list.append(layer)
  1290. except:
  1291. pass
  1292. list = natural_sort(list)
  1293. self.layers.Set(list)
  1294. self.OnSelectAll(None)
  1295. event.Skip()
  1296. def OnToggle(self, event):
  1297. """Select toggle (check or uncheck all layers)"""
  1298. check = event.IsChecked()
  1299. for item in range(self.layers.GetCount()):
  1300. self.layers.Check(item, check)
  1301. event.Skip()
  1302. def GetMapLayers(self):
  1303. """Return list of checked map layers"""
  1304. layerNames = []
  1305. for indx in self.layers.GetSelections():
  1306. # layers.append(self.layers.GetStringSelec(indx))
  1307. pass
  1308. mapset = self.mapset.GetStringSelection()
  1309. for item in range(self.layers.GetCount()):
  1310. if not self.layers.IsChecked(item):
  1311. continue
  1312. if self._useFullyQualifiedNames():
  1313. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  1314. else:
  1315. layerNames.append(self.layers.GetString(item))
  1316. return layerNames
  1317. def GetLayerType(self, cmd=False):
  1318. """Get selected layer type
  1319. :param bool cmd: True for g.list
  1320. """
  1321. if not cmd:
  1322. return self.layerType.GetStringSelection()
  1323. sel = self.layerType.GetSelection()
  1324. if sel == 0:
  1325. ltype = 'raster'
  1326. elif sel == 1:
  1327. ltype = 'raster_3d'
  1328. else:
  1329. ltype = 'vector'
  1330. return ltype
  1331. class MapLayersDialog(MapLayersDialogBase):
  1332. """Subclass of MapLayersDialogBase used in Layer Manager.
  1333. Contains apply button, which sends wxApplyMapLayers event.
  1334. """
  1335. def __init__(self, parent, title, **kwargs):
  1336. MapLayersDialogBase.__init__(
  1337. self, parent=parent, title=title, **kwargs)
  1338. def _addApplyButton(self):
  1339. btnApply = wx.Button(parent=self, id=wx.ID_APPLY)
  1340. self.btnSizer.AddButton(btnApply)
  1341. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1342. def OnApply(self, event):
  1343. self.applyAddingMapLayers.emit(mapLayers=self.GetMapLayers(),
  1344. ltype=self.GetLayerType(cmd=True))
  1345. class MapLayersDialogForGroups(MapLayersDialogBase):
  1346. """Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  1347. Shows only raster maps.
  1348. """
  1349. def __init__(self, parent, title, **kwargs):
  1350. MapLayersDialogBase.__init__(
  1351. self, parent=parent, title=title, **kwargs)
  1352. def _layerTypes(self):
  1353. return [_('raster'), ]
  1354. def _selectAll(self):
  1355. """Could be overriden"""
  1356. return False
  1357. def _fullyQualifiedNames(self):
  1358. pass
  1359. def _useFullyQualifiedNames(self):
  1360. return True
  1361. class MapLayersDialogForModeler(MapLayersDialogBase):
  1362. """Subclass of MapLayersDialogBase used in Modeler.
  1363. """
  1364. def __init__(self, parent, title, **kwargs):
  1365. MapLayersDialogBase.__init__(
  1366. self, parent=parent, title=title, **kwargs)
  1367. def _modelerDSeries(self):
  1368. self.dseries = wx.CheckBox(parent=self, id=wx.ID_ANY,
  1369. label=_("Dynamic series (%s)") % 'g.list')
  1370. self.dseries.SetValue(False)
  1371. self.mainSizer.Add(self.dseries, proportion=0,
  1372. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
  1373. def GetDSeries(self):
  1374. """Used by modeler only
  1375. :return: g.list command
  1376. """
  1377. if not self.dseries or not self.dseries.IsChecked():
  1378. return ''
  1379. cond = 'map in `g.list type=%s ' % self.GetLayerType(cmd=True)
  1380. patt = self.filter.GetValue()
  1381. if patt:
  1382. cond += 'pattern=%s ' % patt
  1383. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1384. return cond
  1385. class SetOpacityDialog(wx.Dialog):
  1386. """Set opacity of map layers.
  1387. Dialog expects opacity between 0 and 1 and returns this range, too.
  1388. """
  1389. def __init__(self, parent, id=wx.ID_ANY, title=_("Set Map Layer Opacity"),
  1390. size=wx.DefaultSize, pos=wx.DefaultPosition,
  1391. style=wx.DEFAULT_DIALOG_STYLE, opacity=1):
  1392. self.parent = parent # GMFrame
  1393. self.opacity = opacity # current opacity
  1394. super(
  1395. SetOpacityDialog,
  1396. self).__init__(
  1397. parent,
  1398. id=id,
  1399. pos=pos,
  1400. size=size,
  1401. style=style,
  1402. title=title)
  1403. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1404. panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1405. sizer = wx.BoxSizer(wx.VERTICAL)
  1406. box = wx.GridBagSizer(vgap=5, hgap=5)
  1407. self.value = wx.Slider(
  1408. panel, id=wx.ID_ANY, value=int(self.opacity * 100),
  1409. style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_TOP | wx.SL_LABELS,
  1410. minValue=0, maxValue=100, size=(350, -1))
  1411. box.Add(self.value,
  1412. flag=wx.ALIGN_CENTRE, pos=(0, 0), span=(1, 2))
  1413. box.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
  1414. label=_("transparent")),
  1415. pos=(1, 0))
  1416. box.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
  1417. label=_("opaque")),
  1418. flag=wx.ALIGN_RIGHT,
  1419. pos=(1, 1))
  1420. sizer.Add(box, proportion=0,
  1421. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  1422. line = wx.StaticLine(parent=panel, id=wx.ID_ANY,
  1423. style=wx.LI_HORIZONTAL)
  1424. sizer.Add(line, proportion=0,
  1425. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  1426. # buttons
  1427. btnsizer = wx.StdDialogButtonSizer()
  1428. btnOK = wx.Button(parent=panel, id=wx.ID_OK)
  1429. btnOK.SetDefault()
  1430. btnsizer.AddButton(btnOK)
  1431. btnCancel = wx.Button(parent=panel, id=wx.ID_CANCEL)
  1432. btnsizer.AddButton(btnCancel)
  1433. btnApply = wx.Button(parent=panel, id=wx.ID_APPLY)
  1434. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1435. btnsizer.AddButton(btnApply)
  1436. btnsizer.Realize()
  1437. sizer.Add(btnsizer, proportion=0,
  1438. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  1439. panel.SetSizer(sizer)
  1440. sizer.Fit(panel)
  1441. self.SetSize(self.GetBestSize())
  1442. self.Layout()
  1443. def GetOpacity(self):
  1444. """Button 'OK' pressed"""
  1445. # return opacity value
  1446. opacity = float(self.value.GetValue()) / 100
  1447. return opacity
  1448. def OnApply(self, event):
  1449. self.applyOpacity.emit(value=self.GetOpacity())
  1450. def GetImageHandlers(image):
  1451. """Get list of supported image handlers"""
  1452. lext = list()
  1453. ltype = list()
  1454. for h in image.GetHandlers():
  1455. lext.append(h.GetExtension())
  1456. filetype = ''
  1457. if 'png' in lext:
  1458. filetype += "PNG file (*.png)|*.png|"
  1459. ltype.append({'type': wx.BITMAP_TYPE_PNG,
  1460. 'ext': 'png'})
  1461. filetype += "BMP file (*.bmp)|*.bmp|"
  1462. ltype.append({'type': wx.BITMAP_TYPE_BMP,
  1463. 'ext': 'bmp'})
  1464. if 'gif' in lext:
  1465. filetype += "GIF file (*.gif)|*.gif|"
  1466. ltype.append({'type': wx.BITMAP_TYPE_GIF,
  1467. 'ext': 'gif'})
  1468. if 'jpg' in lext:
  1469. filetype += "JPG file (*.jpg)|*.jpg|"
  1470. ltype.append({'type': wx.BITMAP_TYPE_JPEG,
  1471. 'ext': 'jpg'})
  1472. if 'pcx' in lext:
  1473. filetype += "PCX file (*.pcx)|*.pcx|"
  1474. ltype.append({'type': wx.BITMAP_TYPE_PCX,
  1475. 'ext': 'pcx'})
  1476. if 'pnm' in lext:
  1477. filetype += "PNM file (*.pnm)|*.pnm|"
  1478. ltype.append({'type': wx.BITMAP_TYPE_PNM,
  1479. 'ext': 'pnm'})
  1480. if 'tif' in lext:
  1481. filetype += "TIF file (*.tif)|*.tif|"
  1482. ltype.append({'type': wx.BITMAP_TYPE_TIF,
  1483. 'ext': 'tif'})
  1484. if 'xpm' in lext:
  1485. filetype += "XPM file (*.xpm)|*.xpm"
  1486. ltype.append({'type': wx.BITMAP_TYPE_XPM,
  1487. 'ext': 'xpm'})
  1488. return filetype, ltype
  1489. class ImageSizeDialog(wx.Dialog):
  1490. """Set size for saved graphic file"""
  1491. def __init__(self, parent, id=wx.ID_ANY, title=_("Set image size"),
  1492. style=wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1493. self.parent = parent
  1494. wx.Dialog.__init__(
  1495. self,
  1496. parent,
  1497. id=id,
  1498. style=style,
  1499. title=title,
  1500. **kwargs)
  1501. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1502. self.box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  1503. label=' % s' % _("Image size"))
  1504. size = self.parent.GetWindow().GetClientSize()
  1505. self.width = SpinCtrl(parent=self.panel, id=wx.ID_ANY,
  1506. style=wx.SP_ARROW_KEYS)
  1507. self.width.SetRange(20, 1e6)
  1508. self.width.SetValue(size.width)
  1509. wx.CallAfter(self.width.SetFocus)
  1510. self.height = SpinCtrl(parent=self.panel, id=wx.ID_ANY,
  1511. style=wx.SP_ARROW_KEYS)
  1512. self.height.SetRange(20, 1e6)
  1513. self.height.SetValue(size.height)
  1514. self.template = wx.Choice(parent=self.panel, id=wx.ID_ANY,
  1515. size=(125, -1),
  1516. choices=["",
  1517. "640x480",
  1518. "800x600",
  1519. "1024x768",
  1520. "1280x960",
  1521. "1600x1200",
  1522. "1920x1440"])
  1523. self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
  1524. self.btnOK.SetDefault()
  1525. self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  1526. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1527. self._layout()
  1528. self.SetSize(self.GetBestSize())
  1529. def _layout(self):
  1530. """Do layout"""
  1531. sizer = wx.BoxSizer(wx.VERTICAL)
  1532. # body
  1533. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1534. fbox = wx.FlexGridSizer(cols=2, vgap=5, hgap=5)
  1535. fbox.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  1536. label=_("Width:")),
  1537. flag=wx.ALIGN_CENTER_VERTICAL)
  1538. fbox.Add(self.width)
  1539. fbox.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  1540. label=_("Height:")),
  1541. flag=wx.ALIGN_CENTER_VERTICAL)
  1542. fbox.Add(self.height)
  1543. fbox.Add(wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  1544. label=_("Template:")),
  1545. flag=wx.ALIGN_CENTER_VERTICAL)
  1546. fbox.Add(self.template)
  1547. box.Add(fbox, proportion=1,
  1548. flag=wx.EXPAND | wx.ALL, border=5)
  1549. sizer.Add(box, proportion=1,
  1550. flag=wx.EXPAND | wx.ALL, border=3)
  1551. # buttons
  1552. btnsizer = wx.StdDialogButtonSizer()
  1553. btnsizer.AddButton(self.btnOK)
  1554. btnsizer.AddButton(self.btnCancel)
  1555. btnsizer.Realize()
  1556. sizer.Add(btnsizer, proportion=0,
  1557. flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1558. self.panel.SetSizer(sizer)
  1559. sizer.Fit(self.panel)
  1560. self.Layout()
  1561. def GetValues(self):
  1562. """Get width/height values"""
  1563. return self.width.GetValue(), self.height.GetValue()
  1564. def OnTemplate(self, event):
  1565. """Template selected"""
  1566. sel = event.GetString()
  1567. if not sel:
  1568. width, height = self.parent.GetWindow().GetClientSize()
  1569. else:
  1570. width, height = map(int, sel.split('x'))
  1571. self.width.SetValue(width)
  1572. self.height.SetValue(height)
  1573. class SqlQueryFrame(wx.Frame):
  1574. def __init__(self, parent, id=wx.ID_ANY,
  1575. title=_("GRASS GIS SQL Query Utility"),
  1576. *kwargs):
  1577. """SQL Query Utility window
  1578. """
  1579. self.parent = parent
  1580. wx.Frame.__init__(self, parent=parent, id=id, title=title, *kwargs)
  1581. self.SetIcon(
  1582. wx.Icon(
  1583. os.path.join(
  1584. globalvar.ICONDIR,
  1585. 'grass_sql.ico'),
  1586. wx.BITMAP_TYPE_ICO))
  1587. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1588. self.sqlBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  1589. label=_(" SQL statement "))
  1590. self.sql = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
  1591. style=wx.TE_MULTILINE)
  1592. self.btnApply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
  1593. self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  1594. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1595. self._layout()
  1596. self.SetMinSize(wx.Size(300, 150))
  1597. self.SetSize(wx.Size(500, 200))
  1598. def _layout(self):
  1599. """Do layout"""
  1600. sizer = wx.BoxSizer(wx.VERTICAL)
  1601. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1602. sqlSizer.Add(self.sql, proportion=1,
  1603. flag=wx.EXPAND)
  1604. btnSizer = wx.StdDialogButtonSizer()
  1605. btnSizer.AddButton(self.btnApply)
  1606. btnSizer.AddButton(self.btnCancel)
  1607. btnSizer.Realize()
  1608. sizer.Add(sqlSizer, proportion=1,
  1609. flag=wx.EXPAND | wx.ALL, border=5)
  1610. sizer.Add(btnSizer, proportion=0,
  1611. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  1612. self.panel.SetSizer(sizer)
  1613. self.Layout()
  1614. def OnCloseWindow(self, event):
  1615. """Close window
  1616. """
  1617. self.Close()
  1618. class SymbolDialog(wx.Dialog):
  1619. """Dialog for GRASS symbols selection.
  1620. Dialog is called in gui_core::forms module.
  1621. """
  1622. def __init__(self, parent, symbolPath,
  1623. currentSymbol=None, title=_("Symbols")):
  1624. """Dialog constructor.
  1625. It is assumed that symbolPath contains folders with symbols.
  1626. :param parent: dialog parent
  1627. :param symbolPath: absolute path to symbols
  1628. :param currentSymbol: currently selected symbol (e.g. 'basic/x')
  1629. :param title: dialog title
  1630. """
  1631. wx.Dialog.__init__(self, parent=parent, title=title, id=wx.ID_ANY)
  1632. self.symbolPath = symbolPath
  1633. self.currentSymbol = currentSymbol # default basic/x
  1634. self.selected = None
  1635. self.selectedDir = None
  1636. self._layout()
  1637. def _layout(self):
  1638. mainPanel = wx.Panel(self, id=wx.ID_ANY)
  1639. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1640. vSizer = wx.BoxSizer(wx.VERTICAL)
  1641. fgSizer = wx.FlexGridSizer(rows=2, vgap=5, hgap=5)
  1642. self.folderChoice = wx.Choice(
  1643. mainPanel,
  1644. id=wx.ID_ANY,
  1645. choices=os.listdir(
  1646. self.symbolPath))
  1647. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  1648. fgSizer.Add(
  1649. wx.StaticText(
  1650. mainPanel,
  1651. id=wx.ID_ANY,
  1652. label=_("Symbol directory:")),
  1653. proportion=0,
  1654. flag=wx.ALIGN_CENTER_VERTICAL)
  1655. fgSizer.Add(self.folderChoice, proportion=0,
  1656. flag=wx.ALIGN_CENTER, border=0)
  1657. self.infoLabel = wx.StaticText(mainPanel, id=wx.ID_ANY)
  1658. fgSizer.Add(
  1659. wx.StaticText(
  1660. mainPanel,
  1661. id=wx.ID_ANY,
  1662. label=_("Symbol name:")),
  1663. flag=wx.ALIGN_CENTRE_VERTICAL)
  1664. fgSizer.Add(self.infoLabel, proportion=0,
  1665. flag=wx.ALIGN_CENTRE_VERTICAL)
  1666. vSizer.Add(fgSizer, proportion=0, flag=wx.ALL, border=5)
  1667. self.panels = self._createSymbolPanels(mainPanel)
  1668. for panel in self.panels:
  1669. vSizer.Add(panel, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
  1670. mainSizer.Add(vSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
  1671. self.btnCancel = wx.Button(parent=mainPanel, id=wx.ID_CANCEL)
  1672. self.btnOK = wx.Button(parent=mainPanel, id=wx.ID_OK)
  1673. self.btnOK.SetDefault()
  1674. self.btnOK.Enable(False)
  1675. # buttons
  1676. btnSizer = wx.StdDialogButtonSizer()
  1677. btnSizer.AddButton(self.btnCancel)
  1678. btnSizer.AddButton(self.btnOK)
  1679. btnSizer.Realize()
  1680. mainSizer.Add(btnSizer, proportion=0,
  1681. flag=wx.EXPAND | wx.ALL, border=5)
  1682. # show panel with the largest number of images and fit size
  1683. count = []
  1684. for folder in os.listdir(self.symbolPath):
  1685. count.append(
  1686. len(os.listdir(os.path.join(self.symbolPath, folder))))
  1687. index = count.index(max(count))
  1688. self.folderChoice.SetSelection(index)
  1689. self.OnFolderSelect(None)
  1690. self.infoLabel.Show()
  1691. mainPanel.SetSizerAndFit(mainSizer)
  1692. self.SetSize(self.GetBestSize())
  1693. # show currently selected symbol
  1694. if self.currentSymbol:
  1695. # set directory
  1696. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  1697. self.folderChoice.SetStringSelection(self.selectedDir)
  1698. # select symbol
  1699. panelIdx = self.folderChoice.GetSelection()
  1700. for panel in self.symbolPanels[panelIdx]:
  1701. if panel.GetName() == self.selected:
  1702. panel.Select()
  1703. else:
  1704. self.folderChoice.SetSelection(0)
  1705. self.OnFolderSelect(None)
  1706. def _createSymbolPanels(self, parent):
  1707. """Creates multiple panels with symbols.
  1708. Panels are shown/hidden according to selected folder."""
  1709. folders = os.listdir(self.symbolPath)
  1710. panels = []
  1711. self.symbolPanels = []
  1712. for folder in folders:
  1713. panel = wx.Panel(parent, style=wx.BORDER_RAISED)
  1714. sizer = wx.GridSizer(cols=6, vgap=3, hgap=3)
  1715. images = self._getSymbols(
  1716. path=os.path.join(
  1717. self.symbolPath, folder))
  1718. symbolPanels = []
  1719. for img in images:
  1720. iP = SingleSymbolPanel(parent=panel, symbolPath=img)
  1721. iP.symbolSelectionChanged.connect(self.SelectionChanged)
  1722. sizer.Add(iP, proportion=0, flag=wx.ALIGN_CENTER)
  1723. symbolPanels.append(iP)
  1724. panel.SetSizerAndFit(sizer)
  1725. panel.Hide()
  1726. panels.append(panel)
  1727. self.symbolPanels.append(symbolPanels)
  1728. return panels
  1729. def _getSymbols(self, path):
  1730. # we assume that images are in subfolders (1 level only)
  1731. imageList = []
  1732. for image in os.listdir(path):
  1733. imageList.append(os.path.join(path, image))
  1734. return sorted(imageList)
  1735. def OnFolderSelect(self, event):
  1736. """Selected folder with symbols changed."""
  1737. idx = self.folderChoice.GetSelection()
  1738. for i in range(len(self.panels)):
  1739. sizer = self.panels[i].GetContainingSizer()
  1740. sizer.Show(self.panels[i], i == idx, recursive=True)
  1741. sizer.Layout()
  1742. if self.selectedDir == self.folderChoice.GetStringSelection():
  1743. self.btnOK.Enable()
  1744. self.infoLabel.SetLabel(self.selected)
  1745. else:
  1746. self.btnOK.Disable()
  1747. self.infoLabel.SetLabel('')
  1748. def SelectionChanged(self, name, doubleClick):
  1749. """Selected symbol changed."""
  1750. if doubleClick:
  1751. self.EndModal(wx.ID_OK)
  1752. # deselect all
  1753. for i in range(len(self.panels)):
  1754. for panel in self.symbolPanels[i]:
  1755. if panel.GetName() != name:
  1756. panel.Deselect()
  1757. self.btnOK.Enable()
  1758. self.selected = name
  1759. self.selectedDir = self.folderChoice.GetStringSelection()
  1760. self.infoLabel.SetLabel(name)
  1761. def GetSelectedSymbolName(self):
  1762. """Returns currently selected symbol name (e.g. 'basic/x').
  1763. """
  1764. # separator must be '/' and not dependent on OS
  1765. return self.selectedDir + '/' + self.selected
  1766. def GetSelectedSymbolPath(self):
  1767. """Returns currently selected symbol full path.
  1768. """
  1769. return os.path.join(self.symbolPath, self.selectedDir, self.selected)
  1770. class TextEntryDialog(wx.Dialog):
  1771. """Simple dialog with text field.
  1772. It differs from wx.TextEntryDialog because it allows adding validator.
  1773. """
  1774. def __init__(
  1775. self, parent, message, caption='', defaultValue='',
  1776. validator=wx.DefaultValidator, style=wx.OK | wx.CANCEL | wx.CENTRE,
  1777. textStyle=0, textSize=(300, -1),
  1778. **kwargs):
  1779. wx.Dialog.__init__(
  1780. self,
  1781. parent=parent,
  1782. id=wx.ID_ANY,
  1783. title=caption,
  1784. **kwargs)
  1785. vbox = wx.BoxSizer(wx.VERTICAL)
  1786. stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
  1787. vbox.Add(stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  1788. self._textCtrl = wx.TextCtrl(
  1789. self,
  1790. id=wx.ID_ANY,
  1791. value=defaultValue,
  1792. validator=validator,
  1793. style=textStyle)
  1794. self._textCtrl.SetInitialSize(textSize)
  1795. wx.CallAfter(self._textCtrl.SetFocus)
  1796. vbox.Add(
  1797. self._textCtrl,
  1798. proportion=0,
  1799. flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
  1800. border=10)
  1801. self._textCtrl.SetFocus()
  1802. sizer = self.CreateSeparatedButtonSizer(style)
  1803. vbox.Add(sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  1804. self.SetSizerAndFit(vbox)
  1805. def GetValue(self):
  1806. return self._textCtrl.GetValue()
  1807. def SetValue(self, value):
  1808. self._textCtrl.SetValue(value)
  1809. class HyperlinkDialog(wx.Dialog):
  1810. """Dialog for displaying message with hyperlink."""
  1811. def __init__(self, parent, title, message, hyperlink,
  1812. hyperlinkLabel=None, style=wx.OK):
  1813. """Constructor
  1814. :param parent: gui parent
  1815. :param title: dialog title
  1816. :param message: message
  1817. :param hyperlink: url
  1818. :param hyperlinkLabel: label shown instead of url
  1819. :param style: button style
  1820. """
  1821. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  1822. style=wx.DEFAULT_DIALOG_STYLE)
  1823. sizer = wx.BoxSizer(wx.VERTICAL)
  1824. label = wx.StaticText(self, label=message)
  1825. sizer.Add(
  1826. label,
  1827. proportion=0,
  1828. flag=wx.ALIGN_CENTRE | wx.ALL,
  1829. border=10)
  1830. hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
  1831. hyperlinkCtrl = wx.HyperlinkCtrl(
  1832. self, id=wx.ID_ANY, label=hyperlinkLabel, url=hyperlink,
  1833. style=wx.HL_ALIGN_LEFT | wx.HL_CONTEXTMENU)
  1834. sizer.Add(
  1835. hyperlinkCtrl,
  1836. proportion=0,
  1837. flag=wx.EXPAND | wx.ALL,
  1838. border=10)
  1839. btnsizer = self.CreateSeparatedButtonSizer(style)
  1840. sizer.Add(
  1841. btnsizer,
  1842. proportion=1,
  1843. flag=wx.EXPAND | wx.ALL,
  1844. border=10)
  1845. self.SetSizer(sizer)
  1846. sizer.Fit(self)
  1847. class QuitDialog(wx.Dialog):
  1848. def __init__(self, parent, title=_("Quit GRASS GIS"), id=wx.ID_ANY,
  1849. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  1850. """Dialog to quit GRASS
  1851. :param parent: window
  1852. """
  1853. wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
  1854. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1855. self._icon = wx.StaticBitmap(
  1856. self.panel, wx.ID_ANY,
  1857. wx.ArtProvider().GetBitmap(
  1858. wx.ART_QUESTION,
  1859. client=wx.ART_MESSAGE_BOX))
  1860. self.informLabel = wx.StaticText(
  1861. parent=self.panel, id=wx.ID_ANY, label=_(
  1862. "Do you want to quit GRASS including shell "
  1863. "prompt or just close the GUI?"))
  1864. self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  1865. self.btnClose = wx.Button(parent=self.panel, id=wx.ID_NO,
  1866. label=_("Close GUI"))
  1867. self.btnClose.SetFocus()
  1868. self.btnQuit = wx.Button(parent=self.panel, id=wx.ID_YES,
  1869. label=_("Quit GRASS GIS"))
  1870. self.btnQuit.SetForegroundColour(wx.Colour(35, 142, 35))
  1871. self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  1872. self.btnQuit.Bind(wx.EVT_BUTTON, self.OnQuit)
  1873. self.__layout()
  1874. def __layout(self):
  1875. """Do layout"""
  1876. sizer = wx.BoxSizer(wx.VERTICAL)
  1877. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1878. btnSizer.Add(self.btnCancel, flag=wx.RIGHT, border=5)
  1879. btnSizer.Add(self.btnClose, flag=wx.RIGHT, border=5)
  1880. btnSizer.Add(self.btnQuit, flag=wx.RIGHT, border=5)
  1881. bodySizer = wx.BoxSizer(wx.HORIZONTAL)
  1882. bodySizer.Add(self._icon, flag=wx.RIGHT, border=10)
  1883. bodySizer.Add(self.informLabel, proportion=1, flag=wx.EXPAND)
  1884. sizer.Add(bodySizer, proportion=1,
  1885. flag=wx.EXPAND | wx.ALL, border=15)
  1886. sizer.Add(btnSizer, proportion=0,
  1887. flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
  1888. self.panel.SetSizer(sizer)
  1889. sizer.Fit(self)
  1890. self.Layout()
  1891. def OnClose(self, event):
  1892. self.EndModal(wx.ID_NO)
  1893. def OnQuit(self, event):
  1894. self.EndModal(wx.ID_YES)
  1895. class DefaultFontDialog(wx.Dialog):
  1896. """
  1897. Opens a file selection dialog to select default font
  1898. to use in all GRASS displays
  1899. """
  1900. def __init__(self, parent, title, id=wx.ID_ANY,
  1901. style=wx.DEFAULT_DIALOG_STYLE |
  1902. wx.RESIZE_BORDER,
  1903. settings=UserSettings,
  1904. type='font'):
  1905. self.settings = settings
  1906. self.type = type
  1907. wx.Dialog.__init__(self, parent, id, title, style=style)
  1908. panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1909. self.tmp_file = grass.tempfile(False) + '.png'
  1910. self.fontdict, fontdict_reverse, self.fontlist = self.GetFonts()
  1911. border = wx.BoxSizer(wx.VERTICAL)
  1912. box = wx.StaticBox(
  1913. parent=panel,
  1914. id=wx.ID_ANY,
  1915. label=" %s " %
  1916. _("Font settings"))
  1917. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1918. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1919. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1920. label=_("Select font:"))
  1921. gridSizer.Add(label,
  1922. flag=wx.ALIGN_TOP,
  1923. pos=(0, 0))
  1924. self.fontlb = wx.ListBox(
  1925. parent=panel,
  1926. id=wx.ID_ANY,
  1927. pos=wx.DefaultPosition,
  1928. choices=self.fontlist,
  1929. style=wx.LB_SINGLE)
  1930. self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.fontlb)
  1931. self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.fontlb)
  1932. gridSizer.Add(self.fontlb,
  1933. flag=wx.EXPAND, pos=(1, 0))
  1934. self.renderfont = wx.StaticBitmap(panel, -1, wx.EmptyBitmapRGBA(100, 50, 255, 255, 255))
  1935. gridSizer.Add(self.renderfont,
  1936. flag=wx.EXPAND, pos=(2, 0))
  1937. if self.type == 'font':
  1938. if "GRASS_FONT" in os.environ:
  1939. self.font = os.environ["GRASS_FONT"]
  1940. else:
  1941. self.font = self.settings.Get(group='display',
  1942. key='font', subkey='type')
  1943. self.encoding = self.settings.Get(group='display',
  1944. key='font', subkey='encoding')
  1945. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1946. label=_("Character encoding:"))
  1947. gridSizer.Add(label,
  1948. flag=wx.ALIGN_CENTER_VERTICAL,
  1949. pos=(3, 0))
  1950. self.textentry = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
  1951. value=self.encoding)
  1952. gridSizer.Add(self.textentry,
  1953. flag=wx.EXPAND, pos=(4, 0))
  1954. self.textentry.Bind(wx.EVT_TEXT, self.OnEncoding)
  1955. elif self.type == 'outputfont':
  1956. self.font = self.settings.Get(group='appearance',
  1957. key='outputfont', subkey='type')
  1958. self.fontsize = self.settings.Get(group='appearance',
  1959. key='outputfont', subkey='size')
  1960. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1961. label=_("Font size:"))
  1962. gridSizer.Add(label,
  1963. flag=wx.ALIGN_CENTER_VERTICAL,
  1964. pos=(2, 0))
  1965. self.spin = SpinCtrl(parent=panel, id=wx.ID_ANY)
  1966. if self.fontsize:
  1967. self.spin.SetValue(int(self.fontsize))
  1968. self.spin.Bind(wx.EVT_SPINCTRL, self.OnSizeSpin)
  1969. self.spin.Bind(wx.EVT_TEXT, self.OnSizeSpin)
  1970. gridSizer.Add(self.spin,
  1971. flag=wx.ALIGN_CENTER_VERTICAL,
  1972. pos=(3, 0))
  1973. else:
  1974. return
  1975. if self.font:
  1976. self.fontlb.SetStringSelection(fontdict_reverse[self.font], True)
  1977. gridSizer.AddGrowableCol(0)
  1978. sizer.Add(gridSizer, proportion=1,
  1979. flag=wx.EXPAND | wx.ALL,
  1980. border=5)
  1981. border.Add(sizer, proportion=1,
  1982. flag=wx.ALL | wx.EXPAND, border=3)
  1983. btnsizer = wx.StdDialogButtonSizer()
  1984. btn = wx.Button(parent=panel, id=wx.ID_OK)
  1985. btn.SetDefault()
  1986. btnsizer.AddButton(btn)
  1987. btn = wx.Button(parent=panel, id=wx.ID_CANCEL)
  1988. btnsizer.AddButton(btn)
  1989. btnsizer.Realize()
  1990. border.Add(btnsizer, proportion=0,
  1991. flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1992. panel.SetAutoLayout(True)
  1993. panel.SetSizer(border)
  1994. border.Fit(self)
  1995. row, col = gridSizer.GetItemPosition(self.renderfont)
  1996. self.renderfont.SetSize(gridSizer.GetCellSize(row, col))
  1997. if self.font:
  1998. self.RenderText(self.font, _("Example"), size=self.renderfont.GetSize())
  1999. self.Layout()
  2000. def OnEncoding(self, event):
  2001. self.encoding = event.GetString()
  2002. def EvtListBox(self, event):
  2003. self.font = self.fontdict[event.GetString()]
  2004. self.RenderText(self.font, "Example", size=self.renderfont.GetSize())
  2005. event.Skip()
  2006. def EvtListBoxDClick(self, event):
  2007. self.font = self.fontdict[event.GetString()]
  2008. event.Skip()
  2009. def OnSizeSpin(self, event):
  2010. self.fontsize = self.spin.GetValue()
  2011. event.Skip()
  2012. def GetFonts(self):
  2013. """
  2014. parses fonts directory or fretypecap file to get a list of fonts
  2015. for the listbox
  2016. """
  2017. fontlist = []
  2018. fontdict = {}
  2019. fontdict_reverse = {}
  2020. env = os.environ.copy()
  2021. driver = UserSettings.Get(group='display', key='driver', subkey='type')
  2022. if driver == 'png':
  2023. env['GRASS_RENDER_IMMEDIATE'] = 'png'
  2024. else:
  2025. env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  2026. ret = RunCommand('d.fontlist', flags='v',
  2027. read=True,
  2028. env=env)
  2029. if not ret:
  2030. return fontlist
  2031. dfonts = ret.splitlines()
  2032. for line in dfonts:
  2033. shortname = line.split('|')[0]
  2034. longname = line.split('|')[1]
  2035. # not sure when this happens?
  2036. if shortname.startswith('#'):
  2037. continue
  2038. fontlist.append(longname)
  2039. fontdict[longname] = shortname
  2040. fontdict_reverse[shortname] = longname
  2041. fontlist = natural_sort(list(set(fontlist)))
  2042. return fontdict, fontdict_reverse, fontlist
  2043. def RenderText(self, font, text, size):
  2044. """Renders an example text with the selected font and resets the bitmap widget"""
  2045. env = os.environ.copy()
  2046. driver = UserSettings.Get(group='display', key='driver', subkey='type')
  2047. if driver == 'png':
  2048. env['GRASS_RENDER_IMMEDIATE'] = 'png'
  2049. else:
  2050. env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  2051. env['GRASS_RENDER_WIDTH'] = str(size[0])
  2052. env['GRASS_RENDER_HEIGHT'] = str(size[1])
  2053. env['GRASS_RENDER_FILE'] = self.tmp_file
  2054. ret = RunCommand('d.text', text=text, font=font, align='cc', at='50,50',
  2055. size=80, color='black', env=env)
  2056. if ret == 0:
  2057. self.renderfont.SetBitmap(wx.Bitmap(self.tmp_file))
  2058. else:
  2059. self.renderfont.SetBitmap(wx.EmptyBitmapRGBA(size[0], size[1]))
  2060. try_remove(self.tmp_file)