view ide/project.py @ 8:edd70006d3e4

Started with MDI functions
author windel
date Fri, 21 Oct 2011 17:36:57 +0200
parents 2db4d2b362e6
children de004f808e56
line wrap: on
line source

"""
 Project that can be stored to and loaded from XML.
"""

from xml.sax import ContentHandler, make_parser
import xml.dom.minidom as md
import os.path

class ProjectContentHandler(ContentHandler):
   def __init__(self, project):
      self.project =  project
      self.inFiles = False
   def startElement(self, name, attrs):
      if name == 'Project':
         self.project.name = attrs['name']
      if name == 'Files':
         self.inFiles = True
      if name == 'File' and self.inFiles:
         self.project.files.append(attrs['Filename'])
   def endElement(self, name):
      if name == 'Files':
         self.inFiles = False

class Project:
   def __init__(self):
      self.name = ""
      self.files = []
      self.settings = {}
      self.filename = ""

   def save(self, filename):
      """ Save the project in XML format """
      # Create document:
      doc = md.Document()
      # Add project:
      project = doc.createElement("Project")
      project.setAttribute("name", self.name)
      doc.appendChild(project)

      # Add project files:
      filesNode = doc.createElement("Files")
      project.appendChild(filesNode)
      for f in self.files:
         fe = doc.createElement("File")
         fe.setAttribute("Filename", f)
         filesNode.appendChild(fe)

      # Write the XML file:
      xml = doc.toprettyxml()
      with open(filename, 'w') as f:
         f.write(xml)

   def load(self, filename):
      """ Load the project from the XML file """
      if not os.path.exists(filename):
         return
      self.filename = filename
      print(self.filename)
      parser = make_parser()
      handler = ProjectContentHandler(self)
      parser.setContentHandler(handler)
      parser.parse(filename)