<commit_before>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang diagnostics tables.
//
//===----------------------------------------------------------------------===//

#include "ClangDiagnosticsEmitter.h"
#include "llvm/TableGen/Record.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/VectorExtras.h"
#include <map>
#include <algorithm>
#include <functional>
using namespace llvm;

//===----------------------------------------------------------------------===//
// Diagnostic category computation code.
//===----------------------------------------------------------------------===//

namespace {
class DiagGroupParentMap {
  RecordKeeper &Records;
  std::map<const Record*, std::vector<Record*> > Mapping;
public:
  DiagGroupParentMap(RecordKeeper &records) : Records(records) {
    std::vector<Record*> DiagGroups
      = Records.getAllDerivedDefinitions("DiagGroup");
    for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
      std::vector<Record*> SubGroups =
        DiagGroups[i]->getValueAsListOfDefs("SubGroups");
      for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
        Mapping[SubGroups[j]].push_back(DiagGroups[i]);
    }
  }

  const std::vector<Record*> &getParents(const Record *Group) {
    return Mapping[Group];
  }
};
} // end anonymous namespace.

static std::string
getCategoryFromDiagGroup(const Record *Group,
                         DiagGroupParentMap &DiagGroupParents) {
  // If the DiagGroup has a category, return it.
  std::string CatName = Group->getValueAsString("CategoryName");
  if (!CatName.empty()) return CatName;

  // The diag group may the subgroup of one or more other diagnostic groups,
  // check these for a category as well.
  const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  for (unsigned i = 0, e = Parents.size(); i != e; ++i) {
    CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);
    if (!CatName.empty()) return CatName;
  }
  return "";
}

/// getDiagnosticCategory - Return the category that the specified diagnostic
/// lives in.
static std::string getDiagnosticCategory(const Record *R,
                                         DiagGroupParentMap &DiagGroupParents) {
  // If the diagnostic is in a group, and that group has a category, use it.
  if (DefInit *Group = dynamic_cast<DefInit*>(R->getValueInit("Group"))) {
    // Check the diagnostic's diag group for a category.
    std::string CatName = getCategoryFromDiagGroup(Group->getDef(),
                                                   DiagGroupParents);
    if (!CatName.empty()) return CatName;
  }

  // If the diagnostic itself has a category, get it.
  return R->getValueAsString("CategoryName");
}

namespace {
  class DiagCategoryIDMap {
    RecordKeeper &Records;
    StringMap<unsigned> CategoryIDs;
    std::vector<std::string> CategoryStrings;
  public:
    DiagCategoryIDMap(RecordKeeper &records) : Records(records) {
      DiagGroupParentMap ParentInfo(Records);

      // The zero'th category is "".
      CategoryStrings.push_back("");
      CategoryIDs[""] = 0;

      std::vector<Record*> Diags =
      Records.getAllDerivedDefinitions("Diagnostic");
      for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
        std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);
        if (Category.empty()) continue;  // Skip diags with no category.

        unsigned &ID = CategoryIDs[Category];
        if (ID != 0) continue;  // Already seen.

        ID = CategoryStrings.size();
        CategoryStrings.push_back(Category);
      }
    }

    unsigned getID(StringRef CategoryString) {
      return CategoryIDs[CategoryString];
    }

    typedef std::vector<std::string>::iterator iterator;
    iterator begin() { return CategoryStrings.begin(); }
    iterator end() { return CategoryStrings.end(); }
  };
} // end anonymous namespace.

//===----------------------------------------------------------------------===//
// Warning Tables (.inc file) generation.
//===----------------------------------------------------------------------===//

void ClangDiagsDefsEmitter::run(raw_ostream &OS) {
  // Write the #if guard
  if (!Component.empty()) {
    std::string ComponentName = StringRef(Component).upper();
    OS << "#ifdef " << ComponentName << "START\n";
    OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
       << ",\n";
    OS << "#undef " << ComponentName << "START\n";
    OS << "#endif\n\n";
  }

  const std::vector<Record*> &Diags =
    Records.getAllDerivedDefinitions("Diagnostic");

  DiagCategoryIDMap CategoryIDs(Records);
  DiagGroupParentMap DGParentMap(Records);

  for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
    const Record &R = *Diags[i];
    // Filter by component.
    if (!Component.empty() && Component != R.getValueAsString("Component"))
      continue;

    OS << "DIAG(" << R.getName() << ", ";
    OS << R.getValueAsDef("Class")->getName();
    OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();

    // Description string.
    OS << ", \"";
    OS.write_escaped(R.getValueAsString("Text")) << '"';

    // Warning associated with the diagnostic.
    if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) {
      OS << ", \"";
      OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"';
    } else {
      OS << ", \"\"";
    }

    // SFINAE bit
    if (R.getValueAsBit("SFINAE"))
      OS << ", true";
    else
      OS << ", false";

    // Access control bit
    if (R.getValueAsBit("AccessControl"))
      OS << ", true";
    else
      OS << ", false";

    // FIXME: This condition is just to avoid temporary revlock, it can be
    // removed.
    if (R.getValue("WarningNoWerror")) {
      // Default warning has no Werror bit.
      if (R.getValueAsBit("WarningNoWerror"))
        OS << ", true";
      else
        OS << ", false";

      // Default warning show in system header bit.
      if (R.getValueAsBit("WarningShowInSystemHeader"))
        OS << ", true";
      else
        OS << ", false";
    }

    // Category number.
    OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));

    // Brief
    OS << ", \"";
    OS.write_escaped(R.getValueAsString("Brief")) << '"';

    // Explanation
    OS << ", \"";
    OS.write_escaped(R.getValueAsString("Explanation")) << '"';
    OS << ")\n";
  }
}

//===----------------------------------------------------------------------===//
// Warning Group Tables generation
//===----------------------------------------------------------------------===//

static std::string getDiagCategoryEnum(llvm::StringRef name) {
  if (name.empty())
    return "DiagCat_None";
  llvm::SmallString<256> enumName = llvm::StringRef("DiagCat_");
  for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)
    enumName += isalnum(*I) ? *I : '_';
  return enumName.str();
}

namespace {
struct GroupInfo {
  std::vector<const Record*> DiagsInGroup;
  std::vector<std::string> SubGroups;
  unsigned IDNo;
};
} // end anonymous namespace.

void ClangDiagGroupsEmitter::run(raw_ostream &OS) {
  // Compute a mapping from a DiagGroup to all of its parents.
  DiagGroupParentMap DGParentMap(Records);

  // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of
  // groups to diags in the group.
  std::map<std::string, GroupInfo> DiagsInGroup;

  std::vector<Record*> Diags =
    Records.getAllDerivedDefinitions("Diagnostic");
  for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
    const Record *R = Diags[i];
    DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"));
    if (DI == 0) continue;
    std::string GroupName = DI->getDef()->getValueAsString("GroupName");
    DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
  }

  // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
  // groups (these are warnings that GCC supports that clang never produces).
  std::vector<Record*> DiagGroups
    = Records.getAllDerivedDefinitions("DiagGroup");
  for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
    Record *Group = DiagGroups[i];
    GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];

    std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
    for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
      GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
  }

  // Assign unique ID numbers to the groups.
  unsigned IDNo = 0;
  for (std::map<std::string, GroupInfo>::iterator
       I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
    I->second.IDNo = IDNo;

  // Walk through the groups emitting an array for each diagnostic of the diags
  // that are mapped to.
  OS << "\n#ifdef GET_DIAG_ARRAYS\n";
  unsigned MaxLen = 0;
  for (std::map<std::string, GroupInfo>::iterator
       I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
    MaxLen = std::max(MaxLen, (unsigned)I->first.size());

    std::vector<const Record*> &V = I->second.DiagsInGroup;
    if (!V.empty()) {
      OS << "static const short DiagArray" << I->second.IDNo << "[] = { ";
      for (unsigned i = 0, e = V.size(); i != e; ++i)
        OS << "diag::" << V[i]->getName() << ", ";
      OS << "-1 };\n";
    }

    const std::vector<std::string> &SubGroups = I->second.SubGroups;
    if (!SubGroups.empty()) {
      OS << "static const short DiagSubGroup" << I->second.IDNo << "[] = { ";
      for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {
        std::map<std::string, GroupInfo>::iterator RI =
          DiagsInGroup.find(SubGroups[i]);
        assert(RI != DiagsInGroup.end() && "Referenced without existing?");
        OS << RI->second.IDNo << ", ";
      }
      OS << "-1 };\n";
    }
  }
  OS << "#endif // GET_DIAG_ARRAYS\n\n";

  // Emit the table now.
  OS << "\n#ifdef GET_DIAG_TABLE\n";
  for (std::map<std::string, GroupInfo>::iterator
       I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
    // Group option string.
    OS << "  { ";
    OS << I->first.size() << ", ";
    OS << "\"";
    if (I->first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
                                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                   "0123456789!@#$%^*-+=:?")!=std::string::npos)
      throw "Invalid character in diagnostic group '" + I->first + "'";
    OS.write_escaped(I->first) << "\","
                               << std::string(MaxLen-I->first.size()+1, ' ');

    // Diagnostics in the group.
    if (I->second.DiagsInGroup.empty())
      OS << "0, ";
    else
      OS << "DiagArray" << I->second.IDNo << ", ";

    // Subgroups.
    if (I->second.SubGroups.empty())
      OS << 0;
    else
      OS << "DiagSubGroup" << I->second.IDNo;
    OS << " },\n";
  }
  OS << "#endif // GET_DIAG_TABLE\n\n";

  // Emit the category table next.
  DiagCategoryIDMap CategoriesByID(Records);
  OS << "\n#ifdef GET_CATEGORY_TABLE\n";
  for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(),
       E = CategoriesByID.end(); I != E; ++I)
    OS << "CATEGORY(\"" << *I << "\", " << getDiagCategoryEnum(*I) << ")\n";
  OS << "#endif // GET_CATEGORY_TABLE\n\n";
}

