<commit_before>#include <iostream>
#include <string>

#include <affine_invariant_features/feature_parameters.hpp>
#include <affine_invariant_features/target.hpp>
#include <affine_invariant_features/results.hpp>
#include <affine_invariant_features/result_matcher.hpp>

#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>

namespace aif = affine_invariant_features;

bool readEverything(const std::string &path, aif::TargetData &target_data, aif::Results &results) {
  const cv::FileStorage file(path, cv::FileStorage::READ);

  aif::TargetDescription target_desc;
  file[target_desc.getDefaultName()] >> target_desc;
  target_data = target_desc.toData();
  if (target_data.image.empty()) {
    std::cerr << "Could not load an image described in " << path << std::endl;
    return false;
  }

  file[results.getDefaultName()] >> results;
  if (results.keypoints.empty() || results.descriptors.empty()) {
    std::cerr << "Could not load extracted features from " << path << std::endl;
    return false;
  }

  return true;
}

cv::Mat shadeImage(const cv::Mat &src, const cv::Mat &mask) {
  cv::Mat dst;
  if (mask.empty()) {
    dst = src.clone();
  } else {
    dst = src / 4;
    src.copyTo(dst, mask);
  }
  return dst;
}

int main(int argc, char *argv[]) {

  if (argc != 3) {
    std::cout << "Usage: match_features <feature_file1> <feature_file2>" << std::endl;
    std::cout << "Note: use extract_features to generate feature files" << std::endl;
    return 0;
  }

  const std::string feature_path1(argv[1]);
  const std::string feature_path2(argv[2]);

  aif::TargetData target1;
  aif::Results results1;
  if (!readEverything(feature_path1, target1, results1)) {
    return 1;
  }
  std::cout << "loaded " << results1.keypoints.size() << " feature points from " << feature_path1
            << std::endl;

  aif::TargetData target2;
  aif::Results results2;
  if (!readEverything(feature_path2, target2, results2)) {
    return 1;
  }
  std::cout << "loaded " << results2.keypoints.size() << " feature points from " << feature_path2
            << std::endl;

  aif::ResultMatcher matcher(results2);
  std::cout << "Matching feature points. This may take seconds." << std::endl;
  cv::Matx33f transform;
  std::vector< cv::DMatch > matches;
  matcher.match(results1, transform, matches);
  std::cout << "found " << matches.size() << " matches" << std::endl;

  const cv::Mat image1(shadeImage(target1.image, target1.mask));
  const cv::Mat image2(shadeImage(target2.image, target2.mask));
  cv::Mat image;
  cv::drawMatches(image1, results1.keypoints, image2, results2.keypoints, matches, image);

  std::cout << "Showing feature points and matches. Press any key to continue." << std::endl;
  cv::imshow("Matches", image);
  cv::waitKey(0);

  return 0;
}
<commit_msg>refactor match_features<commit_after>#include <iostream>
#include <string>

#include <affine_invariant_features/feature_parameters.hpp>
#include <affine_invariant_features/target.hpp>
#include <affine_invariant_features/results.hpp>
#include <affine_invariant_features/result_matcher.hpp>

#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>

namespace aif = affine_invariant_features;

bool readEverything(const std::string &path, aif::TargetData &target_data, aif::Results &results) {
  const cv::FileStorage file(path, cv::FileStorage::READ);
  if (!file.isOpened()) {
    std::cerr << "Could not open " << path << std::endl;
    return false;
  }

  aif::TargetDescription target_desc;
  file[target_desc.getDefaultName()] >> target_desc;
  if (target_desc.imagePath.empty()) {
    std::cerr << "Could not load an image path from " << path << std::endl;
    return false;
  }

  target_data = target_desc.toData();
  if (target_data.image.empty()) {
    std::cerr << "Could not load an image described in " << path << std::endl;
    return false;
  }

  file[results.getDefaultName()] >> results;
  if (results.keypoints.empty() || results.descriptors.empty()) {
    std::cerr << "Could not load extracted features from " << path << std::endl;
    return false;
  }

  return true;
}

cv::Mat shadeImage(const cv::Mat &src, const cv::Mat &mask) {
  cv::Mat dst;
  if (mask.empty()) {
    dst = src.clone();
  } else {
    dst = src / 4;
    src.copyTo(dst, mask);
  }
  return dst;
}

int main(int argc, char *argv[]) {

  const cv::CommandLineParser args(
      argc, argv, "{ help | | }"
                  "{ @feature-file1 | <none> | can be generated by extract_features }"
                  "{ @feature-file2 | <none> | can be generated by extract_features }");

  if (args.has("help")) {
    args.printMessage();
    return 0;
  }

  const std::string feature_path1(args.get< std::string >("@feature-file1"));
  const std::string feature_path2(args.get< std::string >("@feature-file2"));
  if (!args.check()) {
    args.printErrors();
    return 1;
  }

  aif::TargetData target1;
  aif::Results results1;
  if (!readEverything(feature_path1, target1, results1)) {
    return 1;
  }
  std::cout << "loaded " << results1.keypoints.size() << " feature points from " << feature_path1
            << std::endl;

  aif::TargetData target2;
  aif::Results results2;
  if (!readEverything(feature_path2, target2, results2)) {
    return 1;
  }
  std::cout << "loaded " << results2.keypoints.size() << " feature points from " << feature_path2
            << std::endl;

  aif::ResultMatcher matcher(results2);
  std::cout << "Matching feature points. This may take seconds." << std::endl;
  cv::Matx33f transform;
  std::vector< cv::DMatch > matches;
  matcher.match(results1, transform, matches);
  std::cout << "found " << matches.size() << " matches" << std::endl;

  const cv::Mat image1(shadeImage(target1.image, target1.mask));
  const cv::Mat image2(shadeImage(target2.image, target2.mask));
  cv::Mat image;
  cv::drawMatches(image1, results1.keypoints, image2, results2.keypoints, matches, image);

  std::cout << "Showing feature points and matches. Press any key to continue." << std::endl;
  cv::imshow("Matches", image);
  cv::waitKey(0);

  return 0;
}
<|endoftext|>


<commit_before>/** \file    add_superior_and_alertable_flags.cc
 *  \author  Oliver Obenland
 *  \author  Dr. Johannes Ruscheinski
 *
 *  A tool for marking superior records that have associated inferior records in our data sets.
 */

/*
    Copyright (C) 2016-2018, 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 <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "FileUtil.h"
#include "MARC.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
    std::exit(EXIT_FAILURE);
}

void LoadSuperiorPPNs(MARC::Reader * const marc_reader, std::unordered_set<std::string> * const superior_ppns) {
    const std::vector<std::string> TAGS{ "800", "810", "830", "773", "776"};
    while (const MARC::Record record = marc_reader->read()) {
        for (const auto &tag : TAGS) {
            for (const auto &field : record.getTagRange(tag)) {
                const MARC::Subfields subfields(field.getSubfields());
                const std::string subfield_w_contents(subfields.getFirstSubfieldWithCode('w'));
                if (StringUtil::StartsWith(subfield_w_contents, "(DE-576)")) {
                    if (tag != "776" or subfields.getFirstSubfieldWithCode('i') != "Erscheint auch als")
                        superior_ppns->emplace(subfield_w_contents.substr(__builtin_strlen("(DE-576)")));
                }
            }
        }
    }

    INFO("Found " + std::to_string(superior_ppns->size()) + " superior PPNs.");
}

bool SeriesHasNotBeenCompleted(const MARC::Record &record) {
    const auto _008_field(record.getFirstField("008"));
    if (unlikely(_008_field == record.end()))
        return false;

    return _008_field->getContents().substr(11, 4) == "9999";
}

void ProcessRecord(MARC::Writer * const marc_writer, const std::unordered_set<std::string> &superior_ppns,
                   MARC::Record * const record, unsigned * const modified_count)
{
    // Don't add the flag twice:
    if (record->getFirstField("SPR") != record->end()) {
        marc_writer->write(*record);
        return;
    }

    MARC::Subfields superior_subfields;

    // Set the we are a "superior" record, if appropriate:
    const auto iter(superior_ppns.find(record->getControlNumber()));
    if (iter != superior_ppns.end())
        superior_subfields.addSubfield('a', "1"); // Could be anything but we can't have an empty field.

    // Set the, you-can-subscribe-to-this flag, if appropriate:
    if (record->isSerial() and SeriesHasNotBeenCompleted(*record))
        superior_subfields.addSubfield('b', "1");

    if (not superior_subfields.empty()) {
        record->insertField("SPR", superior_subfields.toString());
        ++*modified_count;
    }

    marc_writer->write(*record);
}

void AddSuperiorFlag(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
                     const std::unordered_set<std::string> &superior_ppns)
{
    unsigned modified_count(0);
    while (MARC::Record record = marc_reader->read())
        ProcessRecord(marc_writer, superior_ppns, &record, &modified_count);

    INFO("Modified " + std::to_string(modified_count) + " record(s).");
}

} // unnamed namespace

int main(int argc, char **argv) {
    ::progname = argv[0];

    if (argc != 3)
        Usage();

    const std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[1]));
    const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[2]));

    try {
        std::unordered_set<std::string> superior_ppns;
        LoadSuperiorPPNs(marc_reader.get(), &superior_ppns);
        marc_reader->rewind();
        AddSuperiorFlag(marc_reader.get(), marc_writer.get(), superior_ppns);
    } catch (const std::exception &x) {
        ERROR("caught exception: " + std::string(x.what()));
    }
}
<commit_msg>Added missing indicators.<commit_after>/** \file    add_superior_and_alertable_flags.cc
 *  \author  Oliver Obenland
 *  \author  Dr. Johannes Ruscheinski
 *
 *  A tool for marking superior records that have associated inferior records in our data sets.
 */

