File: ogrstart.py

package info (click to toggle)
thuban 1.2.2-14
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,176 kB
  • sloc: python: 30,410; ansic: 6,181; xml: 4,234; cpp: 1,595; makefile: 145
file content (236 lines) | stat: -rw-r--r-- 9,041 bytes parent folder | download | duplicates (2)
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# Copyright (c) 2004,2006,2007 by Intevation GmbH    vim:encoding=iso-8859-15:
# Authors:
# Nina H├╝ffmeyer <nhueffme@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

__version__ = "$Revision: 2812 $"
# $Source$
# $Id: ogrstart.py 2812 2008-01-19 01:15:56Z bernhard $

# Needed wx-toolkit classes
import wx

# We need os.path
import os

# use _() already now for all strings that may later be translated
from Thuban import _

from Thuban.Model.layer import Layer
from Thuban.UI import internal_from_wxstring

# Import ogr related classes
from Extensions.ogr import ogrshapes, ogrdialog
from Extensions.ogr.ogrdialog import ChooseOGRDBTableDialog

from Thuban.UI.menu import Menu
from Thuban.UI.mainwindow import _has_dbconnections, _has_gdal_support

def open_with_ogr(context):
    '''Open a file supported by ogr.
    '''
    canvas = context.mainwindow.canvas
    mymap = canvas.Map()

    # Get the file to be opened
    wildcard = _("Shapefiles (*.shp)") + "|*.shp|" +\
                           _("GML files (*.gml)") + "|*.gml|" +\
                           _("MapInfo files (*.tab)") + "|*.tab|" +\
                           _("DGN files (*.dgn)") + "|*.dgn|" +\
                           _("CSV files (*.csv)") + "|*.csv|" +\
                           _("All Files (*.*)") + "|*.*"
    dlg = wx.FileDialog(canvas, _("Select a data file"),
                           context.application.Path("data"), "",
                           wildcard,
                           wx.OPEN | wx.MULTIPLE)
    if dlg.ShowModal() == wx.ID_OK:
        filenames = map(internal_from_wxstring, dlg.GetPaths())
        for filename in filenames:
            title = os.path.splitext(os.path.basename(filename))[0]
            has_layers = mymap.HasLayers()
            layerDlg = ogrdialog.ChooseLayer(canvas, filename)
            if layerDlg.ShowModal() == wx.ID_OK:
                layername = layerDlg.GetLayer()
                try:
                    session = context.application.Session()
                    store = OpenFileShapestore(context.mainwindow, session,
                                               filename, layername)
                    session.AddShapeStore(store)
                except:
                    # the layer couldn't be opened
                    context.mainwindow.RunMessageBox(_("Add Layer"),
                                _("Can't open the file '%s'.") % filename)
                else:
                    if store is not None:
                        layer = Layer(title, store)
                        mymap.AddLayer(layer)
                        if not has_layers:
                            # if we're adding a layer to an empty map, fit the
                            # new map to the window
                            canvas.FitMapToWindow()
                    context.application.SetPath("data",filename)
        dlg.Destroy()

def select_file_format(context):
    ''' Display all available supported formats.
    '''
    canvas = context.mainwindow.canvas

    session = context.application.Session()

    dlg = ogrdialog.ChooseFileFormat(canvas, session)

    if dlg.ShowModal() == wx.ID_OK:
        pass
    dlg.Destroy()

def open_db(context):
    ''' Open a table in a database as a layer.
    '''

    canvas = context.mainwindow.canvas
    map = canvas.Map()

    session = context.application.Session()
    dlg = ChooseOGRDBTableDialog(canvas, session)

    if dlg.ShowModal() == wx.ID_OK:
        dbconn, connString, dbtable, id_column = dlg.GetTable()
        try:
            store = OpenDBShapestore(session, dbconn, dbtable, id_column,
                                            None)
            session.AddShapeStore(store)

            layer = Layer(dbtable, store)

            has_layers = map.HasLayers()
            map.AddLayer(layer)
            if not has_layers:
                canvas.FitMapToWindow()
        except:
            # Some error occurred while initializing the layer
            context.mainwindow.RunMessageBox(_("Add Layer from database"),
                               _("Can't open the database table '%s'")
                               % dbtable)
    dlg.Destroy()

