dialogs.py 83 KB

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