/*
    Copyright (C) 2016-2018, 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 <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "FileUtil.h"
#include "MARC.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
    std::exit(EXIT_FAILURE);
}

void LoadSuperiorPPNs(MARC::Reader * const marc_reader, std::unordered_set<std::string> * const superior_ppns) {
    const std::vector<std::string> TAGS{ "800", "810", "830", "773", "776"};
    while (const MARC::Record record = marc_reader->read()) {
        for (const auto &tag : TAGS) {
            for (const auto &field : record.getTagRange(tag)) {
                const MARC::Subfields subfields(field.getSubfields());
                const std::string subfield_w_contents(subfields.getFirstSubfieldWithCode('w'));
                if (StringUtil::StartsWith(subfield_w_contents, "(DE-576)")) {
                    if (tag != "776" or subfields.getFirstSubfieldWithCode('i') != "Erscheint auch als")
                        superior_ppns->emplace(subfield_w_contents.substr(__builtin_strlen("(DE-576)")));
                }
            }
        }
    }

    INFO("Found " + std::to_string(superior_ppns->size()) + " superior PPNs.");
}

bool SeriesHasNotBeenCompleted(const MARC::Record &record) {
    const auto _008_field(record.getFirstField("008"));
    if (unlikely(_008_field == record.end()))
        return false;

    return _008_field->getContents().substr(11, 4) == "9999";
}

void ProcessRecord(MARC::Writer * const marc_writer, const std::unordered_set<std::string> &superior_ppns,
                   MARC::Record * const record, unsigned * const modified_count)
{
    // Don't add the flag twice:
    if (record->getFirstField("SPR") != record->end()) {
        marc_writer->write(*record);
        return;
    }

    MARC::Subfields superior_subfields;

    // Set the we are a "superior" record, if appropriate:
    const auto iter(superior_ppns.find(record->getControlNumber()));
    if (iter != superior_ppns.end())
        superior_subfields.addSubfield('a', "1"); // Could be anything but we can't have an empty field.

    // Set the, you-can-subscribe-to-this flag, if appropriate:
    if (record->isSerial() and SeriesHasNotBeenCompleted(*record))
        superior_subfields.addSubfield('b', "1");

    if (not superior_subfields.empty()) {
        record->insertField("SPR", /* indicators = */"  " + superior_subfields.toString());
        ++*modified_count;
    }

    marc_writer->write(*record);
}

void AddSuperiorFlag(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
                     const std::unordered_set<std::string> &superior_ppns)
{
    unsigned modified_count(0);
    while (MARC::Record record = marc_reader->read())
        ProcessRecord(marc_writer, superior_ppns, &record, &modified_count);

    INFO("Modified " + std::to_string(modified_count) + " record(s).");
}

} // unnamed namespace

int main(int argc, char **argv) {
    ::progname = argv[0];

    if (argc != 3)
        Usage();

    const std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[1]));
    const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[2]));

    try {
        std::unordered_set<std::string> superior_ppns;
        LoadSuperiorPPNs(marc_reader.get(), &superior_ppns);
        marc_reader->rewind();
        AddSuperiorFlag(marc_reader.get(), marc_writer.get(), superior_ppns);
    } catch (const std::exception &x) {
        ERROR("caught exception: " + std::string(x.what()));
    }
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#pragma once

#include "exceptions/exceptions.hh"
#include "core/print.hh"
#include "core/sstring.hh"

#include <experimental/optional>
#include <unordered_map>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <set>

#include <boost/any.hpp>

namespace cql3 {

namespace statements {

class property_definitions {
protected:
#if 0
    protected static final Logger logger = LoggerFactory.getLogger(PropertyDefinitions.class);
#endif
    std::unordered_map<sstring, boost::any> _properties;

    property_definitions()
        : _properties{}
    { }
public:
    void add_property(const sstring& name, sstring value) {
        auto it = _properties.find(name);
        if (it != _properties.end()) {
            throw exceptions::syntax_exception(sprint("Multiple definition for property '%s'", name));
        }
        _properties.emplace(name, value);
    }

    void add_property(const sstring& name, const std::map<sstring, sstring>& value) {
        auto it = _properties.find(name);
        if (it != _properties.end()) {
            throw exceptions::syntax_exception(sprint("Multiple definition for property '%s'", name));
        }
        _properties.emplace(name, value);
    }

    void validate(const std::set<sstring>& keywords, const std::set<sstring>& obsolete) {
        for (auto&& kv : _properties) {
            auto&& name = kv.first;
            if (keywords.count(name)) {
                continue;
            }
            if (obsolete.count(name)) {
#if 0
                logger.warn("Ignoring obsolete property {}", name);
#endif
            } else {
                throw exceptions::syntax_exception(sprint("Unknown property '%s'", name));
            }
        }
    }
protected:
    std::experimental::optional<sstring> get_simple(const sstring& name) const {
        auto it = _properties.find(name);
        if (it == _properties.end()) {
            return std::experimental::nullopt;
        }
        try {
            return boost::any_cast<sstring>(it->second);
        } catch (const boost::bad_any_cast& e) {
            throw exceptions::syntax_exception(sprint("Invalid value for property '%s'. It should be a string", name));
        }
    }

    std::experimental::optional<std::map<sstring, sstring>> get_map(const sstring& name) const {
        auto it = _properties.find(name);
        if (it == _properties.end()) {
            return std::experimental::nullopt;
        }
        try {
            return boost::any_cast<std::map<sstring, sstring>>(it->second);
        } catch (const boost::bad_any_cast& e) {
            throw exceptions::syntax_exception(sprint("Invalid value for property '%s'. It should be a map.", name));
        }
    }
public:
    bool has_property(const sstring& name) const {
        return _properties.find(name) != _properties.end();
    }

    sstring get_string(sstring key, sstring default_value) const {
        auto value = get_simple(key);
        if (value) {
            return value.value();
        } else {
            return default_value;
        }
    }

    // Return a property value, typed as a Boolean
    bool get_boolean(sstring key, bool default_value) const {
        auto value = get_simple(key);
        if (value) {
            std::string s{value.value()};
            std::transform(s.begin(), s.end(), s.begin(), ::tolower);
            return s == "1" || s == "true" || s == "yes";
        } else {
            return default_value;
        }
    }

    // Return a property value, typed as a double
    double get_double(sstring key, double default_value) const {
        auto value = get_simple(key);
        if (value) {
            auto val = value.value();
            try {
                return std::stod(val);
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sprint("Invalid double value %s for '%s'", val, key));
            }
        } else {
            return default_value;
        }
    }

    // Return a property value, typed as an Integer
    int32_t get_int(sstring key, int32_t default_value) const {
        auto value = get_simple(key);
        return to_int(key, value, default_value);
    }

    static int32_t to_int(sstring key, std::experimental::optional<sstring> value, int32_t default_value) {
        if (value) {
            auto val = value.value();
            try {
                return std::stoi(val);
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sprint("Invalid integer value %s for '%s'", val, key));
            }
        } else {
            return default_value;
        }
    }
};

}

}
<commit_msg>cql3: add static function to_double to property_definitions<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#pragma once

#include "exceptions/exceptions.hh"
#include "core/print.hh"
#include "core/sstring.hh"

#include <experimental/optional>
#include <unordered_map>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <set>

#include <boost/any.hpp>

namespace cql3 {

namespace statements {

class property_definitions {
protected:
#if 0
    protected static final Logger logger = LoggerFactory.getLogger(PropertyDefinitions.class);
#endif
    std::unordered_map<sstring, boost::any> _properties;

    property_definitions()
        : _properties{}
    { }
public:
    void add_property(const sstring& name, sstring value) {
        auto it = _properties.find(name);
        if (it != _properties.end()) {
            throw exceptions::syntax_exception(sprint("Multiple definition for property '%s'", name));
        }
        _properties.emplace(name, value);
    }

    void add_property(const sstring& name, const std::map<sstring, sstring>& value) {
        auto it = _properties.find(name);
        if (it != _properties.end()) {
            throw exceptions::syntax_exception(sprint("Multiple definition for property '%s'", name));
        }
        _properties.emplace(name, value);
    }

    void validate(const std::set<sstring>& keywords, const std::set<sstring>& obsolete) {
        for (auto&& kv : _properties) {
            auto&& name = kv.first;
            if (keywords.count(name)) {
                continue;
            }
            if (obsolete.count(name)) {
#if 0
                logger.warn("Ignoring obsolete property {}", name);
#endif
            } else {
                throw exceptions::syntax_exception(sprint("Unknown property '%s'", name));
            }
        }
    }
protected:
    std::experimental::optional<sstring> get_simple(const sstring& name) const {
        auto it = _properties.find(name);
        if (it == _properties.end()) {
            return std::experimental::nullopt;
        }
        try {
            return boost::any_cast<sstring>(it->second);
        } catch (const boost::bad_any_cast& e) {
            throw exceptions::syntax_exception(sprint("Invalid value for property '%s'. It should be a string", name));
        }
    }

    std::experimental::optional<std::map<sstring, sstring>> get_map(const sstring& name) const {
        auto it = _properties.find(name);
        if (it == _properties.end()) {
            return std::experimental::nullopt;
        }
        try {
            return boost::any_cast<std::map<sstring, sstring>>(it->second);
        } catch (const boost::bad_any_cast& e) {
            throw exceptions::syntax_exception(sprint("Invalid value for property '%s'. It should be a map.", name));
        }
    }
public:
    bool has_property(const sstring& name) const {
        return _properties.find(name) != _properties.end();
    }

    sstring get_string(sstring key, sstring default_value) const {
        auto value = get_simple(key);
        if (value) {
            return value.value();
        } else {
            return default_value;
        }
    }

    // Return a property value, typed as a Boolean
    bool get_boolean(sstring key, bool default_value) const {
        auto value = get_simple(key);
        if (value) {
            std::string s{value.value()};
            std::transform(s.begin(), s.end(), s.begin(), ::tolower);
            return s == "1" || s == "true" || s == "yes";
        } else {
            return default_value;
        }
    }

    // Return a property value, typed as a double
    double get_double(sstring key, double default_value) const {
        auto value = get_simple(key);
        return to_double(key, value, default_value);
    }

    static double to_double(sstring key, std::experimental::optional<sstring> value, double default_value) {
        if (value) {
            auto val = value.value();
            try {
                return std::stod(val);
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sprint("Invalid double value %s for '%s'", val, key));
            }
        } else {
            return default_value;
        }
    }

    // Return a property value, typed as an Integer
    int32_t get_int(sstring key, int32_t default_value) const {
        auto value = get_simple(key);
        return to_int(key, value, default_value);
    }