//===----------------------------------------------------------------------===//
// Diagnostic name index generation
//===----------------------------------------------------------------------===//

namespace {
struct RecordIndexElement
{
  RecordIndexElement() {}
  explicit RecordIndexElement(Record const &R):
    Name(R.getName()) {}

  std::string Name;
};

struct RecordIndexElementSorter :
  public std::binary_function<RecordIndexElement, RecordIndexElement, bool> {

  bool operator()(RecordIndexElement const &Lhs,
                  RecordIndexElement const &Rhs) const {
    return Lhs.Name < Rhs.Name;
  }

};

} // end anonymous namespace.

void ClangDiagsIndexNameEmitter::run(raw_ostream &OS) {
  const std::vector<Record*> &Diags =
    Records.getAllDerivedDefinitions("Diagnostic");

  std::vector<RecordIndexElement> Index;
  Index.reserve(Diags.size());
  for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
    const Record &R = *(Diags[i]);
    Index.push_back(RecordIndexElement(R));
  }

  std::sort(Index.begin(), Index.end(), RecordIndexElementSorter());

  for (unsigned i = 0, e = Index.size(); i != e; ++i) {
    const RecordIndexElement &R = Index[i];

    OS << "DIAG_NAME_INDEX(" << R.Name << ")\n";
  }
}
<commit_msg>Remove unused include of VectorExtras.h.<commit_after>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang diagnostics tables.
//
//===----------------------------------------------------------------------===//

#include "ClangDiagnosticsEmitter.h"
#include "llvm/TableGen/Record.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/SmallString.h"
#include <map>
#include <algorithm>
#include <functional>
using namespace llvm;

//===----------------------------------------------------------------------===//
// Diagnostic category computation code.
//===----------------------------------------------------------------------===//

namespace {
class DiagGroupParentMap {
  RecordKeeper &Records;
  std::map<const Record*, std::vector<Record*> > Mapping;
public:
  DiagGroupParentMap(RecordKeeper &records) : Records(records) {
    std::vector<Record*> DiagGroups
      = Records.getAllDerivedDefinitions("DiagGroup");
    for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
      std::vector<Record*> SubGroups =
        DiagGroups[i]->getValueAsListOfDefs("SubGroups");
      for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
        Mapping[SubGroups[j]].push_back(DiagGroups[i]);
    }
  }

  const std::vector<Record*> &getParents(const Record *Group) {
    return Mapping[Group];
  }
};
} // end anonymous namespace.

static std::string
getCategoryFromDiagGroup(const Record *Group,
                         DiagGroupParentMap &DiagGroupParents) {
  // If the DiagGroup has a category, return it.
  std::string CatName = Group->getValueAsString("CategoryName");
  if (!CatName.empty()) return CatName;

  // The diag group may the subgroup of one or more other diagnostic groups,
  // check these for a category as well.
  const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  for (unsigned i = 0, e = Parents.size(); i != e; ++i) {
    CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);
    if (!CatName.empty()) return CatName;
  }
  return "";
}

/// getDiagnosticCategory - Return the category that the specified diagnostic
/// lives in.
static std::string getDiagnosticCategory(const Record *R,
                                         DiagGroupParentMap &DiagGroupParents) {
  // If the diagnostic is in a group, and that group has a category, use it.
  if (DefInit *Group = dynamic_cast<DefInit*>(R->getValueInit("Group"))) {
    // Check the diagnostic's diag group for a category.
    std::string CatName = getCategoryFromDiagGroup(Group->getDef(),
                                                   DiagGroupParents);
    if (!CatName.empty()) return CatName;
  }

  // If the diagnostic itself has a category, get it.
  return R->getValueAsString("CategoryName");
}

namespace {
  class DiagCategoryIDMap {
    RecordKeeper &Records;
    StringMap<unsigned> CategoryIDs;
    std::vector<std::string> CategoryStrings;
  public:
    DiagCategoryIDMap(RecordKeeper &records) : Records(records) {
      DiagGroupParentMap ParentInfo(Records);

      // The zero'th category is "".
      CategoryStrings.push_back("");
      CategoryIDs[""] = 0;

      std::vector<Record*> Diags =
      Records.getAllDerivedDefinitions("Diagnostic");
      for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
        std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);
        if (Category.empty()) continue;  // Skip diags with no category.

        unsigned &ID = CategoryIDs[Category];
        if (ID != 0) continue;  // Already seen.

        ID = CategoryStrings.size();
        CategoryStrings.push_back(Category);
      }
    }

    unsigned getID(StringRef CategoryString) {
      return CategoryIDs[CategoryString];
    }

    typedef std::vector<std::string>::iterator iterator;
    iterator begin() { return CategoryStrings.begin(); }
    iterator end() { return CategoryStrings.end(); }
  };
} // end anonymous namespace.

//===----------------------------------------------------------------------===//
// Warning Tables (.inc file) generation.
//===----------------------------------------------------------------------===//

void ClangDiagsDefsEmitter::run(raw_ostream &OS) {
  // Write the #if guard
  if (!Component.empty()) {
    std::string ComponentName = StringRef(Component).upper();
    OS << "#ifdef " << ComponentName << "START\n";
    OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
       << ",\n";
    OS << "#undef " << ComponentName << "START\n";
    OS << "#endif\n\n";
  }

  const std::vector<Record*> &Diags =
    Records.getAllDerivedDefinitions("Diagnostic");

  DiagCategoryIDMap CategoryIDs(Records);
  DiagGroupParentMap DGParentMap(Records);

  for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
    const Record &R = *Diags[i];
    // Filter by component.
    if (!Component.empty() && Component != R.getValueAsString("Component"))
      continue;

    OS << "DIAG(" << R.getName() << ", ";
    OS << R.getValueAsDef("Class")->getName();
    OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();

    // Description string.
    OS << ", \"";
    OS.write_escaped(R.getValueAsString("Text")) << '"';

    // Warning associated with the diagnostic.
    if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) {
      OS << ", \"";
      OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"';
    } else {
      OS << ", \"\"";
    }

    // SFINAE bit
    if (R.getValueAsBit("SFINAE"))
      OS << ", true";
    else
      OS << ", false";

    // Access control bit
    if (R.getValueAsBit("AccessControl"))
      OS << ", true";
    else
      OS << ", false";

    // FIXME: This condition is just to avoid temporary revlock, it can be
    // removed.
    if (R.getValue("WarningNoWerror")) {
      // Default warning has no Werror bit.
      if (R.getValueAsBit("WarningNoWerror"))
        OS << ", true";
      else
        OS << ", false";

      // Default warning show in system header bit.
      if (R.getValueAsBit("WarningShowInSystemHeader"))
        OS << ", true";
      else
        OS << ", false";
    }

    // Category number.
    OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));

    // Brief
    OS << ", \"";
    OS.write_escaped(R.getValueAsString("Brief")) << '"';

    // Explanation
    OS << ", \"";
    OS.write_escaped(R.getValueAsString("Explanation")) << '"';
    OS << ")\n";
  }
}

//===----------------------------------------------------------------------===//
// Warning Group Tables generation
//===----------------------------------------------------------------------===//

static std::string getDiagCategoryEnum(llvm::StringRef name) {
  if (name.empty())
    return "DiagCat_None";
  llvm::SmallString<256> enumName = llvm::StringRef("DiagCat_");
  for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)
    enumName += isalnum(*I) ? *I : '_';
  return enumName.str();
}

