/[thuban]/branches/WIP-pyshapelib-bramz/Thuban/Model/save.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Thuban/Model/save.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1417 by bh, Tue Jul 15 08:43:53 2003 UTC revision 2551 by jonathan, Thu Jan 27 14:19:41 2005 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001, 2002, 2003 by Intevation GmbH  # Copyright (c) 2001-2004 by Intevation GmbH
2  # Authors:  # Authors:
3  # Jan-Oliver Wagner <[email protected]>  # Jan-Oliver Wagner <[email protected]> (2004)
4  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]> (2001-2004)
5  # Jonathan Coles <[email protected]>  # Jonathan Coles <[email protected]> (2003)
6    # Frank Koormann <[email protected]> (2003)
7  #  #
8  # This program is free software under the GPL (>=v2)  # This program is free software under the GPL (>=v2)
9  # Read the file COPYING coming with Thuban for details.  # Read the file COPYING coming with Thuban for details.
# Line 12  Functions to save a session to a file Line 13  Functions to save a session to a file
13  """  """
14    
15  __version__ = "$Revision$"  __version__ = "$Revision$"
16    # $Source$
17    # $Id$
18    
19  import os  import os
20    
# Line 23  from Thuban.Model.classification import Line 26  from Thuban.Model.classification import
26      ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap      ClassGroupDefault, ClassGroupSingleton, ClassGroupRange, ClassGroupMap
27  from Thuban.Model.transientdb import AutoTransientTable, TransientJoinedTable  from Thuban.Model.transientdb import AutoTransientTable, TransientJoinedTable
28  from Thuban.Model.table import DBFTable, FIELDTYPE_STRING  from Thuban.Model.table import DBFTable, FIELDTYPE_STRING
29  from Thuban.Model.data import DerivedShapeStore, ShapefileStore  from Thuban.Model.data import DerivedShapeStore, ShapefileStore, \
30                                  SHAPETYPE_POINT
31    
32  from Thuban.Model.xmlwriter import XMLWriter  from Thuban.Model.xmlwriter import XMLWriter
33    from postgisdb import PostGISConnection, PostGISShapeStore
34    
35  def relative_filename(dir, filename):  def relative_filename(dir, filename):
36      """Return a filename relative to dir for the absolute file name absname.      """Return a filename relative to dir for the absolute file name absname.
# Line 40  def relative_filename(dir, filename): Line 45  def relative_filename(dir, filename):
45          return filename          return filename
46    
47    
48    def unify_filename(filename):
49        """Return a 'unified' version of filename
50    
51        The .thuban files should be as platform independent as possible.
52        Since they must contain filenames the filenames have to unified. We
53        unify on unix-like filenames for now, which means we do nothing on a
54        posix system and simply replace backslashes with slashes on windows
55        """
56        if os.name == "posix":
57            return filename
58        elif os.name == "nt":
59            return "/".join(filename.split("\\"))
60        else:
61            raise RuntimeError("Unsupported platform for unify_filename: %s"
62                               % os.name)
63    
64  def sort_data_stores(stores):  def sort_data_stores(stores):
65      """Return a topologically sorted version of the sequence of data containers      """Return a topologically sorted version of the sequence of data containers
66    
# Line 69  def sort_data_stores(stores): Line 90  def sort_data_stores(stores):
90              processed[id(container)] = 1              processed[id(container)] = 1
91      return result      return result
92    
93    def bool2str(b):
94        if b: return "true"
95        else: return "false"
96    
97  class SessionSaver(XMLWriter):  class SessionSaver(XMLWriter):
98    
# Line 102  class SessionSaver(XMLWriter): Line 126  class SessionSaver(XMLWriter):
126      def has_id(self, obj):      def has_id(self, obj):
127          return self.idmap.has_key(id(obj))          return self.idmap.has_key(id(obj))
128    
129        def prepare_filename(self, filename):
130            """Return the string to use when writing filename to the thuban file
131    
132            The returned string is a unified version (only slashes as
133            directory separators, see unify_filename) of filename expressed
134            relative to the directory the .thuban file is written to.
135            """
136            return unify_filename(relative_filename(self.dir, filename))
137    
138      def write(self, file_or_filename):      def write(self, file_or_filename):
139          XMLWriter.write(self, file_or_filename)          XMLWriter.write(self, file_or_filename)
140    
141          self.write_header("session", "thuban-0.9.dtd")          self.write_header("session", "thuban-1.1.dtd")
142          self.write_session(self.session)          self.write_session(self.session)
143          self.close()          self.close()
144    
# Line 132  class SessionSaver(XMLWriter): Line 165  class SessionSaver(XMLWriter):
165              attrs["xmlns:" + name] = uri              attrs["xmlns:" + name] = uri
166          # default name space          # default name space
167          attrs["xmlns"] = \          attrs["xmlns"] = \
168                 "http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"                 "http://thuban.intevation.org/dtds/thuban-1.1-dev.dtd"
169          self.open_element("session", attrs)          self.open_element("session", attrs)
170            self.write_db_connections(session)
171          self.write_data_containers(session)          self.write_data_containers(session)
172          for map in session.Maps():          for map in session.Maps():
173              self.write_map(map)              self.write_map(map)
174          self.close_element("session")          self.close_element("session")
175    
176        def write_db_connections(self, session):
177            for conn in session.DBConnections():
178                if isinstance(conn, PostGISConnection):
179                    self.write_element("dbconnection",
180                                       {"id": self.define_id(conn),
181                                        "dbtype": "postgis",
182                                        "host": conn.host,
183                                        "port": conn.port,
184                                        "user": conn.user,
185                                        "dbname": conn.dbname})
186                else:
187                    raise ValueError("Can't handle db connection %r" % conn)
188    
189      def write_data_containers(self, session):      def write_data_containers(self, session):
190          containers = sort_data_stores(session.DataContainers())          containers = sort_data_stores(session.DataContainers())
191          for container in containers:          for container in containers:
# Line 156  class SessionSaver(XMLWriter): Line 203  class SessionSaver(XMLWriter):
203              idvalue = self.define_id(container)              idvalue = self.define_id(container)
204              if isinstance(container, ShapefileStore):              if isinstance(container, ShapefileStore):
205                  self.define_id(container.Table(), idvalue)                  self.define_id(container.Table(), idvalue)
206                  filename = relative_filename(self.dir, container.FileName())                  filename = self.prepare_filename(container.FileName())
207                  self.write_element("fileshapesource",                  self.write_element("fileshapesource",
208                                     {"id": idvalue, "filename": filename,                                     {"id": idvalue, "filename": filename,
209                                      "filetype": "shapefile"})                                      "filetype": "shapefile"})
# Line 166  class SessionSaver(XMLWriter): Line 213  class SessionSaver(XMLWriter):
213                                     {"id": idvalue,                                     {"id": idvalue,
214                                      "shapesource": self.get_id(shapesource),                                      "shapesource": self.get_id(shapesource),
215                                      "table": self.get_id(table)})                                      "table": self.get_id(table)})
216                elif isinstance(container, PostGISShapeStore):
217                    conn = container.DBConnection()
218                    self.write_element("dbshapesource",
219                                       {"id": idvalue,
220                                        "dbconn": self.get_id(conn),
221                                        "tablename": container.TableName(),
222                                        "id_column": container.IDColumn().name,
223                                        "geometry_column":
224                                          container.GeometryColumn().name,
225                                        })
226              elif isinstance(container, DBFTable):              elif isinstance(container, DBFTable):
227                  filename = relative_filename(self.dir, container.FileName())                  filename = self.prepare_filename(container.FileName())
228                  self.write_element("filetable",                  self.write_element("filetable",
229                                     {"id": idvalue,                                     {"id": idvalue,
230                                      "title": container.Title(),                                      "title": container.Title(),
# Line 208  class SessionSaver(XMLWriter): Line 265  class SessionSaver(XMLWriter):
265          """Write the projection.          """Write the projection.
266          """          """
267          if projection and len(projection.params) > 0:          if projection and len(projection.params) > 0:
268              self.open_element("projection", {"name": projection.GetName()})              attrs = {"name": projection.GetName()}
269                epsg = projection.EPSGCode()
270                if epsg is not None:
271                    attrs["epsg"] = epsg
272                self.open_element("projection", attrs)
273              for param in projection.params:              for param in projection.params:
274                  self.write_element('parameter value="%s"' %                  self.write_element('parameter value="%s"' %
275                                     self.encode(param))                                     self.encode(param))
# Line 226  class SessionSaver(XMLWriter): Line 287  class SessionSaver(XMLWriter):
287              attrs = {}              attrs = {}
288    
289          attrs["title"]   = layer.title          attrs["title"]   = layer.title
290          attrs["visible"] = ("false", "true")[int(layer.Visible())]          attrs["visible"] = bool2str(layer.Visible())
291    
292          if isinstance(layer, Layer):          if isinstance(layer, Layer):
293              attrs["shapestore"]   = self.get_id(layer.ShapeStore())              attrs["shapestore"]   = self.get_id(layer.ShapeStore())
# Line 241  class SessionSaver(XMLWriter): Line 302  class SessionSaver(XMLWriter):
302              self.write_classification(layer)              self.write_classification(layer)
303              self.close_element("layer")              self.close_element("layer")
304          elif isinstance(layer, RasterLayer):          elif isinstance(layer, RasterLayer):
305              attrs["filename"] = relative_filename(self.dir, layer.filename)              attrs["filename"] = self.prepare_filename(layer.filename)
306                if layer.UseMask():
307                    attrs["use_mask"] = "true"
308    
309              self.open_element("rasterlayer", attrs)              self.open_element("rasterlayer", attrs)
310              self.write_projection(layer.GetProjection())              self.write_projection(layer.GetProjection())
311              self.close_element("rasterlayer")              self.close_element("rasterlayer")
# Line 254  class SessionSaver(XMLWriter): Line 318  class SessionSaver(XMLWriter):
318    
319          lc = layer.GetClassification()          lc = layer.GetClassification()
320    
321          field = lc.GetField()          field = layer.GetClassificationColumn()
322    
323          #          #
324          # there isn't a classification of anything so do nothing          # there isn't a classification of anything so do nothing
325          #          #
326          if field is None: return          if field is None: return
327    
328          attrs["field"] = field          attrs["field"] = field
329          attrs["field_type"] = str(lc.GetFieldType())          attrs["field_type"] = str(layer.GetFieldType(field))
330          self.open_element("classification", attrs)          self.open_element("classification", attrs)
331    
332          for g in lc:          for g in lc:
# Line 270  class SessionSaver(XMLWriter): Line 334  class SessionSaver(XMLWriter):
334                  open_el  = 'clnull label="%s"' % self.encode(g.GetLabel())                  open_el  = 'clnull label="%s"' % self.encode(g.GetLabel())
335                  close_el = 'clnull'                  close_el = 'clnull'
336              elif isinstance(g, ClassGroupSingleton):              elif isinstance(g, ClassGroupSingleton):
337                  if lc.GetFieldType() == FIELDTYPE_STRING:                  if layer.GetFieldType(field) == FIELDTYPE_STRING:
338                      value = self.encode(g.GetValue())                      value = self.encode(g.GetValue())
339                  else:                  else:
340                      value = str(g.GetValue())                      value = str(g.GetValue())
# Line 290  class SessionSaver(XMLWriter): Line 354  class SessionSaver(XMLWriter):
354                      'stroke_width': str(data.GetLineWidth()),                      'stroke_width': str(data.GetLineWidth()),
355                      'fill'        : data.GetFill().hex()}                      'fill'        : data.GetFill().hex()}
356    
357                # only for point layers write the size attribute
358                if layer.ShapeType() == SHAPETYPE_POINT:
359                    dict['size'] =  str(data.GetSize())
360    
361              self.open_element(open_el)              self.open_element(open_el)
362              self.write_element("cldata", dict)              self.write_element("cldata", dict)
363              self.close_element(close_el)              self.close_element(close_el)

Legend:
Removed from v.1417  
changed lines
  Added in v.2551

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26