dialogs.py 83 KB

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