1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
# Copyright (C) 2005 by Intevation GmbH
# Authors:
# Jan-Oliver Wagner <jan@intevation.de> (2005)
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.
"""
Extend Thuban with a routine to export a layer
as a Shapefile.
"""
__version__ = '$Revision: 2724 $'
# $Source$
# $Id: export_shapefile.py 2724 2007-02-20 10:25:11Z bernhard $
import wx
from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, \
SHAPETYPE_POINT
from Thuban.Model.table import table_to_dbf
from Thuban.UI.command import registry, Command
from Thuban.UI.mainwindow import main_menu
from Thuban import _
import shapelib
def ExportLayerAsShapefile(context):
"""Request filename from user,
and create the Shapefile(s) .shp, .dbf and .shx.
context -- The Thuban context.
"""
# First, find the current layer
layer = context.mainwindow.canvas.SelectedLayer()
if layer is None:
context.mainwindow.RunMessageBox(_('Export Shapefile'),
_('No layer selected'))
return
# Second, get the basefilename for the shapefile.
dlg = wx.FileDialog(context.mainwindow,
_('Export Shapefile'), '.', '',
_('Shapefile Files (*.shp)|*.shp|'),
wx.SAVE|wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()[:-4]
dlg.Destroy()
else:
return
# Third, create the dbf file of the new Shapefile
dbf_filename = filename + '.dbf'
if hasattr(layer, "ShapeStore"):
table = layer.ShapeStore().Table()
table_to_dbf(table, dbf_filename)
# Fourth, prepare the shp file of the new Shapefile
shp_filename = filename + '.shp'
shapetypes = { SHAPETYPE_POLYGON: shapelib.SHPT_POLYGON,
SHAPETYPE_ARC: shapelib.SHPT_ARC,
SHAPETYPE_POINT: shapelib.SHPT_POINT}
shp = shapelib.create(shp_filename, shapetypes[layer.ShapeType()])
# Now go through all shapes and store them to the file
dlg= wx.ProgressDialog(_("Export Shapefile"),
_("Storing shapes ..."),
layer.ShapeStore().NumShapes(),
None)
cnt = 0
step = int(layer.ShapeStore().NumShapes() / 100.0)
if step == 0: step = 1
for s in layer.ShapeStore().AllShapes():
i = s.ShapeID()
print s.Points()
obj = shapelib.SHPObject(shapetypes[layer.ShapeType()], i, s.Points())
shp.write_object(i, obj)
if cnt % step == 0:
dlg.Update(cnt)
cnt = cnt + 1
del shp
dlg.Destroy()
# register the new command
registry.Add(Command('ExportShapefile', _('Export Layer as Shapefile ...'),
ExportLayerAsShapefile,
helptext = _('Export the active layer as a Shapefile')))
# find the experimental menu (create it anew if not found)
experimental_menu = main_menu.FindOrInsertMenu("experimental", \
_("Experimenta&l"))
# finally add the new entry to the extensions menu
experimental_menu.InsertItem('ExportShapefile')
|