    static int32_t to_int(sstring key, std::experimental::optional<sstring> value, int32_t default_value) {
        if (value) {
            auto val = value.value();
            try {
                return std::stoi(val);
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sprint("Invalid integer value %s for '%s'", val, key));
            }
        } else {
            return default_value;
        }
    }
};

}

}
<|endoftext|>


<commit_before>//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Flight Systems and Automatic Control group,
//       TU Darmstadt, nor the names of its contributors may be used to
//       endorse or promote products derived from this software without
//       specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>

class Teleop
{
private:
  ros::NodeHandle node_handle_;
  ros::Subscriber joy_subscriber_;

  ros::Publisher velocity_publisher_;
  geometry_msgs::Twist velocity_;

  struct Axis
  {
    int axis;
    double max;
  };

  struct Button
  {
    int button;
  };

  struct
  {
    Axis x;
    Axis y;
    Axis z;
    Axis yaw;
  } axes_;

public:
  Teleop()
  {
    ros::NodeHandle params("~");

    params.param<int>("x_axis", axes_.x.axis, 4);
    params.param<int>("y_axis", axes_.y.axis, 3);
    params.param<int>("z_axis", axes_.z.axis, 2);
    params.param<int>("yaw_axis", axes_.yaw.axis, 1);

    params.param<double>("yaw_velocity_max", axes_.yaw.max, 90.0 * M_PI / 180.0);

    params.param<double>("x_velocity_max", axes_.x.max, 2.0);
    params.param<double>("y_velocity_max", axes_.y.max, 2.0);
    params.param<double>("z_velocity_max", axes_.z.max, 2.0);

    joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyTwistCallback, this, _1));
    velocity_publisher_ = node_handle_.advertise<geometry_msgs::Twist>("cmd_vel", 10);
  }

  ~Teleop()
  {
    stop();
  }

  void joyTwistCallback(const sensor_msgs::JoyConstPtr &joy)
  {
    velocity_.linear.x = getAxis(joy, axes_.x);
    velocity_.linear.y = getAxis(joy, axes_.y);
    velocity_.linear.z = getAxis(joy, axes_.z);
    velocity_.angular.z = getAxis(joy, axes_.yaw);
    velocity_publisher_.publish(velocity_);
  }

  sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr &joy, Axis axis)
  {
    if (axis.axis == 0)
    {return 0;}
    sensor_msgs::Joy::_axes_type::value_type sign = 1.0;
    if (axis.axis < 0)
    {
      sign = -1.0;
      axis.axis = -axis.axis;
    }
    if ((size_t) axis.axis > joy->axes.size())
    {return 0;}
    return sign * joy->axes[axis.axis - 1] * axis.max;
  }

  sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr &joy, int button)
  {
    if (button <= 0)
    {return 0;}
    if ((size_t) button > joy->buttons.size())
    {return 0;}
    return joy->buttons[button - 1];
  }

  void stop()
  {
    if(velocity_publisher_.getNumSubscribers() > 0)
    {
      velocity_ = geometry_msgs::Twist();
      velocity_publisher_.publish(velocity_);
    }
  }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "quadrotor_teleop");

  Teleop teleop;
  ros::spin();

  return 0;
}
<commit_msg>teleop: send cmd_vel at fixed frequency<commit_after>//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
//               2018, Wolfgang Hoenig, USC
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Flight Systems and Automatic Control group,
//       TU Darmstadt, nor the names of its contributors may be used to
//       endorse or promote products derived from this software without
//       specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//=================================================================================================

#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>

class Teleop
{
private:
  ros::NodeHandle node_handle_;
  ros::Subscriber joy_subscriber_;

  ros::Publisher velocity_publisher_;
  geometry_msgs::Twist velocity_;

  struct Axis
  {
    int axis;
    double max;
  };

  struct Button
  {
    int button;
  };

  struct
  {
    Axis x;
    Axis y;
    Axis z;
    Axis yaw;
  } axes_;

  double frequency_;

public:
  Teleop()
  {
    ros::NodeHandle params("~");

    params.param<int>("x_axis", axes_.x.axis, 4);
    params.param<int>("y_axis", axes_.y.axis, 3);
    params.param<int>("z_axis", axes_.z.axis, 2);
    params.param<int>("yaw_axis", axes_.yaw.axis, 1);

    params.param<double>("yaw_velocity_max", axes_.yaw.max, 90.0 * M_PI / 180.0);

    params.param<double>("x_velocity_max", axes_.x.max, 2.0);
    params.param<double>("y_velocity_max", axes_.y.max, 2.0);
    params.param<double>("z_velocity_max", axes_.z.max, 2.0);

    params.param<double>("frequency", frequency_, 100);

    joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyTwistCallback, this, _1));
    velocity_publisher_ = node_handle_.advertise<geometry_msgs::Twist>("cmd_vel", 10);
  }

  ~Teleop()
  {
    stop();
  }

  void execute()
  {
    ros::Rate loop_rate(frequency_);
    while (ros::ok()) {
      velocity_publisher_.publish(velocity_);

      ros::spinOnce();
      loop_rate.sleep();
    }
  }

  void joyTwistCallback(const sensor_msgs::JoyConstPtr &joy)
  {
    velocity_.linear.x = getAxis(joy, axes_.x);
    velocity_.linear.y = getAxis(joy, axes_.y);
    velocity_.linear.z = getAxis(joy, axes_.z);
    velocity_.angular.z = getAxis(joy, axes_.yaw);
  }

  sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr &joy, Axis axis)
  {
    if (axis.axis == 0) {
      return 0;
    }
    sensor_msgs::Joy::_axes_type::value_type sign = 1.0;
    if (axis.axis < 0) {
      sign = -1.0;
      axis.axis = -axis.axis;
    }
    if ((size_t) axis.axis > joy->axes.size()) {
      return 0;
    }
    return sign * joy->axes[axis.axis - 1] * axis.max;
  }

  sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr &joy, int button)
  {
    if (button <= 0) {
      return 0;
    }
    if ((size_t) button > joy->buttons.size()) {
      return 0;
    }
    return joy->buttons[button - 1];
  }

  void stop()
  {
    if(velocity_publisher_.getNumSubscribers() > 0) {
      velocity_ = geometry_msgs::Twist();
      velocity_publisher_.publish(velocity_);
    }
  }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "quadrotor_teleop");

  Teleop teleop;
  teleop.execute();

  return 0;
}
<|endoftext|>


<commit_before>//===- lib/Clang/DotGraph.cpp ---------------------------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#include "seec/Clang/DotGraph.hpp"
#include "seec/Clang/MappedAllocaState.hpp"
#include "seec/Clang/MappedMallocState.hpp"
#include "seec/Clang/MappedFunctionState.hpp"
#include "seec/Clang/MappedGlobalVariable.hpp"
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedProcessTrace.hpp"
#include "seec/Clang/MappedThreadState.hpp"
#include "seec/Clang/MappedValue.hpp"
#include "seec/Trace/ProcessState.hpp"
#include "seec/Trace/ThreadState.hpp"
#include "seec/Trace/TraceReader.hpp"

#include "llvm/ADT/StringRef.h"

#include <set>
#include <string>

namespace seec {

namespace cm {

std::string EscapeForHTML(llvm::StringRef String)
{
  std::string Escaped;
  Escaped.reserve(String.size());

  for (auto const Char : String) {
    if (std::isalnum(Char))
      Escaped.push_back(Char);
    else {
      Escaped.push_back('&');
      Escaped.push_back('#');

      if (Char > 99) {
        Escaped.push_back('0' + ( Char        / 100));
        Escaped.push_back('0' + ((Char % 100) / 10 ));
        Escaped.push_back('0' + ( Char % 10        ));
      }
      else if (Char > 9) {
        Escaped.push_back('0' + (Char / 10));
        Escaped.push_back('0' + (Char % 10));
      }

      Escaped.push_back(';');
    }
  }

  return Escaped;
}

std::string getPortFor(seec::cm::Value const &Value)
{
  std::string Port = "addr";
  {
    // Use the Value's address rather than the runtime address, because it also
    // specifies the type of the value (this should allow us to handle, e.g.
    // pointers to different members of a union that occupy the same address).
    llvm::raw_string_ostream Stream {Port};
    Stream << reinterpret_cast<uintptr_t>(&Value);
  }
  return Port;
}

class Node {
  std::string Identifier;

  std::set<uintptr_t> Ports;

public:
  Node(std::string WithIdentifier)
  : Identifier(std::move(WithIdentifier))
  {}

  std::string const &getIdentifier() const { return Identifier; }

  void addPort(seec::cm::Value const &ForValue) {
    Ports.emplace(reinterpret_cast<uintptr_t>(&ForValue));
  }

  bool hasPort(seec::cm::Value const &ForValue) const {
    return Ports.count(reinterpret_cast<uintptr_t>(&ForValue));
  }