def open_OGRConnection(context):
    """Open a datasource with an OGRConnection string."""
    canvas = context.mainwindow.canvas
    map = canvas.Map()

    session = context.application.Session()
    dlg = ogrdialog.OGRConnectionDialog(canvas, session)

    if dlg.ShowModal() == wx.ID_OK:
        dsname = dlg.GetDatasourceName()

        layerDlg = ogrdialog.ChooseLayer(canvas, dsname)
        if layerDlg.ShowModal() == wx.ID_OK:
            layername = layerDlg.GetLayer()
            try:
                store = ogrshapes.OGRShapeStore(session, dsname, layername)
                session.AddShapeStore(store)
            except:
                # the layer couldn't be opened
                context.mainwindow.RunMessageBox(("Add Layer"),
                            ("Can't open the file '%s'.") % dsname)
            else:
                layer = Layer(dsname, store)
                has_layers = map.HasLayers()
                map.AddLayer(layer)
                if not has_layers:
                    # if we're adding a layer to an empty map, fit the
                    # new map to the window
                    canvas.FitMapToWindow()
    dlg.Destroy()

def OpenFileShapestore(mainwindow, session, filename, layername):
    """Open a datasource and add the required layer.
    """
    try:
        store = ogrshapes.OGRFileShapeStore(session, filename, layername)
        return store
    except:
        # Some error occurred while initializing the layer
        mainwindow.RunMessageBox(_("Open datasource"),
                           _("Can't open the datasource '%s'")
                           % filename)
        return None

def OpenDBShapestore(session, dbconn, layername, id_column, geo_column):
    """Open a datasource and add the required layer.

    dbconn     - shold be a DBConnection
    layername  - the name of the table which should opened as layer
    id_column  - the column name which should be used as ID column
    geo_column - always None for ogr
    """
    try:
        filename = "PG: dbname=%s" %dbconn.dbname
        if dbconn.host is not "":
            filename = filename + " host=%s" % dbconn.host
        if dbconn.user is not "":
            filename = filename + " user=%s" % dbconn.user
        if dbconn.password is not "":
            filename = filename + " password=%s" % dbconn.password
        if dbconn.port is not "":
            filename = filename + " port=%s" % dbconn.port
        store = ogrshapes.OGRShapeStore(session, filename, layername,
                                        id_column = id_column)
        return store
    except:
        # Some error occurred while initializing the layer
        context.mainwindow.RunMessageBox(_("Open datasource"),
                           _("Can't open the datasource '%s'")
                           % filename)

# Thuban has named commands which can be registered in the central
# instance registry.
from Thuban.UI.command import registry, Command

# The instance of the main menu of the Thuban application
# See Thuban/UI/menu.py for the API of the Menu class
from Thuban.UI.mainwindow import main_menu


# find the map menu (create a new if not found)
#map_menu = main_menu.FindOrInsertMenu('map', _('Map'))
#ogr_menu = Menu("ogr", _("Open layer via OGR"),[])
# as long as there we are not stable, better add to "Extentions" marked "beta"
map_menu = main_menu.FindOrInsertMenu('extensions', _('E&xtensions'))
ogr_menu = Menu("ogr", _("(testing) ") + _("Open layer via OGR"),[])


ogrsupport = ogrshapes.has_ogr_support()

# create new commands and register them
registry.Add(Command('open_ogr_files', 'Open an ogr-file', open_with_ogr,
                     sensitive = _has_gdal_support,
                     helptext = 'Open a file supported from ogr'))

#registry.Add(Command('select_file_format', 'Select a file format',
#                     select_file_format,
#                     helptext = "Select a file format supported from ogr"))

registry.Add(Command('open_db', 'Open a layer from a database',
                     open_db,
                     sensitive = _has_dbconnections,
                     helptext = "Open a layer from a database, e.g. PostGIS"))

registry.Add(Command('open_OGRConnection',
                     ("Open a datasource with an OGRConnection string"),
                     open_OGRConnection,
                     sensitive = _has_gdal_support, helptext =
                     "Open a datasource with an OGRConnection string"))

# finally bind the new command with an entry in the extensions menu
ogr_menu.InsertItem("open_ogr_files")
#ogr_menu.InsertItem('select_file_format')
ogr_menu.InsertItem('open_db')
ogr_menu.InsertItem('open_OGRConnection')

# Add ogr menu to map menu
map_menu.InsertItem(ogr_menu, after = "rasterlayer_add")