<commit_before>/** \file    augment_canones_references.cc
 *  \brief   A tool for adding numerical canon law references to MARC-21 datasets.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2019, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <string>
#include <unordered_map>
#include <cstdlib>
#include <strings.h>
#include "BibleUtil.h"
#include "Compiler.h"
#include "FileUtil.h"
#include "MARC.h"
#include "MiscUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"

namespace {

enum Codex { CIC1917, CIC1983, CCEO };

Codex DetermineCodex(const std::string &subfield_codex, const std::string &subfield_year, const std::string &ppn) {
    if (::strcasecmp(subfield_codex.c_str(), "Codex canonum ecclesiarum orientalium") == 0)
        return CCEO;

    if (unlikely(subfield_year.empty()))
        LOG_ERROR("missing year for Codex Iuris Canonici! (PPN: " + ppn + ")");
    if (subfield_year == "1917")
        return CIC1917;
    else if (subfield_year == "1983")
        return CIC1983;

    LOG_ERROR("bad year for Codex Iuris Canonici \"" + subfield_year + "\"! (PPN: " + ppn + ")");
}

// To understand this code read https://github.com/ubtue/tuefind/wiki/Codices
std::string FieldToCanonLawCode(const std::string &ppn, const Codex codex, const std::string &subfield_part) {
    unsigned range_start, range_end;
    if (subfield_part.empty()) {
        range_start = 0;
        range_end = 99999999;
    } else if (not MiscUtil::ParseCanonLawRanges(subfield_part, &range_start, &range_end))
        LOG_ERROR("don't know how to parse codex parts \"" + subfield_part + "\"! (PPN: " + ppn + ")");

    switch (codex) {
    case CIC1917:
        return StringUtil::ToString(100000000 + range_start) + "_" + StringUtil::ToString(100000000 + range_end);
    case CIC1983:
        return StringUtil::ToString(200000000 + range_start) + "_" + StringUtil::ToString(200000000 + range_end);
    case CCEO:
        return StringUtil::ToString(300000000 + range_start) + "_" + StringUtil::ToString(300000000 + range_end);
    default:
        LOG_ERROR("unknown codex: " + std::to_string(codex));
    }
}

std::string CodexToPrefix(const Codex codex) {
    switch (codex) {
    case CIC1917:
        return "CIC17";
    case CIC1983:
        return "CIC83";
    case CCEO:
        return "CCEO";
    default:
        LOG_ERROR("unknown codex: " + std::to_string(codex));
    }
}

void LoadAuthorityData(MARC::Reader * const reader,
                       std::unordered_map<std::string, std::string> * const authority_ppns_to_canon_law_codes_map)
{
    const auto aliases_file(FileUtil::OpenOutputFileOrDie(UBTools::GetTuelibPath() + "canon_law_aliases.map"));

    unsigned total_count(0);
    while (auto record = reader->read()) {
        ++total_count;

        const auto _110_field(record.findTag("110"));
        if (_110_field == record.end() or ::strcasecmp(_110_field->getFirstSubfieldWithCode('a').c_str(), "Katholische Kirche") != 0)
            continue;

        const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t'));
        if (::strcasecmp(t_subfield.c_str(),"Codex Iuris Canonici") != 0
            and ::strcasecmp(t_subfield.c_str(), "Codex canonum ecclesiarum orientalium") != 0)
            continue;

        const Codex codex(DetermineCodex(t_subfield, _110_field->getFirstSubfieldWithCode('f'), record.getControlNumber()));
        const auto canon_law_code(FieldToCanonLawCode(record.getControlNumber(), codex, _110_field->getFirstSubfieldWithCode('p')));
        (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = canon_law_code;

        for (const auto &_140_field : record.getTagRange("410")) {
            const auto p_subfield(_140_field.getFirstSubfieldWithCode('p'));
            if (not p_subfield.empty())
                (*aliases_file) << CodexToPrefix(codex) << ' ' << TextUtil::UTF8ToLower(p_subfield) << '=' << canon_law_code << '\n';
        }
    }

    LOG_INFO("found " + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + " canon law records among "
             + std::to_string(total_count) + " authority records.");
}

void CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field, std::vector<std::string> * const authority_ppns) {
    for (const auto &field : record.getTagRange(linking_field)) {
        const MARC::Subfields subfields(field.getSubfields());
        for (const auto &subfield : subfields) {
            if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-576)"))
                authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen("(DE-576)")));
        }
    }
}

void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer,
                    const std::unordered_map<std::string, std::string> &authority_ppns_to_canon_law_codes_map)
{
    static const std::vector<std::string> CANONES_GND_LINKING_TAGS{ "689", "655" };

    unsigned total_count(0), augmented_count(0);
    std::map<std::string, unsigned> reference_counts;

    while (auto record = reader->read()) {
        ++total_count;

        bool augmented_record(false);
        for (const auto &linking_tag : CANONES_GND_LINKING_TAGS) {
            std::vector<std::string> authority_ppns;
            CollectAuthorityPPNs(record, linking_tag, &authority_ppns);

            if (not authority_ppns.empty()) {
                for (const auto &authority_ppn : authority_ppns) {
                    const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn));
                    if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) {
                        record.insertField("CAL", { { 'a', ppn_and_canon_law_code->second } });
                        augmented_record = true;
                        ++reference_counts[linking_tag];
                    }
                }
            }
        }

        if (not augmented_record) {
            // check if the codex data is embedded directly in the 689 field
            // apparently, 689$t is repeatable and the first instance (always?) appears to be 'Katholische Kirche'
            std::vector<std::string> ranges_to_insert;
            for (const auto &_689_field : record.getTagRange("689")) {
                if (_689_field.getFirstSubfieldWithCode('a') != "Katholische Kirche")
                    continue;

                std::string subfield_codex, subfield_year, subfield_part;
                for (const auto &subfield : _689_field.getSubfields()) {
                    if (subfield.code_ == 't' and subfield.value_ != "Katholische Kirche")
                        subfield_codex = subfield.value_;
                    else if (subfield.code_ == 'f')
                        subfield_year = subfield.value_;
                    else if (subfield.code_ == 'p')
                        subfield_part = subfield.value_;
                }

                if (not subfield_codex.empty() and not subfield_year.empty() and not subfield_part.empty()) {
                    const Codex codex(DetermineCodex(subfield_codex, subfield_year, record.getControlNumber()));
                    ranges_to_insert.emplace_back(FieldToCanonLawCode(record.getControlNumber(), codex, subfield_part));
                    augmented_record = true;
                    ++reference_counts["689*"];
                }
            }

            for (const auto &range : ranges_to_insert)
                record.insertField("CAL", { { 'a', range } });
        }

        if (augmented_record)
            ++augmented_count;

        writer->write(record);
    }

    LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records.");
    LOG_INFO("found " + std::to_string(reference_counts["689"]) + " references in field 689");
    LOG_INFO("found " + std::to_string(reference_counts["689*"]) + " direct references in field 689");
    LOG_INFO("found " + std::to_string(reference_counts["655"]) + " references in field 655");
}

} // unnamed namespace

int Main(int argc, char **argv) {
    if (argc != 4)
        ::Usage("ixtheo_titles authority_records augmented_ixtheo_titles");

    const std::string title_input_filename(argv[1]);
    const std::string authority_filename(argv[2]);
    const std::string title_output_filename(argv[3]);
    if (unlikely(title_input_filename == title_output_filename))
        LOG_ERROR("Title input file name equals title output file name!");
    if (unlikely(title_input_filename == authority_filename))
        LOG_ERROR("Title input file name equals authority file name!");
    if (unlikely(title_output_filename == authority_filename))
        LOG_ERROR("Title output file name equals authority file name!");

    auto authority_reader(MARC::Reader::Factory(authority_filename));
    std::unordered_map<std::string, std::string> authority_ppns_to_canon_law_codes_map;
    LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map);

    auto title_reader(MARC::Reader::Factory(title_input_filename));
    auto title_writer(MARC::Writer::Factory(title_output_filename));
    ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map);

    return EXIT_SUCCESS;
}
<commit_msg>We now use only a single field per record for canon-law ranges.<commit_after>/** \file    augment_canones_references.cc
 *  \brief   A tool for adding numerical canon law references to MARC-21 datasets.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2019, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <string>
#include <unordered_map>
#include <cstdlib>
#include <strings.h>
#include "BibleUtil.h"
#include "Compiler.h"
#include "FileUtil.h"
#include "MARC.h"
#include "MiscUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"

namespace {

enum Codex { CIC1917, CIC1983, CCEO };

Codex DetermineCodex(const std::string &subfield_codex, const std::string &subfield_year, const std::string &ppn) {
    if (::strcasecmp(subfield_codex.c_str(), "Codex canonum ecclesiarum orientalium") == 0)
        return CCEO;

    if (unlikely(subfield_year.empty()))
        LOG_ERROR("missing year for Codex Iuris Canonici! (PPN: " + ppn + ")");
    if (subfield_year == "1917")
        return CIC1917;
    else if (subfield_year == "1983")
        return CIC1983;

    LOG_ERROR("bad year for Codex Iuris Canonici \"" + subfield_year + "\"! (PPN: " + ppn + ")");
}

// To understand this code read https://github.com/ubtue/tuefind/wiki/Codices
std::string FieldToCanonLawCode(const std::string &ppn, const Codex codex, const std::string &subfield_part) {
    unsigned range_start, range_end;
    if (subfield_part.empty()) {
        range_start = 0;
        range_end = 99999999;
    } else if (not MiscUtil::ParseCanonLawRanges(subfield_part, &range_start, &range_end))
        LOG_ERROR("don't know how to parse codex parts \"" + subfield_part + "\"! (PPN: " + ppn + ")");

    switch (codex) {
    case CIC1917:
        return StringUtil::ToString(100000000 + range_start) + "_" + StringUtil::ToString(100000000 + range_end);
    case CIC1983:
        return StringUtil::ToString(200000000 + range_start) + "_" + StringUtil::ToString(200000000 + range_end);
    case CCEO:
        return StringUtil::ToString(300000000 + range_start) + "_" + StringUtil::ToString(300000000 + range_end);
    default:
        LOG_ERROR("unknown codex: " + std::to_string(codex));
    }
}

std::string CodexToPrefix(const Codex codex) {
    switch (codex) {
    case CIC1917:
        return "CIC17";
    case CIC1983:
        return "CIC83";
    case CCEO:
        return "CCEO";
    default:
        LOG_ERROR("unknown codex: " + std::to_string(codex));
    }
}

void LoadAuthorityData(MARC::Reader * const reader,
                       std::unordered_map<std::string, std::string> * const authority_ppns_to_canon_law_codes_map)
{
    const auto aliases_file(FileUtil::OpenOutputFileOrDie(UBTools::GetTuelibPath() + "canon_law_aliases.map"));

    unsigned total_count(0);
    while (auto record = reader->read()) {
        ++total_count;

        const auto _110_field(record.findTag("110"));
        if (_110_field == record.end() or ::strcasecmp(_110_field->getFirstSubfieldWithCode('a').c_str(), "Katholische Kirche") != 0)
            continue;

        const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t'));
        if (::strcasecmp(t_subfield.c_str(),"Codex Iuris Canonici") != 0
            and ::strcasecmp(t_subfield.c_str(), "Codex canonum ecclesiarum orientalium") != 0)
            continue;

        const Codex codex(DetermineCodex(t_subfield, _110_field->getFirstSubfieldWithCode('f'), record.getControlNumber()));
        const auto canon_law_code(FieldToCanonLawCode(record.getControlNumber(), codex, _110_field->getFirstSubfieldWithCode('p')));
        (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = canon_law_code;

        for (const auto &_140_field : record.getTagRange("410")) {
            const auto p_subfield(_140_field.getFirstSubfieldWithCode('p'));
            if (not p_subfield.empty())
                (*aliases_file) << CodexToPrefix(codex) << ' ' << TextUtil::UTF8ToLower(p_subfield) << '=' << canon_law_code << '\n';
        }
    }

    LOG_INFO("found " + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + " canon law records among "
             + std::to_string(total_count) + " authority records.");
}

void CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field, std::vector<std::string> * const authority_ppns) {
    for (const auto &field : record.getTagRange(linking_field)) {
        const MARC::Subfields subfields(field.getSubfields());
        for (const auto &subfield : subfields) {
            if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-576)"))
                authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen("(DE-576)")));
        }
    }
}

void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer,
                    const std::unordered_map<std::string, std::string> &authority_ppns_to_canon_law_codes_map)
{
    static const std::vector<std::string> CANONES_GND_LINKING_TAGS{ "689", "655" };

    unsigned total_count(0), augmented_count(0);
    std::map<std::string, unsigned> reference_counts;

    while (auto record = reader->read()) {
        ++total_count;

        bool augmented_record(false);
        for (const auto &linking_tag : CANONES_GND_LINKING_TAGS) {
            std::vector<std::string> authority_ppns;
            CollectAuthorityPPNs(record, linking_tag, &authority_ppns);

            if (not authority_ppns.empty()) {
                for (const auto &authority_ppn : authority_ppns) {
                    const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn));
                    if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) {
                        record.insertField("CAL", { { 'a', ppn_and_canon_law_code->second } });
                        augmented_record = true;
                        ++reference_counts[linking_tag];
                    }
                }
            }
        }

        if (not augmented_record) {
            // check if the codex data is embedded directly in the 689 field
            // apparently, 689$t is repeatable and the first instance (always?) appears to be 'Katholische Kirche'
            std::vector<std::string> ranges_to_insert;
            for (const auto &_689_field : record.getTagRange("689")) {
                if (_689_field.getFirstSubfieldWithCode('a') != "Katholische Kirche")
                    continue;

                std::string subfield_codex, subfield_year, subfield_part;
                for (const auto &subfield : _689_field.getSubfields()) {
                    if (subfield.code_ == 't' and subfield.value_ != "Katholische Kirche")
                        subfield_codex = subfield.value_;
                    else if (subfield.code_ == 'f')
                        subfield_year = subfield.value_;
                    else if (subfield.code_ == 'p')
                        subfield_part = subfield.value_;
                }

                if (not subfield_codex.empty() and not subfield_year.empty() and not subfield_part.empty()) {
                    const Codex codex(DetermineCodex(subfield_codex, subfield_year, record.getControlNumber()));
                    ranges_to_insert.emplace_back(FieldToCanonLawCode(record.getControlNumber(), codex, subfield_part));
                    augmented_record = true;
                    ++reference_counts["689*"];
                }
            }

            if (not ranges_to_insert.empty())
                record.insertField("CAL", { { 'a', StringUtil::Join(ranges_to_insert, ',') } });
        }

        if (augmented_record)
            ++augmented_count;

        writer->write(record);
    }

    LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records.");
    LOG_INFO("found " + std::to_string(reference_counts["689"]) + " references in field 689");
    LOG_INFO("found " + std::to_string(reference_counts["689*"]) + " direct references in field 689");
    LOG_INFO("found " + std::to_string(reference_counts["655"]) + " references in field 655");
}

} // unnamed namespace

int Main(int argc, char **argv) {
    if (argc != 4)
        ::Usage("ixtheo_titles authority_records augmented_ixtheo_titles");

    const std::string title_input_filename(argv[1]);
    const std::string authority_filename(argv[2]);
    const std::string title_output_filename(argv[3]);
    if (unlikely(title_input_filename == title_output_filename))
        LOG_ERROR("Title input file name equals title output file name!");
    if (unlikely(title_input_filename == authority_filename))
        LOG_ERROR("Title input file name equals authority file name!");
    if (unlikely(title_output_filename == authority_filename))
        LOG_ERROR("Title output file name equals authority file name!");

    auto authority_reader(MARC::Reader::Factory(authority_filename));
    std::unordered_map<std::string, std::string> authority_ppns_to_canon_law_codes_map;
    LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map);

    auto title_reader(MARC::Reader::Factory(title_input_filename));
    auto title_writer(MARC::Writer::Factory(title_output_filename));
    ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map);

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin
 *               2012 by Matthias Noack, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include <gtest/gtest.h>

#include <boost/scoped_ptr.hpp>
#include <sstream>
#include <string>
#include <vector>

#include "libxtreemfs/stripe_translator.h"
#include "libxtreemfs/uuid_container.h"
#include "libxtreemfs/uuid_item.h"
#include "libxtreemfs/container_uuid_iterator.h"
#include "libxtreemfs/simple_uuid_iterator.h"
#include "libxtreemfs/xtreemfs_exception.h"
#include "util/logging.h"
#include "xtreemfs/GlobalTypes.pb.h"

using namespace std;
using namespace xtreemfs::util;

namespace xtreemfs {

// factory function, works fine with all default constructible iterator types
template<class IteratorType>
UUIDIterator* CreateUUIDIterator() {
  return new IteratorType();
}

// functor to encapsulate different uuid adding mechanisms
template<class IteratorType>
struct UUIDAdder;

template<>
struct UUIDAdder<SimpleUUIDIterator> {
  void operator()(UUIDIterator* it, string uuid) {
    static_cast<SimpleUUIDIterator*>(it)->AddUUID(uuid);
  }
};

template<>
struct UUIDAdder<ContainerUUIDIterator> {
  void operator()(UUIDIterator* it, string uuid) {
    created_items_.push_back(new UUIDItem(uuid));
    // safe downcast here
    static_cast<ContainerUUIDIterator*>(it)->AddUUIDItem(created_items_.back());
  }

  typedef vector<UUIDItem*> ItemPtrList;

  ~UUIDAdder() {
    for (ItemPtrList::iterator it = created_items_.begin();
        it != created_items_.end();
        ++it) {
      delete *it;
    }
    created_items_.clear();
  }
 private:
  vector<UUIDItem*> created_items_;
};

template<class IteratorType>
class UUIDIteratorTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    initialize_logger(LEVEL_WARN);

    uuid_iterator_.reset(CreateUUIDIterator<IteratorType>());
  }

  virtual void TearDown() {
    shutdown_logger();
  }

  boost::scoped_ptr<UUIDIterator> uuid_iterator_;
  UUIDAdder<IteratorType> adder_;
};

#if GTEST_HAS_TYPED_TEST

using testing::Types;

typedef Types<SimpleUUIDIterator, ContainerUUIDIterator> Implementations;

TYPED_TEST_CASE(UUIDIteratorTest, Implementations);

TYPED_TEST(UUIDIteratorTest, ListWithOneUUID) {
  string uuid1 = "uuid1";
  string current_uuid;

  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  // If there is only one UUID and it fails, there is no other choice and it
  // should be always returned.
  for (int i = 0; i < 2; i++) {
    this->uuid_iterator_->MarkUUIDAsFailed(current_uuid);
    this->uuid_iterator_->GetUUID(&current_uuid);
    EXPECT_EQ(uuid1, current_uuid);
  }
}

TYPED_TEST(UUIDIteratorTest, ClearLeavesEmptyList) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->adder_(this->uuid_iterator_.get(), uuid2);

  // Clear the list.
  this->uuid_iterator_->Clear();

  // There should be no element left and GetUUID should fail.
  string current_uuid;
  EXPECT_THROW({this->uuid_iterator_->GetUUID(&current_uuid);},
               UUIDIteratorListIsEmpyException);
}

TYPED_TEST(UUIDIteratorTest, ResetAfterEndOfList) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string current_uuid;

  // Fill iterator with two UUIDs.
  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  this->adder_(this->uuid_iterator_.get(), uuid2);
  // No entry is marked as failed yet, the first UUID is still available.
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  // Mark the current entry (uuid1) as failed. uuid2 now current?
  this->uuid_iterator_->MarkUUIDAsFailed(uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);

  // Mark uuid1 again as failed - should have no consequences.
  this->uuid_iterator_->MarkUUIDAsFailed(uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);

  // Also mark uuid2 as failed now. Now all entries have failed. As we did reach
  // the end of the list, the status of all entries should be reset and set to
  // the first entry in the list.
  this->uuid_iterator_->MarkUUIDAsFailed(uuid2);
  for (list<UUIDItem*>::iterator it
         = this->uuid_iterator_->uuids_.begin();
       it != this->uuid_iterator_->uuids_.end();
       ++it) {
    EXPECT_FALSE((*it)->IsFailed());
  }
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
}

TYPED_TEST(UUIDIteratorTest, SetCurrentUUID) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";
  string current_uuid;

  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->adder_(this->uuid_iterator_.get(), uuid2);
  this->adder_(this->uuid_iterator_.get(), uuid3);

  // First UUID is current.
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  // Set third as current one.
  this->uuid_iterator_->SetCurrentUUID(uuid3);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid3, current_uuid);

  // Fail the third (and last one): current UUID should be the first again.
  this->uuid_iterator_->MarkUUIDAsFailed(uuid3);
  this->uuid_iterator_->GetUUID(&current_uuid);
  for (list<UUIDItem*>::iterator it
         = this->uuid_iterator_->uuids_.begin();
       it != this->uuid_iterator_->uuids_.end();
       ++it) {
    EXPECT_FALSE((*it)->IsFailed());
  }
  EXPECT_EQ(uuid1, current_uuid);
}

TYPED_TEST(UUIDIteratorTest, DebugString) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";

  EXPECT_EQ("[  ]", this->uuid_iterator_->DebugString());

  this->adder_(this->uuid_iterator_.get(), uuid1);
  EXPECT_EQ("[ [ uuid1, 0] ]", this->uuid_iterator_->DebugString());

  this->adder_(this->uuid_iterator_.get(), uuid2);
  EXPECT_EQ("[ [ uuid1, 0], [ uuid2, 0] ]", this->uuid_iterator_->DebugString());

  this->adder_(this->uuid_iterator_.get(), uuid3);
  EXPECT_EQ("[ [ uuid1, 0], [ uuid2, 0], [ uuid3, 0] ]", this->uuid_iterator_->DebugString());
}

#endif  // GTEST_HAS_TYPED_TEST

// Tests for SimpleUUIDIterator

class SimpleUUIDIteratorTest : public UUIDIteratorTest<SimpleUUIDIterator> {
 public:
  void SetUp() {
    UUIDIteratorTest::SetUp();
    simple_uuid_iterator_ =
        static_cast<SimpleUUIDIterator*>(uuid_iterator_.get());
  }
 protected:
  SimpleUUIDIterator* simple_uuid_iterator_;
};

TEST_F(SimpleUUIDIteratorTest, LaterAddsDoNotBreakIterator) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";
  string current_uuid;

  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->adder_(this->uuid_iterator_.get(), uuid2);

  // Mark first uuid as failed and the second takes over.
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
  uuid_iterator_->MarkUUIDAsFailed(uuid1);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);

  // Add a third uuid which should be the next element if the second does fail.
  this->adder_(this->uuid_iterator_.get(), uuid3);
  uuid_iterator_->MarkUUIDAsFailed(uuid2);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid3, current_uuid);

  // After all uuids have failed, the first will be returned again.
  uuid_iterator_->MarkUUIDAsFailed(uuid3);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
}

TEST_F(SimpleUUIDIteratorTest, SetCurrentUUIDAddsUnknownUUID) {
  string uuid1 = "uuid1";
  string current_uuid;

  // UUID1 not added so far. Setting it will automatically add it.
  uuid_iterator_->SetCurrentUUID(uuid1);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
}

TEST_F(SimpleUUIDIteratorTest, ClearAndAddUUID) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";
  string current_uuid;

  EXPECT_EQ(0, simple_uuid_iterator_->uuids_.size());

  simple_uuid_iterator_->ClearAndAddUUID(uuid1);
  simple_uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
  EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());

  simple_uuid_iterator_->ClearAndAddUUID(uuid2);
  simple_uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);
  EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());

  simple_uuid_iterator_->ClearAndAddUUID(uuid3);
  simple_uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid3, current_uuid);
  EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());
}

// Tests for ContainerUUIDIterator

class ContainerUUIDIteratorTest
  : public UUIDIteratorTest<ContainerUUIDIterator> {};

TEST_F(ContainerUUIDIteratorTest, CreateContainerAndGetUUID) {
  // Create container from XLocList
  pbrpc::XLocSet xlocs;
  pbrpc::StripingPolicyType type = pbrpc::STRIPING_POLICY_RAID0;
  const int replicaCount = 3;
  stringstream sstream;

  for (int i = 0; i < replicaCount; ++i) {
    pbrpc::Replica* replica = xlocs.add_replicas();
    const int stripe_width = i + 2;

    for (int j = 0; j < stripe_width; ++j) {
      sstream.str("");
      sstream << "uuid" << i << j;
      replica->add_osd_uuids(sstream.str());
      replica->mutable_striping_policy()->set_type(type);
      replica->mutable_striping_policy()->set_stripe_size(128);  // kb
      replica->mutable_striping_policy()->set_width(stripe_width);
    }
  }

  // get all striping policies
  StripeTranslator::PolicyContainer striping_policies;
  for (uint32_t i = 0; i < xlocs.replicas_size(); ++i) {
    striping_policies.push_back(&(xlocs.replicas(i).striping_policy()));
  }

  boost::scoped_ptr<UUIDContainer> uuid_container(new UUIDContainer(xlocs));

  // NOTE: We assume that all replicas use the same striping policy type and
  //       that all replicas use the same stripe size.
  boost::scoped_ptr<StripeTranslator> translator(new StripeTranslatorRaid0());
  // Map offset to corresponding OSDs.
  std::vector<ReadOperation> operations;
  off_t read_offsets[] = {0, 128 * 1024};

  for (int i = 0; i < sizeof(read_offsets); ++i) {
    operations.clear();
    translator->TranslateReadRequest(NULL,
                                     128 * 1024,
                                     read_offsets[i],
                                     striping_policies,
                                     &operations);

    // Create a UUIDIterator for a specific set of offsets
    boost::scoped_ptr<ContainerUUIDIterator> uuid_iterator(
        new ContainerUUIDIterator(uuid_container.get(),
                                  operations[0].osd_offsets));

    // check results
    string actual;
    for (int j = 0; j < replicaCount; ++j) {
      uuid_iterator->GetUUID(&actual);
      uuid_iterator->MarkUUIDAsFailed(actual);
      sstream.str("");
      sstream << "uuid" << j << operations[0].osd_offsets[j];
      EXPECT_EQ(sstream.str(), actual);
    }
  }
}

}  // namespace xtreemfs
<commit_msg>client: Fixed compilation problem of UUIDIteratorTest on older systems.<commit_after>/*
 * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin
 *               2012 by Matthias Noack, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include <gtest/gtest.h>

#include <boost/scoped_ptr.hpp>
#include <sstream>
#include <string>
#include <vector>

#include "libxtreemfs/stripe_translator.h"
#include "libxtreemfs/uuid_container.h"
#include "libxtreemfs/uuid_item.h"
#include "libxtreemfs/container_uuid_iterator.h"
#include "libxtreemfs/simple_uuid_iterator.h"
#include "libxtreemfs/xtreemfs_exception.h"
#include "util/logging.h"
#include "xtreemfs/GlobalTypes.pb.h"

using namespace std;
using namespace xtreemfs::util;

namespace xtreemfs {

// factory function, works fine with all default constructible iterator types
template<class IteratorType>
UUIDIterator* CreateUUIDIterator() {
  return new IteratorType();
}

// functor to encapsulate different uuid adding mechanisms
template<class IteratorType>
struct UUIDAdder;

template<>
struct UUIDAdder<SimpleUUIDIterator> {
  void operator()(UUIDIterator* it, string uuid) {
    static_cast<SimpleUUIDIterator*>(it)->AddUUID(uuid);
  }
};

template<>
struct UUIDAdder<ContainerUUIDIterator> {
  void operator()(UUIDIterator* it, string uuid) {
    created_items_.push_back(new UUIDItem(uuid));
    // safe downcast here
    static_cast<ContainerUUIDIterator*>(it)->AddUUIDItem(created_items_.back());
  }

  typedef vector<UUIDItem*> ItemPtrList;

  ~UUIDAdder() {
    for (ItemPtrList::iterator it = created_items_.begin();
        it != created_items_.end();
        ++it) {
      delete *it;
    }
    created_items_.clear();
  }
 private:
  vector<UUIDItem*> created_items_;
};

template<class IteratorType>
class UUIDIteratorTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    initialize_logger(LEVEL_WARN);

    uuid_iterator_.reset(CreateUUIDIterator<IteratorType>());
  }

  virtual void TearDown() {
    shutdown_logger();
  }

  boost::scoped_ptr<UUIDIterator> uuid_iterator_;
  UUIDAdder<IteratorType> adder_;
};

#if GTEST_HAS_TYPED_TEST

using testing::Types;

typedef Types<SimpleUUIDIterator, ContainerUUIDIterator> Implementations;

TYPED_TEST_CASE(UUIDIteratorTest, Implementations);

TYPED_TEST(UUIDIteratorTest, ListWithOneUUID) {
  string uuid1 = "uuid1";
  string current_uuid;

  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  // If there is only one UUID and it fails, there is no other choice and it
  // should be always returned.
  for (int i = 0; i < 2; i++) {
    this->uuid_iterator_->MarkUUIDAsFailed(current_uuid);
    this->uuid_iterator_->GetUUID(&current_uuid);
    EXPECT_EQ(uuid1, current_uuid);
  }
}

TYPED_TEST(UUIDIteratorTest, ClearLeavesEmptyList) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->adder_(this->uuid_iterator_.get(), uuid2);

  // Clear the list.
  this->uuid_iterator_->Clear();

  // There should be no element left and GetUUID should fail.
  string current_uuid;
  EXPECT_THROW({this->uuid_iterator_->GetUUID(&current_uuid);},
               UUIDIteratorListIsEmpyException);
}

TYPED_TEST(UUIDIteratorTest, ResetAfterEndOfList) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string current_uuid;

  // Fill iterator with two UUIDs.
  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  this->adder_(this->uuid_iterator_.get(), uuid2);
  // No entry is marked as failed yet, the first UUID is still available.
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  // Mark the current entry (uuid1) as failed. uuid2 now current?
  this->uuid_iterator_->MarkUUIDAsFailed(uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);

  // Mark uuid1 again as failed - should have no consequences.
  this->uuid_iterator_->MarkUUIDAsFailed(uuid1);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);

  // Also mark uuid2 as failed now. Now all entries have failed. As we did reach
  // the end of the list, the status of all entries should be reset and set to
  // the first entry in the list.
  this->uuid_iterator_->MarkUUIDAsFailed(uuid2);
  for (list<UUIDItem*>::iterator it
         = this->uuid_iterator_->uuids_.begin();
       it != this->uuid_iterator_->uuids_.end();
       ++it) {
    EXPECT_FALSE((*it)->IsFailed());
  }
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
}

TYPED_TEST(UUIDIteratorTest, SetCurrentUUID) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";
  string current_uuid;

  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->adder_(this->uuid_iterator_.get(), uuid2);
  this->adder_(this->uuid_iterator_.get(), uuid3);

  // First UUID is current.
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);

  // Set third as current one.
  this->uuid_iterator_->SetCurrentUUID(uuid3);
  this->uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid3, current_uuid);

  // Fail the third (and last one): current UUID should be the first again.
  this->uuid_iterator_->MarkUUIDAsFailed(uuid3);
  this->uuid_iterator_->GetUUID(&current_uuid);
  for (list<UUIDItem*>::iterator it
         = this->uuid_iterator_->uuids_.begin();
       it != this->uuid_iterator_->uuids_.end();
       ++it) {
    EXPECT_FALSE((*it)->IsFailed());
  }
  EXPECT_EQ(uuid1, current_uuid);
}

TYPED_TEST(UUIDIteratorTest, DebugString) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";

  EXPECT_EQ("[  ]", this->uuid_iterator_->DebugString());

  this->adder_(this->uuid_iterator_.get(), uuid1);
  EXPECT_EQ("[ [ uuid1, 0] ]", this->uuid_iterator_->DebugString());

  this->adder_(this->uuid_iterator_.get(), uuid2);
  EXPECT_EQ("[ [ uuid1, 0], [ uuid2, 0] ]", this->uuid_iterator_->DebugString());

  this->adder_(this->uuid_iterator_.get(), uuid3);
  EXPECT_EQ("[ [ uuid1, 0], [ uuid2, 0], [ uuid3, 0] ]", this->uuid_iterator_->DebugString());
}

#endif  // GTEST_HAS_TYPED_TEST

// Tests for SimpleUUIDIterator

class SimpleUUIDIteratorTest : public UUIDIteratorTest<SimpleUUIDIterator> {
 public:
  void SetUp() {
    UUIDIteratorTest<SimpleUUIDIterator>::SetUp();
    simple_uuid_iterator_ =
        static_cast<SimpleUUIDIterator*>(uuid_iterator_.get());
  }
 protected:
  SimpleUUIDIterator* simple_uuid_iterator_;
};

TEST_F(SimpleUUIDIteratorTest, LaterAddsDoNotBreakIterator) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";
  string current_uuid;

  this->adder_(this->uuid_iterator_.get(), uuid1);
  this->adder_(this->uuid_iterator_.get(), uuid2);

  // Mark first uuid as failed and the second takes over.
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
  uuid_iterator_->MarkUUIDAsFailed(uuid1);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);

  // Add a third uuid which should be the next element if the second does fail.
  this->adder_(this->uuid_iterator_.get(), uuid3);
  uuid_iterator_->MarkUUIDAsFailed(uuid2);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid3, current_uuid);

  // After all uuids have failed, the first will be returned again.
  uuid_iterator_->MarkUUIDAsFailed(uuid3);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
}

TEST_F(SimpleUUIDIteratorTest, SetCurrentUUIDAddsUnknownUUID) {
  string uuid1 = "uuid1";
  string current_uuid;

  // UUID1 not added so far. Setting it will automatically add it.
  uuid_iterator_->SetCurrentUUID(uuid1);
  uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
}

TEST_F(SimpleUUIDIteratorTest, ClearAndAddUUID) {
  string uuid1 = "uuid1";
  string uuid2 = "uuid2";
  string uuid3 = "uuid3";
  string current_uuid;

  EXPECT_EQ(0, simple_uuid_iterator_->uuids_.size());

  simple_uuid_iterator_->ClearAndAddUUID(uuid1);
  simple_uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid1, current_uuid);
  EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());

  simple_uuid_iterator_->ClearAndAddUUID(uuid2);
  simple_uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid2, current_uuid);
  EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());

  simple_uuid_iterator_->ClearAndAddUUID(uuid3);
  simple_uuid_iterator_->GetUUID(&current_uuid);
  EXPECT_EQ(uuid3, current_uuid);
  EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());
}

// Tests for ContainerUUIDIterator

class ContainerUUIDIteratorTest
  : public UUIDIteratorTest<ContainerUUIDIterator> {};

TEST_F(ContainerUUIDIteratorTest, CreateContainerAndGetUUID) {
  // Create container from XLocList
  pbrpc::XLocSet xlocs;
  pbrpc::StripingPolicyType type = pbrpc::STRIPING_POLICY_RAID0;
  const int replicaCount = 3;
  stringstream sstream;

  for (int i = 0; i < replicaCount; ++i) {
    pbrpc::Replica* replica = xlocs.add_replicas();
    const int stripe_width = i + 2;

    for (int j = 0; j < stripe_width; ++j) {
      sstream.str("");
      sstream << "uuid" << i << j;
      replica->add_osd_uuids(sstream.str());
      replica->mutable_striping_policy()->set_type(type);
      replica->mutable_striping_policy()->set_stripe_size(128);  // kb
      replica->mutable_striping_policy()->set_width(stripe_width);
    }
  }

  // get all striping policies
  StripeTranslator::PolicyContainer striping_policies;
  for (uint32_t i = 0; i < xlocs.replicas_size(); ++i) {
    striping_policies.push_back(&(xlocs.replicas(i).striping_policy()));
  }

  boost::scoped_ptr<UUIDContainer> uuid_container(new UUIDContainer(xlocs));

  // NOTE: We assume that all replicas use the same striping policy type and
  //       that all replicas use the same stripe size.
  boost::scoped_ptr<StripeTranslator> translator(new StripeTranslatorRaid0());
  // Map offset to corresponding OSDs.
  std::vector<ReadOperation> operations;
  off_t read_offsets[] = {0, 128 * 1024};

  for (int i = 0; i < sizeof(read_offsets); ++i) {
    operations.clear();
    translator->TranslateReadRequest(NULL,
                                     128 * 1024,
                                     read_offsets[i],
                                     striping_policies,
                                     &operations);

    // Create a UUIDIterator for a specific set of offsets
    boost::scoped_ptr<ContainerUUIDIterator> uuid_iterator(
        new ContainerUUIDIterator(uuid_container.get(),
                                  operations[0].osd_offsets));

    // check results
    string actual;
    for (int j = 0; j < replicaCount; ++j) {
      uuid_iterator->GetUUID(&actual);
      uuid_iterator->MarkUUIDAsFailed(actual);
      sstream.str("");
      sstream << "uuid" << j << operations[0].osd_offsets[j];
      EXPECT_EQ(sstream.str(), actual);
    }
  }
}

}  // namespace xtreemfs
<|endoftext|>


<commit_before>//
// Copyright (C) 2013 Mateusz Łoskot <mateusz@loskot.net>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the  GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See the LICENSE.txt file for more information.
//
#include "bbopenprojectwizard.hpp"
#include "bbproject.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbutility.hpp"
#include "filesselectionwizardpage.hpp"
// Qt Creator
#include <coreplugin/dialogs/iwizard.h>
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
// Qt
#include <QFileInfo>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>

namespace BoostBuildProjectManager {
namespace Internal {

//////////////////////////////////////////////////////////////////////////////////////////

OpenProjectWizard::OpenProjectWizard(Project const* const project)
    : project_(project)
    , projectOpened_(false)
{
    // Project instance has been created, but it's only partially initialised and
    // rest of the initialisation takes place after this wizard completes.
    Q_ASSERT(project_);

    setDisplayName(tr("Open %1 Project").arg(BBPM_C(BOOSTBUILD)));
    setId(BBPM_C(PROJECT_WIZARD_ID));
    setWizardKind(ProjectWizard); // affects dir vs file path and sub-projects handling

    // TODO: do we need categories or flags?
}

bool OpenProjectWizard::run(QString const& platform, QVariantMap const& extraValues)
{
    QVariantMap extraValuesCopy(extraValues);

    // Project name should be passed by caller, but,
    // since we have Project instance handy, double-check.
    if (!extraValuesCopy.contains(BBPM_C(P_KEY_PROJECTNAME)))
        extraValuesCopy.insert(BBPM_C(P_KEY_PROJECTNAME), project_->displayName());

    projectOpened_ = false;
    outputValues_.clear();

    runWizard(project_->projectFilePath(), 0, platform, extraValuesCopy);

    return projectOpened_;
}

QWizard*
OpenProjectWizard::createWizardDialog(QWidget* parent
    , Core::WizardDialogParameters const& parameters) const
{

    OpenProjectWizardDialog* wizard(new OpenProjectWizardDialog(parent
        , parameters.defaultPath(), parameters.extraValues()
        , const_cast<OpenProjectWizard*>(this)->outputValues_));

    foreach (QWizardPage* p, parameters.extensionPages())
        BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(p));

    return wizard;
}

Core::GeneratedFiles
OpenProjectWizard::generateFiles(QWizard const* wizard, QString* errorMessage) const
{
    Q_UNUSED(errorMessage)
    Q_ASSERT(project_);

    OpenProjectWizardDialog const* openWizard
        = qobject_cast<OpenProjectWizardDialog const*>(wizard);

    QDir const projectDir(openWizard->path());

    // Set up MIME filters for C/C++ headers
    QStringList headerFilters;
    QStringList const headerMimeTypes = QStringList()
        << QLatin1String("text/x-chdr") << QLatin1String("text/x-c++hdr");
    foreach (QString const& headerMime, headerMimeTypes)
    {
        Core::MimeType mime = Core::MimeDatabase::findByType(headerMime);
        foreach (Core::MimeGlobPattern const& gp, mime.globPatterns())
            headerFilters.append(gp.pattern());
    }

    // Generate list of include paths.
    // If any C/C++ headers in any directory from paths, add it to include paths,
    // used for C/C++ parsing only.
    QStringList includePaths;
    QStringList const paths = openWizard->selectedPaths();
    foreach (QString const& path, paths)
    {
        QFileInfo const fileInfo(path);
        QDir const thisDir(fileInfo.absoluteFilePath());
        if (!thisDir.entryList(headerFilters, QDir::Files).isEmpty())
        {
            QString const relative = projectDir.relativeFilePath(thisDir.path());
            includePaths.append(relative.isEmpty() ? QLatin1String(".") : relative);
        }
    }

    // Generate list of sources
    QStringList sources = openWizard->selectedFiles();
    Utility::makeRelativePaths(projectDir.absolutePath(), sources);

    Core::GeneratedFile generatedFilesFile(project_->filesFilePath());
    generatedFilesFile.setContents(sources.join(QLatin1String("\n")));

    Core::GeneratedFile generatedIncludesFile(project_->includesFilePath());
    generatedIncludesFile.setContents(includePaths.join(QLatin1String("\n")));

    Core::GeneratedFiles files;
    files.append(generatedFilesFile);
    files.append(generatedIncludesFile);
    return files;
}

bool
OpenProjectWizard::postGenerateFiles(QWizard const* wizard
    , Core::GeneratedFiles const& files, QString* errorMessage)
{
    Q_UNUSED(wizard);

    projectOpened_
        = ProjectExplorer::CustomProjectWizard::postGenerateOpen(files, errorMessage);

    return projectOpened_;
}

//////////////////////////////////////////////////////////////////////////////////////////
OpenProjectWizardDialog::OpenProjectWizardDialog(QWidget* parent
    , QString const& projectFile
    , QVariantMap const& extraValues, QVariantMap& outputValues)
    : Utils::Wizard(parent)
    , outputValues_(outputValues)
    , extraValues_(extraValues)
    , projectFile_(projectFile)
{
    setWindowTitle(tr("Open %1 Project").arg(BBPM_C(BOOSTBUILD)));

    pathsPage_ = new PathsSelectionWizardPage(this);
    pathsPage_->setTitle(tr("Project Name and Paths"));
    int const pathsPageId = addPage(pathsPage_);
    wizardProgress()->item(pathsPageId)->setTitle(tr("Location"));

    filesPage_ = new FilesSelectionWizardPage(this);
    filesPage_->setTitle(tr("File Selection"));
    int const filesPageId = addPage(filesPage_);
    wizardProgress()->item(filesPageId)->setTitle(tr("Files"));
}

QString OpenProjectWizardDialog::path() const
{
    QFileInfo const projectFileInfo(projectFile());
    QTC_ASSERT(projectFileInfo.isFile(), return QString());

    return projectFileInfo.absoluteDir().absolutePath();
}

QString OpenProjectWizardDialog::projectFile() const
{
    return projectFile_;
}

QString OpenProjectWizardDialog::projectName() const
{
    return pathsPage_->projectName();
}

QString OpenProjectWizardDialog::defaultProjectName() const
{
    return extraValues_.value(BBPM_C(P_KEY_PROJECTNAME)).toString();
}

QStringList OpenProjectWizardDialog::selectedFiles() const
{
    return filesPage_->selectedFiles();
}

QStringList OpenProjectWizardDialog::selectedPaths() const
{
    return filesPage_->selectedPaths();
}

void OpenProjectWizardDialog::setProjectName(QString const& name)
{
    outputValues_.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), name);
}

//////////////////////////////////////////////////////////////////////////////////////////
PathsSelectionWizardPage::PathsSelectionWizardPage(OpenProjectWizardDialog* wizard)
    : QWizardPage(wizard)
    , wizard_(wizard)
{
    QFormLayout *fl = new QFormLayout();
    setLayout(fl);

    QLabel* pathLabel = new QLabel(this);
    pathLabel->setText(tr("Opening the following Jamfile as a project:"));
    fl->addRow(pathLabel);

    QLineEdit* pathLine = new QLineEdit(this);
    pathLine->setReadOnly(true);
    pathLine->setDisabled(true);
    pathLine->setText(wizard_->path());
    fl->addRow(pathLine);

    QString projectName(Utility::parseJamfileProjectName(wizard_->projectFile()));
    if (projectName.isEmpty())
        projectName = wizard_->defaultProjectName();

    nameLineEdit_ = new QLineEdit(this);
    connect(nameLineEdit_, &QLineEdit::textChanged
          , wizard_, &OpenProjectWizardDialog::setProjectName);
    nameLineEdit_->setText(projectName);
    fl->addRow(tr("Project name:"), nameLineEdit_);

    QLabel* defaultsLabel = new QLabel(this);
    defaultsLabel->setText(tr("Default Boost.Build runtime locations:"));
    fl->addRow(defaultsLabel);

    QLineEdit* workingLine = new QLineEdit(this);
    workingLine->setReadOnly(true);
    workingLine->setDisabled(true);
    workingLine->setText(Project::defaultWorkingDirectory(wizard_->path()));
    fl->addRow(tr("Working directory:"), workingLine);

    QLineEdit* buildLine = new QLineEdit(this);
    buildLine->setReadOnly(true);
    buildLine->setDisabled(true);
    buildLine->setText(Project::defaultBuildDirectory(wizard_->path()));
    fl->addRow(tr("Build directory:"), buildLine);

    // TODO: indicate if we can find Boost.Build executable?

    QString const info(tr(
        "This allows you to use Qt Creator as an IDE to edit and navigate C++ code, "
        "run %1 command, work through compilation issues, "
        "configure executable targets to run and debug.")
        .arg(QLatin1String(Constants::BOOSTBUILD)));
    QLabel* infoLabel = new QLabel(this);
    infoLabel->setWordWrap(true);
    infoLabel->setText(info);
    fl->addRow(infoLabel);
}

QString PathsSelectionWizardPage::projectName() const
{
    return nameLineEdit_->text();
}

} // namespace Internal
} // namespace BoostBuildProjectManager
<commit_msg>Fix project path and projectFile location mismatch<commit_after>//
// Copyright (C) 2013 Mateusz Łoskot <mateusz@loskot.net>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the  GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See the LICENSE.txt file for more information.
//
#include "bbopenprojectwizard.hpp"
#include "bbproject.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbutility.hpp"
#include "filesselectionwizardpage.hpp"
// Qt Creator
#include <coreplugin/dialogs/iwizard.h>
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
// Qt
#include <QFileInfo>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>

namespace BoostBuildProjectManager {
namespace Internal {

//////////////////////////////////////////////////////////////////////////////////////////

OpenProjectWizard::OpenProjectWizard(Project const* const project)
    : project_(project)
    , projectOpened_(false)
{
    // Project instance has been created, but it's only partially initialised and
    // rest of the initialisation takes place after this wizard completes.
    Q_ASSERT(project_);

    setDisplayName(tr("Open %1 Project").arg(BBPM_C(BOOSTBUILD)));
    setId(BBPM_C(PROJECT_WIZARD_ID));
    setWizardKind(ProjectWizard); // affects dir vs file path and sub-projects handling

    // TODO: do we need categories or flags?
}

bool OpenProjectWizard::run(QString const& platform, QVariantMap const& extraValues)
{
    QVariantMap extraValuesCopy(extraValues);

    // Project name should be passed by caller, but,
    // since we have Project instance handy, double-check.
    if (!extraValuesCopy.contains(BBPM_C(P_KEY_PROJECTNAME)))
        extraValuesCopy.insert(BBPM_C(P_KEY_PROJECTNAME), project_->displayName());

    projectOpened_ = false;
    outputValues_.clear();

    runWizard(project_->projectFilePath(), 0, platform, extraValuesCopy);

    return projectOpened_;
}

QWizard*
OpenProjectWizard::createWizardDialog(QWidget* parent
    , Core::WizardDialogParameters const& parameters) const
{

    OpenProjectWizardDialog* wizard(new OpenProjectWizardDialog(parent
        , parameters.defaultPath(), parameters.extraValues()
        , const_cast<OpenProjectWizard*>(this)->outputValues_));

    foreach (QWizardPage* p, parameters.extensionPages())
        BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(p));

    return wizard;
}

Core::GeneratedFiles
OpenProjectWizard::generateFiles(QWizard const* wizard, QString* errorMessage) const
{
    Q_UNUSED(errorMessage)
    Q_ASSERT(project_);

    OpenProjectWizardDialog const* openWizard
        = qobject_cast<OpenProjectWizardDialog const*>(wizard);

    QDir const projectDir(openWizard->path());

    // Set up MIME filters for C/C++ headers
    QStringList headerFilters;
    QStringList const headerMimeTypes = QStringList()
        << QLatin1String("text/x-chdr") << QLatin1String("text/x-c++hdr");
    foreach (QString const& headerMime, headerMimeTypes)
    {
        Core::MimeType mime = Core::MimeDatabase::findByType(headerMime);
        foreach (Core::MimeGlobPattern const& gp, mime.globPatterns())
            headerFilters.append(gp.pattern());
    }

    // Generate list of include paths.
    // If any C/C++ headers in any directory from paths, add it to include paths,
    // used for C/C++ parsing only.
    QStringList includePaths;
    QStringList const paths = openWizard->selectedPaths();
    foreach (QString const& path, paths)
    {
        QFileInfo const fileInfo(path);
        QDir const thisDir(fileInfo.absoluteFilePath());
        if (!thisDir.entryList(headerFilters, QDir::Files).isEmpty())
        {
            QString const relative = projectDir.relativeFilePath(thisDir.path());
            includePaths.append(relative.isEmpty() ? QLatin1String(".") : relative);
        }
    }

    // Generate list of sources
    QStringList sources = openWizard->selectedFiles();
    Utility::makeRelativePaths(projectDir.absolutePath(), sources);

    Core::GeneratedFile generatedFilesFile(project_->filesFilePath());
    generatedFilesFile.setContents(sources.join(QLatin1String("\n")));

    Core::GeneratedFile generatedIncludesFile(project_->includesFilePath());
    generatedIncludesFile.setContents(includePaths.join(QLatin1String("\n")));

    Core::GeneratedFiles files;
    files.append(generatedFilesFile);
    files.append(generatedIncludesFile);
    return files;
}

bool
OpenProjectWizard::postGenerateFiles(QWizard const* wizard
    , Core::GeneratedFiles const& files, QString* errorMessage)
{
    Q_UNUSED(wizard);

    projectOpened_
        = ProjectExplorer::CustomProjectWizard::postGenerateOpen(files, errorMessage);

    return projectOpened_;
}

//////////////////////////////////////////////////////////////////////////////////////////
OpenProjectWizardDialog::OpenProjectWizardDialog(QWidget* parent
    , QString const& projectFile
    , QVariantMap const& extraValues, QVariantMap& outputValues)
    : Utils::Wizard(parent)
    , outputValues_(outputValues)
    , extraValues_(extraValues)
    , projectFile_(projectFile)
{
    setWindowTitle(tr("Open %1 Project").arg(BBPM_C(BOOSTBUILD)));

    pathsPage_ = new PathsSelectionWizardPage(this);
    pathsPage_->setTitle(tr("Project Name and Paths"));
    int const pathsPageId = addPage(pathsPage_);
    wizardProgress()->item(pathsPageId)->setTitle(tr("Location"));

    filesPage_ = new FilesSelectionWizardPage(this);
    filesPage_->setTitle(tr("File Selection"));
    int const filesPageId = addPage(filesPage_);
    wizardProgress()->item(filesPageId)->setTitle(tr("Files"));
}

QString OpenProjectWizardDialog::path() const
{
    QFileInfo const projectFileInfo(projectFile());
    QTC_ASSERT(projectFileInfo.isFile(), return QString());

    return projectFileInfo.absoluteDir().absolutePath();
}

QString OpenProjectWizardDialog::projectFile() const
{
    return projectFile_;
}

QString OpenProjectWizardDialog::projectName() const
{
    return pathsPage_->projectName();
}

QString OpenProjectWizardDialog::defaultProjectName() const
{
    return extraValues_.value(BBPM_C(P_KEY_PROJECTNAME)).toString();
}

QStringList OpenProjectWizardDialog::selectedFiles() const
{
    return filesPage_->selectedFiles();
}

QStringList OpenProjectWizardDialog::selectedPaths() const
{
    return filesPage_->selectedPaths();
}

void OpenProjectWizardDialog::setProjectName(QString const& name)
{
    outputValues_.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), name);
}

//////////////////////////////////////////////////////////////////////////////////////////
PathsSelectionWizardPage::PathsSelectionWizardPage(OpenProjectWizardDialog* wizard)
    : QWizardPage(wizard)
    , wizard_(wizard)
{
    QFormLayout *fl = new QFormLayout();
    setLayout(fl);

    QLabel* pathLabel = new QLabel(this);
    pathLabel->setText(tr("Opening the following Jamfile as a project:"));
    fl->addRow(pathLabel);

    QLineEdit* pathLine = new QLineEdit(this);
    pathLine->setReadOnly(true);
    pathLine->setDisabled(true);
    pathLine->setText(wizard_->projectFile());
    fl->addRow(pathLine);

    QString projectName(Utility::parseJamfileProjectName(wizard_->projectFile()));
    if (projectName.isEmpty())
        projectName = wizard_->defaultProjectName();

    nameLineEdit_ = new QLineEdit(this);
    connect(nameLineEdit_, &QLineEdit::textChanged
          , wizard_, &OpenProjectWizardDialog::setProjectName);
    nameLineEdit_->setText(projectName);
    fl->addRow(tr("Project name:"), nameLineEdit_);

    QLabel* defaultsLabel = new QLabel(this);
    defaultsLabel->setText(tr("Default Boost.Build runtime locations:"));
    fl->addRow(defaultsLabel);

    QLineEdit* workingLine = new QLineEdit(this);
    workingLine->setReadOnly(true);
    workingLine->setDisabled(true);
    workingLine->setText(Project::defaultWorkingDirectory(wizard_->projectFile()));
    fl->addRow(tr("Working directory:"), workingLine);

    QLineEdit* buildLine = new QLineEdit(this);
    buildLine->setReadOnly(true);
    buildLine->setDisabled(true);
    buildLine->setText(Project::defaultBuildDirectory(wizard_->projectFile()));
    fl->addRow(tr("Build directory:"), buildLine);

    // TODO: indicate if we can find Boost.Build executable?

    QString const info(tr(
        "This allows you to use Qt Creator as an IDE to edit and navigate C++ code, "
        "run %1 command, work through compilation issues, "
        "configure executable targets to run and debug.")
        .arg(QLatin1String(Constants::BOOSTBUILD)));
    QLabel* infoLabel = new QLabel(this);
    infoLabel->setWordWrap(true);
    infoLabel->setText(info);
    fl->addRow(infoLabel);
}

QString PathsSelectionWizardPage::projectName() const
{
    return nameLineEdit_->text();
}

} // namespace Internal
} // namespace BoostBuildProjectManager
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: gconflayer.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-30 15:05:29 $
 *
 *  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 OOurce 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 OOftware; 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 OOftware 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 OOftware
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards OOurce License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  OOurce 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.
 *
 *  OOftware 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 OOFTWARE 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 OOftware.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef GCONFLAYER_HXX_
#include "gconflayer.hxx"
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_PROPERTYINFO_HPP_
#include <com/sun/star/configuration/backend/PropertyInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERCONTENTDESCIBER_HPP_
#include <com/sun/star/configuration/backend/XLayerContentDescriber.hpp>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
//==============================================================================

GconfLayer::GconfLayer(
    const rtl::OUString& sComponent,
    const KeyMappingTable& aKeyMap,
    const rtl::OUString& sTimestamp,
    const TSMappingTable& aTSMap,
    const uno::Reference<lang::XMultiServiceFactory>& xFactory)
  : mComponent(sComponent), mKeyMap(aKeyMap),
    mTimestamp(sTimestamp), mTSMap(aTSMap),
    mFactory(xFactory)
{

}
//------------------------------------------------------------------------------
void GconfLayer::convertGconfValue(
    const GConfValue* aValue,
    uno::Any* aOOValue,
    const rtl::OUString& aOOType)
{
    sal_Bool bCorrectType = sal_True;
    switch (aValue->type)
    {
        case GCONF_VALUE_STRING:
        {
            if(aOOType != rtl::OUString::createFromAscii("string"))
            {
                bCorrectType = sal_False;
            }
            else
            {
                rtl::OUString aVal(
                    rtl::OUString::createFromAscii(gconf_value_get_string(aValue)));
                *aOOValue <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_INT:
        {
            if(aOOType != rtl::OUString::createFromAscii("int") &&
                aOOType != rtl::OUString::createFromAscii("integer"))
            {
                bCorrectType = sal_False;
            }
            else
            {
                sal_Int32 aVal = gconf_value_get_int(aValue);
                 *aOOValue <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_FLOAT:
        {
            if(aOOType != rtl::OUString::createFromAscii("double") )
            {
                bCorrectType = sal_False;
            }
            else
            {
                double aVal = gconf_value_get_float(aValue);
                 *aOOValue <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_BOOL:
        {
            if(aOOType != rtl::OUString::createFromAscii("boolean"))
            {
                bCorrectType = sal_False;
            }
            else
            {
                sal_Bool aVal = gconf_value_get_bool(aValue);
                 *aOOValue <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_LIST:
            //TODO
            break;
        case GCONF_VALUE_PAIR:
            //TODO
            break;
        case GCONF_VALUE_INVALID:
            break;

        default:
            break;
    }
    if (!bCorrectType)
     throw backend::MalformedDataException(
        rtl::OUString::createFromAscii("Gconfbe:GconfLayer: GconfType does not match StarOffice Type"),
            *this, uno::Any());

}
//------------------------------------------------------------------------------

void SAL_CALL GconfLayer::readData(
    const uno::Reference<backend::XLayerHandler>& xHandler)
    throw ( backend::MalformedDataException,
            lang::NullPointerException,
            lang::WrappedTargetException,
            uno::RuntimeException)
{
    std::vector<backend::PropertyInfo> aPropList;
    //Look up in map all keys asociated with requested OOffice Component
    //and retrieve values from Gconf
    typedef KeyMappingTable::const_iterator BFIter;
    typedef std::pair<BFIter, BFIter> BFRange;

    BFRange aRange = mKeyMap.equal_range(mComponent);
    GError* aError = NULL;
    GConfClient* aClient = NULL;
    if  (aRange.first != mKeyMap.end())
    {
        aClient = GconfBackend::getGconfClient();
    }

    while (aRange.first != aRange.second)
    {
        BFIter cur = aRange.first++;

        //Need to read data using Gconf api here

        GConfValue* aGconfValue = NULL;
        rtl::OString sKeyValue = rtl::OUStringToOString(cur->second.mGconfName, RTL_TEXTENCODING_ASCII_US);
        aGconfValue = gconf_client_get( aClient, sKeyValue.getStr(),&aError);

        if (aError == NULL)
        {

            //Fill in the ProperyInfo Struct
            backend::PropertyInfo aPropInfo;

            aPropInfo.Name = cur->second.mOOName;
            aPropInfo.Type = cur->second.mOOType;
            aPropInfo.Protected = cur->second.mbProtected;
            convertGconfValue(aGconfValue, &aPropInfo.Value,aPropInfo.Type );

            aPropList.push_back(aPropInfo);
            gconf_value_free(aGconfValue);
        }
        else
        {
            rtl::OString aErrorStr(aError->message);
            //Do nothing for now - real impl can decide whether to throw exception
            OSL_TRACE("GconfLayer cannot read data for Gconfkey:%s with message:%s",
                sKeyValue.getStr(), aError->message);
        }

    }
    if ( !aPropList.empty())
    {

        uno::Sequence<backend::PropertyInfo> aPropInfoList(aPropList.size());
        for( sal_Int32 i = 0; i < aPropList.size(); i++)
        {
            aPropInfoList[i] = aPropList[i];
        }

        //Create instance of LayerContentDescriber Service
        rtl::OUString const k_sLayerDescriberService (RTL_CONSTASCII_USTRINGPARAM(
        "com.sun.star.comp.configuration.backend.LayerDescriber"));

        typedef uno::Reference<backend::XLayerContentDescriber> LayerDescriber;
        LayerDescriber xLayerDescriber = LayerDescriber::query(
            mFactory->createInstance(k_sLayerDescriberService));

        if (xLayerDescriber.is())
        {
            xLayerDescriber->describeLayer(xHandler, aPropInfoList);
        }
        else
        {
            OSL_TRACE("Could not create com.sun.star.configuration.backend.LayerContentDescriber Service");
        }
    }

}
//------------------------------------------------------------------------------

 rtl::OUString SAL_CALL GconfLayer::getTimestamp(void)
            throw (uno::RuntimeException)
{
    TSMappingTable::const_iterator aTSIter;
    aTSIter = mTSMap.find(mComponent);
    if (aTSIter != mTSMap.end())
    {
        mTimestamp= aTSIter->second;
    }

    return mTimestamp;
}
//------------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS syssettings02 (1.2.50); FILE MERGED 2004/09/03 07:13:32 obr 1.2.50.2: #i20364#,#i20369# removed debug output 2004/09/03 06:16:04 obr 1.2.50.1: #i20364#,#i20369# gconf platform configuration backend now buildable<commit_after>/*************************************************************************
 *
 *  $RCSfile: gconflayer.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-17 13:01:14 $
 *
 *  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 OOurce 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 OOftware; 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 OOftware 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 OOftware
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards OOurce License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  OOurce 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.
 *
 *  OOftware 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 OOFTWARE 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 OOftware.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef GCONFLAYER_HXX_
#include "gconflayer.hxx"
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_PROPERTYINFO_HPP_
#include <com/sun/star/configuration/backend/PropertyInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERCONTENTDESCIBER_HPP_
#include <com/sun/star/configuration/backend/XLayerContentDescriber.hpp>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#include <stdio.h>

//==============================================================================

GconfLayer::GconfLayer(
    const rtl::OUString& aComponent,
    const rtl::OUString& aTimestamp,
    const uno::Reference<uno::XComponentContext>& xContext)
  : m_aComponent(aComponent), m_aTimestamp(aTimestamp)
{
    //Create instance of LayerContentDescriber Service
    rtl::OUString const k_sLayerDescriberService(RTL_CONSTASCII_USTRINGPARAM(
        "com.sun.star.comp.configuration.backend.LayerDescriber"));

    typedef uno::Reference<backend::XLayerContentDescriber> LayerDescriber;
    uno::Reference< lang::XMultiComponentFactory > xServiceManager = xContext->getServiceManager();
    if( xServiceManager.is() )
    {
        m_xLayerContentDescriber = LayerDescriber::query(
            xServiceManager->createInstanceWithContext(k_sLayerDescriberService, xContext));
    }
    else
    {
        OSL_TRACE("Could not retrieve ServiceManager");
    }
}

//------------------------------------------------------------------------------

/*
uno::Any GconfLayer::convertGconfValue(const GConfValue* aValue, const rtl::OUString& aOOType)
{
    uno::Any aRetVal;

    sal_Bool bCorrectType = sal_True;
    switch (aValue->type)
    {
        case GCONF_VALUE_STRING:
        {
            if(aOOType != rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("string")))
            {
                bCorrectType = sal_False;
            }
            else
            {
                rtl::OString aVal(gconf_value_get_string(aValue));
                aRetVal <<= OStringToOUString(aVal, RTL_TEXTENCODING_UTF-8);
            }
            break;
        }
        case GCONF_VALUE_INT:
        {
            if( aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("int") ) &&
                aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("integer") ) )
            {
                bCorrectType = sal_False;
            }
            else
            {
                sal_Int32 aVal = gconf_value_get_int(aValue);
                aRetVal <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_FLOAT:
        {
            if(aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("double") ) )
            {
                bCorrectType = sal_False;
            }
            else
            {
                double aVal = gconf_value_get_float(aValue);
                aRetVal <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_BOOL:
        {
            if(aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("boolean") ) )
            {
                bCorrectType = sal_False;
            }
            else
            {
                sal_Bool aVal = gconf_value_get_bool(aValue);
                aRetVal <<= aVal;
            }
            break;
        }
        case GCONF_VALUE_LIST:
            //TODO
            break;
        case GCONF_VALUE_PAIR:
            //TODO
            break;
        case GCONF_VALUE_INVALID:
            break;

        default:
            break;
    }

    if (!bCorrectType)
        throw backend::MalformedDataException( rtl::OUString(
            RTL_CONSTASCII_USTRINGPARAM("Gconfbe:GconfLayer: GconfType does not match StarOffice Type")
            ), *this, uno::Any());

}

*/

