/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Verbosio XML DTD Document Wrapper.
 *
 * The Initial Developer of the Original Code is
 * Alexander J. Vincent <ajvincent@gmail.com>.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// Utility function.
function ERROR_FAILURE() {
  throw Components.results.NS_ERROR_FAILURE;
}

// Utility function.
function NOT_IMPLEMENTED() {
  throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
}

// Utility function.
function ERROR_ABORT() {
  throw Components.results.NS_ERROR_ABORT;
}

// Utility function
function NOT_INITIALIZED() {
  throw Components.results.NS_ERROR_NOT_INITIALIZED;
}

// Utility function
function ALREADY_INITIALIZED() {
  throw Components.results.NS_ERROR_ALREADY_INITIALIZED;
}

const C_i = Components.interfaces;

const xeIDTDWrapper               = C_i.xeIDTDWrapper;
const xeITextDocumentWrapper      = C_i.xeITextDocumentWrapper;
const xeIDocumentWrapper          = C_i.xeIDocumentWrapper;
const xeIVirtualFile              = C_i.xeIVirtualFile;
const xeIDocumentFile             = C_i.xeIDocumentFile;
const xeIXMLDocumentWrapper       = C_i.xeIXMLDocumentWrapper;
const xeIBaseURIMap               = C_i.xeIBaseURIMap;
const mozIJSSubScriptLoader       = C_i.mozIJSSubScriptLoader;
const nsICategoryManager          = C_i.nsICategoryManager;
const nsIScriptError              = C_i.nsIScriptError;
const nsIProgrammingLanguage      = C_i.nsIProgrammingLanguage;
const nsISecurityCheckedComponent = C_i.nsISecurityCheckedComponent;
const nsIClassInfo                = C_i.nsIClassInfo;
const nsIComponentRegistrar       = C_i.nsIComponentRegistrar;
const nsIFactory                  = C_i.nsIFactory;
const nsIModule                   = C_i.nsIModule;
const nsISupports                 = C_i.nsISupports;

var Module = {
  factoriesByClassId: {},

  constructorsArray: [],

  /**
   * Add a component constructor to the module.
   *
   * @param aConstructor JavaScript function implementing nsIClassInfo
   */
  addConstructor: function addConstructor(aConstructor) {
    var cid = aConstructor.prototype.classID.toString();
    this.factoriesByClassId[cid] = {
      createInstance: function createInstance(outer, iid) {
        if (outer != null)
          throw Components.results.NS_ERROR_NO_AGGREGATION;
        return (new aConstructor()).QueryInterface(iid);
      }
    };

    this.constructorsArray[this.constructorsArray.length] = aConstructor;
  },

  categoriesArray: [],

  /**
   * Add a category for the category manager to accept at registration time.
   *
   * @param aCategory   The category to add.
   * @param aEntryName  The name of the entry.
   * @param aEntryValue The value of the entry (usually a component class id).
   */
  addCategory: function addCategory(aCategory, aEntryName, aEntryValue) {
    this.categoriesArray[this.categoriesArray.length] = {
      category: aCategory,
      name: aEntryName,
      value: aEntryValue
    };
  },

  // nsIModule
  registerSelf: function registerSelf(compMgr, fileSpec, location, type) {
    compReg = compMgr.QueryInterface(nsIComponentRegistrar);

    for (var i = 0; i < this.constructorsArray.length; i++) {
      var proto = this.constructorsArray[i].prototype;
      compReg.registerFactoryLocation(proto.classID,
                                      proto.classDescription,
                                      proto.contractID,
                                      fileSpec,
                                      location,
                                      type);
    }

    if (!this.categoriesArray.length) {
      return;
    }
    var catman = Components.classes["@mozilla.org/categorymanager;1"]
                           .getService(nsICategoryManager);
    for (i = 0; i < this.categoriesArray.length; i++) {
      var entry = this.categoriesArray[i];
      catman.addCategoryEntry(entry.category,
                              entry.name,
                              entry.value,
                              true,
                              true);
    }
  },

  // nsIModule
  getClassObject: function getClassObject(compMgr, aCID, aIID) {
    if (!aIID.equals(nsIFactory)) {
      throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
    }

    for (var prop in this.factoriesByClassId) {
      if (aCID.equals(Components.ID(prop))) {
        loadSubscripts();
        return this.factoriesByClassId[prop];
      }
    }
    throw Components.results.NS_ERROR_NO_INTERFACE;
  },

  // nsIModule
  canUnload: function canUnload() {
    return true;
  },

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(nsIModule) ||
       (aIID.equals(nsISupports)))
      return this;

    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

