dialogs.py 83 KB

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