namespace {
struct GroupInfo {
  std::vector<const Record*> DiagsInGroup;
  std::vector<std::string> SubGroups;
  unsigned IDNo;
};
} // end anonymous namespace.

void ClangDiagGroupsEmitter::run(raw_ostream &OS) {
  // Compute a mapping from a DiagGroup to all of its parents.
  DiagGroupParentMap DGParentMap(Records);

  // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of
  // groups to diags in the group.
  std::map<std::string, GroupInfo> DiagsInGroup;

  std::vector<Record*> Diags =
    Records.getAllDerivedDefinitions("Diagnostic");
  for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
    const Record *R = Diags[i];
    DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"));
    if (DI == 0) continue;
    std::string GroupName = DI->getDef()->getValueAsString("GroupName");
    DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
  }

  // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
  // groups (these are warnings that GCC supports that clang never produces).
  std::vector<Record*> DiagGroups
    = Records.getAllDerivedDefinitions("DiagGroup");
  for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
    Record *Group = DiagGroups[i];
    GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];

    std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
    for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
      GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
  }

  // Assign unique ID numbers to the groups.
  unsigned IDNo = 0;
  for (std::map<std::string, GroupInfo>::iterator
       I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
    I->second.IDNo = IDNo;

  // Walk through the groups emitting an array for each diagnostic of the diags
  // that are mapped to.
  OS << "\n#ifdef GET_DIAG_ARRAYS\n";
  unsigned MaxLen = 0;
  for (std::map<std::string, GroupInfo>::iterator
       I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
    MaxLen = std::max(MaxLen, (unsigned)I->first.size());

    std::vector<const Record*> &V = I->second.DiagsInGroup;
    if (!V.empty()) {
      OS << "static const short DiagArray" << I->second.IDNo << "[] = { ";
      for (unsigned i = 0, e = V.size(); i != e; ++i)
        OS << "diag::" << V[i]->getName() << ", ";
      OS << "-1 };\n";
    }

    const std::vector<std::string> &SubGroups = I->second.SubGroups;
    if (!SubGroups.empty()) {
      OS << "static const short DiagSubGroup" << I->second.IDNo << "[] = { ";
      for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {
        std::map<std::string, GroupInfo>::iterator RI =
          DiagsInGroup.find(SubGroups[i]);
        assert(RI != DiagsInGroup.end() && "Referenced without existing?");
        OS << RI->second.IDNo << ", ";
      }
      OS << "-1 };\n";
    }
  }
  OS << "#endif // GET_DIAG_ARRAYS\n\n";

  // Emit the table now.
  OS << "\n#ifdef GET_DIAG_TABLE\n";
  for (std::map<std::string, GroupInfo>::iterator
       I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
    // Group option string.
    OS << "  { ";
    OS << I->first.size() << ", ";
    OS << "\"";
    if (I->first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
                                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                   "0123456789!@#$%^*-+=:?")!=std::string::npos)
      throw "Invalid character in diagnostic group '" + I->first + "'";
    OS.write_escaped(I->first) << "\","
                               << std::string(MaxLen-I->first.size()+1, ' ');

    // Diagnostics in the group.
    if (I->second.DiagsInGroup.empty())
      OS << "0, ";
    else
      OS << "DiagArray" << I->second.IDNo << ", ";

    // Subgroups.
    if (I->second.SubGroups.empty())
      OS << 0;
    else
      OS << "DiagSubGroup" << I->second.IDNo;
    OS << " },\n";
  }
  OS << "#endif // GET_DIAG_TABLE\n\n";

  // Emit the category table next.
  DiagCategoryIDMap CategoriesByID(Records);
  OS << "\n#ifdef GET_CATEGORY_TABLE\n";
  for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(),
       E = CategoriesByID.end(); I != E; ++I)
    OS << "CATEGORY(\"" << *I << "\", " << getDiagCategoryEnum(*I) << ")\n";
  OS << "#endif // GET_CATEGORY_TABLE\n\n";
}

//===----------------------------------------------------------------------===//
// Diagnostic name index generation
//===----------------------------------------------------------------------===//

namespace {
struct RecordIndexElement
{
  RecordIndexElement() {}
  explicit RecordIndexElement(Record const &R):
    Name(R.getName()) {}

  std::string Name;
};

struct RecordIndexElementSorter :
  public std::binary_function<RecordIndexElement, RecordIndexElement, bool> {

  bool operator()(RecordIndexElement const &Lhs,
                  RecordIndexElement const &Rhs) const {
    return Lhs.Name < Rhs.Name;
  }

};

} // end anonymous namespace.

void ClangDiagsIndexNameEmitter::run(raw_ostream &OS) {
  const std::vector<Record*> &Diags =
    Records.getAllDerivedDefinitions("Diagnostic");

  std::vector<RecordIndexElement> Index;
  Index.reserve(Diags.size());
  for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
    const Record &R = *(Diags[i]);
    Index.push_back(RecordIndexElement(R));
  }

  std::sort(Index.begin(), Index.end(), RecordIndexElementSorter());

  for (unsigned i = 0, e = Index.size(); i != e; ++i) {
    const RecordIndexElement &R = Index[i];

    OS << "DIAG_NAME_INDEX(" << R.Name << ")\n";
  }
}
<|endoftext|>


<commit_before>#include "mugen/storyboard.h"

#include "util/bitmap.h"
#include "init.h"
#include "resource.h"
#include "util/funcs.h"
#include "globals.h"
#include "factory/font_render.h"

#include "mugen_animation.h"
#include "mugen/background.h"
#include "mugen_sound.h"
#include "mugen_reader.h"
#include "mugen_sprite.h"
#include "mugen_util.h"
#include "mugen_font.h"

#include "util/timedifference.h"
#include "ast/all.h"
#include "parser/all.h"
#include "input/input-map.h"
#include "input/input-manager.h"

namespace PaintownUtil = ::Util;

using namespace std;
using namespace Mugen;

static const int DEFAULT_WIDTH = 320;
static const int DEFAULT_HEIGHT = 240;
static const int DEFAULT_SCREEN_X_AXIS = 160;
static const int DEFAULT_SCREEN_Y_AXIS = 0;

Layer::Layer():
startTime(0),
enabled(false),
animation(0){
}

Layer::~Layer(){
}

void Layer::act(int currentTime){
    if (startTime >= currentTime && !enabled){
        enabled = true;
    }
    if (enabled){
        animation->logic();
    }
}

void Layer::render(int x, int y, const Bitmap &bmp){
    if (enabled){
        animation->render(x + offset.x, y + offset.y, bmp);
    }
}

void Layer::reset(){
    enabled = false;
    animation->reset();
}

Scene::Scene(Ast::Section * data, const std::string & file, Ast::AstParse & parsed, SpriteMap & sprites):
clearColor(-2),
ticker(0),
endTime(0),
background(0),
layers(9){
    class SceneWalker: public Ast::Walker {
	public:
	    SceneWalker(Scene & scene, const std::string & file, SpriteMap & sprites, Ast::AstParse & parse):
	    scene(scene),
	    file(file),
	    sprites(sprites),
	    parsed(parsed){
	    }
	    ~SceneWalker(){
	    }

	    Scene & scene;
	    const std::string & file;
	    SpriteMap & sprites;
	    Ast::AstParse & parsed;

	    virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
		if (simple == "fadein.time"){
		    int time;
		    simple >> time;
		    scene.fader.setFadeInTime(time);
		} else if (simple == "fadein.col"){
		    int r=0,g=0,b=0;
		    try{
			simple >> r >> g >> b;
		    } catch (const Ast::Exception & e){
		    }
		    scene.fader.setFadeInColor(Bitmap::makeColor(r,g,b));
		} else if (simple == "fadeout.time"){
		    int time;
		    simple >> time;
		    scene.fader.setFadeOutTime(time);
		} else if (simple == "fadeout.col"){
		    int r=0,g=0,b=0;
		    try {
			simple >> r >> g >> b;
		    } catch (const Ast::Exception & e){
		    }
		    scene.fader.setFadeOutColor(Bitmap::makeColor(r,g,b));
		} else if (simple == "bg.name"){
		    std::string name;
		    simple >> name;
		    scene.background = new Background(file,name);
		} else if (simple == "clearcolor"){
		    int r=0,g=0,b=0;
		    try {
			simple >> r >> g >> b;
		    } catch (const Ast::Exception & e){
		    }
		    scene.clearColor = (r == -1 ? r : Bitmap::makeColor(r,g,b));
		} else if (simple == "end.time"){
		    simple >> scene.endTime;
		} else if (simple == "layerall.pos"){
		    try{
			simple >> scene.defaultPosition.x;
			simple >> scene.defaultPosition.y;
		    } catch (const Ast::Exception & e){
		    }
		} else if (PaintownUtil::matchRegex(simple.idString(), "layer[0-9]\\.anim")){
		    std::string action = PaintownUtil::captureRegex(simple.idString(), "layer([0-9])\\.anim", 0);
		    int num = atoi(action.c_str());
		    if (num >= 0 && num < 10){
			Layer *layer = scene.layers[num];
			Ast::Section * section = parsed.findSection("begin action " + action);
			layer->setAnimation(Util::getAnimation(section,sprites));
		    }
		} else if (PaintownUtil::matchRegex(simple.idString(), "layer[0-9]\\.offset")){
		    int num = atoi(PaintownUtil::captureRegex(simple.idString(), "layer([0-9])\\.offset", 0).c_str());
		    if (num >= 0 && num < 10){
			int x=0,y=0;
			try{
			    simple >> x >> y;
			} catch (Ast::Exception & e){
			}
			Layer *layer = scene.layers[num];
			layer->setOffset(x,y);
		    }
		} else if (PaintownUtil::matchRegex(simple.idString(), "layer[0-9]\\.starttime")){
		    int num = atoi(PaintownUtil::captureRegex(simple.idString(), "layer([0-9])\\.starttime", 0).c_str());
		    if (num >= 0 && num < 10){
			int time;
			simple >> time;
			Layer *layer = scene.layers[num];
			layer->setStartTime(time);
		    }
		} else if (simple == "bgm"){
		    // do nothing
		} else if (simple == "bgm.loop"){
		    // do nothing
		} else {
			Global::debug(0) << "Unhandled option in Scene Section: " << simple.toString();
		}
	    }
    };

    SceneWalker walker(*this,file,sprites,parsed);
    data->walk(walker);

    // set initial fade state
    fader.setState(FADEIN);
}