function NSGetModule(compMgr, fileSpec) {
  return Module;
}

var subscriptsLoaded = false;
var jsLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                         .getService(mozIJSSubScriptLoader);
jsLoader.loadSubScript("resource://app/res/ecma-debug.js");

function loadSubscripts() {
  if (subscriptsLoaded) {
    return;
  }
  jsLoader.loadSubScript("chrome://jslib/content/jslib.js");
  jsLoader.loadSubScript("chrome://jslib/content/io/io.js");
  subscriptsLoaded = true;
}

function DTDParser() {
}
DTDParser.prototype = {
  /**
   * Load a new DTD wrapper from an external source.
   *
   * @param aPath The URI to the DTD.
   */
  loadNewDTDWrapper: function loadNewDTDWrapper(aPath) {
    assert(!(aPath in this._externalDTDWrappers), "Who called this?");
    var wrapper;
    var localPath;

    // Check our base URI map first for an equivalent base URI.
    var types = this._baseURIMap.getURITypes({});
    var baseURI = null;
    for (var i = 0; i < types.length; i++) {
      var uriType = types[i];
      var baseURIPath = this._baseURIMap.getURI(uriType);
      if (aPath.indexOf(baseURIPath) == 0) {
        baseURI = this._baseURIMap;
        break;
      }
    }

    if (!baseURI) {
      // Now check all base URI's in the document pack.
      baseURI = this._ownerDocumentPack.getBaseURI(aPath);
    }

    // A chrome://global/locale/ DTD probably won't have a base URI.
    if (!baseURI && ((aPath.indexOf("chrome://global/") == 0) ||
          (aPath.indexOf("chrome://toolkit/") == 0))) {
      return;
    }

    // Build and add the wrapper if it's not in the pack.
    if (!this._ownerDocumentPack.hasWrapper(aPath)) {
      assert(baseURI instanceof xeIBaseURIMap, "Crack smoking!");
      localPath = baseURI.getPrimaryLocalURI(aPath);
      wrapper = new DTDDocumentWrapper();
      wrapper.initializeByFile(localPath, this._ownerDocumentPack);

      this._ownerDocumentPack.addWrapper(wrapper);
    } else {
      wrapper = this._ownerDocumentPack.getWrapper(aPath);
      assert(wrapper instanceof xeIDTDWrapper, "Not a DTD wrapper?");
      assert(wrapper instanceof xeIDocumentWrapper, "Not a document wrapper?");
    }

    this._externalDTDWrappers[aPath] = wrapper;
  },


  noMinusOnes: function noMinusOnes(aNum) {
    return (aNum == -1) ? Infinity : aNum;
  },

  /**
   * Parse an entity and add it to the internal entity map.
   *
   * @param aSource The source code behind the entity.
   */
  parseEntity: function parseEntity(aSource) {
    assert(aSource.indexOf("<!ENTITY") == 0, "Who called this?");
    var singleQuoteIndex = this.noMinusOnes(aSource.indexOf("'"));
    var doubleQuoteIndex = this.noMinusOnes(aSource.indexOf('"'));
    var quoteIndex       = Math.min(singleQuoteIndex, doubleQuoteIndex);
    var quoteChar        = (quoteIndex == singleQuoteIndex) ? "'" : '"';

    var percentIndex     = this.noMinusOnes(aSource.indexOf("%"));
    const entityMap = (percentIndex < quoteIndex) ?
                      this._externalDTDReferences :
                      this._internalEntityNames;
    var sourceCode = "";
    if (percentIndex < quoteIndex) {
      assert(percentIndex >= 9, "Where's the percent character?");
      sourceCode = aSource.substr(percentIndex + 1);
    } else {
      sourceCode = aSource.substr(9) // ("<!ENTITY ").length
    }

    // Find the entity name.
    const noWS = /\S/;
    sourceCode = sourceCode.substr(sourceCode.indexOf(noWS.exec(sourceCode)));
    var spaceIndex = sourceCode.indexOf(/\s/.exec(sourceCode));
    var entityName = sourceCode.substr(0, spaceIndex);
    assert(entityName != "%", "Expected entity name: " + sourceCode.substr(2));
    sourceCode = sourceCode.substr(sourceCode.indexOf(quoteChar) + 1);

    // Find the entity value.
    var entityValue = sourceCode.substr(0, sourceCode.indexOf(quoteChar));
    sourceCode = sourceCode.substr(sourceCode.indexOf(quoteChar) + 1);

    // Close by checking the next character is ">".
    var closeEntityChar = noWS.exec(sourceCode);
    assert(closeEntityChar == ">", "Expected '>', got '" + closeEntityChar + "'");
    entityMap[entityName] = entityValue;
    return entityValue;
  },

  // xeIDTDWrapper
  parseDTD: function parseDTD(aSource, aDocWrapper, aDocPack) {
    try {
      assert(aSource, "No source code?");
      assert((aDocWrapper == this) ||
             (aDocWrapper instanceof xeIXMLDocumentWrapper),
             "Not a DTD or XML document wrapper?");
      assert(aDocPack, "No document pack?");
    } catch (e) {
      dump(e.stack + "\n");
      throw e;
    }

    // xeIDTDWrapper
    this.baseWrapper = aDocWrapper;

    this._externalDTDWrappers = {};
    this._externalDTDReferences = {};
    this._internalEntityNames = {};

    if (!this._baseURIMap) {
      this._baseURIMap = aDocWrapper.baseURIMap;
    } else {
      assert(this._baseURIMap == aDocWrapper.baseURIMap, "Who called this?");
    }
    if (!this._ownerDocumentPack) {
      this._ownerDocumentPack = aDocPack;
    } else {
      assert(this._ownerDocumentPack == aDocPack, "Who called this?");
    }
    /* We can't assert the document wrapper is in the pack yet; the wrapper is
       probably still in its initialization phase.
    */

    const noWS = /\S/;
    var sourceCode = aSource;
    var charIndex = sourceCode.indexOf(noWS.exec(sourceCode));
    var semicolonIndex = -1;
    while (charIndex != -1) {
      switch (sourceCode.charAt(charIndex)) {
        case "%":
          semicolonIndex = sourceCode.indexOf(";");
          entityName = sourceCode.substring(charIndex + 1, semicolonIndex);
          if (entityName in this._externalDTDReferences) {
            var path = this._externalDTDReferences[entityName];
            assert(path, "No path?");
            if (!(path in this._externalDTDWrappers)) {
              this.loadNewDTDWrapper(path);
            }
          } else {
            // Not an assertion; we need this entity.
            throw new Error(entityName + " not defined!");
          }
          sourceCode = sourceCode.substr(semicolonIndex + 1);
          break;

        case "<":
          sourceCode = sourceCode.substr(charIndex);
          if (sourceCode.indexOf("<!--") == 0) {
            // Comment.  Skip forward to the end of the comment.
            sourceCode = sourceCode.substr(sourceCode.indexOf("-->") + 3);
            break;
          }
          else if (sourceCode.indexOf("<!ENTITY") == 0) {
            var entityValue = this.parseEntity(sourceCode);
            charIndex =  sourceCode.indexOf(entityValue) + entityValue.length;
            sourceCode = sourceCode.substr(charIndex);
            sourceCode = sourceCode.substr(sourceCode.indexOf(">") + 1);
            break;
          }
          // Fall through to error for anything else.
        default:
          dump("'" + sourceCode.substr(0, 40) + "'\n");
          dump(aDocWrapper.pathToDocument + "\n");
          try {
            throw new Error("Unsupported content in DTD");
          } catch (e) {
            dump("\n\n" + e.stack + "\n\n");
            throw e;
          }
      }
      charIndex = sourceCode.indexOf(noWS.exec(sourceCode));
    }

    this._dtdSource = aSource;
    this._isInitialized = true;
  },

  checkInitialized: function checkInitialized() {
    if (!this._isInitialized) {
      dumpJSStack();
      NOT_INITIALIZED();
    }
  },

  checkNotInitialized: function checkNotInitialized() {
    if (this._isInitialized) {
      dumpJSStack();
      ALREADY_INITIALIZED();
    }
  },

  // xeIDTDWrapper
  getExternalDTDReferences: function getExternalDTDReferences(aCount) {
    var values = [];
    for (var prop in this._externalDTDReferences) {
      values[values.length] = prop;
    }
    aCount.value = values.length;
    return values;
  },

  // xeIDTDWrapper
  getExternalDTDWrappers: function getExternalDTDWrappers(aCount) {
    this.checkInitialized();
    var values = [];
    for each (var wrapper in this._externalDTDWrappers) {
      assert(wrapper instanceof xeIDTDWrapper ||
             wrapper instanceof DTDDocumentWrapper,
             "wrapper: " + wrapper.toSource());
      values[values.length] = wrapper;
    }
    aCount.value = values.length;
    return values;
  },

  // xeIDTDWrapper
  getInternalEntityNames: function getInternalEntityNames(aCount) {
    this.checkInitialized();
    var values = [];
    for (var prop in this._internalEntityNames) {
      values[values.length] = prop;
    }
    aCount.value = values.length;
    return values;
  },

  // xeIDTDWrapper
  getDTDRefValue: function getDTDRefValue(aName) {
    return (aName in this._externalDTDReferences) ?
           this._externalDTDReferences[aName] :
           null;
  },

  // xeIDTDWrapper
  getEntityValue: function getEntityValue(aName) {
    this.checkInitialized();
    return (aName in this._internalEntityNames) ?
           this._internalEntityNames[aName] :
           null;
  },

  // xeIDTDWrapper
  setEntityValue: function setEntityValue(aName, aValue) {
    this.checkInitialized();

    // Build a regexp to find the entity declaration.
    var name = aName;
    name.replace(/\\/, "\\\\");
    name.replace(/\./, "\\.");
    const entityRE = new RegExp("<!ENTITY\\s+" + name + "\\s+[\\'\\\"]");

    // Find the last entity declaration in the DTD (it will have preference).
    var matches = entityRE.exec(this._dtdSource);
    assert(matches != null, "Missed.");
    var largestIndex = -1;
    var selection = "";
    var source = this._dtdSource;
    for (var i = 0; i < matches.length; i++) {
      var index = source.lastIndexOf(matches[i]);
      if (index > largestIndex) {
        largestIndex = index;
        selection = matches[i];
      }
    }
    assert(largestIndex > -1, "Missed.");

    // Find the boundaries to splice the value in.
    var quote = selection.charAt(selection.length - 1);
    var lastQuoteIndex = source.indexOf(quote,
                                        largestIndex + selection.length);

    // Insert the new value.
    // XXX ajvincent This doesn't escape characters!
    var part1 = source.substr(0, largestIndex + selection.length);
    var part3 = source.substr(lastQuoteIndex);
    this._dtdSource = part1 + aValue + part3;
    this.acceptNewSource();

    this._internalEntityNames[aName] = aValue;
  }
}