//------------------------------------------------------------------------------

void SAL_CALL GconfLayer::readData( const uno::Reference<backend::XLayerHandler>& xHandler)
    throw ( backend::MalformedDataException, lang::NullPointerException,
            lang::WrappedTargetException, uno::RuntimeException)
{

    if( m_xLayerContentDescriber.is() )
    {
        uno::Sequence<backend::PropertyInfo> aPropInfoList(5);
        sal_Int32 nProperties = 0;

        GError* aError;
        GConfClient* aClient = GconfBackend::getGconfClient();
        GConfValue* aGconfValue;

        if( m_aComponent.equalsAscii("org.openoffice.Inet" ) )
        {
            aError = NULL;
            aGconfValue = gconf_client_get(aClient, "/system/proxy/mode" , &aError);

            if( aError == NULL )
            {
                rtl::OString aMode(gconf_value_get_string(aGconfValue));

                if( aMode.equals("manual") )
                {
                    aPropInfoList[nProperties].Name = rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Inet/Settings/ooInetProxyType") );
                    aPropInfoList[nProperties].Type = rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM( "int" ) );
                    aPropInfoList[nProperties].Protected = sal_False;
                    aPropInfoList[nProperties++].Value = uno::makeAny( (sal_Int32) 1 );

                    aError = NULL;
                    aGconfValue = gconf_client_get(aClient, "/system/http_proxy/host" , &aError);

                    if( aError == NULL ) {
                        aPropInfoList[nProperties].Name = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Inet/Settings/ooInetHTTPProxyName") );
                        aPropInfoList[nProperties].Type = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "string" ) );
                        aPropInfoList[nProperties].Protected = sal_False;
                        aPropInfoList[nProperties++].Value = uno::makeAny( OStringToOUString(
                            rtl::OString( gconf_value_get_string(aGconfValue) ),
                            RTL_TEXTENCODING_UTF8 ) );
                    }

                    aError = NULL;
                    aGconfValue = gconf_client_get(aClient, "/system/http_proxy/port" , &aError);

                    if( aError == NULL ) {
                        aPropInfoList[nProperties].Name = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Inet/Settings/ooInetHTTPProxyPort") );
                        aPropInfoList[nProperties].Type = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "int" ) );
                        aPropInfoList[nProperties].Protected = sal_False;
                        aPropInfoList[nProperties++].Value = uno::makeAny(
                            (sal_Int32) gconf_value_get_int(aGconfValue) );
                    }

                    aError = NULL;
                    aGconfValue = gconf_client_get(aClient, "/system/proxy/ftp_host" , &aError);

                    if( aError == NULL ) {
                        aPropInfoList[nProperties].Name = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Inet/Settings/ooInetFTPProxyName") );
                        aPropInfoList[nProperties].Type = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "string" ) );
                        aPropInfoList[nProperties].Protected = sal_False;
                        aPropInfoList[nProperties++].Value = uno::makeAny( OStringToOUString(
                            rtl::OString( gconf_value_get_string(aGconfValue) ),
                            RTL_TEXTENCODING_UTF8 ) );
                    }

                    aError = NULL;
                    aGconfValue = gconf_client_get(aClient, "/system/proxy/ftp_port" , &aError);

                    if( aError == NULL ) {
                        aPropInfoList[nProperties].Name = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Inet/Settings/ooInetFTPProxyPort") );
                        aPropInfoList[nProperties].Type = rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM( "int" ) );
                        aPropInfoList[nProperties].Protected = sal_False;
                        aPropInfoList[nProperties++].Value = uno::makeAny(
                            (sal_Int32) gconf_value_get_int(aGconfValue) );
                    }
                }
                else if( aMode.equals("none") )
                {
                    aPropInfoList[nProperties].Name = rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Inet/Settings/ooInetProxyType") );
                    aPropInfoList[nProperties].Type = rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM( "int" ) );
                    aPropInfoList[nProperties].Protected = sal_False;
                    aPropInfoList[nProperties++].Value = uno::makeAny( (sal_Int32) 0 );
                }
            }
        }
        else if( m_aComponent.equalsAscii("org.openoffice.Office.Common" ) )
        {
            aError = NULL;
            aGconfValue = gconf_client_get(aClient, "/desktop/gnome/url-handlers/mailto/command" , &aError);

            if( aError == NULL ) {
                sal_Int32 nIndex = 0;
                aPropInfoList[nProperties].Name = rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.Office.Common/ExternalMailer/Program") );
                aPropInfoList[nProperties].Type = rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM( "string" ) );
                aPropInfoList[nProperties].Protected = sal_False;
                aPropInfoList[nProperties++].Value = uno::makeAny( OStringToOUString(
                    rtl::OString( gconf_value_get_string(aGconfValue) ).getToken(0, ' ', nIndex),
                    RTL_TEXTENCODING_UTF8 ) );
            }
        }

        aPropInfoList.realloc(nProperties);

        m_xLayerContentDescriber->describeLayer(xHandler, aPropInfoList);
    }
    else
    {
        OSL_TRACE("Could not create com.sun.star.configuration.backend.LayerContentDescriber Service");
    }
}