Scene::~Scene(){

    if (background){
        delete background;
    }

    // layers
    for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
        if ((*i))delete (*i);
    }
}

void Scene::act(){
    // backgrounds
    if (background){
        background->act();
    }
    // layers
    for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
        Layer *layer = *i;
        layer->act(ticker);
    }
    // Fader
    fader.act();
    if (ticker == endTime - fader.getFadeOutTime()){
        fader.setState(FADEOUT);
    }
    // tick tick
    ticker++;
}
void Scene::render(const Bitmap & bmp){
    if (clearColor != -1 && clearColor != -2){
        bmp.fill(clearColor);
    }
    // backgrounds
    if (background){
        background->renderBackground(0,0, bmp);
    }
    // layers
    for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
        Layer *layer = *i;
        layer->render(defaultPosition.x,defaultPosition.y,bmp);
    }
    // foregrounds
    if (background){
        background->renderForeground(0,0, bmp);
    }
    // fader
    fader.draw(bmp);
}

bool Scene::isDone(){
    return (ticker >= endTime);
}

void Scene::reset(){
    ticker = 0;
    fader.setState(FADEIN);
    // layers
    for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
	Layer *layer = *i;
	layer->reset();
    }
}

Storyboard::Storyboard( const string & s )throw (MugenException):
storyBoardFile(s),
startscene(0){
    // Lets look for our def since some people think that all file systems are case insensitive
    std::string baseDir = Util::getFileDir(storyBoardFile);
    const std::string ourDefFile = Util::fixFileName( baseDir, Util::stripDir(storyBoardFile) );
    // get real basedir
    //baseDir = Util::getFileDir( ourDefFile );
    Global::debug(1) << baseDir << endl;

    if (ourDefFile.empty()){
        throw MugenException("Cannot locate storyboard definition file for: " + storyBoardFile);
    }

    std::string filesdir = "";

    Global::debug(1) << "Got subdir: " << filesdir << endl;

    TimeDifference diff;
    diff.startTime();
    Ast::AstParse parsed((list<Ast::Section*>*) Def::main(ourDefFile));
    diff.endTime();
    Global::debug(1) << "Parsed mugen file " + ourDefFile + " in" + diff.printTime("") << endl;

    /* set by bg.name = "foo" */
    string bgname;

    for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){
        Ast::Section * section = *section_it;
	std::string head = section->getName();

	head = Util::fixCase(head);

        if (head == "info"){
            class InfoWalk: public Ast::Walker{
            public:
                virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
                    if (simple == "name"){
                        string name;
                        simple >> name;
                        Global::debug(1) << "Read name '" << name << "'" << endl;
                    } else if (simple == "author"){
                        string name;
                        simple >> name;
                        Global::debug(1) << "Made by: '" << name << "'" << endl;
                    } else {
                        Global::debug(0) << "Warning: ignored attribute: " << simple.toString() << endl;
                    }
                }
            };

            InfoWalk walk;
            section->walk(walk);

        } else if (head == "scenedef"){
            class SceneWalk: public Ast::Walker{
            public:
                SceneWalk(const string & baseDir, Storyboard & board):
                    baseDir(baseDir),
                    board(board){
                }

                const string & baseDir;
                Storyboard & board;

                virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
                    if (simple == "spr"){
			std::string temp;
                        simple >> temp;
                        Util::readSprites(Util::getCorrectFileLocation(this->baseDir, temp), "", board.sprites);
                    } else if (simple == "startscene"){
                        simple >> board.startscene;
                        Global::debug(1) << "Starting storyboard at: '" << board.startscene << "'" << endl;
                    } else {
                        Global::debug(0) << "Warning: ignored attribute: " << simple.toString() << endl;
                    }
                }
            };

            SceneWalk walk(baseDir, *this);
            section->walk(walk);
        } else if (PaintownUtil::matchRegex(head, "^scene")){
	    Scene *scene = new Scene(section,ourDefFile,parsed,sprites);
	    scenes.push_back(scene);
	}
    }
}

Storyboard::~Storyboard(){
    // Get rid of animation lists;
    for( std::map< int, MugenAnimation * >::iterator i = animations.begin() ; i != animations.end() ; ++i ){
        if( i->second )delete i->second;
    }

    // Get rid of scene lists;
    for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){
        if( (*i) )delete (*i);
    }
    // sprites
    for( SpriteMap::iterator i = sprites.begin() ; i != sprites.end() ; ++i ){
        for( std::map< unsigned int, MugenSprite * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){
            if( j->second )delete j->second;
        }
    }
}

void Storyboard::run(const Bitmap &bmp, bool repeat){
    double gameSpeed = 1.0;
    double runCounter = 0;
    bool quit = false;

    Bitmap work( 320, 240 );

    for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){
        if( (*i) ){
            (*i)->reset();
        }
    }

    std::vector< Scene * >::iterator sceneIterator = scenes.begin() + startscene;

    while( !quit ){
        bool draw = false;

        Scene *scene = *sceneIterator;
        if ( Global::speed_counter > 0 ){

            runCounter += Global::speed_counter * gameSpeed * Global::LOGIC_MULTIPLIER;//(double) 90 / (double) 60;
            while (runCounter > 1){
                runCounter -= 1;
                draw = true;
                // Key handler
		InputManager::poll();

                InputMap<CharacterKeys>::Output out = InputManager::getMap(input);

                if (out[Up]){
	        }
	        if (out[Down]){
	        }
	        if (out[Left]){
	        }
	        if (out[Right]){
	        }
	        if (out[A]){
                    quit = true;
                    return;
	        }
	        if (out[B]){
                    quit = true;
                    return;
	        }
	        if (out[C]){
                    quit = true;
                    return;
	        }
	        if (out[X]){
                    quit = true;
                    return;
	        }
	        if (out[Y]){
                    quit = true;
                    return;
	        }
	        if (out[Z]){
                    quit = true;
                    return;
	        }
	        if (out[Start]){
                    quit = true;
                    return;
	        }
                scene->act();

                if (scene->isDone()){
                    sceneIterator++;
                    if (sceneIterator == scenes.end()){
                        if (repeat){
                            sceneIterator = scenes.begin();
                        } else {
                            return;
                        }
                    }
                    scene = *sceneIterator;
                    scene->reset();
                }
            }
            Global::speed_counter = 0;
        }

        if (draw){
            scene->render(work);
            work.Stretch(bmp);
            if (Global::getDebug() > 0){
                Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor(0,255,128), bmp, "Scene: Time(%i) : EndTime(%i) : Fade in(%i) : Fade out(%i)",0, scene->getTicker(),scene->getEndTime(),scene->getFadeTool().getFadeInTime(),scene->getFadeTool().getFadeOutTime() );
            }
            bmp.BlitToScreen();
        }

        while (Global::speed_counter == 0){
            PaintownUtil::rest(1);
        }
    }
}

<commit_msg>Fixed unitialized layers.<commit_after>#include "mugen/storyboard.h"

#include "util/bitmap.h"
#include "init.h"
#include "resource.h"
#include "util/funcs.h"
#include "globals.h"
#include "factory/font_render.h"

