dialogs.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  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, 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. self.dataChanged = True
  604. event.Skip()
  605. def OnGSelAll(self, event):
  606. check = event.Checked()
  607. if not check:
  608. self.gLayerBox.DeselectAll()
  609. else:
  610. for item in range(self.subgListBox.GetCount()):
  611. self.gLayerBox.Select(item)
  612. event.Skip()
  613. def _checkGSellAll(self):
  614. check = False
  615. nsel = len(self.gLayerBox.GetSelections())
  616. if self.gLayerBox.GetCount() == nsel and \
  617. self.gLayerBox.GetCount() != 0:
  618. check = True
  619. self.g_sel_all.SetValue(check)
  620. def _checkSubGSellAll(self):
  621. not_all_checked = False
  622. if self.subgListBox.GetCount() == 0:
  623. not_all_checked = True
  624. else:
  625. for item in range(self.subgListBox.GetCount()):
  626. if not self.subgListBox.IsChecked(item):
  627. not_all_checked = True
  628. self.subg_sel_all.SetValue(not not_all_checked)
  629. def OnSubgroupFilter(self, event):
  630. text = event.GetString()
  631. self.gfilter.ChangeValue(text)
  632. self.flt_pattern = text
  633. self.FilterGroup()
  634. self.FilterSubgroup()
  635. event.Skip()
  636. def OnGroupFilter(self, event):
  637. text = event.GetString()
  638. self.subgfilter.ChangeValue(text)
  639. self.flt_pattern = text
  640. self.FilterGroup()
  641. self.FilterSubgroup()
  642. event.Skip()
  643. def OnSubgLayerCheck(self, event):
  644. idx = event.GetInt()
  645. m = self.subgListBox.GetString(idx)
  646. self.subgmaps[m] = self.subgListBox.IsChecked(idx)
  647. self.dataChanged = True
  648. self._checkSubGSellAll()
  649. def CheckSubgItem(self, idx, val):
  650. m = self.subgListBox.GetString(idx)
  651. self.subgListBox.Check(idx, val)
  652. self.subgmaps[m] = val
  653. self.dataChanged = val
  654. def DisableSubgroupEdit(self):
  655. """!Disable editation of subgroups in the dialog
  656. @todo used by gcp manager, maybe the gcp m should also support subgroups,
  657. """
  658. self.edit_subg = False
  659. self.subg_panel.Hide()
  660. self.subg_chbox.Hide()
  661. self.subgListBox.Hide()
  662. self.Layout()
  663. def OnSubgChbox(self, event):
  664. edit_subg = self.subg_chbox.GetValue()
  665. self.SubgChbox(edit_subg)
  666. def SubgChbox(self, edit_subg):
  667. self._checkChange()
  668. if edit_subg:
  669. self.edit_subg = edit_subg
  670. self.SubGroupSelected()
  671. self._subgroupLayout()
  672. else:
  673. self.edit_subg = edit_subg
  674. self.GroupSelected()
  675. self._groupLayout()
  676. self.SetMinSize(self.GetBestSize())
  677. def _groupLayout(self):
  678. self.subg_panel.Hide()
  679. self.subgListPanel.Hide()
  680. self.gListPanel.Show()
  681. self.Layout()
  682. def _subgroupLayout(self):
  683. self.subg_panel.Show()
  684. self.subgListPanel.Show()
  685. self.gListPanel.Hide()
  686. self.Layout()
  687. def OnAddLayer(self, event):
  688. """!Add new layer to listbox"""
  689. dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
  690. if dlg.ShowModal() != wx.ID_OK:
  691. dlg.Destroy()
  692. return
  693. layers = dlg.GetMapLayers()
  694. for layer in layers:
  695. if layer not in self.gmaps:
  696. self.gLayerBox.Append(layer)
  697. self.gmaps.append(layer)
  698. self.dataChanged = True
  699. def OnRemoveLayer(self, event):
  700. """!Remove layer from listbox"""
  701. while self.gLayerBox.GetSelections():
  702. sel = self.gLayerBox.GetSelections()[0]
  703. m = self.gLayerBox.GetString(sel)
  704. self.gLayerBox.Delete(sel)
  705. self.gmaps.remove(m)
  706. self.dataChanged = True
  707. def GetLayers(self):
  708. """!Get layers"""
  709. if self.edit_subg:
  710. layers = []
  711. for maps, sel in self.subgmaps.iteritems():
  712. if sel:
  713. layers.append(maps)
  714. else:
  715. layers = self.gmaps[:]
  716. return layers
  717. def OnGroupSelected(self, event):
  718. """!Text changed in group selector"""
  719. # callAfter must be called to close popup before other actions
  720. wx.CallAfter(self.GroupSelected)
  721. def GroupSelected(self):
  722. """!Group was selected, check if changes were apllied"""
  723. self._checkChange()
  724. group, s = self.GetSelectedGroup()
  725. maps = list()
  726. groups = self.GetExistGroups()
  727. if group in groups:
  728. maps = self.GetGroupLayers(group)
  729. self.subGroupSelect.Insert(group)
  730. self.gmaps = maps
  731. maps = self._filter(maps)
  732. self.ShowGroupLayers(maps)
  733. self.currentGroup = group
  734. self.SubGroupSelected()
  735. self.ClearNotification()
  736. self._checkGSellAll()
  737. def FilterGroup(self):
  738. maps = self._filter(self.gmaps)
  739. self.ShowGroupLayers(maps)
  740. self._checkGSellAll()
  741. def FilterSubgroup(self):
  742. maps = self._filter(self.gmaps)
  743. self.subgListBox.Set(maps)
  744. for i, m in enumerate(maps):
  745. if m in self.subgmaps.iterkeys() and self.subgmaps[m]:
  746. self.subgListBox.Check(i)
  747. self._checkSubGSellAll()
  748. def SubGroupSelected(self):
  749. """!Subgroup was selected, check if changes were apllied"""
  750. self._checkChange()
  751. subgroup = self.subGroupSelect.GetValue().strip()
  752. group = self.currentGroup
  753. gmaps = list()
  754. groups = self.GetExistGroups()
  755. self.subgmaps = {}
  756. if group in groups:
  757. gmaps = self.GetGroupLayers(group)
  758. if subgroup:
  759. maps = self.GetGroupLayers(group, subgroup)
  760. for m in maps:
  761. if m in gmaps:
  762. self.subgmaps[m] = True
  763. else:
  764. self.subgmaps[m] = False
  765. gmaps = self._filter(gmaps)
  766. self.subgListBox.Set(gmaps)
  767. for i, m in enumerate(gmaps):
  768. if self.subgmaps.has_key(m):
  769. self.subgListBox.Check(i)
  770. else:
  771. self.subgListBox.Check(i, False)
  772. self._checkSubGSellAll()
  773. self.currentSubgroup = subgroup
  774. self.ClearNotification()
  775. def _filter(self, data):
  776. """!Apply filter for strings in data list"""
  777. flt_data = []
  778. if len(self.flt_pattern) == 0:
  779. flt_data = data[:]
  780. return flt_data
  781. for dt in data:
  782. try:
  783. if re.compile(self.flt_pattern).search(dt):
  784. flt_data.append(dt)
  785. except:
  786. pass
  787. return flt_data
  788. def _checkChange(self):
  789. if self.edit_subg:
  790. self._checkSubgroupChange()
  791. else:
  792. self._checkGroupChange()
  793. def _checkGroupChange(self):
  794. if self.currentGroup and self.dataChanged:
  795. dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
  796. "do you want to apply changes?") % self.currentGroup,
  797. caption = _("Unapplied changes"),
  798. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  799. if dlg.ShowModal() == wx.ID_YES:
  800. self.ApplyChanges()
  801. dlg.Destroy()
  802. self.dataChanged = False
  803. def _checkSubgroupChange(self):
  804. if self.currentSubgroup and self.dataChanged:
  805. dlg = wx.MessageDialog(self, message = _("Subgroup <%s> was changed, "
  806. "do you want to apply changes?") % self.currentSubgroup,
  807. caption = _("Unapplied changes"),
  808. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  809. if dlg.ShowModal() == wx.ID_YES:
  810. self.ApplyChanges()
  811. dlg.Destroy()
  812. self.dataChanged = False
  813. def ShowGroupLayers(self, mapList):
  814. """!Show map layers in currently selected group"""
  815. self.gLayerBox.Set(mapList)
  816. def EditGroup(self, group, subgroup=None):
  817. """!Edit selected group"""
  818. layersNew = self.GetLayers()
  819. layersOld = self.GetGroupLayers(group, subgroup)
  820. add = []
  821. remove = []
  822. for layerNew in layersNew:
  823. if layerNew not in layersOld:
  824. add.append(layerNew)
  825. for layerOld in layersOld:
  826. if layerOld not in layersNew:
  827. remove.append(layerOld)
  828. kwargs = {}
  829. if subgroup:
  830. kwargs["subgroup"] = subgroup
  831. ret = None
  832. if remove:
  833. ret = RunCommand('i.group',
  834. parent = self,
  835. group = group,
  836. flags = 'r',
  837. input = ','.join(remove),
  838. **kwargs)
  839. if add:
  840. ret = RunCommand('i.group',
  841. parent = self,
  842. group = group,
  843. input = ','.join(add),
  844. **kwargs)
  845. return ret
  846. def CreateNewGroup(self, group, subgroup):
  847. """!Create new group"""
  848. layers = self.GetLayers()
  849. if not layers:
  850. GMessage(parent = self,
  851. message = _("No raster maps selected."))
  852. return 1
  853. kwargs = {}
  854. if subgroup:
  855. kwargs["subgroup"] = subgroup
  856. ret = RunCommand('i.group',
  857. parent = self,
  858. group = group,
  859. input = layers,
  860. **kwargs)
  861. #update subgroup select
  862. self.SubGroupSelected()
  863. return ret
  864. def GetExistGroups(self):
  865. """!Returns existing groups in current mapset"""
  866. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  867. def GetExistSubgroups(self, group):
  868. """!Returns existing subgroups in a group"""
  869. return RunCommand('i.group', group=group,
  870. read=True, flags='sg').splitlines()
  871. def ShowResult(self, group, returnCode, create):
  872. """!Show if operation was successfull."""
  873. group += '@' + grass.gisenv()['MAPSET']
  874. if returnCode is None:
  875. label = _("No changes to apply in group <%s>.") % group
  876. elif returnCode == 0:
  877. if create:
  878. label = _("Group <%s> was successfully created.") % group
  879. else:
  880. label = _("Group <%s> was successfully changed.") % group
  881. else:
  882. if create:
  883. label = _("Creating of new group <%s> failed.") % group
  884. else:
  885. label = _("Changing of group <%s> failed.") % group
  886. self.infoLabel.SetLabel(label)
  887. wx.FutureCall(4000, self.ClearNotification)
  888. def GetSelectedGroup(self):
  889. """!Return currently selected group (without mapset)"""
  890. g = self.groupSelect.GetValue().split('@')[0]
  891. if self.edit_subg:
  892. s = self.subGroupSelect.GetValue()
  893. else:
  894. s = None
  895. return g, s
  896. def GetGroupLayers(self, group, subgroup=None):
  897. """!Get layers in group"""
  898. kwargs = dict()
  899. kwargs['group'] = group
  900. if subgroup:
  901. kwargs['subgroup'] = subgroup
  902. res = RunCommand('i.group',
  903. parent = self,
  904. flags = 'g',
  905. read = True, **kwargs)
  906. if not res:
  907. return []
  908. return res.splitlines()
  909. def ClearNotification(self):
  910. """!Clear notification string"""
  911. self.infoLabel.SetLabel("")
  912. def ApplyChanges(self):
  913. """!Create or edit group"""
  914. group = self.currentGroup
  915. if not group:
  916. GMessage(parent = self,
  917. message = _("No group selected."))
  918. return False
  919. if self.edit_subg and not self.currentSubgroup:
  920. GMessage(parent = self,
  921. message = _("No subgroup selected."))
  922. return 0
  923. if self.edit_subg:
  924. subgroup = self.currentSubgroup
  925. else:
  926. subgroup = None
  927. groups = self.GetExistGroups()
  928. if group in groups:
  929. ret = self.EditGroup(group, subgroup)
  930. self.ShowResult(group = group, returnCode = ret, create = False)
  931. else:
  932. ret = self.CreateNewGroup(group, subgroup)
  933. self.ShowResult(group = group, returnCode = ret, create = True)
  934. self.dataChanged = False
  935. return True
  936. def OnApply(self, event):
  937. """!Apply changes"""
  938. self.ApplyChanges()
  939. def OnOk(self, event):
  940. """!Apply changes and close dialog"""
  941. if self.ApplyChanges():
  942. self.OnClose(event)
  943. def OnClose(self, event):
  944. """!Close dialog"""
  945. if not self.IsModal():
  946. self.Destroy()
  947. event.Skip()
  948. class MapLayersDialogBase(wx.Dialog):
  949. """!Base dialog for selecting map layers (raster, vector).
  950. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  951. MapLayersDialog. Base class contains core functionality.
  952. """
  953. def __init__(self, parent, title,
  954. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  955. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  956. style = style, **kwargs)
  957. self.parent = parent # GMFrame or ?
  958. self.applyAddingMapLayers = Signal('MapLayersDialogBase.applyAddingMapLayers')
  959. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  960. # dialog body
  961. self.bodySizer = self._createDialogBody()
  962. self.mainSizer.Add(item = self.bodySizer, proportion = 1,
  963. flag = wx.EXPAND | wx.ALL, border = 5)
  964. # update list of layer to be loaded
  965. self.map_layers = [] # list of map layers (full list type/mapset)
  966. self.LoadMapLayers(self.GetLayerType(cmd = True),
  967. self.mapset.GetStringSelection())
  968. self._fullyQualifiedNames()
  969. self._modelerDSeries()
  970. # buttons
  971. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  972. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  973. btnOk.SetDefault()
  974. # sizers & do layout
  975. self.btnSizer = wx.StdDialogButtonSizer()
  976. self.btnSizer.AddButton(btnCancel)
  977. self.btnSizer.AddButton(btnOk)
  978. self._addApplyButton()
  979. self.btnSizer.Realize()
  980. self.mainSizer.Add(item = self.btnSizer, proportion = 0,
  981. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  982. self.SetSizer(self.mainSizer)
  983. self.mainSizer.Fit(self)
  984. # set dialog min size
  985. self.SetMinSize(self.GetSize())
  986. def _modelerDSeries(self):
  987. """!Method used only by MapLayersDialogForModeler,
  988. for other subclasses does nothing.
  989. """
  990. pass
  991. def _addApplyButton(self):
  992. """!Method used only by MapLayersDialog,
  993. for other subclasses does nothing.
  994. """
  995. pass
  996. def _fullyQualifiedNames(self):
  997. """!Adds CheckBox which determines is fully qualified names are retuned.
  998. """
  999. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1000. label = _("Use fully-qualified map names"))
  1001. self.fullyQualified.SetValue(True)
  1002. self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
  1003. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1004. def _useFullyQualifiedNames(self):
  1005. return self.fullyQualified.IsChecked()
  1006. def _layerTypes(self):
  1007. """!Determines which layer types can be chosen.
  1008. Valid values:
  1009. - raster
  1010. - raster3d
  1011. - vector
  1012. """
  1013. return [_('raster'), _('3D raster'), _('vector')]
  1014. def _selectAll(self):
  1015. """!Check all layers by default"""
  1016. return True
  1017. def _createDialogBody(self):
  1018. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  1019. # layer type
  1020. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  1021. flag = wx.ALIGN_CENTER_VERTICAL,
  1022. pos = (0,0))
  1023. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  1024. choices = self._layerTypes(), size = (100,-1))
  1025. self.layerType.SetSelection(0)
  1026. bodySizer.Add(item = self.layerType,
  1027. pos = (0,1))
  1028. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  1029. # select toggle
  1030. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1031. label = _("Select toggle"))
  1032. self.toggle.SetValue(self._selectAll())
  1033. bodySizer.Add(item = self.toggle,
  1034. flag = wx.ALIGN_CENTER_VERTICAL,
  1035. pos = (0,2))
  1036. # mapset filter
  1037. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  1038. flag = wx.ALIGN_CENTER_VERTICAL,
  1039. pos = (1,0))
  1040. self.mapset = MapsetSelect(parent = self, searchPath = True)
  1041. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  1042. bodySizer.Add(item = self.mapset,
  1043. pos = (1,1), span = (1, 2))
  1044. # map name filter
  1045. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  1046. flag = wx.ALIGN_CENTER_VERTICAL,
  1047. pos = (2,0))
  1048. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1049. value = "",
  1050. size = (250,-1))
  1051. bodySizer.Add(item = self.filter,
  1052. flag = wx.EXPAND,
  1053. pos = (2,1), span = (1, 2))
  1054. self.filter.SetFocus()
  1055. #TODO same text in GroupDialog
  1056. self.filter.SetToolTipString(_("Put here a regular expression."
  1057. " Characters '.*' stand for anything,"
  1058. " character '^' stands for the beginning"
  1059. " and '$' for the end."))
  1060. # layer list
  1061. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  1062. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  1063. pos = (3,0))
  1064. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1065. size = (250, 100),
  1066. choices = [])
  1067. bodySizer.Add(item = self.layers,
  1068. flag = wx.EXPAND,
  1069. pos = (3,1), span = (1, 2))
  1070. bodySizer.AddGrowableCol(1)
  1071. bodySizer.AddGrowableRow(3)
  1072. # bindings
  1073. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  1074. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  1075. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  1076. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  1077. return bodySizer
  1078. def LoadMapLayers(self, type, mapset):
  1079. """!Load list of map layers
  1080. @param type layer type ('raster' or 'vector')
  1081. @param mapset mapset name
  1082. """
  1083. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  1084. self.layers.Set(self.map_layers)
  1085. # check all items by default
  1086. for item in range(self.layers.GetCount()):
  1087. self.layers.Check(item, check = self._selectAll())
  1088. def OnChangeParams(self, event):
  1089. """!Filter parameters changed by user"""
  1090. # update list of layer to be loaded
  1091. self.LoadMapLayers(self.GetLayerType(cmd = True),
  1092. self.mapset.GetStringSelection())
  1093. event.Skip()
  1094. def OnMenu(self, event):
  1095. """!Table description area, context menu"""
  1096. if not hasattr(self, "popupID1"):
  1097. self.popupDataID1 = wx.NewId()
  1098. self.popupDataID2 = wx.NewId()
  1099. self.popupDataID3 = wx.NewId()
  1100. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1101. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  1102. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  1103. # generate popup-menu
  1104. menu = wx.Menu()
  1105. menu.Append(self.popupDataID1, _("Select all"))
  1106. menu.Append(self.popupDataID2, _("Invert selection"))
  1107. menu.Append(self.popupDataID3, _("Deselect all"))
  1108. self.PopupMenu(menu)
  1109. menu.Destroy()
  1110. def OnSelectAll(self, event):
  1111. """!Select all map layer from list"""
  1112. for item in range(self.layers.GetCount()):
  1113. self.layers.Check(item, True)
  1114. def OnSelectInvert(self, event):
  1115. """!Invert current selection"""
  1116. for item in range(self.layers.GetCount()):
  1117. if self.layers.IsChecked(item):
  1118. self.layers.Check(item, False)
  1119. else:
  1120. self.layers.Check(item, True)
  1121. def OnDeselectAll(self, event):
  1122. """!Select all map layer from list"""
  1123. for item in range(self.layers.GetCount()):
  1124. self.layers.Check(item, False)
  1125. def OnFilter(self, event):
  1126. """!Apply filter for map names"""
  1127. if len(event.GetString()) == 0:
  1128. self.layers.Set(self.map_layers)
  1129. return
  1130. list = []
  1131. for layer in self.map_layers:
  1132. try:
  1133. if re.compile(event.GetString()).search(layer):
  1134. list.append(layer)
  1135. except:
  1136. pass
  1137. self.layers.Set(list)
  1138. self.OnSelectAll(None)
  1139. event.Skip()
  1140. def OnToggle(self, event):
  1141. """!Select toggle (check or uncheck all layers)"""
  1142. check = event.Checked()
  1143. for item in range(self.layers.GetCount()):
  1144. self.layers.Check(item, check)
  1145. event.Skip()
  1146. def GetMapLayers(self):
  1147. """!Return list of checked map layers"""
  1148. layerNames = []
  1149. for indx in self.layers.GetSelections():
  1150. # layers.append(self.layers.GetStringSelec(indx))
  1151. pass
  1152. mapset = self.mapset.GetStringSelection()
  1153. for item in range(self.layers.GetCount()):
  1154. if not self.layers.IsChecked(item):
  1155. continue
  1156. if self._useFullyQualifiedNames():
  1157. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  1158. else:
  1159. layerNames.append(self.layers.GetString(item))
  1160. return layerNames
  1161. def GetLayerType(self, cmd = False):
  1162. """!Get selected layer type
  1163. @param cmd True for g.mlist
  1164. """
  1165. if not cmd:
  1166. return self.layerType.GetStringSelection()
  1167. sel = self.layerType.GetSelection()
  1168. if sel == 0:
  1169. ltype = 'rast'
  1170. elif sel == 1:
  1171. ltype = 'rast3d'
  1172. else:
  1173. ltype = 'vect'
  1174. return ltype
  1175. class MapLayersDialog(MapLayersDialogBase):
  1176. """!Subclass of MapLayersDialogBase used in Layer Manager.
  1177. Contains apply button, which sends wxApplyMapLayers event.
  1178. """
  1179. def __init__(self, parent, title, **kwargs):
  1180. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1181. def _addApplyButton(self):
  1182. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  1183. self.btnSizer.AddButton(btnApply)
  1184. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1185. def OnApply(self, event):
  1186. self.applyAddingMapLayers.emit(mapLayers = self.GetMapLayers(),
  1187. ltype = self.GetLayerType(cmd = True))
  1188. class MapLayersDialogForGroups(MapLayersDialogBase):
  1189. """!Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  1190. Shows only raster maps.
  1191. """
  1192. def __init__(self, parent, title, **kwargs):
  1193. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1194. def _layerTypes(self):
  1195. return [_('raster'),]
  1196. def _selectAll(self):
  1197. """!Could be overriden"""
  1198. return False
  1199. def _fullyQualifiedNames(self):
  1200. pass
  1201. def _useFullyQualifiedNames(self):
  1202. return True
  1203. class MapLayersDialogForModeler(MapLayersDialogBase):
  1204. """!Subclass of MapLayersDialogBase used in Modeler.
  1205. """
  1206. def __init__(self, parent, title, **kwargs):
  1207. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1208. def _modelerDSeries(self):
  1209. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1210. label = _("Dynamic series (%s)") % 'g.mlist')
  1211. self.dseries.SetValue(False)
  1212. self.mainSizer.Add(item = self.dseries, proportion = 0,
  1213. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1214. def GetDSeries(self):
  1215. """!Used by modeler only
  1216. @return g.mlist command
  1217. """
  1218. if not self.dseries or not self.dseries.IsChecked():
  1219. return ''
  1220. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  1221. patt = self.filter.GetValue()
  1222. if patt:
  1223. cond += 'pattern=%s ' % patt
  1224. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1225. return cond
  1226. class ImportDialog(wx.Dialog):
  1227. """!Dialog for bulk import of various data (base class)"""
  1228. def __init__(self, parent, giface, itype,
  1229. id = wx.ID_ANY, title = _("Multiple import"),
  1230. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1231. self.parent = parent # GMFrame
  1232. self._giface = giface # used to add layers
  1233. self.importType = itype
  1234. self.options = dict() # list of options
  1235. self.commandId = -1 # id of running command
  1236. wx.Dialog.__init__(self, parent, id, title, style = style,
  1237. name = "MultiImportDialog")
  1238. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1239. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
  1240. if self.importType == 'gdal':
  1241. label = _("List of raster layers")
  1242. elif self.importType == 'ogr':
  1243. label = _("List of vector layers")
  1244. else:
  1245. label = _("List of %s layers") % self.importType.upper()
  1246. self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
  1247. # list of layers
  1248. columns = [_('Layer id'),
  1249. _('Layer name'),
  1250. _('Name for output GRASS map (editable)')]
  1251. if itype == 'ogr':
  1252. columns.insert(2, _('Feature type'))
  1253. columns.insert(3, _('Projection match'))
  1254. self.list = LayersList(parent = self.panel, columns = columns)
  1255. self.list.LoadData()
  1256. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1257. label = "%s" % _("Options"))
  1258. cmd = self._getCommand()
  1259. task = gtask.parse_interface(cmd)
  1260. for f in task.get_options()['flags']:
  1261. name = f.get('name', '')
  1262. desc = f.get('label', '')
  1263. if not desc:
  1264. desc = f.get('description', '')
  1265. if not name and not desc:
  1266. continue
  1267. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  1268. continue
  1269. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  1270. continue
  1271. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  1272. continue
  1273. elif cmd == 'v.external' and name not in ('b'):
  1274. continue
  1275. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  1276. continue
  1277. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1278. label = desc)
  1279. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1280. label = _("Allow output files to overwrite existing files"))
  1281. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1282. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  1283. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1284. label = _("Close dialog on finish"))
  1285. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1286. #
  1287. # buttons
  1288. #
  1289. # cancel
  1290. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1291. self.btn_close.SetToolTipString(_("Close dialog"))
  1292. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1293. # run
  1294. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1295. self.btn_run.SetToolTipString(_("Import selected layers"))
  1296. self.btn_run.SetDefault()
  1297. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1298. self.Bind(wx.EVT_CLOSE, lambda evt: self.Destroy())
  1299. def doLayout(self):
  1300. """!Do layout"""
  1301. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1302. # dsn input
  1303. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1304. flag = wx.EXPAND)
  1305. #
  1306. # list of DXF layers
  1307. #
  1308. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1309. layerSizer.Add(item = self.list, proportion = 1,
  1310. flag = wx.ALL | wx.EXPAND, border = 5)
  1311. dialogSizer.Add(item = layerSizer, proportion = 1,
  1312. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1313. # options
  1314. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1315. for key in self.options.keys():
  1316. optionSizer.Add(item = self.options[key], proportion = 0)
  1317. dialogSizer.Add(item = optionSizer, proportion = 0,
  1318. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1319. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1320. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1321. dialogSizer.Add(item = self.add, proportion = 0,
  1322. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1323. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1324. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1325. #
  1326. # buttons
  1327. #
  1328. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1329. btnsizer.Add(item = self.btn_close, proportion = 0,
  1330. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1331. border = 10)
  1332. btnsizer.Add(item = self.btn_run, proportion = 0,
  1333. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1334. border = 10)
  1335. dialogSizer.Add(item = btnsizer, proportion = 0,
  1336. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1337. border = 10)
  1338. # dialogSizer.SetSizeHints(self.panel)
  1339. self.panel.SetAutoLayout(True)
  1340. self.panel.SetSizer(dialogSizer)
  1341. dialogSizer.Fit(self.panel)
  1342. # auto-layout seems not work here - FIXME
  1343. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1344. self.SetMinSize(size)
  1345. self.SetSize((size.width, size.height + 100))
  1346. # width = self.GetSize()[0]
  1347. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1348. self.Layout()
  1349. def _getCommand(self):
  1350. """!Get command"""
  1351. return ''
  1352. def OnClose(self, event = None):
  1353. """!Close dialog"""
  1354. self.Close()
  1355. def OnRun(self, event):
  1356. """!Import/Link data (each layes as separate vector map)"""
  1357. pass
  1358. def AddLayers(self, returncode, cmd = None):
  1359. """!Add imported/linked layers into layer tree"""
  1360. if not self.add.IsChecked() or returncode != 0:
  1361. return
  1362. # TODO: if importing map creates more map the folowing does not work
  1363. # * do nothing if map does not exist or
  1364. # * try to determine names using regexp or
  1365. # * persuade import tools to report map names
  1366. self.commandId += 1
  1367. layer, output = self.list.GetLayers()[self.commandId]
  1368. if '@' not in output:
  1369. name = output + '@' + grass.gisenv()['MAPSET']
  1370. else:
  1371. name = output
  1372. # add imported layers into layer tree
  1373. # an alternative would be emit signal (mapCreated) and (optionally)
  1374. # connect to this signal
  1375. llist = self._giface.GetLayerList()
  1376. if self.importType == 'gdal':
  1377. cmd = ['d.rast',
  1378. 'map=%s' % name]
  1379. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1380. cmd.append('-n')
  1381. llist.AddLayer(ltype='raster',
  1382. name=name, checked=True,
  1383. cmd=cmd)
  1384. else:
  1385. llist.AddLayer(ltype='vector',
  1386. name=name, checked=True,
  1387. cmd=['d.vect',
  1388. 'map=%s' % name] + GetDisplayVectSettings())
  1389. self._giface.GetMapWindow().ZoomToMap()
  1390. def OnAbort(self, event):
  1391. """!Abort running import
  1392. @todo not yet implemented
  1393. """
  1394. pass
  1395. class GdalImportDialog(ImportDialog):
  1396. def __init__(self, parent, giface, ogr = False, link = False):
  1397. """!Dialog for bulk import of various raster/vector data
  1398. @todo Split into GdalImportDialog and OgrImportDialog
  1399. @param parent parent window
  1400. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1401. @param link True for linking data otherwise importing data
  1402. """
  1403. self._giface = giface
  1404. self.link = link
  1405. self.ogr = ogr
  1406. if ogr:
  1407. ImportDialog.__init__(self, parent, giface=giface, itype='ogr')
  1408. if link:
  1409. self.SetTitle(_("Link external vector data"))
  1410. else:
  1411. self.SetTitle(_("Import vector data"))
  1412. else:
  1413. ImportDialog.__init__(self, parent, giface=giface, itype='gdal')
  1414. if link:
  1415. self.SetTitle(_("Link external raster data"))
  1416. else:
  1417. self.SetTitle(_("Import raster data"))
  1418. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1419. ogr = ogr, link = link)
  1420. self.dsnInput.reloadDataRequired.connect(lambda data: self.list.LoadData(data))
  1421. mightNotWork = _("this might not work for multiple bands")
  1422. if link:
  1423. self.add.SetLabel(_("Add linked layers into layer tree"
  1424. " ({mightNotWork})".format(mightNotWork=mightNotWork)))
  1425. else:
  1426. self.add.SetLabel(_("Add imported layers into layer tree"
  1427. " ({mightNotWork})".format(mightNotWork=mightNotWork)))
  1428. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1429. if link:
  1430. self.btn_run.SetLabel(_("&Link"))
  1431. self.btn_run.SetToolTipString(_("Link selected layers"))
  1432. else:
  1433. self.btn_run.SetLabel(_("&Import"))
  1434. self.btn_run.SetToolTipString(_("Import selected layers"))
  1435. self.doLayout()
  1436. def OnRun(self, event):
  1437. """!Import/Link data (each layes as separate vector map)"""
  1438. self.commandId = -1
  1439. data = self.list.GetLayers()
  1440. if not data:
  1441. GMessage(_("No layers selected. Operation canceled."),
  1442. parent = self)
  1443. return
  1444. dsn = self.dsnInput.GetDsn()
  1445. ext = self.dsnInput.GetFormatExt()
  1446. # determine data driver for PostGIS links
  1447. popOGR = False
  1448. if self.importType == 'ogr' and \
  1449. self.dsnInput.GetType() == 'db' and \
  1450. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1451. 'GRASS_VECTOR_OGR' not in os.environ:
  1452. popOGR = True
  1453. os.environ['GRASS_VECTOR_OGR'] = '1'
  1454. for layer, output in data:
  1455. if self.importType == 'ogr':
  1456. if ext and layer.rfind(ext) > -1:
  1457. layer = layer.replace('.' + ext, '')
  1458. if self.link:
  1459. cmd = ['v.external',
  1460. 'dsn=%s' % dsn,
  1461. 'output=%s' % output,
  1462. 'layer=%s' % layer]
  1463. else:
  1464. cmd = ['v.in.ogr',
  1465. 'dsn=%s' % dsn,
  1466. 'layer=%s' % layer,
  1467. 'output=%s' % output]
  1468. else: # gdal
  1469. if self.dsnInput.GetType() == 'dir':
  1470. idsn = os.path.join(dsn, layer)
  1471. else:
  1472. idsn = dsn
  1473. if self.link:
  1474. cmd = ['r.external',
  1475. 'input=%s' % idsn,
  1476. 'output=%s' % output]
  1477. else:
  1478. cmd = ['r.in.gdal',
  1479. 'input=%s' % idsn,
  1480. 'output=%s' % output]
  1481. if self.overwrite.IsChecked():
  1482. cmd.append('--overwrite')
  1483. for key in self.options.keys():
  1484. if self.options[key].IsChecked():
  1485. cmd.append('-%s' % key)
  1486. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1487. '--overwrite' not in cmd:
  1488. cmd.append('--overwrite')
  1489. # run in Layer Manager
  1490. self._giface.RunCmd(cmd, onDone=self.AddLayers)
  1491. if popOGR:
  1492. os.environ.pop('GRASS_VECTOR_OGR')
  1493. if self.closeOnFinish.IsChecked():
  1494. self.Close()
  1495. def _getCommand(self):
  1496. """!Get command"""
  1497. if self.link:
  1498. if self.ogr:
  1499. return 'v.external'
  1500. else:
  1501. return 'r.external'
  1502. else:
  1503. if self.ogr:
  1504. return 'v.in.ogr'
  1505. else:
  1506. return 'r.in.gdal'
  1507. return ''
  1508. class GdalOutputDialog(wx.Dialog):
  1509. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1510. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1511. """!Dialog for setting output format for rasters/vectors
  1512. @todo Split into GdalOutputDialog and OgrOutputDialog
  1513. @param parent parent window
  1514. @param id window id
  1515. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1516. @param style window style
  1517. @param *kwargs other wx.Dialog's arguments
  1518. """
  1519. self.parent = parent # GMFrame
  1520. self.ogr = ogr
  1521. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1522. if self.ogr:
  1523. self.SetTitle(_("Define output format for vector data"))
  1524. else:
  1525. self.SetTitle(_("Define output format for raster data"))
  1526. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1527. # buttons
  1528. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1529. self.btnCancel.SetToolTipString(_("Close dialog"))
  1530. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1531. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1532. self.btnOk.SetDefault()
  1533. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1534. ogr = ogr,
  1535. exclude = ['file', 'protocol'], dest = True)
  1536. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1537. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1538. self._layout()
  1539. def _layout(self):
  1540. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1541. dialogSizer.Add(item = self.dsnInput, proportion = 1,
  1542. flag = wx.EXPAND)
  1543. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1544. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1545. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1546. border = 10)
  1547. btnSizer.Add(item = self.btnOk, proportion = 0,
  1548. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1549. border = 10)
  1550. dialogSizer.Add(item = btnSizer, proportion = 0,
  1551. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1552. border = 10)
  1553. self.panel.SetAutoLayout(True)
  1554. self.panel.SetSizer(dialogSizer)
  1555. dialogSizer.Fit(self.panel)
  1556. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1] + 35)
  1557. self.SetMinSize(size)
  1558. self.SetSize((size.width, size.height))
  1559. self.Layout()
  1560. def OnCancel(self, event):
  1561. self.Destroy()
  1562. def OnOK(self, event):
  1563. if self.dsnInput.GetType() == 'native':
  1564. RunCommand('v.external.out',
  1565. parent = self,
  1566. flags = 'r')
  1567. else:
  1568. dsn = self.dsnInput.GetDsn()
  1569. frmt = self.dsnInput.GetFormat()
  1570. options = self.dsnInput.GetOptions()
  1571. if not dsn:
  1572. GMessage(_("No data source selected."), parent=self)
  1573. return
  1574. RunCommand('v.external.out',
  1575. parent = self,
  1576. dsn = dsn, format = frmt,
  1577. options = options)
  1578. self.Close()
  1579. class DxfImportDialog(ImportDialog):
  1580. """!Dialog for bulk import of DXF layers"""
  1581. def __init__(self, parent, giface):
  1582. ImportDialog.__init__(self, parent, giface=giface, itype='dxf',
  1583. title = _("Import DXF layers"))
  1584. self._giface = giface
  1585. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1586. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1587. dialogTitle = _('Choose DXF file to import'),
  1588. buttonText = _('Browse'),
  1589. startDirectory = os.getcwd(), fileMode = 0,
  1590. changeCallback = self.OnSetDsn,
  1591. fileMask = "DXF File (*.dxf)|*.dxf")
  1592. self.add.SetLabel(_("Add imported layers into layer tree"))
  1593. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1594. self.doLayout()
  1595. def _getCommand(self):
  1596. """!Get command"""
  1597. return 'v.in.dxf'
  1598. def OnRun(self, event):
  1599. """!Import/Link data (each layes as separate vector map)"""
  1600. data = self.list.GetLayers()
  1601. if not data:
  1602. GMessage(_("No layers selected."), parent=self)
  1603. return
  1604. # hide dialog
  1605. self.Hide()
  1606. inputDxf = self.dsnInput.GetValue()
  1607. for layer, output in data:
  1608. cmd = ['v.in.dxf',
  1609. 'input=%s' % inputDxf,
  1610. 'layers=%s' % layer,
  1611. 'output=%s' % output]
  1612. for key in self.options.keys():
  1613. if self.options[key].IsChecked():
  1614. cmd.append('-%s' % key)
  1615. if self.overwrite.IsChecked() or \
  1616. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1617. cmd.append('--overwrite')
  1618. # run in Layer Manager
  1619. self._giface.RunCmd(cmd, onDone=self.AddLayers)
  1620. self.Close()
  1621. def OnSetDsn(self, event):
  1622. """!Input DXF file defined, update list of layer widget"""
  1623. path = event.GetString()
  1624. if not path:
  1625. return
  1626. data = list()
  1627. ret = RunCommand('v.in.dxf',
  1628. quiet = True,
  1629. parent = self,
  1630. read = True,
  1631. flags = 'l',
  1632. input = path)
  1633. if not ret:
  1634. self.list.LoadData()
  1635. return
  1636. for line in ret.splitlines():
  1637. layerId = line.split(':')[0].split(' ')[1]
  1638. layerName = line.split(':')[1].strip()
  1639. grassName = GetValidLayerName(layerName)
  1640. data.append((layerId, layerName.strip(), grassName.strip()))
  1641. self.list.LoadData(data)
  1642. class LayersList(GListCtrl, listmix.TextEditMixin):
  1643. """!List of layers to be imported (dxf, shp...)"""
  1644. def __init__(self, parent, columns, log = None):
  1645. GListCtrl.__init__(self, parent)
  1646. self.log = log
  1647. # setup mixins
  1648. listmix.TextEditMixin.__init__(self)
  1649. for i in range(len(columns)):
  1650. self.InsertColumn(i, columns[i])
  1651. if len(columns) == 3:
  1652. width = (65, 200)
  1653. else:
  1654. width = (65, 180, 90, 70)
  1655. for i in range(len(width)):
  1656. self.SetColumnWidth(col = i, width = width[i])
  1657. def LoadData(self, data = None):
  1658. """!Load data into list"""
  1659. self.DeleteAllItems()
  1660. if data is None:
  1661. return
  1662. for item in data:
  1663. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1664. for i in range(1, len(item)):
  1665. self.SetStringItem(index, i, "%s" % str(item[i]))
  1666. # check by default only on one item
  1667. if len(data) == 1:
  1668. self.CheckItem(index, True)
  1669. def OnLeftDown(self, event):
  1670. """!Allow editing only output name
  1671. Code taken from TextEditMixin class.
  1672. """
  1673. x, y = event.GetPosition()
  1674. colLocs = [0]
  1675. loc = 0
  1676. for n in range(self.GetColumnCount()):
  1677. loc = loc + self.GetColumnWidth(n)
  1678. colLocs.append(loc)
  1679. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1680. if col == self.GetColumnCount() - 1:
  1681. listmix.TextEditMixin.OnLeftDown(self, event)
  1682. else:
  1683. event.Skip()
  1684. def GetLayers(self):
  1685. """!Get list of layers (layer name, output name)"""
  1686. data = []
  1687. item = -1
  1688. while True:
  1689. item = self.GetNextItem(item)
  1690. if item == -1:
  1691. break
  1692. if not self.IsChecked(item):
  1693. continue
  1694. # layer / output name
  1695. data.append((self.GetItem(item, 1).GetText(),
  1696. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1697. return data
  1698. class SetOpacityDialog(wx.Dialog):
  1699. """!Set opacity of map layers.
  1700. Dialog expects opacity between 0 and 1 and returns this range, too.
  1701. """
  1702. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1703. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1704. style = wx.DEFAULT_DIALOG_STYLE, opacity = 1):
  1705. self.parent = parent # GMFrame
  1706. self.opacity = opacity # current opacity
  1707. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1708. size = size, style = style, title = title)
  1709. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1710. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1711. sizer = wx.BoxSizer(wx.VERTICAL)
  1712. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1713. self.value = wx.Slider(panel, id = wx.ID_ANY, value = int(self.opacity * 100),
  1714. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1715. wx.SL_TOP | wx.SL_LABELS,
  1716. minValue = 0, maxValue = 100,
  1717. size = (350, -1))
  1718. box.Add(item = self.value,
  1719. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1720. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1721. label = _("transparent")),
  1722. pos = (1, 0))
  1723. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1724. label = _("opaque")),
  1725. flag = wx.ALIGN_RIGHT,
  1726. pos = (1, 1))
  1727. sizer.Add(item = box, proportion = 0,
  1728. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1729. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1730. style = wx.LI_HORIZONTAL)
  1731. sizer.Add(item = line, proportion = 0,
  1732. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1733. # buttons
  1734. btnsizer = wx.StdDialogButtonSizer()
  1735. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1736. btnOK.SetDefault()
  1737. btnsizer.AddButton(btnOK)
  1738. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1739. btnsizer.AddButton(btnCancel)
  1740. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1741. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1742. btnsizer.AddButton(btnApply)
  1743. btnsizer.Realize()
  1744. sizer.Add(item = btnsizer, proportion = 0,
  1745. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1746. panel.SetSizer(sizer)
  1747. sizer.Fit(panel)
  1748. self.SetSize(self.GetBestSize())
  1749. self.Layout()
  1750. def GetOpacity(self):
  1751. """!Button 'OK' pressed"""
  1752. # return opacity value
  1753. opacity = float(self.value.GetValue()) / 100
  1754. return opacity
  1755. def OnApply(self, event):
  1756. self.applyOpacity.emit(value = self.GetOpacity())
  1757. def GetImageHandlers(image):
  1758. """!Get list of supported image handlers"""
  1759. lext = list()
  1760. ltype = list()
  1761. for h in image.GetHandlers():
  1762. lext.append(h.GetExtension())
  1763. filetype = ''
  1764. if 'png' in lext:
  1765. filetype += "PNG file (*.png)|*.png|"
  1766. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1767. 'ext' : 'png' })
  1768. filetype += "BMP file (*.bmp)|*.bmp|"
  1769. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1770. 'ext' : 'bmp' })
  1771. if 'gif' in lext:
  1772. filetype += "GIF file (*.gif)|*.gif|"
  1773. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1774. 'ext' : 'gif' })
  1775. if 'jpg' in lext:
  1776. filetype += "JPG file (*.jpg)|*.jpg|"
  1777. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1778. 'ext' : 'jpg' })
  1779. if 'pcx' in lext:
  1780. filetype += "PCX file (*.pcx)|*.pcx|"
  1781. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1782. 'ext' : 'pcx' })
  1783. if 'pnm' in lext:
  1784. filetype += "PNM file (*.pnm)|*.pnm|"
  1785. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1786. 'ext' : 'pnm' })
  1787. if 'tif' in lext:
  1788. filetype += "TIF file (*.tif)|*.tif|"
  1789. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1790. 'ext' : 'tif' })
  1791. if 'xpm' in lext:
  1792. filetype += "XPM file (*.xpm)|*.xpm"
  1793. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1794. 'ext' : 'xpm' })
  1795. return filetype, ltype
  1796. class ImageSizeDialog(wx.Dialog):
  1797. """!Set size for saved graphic file"""
  1798. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1799. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1800. self.parent = parent
  1801. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1802. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1803. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1804. label = ' % s' % _("Image size"))
  1805. size = self.parent.GetWindow().GetClientSize()
  1806. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1807. style = wx.SP_ARROW_KEYS)
  1808. self.width.SetRange(20, 1e6)
  1809. self.width.SetValue(size.width)
  1810. wx.CallAfter(self.width.SetFocus)
  1811. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1812. style = wx.SP_ARROW_KEYS)
  1813. self.height.SetRange(20, 1e6)
  1814. self.height.SetValue(size.height)
  1815. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1816. size = (125, -1),
  1817. choices = [ "",
  1818. "640x480",
  1819. "800x600",
  1820. "1024x768",
  1821. "1280x960",
  1822. "1600x1200",
  1823. "1920x1440" ])
  1824. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1825. self.btnOK.SetDefault()
  1826. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1827. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1828. self._layout()
  1829. self.SetSize(self.GetBestSize())
  1830. def _layout(self):
  1831. """!Do layout"""
  1832. sizer = wx.BoxSizer(wx.VERTICAL)
  1833. # body
  1834. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1835. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1836. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1837. label = _("Width:")),
  1838. flag = wx.ALIGN_CENTER_VERTICAL)
  1839. fbox.Add(item = self.width)
  1840. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1841. label = _("Height:")),
  1842. flag = wx.ALIGN_CENTER_VERTICAL)
  1843. fbox.Add(item = self.height)
  1844. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1845. label = _("Template:")),
  1846. flag = wx.ALIGN_CENTER_VERTICAL)
  1847. fbox.Add(item = self.template)
  1848. box.Add(item = fbox, proportion = 1,
  1849. flag = wx.EXPAND | wx.ALL, border = 5)
  1850. sizer.Add(item = box, proportion = 1,
  1851. flag=wx.EXPAND | wx.ALL, border = 3)
  1852. # buttons
  1853. btnsizer = wx.StdDialogButtonSizer()
  1854. btnsizer.AddButton(self.btnOK)
  1855. btnsizer.AddButton(self.btnCancel)
  1856. btnsizer.Realize()
  1857. sizer.Add(item = btnsizer, proportion = 0,
  1858. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1859. self.panel.SetSizer(sizer)
  1860. sizer.Fit(self.panel)
  1861. self.Layout()
  1862. def GetValues(self):
  1863. """!Get width/height values"""
  1864. return self.width.GetValue(), self.height.GetValue()
  1865. def OnTemplate(self, event):
  1866. """!Template selected"""
  1867. sel = event.GetString()
  1868. if not sel:
  1869. width, height = self.parent.GetWindow().GetClientSize()
  1870. else:
  1871. width, height = map(int, sel.split('x'))
  1872. self.width.SetValue(width)
  1873. self.height.SetValue(height)
  1874. class SqlQueryFrame(wx.Frame):
  1875. def __init__(self, parent, id = wx.ID_ANY,
  1876. title = _("GRASS GIS SQL Query Utility"),
  1877. *kwargs):
  1878. """!SQL Query Utility window
  1879. """
  1880. self.parent = parent
  1881. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1882. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1883. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1884. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1885. label = _(" SQL statement "))
  1886. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1887. style = wx.TE_MULTILINE)
  1888. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1889. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1890. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1891. self._layout()
  1892. self.SetMinSize(wx.Size(300, 150))
  1893. self.SetSize(wx.Size(500, 200))
  1894. def _layout(self):
  1895. """!Do layout"""
  1896. sizer = wx.BoxSizer(wx.VERTICAL)
  1897. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1898. sqlSizer.Add(item = self.sql, proportion = 1,
  1899. flag = wx.EXPAND)
  1900. btnSizer = wx.StdDialogButtonSizer()
  1901. btnSizer.AddButton(self.btnApply)
  1902. btnSizer.AddButton(self.btnCancel)
  1903. btnSizer.Realize()
  1904. sizer.Add(item = sqlSizer, proportion = 1,
  1905. flag = wx.EXPAND | wx.ALL, border = 5)
  1906. sizer.Add(item = btnSizer, proportion = 0,
  1907. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1908. self.panel.SetSizer(sizer)
  1909. self.Layout()
  1910. def OnCloseWindow(self, event):
  1911. """!Close window
  1912. """
  1913. self.Close()
  1914. class SymbolDialog(wx.Dialog):
  1915. """!Dialog for GRASS symbols selection.
  1916. Dialog is called in gui_core::forms module.
  1917. """
  1918. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  1919. """!Dialog constructor.
  1920. It is assumed that symbolPath contains folders with symbols.
  1921. @param parent dialog parent
  1922. @param symbolPath absolute path to symbols
  1923. @param currentSymbol currently selected symbol (e.g. 'basic/x')
  1924. @param title dialog title
  1925. """
  1926. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  1927. self.symbolPath = symbolPath
  1928. self.currentSymbol = currentSymbol # default basic/x
  1929. self.selected = None
  1930. self.selectedDir = None
  1931. self._layout()
  1932. def _layout(self):
  1933. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  1934. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1935. vSizer = wx.BoxSizer( wx.VERTICAL)
  1936. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  1937. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  1938. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  1939. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  1940. proportion = 0,
  1941. flag = wx.ALIGN_CENTER_VERTICAL)
  1942. fgSizer.Add(item = self.folderChoice, proportion = 0,
  1943. flag = wx.ALIGN_CENTER, border = 0)
  1944. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  1945. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  1946. flag = wx.ALIGN_CENTRE_VERTICAL)
  1947. fgSizer.Add(self.infoLabel, proportion = 0,
  1948. flag = wx.ALIGN_CENTRE_VERTICAL)
  1949. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  1950. self.panels = self._createSymbolPanels(mainPanel)
  1951. for panel in self.panels:
  1952. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  1953. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  1954. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  1955. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  1956. self.btnOK.SetDefault()
  1957. self.btnOK.Enable(False)
  1958. # buttons
  1959. btnSizer = wx.StdDialogButtonSizer()
  1960. btnSizer.AddButton(self.btnCancel)
  1961. btnSizer.AddButton(self.btnOK)
  1962. btnSizer.Realize()
  1963. mainSizer.Add(item = btnSizer, proportion = 0,
  1964. flag = wx.EXPAND | wx.ALL, border = 5)
  1965. # show panel with the largest number of images and fit size
  1966. count = []
  1967. for folder in os.listdir(self.symbolPath):
  1968. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  1969. index = count.index(max(count))
  1970. self.folderChoice.SetSelection(index)
  1971. self.OnFolderSelect(None)
  1972. self.infoLabel.Show()
  1973. mainPanel.SetSizerAndFit(mainSizer)
  1974. self.SetSize(self.GetBestSize())
  1975. # show currently selected symbol
  1976. if self.currentSymbol:
  1977. # set directory
  1978. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  1979. self.folderChoice.SetStringSelection(self.selectedDir)
  1980. # select symbol
  1981. panelIdx = self.folderChoice.GetSelection()
  1982. for panel in self.symbolPanels[panelIdx]:
  1983. if panel.GetName() == self.selected:
  1984. panel.Select()
  1985. else:
  1986. self.folderChoice.SetSelection(0)
  1987. self.OnFolderSelect(None)
  1988. def _createSymbolPanels(self, parent):
  1989. """!Creates multiple panels with symbols.
  1990. Panels are shown/hidden according to selected folder."""
  1991. folders = os.listdir(self.symbolPath)
  1992. panels = []
  1993. self.symbolPanels = []
  1994. for folder in folders:
  1995. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  1996. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  1997. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  1998. symbolPanels = []
  1999. for img in images:
  2000. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  2001. iP.symbolSelectionChanged.connect(self.SelectionChanged)
  2002. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  2003. symbolPanels.append(iP)
  2004. panel.SetSizerAndFit(sizer)
  2005. panel.Hide()
  2006. panels.append(panel)
  2007. self.symbolPanels.append(symbolPanels)
  2008. return panels
  2009. def _getSymbols(self, path):
  2010. # we assume that images are in subfolders (1 level only)
  2011. imageList = []
  2012. for image in os.listdir(path):
  2013. imageList.append(os.path.join(path, image))
  2014. return sorted(imageList)
  2015. def OnFolderSelect(self, event):
  2016. """!Selected folder with symbols changed."""
  2017. idx = self.folderChoice.GetSelection()
  2018. for i in range(len(self.panels)):
  2019. sizer = self.panels[i].GetContainingSizer()
  2020. sizer.Show(self.panels[i], i == idx, recursive = True)
  2021. sizer.Layout()
  2022. if self.selectedDir == self.folderChoice.GetStringSelection():
  2023. self.btnOK.Enable()
  2024. self.infoLabel.SetLabel(self.selected)
  2025. else:
  2026. self.btnOK.Disable()
  2027. self.infoLabel.SetLabel('')
  2028. def SelectionChanged(self, name, doubleClick):
  2029. """!Selected symbol changed."""
  2030. if doubleClick:
  2031. self.EndModal(wx.ID_OK)
  2032. # deselect all
  2033. for i in range(len(self.panels)):
  2034. for panel in self.symbolPanels[i]:
  2035. if panel.GetName() != name:
  2036. panel.Deselect()
  2037. self.btnOK.Enable()
  2038. self.selected = name
  2039. self.selectedDir = self.folderChoice.GetStringSelection()
  2040. self.infoLabel.SetLabel(name)
  2041. def GetSelectedSymbolName(self):
  2042. """!Returns currently selected symbol name (e.g. 'basic/x').
  2043. """
  2044. # separator must be '/' and not dependent on OS
  2045. return self.selectedDir + '/' + self.selected
  2046. def GetSelectedSymbolPath(self):
  2047. """!Returns currently selected symbol full path.
  2048. """
  2049. return os.path.join(self.symbolPath, self.selectedDir, self.selected)
  2050. class TextEntryDialog(wx.Dialog):
  2051. """!Simple dialog with text field.
  2052. It differs from wx.TextEntryDialog because it allows adding validator.
  2053. """
  2054. def __init__(self, parent, message, caption='',
  2055. defaultValue='', validator=wx.DefaultValidator,
  2056. style=wx.OK | wx.CANCEL, **kwargs):
  2057. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=caption, **kwargs)
  2058. vbox = wx.BoxSizer(wx.VERTICAL)
  2059. stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
  2060. vbox.Add(item=stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  2061. self._textCtrl = wx.TextCtrl(self, id=wx.ID_ANY, size = (300, -1),
  2062. value=defaultValue, validator=validator)
  2063. vbox.Add(item=self._textCtrl, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  2064. self._textCtrl.SetFocus()
  2065. sizer = self.CreateSeparatedButtonSizer(style)
  2066. vbox.Add(item=sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2067. self.SetSizerAndFit(vbox)
  2068. def GetValue(self):
  2069. return self._textCtrl.GetValue()
  2070. def SetValue(self, value):
  2071. self._textCtrl.SetValue(value)
  2072. class HyperlinkDialog(wx.Dialog):
  2073. """!Dialog for displaying message with hyperlink."""
  2074. def __init__(self, parent, title, message, hyperlink,
  2075. hyperlinkLabel=None, style=wx.OK):
  2076. """!Constructor
  2077. @param parent gui parent
  2078. @param title dialog title
  2079. @param message message
  2080. @param hyperlink url
  2081. @param hyperlinkLabel label shown instead of url
  2082. @param style button style
  2083. """
  2084. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  2085. style=wx.DEFAULT_DIALOG_STYLE)
  2086. sizer = wx.BoxSizer(wx.VERTICAL)
  2087. label = wx.StaticText(self, label=message)
  2088. sizer.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=10)
  2089. hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
  2090. hyperlinkCtrl = wx.HyperlinkCtrl(self, id=wx.ID_ANY,
  2091. label=hyperlinkLabel, url=hyperlink,
  2092. style=wx.HL_ALIGN_LEFT|wx.HL_CONTEXTMENU)
  2093. sizer.Add(item=hyperlinkCtrl, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)
  2094. btnsizer = self.CreateSeparatedButtonSizer(style)
  2095. sizer.Add(item=btnsizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2096. self.SetSizer(sizer)
  2097. sizer.Fit(self)