dialogs.py 84 KB

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