#include "mugen_animation.h"
#include "mugen/background.h"
#include "mugen_sound.h"
#include "mugen_reader.h"
#include "mugen_sprite.h"
#include "mugen_util.h"
#include "mugen_font.h"

#include "util/timedifference.h"
#include "ast/all.h"
#include "parser/all.h"
#include "input/input-map.h"
#include "input/input-manager.h"

namespace PaintownUtil = ::Util;

using namespace std;
using namespace Mugen;

static const int DEFAULT_WIDTH = 320;
static const int DEFAULT_HEIGHT = 240;
static const int DEFAULT_SCREEN_X_AXIS = 160;
static const int DEFAULT_SCREEN_Y_AXIS = 0;

Layer::Layer():
startTime(0),
enabled(false),
animation(0){
}

Layer::~Layer(){
}

void Layer::act(int currentTime){
    if (startTime >= currentTime && !enabled){
        enabled = true;
    }
    if (enabled && animation){
        animation->logic();
    }
}

void Layer::render(int x, int y, const Bitmap &bmp){
    if (enabled && animation){
        animation->render(x + offset.x, y + offset.y, bmp);
    }
}

void Layer::reset(){
    enabled = false;
    if (animation){
	animation->reset();
    }
}

Scene::Scene(Ast::Section * data, const std::string & file, Ast::AstParse & parsed, SpriteMap & sprites):
clearColor(-2),
ticker(0),
endTime(0),
background(0){
    for (int i = 0; i < 10; ++i){
	Layer *layer = new Layer();
	layers.push_back(layer);
    }
    class SceneWalker: public Ast::Walker {
	public:
	    SceneWalker(Scene & scene, const std::string & file, SpriteMap & sprites, Ast::AstParse & parse):
	    scene(scene),
	    file(file),
	    sprites(sprites),
	    parsed(parse){
	    }
	    ~SceneWalker(){
	    }

	    Scene & scene;
	    const std::string & file;
	    SpriteMap & sprites;
	    Ast::AstParse & parsed;

	    virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
		if (simple == "fadein.time"){
		    int time;
		    simple >> time;
		    scene.fader.setFadeInTime(time);
		} else if (simple == "fadein.col"){
		    int r=0,g=0,b=0;
		    try{
			simple >> r >> g >> b;
		    } catch (const Ast::Exception & e){
		    }
		    scene.fader.setFadeInColor(Bitmap::makeColor(r,g,b));
		} else if (simple == "fadeout.time"){
		    int time;
		    simple >> time;
		    scene.fader.setFadeOutTime(time);
		} else if (simple == "fadeout.col"){
		    int r=0,g=0,b=0;
		    try {
			simple >> r >> g >> b;
		    } catch (const Ast::Exception & e){
		    }
		    scene.fader.setFadeOutColor(Bitmap::makeColor(r,g,b));
		} else if (simple == "bg.name"){
		    std::string name;
		    simple >> name;
		    scene.background = new Background(file,name);
		} else if (simple == "clearcolor"){
		    int r=0,g=0,b=0;
		    try {
			simple >> r >> g >> b;
		    } catch (const Ast::Exception & e){
		    }
		    scene.clearColor = (r == -1 ? r : Bitmap::makeColor(r,g,b));
		} else if (simple == "end.time"){
		    simple >> scene.endTime;
		} else if (simple == "layerall.pos"){
		    try{
			simple >> scene.defaultPosition.x;
			simple >> scene.defaultPosition.y;
		    } catch (const Ast::Exception & e){
		    }
		} else if (PaintownUtil::matchRegex(simple.idString(), "layer[0-9]\\.anim")){
		    int num = atoi(PaintownUtil::captureRegex(simple.idString(), "layer([0-9])\\.anim", 0).c_str());
		    if (num >= 0 && num < 10){
			std::string action;
			simple >> action;
			Layer *layer = scene.layers[num];
			Ast::Section * section = parsed.findSection("begin action " + action);
			layer->setAnimation(Util::getAnimation(section,sprites));
		    }
		} else if (PaintownUtil::matchRegex(simple.idString(), "layer[0-9]\\.offset")){
		    int num = atoi(PaintownUtil::captureRegex(simple.idString(), "layer([0-9])\\.offset", 0).c_str());
		    if (num >= 0 && num < 10){
			int x=0,y=0;
			try{
			    simple >> x >> y;
			} catch (Ast::Exception & e){
			}
			Layer *layer = scene.layers[num];
			layer->setOffset(x, y);
		    }
		} else if (PaintownUtil::matchRegex(simple.idString(), "layer[0-9]\\.starttime")){
		    int num = atoi(PaintownUtil::captureRegex(simple.idString(), "layer([0-9])\\.starttime", 0).c_str());
		    if (num >= 0 && num < 10){
			int time;
			simple >> time;
			Layer *layer = scene.layers[num];
			layer->setStartTime(time);
		    }
		} else if (simple == "bgm"){
		    // do nothing
		} else if (simple == "bgm.loop"){
		    // do nothing
		} else {
			Global::debug(0) << "Unhandled option in Scene Section: " << simple.toString();
		}
	    }
    };

    SceneWalker walker(*this, file, sprites, parsed);
    data->walk(walker);

    // set initial fade state
    fader.setState(FADEIN);
}

Scene::~Scene(){

    if (background){
        delete background;
    }

    // layers
    for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
        if ((*i))delete (*i);
    }
}

void Scene::act(){
    // backgrounds
    if (background){
        background->act();
    }
    // layers
    for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
        Layer *layer = *i;
        layer->act(ticker);
    }
    // Fader
    fader.act();
    if (ticker == endTime - fader.getFadeOutTime()){
        fader.setState(FADEOUT);
    }
    // tick tick
    ticker++;
}
void Scene::render(const Bitmap & bmp){
    if (clearColor != -1 && clearColor != -2){
        bmp.fill(clearColor);
    }
    // backgrounds
    if (background){
        background->renderBackground(0,0, bmp);
    }
    // layers
    for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
        Layer *layer = *i;
        layer->render(defaultPosition.x,defaultPosition.y,bmp);
    }
    // foregrounds
    if (background){
        background->renderForeground(0,0, bmp);
    }
    // fader
    fader.draw(bmp);
}

bool Scene::isDone(){
    return (ticker >= endTime);
}

void Scene::reset(){
    ticker = 0;
    fader.setState(FADEIN);
    // layers
    for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){
	Layer *layer = *i;
	layer->reset();
    }
}

Storyboard::Storyboard( const string & s )throw (MugenException):
storyBoardFile(s),
startscene(0){
    // Lets look for our def since some people think that all file systems are case insensitive
    std::string baseDir = Util::getFileDir(storyBoardFile);
    const std::string ourDefFile = Util::fixFileName( baseDir, Util::stripDir(storyBoardFile) );
    // get real basedir
    //baseDir = Util::getFileDir( ourDefFile );
    Global::debug(1) << baseDir << endl;

    if (ourDefFile.empty()){
        throw MugenException("Cannot locate storyboard definition file for: " + storyBoardFile);
    }

    std::string filesdir = "";

    Global::debug(1) << "Got subdir: " << filesdir << endl;

    TimeDifference diff;
    diff.startTime();
    Ast::AstParse parsed((list<Ast::Section*>*) Def::main(ourDefFile));
    diff.endTime();
    Global::debug(1) << "Parsed mugen file " + ourDefFile + " in" + diff.printTime("") << endl;

    /* set by bg.name = "foo" */
    string bgname;

    for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){
        Ast::Section * section = *section_it;
	std::string head = section->getName();

	head = Util::fixCase(head);

        if (head == "info"){
            class InfoWalk: public Ast::Walker{
            public:
                virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
                    if (simple == "name"){
                        string name;
                        simple >> name;
                        Global::debug(1) << "Read name '" << name << "'" << endl;
                    } else if (simple == "author"){
                        string name;
                        simple >> name;
                        Global::debug(1) << "Made by: '" << name << "'" << endl;
                    } else {
                        Global::debug(0) << "Warning: ignored attribute: " << simple.toString() << endl;
                    }
                }
            };

            InfoWalk walk;
            section->walk(walk);

        } else if (head == "scenedef"){
            class SceneWalk: public Ast::Walker{
            public:
                SceneWalk(const string & baseDir, Storyboard & board):
                    baseDir(baseDir),
                    board(board){
                }

                const string & baseDir;
                Storyboard & board;

                virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
                    if (simple == "spr"){
			std::string temp;
                        simple >> temp;
                        Util::readSprites(Util::getCorrectFileLocation(this->baseDir, temp), "", board.sprites);
                    } else if (simple == "startscene"){
                        simple >> board.startscene;
                        Global::debug(1) << "Starting storyboard at: '" << board.startscene << "'" << endl;
                    } else {
                        Global::debug(0) << "Warning: ignored attribute: " << simple.toString() << endl;
                    }
                }
            };

            SceneWalk walk(baseDir, *this);
            section->walk(walk);
        } else if (PaintownUtil::matchRegex(head, "^scene")){
	    Scene *scene = new Scene(section,ourDefFile,parsed,sprites);
	    scenes.push_back(scene);
	}
    }
}