  /// pre: hasPort(ForValue) == true
  ///
  std::string getEdgeEndForPort(seec::cm::Value const &ForValue) const {
    return Identifier + ":" + getPortFor(ForValue);
  }
};

typedef std::pair<std::shared_ptr<seec::cm::Value const>,
                  std::shared_ptr<seec::cm::Value const>> Edge;

void WritePort(seec::cm::Value const &Value,
               llvm::raw_ostream &Stream,
               Node &InNode)
{
  Stream << " PORT=\"" << getPortFor(Value) << "\"";
  InNode.addPort(Value);
}

void WriteDot(std::shared_ptr<seec::cm::Value const> Value,
              llvm::raw_ostream &Stream,
              Node &InNode,
              std::set<Edge> &AllEdges)
{
  if (!Value)
    return;

  switch (Value->getKind()) {
    case seec::cm::Value::Kind::Basic:
      {
        Stream << EscapeForHTML(Value->getValueAsStringFull());
      }
      break;

    case seec::cm::Value::Kind::Array:
      {
        auto const Array = llvm::cast<seec::cm::ValueOfArray>(Value.get());
        unsigned const ChildCount = Array->getChildCount();

        Stream << "
";

        for (unsigned i = 0; i < ChildCount; ++i) {
          auto const ChildValue = Array->getChildAt(i);

          Stream << "
";
          Stream << "<TD";
          WritePort(*ChildValue, Stream, InNode);
          Stream << ">[" << i << "]	";

          Stream << "";
          WriteDot(ChildValue, Stream, InNode, AllEdges);
          Stream << "	";
          Stream << "
";
        }

        Stream << "
";
      }
      break;

    case seec::cm::Value::Kind::Record:
      {
        auto const Record = llvm::cast<seec::cm::ValueOfRecord>(Value.get());
        unsigned const ChildCount = Record->getChildCount();

        Stream << "
";

        for (unsigned i = 0; i < ChildCount; ++i) {
          auto const ChildValue = Record->getChildAt(i);

          Stream << "
";
          Stream << "<TD";
          WritePort(*ChildValue, Stream, InNode);
          Stream << ">";
          auto const ChildField = Record->getChildField(i);
          if (ChildField)
            Stream << "." << Record->getChildField(i)->getName();
          Stream << "	";

          Stream << "";
          WriteDot(ChildValue, Stream, InNode, AllEdges);
          Stream << "	";
          Stream << "
";
        }

        Stream << "
";
      }
      break;

    case seec::cm::Value::Kind::Pointer:
      {
        Stream << " ";

        auto const Pointer = llvm::cast<seec::cm::ValueOfPointer>(Value.get());
        unsigned const DerefLimit = Pointer->getDereferenceIndexLimit();

        llvm::errs() << "writing pointer with limit = " << DerefLimit << "\n";

        for (unsigned i = 0; i < DerefLimit; ++i) {
          auto const Pointee = Pointer->getDereferenced(i);

          llvm::errs() << "recording edge.\n";

          auto const Inserted = AllEdges.emplace(Value, Pointee);

          if (!Inserted.second)
            llvm::errs() << "emplace failed.\n";
        }
      }
      break;
  }
}

void WriteDot(seec::cm::AllocaState const &State,
              llvm::raw_ostream &Stream,
              Node &InNode,
              std::set<Edge> &AllEdges)
{
  auto const Value = State.getValue();

  Stream << "
"
         << State.getDecl()->getNameAsString()
         << "	<TD ALIGN=\"LEFT\"";
  WritePort(*Value, Stream, InNode);
  Stream << ">";
  WriteDot(State.getValue(), Stream, InNode, AllEdges);
  Stream << "
";
}

void WriteDot(seec::cm::FunctionState const &State,
              llvm::raw_ostream &Stream,
              std::vector<Node> &FunctionNodes,
              std::set<Edge> &AllEdges)
{
  std::string NodeIdentifier;

  {
    llvm::raw_string_ostream NodeIdentifierStream {NodeIdentifier};
    NodeIdentifierStream << "function" << reinterpret_cast<uintptr_t>(&State);
  }

  Stream << NodeIdentifier
         << " [ label = <
";

  Stream << "
"
         << State.getNameAsString()
         << "
";

  FunctionNodes.emplace_back(std::move(NodeIdentifier));

  for (auto const &Parameter : State.getParameters())
    WriteDot(Parameter, Stream, FunctionNodes.back(), AllEdges);

  for (auto const &Local : State.getLocals())
    WriteDot(Local, Stream, FunctionNodes.back(), AllEdges);

  Stream << "
 > ];\n";
}

/// \brief Write the dot describing a ThreadState.
///
void WriteDot(seec::cm::ThreadState const &State,
              llvm::raw_ostream &Stream,
              std::vector<Node> &AllNodes,
              std::set<Edge> &AllEdges)
{
  auto const ID = State.getUnmappedState().getTrace().getThreadID();
  std::vector<Node> FunctionNodes;

  Stream << "subgraph thread" << ID << " {\n";
  Stream << "node [shape=plaintext];\n";

  for (auto const &FunctionState : State.getCallStack()) {
    WriteDot(FunctionState, Stream, FunctionNodes, AllEdges);
  }

  Stream << "{ rank=same; ";
  for (auto const &FunctionNode : FunctionNodes)
    Stream << FunctionNode.getIdentifier() << "; ";
  Stream << "};\n";

  Stream << "}\n";

  // Add the function nodes to the global list of nodes.
  AllNodes.insert(AllNodes.end(), FunctionNodes.begin(), FunctionNodes.end());
}

/// \brief Write the dot describing a GlobalVariable.
///
void writeDot(seec::cm::GlobalVariable const &State,
              llvm::raw_ostream &Stream,
              std::vector<Node> &AllNodes,
              std::set<Edge> &AllEdges)
{
  std::string NodeIdentifier = "global";
  {
    llvm::raw_string_ostream Stream { NodeIdentifier };
    Stream << State.getAddress();
  }

  Stream << NodeIdentifier
         << " [ label = <
"
         << "
"
         << State.getClangValueDecl()->getName()
         << "	";

  AllNodes.emplace_back(std::move(NodeIdentifier));

  auto const Value = State.getValue();

  Stream << "<TD";
  if (Value)
    WritePort(*Value, Stream, AllNodes.back());
  Stream << ">";
  WriteDot(Value, Stream, AllNodes.back(), AllEdges);
  Stream << "

 > ];\n";
}

/// \brief Write a graph in dot format describing a complete ProcessState.
///
void writeDotGraph(seec::cm::ProcessState const &State,
                   llvm::raw_ostream &Stream)
{
  Stream << "digraph Process {\n";
  Stream << "node [shape=plaintext];\n";
  Stream << "rankdir=LR;\n";

  std::vector<Node> AllNodes;
  std::set<Edge> AllEdges;

  // Write all threads.
  for (std::size_t i = 0; i < State.getThreadCount(); ++i) {
    WriteDot(State.getThread(i), Stream, AllNodes, AllEdges);
  }

  // Write global variables.
  for (auto const &Global : State.getGlobalVariables()) {
    writeDot(Global, Stream, AllNodes, AllEdges);
  }

  // Write all referenced, but non-present nodes.
  // One possible method for this is to expand all Value objects, then filter
  // them according to the mallocs they belong to, then draw the mallocs as
  // nodes. Finally we would need to draw Values that existed in Known memory
  // (non-alloca, non-malloc, non-global).

  llvm::errs() << "got " << AllEdges.size() << " edges.\n";

  // Write edges.
  for (auto const &E : AllEdges) {
    auto const NodeStart =
      std::find_if(AllNodes.begin(),
                   AllNodes.end(),
                   [&E] (Node const &N) { return N.hasPort(*(E.first)); });

    auto const NodeEnd =
      std::find_if(AllNodes.begin(),
                   AllNodes.end(),
                   [&E] (Node const &N) { return N.hasPort(*(E.second)); });

    if (NodeStart == AllNodes.end() || NodeEnd == AllNodes.end()) {
      llvm::errs() << "couldn't find start and end for edge.\n";
      continue;
    }

    Stream << NodeStart->getEdgeEndForPort(*(E.first))
           << ":c -> "
           << NodeEnd->getEdgeEndForPort(*(E.second))
           << ";\n";
  }

  Stream << "}\n";
}

} // namespace cm

} // namespace seec
<commit_msg>Fix compilation under GCC 4.7 on Ubuntu.<commit_after>//===- lib/Clang/DotGraph.cpp ---------------------------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#include "seec/Clang/DotGraph.hpp"
#include "seec/Clang/MappedAllocaState.hpp"
#include "seec/Clang/MappedMallocState.hpp"
#include "seec/Clang/MappedFunctionState.hpp"
#include "seec/Clang/MappedGlobalVariable.hpp"
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedProcessTrace.hpp"
#include "seec/Clang/MappedThreadState.hpp"
#include "seec/Clang/MappedValue.hpp"
#include "seec/Trace/ProcessState.hpp"
#include "seec/Trace/ThreadState.hpp"
#include "seec/Trace/TraceReader.hpp"

#include "llvm/ADT/StringRef.h"

#include <set>
#include <string>

namespace seec {

namespace cm {

std::string EscapeForHTML(llvm::StringRef String)
{
  std::string Escaped;
  Escaped.reserve(String.size());

  for (auto const Char : String) {
    if (std::isalnum(Char))
      Escaped.push_back(Char);
    else {
      Escaped.push_back('&');
      Escaped.push_back('#');

      if (Char > 99) {
        Escaped.push_back('0' + ( Char        / 100));
        Escaped.push_back('0' + ((Char % 100) / 10 ));
        Escaped.push_back('0' + ( Char % 10        ));
      }
      else if (Char > 9) {
        Escaped.push_back('0' + (Char / 10));
        Escaped.push_back('0' + (Char % 10));
      }

      Escaped.push_back(';');
    }
  }

  return Escaped;
}

std::string getPortFor(seec::cm::Value const &Value)
{
  std::string Port = "addr";
  {
    // Use the Value's address rather than the runtime address, because it also
    // specifies the type of the value (this should allow us to handle, e.g.
    // pointers to different members of a union that occupy the same address).
    llvm::raw_string_ostream Stream {Port};
    Stream << reinterpret_cast<uintptr_t>(&Value);
  }
  return Port;
}

class Node {
  std::string Identifier;

  std::set<uintptr_t> Ports;

public:
  Node(std::string WithIdentifier)
  : Identifier(std::move(WithIdentifier))
  {}

  std::string const &getIdentifier() const { return Identifier; }

  void addPort(seec::cm::Value const &ForValue) {
    Ports.insert(reinterpret_cast<uintptr_t>(&ForValue));
  }

  bool hasPort(seec::cm::Value const &ForValue) const {
    return Ports.count(reinterpret_cast<uintptr_t>(&ForValue));
  }