//------------------------------------------------------------------------------

rtl::OUString SAL_CALL GconfLayer::getTimestamp(void)
    throw (uno::RuntimeException)
{
    return m_aTimestamp;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/gtk_theme_preview_infobar_delegate.h"

#include "chrome/browser/profile.h"

GtkThemeInstalledInfoBarDelegate::GtkThemeInstalledInfoBarDelegate(
    TabContents* tab_contents,
    const std::string& name,
    const std::string& previous_theme,
    bool previous_use_gtk_theme)
    : ThemeInstalledInfoBarDelegate(tab_contents, name, previous_theme),
      previous_use_gtk_theme_(previous_use_gtk_theme) {
}

bool GtkThemeInstalledInfoBarDelegate::Cancel() {
  if (previous_use_gtk_theme_) {
    profile()->SetNativeTheme();
    return true;
  } else {
    return ThemeInstalledInfoBarDelegate::Cancel();
  }
}
<commit_msg>whee<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"

#include "chrome/browser/profile.h"

GtkThemeInstalledInfoBarDelegate::GtkThemeInstalledInfoBarDelegate(
    TabContents* tab_contents,
    const std::string& name,
    const std::string& previous_theme,
    bool previous_use_gtk_theme)
    : ThemeInstalledInfoBarDelegate(tab_contents, name, previous_theme),
      previous_use_gtk_theme_(previous_use_gtk_theme) {
}

bool GtkThemeInstalledInfoBarDelegate::Cancel() {
  if (previous_use_gtk_theme_) {
    profile()->SetNativeTheme();
    return true;
  } else {
    return ThemeInstalledInfoBarDelegate::Cancel();
  }
}
<|endoftext|>


<commit_before>#ifndef GUARD_MLOPEN_GEMM_DRIVER_HPP
#define GUARD_MLOPEN_GEMM_DRIVER_HPP

#ifndef WIN32 // so Linux and APPLE
#include <cstdlib>
#include <mlopen.h>
#include "driver.hpp"
#include "InputFlags.hpp"
#include <vector>
#include <algorithm>
#include <float.h>
#include <memory>
#include <numeric>

template<typename T>
class GemmDriver : public Driver
{
    public:
        GemmDriver() : Driver() {}

        int AddCmdLineArgs();
        int ParseCmdLineArgs(int argc, char *argv[]);
        InputFlags & GetInputFlags() { return inflags; }

        int GetandSetData();
        std::vector<int> GetInputTensorLengthsFromCmdLine();

        int AllocateBuffersAndCopy();

        int RunForwardGPU();

        int RunBackwardGPU();

        int VerifyBackward();
        int VerifyForward();
        ~GemmDriver() {}

    private:
        InputFlags inflags;

        std::unique_ptr<GPUMem> a_dev;
        std::unique_ptr<GPUMem> b_dev;
        std::unique_ptr<GPUMem> c_dev;

        std::vector<T> a;
        std::vector<T> b;
        std::vector<T> c;
        std::vector<T> chost;

        int M, N, K; // Netlib BLAS dims, user inputs
        bool transA, transB;
        T alpha, beta;

        int lda, ldb;
};

template<typename T>
int GemmDriver<T>::AddCmdLineArgs() {
    inflags.AddInputFlag("forw", 'F', "1", "Run only Forward Gemm (Default=1)", "int");
    inflags.AddInputFlag("batchsize", 'b', "1", "batch size for Gemm (Default=1)", "int");
    inflags.AddInputFlag("a_h", 'm', "256", "Height of A matrix (Default=256)", "int");
    inflags.AddInputFlag("a_w", 'k', "256", "Width of A matrix (Default=256)", "int");
    inflags.AddInputFlag("b_w", 'n', "256", "Width of B matrix (Default=256)", "int");
    inflags.AddInputFlag("alpha", 'A', "1.0", "Gemm alpha (Default=1.0)", "double");
    inflags.AddInputFlag("beta", 'B', "0.0", "Gemm beta (Default=0.0)", "double");
    inflags.AddInputFlag("transA", 'u', "0", "Transpose A matrix (Default=0)", "int");
    inflags.AddInputFlag("transB", 'v', "0", "Transpose B matrix (Default=0)", "int");
    inflags.AddInputFlag("iter", 'i', "10", "Number of Iterations (Default=10)", "int");
    inflags.AddInputFlag("verify", 'V', "0", "Verify Each Layer (Default=1)", "int");
    inflags.AddInputFlag("time", 't', "0", "Time Each Layer (Default=0)", "int");

    return 0;
}

template<typename T>
int GemmDriver<T>::ParseCmdLineArgs(int argc, char *argv[]) {
    inflags.Parse(argc, argv);

    if(inflags.GetValueInt("time") == 1) {
        mlopenEnableProfiling(GetHandle(), true);
    }
    return 0;
}

template<typename T>
int GemmDriver<T>::GetandSetData() {

    M = inflags.GetValueInt("a_h");
    K = inflags.GetValueInt("a_w");
    N = inflags.GetValueInt("b_w");

    transA = inflags.GetValueInt("transA");
    transB = inflags.GetValueInt("transB");

    alpha = inflags.GetValueDouble("alpha");
    beta = inflags.GetValueDouble("beta");

    lda = transA == 0 ? K : M;
    ldb = transB == 0 ? N : K;

    return(0);
}

template<typename T>
int GemmDriver<T>::AllocateBuffersAndCopy() {

    size_t a_sz = M*K;
    size_t b_sz = K*N;
    size_t c_sz = M*N;

    cl_context ctx;

    clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);

    a_dev = std::unique_ptr<GPUMem>( new GPUMem(ctx, a_sz, sizeof(T)));
    b_dev = std::unique_ptr<GPUMem>( new GPUMem(ctx, b_sz, sizeof(T)));
    c_dev = std::unique_ptr<GPUMem>( new GPUMem(ctx, c_sz, sizeof(T)));

    a = std::vector<T>(a_sz);
    b = std::vector<T>(b_sz);
    c = std::vector<T>(c_sz, 0.);
    chost = std::vector<T>(c_sz, 0.);

    for (int i = 0; i < a_sz; i++) {
        a[i] =  (T)((double)rand() * (1.0 / RAND_MAX));
    }

    for (int i = 0; i <b_sz; i++) {
        b[i] = (double)(rand() * (1.0 / RAND_MAX) - 0.5) * 0.001;
    }

    cl_int status;
    status = a_dev->ToGPU(q, a.data());
    status |= b_dev->ToGPU(q, b.data());
    status |= c_dev->ToGPU(q, c.data());

    if(status != CL_SUCCESS)
        printf("Error copying data to GPU\n");

    return mlopenStatusSuccess;
}