Storyboard::~Storyboard(){
    // Get rid of animation lists;
    for( std::map< int, MugenAnimation * >::iterator i = animations.begin() ; i != animations.end() ; ++i ){
        if( i->second )delete i->second;
    }

    // Get rid of scene lists;
    for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){
        if( (*i) )delete (*i);
    }
    // sprites
    for( SpriteMap::iterator i = sprites.begin() ; i != sprites.end() ; ++i ){
        for( std::map< unsigned int, MugenSprite * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){
            if( j->second )delete j->second;
        }
    }
}

void Storyboard::run(const Bitmap &bmp, bool repeat){
    double gameSpeed = 1.0;
    double runCounter = 0;
    bool quit = false;

    Bitmap work( 320, 240 );

    for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){
        if( (*i) ){
            (*i)->reset();
        }
    }

    std::vector< Scene * >::iterator sceneIterator = scenes.begin() + startscene;

    while( !quit ){
        bool draw = false;

        Scene *scene = *sceneIterator;
        if ( Global::speed_counter > 0 ){

            runCounter += Global::speed_counter * gameSpeed * Global::LOGIC_MULTIPLIER;//(double) 90 / (double) 60;
            while (runCounter > 1){
                runCounter -= 1;
                draw = true;
                // Key handler
		InputManager::poll();

                InputMap<CharacterKeys>::Output out = InputManager::getMap(input);

                if (out[Up]){
	        }
	        if (out[Down]){
	        }
	        if (out[Left]){
	        }
	        if (out[Right]){
	        }
	        if (out[A]){
                    quit = true;
                    return;
	        }
	        if (out[B]){
                    quit = true;
                    return;
	        }
	        if (out[C]){
                    quit = true;
                    return;
	        }
	        if (out[X]){
                    quit = true;
                    return;
	        }
	        if (out[Y]){
                    quit = true;
                    return;
	        }
	        if (out[Z]){
                    quit = true;
                    return;
	        }
	        if (out[Start]){
                    quit = true;
                    return;
	        }
                scene->act();

                if (scene->isDone()){
                    sceneIterator++;
                    if (sceneIterator == scenes.end()){
                        if (repeat){
                            sceneIterator = scenes.begin();
                        } else {
                            return;
                        }
                    }
                    scene = *sceneIterator;
                    scene->reset();
                }
            }
            Global::speed_counter = 0;
        }

        if (draw){
            scene->render(work);
            work.Stretch(bmp);
            if (Global::getDebug() > 0){
                Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor(0,255,128), bmp, "Scene: Time(%i) : EndTime(%i) : Fade in(%i) : Fade out(%i)",0, scene->getTicker(),scene->getEndTime(),scene->getFadeTool().getFadeInTime(),scene->getFadeTool().getFadeOutTime() );
            }
            bmp.BlitToScreen();
        }

        while (Global::speed_counter == 0){
            PaintownUtil::rest(1);
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Include the header to get QDesktopWidget defined<commit_after><|endoftext|>


<commit_before>#ifndef __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif

namespace framework
{

struct ToolBoxItemDescriptor
{
    Bitmap* pBmp;                       // Bitmap ptr not used by xml configuration
    String  aBitmapName;                // bitmap name => use to find correct bmp file
    String  aItemText;                  // label for this toolbox item
    String  aURL;                       // URL command to dispatch
    USHORT  nId;                        // internal id not used by xml configuration
    USHORT  nItemBits;                  // properties for this toolbox item (WinBits)
    USHORT  nItemType;                  // toolbox item type (BUTTON, SPACE, BREAK, SEPARATOR)
    USHORT  nVisible;                   // toolbox item visible?
    USHORT  nWidth;                     // width of a toolbox window (edit field, etc.)
    USHORT  nUserDef;                   // user defined toolbox item (1=yes/0=no)
    String  aHelpId;                    // A help id associated with this toolbox item

    public:

        ToolBoxItemDescriptor() : pBmp( 0 )
                                 ,nId( 0 )
                                 ,nItemBits( 0 )
                                 ,nItemType( (USHORT)TOOLBOXITEM_SPACE )
                                 ,nVisible( sal_True )
                                 ,nWidth( 0 )
                                 ,nUserDef( sal_False ) {}
};

typedef ToolBoxItemDescriptor* ToolBoxItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ToolBoxDescriptor, ToolBoxItemDescriptorPtr, 10, 2)

struct ToolBoxLayoutItemDescriptor
{
    String                      aName;          // Unique name of the toolbox ( Objectbar, Toolbar etc. )
    String                      aUserName;      // Userspecified name for this toolbar
    Point                       aFloatingPos;   // Position in floating mode
    USHORT                      nFloatingLines; // Number of lines in floating mode
    USHORT                      nLines;         // Number of lines in docking mode
    ToolBoxAlign                eAlign;         // Aligned position in docking mode
    BOOL                        bVisible;       // Visible or not
    BOOL                        bFloating;      // Floating mode on/off
    ButtonType                  eType;          // text, symbol or text+symbol

    ToolBoxLayoutItemDescriptor() : nFloatingLines( 0 )
                                    ,nLines( 1 )
                                    ,eAlign( BOXALIGN_LEFT )
                                    ,bVisible( sal_False )
                                    ,bFloating( sal_False )
                                    ,eType( BUTTON_SYMBOL ) {}
};

typedef ToolBoxLayoutItemDescriptor* ToolBoxLayoutItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ToolBoxLayoutDescriptor, ToolBoxLayoutItemDescriptorPtr, 10, 2)

class ToolBoxConfiguration
{
    public:
        static sal_Bool LoadToolBox( SvStream& rInStream, ToolBoxDescriptor& aItems );
        static sal_Bool StoreToolBox( SvStream& rOutStream, const ToolBoxDescriptor& aItems );
        static sal_Bool LoadToolBoxLayout( SvStream& rInStream, ToolBoxLayoutDescriptor& aItems );
        static sal_Bool StoreToolBoxLayout( SvStream& rOutStream, ToolBoxLayoutDescriptor& aItems );
};

} // namespace framework

#endif // __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.6.170); FILE MERGED 2003/12/04 17:08:40 mt 1.6.170.1: #i23061# Removed/Changed old StarView stuff<commit_after>#ifndef __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif

namespace framework
{

struct ToolBoxItemDescriptor
{
    Bitmap* pBmp;                       // Bitmap ptr not used by xml configuration
    String  aBitmapName;                // bitmap name => use to find correct bmp file
    String  aItemText;                  // label for this toolbox item
    String  aURL;                       // URL command to dispatch
    USHORT  nId;                        // internal id not used by xml configuration
    USHORT  nItemBits;                  // properties for this toolbox item (WinBits)
    USHORT  nItemType;                  // toolbox item type (BUTTON, SPACE, BREAK, SEPARATOR)
    USHORT  nVisible;                   // toolbox item visible?
    USHORT  nWidth;                     // width of a toolbox window (edit field, etc.)
    USHORT  nUserDef;                   // user defined toolbox item (1=yes/0=no)
    String  aHelpId;                    // A help id associated with this toolbox item

    public:

        ToolBoxItemDescriptor() : pBmp( 0 )
                                 ,nId( 0 )
                                 ,nItemBits( 0 )
                                 ,nItemType( (USHORT)TOOLBOXITEM_SPACE )
                                 ,nVisible( sal_True )
                                 ,nWidth( 0 )
                                 ,nUserDef( sal_False ) {}
};

typedef ToolBoxItemDescriptor* ToolBoxItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ToolBoxDescriptor, ToolBoxItemDescriptorPtr, 10, 2)

struct ToolBoxLayoutItemDescriptor
{
    String                      aName;          // Unique name of the toolbox ( Objectbar, Toolbar etc. )
    String                      aUserName;      // Userspecified name for this toolbar
    Point                       aFloatingPos;   // Position in floating mode
    USHORT                      nFloatingLines; // Number of lines in floating mode
    USHORT                      nLines;         // Number of lines in docking mode
    WindowAlign                 eAlign;         // Aligned position in docking mode
    BOOL                        bVisible;       // Visible or not
    BOOL                        bFloating;      // Floating mode on/off
    ButtonType                  eType;          // text, symbol or text+symbol

