/[thuban]/branches/WIP-pyshapelib-bramz/Extensions/importAPR/importAPR.py
ViewVC logotype

Annotation of /branches/WIP-pyshapelib-bramz/Extensions/importAPR/importAPR.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2402 - (hide annotations)
Sat Nov 20 12:55:01 2004 UTC (20 years, 3 months ago) by jan
Original Path: trunk/thuban/Extensions/importAPR/importAPR.py
File MIME type: text/x-python
File size: 10998 byte(s)
Removed registry entry (moved to __init__.py).

1 jan 2379 # Copyright (C) 2003, 2004 by Intevation GmbH
2 jan 1728 # Authors:
3 jan 2402 # Jan-Oliver Wagner <[email protected]> (2003, 2004)
4 jan 1728 #
5     # This program is free software under the GPL (>=v2)
6     # Read the file COPYING coming with Thuban for details.
7    
8     """
9     Import a ArcView project file (.apr) and convert it
10     to Thuban.
11     """
12    
13     __version__ = "$Revision$"
14 jan 2203 # $Source$
15     # $Id$
16 jan 1728
17     import os, sys
18    
19     from types import StringType
20    
21     from wxPython.wx import *
22    
23     from Thuban.Model.extension import Extension
24     from Thuban.Model.base import TitledObject, Modifiable
25     from Thuban.UI.command import registry, Command
26 jan 2203 from Thuban.UI.mainwindow import main_menu
27 jan 1728 from Thuban import _
28     from Thuban.Model.layer import Layer
29 jan 1884 from Thuban.Model.classification import ClassGroupRange, ClassGroupSingleton
30 jan 1728
31     from odb import ODBBaseObject
32 jan 1884 from apr import APR_LClass, APR_TClr, APR_BLnSym, APR_BMkSym, APR_BShSym
33 jan 1728
34     class ODBExtension(Extension):
35     def TreeInfo(self):
36     return (_("Extension: %s") % self.title,
37     [ object.TreeInfo() for object in self.objects ])
38    
39     class APR_FTheme(ODBBaseObject):
40     _obj_refs = [ 'Source', 'Legend' ]
41    
42     class APR_Legend(ODBBaseObject):
43     """Legend object.
44     There could one or more Class objects. Each class corresponds to a
45     Child in the Symbols.
46     """
47     _obj_refs = [ 'FieldNames', 'Symbols', 'Class', 'NullSym',
48     'NullValues', 'StatValues' ]
49    
50     class APR_Project(ODBBaseObject):
51     _obj_refs = [ 'Doc' ]
52    
53     class APR_ShpSrc(ODBBaseObject):
54     _obj_refs = [ 'Name' ]
55    
56     class APR_SrcName(ODBBaseObject):
57     _obj_refs = [ 'FileName' ]
58    
59     class APR_SymList(ODBBaseObject):
60     _obj_refs = [ 'Child' ]
61    
62     class APR_View(ODBBaseObject):
63 jan 1884 _obj_refs = [ 'Theme', 'ITheme' ]
64 jan 1728
65     class ODB(TitledObject, Modifiable):
66    
67     def __init__(self):
68     TitledObject.__init__(self, 'ODB Object')
69     self._objects = {}
70     self._version = None
71     self._filename = None
72     self.name = None # required for Thuban.model.extension.Extension
73    
74     def SetFileName(self, fname):
75     self._filename = fname
76     self.name = fname
77    
78     def AddObject(self, object):
79     self._objects[object.number] = object
80    
81     def GetObjects(self):
82     return self._objects
83    
84     def GetProject(self):
85     """Return the main Root if it is a Project, else None."""
86     # it is assumed that the first object is the ODB object
87     if self._objects[1].type != 'ODB':
88     return None
89     if self._objects[1].FirstRootClassName != 'Project':
90     return None
91    
92     # it is assumed that the second object is the first root
93     o = self._objects[2]
94     if o.type != 'Project':
95     return None
96     return o
97    
98     def TreeInfo(self):
99     items = []
100     items.append(_('Format version: %s') % self._version)
101     p = self.GetProject()
102     items.append(_('Project Name: %s') % p.Name)
103     for doc in p.Get('Doc'):
104     items.append(doc.TreeInfo())
105     return [_("ODB File '%s'" % self._filename), items]
106    
107     def parse_apr(fname):
108     """Load a ArcView project file.
109    
110     fname -- Filename of the .apr file
111    
112     Return: the ODB class object.
113     """
114     odb = ODB()
115     odb.SetFileName(fname)
116    
117     apr = open(fname, 'r').readlines()
118    
119     # get the version from the first line (eg. from "/3.1")
120     odb._version = apr.pop(0)[1:]
121    
122     i = 0
123     in_object = False
124     for line in apr:
125     i += 1
126     if line[0] == '(':
127     line = line[1:]
128     type, number = line.split('.')
129     number = int(number)
130     class_name = 'APR_' + type
131     try:
132     clazz = eval(class_name)
133     object = clazz(odb, type, number)
134     except:
135     object = ODBBaseObject(odb, type, number)
136     in_object = True
137     continue
138     if line[0] == ')':
139     in_object = False
140     odb.AddObject(object)
141     if in_object:
142     line = line.strip()
143     if len(line) == 0: continue
144     try:
145     property, value = line.split(':', 1)
146     property = property.strip()
147     value = value.strip()
148     except:
149     print "Error in line %d:" % i, line
150     continue
151     if value[0] == '"':
152     value = value[1:-1]
153     setattr(object, property, value)
154     return odb
155    
156     def import_apr_dialog(context):
157     """Request filename from user and run importing of apr file.
158    
159     context -- The Thuban context.
160     """
161     dlg = wxFileDialog(context.mainwindow,
162     _("Select APR file"), ".", "",
163     _("ArcView Project Files (*.apr)|*.apr|") +
164     _("All Files (*.*)|*.*"),
165     wxOPEN|wxOVERWRITE_PROMPT)
166     if dlg.ShowModal() == wxID_OK:
167     filename = dlg.GetPath()
168     dlg.Destroy()
169     else:
170     return
171    
172     odb = parse_apr(filename)
173     if odb is None:
174     context.mainwindow.RunMessageBox(_("Import APR"), _("Loading failed"))
175     return
176     else:
177     context.mainwindow.RunMessageBox(_("Import APR"),
178     _("%d objects loaded" %
179     len(odb.GetObjects().keys())))
180    
181     # find the views of the APR file
182     views = {}
183     p = odb.GetProject()
184     for doc in p.Get('Doc'):
185     if doc.type != 'View':
186     continue
187     views[doc.Name] = doc
188    
189     # it is possible that a APR file has no view at all
190     if len(views) == 0:
191     context.mainwindow.RunMessageBox(_("Import APR"),
192     _("No view found in APR file"))
193     return
194    
195     # let the user select one of the views
196     if len(views) > 1:
197     titles = views.keys()
198     dlg = wxSingleChoiceDialog(context.mainwindow,
199     _('Pick a View to import:'),
200     _('Import APR'), titles,
201     style = wxDEFAULT_DIALOG_STYLE |
202     wxRESIZE_BORDER)
203     if dlg.ShowModal() == wxID_OK:
204     view = views[views.keys()[dlg.GetSelection()]]
205     else:
206     return
207     else:
208     view = views[views.keys()[0]]
209    
210     # load the themes of the View as layers into Thuban
211     count_theme = 0
212     count_theme_fail = 0
213     for theme in view.Get('Theme'):
214     if theme.type != 'FTheme':
215     continue
216     count_theme += 1
217     filename = theme.Get('Source').Get('Name').Get('FileName').Path
218     try:
219     store = context.application.Session().OpenShapefile(filename)
220     except IOError:
221     # the layer couldn't be opened
222     context.mainwindow.RunMessageBox(_('Add Layer'),
223     _("Can't open the file '%s'.") % filename)
224     count_theme_fail += 1
225     else:
226     title = theme.Name
227     apr_legend = theme.Get('Legend')
228    
229     map = context.mainwindow.canvas.Map()
230    
231     # create layer
232     layer = Layer(title, store)
233    
234     # set the field for classification (if there is one in the apr)
235     if hasattr(apr_legend, 'FieldNames'):
236     apr_fieldname = apr_legend.Get('FieldNames').S
237     # unfortunately, the APR file does not store the actual
238     # Name of the column, but always makes the first character
239     # a capital letter, the rest lower case.
240     # Therefore, we have to search through the table of the
241     # layer to find out the correct spelling.
242     table_columns = layer.ShapeStore().Table().Columns()
243     for column in table_columns:
244     if apr_fieldname.lower() == column.name.lower():
245     layer.SetClassificationColumn(column.name)
246     break
247    
248     clazz = layer.GetClassification()
249     apr_classes = apr_legend.Get('Class')
250     if not isinstance(apr_classes, list):
251     apr_classes = [ apr_classes ]
252     apr_symbols = apr_legend.Get('Symbols').Get('Child')
253     if not isinstance(apr_symbols, list):
254     apr_symbols = [ apr_symbols ]
255     i = -1
256     for symbol in apr_symbols:
257     i += 1
258    
259     if hasattr(apr_classes[i], 'IsNoData'):
260     group = clazz.GetDefaultGroup()
261     group.SetLabel(apr_classes[i].Label)
262     continue
263    
264     # create a new group property from the symbol
265     prop = symbol.GetThubanProp()
266    
267 jan 1734 # build range
268     range = apr_classes[i].GetThubanRange()
269    
270     if isinstance(range, StringType):
271     new_group = ClassGroupSingleton(value = range,
272 jan 1728 props = prop,
273     label = apr_classes[i].GetLabel())
274     else:
275     new_group = ClassGroupRange(_range = range,
276     props = prop,
277     label = apr_classes[i].GetLabel())
278     clazz.AppendGroup(new_group)
279    
280     map.AddLayer(layer)
281    
282     map.SetTitle(view.Name)
283    
284     # fit the new map to the window
285     context.mainwindow.canvas.FitMapToWindow()
286    
287     context.mainwindow.RunMessageBox(_('Import APR'),
288     _('Imported %d out of %d themes of view "%s" ...') % \
289     (count_theme - count_theme_fail, count_theme, view.Name))
290    
291     # import_apr as an extension to Thuban
292     if context.session.HasExtensions():
293     for ext in context.session.Extensions():
294     if ext.Title() == apr_import_extension.Title():
295     ext.AddObject(odb)
296     return
297    
298     # no extension found, so lets make a new
299     context.session.AddExtension(apr_import_extension)
300     apr_import_extension.AddObject(odb)
301    
302     if __name__ == "__main__": # import_apr executed as a command line tool
303     if len(sys.argv) == 2:
304     odb = parse_apr(sys.argv[1])
305     print "%d objects loaded" % len(odb.GetObjects().keys())
306    
307     def print_structured_list(lst, indent = ''):
308     for item in lst:
309     if isinstance(item, StringType):
310     print indent + item
311     elif isinstance(item, list):
312     print_structured_list(item, indent + ' ')
313    
314     print_structured_list(odb.TreeInfo())
315     sys.exit(0)
316     else:
317     print 'usage: %s apr-file' % sys.argv[0]
318     sys.exit(1)
319    
320     apr_import_extension = ODBExtension('APR Import')
321    
322     # register the new command
323     registry.Add(Command('import-apr', _('Import apr-file...'), import_apr_dialog,
324     helptext = _('Import a ArcView project file')))
325    
326     # find the experimental menu (create it anew if not found)
327 jan 2203 experimental_menu = main_menu.FindOrInsertMenu('experimental',
328     _('Experimenta&l'))
329 jan 1728
330     # finally add the new entry to the experimental menu
331     experimental_menu.InsertItem('import-apr')

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26