template<typename T>
int GemmDriver<T>::RunForwardGPU() {

#if MLOPEN_USE_TINYGEMM
    mlopenGemm(GetHandle(),
            false,              // isDataColMajor
            transA, transB,
            M, N, K,
            &alpha,
            a_dev->GetMem(), lda,
            b_dev->GetMem(), ldb,
            &beta,
            c_dev->GetMem(), N);

    if(inflags.GetValueInt("time") == 1) {
        float time = 0.0;
        mlopenGetKernelTime(GetHandle(), &time);
        printf("GPU Kernel Time Gemm Elapsed: %f ms\n", time);
    }

    c_dev->FromGPU(GetStream(), c.data());
#else
    std::cerr<<"GEMM is not supported\n";
#endif
    return mlopenStatusSuccess;
}

template<typename T>
int GemmDriver<T>::RunBackwardGPU() {
    return(0);
}

template<typename T>
int GemmDriver<T>::VerifyForward() {
    return 0;
}

template<typename T>
int GemmDriver<T>::VerifyBackward() {
    return 0;
}

#endif

#endif // GUARD_MLOPEN_GEMM_DRIVER_HPP
<commit_msg>removed #if<commit_after>#ifndef GUARD_MLOPEN_GEMM_DRIVER_HPP
#define GUARD_MLOPEN_GEMM_DRIVER_HPP

