dialogs.py 98 KB

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