view applications/ide/project.py @ 59:f6ea630c4057

Cleanup
author windel
date Tue, 24 Apr 2012 08:01:55 +0200
parents 600f48b74799
children
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 ProjectFile:
   def __init__(self, filename):
      self.filename = filename

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

      if not isnew:
         """ Load the project from the XML file """
         parser = make_parser()
         handler = ProjectContentHandler(self)
         parser.setContentHandler(handler)
         parser.parse(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 loadProjectFile(self, filename):
      basedir = os.path.dirname(self.filename)
      filename = os.path.join(basedir, filename)
      with open(filename, 'r') as f:
         src = f.read()
      return src