#include <cstdlib>
#include <mlopen.h>
#include "driver.hpp"
#include "InputFlags.hpp"
#include <vector>
#include <algorithm>
#include <float.h>
#include <memory>
#include <numeric>

template<typename T>
class GemmDriver : public Driver
{
    public:
        GemmDriver() : Driver() {}

        int AddCmdLineArgs();
        int ParseCmdLineArgs(int argc, char *argv[]);
        InputFlags & GetInputFlags() { return inflags; }

        int GetandSetData();
        std::vector<int> GetInputTensorLengthsFromCmdLine();

        int AllocateBuffersAndCopy();

        int RunForwardGPU();

        int RunBackwardGPU();

        int VerifyBackward();
        int VerifyForward();
        ~GemmDriver() {}

    private:
        InputFlags inflags;

        std::unique_ptr<GPUMem> a_dev;
        std::unique_ptr<GPUMem> b_dev;
        std::unique_ptr<GPUMem> c_dev;

        std::vector<T> a;
        std::vector<T> b;
        std::vector<T> c;
        std::vector<T> chost;

        int M, N, K; // Netlib BLAS dims, user inputs
        bool transA, transB;
        T alpha, beta;

        int lda, ldb;
};

template<typename T>
int GemmDriver<T>::AddCmdLineArgs() {
    inflags.AddInputFlag("forw", 'F', "1", "Run only Forward Gemm (Default=1)", "int");
    inflags.AddInputFlag("batchsize", 'b', "1", "batch size for Gemm (Default=1)", "int");
    inflags.AddInputFlag("a_h", 'm', "256", "Height of A matrix (Default=256)", "int");
    inflags.AddInputFlag("a_w", 'k', "256", "Width of A matrix (Default=256)", "int");
    inflags.AddInputFlag("b_w", 'n', "256", "Width of B matrix (Default=256)", "int");
    inflags.AddInputFlag("alpha", 'A', "1.0", "Gemm alpha (Default=1.0)", "double");
    inflags.AddInputFlag("beta", 'B', "0.0", "Gemm beta (Default=0.0)", "double");
    inflags.AddInputFlag("transA", 'u', "0", "Transpose A matrix (Default=0)", "int");
    inflags.AddInputFlag("transB", 'v', "0", "Transpose B matrix (Default=0)", "int");
    inflags.AddInputFlag("iter", 'i', "10", "Number of Iterations (Default=10)", "int");
    inflags.AddInputFlag("verify", 'V', "0", "Verify Each Layer (Default=1)", "int");
    inflags.AddInputFlag("time", 't', "0", "Time Each Layer (Default=0)", "int");

    return 0;
}

