dialogs.py 95 KB

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