  /// pre: hasPort(ForValue) == true
  ///
  std::string getEdgeEndForPort(seec::cm::Value const &ForValue) const {
    return Identifier + ":" + getPortFor(ForValue);
  }
};

typedef std::pair<std::shared_ptr<seec::cm::Value const>,
                  std::shared_ptr<seec::cm::Value const>> Edge;

void WritePort(seec::cm::Value const &Value,
               llvm::raw_ostream &Stream,
               Node &InNode)
{
  Stream << " PORT=\"" << getPortFor(Value) << "\"";
  InNode.addPort(Value);
}

void WriteDot(std::shared_ptr<seec::cm::Value const> Value,
              llvm::raw_ostream &Stream,
              Node &InNode,
              std::set<Edge> &AllEdges)
{
  if (!Value)
    return;

  switch (Value->getKind()) {
    case seec::cm::Value::Kind::Basic:
      {
        Stream << EscapeForHTML(Value->getValueAsStringFull());
      }
      break;

    case seec::cm::Value::Kind::Array:
      {
        auto const Array = llvm::cast<seec::cm::ValueOfArray>(Value.get());
        unsigned const ChildCount = Array->getChildCount();

        Stream << "
";

        for (unsigned i = 0; i < ChildCount; ++i) {
          auto const ChildValue = Array->getChildAt(i);

          Stream << "
";
          Stream << "<TD";
          WritePort(*ChildValue, Stream, InNode);
          Stream << ">[" << i << "]	";

          Stream << "";
          WriteDot(ChildValue, Stream, InNode, AllEdges);
          Stream << "	";
          Stream << "
";
        }

        Stream << "
";
      }
      break;

    case seec::cm::Value::Kind::Record:
      {
        auto const Record = llvm::cast<seec::cm::ValueOfRecord>(Value.get());
        unsigned const ChildCount = Record->getChildCount();

        Stream << "
";

        for (unsigned i = 0; i < ChildCount; ++i) {
          auto const ChildValue = Record->getChildAt(i);

          Stream << "
";
          Stream << "<TD";
          WritePort(*ChildValue, Stream, InNode);
          Stream << ">";
          auto const ChildField = Record->getChildField(i);
          if (ChildField)
            Stream << "." << Record->getChildField(i)->getName();
          Stream << "	";

          Stream << "";
          WriteDot(ChildValue, Stream, InNode, AllEdges);
          Stream << "	";
          Stream << "
";
        }

        Stream << "
";
      }
      break;

    case seec::cm::Value::Kind::Pointer:
      {
        Stream << " ";

        auto const Pointer = llvm::cast<seec::cm::ValueOfPointer>(Value.get());
        unsigned const DerefLimit = Pointer->getDereferenceIndexLimit();

        llvm::errs() << "writing pointer with limit = " << DerefLimit << "\n";

        for (unsigned i = 0; i < DerefLimit; ++i) {
          auto const Pointee = Pointer->getDereferenced(i);
          AllEdges.insert(std::make_pair(Value, Pointee));
        }
      }
      break;
  }
}

void WriteDot(seec::cm::AllocaState const &State,
              llvm::raw_ostream &Stream,
              Node &InNode,
              std::set<Edge> &AllEdges)
{
  auto const Value = State.getValue();

  Stream << "
"
         << State.getDecl()->getNameAsString()
         << "	<TD ALIGN=\"LEFT\"";
  WritePort(*Value, Stream, InNode);
  Stream << ">";
  WriteDot(State.getValue(), Stream, InNode, AllEdges);
  Stream << "
";
}

void WriteDot(seec::cm::FunctionState const &State,
              llvm::raw_ostream &Stream,
              std::vector<Node> &FunctionNodes,
              std::set<Edge> &AllEdges)
{
  std::string NodeIdentifier;

  {
    llvm::raw_string_ostream NodeIdentifierStream {NodeIdentifier};
    NodeIdentifierStream << "function" << reinterpret_cast<uintptr_t>(&State);
  }

  Stream << NodeIdentifier
         << " [ label = <
";

  Stream << "
"
         << State.getNameAsString()
         << "
";

  FunctionNodes.emplace_back(std::move(NodeIdentifier));

  for (auto const &Parameter : State.getParameters())
    WriteDot(Parameter, Stream, FunctionNodes.back(), AllEdges);

  for (auto const &Local : State.getLocals())
    WriteDot(Local, Stream, FunctionNodes.back(), AllEdges);

  Stream << "
 > ];\n";
}

/// \brief Write the dot describing a ThreadState.
///
void WriteDot(seec::cm::ThreadState const &State,
              llvm::raw_ostream &Stream,
              std::vector<Node> &AllNodes,
              std::set<Edge> &AllEdges)
{
  auto const ID = State.getUnmappedState().getTrace().getThreadID();
  std::vector<Node> FunctionNodes;

  Stream << "subgraph thread" << ID << " {\n";
  Stream << "node [shape=plaintext];\n";

  for (auto const &FunctionState : State.getCallStack()) {
    WriteDot(FunctionState, Stream, FunctionNodes, AllEdges);
  }

  Stream << "{ rank=same; ";
  for (auto const &FunctionNode : FunctionNodes)
    Stream << FunctionNode.getIdentifier() << "; ";
  Stream << "};\n";

  Stream << "}\n";

  // Add the function nodes to the global list of nodes.
  AllNodes.insert(AllNodes.end(), FunctionNodes.begin(), FunctionNodes.end());
}

/// \brief Write the dot describing a GlobalVariable.
///
void writeDot(seec::cm::GlobalVariable const &State,
              llvm::raw_ostream &Stream,
              std::vector<Node> &AllNodes,
              std::set<Edge> &AllEdges)
{
  std::string NodeIdentifier = "global";
  {
    llvm::raw_string_ostream Stream { NodeIdentifier };
    Stream << State.getAddress();
  }

  Stream << NodeIdentifier
         << " [ label = <
"
         << "
"
         << State.getClangValueDecl()->getName()
         << "	";

  AllNodes.emplace_back(std::move(NodeIdentifier));

  auto const Value = State.getValue();

  Stream << "<TD";
  if (Value)
    WritePort(*Value, Stream, AllNodes.back());
  Stream << ">";
  WriteDot(Value, Stream, AllNodes.back(), AllEdges);
  Stream << "

 > ];\n";
}

/// \brief Write a graph in dot format describing a complete ProcessState.
///
void writeDotGraph(seec::cm::ProcessState const &State,
                   llvm::raw_ostream &Stream)
{
  Stream << "digraph Process {\n";
  Stream << "node [shape=plaintext];\n";
  Stream << "rankdir=LR;\n";

  std::vector<Node> AllNodes;
  std::set<Edge> AllEdges;

  // Write all threads.
  for (std::size_t i = 0; i < State.getThreadCount(); ++i) {
    WriteDot(State.getThread(i), Stream, AllNodes, AllEdges);
  }

  // Write global variables.
  for (auto const &Global : State.getGlobalVariables()) {
    writeDot(Global, Stream, AllNodes, AllEdges);
  }

  // Write all referenced, but non-present nodes.
  // One possible method for this is to expand all Value objects, then filter
  // them according to the mallocs they belong to, then draw the mallocs as
  // nodes. Finally we would need to draw Values that existed in Known memory
  // (non-alloca, non-malloc, non-global).

  llvm::errs() << "got " << AllEdges.size() << " edges.\n";

  // Write edges.
  for (auto const &E : AllEdges) {
    auto const NodeStart =
      std::find_if(AllNodes.begin(),
                   AllNodes.end(),
                   [&E] (Node const &N) { return N.hasPort(*(E.first)); });

    auto const NodeEnd =
      std::find_if(AllNodes.begin(),
                   AllNodes.end(),
                   [&E] (Node const &N) { return N.hasPort(*(E.second)); });

    if (NodeStart == AllNodes.end() || NodeEnd == AllNodes.end()) {
      llvm::errs() << "couldn't find start and end for edge.\n";
      continue;
    }

    Stream << NodeStart->getEdgeEndForPort(*(E.first))
           << ":c -> "
           << NodeEnd->getEdgeEndForPort(*(E.second))
           << ";\n";
  }

  Stream << "}\n";
}

} // namespace cm

} // namespace seec
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 The Native Client 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 <fcntl.h>
#include <cstring>

#include "native_client/src/include/build_config.h"

#if NACL_WINDOWS
# include <io.h>
#endif

#include "native_client/src/public/chrome_main.h"
#include "native_client/src/public/nacl_app.h"
#include "native_client/src/public/nacl_desc.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/shared/platform/nacl_threads.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "native_client/src/trusted/desc/nacl_desc_custom.h"
#include "native_client/src/trusted/desc/nacl_desc_file_info.h"
#include "native_client/src/trusted/nonnacl_util/sel_ldr_launcher.h"
#include "native_client/src/trusted/service_runtime/include/sys/fcntl.h"
#include "native_client/src/trusted/service_runtime/nacl_all_modules.h"
#include "native_client/src/trusted/service_runtime/nacl_config.h"
#include "native_client/src/trusted/service_runtime/nacl_valgrind_hooks.h"
#include "native_client/src/trusted/service_runtime/sel_addrspace.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/validator/validation_cache.h"

// A global variable that specifies whether or not the test should set
// the irt_load_optional flag in NaClChromeMainArgs.
bool g_irt_load_optional = false;
const char kIrtLoadOptional[] = "--irt_load_optional";

// A global variable that specifies whether or not to test validation
// caching of the main nexe.
bool g_test_validation_cache = false;
const char kTestValidationCache[] = "--test_validation_cache";

int OpenFileReadOnly(const char *filename) {
#if NACL_WINDOWS
  return _open(filename, _O_RDONLY);
#else
  return open(filename, O_RDONLY);
#endif
}

NaClHandle OpenFileHandleReadExec(const char *filename) {
#if NACL_WINDOWS
  return CreateFileA(filename,
                     GENERIC_READ | GENERIC_EXECUTE,
                     FILE_SHARE_READ,
                     NULL,
                     OPEN_EXISTING,
                     FILE_ATTRIBUTE_NORMAL,
                     NULL);
#else
  return open(filename, O_RDONLY);
#endif
}

// This launcher class does not actually launch a process, but we
// reuse SelLdrLauncherBase in order to use its helper methods.
class DummyLauncher : public nacl::SelLdrLauncherBase {
 public:
  explicit DummyLauncher(NaClHandle channel) {
    channel_ = channel;
  }

  virtual bool Start(const char *url) {
    UNREFERENCED_PARAMETER(url);
    return true;
  }
};

struct TestValidationQuery {
  bool known_to_validate;
};

static void *TestCreateQuery(void *handle) {
  UNREFERENCED_PARAMETER(handle);
  return static_cast<void *>(new TestValidationQuery());
}

static void TestAddData(void *query, const unsigned char *data,
                        size_t length) {
  UNREFERENCED_PARAMETER(query);
  UNREFERENCED_PARAMETER(data);
  UNREFERENCED_PARAMETER(length);
}