    ToolBoxLayoutItemDescriptor() : nFloatingLines( 0 )
                                    ,nLines( 1 )
                                    ,eAlign( WINDOWALIGN_LEFT )
                                    ,bVisible( sal_False )
                                    ,bFloating( sal_False )
                                    ,eType( BUTTON_SYMBOL ) {}
};

typedef ToolBoxLayoutItemDescriptor* ToolBoxLayoutItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ToolBoxLayoutDescriptor, ToolBoxLayoutItemDescriptorPtr, 10, 2)

class ToolBoxConfiguration
{
    public:
        static sal_Bool LoadToolBox( SvStream& rInStream, ToolBoxDescriptor& aItems );
        static sal_Bool StoreToolBox( SvStream& rOutStream, const ToolBoxDescriptor& aItems );
        static sal_Bool LoadToolBoxLayout( SvStream& rInStream, ToolBoxLayoutDescriptor& aItems );
        static sal_Bool StoreToolBoxLayout( SvStream& rOutStream, ToolBoxLayoutDescriptor& aItems );
};

} // namespace framework

#endif // __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: framelistanalyzer.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 18:21:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source 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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "classes/framelistanalyzer.hxx"

//_______________________________________________
//  my own includes

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_TARGETS_H_
#include <targets.h>
#endif

#ifndef __FRAMEWORK_PROPERTIES_H_
#include <properties.h>
#endif

//_______________________________________________
//  interface includes

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//_______________________________________________
//  includes of other projects

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_______________________________________________
//  namespace

namespace framework{

//_______________________________________________
//  non exported const

//_______________________________________________
//  non exported definitions

//_______________________________________________
//  declarations

//_______________________________________________

/**
 */

FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier       ,
                                      const css::uno::Reference< css::frame::XFrame >&          xReferenceFrame ,
                                            sal_uInt32                                          eDetectMode     )
    : m_xSupplier      (xSupplier      )
    , m_xReferenceFrame(xReferenceFrame)
    , m_eDetectMode    (eDetectMode    )
{
    impl_analyze();
}

//_______________________________________________

/**
 */

FrameListAnalyzer::~FrameListAnalyzer()
{
}

//_______________________________________________

/** returns an analyzed list of all currently opened (top!) frames inside the desktop tree.

    We try to get a snapshot of all opened frames, which are part of the desktop frame container.
    Of course we can't access frames, which stands outside of this tree.
    But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last
    frame wrong. Further we analyze this list and split into different parts.
    E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model.
    These frames must be closed then. But all other frames must be untouched.
    In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window
    or document was closed. Then we have to initialize the backing window ...
    Last but not least we must know something about our special help frame. It must be handled
    seperatly. And last but not least - the backing component frame must be detected too.
*/

void FrameListAnalyzer::impl_analyze()
{
    // reset all members to get a consistent state
    m_bReferenceIsHidden  = sal_False;
    m_bReferenceIsHelp    = sal_False;
    m_bReferenceIsBacking = sal_False;
    m_xHelp               = css::uno::Reference< css::frame::XFrame >();
    m_xBackingComponent   = css::uno::Reference< css::frame::XFrame >();

    // try to get the task container by using the given supplier
    css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY);

    // All return list get an initial size to include all possible frames.
    // They will be packed at the end of this method ... using the actual step positions then.
    sal_Int32 nVisibleStep = 0;
    sal_Int32 nHiddenStep  = 0;
    sal_Int32 nModelStep   = 0;
    sal_Int32 nCount       = xFrameContainer->getCount();

    m_lOtherVisibleFrames.realloc(nCount);
    m_lOtherHiddenFrames.realloc(nCount);
    m_lModelFrames.realloc(nCount);

    // ask for the model of the given reference frame.
    // It must be compared with the model of every frame of the container
    // to sort it into the list of frames with the same model.
    // Supress this step, if right detect mode isn't set.
    css::uno::Reference< css::frame::XModel > xReferenceModel;
    if ((m_eDetectMode & E_MODEL) == E_MODEL )
    {
        css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController();
        if (xReferenceController.is())
            xReferenceModel = xReferenceController->getModel();
    }

    // check, if the reference frame is in hidden mode.
    // But look, if this analyze step is realy needed.
    css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY);
    if (
        ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) &&
        (xSet.is()                             )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
        aValue >>= m_bReferenceIsHidden;
    }

    // check, if the reference frame includes the backing component.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) &&
        (xSet.is()                                                 )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE);
        aValue >>= m_bReferenceIsBacking;
    }

    // check, if the reference frame includes the help module.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_HELP)     == E_HELP                ) &&
        (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK)
       )
    {
        m_bReferenceIsHelp = sal_True;
    }

    try
    {
        // Step over all frames of the desktop frame container and analyze it.
        for (sal_Int32 i=0; i<nCount; ++i)
        {
            // Ignore invalid items ... and of course the reference frame.
            // It will be a member of the given frame list too - but it was already
            // analyzed before!
            css::uno::Reference< css::frame::XFrame > xFrame;
            if (
                !(xFrameContainer->getByIndex(i) >>= xFrame) ||
                !(xFrame.is()                              ) ||
                 (xFrame==m_xReferenceFrame                )
               )
                continue;

            #ifdef ENABLE_WARNINGS
            if (
                ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) &&
                (
                 (!xFrame->getContainerWindow().is()) ||
                 (!xFrame->getComponentWindow().is())
                )
               )
            {
                LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!")
            }
            #endif

            // -------------------------------------------------
            // a) Is it the special help task?
            //    Return it seperated from any return list.
            if (
                ((m_eDetectMode & E_HELP) == E_HELP      ) &&
                (xFrame->getName()==SPECIALTARGET_HELPTASK)
               )
            {
                m_xHelp = xFrame;
                continue;
            }

            // -------------------------------------------------
            // b) Or is includes this task the special backing component?
            //    Return it seperated from any return list.
            //    But check if the reference task itself is the backing frame.
            //    Our user mst know it to decide right.
            if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                sal_Bool bIsBacking;

                if (
                    (xSet.is()                                                        ) &&
                    (xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE)>>=bIsBacking) &&
                    (bIsBacking                                                       )
                   )
                {
                    m_xBackingComponent = xFrame;
                    continue;
                }
            }

            // -------------------------------------------------
            // c) Or is it the a task, which uses the specified model?
            //    Add it to the list of "model frames".
            if ((m_eDetectMode & E_MODEL) == E_MODEL)
            {
                css::uno::Reference< css::frame::XController > xController = xFrame->getController();
                css::uno::Reference< css::frame::XModel >      xModel      ;
                if (xController.is())
                    xModel = xController->getModel();
                if (xModel==xReferenceModel)
                {
                    m_lModelFrames[nModelStep] = xFrame;
                    ++nModelStep;
                    continue;
                }
            }

            // -------------------------------------------------
            // d) Or is it the a task, which use another or no model at all?
            //    Add it to the list of "other frames". But look for it's
            //    visible state ... if it's allowed to do so.
            // -------------------------------------------------
            sal_Bool bHidden = sal_False;
            if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN )
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                if (xSet.is())
                {
                    css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
                    aValue >>= bHidden;
                }
            }

            if (bHidden)
            {
                m_lOtherHiddenFrames[nHiddenStep] = xFrame;
                ++nHiddenStep;
            }
            else
            {
                m_lOtherVisibleFrames[nVisibleStep] = xFrame;
                ++nVisibleStep;
            }
        }
    }
    catch(css::lang::IndexOutOfBoundsException)
    {
        // stop copying if index seams to be wrong.
        // This interface can't realy guarantee its count for multithreaded
        // environments. So it can occure!
    }

    // Pack both lists by using the actual step positions.
    // All empty or ignorable items should exist at the end of these lists
    // behind the position pointers. So they will be removed by a reallocation.
    m_lOtherVisibleFrames.realloc(nVisibleStep);
    m_lOtherHiddenFrames.realloc(nHiddenStep);
    m_lModelFrames.realloc(nModelStep);
}

} //  namespace framework
<commit_msg>INTEGRATION: CWS fwk01 (1.1.8.2.6); FILE MERGED 2003/03/11 13:21:04 as 1.1.8.2.6.1: #107864# function without reference frame<commit_after>/*************************************************************************
 *
 *  $RCSfile: framelistanalyzer.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2003-04-04 17:14:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source 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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "classes/framelistanalyzer.hxx"

//_______________________________________________
//  my own includes

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_TARGETS_H_
#include <targets.h>
#endif

#ifndef __FRAMEWORK_PROPERTIES_H_
#include <properties.h>
#endif

//_______________________________________________
//  interface includes

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//_______________________________________________
//  includes of other projects

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_______________________________________________
//  namespace