template<typename T>
int GemmDriver<T>::ParseCmdLineArgs(int argc, char *argv[]) {
    inflags.Parse(argc, argv);

    if(inflags.GetValueInt("time") == 1) {
        mlopenEnableProfiling(GetHandle(), true);
    }
    return 0;
}

template<typename T>
int GemmDriver<T>::GetandSetData() {

    M = inflags.GetValueInt("a_h");
    K = inflags.GetValueInt("a_w");
    N = inflags.GetValueInt("b_w");

    transA = inflags.GetValueInt("transA");
    transB = inflags.GetValueInt("transB");

    alpha = inflags.GetValueDouble("alpha");
    beta = inflags.GetValueDouble("beta");

    lda = transA == 0 ? K : M;
    ldb = transB == 0 ? N : K;

    return(0);
}

template<typename T>
int GemmDriver<T>::AllocateBuffersAndCopy() {

    size_t a_sz = M*K;
    size_t b_sz = K*N;
    size_t c_sz = M*N;

    cl_context ctx;

    clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);

    a_dev = std::unique_ptr<GPUMem>( new GPUMem(ctx, a_sz, sizeof(T)));
    b_dev = std::unique_ptr<GPUMem>( new GPUMem(ctx, b_sz, sizeof(T)));
    c_dev = std::unique_ptr<GPUMem>( new GPUMem(ctx, c_sz, sizeof(T)));

    a = std::vector<T>(a_sz);
    b = std::vector<T>(b_sz);
    c = std::vector<T>(c_sz, 0.);
    chost = std::vector<T>(c_sz, 0.);

    for (int i = 0; i < a_sz; i++) {
        a[i] =  (T)((double)rand() * (1.0 / RAND_MAX));
    }

    for (int i = 0; i <b_sz; i++) {
        b[i] = (double)(rand() * (1.0 / RAND_MAX) - 0.5) * 0.001;
    }

    cl_int status;
    status = a_dev->ToGPU(q, a.data());
    status |= b_dev->ToGPU(q, b.data());
    status |= c_dev->ToGPU(q, c.data());

    if(status != CL_SUCCESS)
        printf("Error copying data to GPU\n");

    return mlopenStatusSuccess;
}

template<typename T>
int GemmDriver<T>::RunForwardGPU() {

#if MLOPEN_USE_TINYGEMM
    mlopenGemm(GetHandle(),
            false,              // isDataColMajor
            transA, transB,
            M, N, K,
            &alpha,
            a_dev->GetMem(), lda,
            b_dev->GetMem(), ldb,
            &beta,
            c_dev->GetMem(), N);

    if(inflags.GetValueInt("time") == 1) {
        float time = 0.0;
        mlopenGetKernelTime(GetHandle(), &time);
        printf("GPU Kernel Time Gemm Elapsed: %f ms\n", time);
    }

    c_dev->FromGPU(GetStream(), c.data());
#else
    std::cerr<<"GEMM is not supported\n";
#endif
    return mlopenStatusSuccess;
}

template<typename T>
int GemmDriver<T>::RunBackwardGPU() {
    return(0);
}

template<typename T>
int GemmDriver<T>::VerifyForward() {
    return 0;
}

template<typename T>
int GemmDriver<T>::VerifyBackward() {
    return 0;
}

#endif // GUARD_MLOPEN_GEMM_DRIVER_HPP
<|endoftext|>