static int TestQueryKnownToValidate(void *query) {
  TestValidationQuery *s = static_cast<TestValidationQuery *>(query);
  return s->known_to_validate;
}

static void TestSetKnownToValidate(void *query) {
  TestValidationQuery *s = static_cast<TestValidationQuery *>(query);
  s->known_to_validate = 1;
}

static void TestDestroyQuery(void *query) {
  delete static_cast<TestValidationQuery *>(query);
}

static int TestCachingIsInexpensive(const struct NaClValidationMetadata *m) {
  UNREFERENCED_PARAMETER(m);
  return 1;
}

static int TestResolveFileToken(void *handle, struct NaClFileToken *file_token,
                                int32_t *fd, char **file_path,
                                uint32_t *file_path_length) {
  // We don't expect ResolveFileToken() to be used any more.
  // TODO(mseaborn): Remove ResolveFileToken() entirely.
  UNREFERENCED_PARAMETER(handle);
  UNREFERENCED_PARAMETER(file_token);
  UNREFERENCED_PARAMETER(fd);
  UNREFERENCED_PARAMETER(file_path);
  UNREFERENCED_PARAMETER(file_path_length);
  CHECK(false);
  return 0;
}

struct ThreadArgs {
  NaClHandle channel;
  NaClFileInfo file_info;
};

void WINAPI DummyRendererThread(void *thread_arg) {
  struct ThreadArgs *args = (struct ThreadArgs *) thread_arg;

  DummyLauncher launcher(args->channel);
  NaClSrpcChannel trusted_channel;
  NaClSrpcChannel untrusted_channel;
  CHECK(launcher.SetupCommand(&trusted_channel));
  CHECK(launcher.StartModuleAndSetupAppChannel(&trusted_channel,
                                               &untrusted_channel));
}

void ExampleDescDestroy(void *handle) {
  UNREFERENCED_PARAMETER(handle);
}

ssize_t ExampleDescSendMsg(void *handle,
                           const struct NaClImcTypedMsgHdr *msg,
                           int flags) {
  UNREFERENCED_PARAMETER(handle);
  UNREFERENCED_PARAMETER(msg);
  UNREFERENCED_PARAMETER(flags);

  NaClLog(LOG_FATAL, "ExampleDescSendMsg: Not implemented\n");
  return 0;
}

ssize_t ExampleDescRecvMsg(void *handle,
                           struct NaClImcTypedMsgHdr *msg,
                           int flags) {
  UNREFERENCED_PARAMETER(handle);
  UNREFERENCED_PARAMETER(msg);
  UNREFERENCED_PARAMETER(flags);

  NaClLog(LOG_FATAL, "ExampleDescRecvMsg: Not implemented\n");
  return 0;
}

struct NaClDesc *MakeExampleDesc() {
  struct NaClDescCustomFuncs funcs = NACL_DESC_CUSTOM_FUNCS_INITIALIZER;
  funcs.Destroy = ExampleDescDestroy;
  funcs.SendMsg = ExampleDescSendMsg;
  funcs.RecvMsg = ExampleDescRecvMsg;
  return NaClDescMakeCustomDesc(NULL, &funcs);
}

// Process commandline options and return the index where non-option
// commandline arguments begin. Assumes all options are in the front.
int NaClHandleArguments(int argc, char **argv) {
  static const struct TestArguments {
    const char *flag_name;
    bool *flag_reference;
    bool value_to_set;
  } long_opts[] = {
    {kIrtLoadOptional, &g_irt_load_optional, true},
    {kTestValidationCache, &g_test_validation_cache, true},
    {NULL, NULL, false}
  };
  int cur_arg = 1;
  while (cur_arg < argc) {
    int i = 0;
    bool matched = false;
    while (long_opts[i].flag_name != NULL) {
      if (strcmp(long_opts[i].flag_name, argv[cur_arg]) == 0) {
        *long_opts[i].flag_reference = long_opts[i].value_to_set;
        ++cur_arg;
        matched = true;
        break;
      }
      ++i;
    }
    if (!matched) {
      return cur_arg;
    }
  }
  return cur_arg;
}