namespace framework{

//_______________________________________________
//  non exported const

//_______________________________________________
//  non exported definitions

//_______________________________________________
//  declarations

//_______________________________________________

/**
 */

FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier       ,
                                      const css::uno::Reference< css::frame::XFrame >&          xReferenceFrame ,
                                            sal_uInt32                                          eDetectMode     )
    : m_xSupplier      (xSupplier      )
    , m_xReferenceFrame(xReferenceFrame)
    , m_eDetectMode    (eDetectMode    )
{
    impl_analyze();
}

//_______________________________________________

/**
 */

FrameListAnalyzer::~FrameListAnalyzer()
{
}

//_______________________________________________

/** returns an analyzed list of all currently opened (top!) frames inside the desktop tree.

    We try to get a snapshot of all opened frames, which are part of the desktop frame container.
    Of course we can't access frames, which stands outside of this tree.
    But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last
    frame wrong. Further we analyze this list and split into different parts.
    E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model.
    These frames must be closed then. But all other frames must be untouched.
    In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window
    or document was closed. Then we have to initialize the backing window ...
    Last but not least we must know something about our special help frame. It must be handled
    seperatly. And last but not least - the backing component frame must be detected too.
*/

void FrameListAnalyzer::impl_analyze()
{
    // reset all members to get a consistent state
    m_bReferenceIsHidden  = sal_False;
    m_bReferenceIsHelp    = sal_False;
    m_bReferenceIsBacking = sal_False;
    m_xHelp               = css::uno::Reference< css::frame::XFrame >();
    m_xBackingComponent   = css::uno::Reference< css::frame::XFrame >();

    // try to get the task container by using the given supplier
    css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY);

    // All return list get an initial size to include all possible frames.
    // They will be packed at the end of this method ... using the actual step positions then.
    sal_Int32 nVisibleStep = 0;
    sal_Int32 nHiddenStep  = 0;
    sal_Int32 nModelStep   = 0;
    sal_Int32 nCount       = xFrameContainer->getCount();

    m_lOtherVisibleFrames.realloc(nCount);
    m_lOtherHiddenFrames.realloc(nCount);
    m_lModelFrames.realloc(nCount);

    // ask for the model of the given reference frame.
    // It must be compared with the model of every frame of the container
    // to sort it into the list of frames with the same model.
    // Supress this step, if right detect mode isn't set.
    css::uno::Reference< css::frame::XModel > xReferenceModel;
    if ((m_eDetectMode & E_MODEL) == E_MODEL )
    {
        css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController();
        if (xReferenceController.is())
            xReferenceModel = xReferenceController->getModel();
    }

    // check, if the reference frame is in hidden mode.
    // But look, if this analyze step is realy needed.
    css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY);
    if (
        ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) &&
        (xSet.is()                             )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
        aValue >>= m_bReferenceIsHidden;
    }

    // check, if the reference frame includes the backing component.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) &&
        (xSet.is()                                                 )
       )
    {
        css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE);
        aValue >>= m_bReferenceIsBacking;
    }

    // check, if the reference frame includes the help module.
    // But look, if this analyze step is realy needed.
    if (
        ((m_eDetectMode & E_HELP)     == E_HELP                ) &&
        (m_xReferenceFrame.is()                                ) &&
        (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK)
       )
    {
        m_bReferenceIsHelp = sal_True;
    }

    try
    {
        // Step over all frames of the desktop frame container and analyze it.
        for (sal_Int32 i=0; i<nCount; ++i)
        {
            // Ignore invalid items ... and of course the reference frame.
            // It will be a member of the given frame list too - but it was already
            // analyzed before!
            css::uno::Reference< css::frame::XFrame > xFrame;
            if (
                !(xFrameContainer->getByIndex(i) >>= xFrame) ||
                !(xFrame.is()                              ) ||
                 (xFrame==m_xReferenceFrame                )
               )
                continue;

            #ifdef ENABLE_WARNINGS
            if (
                ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) &&
                (
                 (!xFrame->getContainerWindow().is()) ||
                 (!xFrame->getComponentWindow().is())
                )
               )
            {
                LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!")
            }
            #endif

            // -------------------------------------------------
            // a) Is it the special help task?
            //    Return it seperated from any return list.
            if (
                ((m_eDetectMode & E_HELP) == E_HELP      ) &&
                (xFrame->getName()==SPECIALTARGET_HELPTASK)
               )
            {
                m_xHelp = xFrame;
                continue;
            }

            // -------------------------------------------------
            // b) Or is includes this task the special backing component?
            //    Return it seperated from any return list.
            //    But check if the reference task itself is the backing frame.
            //    Our user mst know it to decide right.
            if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                sal_Bool bIsBacking;

                if (
                    (xSet.is()                                                        ) &&
                    (xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE)>>=bIsBacking) &&
                    (bIsBacking                                                       )
                   )
                {
                    m_xBackingComponent = xFrame;
                    continue;
                }
            }

            // -------------------------------------------------
            // c) Or is it the a task, which uses the specified model?
            //    Add it to the list of "model frames".
            if ((m_eDetectMode & E_MODEL) == E_MODEL)
            {
                css::uno::Reference< css::frame::XController > xController = xFrame->getController();
                css::uno::Reference< css::frame::XModel >      xModel      ;
                if (xController.is())
                    xModel = xController->getModel();
                if (xModel==xReferenceModel)
                {
                    m_lModelFrames[nModelStep] = xFrame;
                    ++nModelStep;
                    continue;
                }
            }

            // -------------------------------------------------
            // d) Or is it the a task, which use another or no model at all?
            //    Add it to the list of "other frames". But look for it's
            //    visible state ... if it's allowed to do so.
            // -------------------------------------------------
            sal_Bool bHidden = sal_False;
            if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN )
            {
                xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);
                if (xSet.is())
                {
                    css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);
                    aValue >>= bHidden;
                }
            }

            if (bHidden)
            {
                m_lOtherHiddenFrames[nHiddenStep] = xFrame;
                ++nHiddenStep;
            }
            else
            {
                m_lOtherVisibleFrames[nVisibleStep] = xFrame;
                ++nVisibleStep;
            }
        }
    }
    catch(css::lang::IndexOutOfBoundsException)
    {
        // stop copying if index seams to be wrong.
        // This interface can't realy guarantee its count for multithreaded
        // environments. So it can occure!
    }

    // Pack both lists by using the actual step positions.
    // All empty or ignorable items should exist at the end of these lists
    // behind the position pointers. So they will be removed by a reallocation.
    m_lOtherVisibleFrames.realloc(nVisibleStep);
    m_lOtherHiddenFrames.realloc(nHiddenStep);
    m_lModelFrames.realloc(nModelStep);
}

} //  namespace framework
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#pragma once

#include "node_types.hpp"

namespace realm {
namespace js {

template<>
class String<node::Types> {
    std::string m_str;

  public:
    String(const char* s) : m_str(s) {}
    String(const std::string &s) : m_str(s) {}
    String(const v8::Local<v8::String> &s);
    String(v8::Local<v8::String> &&s) : String(s) {}

    operator std::string() const& {
        return m_str;
    }
    operator std::string() && {
        return std::move(m_str);
    }
    operator v8::Local<v8::String>() const {
        return Nan::New(m_str).ToLocalChecked();
    }
};

inline String<node::Types>::String(const v8::Local<v8::String> &s) {
    if (s.IsEmpty() || s->Length() == 0) {
        return;
    }
    if (s->IsOneByte()) {
        m_str.resize(s->Length());
    }
    else {
        // Length is in UCS-2 code units, which can take up to 3 bytes each to encode
        m_str.resize(3 * s->Length());
    }
    const int flags = v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8;
    auto length = s->WriteUtf8(&m_str[0], m_str.size(), 0, flags);
    m_str.resize(length);
}

} // js
} // realm
<commit_msg>Don't bother special-casing one-byte strings as they're more complicated than it seemed<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#pragma once

#include "node_types.hpp"

namespace realm {
namespace js {

template<>
class String<node::Types> {
    std::string m_str;

  public:
    String(const char* s) : m_str(s) {}
    String(const std::string &s) : m_str(s) {}
    String(const v8::Local<v8::String> &s);
    String(v8::Local<v8::String> &&s) : String(s) {}

    operator std::string() const& {
        return m_str;
    }
    operator std::string() && {
        return std::move(m_str);
    }
    operator v8::Local<v8::String>() const {
        return Nan::New(m_str).ToLocalChecked();
    }
};

inline String<node::Types>::String(const v8::Local<v8::String> &s) {
    if (s.IsEmpty() || s->Length() == 0) {
        return;
    }
    m_str.resize(s->Utf8Length());
    const int flags = v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8;
    s->WriteUtf8(&m_str[0], m_str.size(), 0, flags);
}

} // js
} // realm
<|endoftext|>