dialogs.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589
  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 GSpinCtrl as SpinCtrl
  41. class SimpleDialog(wx.Dialog):
  42. def __init__(self, parent, title, id=wx.ID_ANY,
  43. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  44. **kwargs):
  45. """General dialog to choose given element (location, mapset, vector map, etc.)
  46. :param parent: window
  47. :param title: window title
  48. """
  49. wx.Dialog.__init__(self, parent, id, title, style=style, **kwargs)
  50. self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
  51. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  52. self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  53. self.btnOK = wx.Button(parent=self.panel, id=wx.ID_OK)
  54. self.btnOK.SetDefault()
  55. self.__layout()
  56. self.warning = _("Required item is not set.")
  57. def __layout(self):
  58. """Do layout"""
  59. self.sizer = wx.BoxSizer(wx.VERTICAL)
  60. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  61. # self.informLabel = wx.StaticText(self.panel, id = wx.ID_ANY)
  62. # buttons
  63. btnSizer = wx.StdDialogButtonSizer()
  64. btnSizer.AddButton(self.btnCancel)
  65. btnSizer.AddButton(self.btnOK)
  66. btnSizer.Realize()
  67. self.sizer.Add(item=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(item=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. item=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(item=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(item=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(item=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. item=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(item=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(item=self.ftype, proportion=0,
  274. flag=wx.EXPAND | wx.ALL, border=1)
  275. self.dataSizer.Add(item=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. item=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(item=self.keycol, proportion=0,
  287. flag=wx.ALIGN_RIGHT)
  288. self.dataSizer.Add(item=keySizer, proportion=1,
  289. flag=wx.EXPAND | wx.ALL, border=1)
  290. self.dataSizer.AddSpacer(5)
  291. self.dataSizer.Add(item=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. item=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. item=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(item=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(item=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. item=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(item=self.bodySizer, proportion=1,
  556. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  557. mainSizer.Add(item=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(item=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(item=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(item=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(item=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. item=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. item=self.subGroupSelect,
  604. flag=wx.EXPAND | wx.TOP,
  605. border=5)
  606. self.subg_panel.SetSizer(subg_sizer)
  607. bodySizer.Add(item=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(item=self.g_sel_all,
  616. flag=wx.ALIGN_CENTER_VERTICAL,
  617. pos=(0, 1))
  618. gListSizer.Add(
  619. item=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(item=self.gfilter,
  631. flag=wx.EXPAND,
  632. pos=(1, 1))
  633. gListSizer.Add(
  634. item=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(item=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(item=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(item=self.removeLayer)
  655. sizer.Add(item=buttonSizer, flag=wx.LEFT, border=5)
  656. gListSizer.Add(item=sizer, flag=wx.EXPAND, pos=(2, 1))
  657. gListSizer.AddGrowableCol(1)
  658. gListSizer.AddGrowableRow(2)
  659. self.gListPanel.SetSizer(gListSizer)
  660. bodySizer.Add(item=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(item=self.subg_sel_all,
  670. flag=wx.ALIGN_CENTER_VERTICAL,
  671. pos=(0, 1))
  672. subgListSizer.Add(
  673. item=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(item=self.subgfilter,
  685. flag=wx.EXPAND,
  686. pos=(1, 1))
  687. subgListSizer.Add(
  688. item=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(item=self.subgListBox, flag=wx.EXPAND, pos=(2, 1))
  701. subgListSizer.AddGrowableCol(1)
  702. subgListSizer.AddGrowableRow(2)
  703. self.subgListPanel.SetSizer(subgListSizer)
  704. bodySizer.Add(item=self.subgListPanel, proportion=1, flag=wx.EXPAND)
  705. self.infoLabel = wx.StaticText(parent=self, id=wx.ID_ANY)
  706. bodySizer.Add(
  707. item=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(item=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(item=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(item=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(item=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(item=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(item=self.toggle,
  1182. flag=wx.ALIGN_CENTER_VERTICAL,
  1183. pos=(0, 2))
  1184. # mapset filter
  1185. bodySizer.Add(item=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(item=self.mapset,
  1191. pos=(1, 1), span=(1, 2))
  1192. # map name filter
  1193. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Pattern:")),
  1194. flag=wx.ALIGN_CENTER_VERTICAL,
  1195. pos=(2, 0))
  1196. self.filter = wx.TextCtrl(parent=self, id=wx.ID_ANY,
  1197. value="",
  1198. size=(250, -1))
  1199. bodySizer.Add(item=self.filter,
  1200. flag=wx.EXPAND,
  1201. pos=(2, 1), span=(1, 2))
  1202. self.filter.SetFocus()
  1203. # TODO same text in GroupDialog
  1204. self.filter.SetToolTipString(
  1205. _(
  1206. "Put here a regular expression."
  1207. " Characters '.*' stand for anything,"
  1208. " character '^' stands for the beginning"
  1209. " and '$' for the end."))
  1210. # layer list
  1211. bodySizer.Add(
  1212. item=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(item=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.Checked()
  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(item=self.dseries, proportion=0,
  1372. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
  1373. def GetDSeries(self):
  1374. """Used by modeler only
  1375. :return: g.list command
  1376. """
  1377. if not self.dseries or not self.dseries.IsChecked():
  1378. return ''
  1379. cond = 'map in `g.list type=%s ' % self.GetLayerType(cmd=True)
  1380. patt = self.filter.GetValue()
  1381. if patt:
  1382. cond += 'pattern=%s ' % patt
  1383. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1384. return cond
  1385. class SetOpacityDialog(wx.Dialog):
  1386. """Set opacity of map layers.
  1387. Dialog expects opacity between 0 and 1 and returns this range, too.
  1388. """
  1389. def __init__(self, parent, id=wx.ID_ANY, title=_("Set Map Layer Opacity"),
  1390. size=wx.DefaultSize, pos=wx.DefaultPosition,
  1391. style=wx.DEFAULT_DIALOG_STYLE, opacity=1):
  1392. self.parent = parent # GMFrame
  1393. self.opacity = opacity # current opacity
  1394. super(
  1395. SetOpacityDialog,
  1396. self).__init__(
  1397. parent,
  1398. id=id,
  1399. pos=pos,
  1400. size=size,
  1401. style=style,
  1402. title=title)
  1403. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1404. panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1405. sizer = wx.BoxSizer(wx.VERTICAL)
  1406. box = wx.GridBagSizer(vgap=5, hgap=5)
  1407. self.value = wx.Slider(
  1408. panel, id=wx.ID_ANY, value=int(self.opacity * 100),
  1409. style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_TOP | wx.SL_LABELS,
  1410. minValue=0, maxValue=100, size=(350, -1))
  1411. box.Add(item=self.value,
  1412. flag=wx.ALIGN_CENTRE, pos=(0, 0), span=(1, 2))
  1413. box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
  1414. label=_("transparent")),
  1415. pos=(1, 0))
  1416. box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
  1417. label=_("opaque")),
  1418. flag=wx.ALIGN_RIGHT,
  1419. pos=(1, 1))
  1420. sizer.Add(item=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(item=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(item=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(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  1536. label=_("Width:")),
  1537. flag=wx.ALIGN_CENTER_VERTICAL)
  1538. fbox.Add(item=self.width)
  1539. fbox.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  1540. label=_("Height:")),
  1541. flag=wx.ALIGN_CENTER_VERTICAL)
  1542. fbox.Add(item=self.height)
  1543. fbox.Add(item=wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  1544. label=_("Template:")),
  1545. flag=wx.ALIGN_CENTER_VERTICAL)
  1546. fbox.Add(item=self.template)
  1547. box.Add(item=fbox, proportion=1,
  1548. flag=wx.EXPAND | wx.ALL, border=5)
  1549. sizer.Add(item=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(item=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(item=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(item=sqlSizer, proportion=1,
  1609. flag=wx.EXPAND | wx.ALL, border=5)
  1610. sizer.Add(item=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. item=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(item=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(item=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(item=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(item=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. item=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(item=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. item=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. item=hyperlinkCtrl,
  1836. proportion=0,
  1837. flag=wx.EXPAND | wx.ALL,
  1838. border=10)
  1839. btnsizer = self.CreateSeparatedButtonSizer(style)
  1840. sizer.Add(
  1841. item=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. parent=self.panel,
  1857. id=wx.ID_ANY,
  1858. bitmap=wx.ArtProvider().GetBitmap(
  1859. wx.ART_QUESTION,
  1860. client=wx.ART_MESSAGE_BOX))
  1861. self.informLabel = wx.StaticText(
  1862. parent=self.panel, id=wx.ID_ANY, label=_(
  1863. "Do you want to quit GRASS including shell "
  1864. "prompt or just close the GUI?"))
  1865. self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  1866. self.btnClose = wx.Button(parent=self.panel, id=wx.ID_NO,
  1867. label=_("Close GUI"))
  1868. self.btnClose.SetFocus()
  1869. self.btnQuit = wx.Button(parent=self.panel, id=wx.ID_YES,
  1870. label=_("Quit GRASS GIS"))
  1871. self.btnQuit.SetForegroundColour(wx.Colour(35, 142, 35))
  1872. self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  1873. self.btnQuit.Bind(wx.EVT_BUTTON, self.OnQuit)
  1874. self.__layout()
  1875. def __layout(self):
  1876. """Do layout"""
  1877. sizer = wx.BoxSizer(wx.VERTICAL)
  1878. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1879. btnSizer.Add(item=self.btnCancel, flag=wx.RIGHT, border=5)
  1880. btnSizer.Add(item=self.btnClose, flag=wx.RIGHT, border=5)
  1881. btnSizer.Add(item=self.btnQuit, flag=wx.RIGHT, border=5)
  1882. bodySizer = wx.BoxSizer(wx.HORIZONTAL)
  1883. bodySizer.Add(item=self._icon, flag=wx.RIGHT, border=10)
  1884. bodySizer.Add(item=self.informLabel, proportion=1, flag=wx.EXPAND)
  1885. sizer.Add(item=bodySizer, proportion=1,
  1886. flag=wx.EXPAND | wx.ALL, border=15)
  1887. sizer.Add(item=btnSizer, proportion=0,
  1888. flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
  1889. self.panel.SetSizer(sizer)
  1890. sizer.Fit(self)
  1891. self.Layout()
  1892. def OnClose(self, event):
  1893. self.EndModal(wx.ID_NO)
  1894. def OnQuit(self, event):
  1895. self.EndModal(wx.ID_YES)
  1896. class DefaultFontDialog(wx.Dialog):
  1897. """
  1898. Opens a file selection dialog to select default font
  1899. to use in all GRASS displays
  1900. """
  1901. def __init__(self, parent, title, id=wx.ID_ANY,
  1902. style=wx.DEFAULT_DIALOG_STYLE |
  1903. wx.RESIZE_BORDER,
  1904. settings=UserSettings,
  1905. type='font'):
  1906. self.settings = settings
  1907. self.type = type
  1908. wx.Dialog.__init__(self, parent, id, title, style=style)
  1909. panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1910. self.tmp_file = grass.tempfile(False) + '.png'
  1911. self.fontdict, fontdict_reverse, self.fontlist = self.GetFonts()
  1912. border = wx.BoxSizer(wx.VERTICAL)
  1913. box = wx.StaticBox(
  1914. parent=panel,
  1915. id=wx.ID_ANY,
  1916. label=" %s " %
  1917. _("Font settings"))
  1918. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1919. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  1920. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1921. label=_("Select font:"))
  1922. gridSizer.Add(item=label,
  1923. flag=wx.ALIGN_TOP,
  1924. pos=(0, 0))
  1925. self.fontlb = wx.ListBox(
  1926. parent=panel,
  1927. id=wx.ID_ANY,
  1928. pos=wx.DefaultPosition,
  1929. choices=self.fontlist,
  1930. style=wx.LB_SINGLE)
  1931. self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.fontlb)
  1932. self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.fontlb)
  1933. gridSizer.Add(item=self.fontlb,
  1934. flag=wx.EXPAND, pos=(1, 0))
  1935. self.renderfont = wx.StaticBitmap(panel, bitmap=wx.EmptyBitmapRGBA(100, 50, 255, 255, 255))
  1936. gridSizer.Add(item=self.renderfont,
  1937. flag=wx.EXPAND, pos=(2, 0))
  1938. if self.type == 'font':
  1939. if "GRASS_FONT" in os.environ:
  1940. self.font = os.environ["GRASS_FONT"]
  1941. else:
  1942. self.font = self.settings.Get(group='display',
  1943. key='font', subkey='type')
  1944. self.encoding = self.settings.Get(group='display',
  1945. key='font', subkey='encoding')
  1946. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1947. label=_("Character encoding:"))
  1948. gridSizer.Add(item=label,
  1949. flag=wx.ALIGN_CENTER_VERTICAL,
  1950. pos=(3, 0))
  1951. self.textentry = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
  1952. value=self.encoding)
  1953. gridSizer.Add(item=self.textentry,
  1954. flag=wx.EXPAND, pos=(4, 0))
  1955. self.textentry.Bind(wx.EVT_TEXT, self.OnEncoding)
  1956. elif self.type == 'outputfont':
  1957. self.font = self.settings.Get(group='appearance',
  1958. key='outputfont', subkey='type')
  1959. self.fontsize = self.settings.Get(group='appearance',
  1960. key='outputfont', subkey='size')
  1961. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1962. label=_("Font size:"))
  1963. gridSizer.Add(item=label,
  1964. flag=wx.ALIGN_CENTER_VERTICAL,
  1965. pos=(2, 0))
  1966. self.spin = SpinCtrl(parent=panel, id=wx.ID_ANY)
  1967. if self.fontsize:
  1968. self.spin.SetValue(int(self.fontsize))
  1969. self.spin.Bind(wx.EVT_SPINCTRL, self.OnSizeSpin)
  1970. self.spin.Bind(wx.EVT_TEXT, self.OnSizeSpin)
  1971. gridSizer.Add(item=self.spin,
  1972. flag=wx.ALIGN_CENTER_VERTICAL,
  1973. pos=(3, 0))
  1974. else:
  1975. return
  1976. if self.font:
  1977. self.fontlb.SetStringSelection(fontdict_reverse[self.font], True)
  1978. gridSizer.AddGrowableCol(0)
  1979. sizer.Add(item=gridSizer, proportion=1,
  1980. flag=wx.EXPAND | wx.ALL,
  1981. border=5)
  1982. border.Add(item=sizer, proportion=1,
  1983. flag=wx.ALL | wx.EXPAND, border=3)
  1984. btnsizer = wx.StdDialogButtonSizer()
  1985. btn = wx.Button(parent=panel, id=wx.ID_OK)
  1986. btn.SetDefault()
  1987. btnsizer.AddButton(btn)
  1988. btn = wx.Button(parent=panel, id=wx.ID_CANCEL)
  1989. btnsizer.AddButton(btn)
  1990. btnsizer.Realize()
  1991. border.Add(item=btnsizer, proportion=0,
  1992. flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1993. panel.SetAutoLayout(True)
  1994. panel.SetSizer(border)
  1995. border.Fit(self)
  1996. row, col = gridSizer.GetItemPosition(self.renderfont)
  1997. self.renderfont.SetSize(gridSizer.GetCellSize(row, col))
  1998. if self.font:
  1999. self.RenderText(self.font, _("Example"), size=self.renderfont.GetSize())
  2000. self.Layout()
  2001. def OnEncoding(self, event):
  2002. self.encoding = event.GetString()
  2003. def EvtListBox(self, event):
  2004. self.font = self.fontdict[event.GetString()]
  2005. self.RenderText(self.font, "Example", size=self.renderfont.GetSize())
  2006. event.Skip()
  2007. def EvtListBoxDClick(self, event):
  2008. self.font = self.fontdict[event.GetString()]
  2009. event.Skip()
  2010. def OnSizeSpin(self, event):
  2011. self.fontsize = self.spin.GetValue()
  2012. event.Skip()
  2013. def GetFonts(self):
  2014. """
  2015. parses fonts directory or fretypecap file to get a list of fonts
  2016. for the listbox
  2017. """
  2018. fontlist = []
  2019. fontdict = {}
  2020. fontdict_reverse = {}
  2021. env = os.environ.copy()
  2022. driver = UserSettings.Get(group='display', key='driver', subkey='type')
  2023. if driver == 'png':
  2024. env['GRASS_RENDER_IMMEDIATE'] = 'png'
  2025. else:
  2026. env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  2027. ret = RunCommand('d.fontlist', flags='v',
  2028. read=True,
  2029. env=env)
  2030. if not ret:
  2031. return fontlist
  2032. dfonts = ret.splitlines()
  2033. for line in dfonts:
  2034. shortname = line.split('|')[0]
  2035. longname = line.split('|')[1]
  2036. # not sure when this happens?
  2037. if shortname.startswith('#'):
  2038. continue
  2039. fontlist.append(longname)
  2040. fontdict[longname] = shortname
  2041. fontdict_reverse[shortname] = longname
  2042. fontlist = natural_sort(list(set(fontlist)))
  2043. return fontdict, fontdict_reverse, fontlist
  2044. def RenderText(self, font, text, size):
  2045. """Renders an example text with the selected font and resets the bitmap widget"""
  2046. env = os.environ.copy()
  2047. driver = UserSettings.Get(group='display', key='driver', subkey='type')
  2048. if driver == 'png':
  2049. env['GRASS_RENDER_IMMEDIATE'] = 'png'
  2050. else:
  2051. env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  2052. env['GRASS_RENDER_WIDTH'] = str(size[0])
  2053. env['GRASS_RENDER_HEIGHT'] = str(size[1])
  2054. env['GRASS_RENDER_FILE'] = self.tmp_file
  2055. ret = RunCommand('d.text', text=text, font=font, align='cc', at='50,50',
  2056. size=80, color='black', env=env)
  2057. if ret == 0:
  2058. self.renderfont.SetBitmap(wx.Bitmap(self.tmp_file))
  2059. else:
  2060. self.renderfont.SetBitmap(wx.EmptyBitmapRGBA(size[0], size[1]))
  2061. try_remove(self.tmp_file)