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