dialogs.py 83 KB

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