dialogs.py 97 KB

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