int main(int argc, char **argv) {
  // Note that we deliberately do not call NaClAllModulesInit() here,
  // in order to mimic what we expect the Chromium side to do.
  NaClChromeMainInit();
  struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
  struct NaClApp *nap = NaClAppCreate();
  struct ThreadArgs thread_args;

  NaClHandleBootstrapArgs(&argc, &argv);
  int last_option_index = NaClHandleArguments(argc, argv);
#if NACL_LINUX
  args->prereserved_sandbox_size = g_prereserved_sandbox_size;
#endif
  // There should be two more arguments after parsing the optional ones.
  if (last_option_index + 2 != argc) {
    NaClLog(
        LOG_FATAL,
        "NaClHandleArguments stopped at opt %d (expected %d == argc(%d)-2\n",
        last_option_index, argc - 2, argc);
  }
  const char *irt_filename = argv[last_option_index];
  const char *nexe_filename = argv[last_option_index + 1];

  NaClLog(LOG_INFO,
          "SelMainChromeTest configuration:\n"
          "g_irt_load_optional: %d\n"
          "g_test_validation_cache: %d\n",
          g_irt_load_optional, g_test_validation_cache);

  args->irt_fd = OpenFileReadOnly(irt_filename);
  args->irt_load_optional = g_irt_load_optional;
  CHECK(args->irt_fd >= 0);

  memset(&thread_args.file_info, 0, sizeof thread_args.file_info);
  thread_args.file_info.desc = OpenFileReadOnly(nexe_filename);
  CHECK(thread_args.file_info.desc >= 0);
  NaClFileNameForValgrind(nexe_filename);

  NaClHandle socketpair[2];
  CHECK(NaClSocketPair(socketpair) == 0);
  args->imc_bootstrap_handle = socketpair[0];
  thread_args.channel = socketpair[1];

  // Check that NaClDescMakeCustomDesc() works when called in this context.
  NaClAppSetDesc(nap, NACL_CHROME_DESC_BASE, MakeExampleDesc());

  // Set up mock validation cache.
  struct NaClValidationCache test_cache;
  if (g_test_validation_cache) {
    test_cache.handle = NULL;
    test_cache.CreateQuery = &TestCreateQuery;
    test_cache.AddData = &TestAddData;
    test_cache.QueryKnownToValidate = &TestQueryKnownToValidate;
    test_cache.SetKnownToValidate = &TestSetKnownToValidate;
    test_cache.DestroyQuery = &TestDestroyQuery;
    test_cache.CachingIsInexpensive = &TestCachingIsInexpensive;
    test_cache.ResolveFileToken = &TestResolveFileToken;
    args->validation_cache = &test_cache;
  }
  NaClHandle nexe_handle = OpenFileHandleReadExec(nexe_filename);
  args->nexe_desc = NaClDescCreateWithFilePathMetadata(nexe_handle,
                                                       "dummy_pathname");

  NaClThread thread;
  CHECK(NaClThreadCtor(&thread, DummyRendererThread, &thread_args,
                       NACL_KERN_STACK_SIZE));

  NaClChromeMainStartApp(nap, args);
  NaClLog(LOG_FATAL, "NaClChromeMainStartApp() should never return\n");
  return 1;
}
<commit_msg>Remove now-unused file_info thread argument in sel_main_chrome_test.cc<commit_after>/*
 * Copyright (c) 2012 The Native Client 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 <fcntl.h>
#include <cstring>

#include "native_client/src/include/build_config.h"

#if NACL_WINDOWS
# include <io.h>
#endif

#include "native_client/src/public/chrome_main.h"
#include "native_client/src/public/nacl_app.h"
#include "native_client/src/public/nacl_desc.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/shared/platform/nacl_threads.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "native_client/src/trusted/desc/nacl_desc_custom.h"
#include "native_client/src/trusted/nonnacl_util/sel_ldr_launcher.h"
#include "native_client/src/trusted/service_runtime/include/sys/fcntl.h"
#include "native_client/src/trusted/service_runtime/nacl_all_modules.h"
#include "native_client/src/trusted/service_runtime/nacl_config.h"
#include "native_client/src/trusted/service_runtime/nacl_valgrind_hooks.h"
#include "native_client/src/trusted/service_runtime/sel_addrspace.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/validator/validation_cache.h"

// A global variable that specifies whether or not the test should set
// the irt_load_optional flag in NaClChromeMainArgs.
bool g_irt_load_optional = false;
const char kIrtLoadOptional[] = "--irt_load_optional";

// A global variable that specifies whether or not to test validation
// caching of the main nexe.
bool g_test_validation_cache = false;
const char kTestValidationCache[] = "--test_validation_cache";

int OpenFileReadOnly(const char *filename) {
#if NACL_WINDOWS
  return _open(filename, _O_RDONLY);
#else
  return open(filename, O_RDONLY);
#endif
}

NaClHandle OpenFileHandleReadExec(const char *filename) {
#if NACL_WINDOWS
  return CreateFileA(filename,
                     GENERIC_READ | GENERIC_EXECUTE,
                     FILE_SHARE_READ,
                     NULL,
                     OPEN_EXISTING,
                     FILE_ATTRIBUTE_NORMAL,
                     NULL);
#else
  return open(filename, O_RDONLY);
#endif
}

// This launcher class does not actually launch a process, but we
// reuse SelLdrLauncherBase in order to use its helper methods.
class DummyLauncher : public nacl::SelLdrLauncherBase {
 public:
  explicit DummyLauncher(NaClHandle channel) {
    channel_ = channel;
  }

  virtual bool Start(const char *url) {
    UNREFERENCED_PARAMETER(url);
    return true;
  }
};

struct TestValidationQuery {
  bool known_to_validate;
};

static void *TestCreateQuery(void *handle) {
  UNREFERENCED_PARAMETER(handle);
  return static_cast<void *>(new TestValidationQuery());
}

static void TestAddData(void *query, const unsigned char *data,
                        size_t length) {
  UNREFERENCED_PARAMETER(query);
  UNREFERENCED_PARAMETER(data);
  UNREFERENCED_PARAMETER(length);
}

static int TestQueryKnownToValidate(void *query) {
  TestValidationQuery *s = static_cast<TestValidationQuery *>(query);
  return s->known_to_validate;
}

static void TestSetKnownToValidate(void *query) {
  TestValidationQuery *s = static_cast<TestValidationQuery *>(query);
  s->known_to_validate = 1;
}

static void TestDestroyQuery(void *query) {
  delete static_cast<TestValidationQuery *>(query);
}

static int TestCachingIsInexpensive(const struct NaClValidationMetadata *m) {
  UNREFERENCED_PARAMETER(m);
  return 1;
}

static int TestResolveFileToken(void *handle, struct NaClFileToken *file_token,
                                int32_t *fd, char **file_path,
                                uint32_t *file_path_length) {
  // We don't expect ResolveFileToken() to be used any more.
  // TODO(mseaborn): Remove ResolveFileToken() entirely.
  UNREFERENCED_PARAMETER(handle);
  UNREFERENCED_PARAMETER(file_token);
  UNREFERENCED_PARAMETER(fd);
  UNREFERENCED_PARAMETER(file_path);
  UNREFERENCED_PARAMETER(file_path_length);
  CHECK(false);
  return 0;
}

struct ThreadArgs {
  NaClHandle channel;
};

void WINAPI DummyRendererThread(void *thread_arg) {
  struct ThreadArgs *args = (struct ThreadArgs *) thread_arg;

  DummyLauncher launcher(args->channel);
  NaClSrpcChannel trusted_channel;
  NaClSrpcChannel untrusted_channel;
  CHECK(launcher.SetupCommand(&trusted_channel));
  CHECK(launcher.StartModuleAndSetupAppChannel(&trusted_channel,
                                               &untrusted_channel));
}

void ExampleDescDestroy(void *handle) {
  UNREFERENCED_PARAMETER(handle);
}

ssize_t ExampleDescSendMsg(void *handle,
                           const struct NaClImcTypedMsgHdr *msg,
                           int flags) {
  UNREFERENCED_PARAMETER(handle);
  UNREFERENCED_PARAMETER(msg);
  UNREFERENCED_PARAMETER(flags);

  NaClLog(LOG_FATAL, "ExampleDescSendMsg: Not implemented\n");
  return 0;
}

ssize_t ExampleDescRecvMsg(void *handle,
                           struct NaClImcTypedMsgHdr *msg,
                           int flags) {
  UNREFERENCED_PARAMETER(handle);
  UNREFERENCED_PARAMETER(msg);
  UNREFERENCED_PARAMETER(flags);

  NaClLog(LOG_FATAL, "ExampleDescRecvMsg: Not implemented\n");
  return 0;
}

struct NaClDesc *MakeExampleDesc() {
  struct NaClDescCustomFuncs funcs = NACL_DESC_CUSTOM_FUNCS_INITIALIZER;
  funcs.Destroy = ExampleDescDestroy;
  funcs.SendMsg = ExampleDescSendMsg;
  funcs.RecvMsg = ExampleDescRecvMsg;
  return NaClDescMakeCustomDesc(NULL, &funcs);
}

// Process commandline options and return the index where non-option
// commandline arguments begin. Assumes all options are in the front.
int NaClHandleArguments(int argc, char **argv) {
  static const struct TestArguments {
    const char *flag_name;
    bool *flag_reference;
    bool value_to_set;
  } long_opts[] = {
    {kIrtLoadOptional, &g_irt_load_optional, true},
    {kTestValidationCache, &g_test_validation_cache, true},
    {NULL, NULL, false}
  };
  int cur_arg = 1;
  while (cur_arg < argc) {
    int i = 0;
    bool matched = false;
    while (long_opts[i].flag_name != NULL) {
      if (strcmp(long_opts[i].flag_name, argv[cur_arg]) == 0) {
        *long_opts[i].flag_reference = long_opts[i].value_to_set;
        ++cur_arg;
        matched = true;
        break;
      }
      ++i;
    }
    if (!matched) {
      return cur_arg;
    }
  }
  return cur_arg;
}

int main(int argc, char **argv) {
  // Note that we deliberately do not call NaClAllModulesInit() here,
  // in order to mimic what we expect the Chromium side to do.
  NaClChromeMainInit();
  struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
  struct NaClApp *nap = NaClAppCreate();
  struct ThreadArgs thread_args;

  NaClHandleBootstrapArgs(&argc, &argv);
  int last_option_index = NaClHandleArguments(argc, argv);
#if NACL_LINUX
  args->prereserved_sandbox_size = g_prereserved_sandbox_size;
#endif
  // There should be two more arguments after parsing the optional ones.
  if (last_option_index + 2 != argc) {
    NaClLog(
        LOG_FATAL,
        "NaClHandleArguments stopped at opt %d (expected %d == argc(%d)-2\n",
        last_option_index, argc - 2, argc);
  }
  const char *irt_filename = argv[last_option_index];
  const char *nexe_filename = argv[last_option_index + 1];

  NaClLog(LOG_INFO,
          "SelMainChromeTest configuration:\n"
          "g_irt_load_optional: %d\n"
          "g_test_validation_cache: %d\n",
          g_irt_load_optional, g_test_validation_cache);

  args->irt_fd = OpenFileReadOnly(irt_filename);
  args->irt_load_optional = g_irt_load_optional;
  CHECK(args->irt_fd >= 0);

  NaClFileNameForValgrind(nexe_filename);

  NaClHandle socketpair[2];
  CHECK(NaClSocketPair(socketpair) == 0);
  args->imc_bootstrap_handle = socketpair[0];
  thread_args.channel = socketpair[1];

  // Check that NaClDescMakeCustomDesc() works when called in this context.
  NaClAppSetDesc(nap, NACL_CHROME_DESC_BASE, MakeExampleDesc());

  // Set up mock validation cache.
  struct NaClValidationCache test_cache;
  if (g_test_validation_cache) {
    test_cache.handle = NULL;
    test_cache.CreateQuery = &TestCreateQuery;
    test_cache.AddData = &TestAddData;
    test_cache.QueryKnownToValidate = &TestQueryKnownToValidate;
    test_cache.SetKnownToValidate = &TestSetKnownToValidate;
    test_cache.DestroyQuery = &TestDestroyQuery;
    test_cache.CachingIsInexpensive = &TestCachingIsInexpensive;
    test_cache.ResolveFileToken = &TestResolveFileToken;
    args->validation_cache = &test_cache;
  }
  NaClHandle nexe_handle = OpenFileHandleReadExec(nexe_filename);
  args->nexe_desc = NaClDescCreateWithFilePathMetadata(nexe_handle,
                                                       "dummy_pathname");

  NaClThread thread;
  CHECK(NaClThreadCtor(&thread, DummyRendererThread, &thread_args,
                       NACL_KERN_STACK_SIZE));

  NaClChromeMainStartApp(nap, args);
  NaClLog(LOG_FATAL, "NaClChromeMainStartApp() should never return\n");
  return 1;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: curledit.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:33:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

//.........................................................................
namespace dbaui
{
//.........................................................................
    DBG_NAME(OConnectionURLEdit)
//=========================================================================
//= OConnectionURLEdit
//=========================================================================
//-------------------------------------------------------------------------
OConnectionURLEdit::OConnectionURLEdit(Window* _pParent, WinBits _nStyle,BOOL _bShowPrefix)
    :Edit(_pParent, _nStyle)
    ,m_pForcedPrefix(NULL)
    ,m_bShowPrefix(_bShowPrefix)
{
    DBG_CTOR(OConnectionURLEdit ,NULL);
}

//-------------------------------------------------------------------------
OConnectionURLEdit::OConnectionURLEdit(Window* _pParent, const ResId& _rResId,BOOL _bShowPrefix)
    :Edit(_pParent, _rResId)
    ,m_pForcedPrefix(NULL)
    ,m_bShowPrefix(_bShowPrefix)
{
    DBG_CTOR(OConnectionURLEdit ,NULL);
}

//-------------------------------------------------------------------------
OConnectionURLEdit::~OConnectionURLEdit()
{
    DBG_DTOR(OConnectionURLEdit ,NULL);
    // delete my sub controls
    Edit* pSubEdit = GetSubEdit();
    SetSubEdit(NULL);
    delete pSubEdit;
    delete m_pForcedPrefix;
}

//-------------------------------------------------------------------------
void OConnectionURLEdit::SetTextNoPrefix(const String& _rText)
{
    DBG_ASSERT(GetSubEdit(), "OConnectionURLEdit::SetTextNoPrefix: have no current type, not changing the text!");
    if (GetSubEdit())
        GetSubEdit()->SetText(_rText);
}

//-------------------------------------------------------------------------
String OConnectionURLEdit::GetTextNoPrefix() const
{
    if (GetSubEdit())
        return GetSubEdit()->GetText();
    return GetText();
}

//-------------------------------------------------------------------------
void OConnectionURLEdit::SetText(const String& _rStr)
{
    Selection aNoSelection(0,0);
    SetText(_rStr, aNoSelection);
}

//-------------------------------------------------------------------------
void OConnectionURLEdit::SetText(const String& _rStr, const Selection& _rNewSelection)
{
    // create new sub controls, if necessary
    if (!GetSubEdit())
        SetSubEdit(new Edit(this, 0));
    if ( !m_pForcedPrefix )
    {
        m_pForcedPrefix = new FixedText(this, WB_VCENTER);

        // we use a gray background for the fixed text
        StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings();
        m_pForcedPrefix->SetBackground(Wallpaper(aSystemStyle.GetDialogColor()));
    }

    m_pForcedPrefix->Show(m_bShowPrefix);

    sal_Bool bIsEmpty = 0 == _rStr.Len();
    // calc the prefix
    String sPrefix;
    if (!bIsEmpty)
    {
        // determine the type of the new URL described by the new text
        DATASOURCE_TYPE eType = m_aTypeCollection.getType(_rStr);
        // and the prefix belonging to this type
        if (DST_UNKNOWN != eType)
            sPrefix = m_aTypeCollection.getDatasourcePrefix(eType);
        else
            DBG_ERROR("OConnectionURLEdit::SetText : the new text is no valid connection URL!");
    }

    // the fixed text gets the prefix
    if ( m_pForcedPrefix )
        m_pForcedPrefix->SetText(sPrefix);

    // both subs have to be resized according to the text len of the prefix
    Size aMySize = GetSizePixel();
    sal_Int32 nTextWidth = 0;
    if ( m_pForcedPrefix && m_bShowPrefix)
    {
        nTextWidth = m_pForcedPrefix->GetTextWidth(sPrefix) + 2;
        m_pForcedPrefix->SetPosSizePixel(Point(0, -2), Size(nTextWidth, aMySize.Height()));
    }
    GetSubEdit()->SetPosSizePixel(Point(nTextWidth, -2), Size(aMySize.Width() - nTextWidth - 4, aMySize.Height()));
        // -2 because the edit has a frame which is 2 pixel wide ... should not be necessary, but I don't fully understand this ....

    // show the sub controls (in case they were just created)
    GetSubEdit()->Show();

    // do the real SetTex
//  Edit::SetText(bIsEmpty ? _rStr : m_aTypeCollection.cutPrefix(_rStr), _rNewSelection);
    String sNewText( _rStr );
    if ( !bIsEmpty )
        sNewText  =m_aTypeCollection.cutPrefix( _rStr );
    Edit::SetText( sNewText );
}

//-------------------------------------------------------------------------
String OConnectionURLEdit::GetText() const
{
    if ( m_pForcedPrefix )
        return m_pForcedPrefix->GetText() += Edit::GetText();
    return Edit::GetText();
}
// -----------------------------------------------------------------------------
void OConnectionURLEdit::ShowPrefix(BOOL _bShowPrefix)
{
    m_bShowPrefix = _bShowPrefix;
    if ( m_pForcedPrefix )
        m_pForcedPrefix->Show(m_bShowPrefix);
}
//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>INTEGRATION: CWS warnings01 (1.9.50); FILE MERGED 2006/03/24 15:36:06 fs 1.9.50.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: curledit.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 02:59:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

//.........................................................................
namespace dbaui
{
//.........................................................................
    DBG_NAME(OConnectionURLEdit)
//=========================================================================
//= OConnectionURLEdit
//=========================================================================
//-------------------------------------------------------------------------
OConnectionURLEdit::OConnectionURLEdit(Window* _pParent, WinBits _nStyle,BOOL _bShowPrefix)
    :Edit(_pParent, _nStyle)
    ,m_pForcedPrefix(NULL)
    ,m_bShowPrefix(_bShowPrefix)
{
    DBG_CTOR(OConnectionURLEdit ,NULL);
}

//-------------------------------------------------------------------------
OConnectionURLEdit::OConnectionURLEdit(Window* _pParent, const ResId& _rResId,BOOL _bShowPrefix)
    :Edit(_pParent, _rResId)
    ,m_pForcedPrefix(NULL)
    ,m_bShowPrefix(_bShowPrefix)
{
    DBG_CTOR(OConnectionURLEdit ,NULL);
}

//-------------------------------------------------------------------------
OConnectionURLEdit::~OConnectionURLEdit()
{
    DBG_DTOR(OConnectionURLEdit ,NULL);
    // delete my sub controls
    Edit* pSubEdit = GetSubEdit();
    SetSubEdit(NULL);
    delete pSubEdit;
    delete m_pForcedPrefix;
}

//-------------------------------------------------------------------------
void OConnectionURLEdit::SetTextNoPrefix(const String& _rText)
{
    DBG_ASSERT(GetSubEdit(), "OConnectionURLEdit::SetTextNoPrefix: have no current type, not changing the text!");
    if (GetSubEdit())
        GetSubEdit()->SetText(_rText);
}

//-------------------------------------------------------------------------
String OConnectionURLEdit::GetTextNoPrefix() const
{
    if (GetSubEdit())
        return GetSubEdit()->GetText();
    return GetText();
}

//-------------------------------------------------------------------------
void OConnectionURLEdit::SetText(const String& _rStr)
{
    Selection aNoSelection(0,0);
    SetText(_rStr, aNoSelection);
}

//-------------------------------------------------------------------------
void OConnectionURLEdit::SetText(const String& _rStr, const Selection& /*_rNewSelection*/)
{
    // create new sub controls, if necessary
    if (!GetSubEdit())
        SetSubEdit(new Edit(this, 0));
    if ( !m_pForcedPrefix )
    {
        m_pForcedPrefix = new FixedText(this, WB_VCENTER);

        // we use a gray background for the fixed text
        StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings();
        m_pForcedPrefix->SetBackground(Wallpaper(aSystemStyle.GetDialogColor()));
    }

    m_pForcedPrefix->Show(m_bShowPrefix);

    sal_Bool bIsEmpty = 0 == _rStr.Len();
    // calc the prefix
    String sPrefix;
    if (!bIsEmpty)
    {
        // determine the type of the new URL described by the new text
        DATASOURCE_TYPE eType = m_aTypeCollection.getType(_rStr);
        // and the prefix belonging to this type
        if (DST_UNKNOWN != eType)
            sPrefix = m_aTypeCollection.getDatasourcePrefix(eType);
        else
            DBG_ERROR("OConnectionURLEdit::SetText : the new text is no valid connection URL!");
    }

    // the fixed text gets the prefix
    if ( m_pForcedPrefix )
        m_pForcedPrefix->SetText(sPrefix);

    // both subs have to be resized according to the text len of the prefix
    Size aMySize = GetSizePixel();
    sal_Int32 nTextWidth = 0;
    if ( m_pForcedPrefix && m_bShowPrefix)
    {
        nTextWidth = m_pForcedPrefix->GetTextWidth(sPrefix) + 2;
        m_pForcedPrefix->SetPosSizePixel(Point(0, -2), Size(nTextWidth, aMySize.Height()));
    }
    GetSubEdit()->SetPosSizePixel(Point(nTextWidth, -2), Size(aMySize.Width() - nTextWidth - 4, aMySize.Height()));
        // -2 because the edit has a frame which is 2 pixel wide ... should not be necessary, but I don't fully understand this ....

    // show the sub controls (in case they were just created)
    GetSubEdit()->Show();

    // do the real SetTex
//  Edit::SetText(bIsEmpty ? _rStr : m_aTypeCollection.cutPrefix(_rStr), _rNewSelection);
    String sNewText( _rStr );
    if ( !bIsEmpty )
        sNewText  =m_aTypeCollection.cutPrefix( _rStr );
    Edit::SetText( sNewText );
}