function DTDDocumentWrapper() {
  loadSubscripts();

  this._docFileObj            = null;
  this._ownerDocumentPack     = null;
  this._externalDTDWrappers   = {};
  this._externalDTDReferences = {};
  this._internalEntityNames   = {};

  // xeIDTDWrapper
  this.baseWrapper = null;

  // xeITextDocumentWrapper
  this.selectionStartIndex = 0;

  // xeITextDocumentWrapper
  this.selectionEndIndex = 0;

  // xeIDocumentWrapper
  this._baseURIMap = null;

  // xeIDocumentWrapper
  this._pathToDocument = null;

  // xeIDocumentWrapper
  this.descendantIndexes = {};

  this._isInitialized = false;
}
DTDDocumentWrapper.prototype = {
  addProperties: function addProperties(aObject) {
    for (var prop in aObject) {
      this[prop] = aObject[prop];
    }
  },

  /**
   * Accept the new source code for the DTD.
   *
   * @param aSource New value to accept.
   */
  acceptNewSource: function acceptNewSource() {
    this.checkInitialized();
    this._docFileObj.contents = this._dtdSource;
  },

  // xeITextDocumentWrapper
  reparseSource: function reparseSource(aSource) {
    this.checkInitialized();
    this._parseDTD(aSource, this, this._ownerDocumentPack);
    this._docFileObj.contents = aSource;
  },

  // xeIDocumentWrapper
  get rootLanguageType() {
    return "DTD";
  },

  // xeIDocumentWrapper
  get baseURIMap() {
    this.checkInitialized();
    return this._baseURIMap;
  },

  // xeIDocumentWrapper
  get pathToDocument() {
    this.checkInitialized();
    return this._pathToDocument;
  },

  // xeIDocumentWrapper
  get pendingAction() {
    this.checkInitialized();
    return this._pendingAction;
  },

  // xeIDocumentWrapper
  set pendingAction(aPendingAction) {
    this.checkInitialized();
    /* XXX ajvincent When this document is part of a document pack, the
     * pending action will have an ownerWrapper property that isn't this.
     */
    this._pendingAction = aPendingAction;
  },

  // xeIDocumentWrapper
  get txlistener() {
    this.checkInitialized();
    return null;
  },

  // xeIDocumentWrapper
  get defaultViewerID() {
    this.checkInitialized();
    return "source-edit@viewers.verbosio.mozdev.org";
  },

  // xeIDocumentWrapper
  get preconditionLocalId() {
    this.checkInitialized();
    return null;
  },

  /**
   * Initialize the wrapper by a global chrome path.
   *
   * @param aPath    Chrome path to fetch.
   * @param aDocPack Document pack owning this wrapper.
   */
  initializeByChromePath: function initializeByChromePath(aPath, aDocPack) {
    this.checkNotInitialized();
    var file = new ChromeFile(aPath);
    if (!file.exists()) {
      throw new Error("You called for a chrome file that doesn't exist!");
    }
    file.open();
    var dtdSource = file.read();
    file.close();

    this._ownerDocumentPack = aDocPack;
    this._docFileObj = {}; // XXX ajvincent This needs better handling.
    // Okay, we need to make a new base URI map.
    this._baseURIMap = Components.classes["@verbosio.mozdev.org/base-uri-map;1"]
                                 .createInstance(xeIBaseURIMap);
    var chromeRE = /^chrome:\/\/[^\/]*\/[^\/]*\//;
    var chromePath = aPath.match(chromeRE);
    this._baseURIMap.addType("chrome", chromePath);
    this._pathToDocument = aPath.substr(chromePath.length);

    this._isInitialized = true;
    try {
      this.parseDTD(dtdSource, this, aDocPack);
    } catch (e) {
      dump("\n\n" + e.stack + "\n\n");
      this._isInitialized = false;
      throw e;
    }
  },

  // xeIDocumentWrapper
  initializeByPrecondition: function initBy(aPrecondition) {
    this.checkNotInitialized();
    NOT_IMPLEMENTED();

    this._isInitialized = true;
  },

  // xeIDocumentWrapper
  initializeByFile: function initializeByFile(aLocalPath, aDocPack) {
    this.checkNotInitialized();
    assert(aLocalPath, "No local path?");
    assert(aDocPack, "No document pack?");

    var docFileClass = "@verbosio.mozdev.org/document-file;1?contentType=";
    var docFileObj = Components.classes[docFileClass + "text/plain"]
                               .createInstance(xeIDocumentFile);
    docFileObj.init(aLocalPath, "text/plain");
    docFileObj.read();

    this._docFileObj = docFileObj;

    // Verify the file is a proper DTD (no syntax errors!)
    /* XXX ajvincent We'll deal with this later.
    var languageClass = "@verbosio.mozdev.org/language-pack-service;1";
    languageClass += "?contentType=application/xml-dtd";
    var checker;
    if (languageClass in Components.classes) {
      checker = Components.classes[languageClass]
                          .getService(xeILanguagePackService);
      assert(checker, "No DTD language pack?");
    }
     */

    this._baseURIMap = aDocPack.getBaseURI(aLocalPath);
    var localBase = this._baseURIMap.getURI("local");
    assert(aLocalPath.indexOf(localBase) == 0, "Local base URI didn't match?");
    assert(aLocalPath.length > localBase.length, "Local base URI is too long!");
    this._pathToDocument = aLocalPath.substr(localBase.length);

    // xeIDocumentWrapper
    this.descendantIndexes = {};
    this._ownerDocumentPack = aDocPack;

    this._isInitialized = true;
    try {
      this.parseDTD(docFileObj.contents, this, aDocPack);
    } catch (e) {
      this._isInitialized = false;
      throw e;
    }
  },

  // xeIDocumentWrapper
  save: function save(aLocalPath) {
    this.checkInitialized();
    var docFileObj = null;
    if (aLocalPath) {
      var docFileClass = "@verbosio.mozdev.org/document-file;1?contentType=";
      docFileObj = Components.classes[docFileClass + "text/plain"]
                             .createInstance(xeIDocumentFile);
      docFileObj.init(aLocalPath, "text/plain");
      docFileObj.contents = this.contents;
    } else {
      docFileObj = this._docFileObj;
    }

    docFileObj.write(docFileObj.contents);
    this._docFileObj = docFileObj;
  },

  // xeIVirtualFile
  get wrappedSource() {
    return (this._docFileObj) ? this._docFileObj.contents : "";
  },

  // xeIVirtualFile
  get contentType() {
    this.checkInitialized();
    return "text/plain";
  },

  // xeIVirtualFile
  get publicURI() {
    this.checkInitialized();
    return (this._docFileObj) ? this._docFileObj.location : null;
  },

  // nsIClassInfo
  getInterfaces: function getInterfaces(aCount) {
    var interfaces = [xeIDTDWrapper,
                      xeITextDocumentWrapper,
                      xeIDocumentWrapper,
                      xeIVirtualFile,
                      nsIClassInfo];
    aCount.value = interfaces.length;
    return interfaces;
  },

  // nsIClassInfo
  getHelperForLanguage: function getHelperForLanguage(aLanguage) {
    return null;
  },

  // nsIClassInfo
  classDescription: "XML DTD Document Wrapper",
  /* "Verbosio Document File" */

  // nsIClassInfo
  classID: Components.ID("{a9196441-963e-41d7-aa75-46b488ae0097}"),

  // nsIClassInfo
  contractID: "@verbosio.mozdev.org/document-wrappers/xml-dtd;1",

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: 0, /* nsIClassInfo.SINGLETON for services */

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(nsISupports))
      return this;

    var interfaces = this.getInterfaces({});
    for each (iface in interfaces) {
      if (aIID.equals(iface)) {
        return this;
      }
    }

    // Known interfaces we don't support
    if (aIID.equals(nsISecurityCheckedComponent) ||
        aIID.equals(xeIXMLDocumentWrapper)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
      return null;
    }

    // Discover what interfaces we need
    var i = Components.interfaces;
    var found = false;
    for (var prop in i) {
      if (aIID.equals(i[prop])) {
        found = true;
        dump("QUERYINTERFACE: DTDDocumentWrapper " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE: DTDDocumentWrapper Unknown\n");
    }
    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
}

DTDDocumentWrapper.prototype.addProperties(DTDParser.prototype);
DTDDocumentWrapper.prototype._parseDTD = DTDParser.prototype.parseDTD;
// xeIDTDWrapper
DTDDocumentWrapper.prototype.parseDTD = DTDDocumentWrapper.prototype.reparseSource;

Module.addConstructor(DTDDocumentWrapper);
Module.addCategory("Verbosio document wrappers by file type",
                   "dtd",
                   DTDDocumentWrapper.prototype.contractID);

function DTDSubsetWrapper()
{
  loadSubscripts();
  this._externalDTDWrappers   = {};
  this._externalDTDReferences = {};
  this._internalEntityNames   = {};
  this._isInitialized = false;
  this._ownerDocumentPack = null;

  // xeIDTDWrapper
  this.baseWrapper = null;
}
DTDSubsetWrapper.prototype =
{
  addProperties: function addProperties(aObject) {
    for (var prop in aObject) {
      this[prop] = aObject[prop];
    }
  },

  /**
   * Accept the new source code for the DTD.
   *
   * @param aSource New value to accept.
   */
  acceptNewSource: function acceptNewSource() {
    this.checkInitialized();
    assert(this.baseWrapper instanceof xeIXMLDocumentWrapper,
           "Not a XML document wrapper?");
    this.baseWrapper.documentType = this._dtdSource;
  },

  // nsIClassInfo
  getInterfaces: function getInterfaces(aCount) {
    var interfaces = [xeIDTDWrapper,
                      nsIClassInfo];
    aCount.value = interfaces.length;
    return interfaces;
  },

  // nsIClassInfo
  getHelperForLanguage: function getHelperForLanguage(aLanguage) {
    return null;
  },

  // nsIClassInfo
  classDescription: "Verbosio DTD Subset Wrapper",

  // nsIClassInfo
  classID: Components.ID("4b6c4b48-9e38-4303-8c71-0ddf8350ff15"),

  // nsIClassInfo
  contractID: "@verbosio.mozdev.org/dtd-subset-wrapper/gecko;1",

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: 0,

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(xeIDTDWrapper) ||
        aIID.equals(nsIClassInfo) ||
        aIID.equals(nsISupports))
      return this;

    // Known interfaces we don't support
    if (aIID.equals(nsISecurityCheckedComponent)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
      return null;
    }

    // Discover what interfaces we need
    var i = Components.interfaces;
    var found = false;
    for (var prop in i) {
      if (aIID.equals(i[prop])) {
        found = true;
        dump("QUERYINTERFACE: DTDSubsetWrapper " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE: DTDSubsetWrapper Unknown\n");
    }
    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

DTDSubsetWrapper.prototype.addProperties(DTDParser.prototype);
Module.addConstructor(DTDSubsetWrapper);