//-------------------------------------------------------------------------
String OConnectionURLEdit::GetText() const
{
    if ( m_pForcedPrefix )
        return m_pForcedPrefix->GetText() += Edit::GetText();
    return Edit::GetText();
}
// -----------------------------------------------------------------------------
void OConnectionURLEdit::ShowPrefix(BOOL _bShowPrefix)
{
    m_bShowPrefix = _bShowPrefix;
    if ( m_pForcedPrefix )
        m_pForcedPrefix->Show(m_bShowPrefix);
}
//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>


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

#ifndef DBAUI_USERADMINDLG_HXX
#define DBAUI_USERADMINDLG_HXX

#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
#ifndef DBAUI_ITEMSETHELPER_HXX
#include "IItemSetHelper.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#include <memory>

FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
FORWARD_DECLARE_INTERFACE(sdbc,XConnection)
FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory)

//.........................................................................
namespace dbaui
{
//.........................................................................
    class ODbDataSourceAdministrationHelper;
    //=========================================================================
    //= OUserAdminDlg
    //=========================================================================

    /** implements the user adin dialog
    */
    class OUserAdminDlg : public SfxTabDialog, public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient
    {
        ::std::auto_ptr<ODbDataSourceAdministrationHelper>  m_pImpl;
        SfxItemSet* m_pItemSet;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>          m_xConnection;
        sal_Bool    m_bOwnConnection;
    protected:
        virtual void PageCreated(USHORT _nId, SfxTabPage& _rPage);
    public:
        OUserAdminDlg( Window* _pParent
                            ,SfxItemSet* _pItems
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
                            ,const ::com::sun::star::uno::Any& _aDataSourceName
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);

        virtual ~OUserAdminDlg();

        virtual const SfxItemSet* getOutputSet() const;
        virtual SfxItemSet* getWriteOutputSet();

        virtual short   Execute();

        // forwards to ODbDataSourceAdministrationHelper
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB();
        virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection();
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver();
        virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const;
        virtual void clearPassword();
        virtual sal_Bool saveDatasource();
        virtual void setTitle(const ::rtl::OUString& _sTitle);
    };
//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // DBAUI_USERADMINDLG_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.98); FILE MERGED 2005/09/05 17:34:32 rt 1.4.98.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: UserAdminDlg.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:41:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef DBAUI_USERADMINDLG_HXX
#define DBAUI_USERADMINDLG_HXX

#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
#ifndef DBAUI_ITEMSETHELPER_HXX
#include "IItemSetHelper.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#include <memory>

FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
FORWARD_DECLARE_INTERFACE(sdbc,XConnection)
FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory)

//.........................................................................
namespace dbaui
{
//.........................................................................
    class ODbDataSourceAdministrationHelper;
    //=========================================================================
    //= OUserAdminDlg
    //=========================================================================

    /** implements the user adin dialog
    */
    class OUserAdminDlg : public SfxTabDialog, public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient
    {
        ::std::auto_ptr<ODbDataSourceAdministrationHelper>  m_pImpl;
        SfxItemSet* m_pItemSet;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>          m_xConnection;
        sal_Bool    m_bOwnConnection;
    protected:
        virtual void PageCreated(USHORT _nId, SfxTabPage& _rPage);
    public:
        OUserAdminDlg( Window* _pParent
                            ,SfxItemSet* _pItems
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
                            ,const ::com::sun::star::uno::Any& _aDataSourceName
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);

        virtual ~OUserAdminDlg();

        virtual const SfxItemSet* getOutputSet() const;
        virtual SfxItemSet* getWriteOutputSet();

        virtual short   Execute();

        // forwards to ODbDataSourceAdministrationHelper
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB();
        virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection();
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver();
        virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const;
        virtual void clearPassword();
        virtual sal_Bool saveDatasource();
        virtual void setTitle(const ::rtl::OUString& _sTitle);
    };
//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // DBAUI_USERADMINDLG_HXX
<|endoftext|>