<commit_before>#include "clustering/administration/issues/name_conflict.hpp"

name_conflict_issue_t::name_conflict_issue_t(
        const std::string &_type,
        const std::string &_contested_name,
        const std::set<uuid_t> &_contestants) :
    type(_type), contested_name(_contested_name), contestants(_contestants) { }

std::string name_conflict_issue_t::get_description() const {
    std::string message = "The following " + type + "s are all named '" + contested_name + "': ";
    for (std::set<uuid_t>::iterator it = contestants.begin(); it != contestants.end(); it++) {
        message += uuid_to_str(*it) + "; ";
    }
    return message;
}

cJSON *name_conflict_issue_t::get_json_description() {
    issue_json_t json;
    json.critical = false;
    json.description = "The following " + type + "s are all named '" + contested_name + "': ";
    for (std::set<uuid_t>::iterator it = contestants.begin(); it != contestants.end(); it++) {
        json.description += uuid_to_str(*it) + "; ";
    }
    json.type = "NAME_CONFLICT_ISSUE";
    json.time = get_secs();

    cJSON *res = render_as_json(&json);

    cJSON_AddItemToObject(res, "contested_type", render_as_json(&type));
    cJSON_AddItemToObject(res, "contested_name", render_as_json(&contested_name));
    cJSON_AddItemToObject(res, "contestants", render_as_json(&contestants));

    return res;
}

name_conflict_issue_t *name_conflict_issue_t::clone() const {
    return new name_conflict_issue_t(type, contested_name, contestants);
}

class name_map_t {
public:
    template<class object_metadata_t>
    void file_away(const std::map<uuid_t, deletable_t<object_metadata_t> > &map) {
        for (typename std::map<uuid_t, deletable_t<object_metadata_t> >::const_iterator it = map.begin();
                it != map.end(); it++) {
            if (!it->second.is_deleted()) {
                if (!it->second.get().name.in_conflict()) {
                    by_name[it->second.get().name.get()].insert(it->first);
                }
            }
        }
    }

    void report(const std::string &type,
            std::list<clone_ptr_t<global_issue_t> > *out) {
        for (std::map<std::string, std::set<uuid_t>, case_insensitive_less_t>::iterator it =
                by_name.begin(); it != by_name.end(); it++) {
            if (it->second.size() > 1) {
                out->push_back(clone_ptr_t<global_issue_t>(
                    new name_conflict_issue_t(type, it->first, it->second)));
            }
        }
    }

private:
    class case_insensitive_less_t : public std::binary_function<std::string, std::string, bool> {
    public:
        bool operator()(const std::string &a, const std::string &b) {
            return strcasecmp(a.c_str(), b.c_str()) < 0;
        }
    };

    std::map<std::string, std::set<uuid_t>, case_insensitive_less_t> by_name;
};

class namespace_map_t {
public:
namespace_map_t(const std::map<uuid_t, deletable_t<database_semilattice_metadata_t> > &_databases)
    : databases(_databases)
{ }
    template<class object_metadata_t>
    void file_away(const std::map<uuid_t, deletable_t<object_metadata_t> > &map) {
        for (typename std::map<uuid_t, deletable_t<object_metadata_t> >::const_iterator it = map.begin();
                it != map.end(); it++) {
            if (!it->second.is_deleted()) {
                if (!it->second.get().name.in_conflict() &&
                    !it->second.get().database.in_conflict()) {
                    if (std_contains(databases, it->second.get().database.get())) {
                        deletable_t<database_semilattice_metadata_t> db = databases[it->second.get().database.get()];
                        if (!db.is_deleted() && !db.get().name.in_conflict()) {
                            by_name[db.get().name.get() + "." + it->second.get().name.get()].insert(it->first);
                        }
                    }
                }
            }
        }
    }

    void report(const std::string &type,
            std::list<clone_ptr_t<global_issue_t> > *out) {
        for (std::map<std::string, std::set<uuid_t>, case_insensitive_less_t>::iterator it =
                by_name.begin(); it != by_name.end(); it++) {
            if (it->second.size() > 1) {
                out->push_back(clone_ptr_t<global_issue_t>(
                    new name_conflict_issue_t(type, it->first, it->second)));
            }
        }
    }

private:
    class case_insensitive_less_t : public std::binary_function<std::string, std::string, bool> {
    public:
        bool operator()(const std::string &a, const std::string &b) {
            return strcasecmp(a.c_str(), b.c_str()) < 0;
        }
    };

    std::map<std::string, std::set<uuid_t>, case_insensitive_less_t> by_name;
    std::map<uuid_t, deletable_t<database_semilattice_metadata_t> > databases;
};

name_conflict_issue_tracker_t::name_conflict_issue_tracker_t(boost::shared_ptr<semilattice_read_view_t<cluster_semilattice_metadata_t> > _semilattice_view)
    : semilattice_view(_semilattice_view) { }

name_conflict_issue_tracker_t::~name_conflict_issue_tracker_t() { }

std::list<clone_ptr_t<global_issue_t> > name_conflict_issue_tracker_t::get_issues() {
    cluster_semilattice_metadata_t metadata = semilattice_view->get();

    std::list<clone_ptr_t<global_issue_t> > issues;

    namespace_map_t namespaces(metadata.databases.databases);
    namespaces.file_away(metadata.rdb_namespaces->namespaces);
    namespaces.file_away(metadata.dummy_namespaces->namespaces);
    namespaces.file_away(metadata.memcached_namespaces->namespaces);
    namespaces.report("table", &issues);

    name_map_t datacenters;
    datacenters.file_away(metadata.datacenters.datacenters);
    datacenters.report("datacenter", &issues);

    name_map_t machines;
    machines.file_away(metadata.machines.machines);
    machines.report("machine", &issues);

    name_map_t databases;
    databases.file_away(metadata.databases.databases);
    machines.report("databases", &issues);

    return issues;
}
<commit_msg>Fix a stupid copy and paste bug.<commit_after>#include "clustering/administration/issues/name_conflict.hpp"

name_conflict_issue_t::name_conflict_issue_t(
        const std::string &_type,
        const std::string &_contested_name,
        const std::set<uuid_t> &_contestants) :
    type(_type), contested_name(_contested_name), contestants(_contestants) { }

std::string name_conflict_issue_t::get_description() const {
    std::string message = "The following " + type + "s are all named '" + contested_name + "': ";
    for (std::set<uuid_t>::iterator it = contestants.begin(); it != contestants.end(); it++) {
        message += uuid_to_str(*it) + "; ";
    }
    return message;
}

cJSON *name_conflict_issue_t::get_json_description() {
    issue_json_t json;
    json.critical = false;
    json.description = "The following " + type + "s are all named '" + contested_name + "': ";
    for (std::set<uuid_t>::iterator it = contestants.begin(); it != contestants.end(); it++) {
        json.description += uuid_to_str(*it) + "; ";
    }
    json.type = "NAME_CONFLICT_ISSUE";
    json.time = get_secs();

    cJSON *res = render_as_json(&json);

    cJSON_AddItemToObject(res, "contested_type", render_as_json(&type));
    cJSON_AddItemToObject(res, "contested_name", render_as_json(&contested_name));
    cJSON_AddItemToObject(res, "contestants", render_as_json(&contestants));

    return res;
}

name_conflict_issue_t *name_conflict_issue_t::clone() const {
    return new name_conflict_issue_t(type, contested_name, contestants);
}

class name_map_t {
public:
    template<class object_metadata_t>
    void file_away(const std::map<uuid_t, deletable_t<object_metadata_t> > &map) {
        for (typename std::map<uuid_t, deletable_t<object_metadata_t> >::const_iterator it = map.begin();
                it != map.end(); it++) {
            if (!it->second.is_deleted()) {
                if (!it->second.get().name.in_conflict()) {
                    by_name[it->second.get().name.get()].insert(it->first);
                }
            }
        }
    }

    void report(const std::string &type,
            std::list<clone_ptr_t<global_issue_t> > *out) {
        for (std::map<std::string, std::set<uuid_t>, case_insensitive_less_t>::iterator it =
                by_name.begin(); it != by_name.end(); it++) {
            if (it->second.size() > 1) {
                out->push_back(clone_ptr_t<global_issue_t>(
                    new name_conflict_issue_t(type, it->first, it->second)));
            }
        }
    }

private:
    class case_insensitive_less_t : public std::binary_function<std::string, std::string, bool> {
    public:
        bool operator()(const std::string &a, const std::string &b) {
            return strcasecmp(a.c_str(), b.c_str()) < 0;
        }
    };

    std::map<std::string, std::set<uuid_t>, case_insensitive_less_t> by_name;
};

class namespace_map_t {
public:
namespace_map_t(const std::map<uuid_t, deletable_t<database_semilattice_metadata_t> > &_databases)
    : databases(_databases)
{ }
    template<class object_metadata_t>
    void file_away(const std::map<uuid_t, deletable_t<object_metadata_t> > &map) {
        for (typename std::map<uuid_t, deletable_t<object_metadata_t> >::const_iterator it = map.begin();
                it != map.end(); it++) {
            if (!it->second.is_deleted()) {
                if (!it->second.get().name.in_conflict() &&
                    !it->second.get().database.in_conflict()) {
                    if (std_contains(databases, it->second.get().database.get())) {
                        deletable_t<database_semilattice_metadata_t> db = databases[it->second.get().database.get()];
                        if (!db.is_deleted() && !db.get().name.in_conflict()) {
                            by_name[db.get().name.get() + "." + it->second.get().name.get()].insert(it->first);
                        }
                    }
                }
            }
        }
    }

    void report(const std::string &type,
            std::list<clone_ptr_t<global_issue_t> > *out) {
        for (std::map<std::string, std::set<uuid_t>, case_insensitive_less_t>::iterator it =
                by_name.begin(); it != by_name.end(); it++) {
            if (it->second.size() > 1) {
                out->push_back(clone_ptr_t<global_issue_t>(
                    new name_conflict_issue_t(type, it->first, it->second)));
            }
        }
    }

private:
    class case_insensitive_less_t : public std::binary_function<std::string, std::string, bool> {
    public:
        bool operator()(const std::string &a, const std::string &b) {
            return strcasecmp(a.c_str(), b.c_str()) < 0;
        }
    };

    std::map<std::string, std::set<uuid_t>, case_insensitive_less_t> by_name;
    std::map<uuid_t, deletable_t<database_semilattice_metadata_t> > databases;
};

name_conflict_issue_tracker_t::name_conflict_issue_tracker_t(boost::shared_ptr<semilattice_read_view_t<cluster_semilattice_metadata_t> > _semilattice_view)
    : semilattice_view(_semilattice_view) { }

name_conflict_issue_tracker_t::~name_conflict_issue_tracker_t() { }

std::list<clone_ptr_t<global_issue_t> > name_conflict_issue_tracker_t::get_issues() {
    cluster_semilattice_metadata_t metadata = semilattice_view->get();

    std::list<clone_ptr_t<global_issue_t> > issues;

    namespace_map_t namespaces(metadata.databases.databases);
    namespaces.file_away(metadata.rdb_namespaces->namespaces);
    namespaces.file_away(metadata.dummy_namespaces->namespaces);
    namespaces.file_away(metadata.memcached_namespaces->namespaces);
    namespaces.report("table", &issues);

    name_map_t datacenters;
    datacenters.file_away(metadata.datacenters.datacenters);
    datacenters.report("datacenter", &issues);

    name_map_t machines;
    machines.file_away(metadata.machines.machines);
    machines.report("machine", &issues);

    name_map_t databases;
    databases.file_away(metadata.databases.databases);
    databases.report("databases", &issues);

    return issues;
}
<|endoftext|>


<commit_before>#include "gpcheckcloud.h"

bool hasHeader;

char eolString[EOL_CHARS_MAX_LEN + 1] = "\n";  // LF by default

string s3extErrorMessage;

volatile sig_atomic_t QueryCancelPending = false;

static bool uploadS3(const char *urlWithOptions, const char *fileToUpload);
static bool downloadS3(const char *urlWithOptions);
static bool checkConfig(const char *urlWithOptions);
static void printBucketContents(const ListBucketResult &result);
static void printTemplate();
static void validateCommandLineArgs(map<char, string> &optionPairs);
static map<char, string> parseCommandLineArgs(int argc, char *argv[]);
static void registerSignalHandler();
static void printUsage(FILE *stream);

// As we can't catch 'IsAbortInProgress()' in UT, so here consider QueryCancelPending only
bool S3QueryIsAbortInProgress(void) {
    return QueryCancelPending;
}

void MaskThreadSignals() {
}

void *S3Alloc(size_t size) {
    return malloc(size);
}

void S3Free(void *p) {
    free(p);
}

static void handleAbortSignal(int signum) {
    fprintf(stderr, "Interrupted by user (%s), exiting...\n\n", strsignal(signum));
    QueryCancelPending = true;
}

static void registerSignalHandler() {
    signal(SIGHUP, handleAbortSignal);
    signal(SIGABRT, handleAbortSignal);
    signal(SIGTERM, handleAbortSignal);
    signal(SIGINT, handleAbortSignal);
    signal(SIGTSTP, handleAbortSignal);
}

static void printUsage(FILE *stream) {
    fprintf(stream,
            "Usage: gpcheckcloud -c \"s3://endpoint/bucket/prefix "
            "config=path_to_config_file [region=region_name]\", to check the configuration.\n"
            "       gpcheckcloud -d \"s3://endpoint/bucket/prefix "
            "config=path_to_config_file [region=region_name]\", to download and output to stdout.\n"
            "       gpcheckcloud -u \"/path/to/file\" \"s3://endpoint/bucket/prefix "
            "config=path_to_config_file [region=region_name]\", to upload a file.\n"
            "       gpcheckcloud -t, to show the config template.\n"
            "       gpcheckcloud -h, to show this help.\n");
}

// parse the arguments into char-string value pairs
static map<char, string> parseCommandLineArgs(int argc, char *argv[]) {
    int opt = 0;
    map<char, string> optionPairs;

    while ((opt = getopt(argc, argv, "c:d:u:ht")) != -1) {
        switch (opt) {
            case 'c':
            case 'd':
            case 'h':
            case 't':
                if (optarg == NULL) {
                    optionPairs[opt] = "";
                } else if (optarg[0] == '-') {
                    fprintf(stderr, "Failed. Invalid argument for -%c: '%s'.\n\n", opt, optarg);
                    printUsage(stderr);
                    exit(EXIT_FAILURE);
                } else {
                    optionPairs[opt] = optarg;
                }

                break;
            case 'u':
                if (optarg == NULL) {
                    optionPairs[opt] = "";
                } else if (optind + 1 == argc) {      // has two option values
                    optionPairs['f'] = optarg;        // value of option file
                    optionPairs['u'] = argv[optind];  // value of option url
                } else {
                    fprintf(stderr, "Failed. Invalid arguments for -u, please check.\n\n");
                    printUsage(stderr);
                    exit(EXIT_FAILURE);
                }
                break;

            default:  // '?'
                printUsage(stderr);
                exit(EXIT_FAILURE);
        }
    }

    return optionPairs;
}

// check if command line arguments are valid
static void validateCommandLineArgs(map<char, string> &optionPairs) {
    uint64_t count = optionPairs.count('f') + optionPairs.count('u');

    if ((count == 2) && (optionPairs.size() == 2)) {
        return;
    } else if (count == 1) {
        fprintf(stderr, "Failed. Option \'-u\' must work with \'-f\'.\n\n");
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }

    if (optionPairs.size() > 1) {
        stringstream ss;

        ss << "Failed. Can't set options ";

        // concatenate all option names
        // e.g. if we have -c and -d, insert "-c, -d" into the stream.
        for (map<char, string>::iterator i = optionPairs.begin(); i != optionPairs.end(); i++) {
            ss << "'-" << i->first << "' ";
        }

        ss << "at the same time.";

        // example message: "Failed. Can't set options '-c' '-d' at the same time."
        fprintf(stderr, "%s\n\n", ss.str().c_str());
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }
}

static void printTemplate() {
    printf(
        "[default]\n"
        "secret = \"aws secret\"\n"
        "accessid = \"aws access id\"\n"
        "threadnum = 4\n"
        "chunksize = 67108864\n"
        "low_speed_limit = 10240\n"
        "low_speed_time = 60\n"
        "encryption = true\n"
        "version = 1\n"
        "proxy = \"\"\n"
        "autocompress = true\n"
        "verifycert = true\n"
        "server_side_encryption = \"\"\n"
        "# gpcheckcloud config\n"
        "gpcheckcloud_newline = \"\\n\"\n");
}

static void printBucketContents(const ListBucketResult &result) {
    char urlbuf[256];
    vector<BucketContent>::const_iterator i;

    for (i = result.contents.begin(); i != result.contents.end(); i++) {
        snprintf(urlbuf, 256, "%s", i->getName().c_str());
        printf("File: %s, Size: %" PRIu64 "\n", urlbuf, i->getSize());
    }
}

static bool checkConfig(const char *urlWithOptions) {
    if (!urlWithOptions) {
        return false;
    }

    GPReader *reader = reader_init(urlWithOptions);
    if (!reader) {
        return false;
    }

    ListBucketResult result = reader->getKeyList();

    if (result.contents.empty()) {
        fprintf(stderr,
                "\nYour configuration works well, however there is no file matching your "
                "prefix.\n");
    } else {
        printBucketContents(result);
        fprintf(stderr, "\nYour configuration works well.\n");
    }

    reader_cleanup(&reader);

    return true;
}

static bool downloadS3(const char *urlWithOptions) {
    if (!urlWithOptions) {
        return false;
    }

    int data_len = BUF_SIZE;
    char data_buf[BUF_SIZE];
    bool ret = true;

    thread_setup();

    GPReader *reader = reader_init(urlWithOptions);
    if (!reader) {
        return false;
    }

    strncpy(eolString, reader->getParams().getGpcheckcloud_newline().c_str(), EOL_CHARS_MAX_LEN);
    eolString[EOL_CHARS_MAX_LEN] = '\0';

    do {
        data_len = BUF_SIZE;

        if (!reader_transfer_data(reader, data_buf, data_len)) {
            fprintf(stderr, "Failed to read data from Amazon S3\n");
            ret = false;
            break;
        }

        fwrite(data_buf, (size_t)data_len, 1, stdout);
    } while (data_len && !S3QueryIsAbortInProgress());

    reader_cleanup(&reader);

    thread_cleanup();

    return ret;
}

static bool uploadS3(const char *urlWithOptions, const char *fileToUpload) {
    if (!urlWithOptions) {
        return false;
    }

    size_t data_len = BUF_SIZE;
    char data_buf[BUF_SIZE];
    size_t read_len = 0;
    bool ret = true;

    thread_setup();

    GPWriter *writer = writer_init(urlWithOptions);
    if (!writer) {
        return false;
    }

    FILE *fd = fopen(fileToUpload, "r");
    if (fd == NULL) {
        fprintf(stderr, "File does not exist\n");
        ret = false;
    } else {
        do {
            read_len = fread(data_buf, 1, data_len, fd);

            if (read_len == 0) {
                break;
            }

            if (!writer_transfer_data(writer, data_buf, (int)read_len)) {
                fprintf(stderr, "Failed to write data to Amazon S3\n");
                ret = false;
                break;
            }
        } while (read_len == data_len && !S3QueryIsAbortInProgress());

        if (ferror(fd)) {
            ret = false;
        }

        fclose(fd);
    }

    writer_cleanup(&writer);

    thread_cleanup();

    return ret;
}

int main(int argc, char *argv[]) {
    bool ret = true;

    s3ext_loglevel = EXT_ERROR;
    s3ext_logtype = STDERR_LOG;

    if (argc == 1) {
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }

    /* Prepare to receive interrupts */
    registerSignalHandler();

    map<char, string> optionPairs = parseCommandLineArgs(argc, argv);

    validateCommandLineArgs(optionPairs);

    if (!optionPairs.empty()) {
        const char *arg = optionPairs.begin()->second.c_str();

        switch (optionPairs.begin()->first) {
            case 'c':
                ret = checkConfig(arg);
                break;
            case 'd':
                ret = downloadS3(arg);
                break;
            case 'u':
            case 'f':
                ret = uploadS3(optionPairs['u'].c_str(), optionPairs['f'].c_str());
                break;
            case 'h':
                printUsage(stdout);
                break;
            case 't':
                printTemplate();
                break;
            default:
                printUsage(stderr);
                exit(EXIT_FAILURE);
        }
    }

    // Abort should not print the failed info
    if (ret || S3QueryIsAbortInProgress()) {
        exit(EXIT_SUCCESS);
    } else {
        fprintf(stderr, "Failed. Please check the arguments and configuration file.\n\n");
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }
}
<commit_msg>Adjust seq of accessid and secret in gpcheckcloud template example. <commit_after>#include "gpcheckcloud.h"

bool hasHeader;

char eolString[EOL_CHARS_MAX_LEN + 1] = "\n";  // LF by default

string s3extErrorMessage;

volatile sig_atomic_t QueryCancelPending = false;

static bool uploadS3(const char *urlWithOptions, const char *fileToUpload);
static bool downloadS3(const char *urlWithOptions);
static bool checkConfig(const char *urlWithOptions);
static void printBucketContents(const ListBucketResult &result);
static void printTemplate();
static void validateCommandLineArgs(map<char, string> &optionPairs);
static map<char, string> parseCommandLineArgs(int argc, char *argv[]);
static void registerSignalHandler();
static void printUsage(FILE *stream);

// As we can't catch 'IsAbortInProgress()' in UT, so here consider QueryCancelPending only
bool S3QueryIsAbortInProgress(void) {
    return QueryCancelPending;
}

void MaskThreadSignals() {
}

void *S3Alloc(size_t size) {
    return malloc(size);
}

void S3Free(void *p) {
    free(p);
}

static void handleAbortSignal(int signum) {
    fprintf(stderr, "Interrupted by user (%s), exiting...\n\n", strsignal(signum));
    QueryCancelPending = true;
}

static void registerSignalHandler() {
    signal(SIGHUP, handleAbortSignal);
    signal(SIGABRT, handleAbortSignal);
    signal(SIGTERM, handleAbortSignal);
    signal(SIGINT, handleAbortSignal);
    signal(SIGTSTP, handleAbortSignal);
}

static void printUsage(FILE *stream) {
    fprintf(stream,
            "Usage: gpcheckcloud -c \"s3://endpoint/bucket/prefix "
            "config=path_to_config_file [region=region_name]\", to check the configuration.\n"
            "       gpcheckcloud -d \"s3://endpoint/bucket/prefix "
            "config=path_to_config_file [region=region_name]\", to download and output to stdout.\n"
            "       gpcheckcloud -u \"/path/to/file\" \"s3://endpoint/bucket/prefix "
            "config=path_to_config_file [region=region_name]\", to upload a file.\n"
            "       gpcheckcloud -t, to show the config template.\n"
            "       gpcheckcloud -h, to show this help.\n");
}

// parse the arguments into char-string value pairs
static map<char, string> parseCommandLineArgs(int argc, char *argv[]) {
    int opt = 0;
    map<char, string> optionPairs;

    while ((opt = getopt(argc, argv, "c:d:u:ht")) != -1) {
        switch (opt) {
            case 'c':
            case 'd':
            case 'h':
            case 't':
                if (optarg == NULL) {
                    optionPairs[opt] = "";
                } else if (optarg[0] == '-') {
                    fprintf(stderr, "Failed. Invalid argument for -%c: '%s'.\n\n", opt, optarg);
                    printUsage(stderr);
                    exit(EXIT_FAILURE);
                } else {
                    optionPairs[opt] = optarg;
                }

                break;
            case 'u':
                if (optarg == NULL) {
                    optionPairs[opt] = "";
                } else if (optind + 1 == argc) {      // has two option values
                    optionPairs['f'] = optarg;        // value of option file
                    optionPairs['u'] = argv[optind];  // value of option url
                } else {
                    fprintf(stderr, "Failed. Invalid arguments for -u, please check.\n\n");
                    printUsage(stderr);
                    exit(EXIT_FAILURE);
                }
                break;

            default:  // '?'
                printUsage(stderr);
                exit(EXIT_FAILURE);
        }
    }

    return optionPairs;
}

// check if command line arguments are valid
static void validateCommandLineArgs(map<char, string> &optionPairs) {
    uint64_t count = optionPairs.count('f') + optionPairs.count('u');

    if ((count == 2) && (optionPairs.size() == 2)) {
        return;
    } else if (count == 1) {
        fprintf(stderr, "Failed. Option \'-u\' must work with \'-f\'.\n\n");
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }

    if (optionPairs.size() > 1) {
        stringstream ss;

        ss << "Failed. Can't set options ";

        // concatenate all option names
        // e.g. if we have -c and -d, insert "-c, -d" into the stream.
        for (map<char, string>::iterator i = optionPairs.begin(); i != optionPairs.end(); i++) {
            ss << "'-" << i->first << "' ";
        }

        ss << "at the same time.";

        // example message: "Failed. Can't set options '-c' '-d' at the same time."
        fprintf(stderr, "%s\n\n", ss.str().c_str());
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }
}

static void printTemplate() {
    printf(
        "[default]\n"
        "accessid = \"aws access id\"\n"
        "secret = \"aws secret\"\n"
        "threadnum = 4\n"
        "chunksize = 67108864\n"
        "low_speed_limit = 10240\n"
        "low_speed_time = 60\n"
        "encryption = true\n"
        "version = 1\n"
        "proxy = \"\"\n"
        "autocompress = true\n"
        "verifycert = true\n"
        "server_side_encryption = \"\"\n"
        "# gpcheckcloud config\n"
        "gpcheckcloud_newline = \"\\n\"\n");
}

static void printBucketContents(const ListBucketResult &result) {
    char urlbuf[256];
    vector<BucketContent>::const_iterator i;

    for (i = result.contents.begin(); i != result.contents.end(); i++) {
        snprintf(urlbuf, 256, "%s", i->getName().c_str());
        printf("File: %s, Size: %" PRIu64 "\n", urlbuf, i->getSize());
    }
}

static bool checkConfig(const char *urlWithOptions) {
    if (!urlWithOptions) {
        return false;
    }

    GPReader *reader = reader_init(urlWithOptions);
    if (!reader) {
        return false;
    }

    ListBucketResult result = reader->getKeyList();

    if (result.contents.empty()) {
        fprintf(stderr,
                "\nYour configuration works well, however there is no file matching your "
                "prefix.\n");
    } else {
        printBucketContents(result);
        fprintf(stderr, "\nYour configuration works well.\n");
    }

    reader_cleanup(&reader);

    return true;
}

static bool downloadS3(const char *urlWithOptions) {
    if (!urlWithOptions) {
        return false;
    }

    int data_len = BUF_SIZE;
    char data_buf[BUF_SIZE];
    bool ret = true;

    thread_setup();

    GPReader *reader = reader_init(urlWithOptions);
    if (!reader) {
        return false;
    }

    strncpy(eolString, reader->getParams().getGpcheckcloud_newline().c_str(), EOL_CHARS_MAX_LEN);
    eolString[EOL_CHARS_MAX_LEN] = '\0';

    do {
        data_len = BUF_SIZE;

        if (!reader_transfer_data(reader, data_buf, data_len)) {
            fprintf(stderr, "Failed to read data from Amazon S3\n");
            ret = false;
            break;
        }

        fwrite(data_buf, (size_t)data_len, 1, stdout);
    } while (data_len && !S3QueryIsAbortInProgress());

    reader_cleanup(&reader);

    thread_cleanup();

    return ret;
}

static bool uploadS3(const char *urlWithOptions, const char *fileToUpload) {
    if (!urlWithOptions) {
        return false;
    }

    size_t data_len = BUF_SIZE;
    char data_buf[BUF_SIZE];
    size_t read_len = 0;
    bool ret = true;

    thread_setup();

    GPWriter *writer = writer_init(urlWithOptions);
    if (!writer) {
        return false;
    }

    FILE *fd = fopen(fileToUpload, "r");
    if (fd == NULL) {
        fprintf(stderr, "File does not exist\n");
        ret = false;
    } else {
        do {
            read_len = fread(data_buf, 1, data_len, fd);

            if (read_len == 0) {
                break;
            }

            if (!writer_transfer_data(writer, data_buf, (int)read_len)) {
                fprintf(stderr, "Failed to write data to Amazon S3\n");
                ret = false;
                break;
            }
        } while (read_len == data_len && !S3QueryIsAbortInProgress());

        if (ferror(fd)) {
            ret = false;
        }

        fclose(fd);
    }

    writer_cleanup(&writer);

    thread_cleanup();

    return ret;
}

int main(int argc, char *argv[]) {
    bool ret = true;

    s3ext_loglevel = EXT_ERROR;
    s3ext_logtype = STDERR_LOG;

    if (argc == 1) {
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }

    /* Prepare to receive interrupts */
    registerSignalHandler();

    map<char, string> optionPairs = parseCommandLineArgs(argc, argv);

    validateCommandLineArgs(optionPairs);

    if (!optionPairs.empty()) {
        const char *arg = optionPairs.begin()->second.c_str();

        switch (optionPairs.begin()->first) {
            case 'c':
                ret = checkConfig(arg);
                break;
            case 'd':
                ret = downloadS3(arg);
                break;
            case 'u':
            case 'f':
                ret = uploadS3(optionPairs['u'].c_str(), optionPairs['f'].c_str());
                break;
            case 'h':
                printUsage(stdout);
                break;
            case 't':
                printTemplate();
                break;
            default:
                printUsage(stderr);
                exit(EXIT_FAILURE);
        }
    }

    // Abort should not print the failed info
    if (ret || S3QueryIsAbortInProgress()) {
        exit(EXIT_SUCCESS);
    } else {
        fprintf(stderr, "Failed. Please check the arguments and configuration file.\n\n");
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Michael C. Heiber
// This source file is part of the KMC_Lattice project, which is subject to the MIT License.
// For more information, see the LICENSE file that accompanies this software.
// The KMC_Lattice project can be found on Github at https://github.com/MikeHeiber/KMC_Lattice

#include "Object.h"

using namespace std;

const string Object::object_type_base = "Object";

Object::~Object(){
    //dtor
}

Object::Object(){

}

Object::Object(const double time,const int tag_num,const Coords& start_coords){
    time_created = time;
    tag = tag_num;
    coords_current = start_coords;
    coords_initial = start_coords;
}

double Object::calculateDisplacement() const{
    return sqrt((double)(coords_current.x+dx-coords_initial.x)*(coords_current.x+dx-coords_initial.x)+(coords_current.y+dy-coords_initial.y)*(coords_current.y+dy-coords_initial.y)+(coords_current.z+dz-coords_initial.z)*(coords_current.z+dz-coords_initial.z));
}

Coords Object::getCoords() const{
    return coords_current;
}

double Object::getCreationTime() const{
    return time_created;
}

list<Event*>::iterator Object::getEventIt() const{
    return event_it;
}

string Object::getObjectType() const{
    return object_type_base;
}

int Object::getTag() const{
    return tag;
}

void Object::incrementDX(const int num){
    dx += num;
}

void Object::incrementDY(const int num){
    dy += num;
}

void Object::incrementDZ(const int num){
    dz += num;
}

void Object::resetInitialCoords(const Coords& input_coords) {
	coords_initial = input_coords;
	dx = 0;
	dy = 0;
	dz = 0;
}

void Object::setCoords(const Coords& input_coords){
    coords_current = input_coords;
}

void Object::setEventIt(const list<Event*>::iterator input_it){
    event_it = input_it;
}

<commit_msg>Object Class Update<commit_after>// Copyright (c) 2018 Michael C. Heiber
// This source file is part of the KMC_Lattice project, which is subject to the MIT License.
// For more information, see the LICENSE file that accompanies this software.
// The KMC_Lattice project can be found on Github at https://github.com/MikeHeiber/KMC_Lattice

#include "Object.h"

using namespace std;

const string Object::object_type_base = "Object";

Object::~Object(){
    //dtor
}

Object::Object(){

}

Object::Object(const double time,const int tag_num,const Coords& start_coords){
    time_created = time;
    tag = tag_num;
    coords_current = start_coords;
    coords_initial = start_coords;
}

double Object::calculateDisplacement() const{
    return sqrt((coords_current.x+dx-coords_initial.x)*(coords_current.x+dx-coords_initial.x)+(coords_current.y+dy-coords_initial.y)*(coords_current.y+dy-coords_initial.y)+(coords_current.z+dz-coords_initial.z)*(coords_current.z+dz-coords_initial.z));
}

Coords Object::getCoords() const{
    return coords_current;
}

double Object::getCreationTime() const{
    return time_created;
}

list<Event*>::iterator Object::getEventIt() const{
    return event_it;
}

string Object::getObjectType() const{
    return object_type_base;
}

int Object::getTag() const{
    return tag;
}

void Object::incrementDX(const int num){
    dx += num;
}

void Object::incrementDY(const int num){
    dy += num;
}

void Object::incrementDZ(const int num){
    dz += num;
}

void Object::resetInitialCoords(const Coords& input_coords) {
	coords_initial = input_coords;
	dx = 0;
	dy = 0;
	dz = 0;
}

void Object::setCoords(const Coords& input_coords){
    coords_current = input_coords;
}

void Object::setEventIt(const list<Event*>::iterator input_it){
    event_it = input_it;
}

<|endoftext|>


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

#include "ppapi/c/pp_errors.h"
#include "ppapi/thunk/thunk.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_input_event_api.h"
#include "ppapi/thunk/ppb_instance_api.h"
#include "ppapi/thunk/resource_creation_api.h"

namespace ppapi {
namespace thunk {

namespace {

typedef EnterFunction<PPB_Instance_FunctionAPI> EnterInstance;
typedef EnterResource<PPB_InputEvent_API> EnterInputEvent;

// InputEvent ------------------------------------------------------------------

int32_t RequestInputEvents(PP_Instance instance, uint32_t event_classes) {
  EnterInstance enter(instance, true);
  if (enter.failed())
    return PP_ERROR_BADARGUMENT;
  return enter.functions()->RequestInputEvents(instance, event_classes);
}

int32_t RequestFilteringInputEvents(PP_Instance instance,
                                    uint32_t event_classes) {
  EnterInstance enter(instance, true);
  if (enter.failed())
    return PP_ERROR_BADARGUMENT;
  return enter.functions()->RequestFilteringInputEvents(instance,
                                                        event_classes);
}

void ClearInputEventRequest(PP_Instance instance,
                            uint32_t event_classes) {
  EnterInstance enter(instance, true);
  if (enter.succeeded())
    enter.functions()->ClearInputEventRequest(instance, event_classes);
}

PP_Bool IsInputEvent(PP_Resource resource) {
  EnterInputEvent enter(resource, false);
  return enter.succeeded() ? PP_TRUE : PP_FALSE;
}

PP_InputEvent_Type GetType(PP_Resource event) {
  EnterInputEvent enter(event, true);
  if (enter.failed())
    return PP_INPUTEVENT_TYPE_UNDEFINED;
  return enter.object()->GetType();
}

PP_TimeTicks GetTimeStamp(PP_Resource event) {
  EnterInputEvent enter(event, true);
  if (enter.failed())
    return 0.0;
  return enter.object()->GetTimeStamp();
}

uint32_t GetModifiers(PP_Resource event) {
  EnterInputEvent enter(event, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetModifiers();
}

const PPB_InputEvent g_ppb_input_event_thunk = {
  &RequestInputEvents,
  &RequestFilteringInputEvents,
  &ClearInputEventRequest,
  &IsInputEvent,
  &GetType,
  &GetTimeStamp,
  &GetModifiers
};

// Mouse -----------------------------------------------------------------------

PP_Resource CreateMouseInputEvent(PP_Instance instance,
                                  PP_InputEvent_Type type,
                                  PP_TimeTicks time_stamp,
                                  uint32_t modifiers,
                                  PP_InputEvent_MouseButton mouse_button,
                                  const PP_Point* mouse_position,
                                  int32_t click_count) {
  EnterFunction<ResourceCreationAPI> enter(instance, true);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateMouseInputEvent(instance, type, time_stamp,
                                                  modifiers, mouse_button,
                                                  mouse_position, click_count);
}

PP_Bool IsMouseInputEvent(PP_Resource resource) {
  if (!IsInputEvent(resource))
    return PP_FALSE;  // Prevent warning log in GetType.
  PP_InputEvent_Type type = GetType(resource);
  return PP_FromBool(type == PP_INPUTEVENT_TYPE_MOUSEDOWN ||
                     type == PP_INPUTEVENT_TYPE_MOUSEUP ||
                     type == PP_INPUTEVENT_TYPE_MOUSEMOVE ||
                     type == PP_INPUTEVENT_TYPE_MOUSEENTER ||
                     type == PP_INPUTEVENT_TYPE_MOUSELEAVE ||
                     type == PP_INPUTEVENT_TYPE_CONTEXTMENU);
}

PP_InputEvent_MouseButton GetMouseButton(PP_Resource mouse_event) {
  EnterInputEvent enter(mouse_event, true);
  if (enter.failed())
    return PP_INPUTEVENT_MOUSEBUTTON_NONE;
  return enter.object()->GetMouseButton();
}

PP_Point GetMousePosition(PP_Resource mouse_event) {
  EnterInputEvent enter(mouse_event, true);
  if (enter.failed())
    return PP_MakePoint(0, 0);
  return enter.object()->GetMousePosition();
}

int32_t GetMouseClickCount(PP_Resource mouse_event) {
  EnterInputEvent enter(mouse_event, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetMouseClickCount();
}

const PPB_MouseInputEvent g_ppb_mouse_input_event_thunk = {
  &CreateMouseInputEvent,
  &IsMouseInputEvent,
  &GetMouseButton,
  &GetMousePosition,
  &GetMouseClickCount
};

// Wheel -----------------------------------------------------------------------

PP_Resource CreateWheelInputEvent(PP_Instance instance,
                                  PP_TimeTicks time_stamp,
                                  uint32_t modifiers,
                                  const PP_FloatPoint* wheel_delta,
                                  const PP_FloatPoint* wheel_ticks,
                                  PP_Bool scroll_by_page) {
  EnterFunction<ResourceCreationAPI> enter(instance, true);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateWheelInputEvent(instance, time_stamp,
                                                  modifiers, wheel_delta,
                                                  wheel_ticks, scroll_by_page);
}

PP_Bool IsWheelInputEvent(PP_Resource resource) {
  if (!IsInputEvent(resource))
    return PP_FALSE;  // Prevent warning log in GetType.
  PP_InputEvent_Type type = GetType(resource);
  return PP_FromBool(type == PP_INPUTEVENT_TYPE_WHEEL);
}

PP_FloatPoint GetWheelDelta(PP_Resource wheel_event) {
  EnterInputEvent enter(wheel_event, true);
  if (enter.failed())
    return PP_MakeFloatPoint(0.0f, 0.0f);
  return enter.object()->GetWheelDelta();
}

PP_FloatPoint GetWheelTicks(PP_Resource wheel_event) {
  EnterInputEvent enter(wheel_event, true);
  if (enter.failed())
    return PP_MakeFloatPoint(0.0f, 0.0f);
  return enter.object()->GetWheelTicks();
}

PP_Bool GetWheelScrollByPage(PP_Resource wheel_event) {
  EnterInputEvent enter(wheel_event, true);
  if (enter.failed())
    return PP_FALSE;
  return enter.object()->GetWheelScrollByPage();
}

const PPB_WheelInputEvent g_ppb_wheel_input_event_thunk = {
  &CreateWheelInputEvent,
  &IsWheelInputEvent,
  &GetWheelDelta,
  &GetWheelTicks,
  &GetWheelScrollByPage
};

// Keyboard --------------------------------------------------------------------

PP_Resource CreateKeyboardInputEvent(PP_Instance instance,
                                     PP_InputEvent_Type type,
                                     PP_TimeTicks time_stamp,
                                     uint32_t modifiers,
                                     uint32_t key_code,
                                     struct PP_Var character_text) {
  EnterFunction<ResourceCreationAPI> enter(instance, true);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateKeyboardInputEvent(instance, type, time_stamp,
                                                     modifiers, key_code,
                                                     character_text);
}

PP_Bool IsKeyboardInputEvent(PP_Resource resource) {
  if (!IsInputEvent(resource))
    return PP_FALSE;  // Prevent warning log in GetType.
  PP_InputEvent_Type type = GetType(resource);
  return PP_FromBool(type == PP_INPUTEVENT_TYPE_KEYDOWN ||
                     type == PP_INPUTEVENT_TYPE_KEYUP ||
                     type == PP_INPUTEVENT_TYPE_CHAR);
}

uint32_t GetKeyCode(PP_Resource key_event) {
  EnterInputEvent enter(key_event, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetKeyCode();
}

PP_Var GetCharacterText(PP_Resource character_event) {
  EnterInputEvent enter(character_event, true);
  if (enter.failed())
    return PP_MakeUndefined();
  return enter.object()->GetCharacterText();
}

const PPB_KeyboardInputEvent g_ppb_keyboard_input_event_thunk = {
  &CreateKeyboardInputEvent,
  &IsKeyboardInputEvent,
  &GetKeyCode,
  &GetCharacterText
};

}  // namespace

const PPB_InputEvent* GetPPB_InputEvent_Thunk() {
  return &g_ppb_input_event_thunk;
}

const PPB_MouseInputEvent* GetPPB_MouseInputEvent_Thunk() {
  return &g_ppb_mouse_input_event_thunk;
}

const PPB_KeyboardInputEvent* GetPPB_KeyboardInputEvent_Thunk() {
  return &g_ppb_keyboard_input_event_thunk;
}

const PPB_WheelInputEvent* GetPPB_WheelInputEvent_Thunk() {
  return &g_ppb_wheel_input_event_thunk;
}

}  // namespace thunk
}  // namespace ppapi
<commit_msg>Fix raw key down events in Pepper.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/c/pp_errors.h"
#include "ppapi/thunk/thunk.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_input_event_api.h"
#include "ppapi/thunk/ppb_instance_api.h"
#include "ppapi/thunk/resource_creation_api.h"

namespace ppapi {
namespace thunk {

namespace {

typedef EnterFunction<PPB_Instance_FunctionAPI> EnterInstance;
typedef EnterResource<PPB_InputEvent_API> EnterInputEvent;

// InputEvent ------------------------------------------------------------------

int32_t RequestInputEvents(PP_Instance instance, uint32_t event_classes) {
  EnterInstance enter(instance, true);
  if (enter.failed())
    return PP_ERROR_BADARGUMENT;
  return enter.functions()->RequestInputEvents(instance, event_classes);
}

int32_t RequestFilteringInputEvents(PP_Instance instance,
                                    uint32_t event_classes) {
  EnterInstance enter(instance, true);
  if (enter.failed())
    return PP_ERROR_BADARGUMENT;
  return enter.functions()->RequestFilteringInputEvents(instance,
                                                        event_classes);
}

void ClearInputEventRequest(PP_Instance instance,
                            uint32_t event_classes) {
  EnterInstance enter(instance, true);
  if (enter.succeeded())
    enter.functions()->ClearInputEventRequest(instance, event_classes);
}

PP_Bool IsInputEvent(PP_Resource resource) {
  EnterInputEvent enter(resource, false);
  return enter.succeeded() ? PP_TRUE : PP_FALSE;
}

PP_InputEvent_Type GetType(PP_Resource event) {
  EnterInputEvent enter(event, true);
  if (enter.failed())
    return PP_INPUTEVENT_TYPE_UNDEFINED;
  return enter.object()->GetType();
}

PP_TimeTicks GetTimeStamp(PP_Resource event) {
  EnterInputEvent enter(event, true);
  if (enter.failed())
    return 0.0;
  return enter.object()->GetTimeStamp();
}

uint32_t GetModifiers(PP_Resource event) {
  EnterInputEvent enter(event, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetModifiers();
}

const PPB_InputEvent g_ppb_input_event_thunk = {
  &RequestInputEvents,
  &RequestFilteringInputEvents,
  &ClearInputEventRequest,
  &IsInputEvent,
  &GetType,
  &GetTimeStamp,
  &GetModifiers
};

// Mouse -----------------------------------------------------------------------

PP_Resource CreateMouseInputEvent(PP_Instance instance,
                                  PP_InputEvent_Type type,
                                  PP_TimeTicks time_stamp,
                                  uint32_t modifiers,
                                  PP_InputEvent_MouseButton mouse_button,
                                  const PP_Point* mouse_position,
                                  int32_t click_count) {
  EnterFunction<ResourceCreationAPI> enter(instance, true);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateMouseInputEvent(instance, type, time_stamp,
                                                  modifiers, mouse_button,
                                                  mouse_position, click_count);
}

PP_Bool IsMouseInputEvent(PP_Resource resource) {
  if (!IsInputEvent(resource))
    return PP_FALSE;  // Prevent warning log in GetType.
  PP_InputEvent_Type type = GetType(resource);
  return PP_FromBool(type == PP_INPUTEVENT_TYPE_MOUSEDOWN ||
                     type == PP_INPUTEVENT_TYPE_MOUSEUP ||
                     type == PP_INPUTEVENT_TYPE_MOUSEMOVE ||
                     type == PP_INPUTEVENT_TYPE_MOUSEENTER ||
                     type == PP_INPUTEVENT_TYPE_MOUSELEAVE ||
                     type == PP_INPUTEVENT_TYPE_CONTEXTMENU);
}

PP_InputEvent_MouseButton GetMouseButton(PP_Resource mouse_event) {
  EnterInputEvent enter(mouse_event, true);
  if (enter.failed())
    return PP_INPUTEVENT_MOUSEBUTTON_NONE;
  return enter.object()->GetMouseButton();
}

PP_Point GetMousePosition(PP_Resource mouse_event) {
  EnterInputEvent enter(mouse_event, true);
  if (enter.failed())
    return PP_MakePoint(0, 0);
  return enter.object()->GetMousePosition();
}

int32_t GetMouseClickCount(PP_Resource mouse_event) {
  EnterInputEvent enter(mouse_event, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetMouseClickCount();
}

const PPB_MouseInputEvent g_ppb_mouse_input_event_thunk = {
  &CreateMouseInputEvent,
  &IsMouseInputEvent,
  &GetMouseButton,
  &GetMousePosition,
  &GetMouseClickCount
};

// Wheel -----------------------------------------------------------------------

PP_Resource CreateWheelInputEvent(PP_Instance instance,
                                  PP_TimeTicks time_stamp,
                                  uint32_t modifiers,
                                  const PP_FloatPoint* wheel_delta,
                                  const PP_FloatPoint* wheel_ticks,
                                  PP_Bool scroll_by_page) {
  EnterFunction<ResourceCreationAPI> enter(instance, true);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateWheelInputEvent(instance, time_stamp,
                                                  modifiers, wheel_delta,
                                                  wheel_ticks, scroll_by_page);
}

PP_Bool IsWheelInputEvent(PP_Resource resource) {
  if (!IsInputEvent(resource))
    return PP_FALSE;  // Prevent warning log in GetType.
  PP_InputEvent_Type type = GetType(resource);
  return PP_FromBool(type == PP_INPUTEVENT_TYPE_WHEEL);
}

PP_FloatPoint GetWheelDelta(PP_Resource wheel_event) {
  EnterInputEvent enter(wheel_event, true);
  if (enter.failed())
    return PP_MakeFloatPoint(0.0f, 0.0f);
  return enter.object()->GetWheelDelta();
}

PP_FloatPoint GetWheelTicks(PP_Resource wheel_event) {
  EnterInputEvent enter(wheel_event, true);
  if (enter.failed())
    return PP_MakeFloatPoint(0.0f, 0.0f);
  return enter.object()->GetWheelTicks();
}

PP_Bool GetWheelScrollByPage(PP_Resource wheel_event) {
  EnterInputEvent enter(wheel_event, true);
  if (enter.failed())
    return PP_FALSE;
  return enter.object()->GetWheelScrollByPage();
}

const PPB_WheelInputEvent g_ppb_wheel_input_event_thunk = {
  &CreateWheelInputEvent,
  &IsWheelInputEvent,
  &GetWheelDelta,
  &GetWheelTicks,
  &GetWheelScrollByPage
};

// Keyboard --------------------------------------------------------------------

PP_Resource CreateKeyboardInputEvent(PP_Instance instance,
                                     PP_InputEvent_Type type,
                                     PP_TimeTicks time_stamp,
                                     uint32_t modifiers,
                                     uint32_t key_code,
                                     struct PP_Var character_text) {
  EnterFunction<ResourceCreationAPI> enter(instance, true);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateKeyboardInputEvent(instance, type, time_stamp,
                                                     modifiers, key_code,
                                                     character_text);
}

PP_Bool IsKeyboardInputEvent(PP_Resource resource) {
  if (!IsInputEvent(resource))
    return PP_FALSE;  // Prevent warning log in GetType.
  PP_InputEvent_Type type = GetType(resource);
  return PP_FromBool(type == PP_INPUTEVENT_TYPE_KEYDOWN ||
                     type == PP_INPUTEVENT_TYPE_KEYUP ||
                     type == PP_INPUTEVENT_TYPE_RAWKEYDOWN ||
                     type == PP_INPUTEVENT_TYPE_CHAR);
}

uint32_t GetKeyCode(PP_Resource key_event) {
  EnterInputEvent enter(key_event, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetKeyCode();
}

PP_Var GetCharacterText(PP_Resource character_event) {
  EnterInputEvent enter(character_event, true);
  if (enter.failed())
    return PP_MakeUndefined();
  return enter.object()->GetCharacterText();
}

const PPB_KeyboardInputEvent g_ppb_keyboard_input_event_thunk = {
  &CreateKeyboardInputEvent,
  &IsKeyboardInputEvent,
  &GetKeyCode,
  &GetCharacterText
};

}  // namespace

const PPB_InputEvent* GetPPB_InputEvent_Thunk() {
  return &g_ppb_input_event_thunk;
}

const PPB_MouseInputEvent* GetPPB_MouseInputEvent_Thunk() {
  return &g_ppb_mouse_input_event_thunk;
}

const PPB_KeyboardInputEvent* GetPPB_KeyboardInputEvent_Thunk() {
  return &g_ppb_keyboard_input_event_thunk;
}

const PPB_WheelInputEvent* GetPPB_WheelInputEvent_Thunk() {
  return &g_ppb_wheel_input_event_thunk;
}

}  // namespace thunk
}  // namespace ppapi
<|endoftext|>


<commit_before>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CQPreferenceDialog.h"
#include "CQMessageBox.h"

#include "copasi.h"
#include "qtUtilities.h"

#include "commandline/CConfigurationFile.h"
#include "copasi/core/CRootContainer.h"

#define COL_NAME 0
#define COL_VALUE 1

/*
 *  Constructs a CQPreferenceDialog as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  true to construct a modal dialog.
 */
CQPreferenceDialog::CQPreferenceDialog(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)
  : QDialog(parent, fl)
  , mpConfiguration(NULL)
{
  setObjectName(QString::fromUtf8(name));
  setModal(modal);
  setupUi(this);

  init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQPreferenceDialog::~CQPreferenceDialog()
{
  if (mpConfiguration != NULL)
    {
      delete mpConfiguration;
      mpConfiguration = NULL;
    }
}

void CQPreferenceDialog::init()
{
  CConfigurationFile * pConfigFile = CRootContainer::getConfiguration();

  if (pConfigFile != NULL)
    {
      mpConfiguration = new CConfigurationFile(*pConfigFile, NO_PARENT);
    }

  mpTreeView->setAdvanced(false);
  mpTreeView->pushGroup(mpConfiguration);
}

void CQPreferenceDialog::slotBtnOk()
{
  if (mpConfiguration != NULL)
    {
      *CRootContainer::getConfiguration() = *mpConfiguration;
      delete mpConfiguration;
      mpConfiguration = NULL;
    }

  done(1);
}

// virtual
void CQPreferenceDialog::slotBtnCancel()
{
  if (mpConfiguration != NULL)
    {
      delete mpConfiguration;
      mpConfiguration = NULL;
    }

  done(0);
}
<commit_msg>- fix crash that occurs if Qt issues some operation on the treeview after the items have been deleted<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CQPreferenceDialog.h"
#include "CQMessageBox.h"

#include "copasi.h"
#include "qtUtilities.h"

#include "commandline/CConfigurationFile.h"
#include "copasi/core/CRootContainer.h"

#define COL_NAME 0
#define COL_VALUE 1

/*
 *  Constructs a CQPreferenceDialog as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  true to construct a modal dialog.
 */
CQPreferenceDialog::CQPreferenceDialog(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)
  : QDialog(parent, fl)
  , mpConfiguration(NULL)
{
  setObjectName(QString::fromUtf8(name));
  setModal(modal);
  setupUi(this);

  init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQPreferenceDialog::~CQPreferenceDialog()
{
  if (mpConfiguration != NULL)
    {
      delete mpConfiguration;
      mpConfiguration = NULL;
    }
}

void CQPreferenceDialog::init()
{
  CConfigurationFile * pConfigFile = CRootContainer::getConfiguration();

  if (pConfigFile != NULL)
    {
      mpConfiguration = new CConfigurationFile(*pConfigFile, NO_PARENT);
    }

  mpTreeView->setAdvanced(false);
  mpTreeView->pushGroup(mpConfiguration);
}

void CQPreferenceDialog::slotBtnOk()
{
  if (mpConfiguration != NULL)
    {
      *CRootContainer::getConfiguration() = *mpConfiguration;

      // remove items from tree, otherwise node pointers will become invalid
      mpTreeView->clearGroups();

      delete mpConfiguration;
      mpConfiguration = NULL;
    }

  done(1);
}

// virtual
void CQPreferenceDialog::slotBtnCancel()
{
  if (mpConfiguration != NULL)
    {
      // remove items from tree, otherwise node pointers will become invalid
      mpTreeView->clearGroups();

      delete mpConfiguration;
      mpConfiguration = NULL;
    }

  done(0);
}
<|endoftext|>


<commit_before>/**
 *  CMathSymbol class.
 *  The class CMathSymbol associates a symbol with a CCopasiObject assuring
 *  that the symbol name is unique.
 *  Symbols are used to enhance redability of mathematical expresions.
 *
 *  Created for Copasi by Stefan Hoops 2003
 */
#include <sstream>

#include "copasi.h"
#include "CMathSymbol.h"

std::map< std::string, CMathSymbol * > CMathSymbol::mList;

std::string & CMathSymbol::alternateName(std::string & name)
{
  unsigned C_INT32 count = 1;
  stringstream tmpName;
  tmpName << name;

  while (mList.count(tmpName.str()))
    tmpName << name << "_" << count++;

  return name = tmpName.str();
}

CMathSymbol * CMathSymbol::find(const CCopasiObject * pObject)
{
  std::map< std::string, CMathSymbol * >::iterator it = mList.begin();
  std::map< std::string, CMathSymbol * >::iterator end = mList.end();

  while (it != end && it->second->getObject() != pObject) it++;

  if (it == end) return NULL;
  else return it->second;
}

CMathSymbol::CMathSymbol():
    mName(),
    mCN(),
    mpObject(NULL)
{}

CMathSymbol::CMathSymbol(std::string & name):
    mName(alternateName(name)),
    mCN(),
    mpObject(NULL)
{mList[mName] = this;}

CMathSymbol::CMathSymbol(const CCopasiObject * pObject):
    mName(pObject->getObjectName()),
    mCN(pObject->getCN()),
    mpObject(const_cast< CCopasiObject * >(pObject))
{
  alternateName(mName);
  mList[mName] = this;
}

CMathSymbol::CMathSymbol(const CMathSymbol & src):
    mName("copy of " + src.mName),
    mCN(src.mCN),
    mpObject(src.mpObject)
{
  alternateName(mName);
  mList[mName] = this;
}

CMathSymbol::~CMathSymbol() {mList.erase(mName);}

bool CMathSymbol::setName(std::string & name)
{
  mList.erase(mName);

  mName = name;
  if (alternateName(mName) == name)
    {
      mList[mName] = this;
      return true;
    }
  else
    {
      mList[mName] = this;
      return false;
    }
}

const std::string & CMathSymbol::getName() const {return mName;}

bool CMathSymbol::setCN(const CCopasiObjectName & cn,
                        const CCopasiContainer * pContainer)
{
  mCN = cn;
  mpObject = const_cast<CCopasiContainer *>(pContainer)->getObject(mCN);
  if (mpObject)
    return true;
  else
    return false;
}

const CCopasiObjectName & CMathSymbol::getCN() const {return mCN;}

bool CMathSymbol::setObject(CCopasiObject * pObject)
{
  mpObject = pObject;
  return true;
}

const CCopasiObject * CMathSymbol::getObject() const {return mpObject;}

CCopasiObject * CMathSymbol::getObject() {return mpObject;}
<commit_msg>Fixes to work under Visual C++.<commit_after>/**
 *  CMathSymbol class.
 *  The class CMathSymbol associates a symbol with a CCopasiObject assuring
 *  that the symbol name is unique.
 *  Symbols are used to enhance redability of mathematical expresions.
 *
 *  Created for Copasi by Stefan Hoops 2003
 */
#include <sstream>

#include "copasi.h"
#include "CMathSymbol.h"

std::map< std::string, CMathSymbol * > CMathSymbol::mList;

std::string & CMathSymbol::alternateName(std::string & name)
{
  unsigned C_INT32 count = 1;
  std::stringstream tmpName;
  tmpName << name;

  while (mList.count(tmpName.str()))
    tmpName << name << "_" << count++;

  return name = tmpName.str();
}

CMathSymbol * CMathSymbol::find(const CCopasiObject * pObject)
{
  std::map< std::string, CMathSymbol * >::iterator it = mList.begin();
  std::map< std::string, CMathSymbol * >::iterator end = mList.end();

  while (it != end && it->second->getObject() != pObject) it++;

  if (it == end) return NULL;
  else return it->second;
}

CMathSymbol::CMathSymbol():
    mName(),
    mCN(),
    mpObject(NULL)
{}

CMathSymbol::CMathSymbol(std::string & name):
    mName(alternateName(name)),
    mCN(),
    mpObject(NULL)
{mList[mName] = this;}

CMathSymbol::CMathSymbol(const CCopasiObject * pObject):
    mName(pObject->getObjectName()),
    mCN(pObject->getCN()),
    mpObject(const_cast< CCopasiObject * >(pObject))
{
  alternateName(mName);
  mList[mName] = this;
}

CMathSymbol::CMathSymbol(const CMathSymbol & src):
    mName("copy of " + src.mName),
    mCN(src.mCN),
    mpObject(src.mpObject)
{
  alternateName(mName);
  mList[mName] = this;
}

CMathSymbol::~CMathSymbol() {mList.erase(mName);}

bool CMathSymbol::setName(std::string & name)
{
  mList.erase(mName);

  mName = name;
  if (alternateName(mName) == name)
    {
      mList[mName] = this;
      return true;
    }
  else
    {
      mList[mName] = this;
      return false;
    }
}

const std::string & CMathSymbol::getName() const {return mName;}

bool CMathSymbol::setCN(const CCopasiObjectName & cn,
                        const CCopasiContainer * pContainer)
{
  mCN = cn;
  mpObject = const_cast<CCopasiContainer *>(pContainer)->getObject(mCN);
  if (mpObject)
    return true;
  else
    return false;
}

const CCopasiObjectName & CMathSymbol::getCN() const {return mCN;}

bool CMathSymbol::setObject(CCopasiObject * pObject)
{
  mpObject = pObject;
  return true;
}

const CCopasiObject * CMathSymbol::getObject() const {return mpObject;}

CCopasiObject * CMathSymbol::getObject() {return mpObject;}
<|endoftext|>


<commit_before>#include "browser/views/inspectable_web_contents_view_views.h"

#include "browser/inspectable_web_contents_impl.h"

#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"

namespace brightray {

namespace {

class DevToolsWindowDelegate : public views::ClientView,
                               public views::WidgetDelegate {
 public:
  DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
                         views::View* view,
                         views::Widget* widget)
      : views::ClientView(widget_, view),
        shell_(shell),
        view_(view),
        widget_(widget),
        title_(base::ASCIIToUTF16("Developer Tools")) {
    // A WidgetDelegate should be deleted on DeleteDelegate.
    set_owned_by_client();
  }
  virtual ~DevToolsWindowDelegate() {}

  // views::WidgetDelegate:
  virtual void DeleteDelegate() OVERRIDE { delete this; }
  virtual views::View* GetInitiallyFocusedView() OVERRIDE { return view_; }
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return false; }
  virtual base::string16 GetWindowTitle() const OVERRIDE { return title_; }
  virtual views::Widget* GetWidget() OVERRIDE { return widget_; }
  virtual const views::Widget* GetWidget() const OVERRIDE { return widget_; }
  virtual views::View* GetContentsView() OVERRIDE { return view_; }
  virtual views::ClientView* CreateClientView(views::Widget* widget) { return this; }

  // views::ClientView:
  virtual bool CanClose() OVERRIDE {
    shell_->inspectable_web_contents()->CloseDevTools();
    return false;
  }

 private:
  InspectableWebContentsViewViews* shell_;
  views::View* view_;
  views::Widget* widget_;
  base::string16 title_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};

}  // namespace

InspectableWebContentsView* CreateInspectableContentsView(
    InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewViews(inspectable_web_contents);
}

InspectableWebContentsViewViews::InspectableWebContentsViewViews(
    InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents),
      devtools_window_web_view_(NULL),
      contents_web_view_(new views::WebView(NULL)),
      devtools_web_view_(new views::WebView(NULL)),
      devtools_visible_(false) {
  set_owned_by_client();

  devtools_web_view_->SetVisible(false);
  contents_web_view_->SetWebContents(inspectable_web_contents_->GetWebContents());
  AddChildView(devtools_web_view_);
  AddChildView(contents_web_view_);
}

InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
  if (devtools_window_)
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}

views::View* InspectableWebContentsViewViews::GetView() {
  return this;
}

views::View* InspectableWebContentsViewViews::GetWebView() {
  return contents_web_view_;
}

void InspectableWebContentsViewViews::ShowDevTools() {
  if (devtools_visible_)
    return;

  devtools_visible_ = true;
  if (devtools_window_) {
    devtools_window_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
    devtools_window_->Show();
  } else {
    devtools_web_view_->SetVisible(true);
    devtools_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_web_view_->RequestFocus();
    Layout();
  }
}

void InspectableWebContentsViewViews::CloseDevTools() {
  if (!devtools_visible_)
    return;

  devtools_visible_ = false;
  if (devtools_window_) {
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
    devtools_window_.reset();
    devtools_window_web_view_ = NULL;
  } else {
    devtools_web_view_->SetVisible(false);
    devtools_web_view_->SetWebContents(NULL);
    Layout();
  }
}

bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
  return devtools_visible_;
}

void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
  CloseDevTools();

  if (!docked) {
    devtools_window_.reset(new views::Widget);
    devtools_window_web_view_ = new views::WebView(NULL);

    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.delegate = new DevToolsWindowDelegate(this,
                                                 devtools_window_web_view_,
                                                 devtools_window_.get());
    params.top_level = true;
    params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if defined(USE_X11)
    // In X11 the window frame is drawn by the application.
    params.remove_standard_frame = true;
#endif
    devtools_window_->Init(params);
  }

  ShowDevTools();
}

void InspectableWebContentsViewViews::SetContentsResizingStrategy(
    const DevToolsContentsResizingStrategy& strategy) {
  strategy_.CopyFrom(strategy);
  Layout();
}

void InspectableWebContentsViewViews::Layout() {
  if (!devtools_web_view_->visible()) {
    contents_web_view_->SetBoundsRect(GetContentsBounds());
    return;
  }

  gfx::Size container_size(width(), height());
  gfx::Rect old_devtools_bounds(devtools_web_view_->bounds());
  gfx::Rect old_contents_bounds(contents_web_view_->bounds());
  gfx::Rect new_devtools_bounds;
  gfx::Rect new_contents_bounds;
  ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
      old_devtools_bounds, old_contents_bounds,
      &new_devtools_bounds, &new_contents_bounds);

  // DevTools cares about the specific position, so we have to compensate RTL
  // layout here.
  new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
  new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));

  devtools_web_view_->SetBoundsRect(new_devtools_bounds);
  contents_web_view_->SetBoundsRect(new_contents_bounds);
}

}  // namespace brightray
<commit_msg>Fix "warning: field 'widget_' is uninitialized when used here".<commit_after>#include "browser/views/inspectable_web_contents_view_views.h"

#include "browser/inspectable_web_contents_impl.h"

#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"

namespace brightray {

namespace {

class DevToolsWindowDelegate : public views::ClientView,
                               public views::WidgetDelegate {
 public:
  DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
                         views::View* view,
                         views::Widget* widget)
      : views::ClientView(widget, view),
        shell_(shell),
        view_(view),
        widget_(widget),
        title_(base::ASCIIToUTF16("Developer Tools")) {
    // A WidgetDelegate should be deleted on DeleteDelegate.
    set_owned_by_client();
  }
  virtual ~DevToolsWindowDelegate() {}

  // views::WidgetDelegate:
  virtual void DeleteDelegate() OVERRIDE { delete this; }
  virtual views::View* GetInitiallyFocusedView() OVERRIDE { return view_; }
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return false; }
  virtual base::string16 GetWindowTitle() const OVERRIDE { return title_; }
  virtual views::Widget* GetWidget() OVERRIDE { return widget_; }
  virtual const views::Widget* GetWidget() const OVERRIDE { return widget_; }
  virtual views::View* GetContentsView() OVERRIDE { return view_; }
  virtual views::ClientView* CreateClientView(views::Widget* widget) { return this; }

  // views::ClientView:
  virtual bool CanClose() OVERRIDE {
    shell_->inspectable_web_contents()->CloseDevTools();
    return false;
  }

 private:
  InspectableWebContentsViewViews* shell_;
  views::View* view_;
  views::Widget* widget_;
  base::string16 title_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};

}  // namespace

InspectableWebContentsView* CreateInspectableContentsView(
    InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewViews(inspectable_web_contents);
}

InspectableWebContentsViewViews::InspectableWebContentsViewViews(
    InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents),
      devtools_window_web_view_(NULL),
      contents_web_view_(new views::WebView(NULL)),
      devtools_web_view_(new views::WebView(NULL)),
      devtools_visible_(false) {
  set_owned_by_client();

  devtools_web_view_->SetVisible(false);
  contents_web_view_->SetWebContents(inspectable_web_contents_->GetWebContents());
  AddChildView(devtools_web_view_);
  AddChildView(contents_web_view_);
}

InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
  if (devtools_window_)
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}

views::View* InspectableWebContentsViewViews::GetView() {
  return this;
}

views::View* InspectableWebContentsViewViews::GetWebView() {
  return contents_web_view_;
}

void InspectableWebContentsViewViews::ShowDevTools() {
  if (devtools_visible_)
    return;

  devtools_visible_ = true;
  if (devtools_window_) {
    devtools_window_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
    devtools_window_->Show();
  } else {
    devtools_web_view_->SetVisible(true);
    devtools_web_view_->SetWebContents(inspectable_web_contents_->devtools_web_contents());
    devtools_web_view_->RequestFocus();
    Layout();
  }
}

void InspectableWebContentsViewViews::CloseDevTools() {
  if (!devtools_visible_)
    return;

  devtools_visible_ = false;
  if (devtools_window_) {
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
    devtools_window_.reset();
    devtools_window_web_view_ = NULL;
  } else {
    devtools_web_view_->SetVisible(false);
    devtools_web_view_->SetWebContents(NULL);
    Layout();
  }
}

bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
  return devtools_visible_;
}

void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
  CloseDevTools();

  if (!docked) {
    devtools_window_.reset(new views::Widget);
    devtools_window_web_view_ = new views::WebView(NULL);

    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.delegate = new DevToolsWindowDelegate(this,
                                                 devtools_window_web_view_,
                                                 devtools_window_.get());
    params.top_level = true;
    params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if defined(USE_X11)
    // In X11 the window frame is drawn by the application.
    params.remove_standard_frame = true;
#endif
    devtools_window_->Init(params);
  }

  ShowDevTools();
}

void InspectableWebContentsViewViews::SetContentsResizingStrategy(
    const DevToolsContentsResizingStrategy& strategy) {
  strategy_.CopyFrom(strategy);
  Layout();
}

void InspectableWebContentsViewViews::Layout() {
  if (!devtools_web_view_->visible()) {
    contents_web_view_->SetBoundsRect(GetContentsBounds());
    return;
  }

  gfx::Size container_size(width(), height());
  gfx::Rect old_devtools_bounds(devtools_web_view_->bounds());
  gfx::Rect old_contents_bounds(contents_web_view_->bounds());
  gfx::Rect new_devtools_bounds;
  gfx::Rect new_contents_bounds;
  ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
      old_devtools_bounds, old_contents_bounds,
      &new_devtools_bounds, &new_contents_bounds);

  // DevTools cares about the specific position, so we have to compensate RTL
  // layout here.
  new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
  new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));

  devtools_web_view_->SetBoundsRect(new_devtools_bounds);
  contents_web_view_->SetBoundsRect(new_contents_bounds);
}

}  // namespace brightray
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/kind.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file dimm.H
/// @brief Encapsulation for dimms of all types
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Craig Hamilton <cchamilt@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP

#ifndef _MSS_DIMM_H_
#define _MSS_DIMM_H_

#include <fapi2.H>

#include <mss_attribute_accessors.H>
#include "../utils/c_str.H"

namespace mss
{

namespace dimm
{

///
/// @class mss::dimm::kind
/// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it?
///
class kind
{
    public:

        kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target):
            iv_target(i_target)
        {
            FAPI_TRY( mss::eff_dram_gen(i_target, iv_dram_generation) );
            FAPI_TRY( mss::eff_dimm_type(i_target, iv_dimm_type) );
            FAPI_TRY( mss::eff_dram_density(i_target, iv_dram_density) );
            FAPI_TRY( mss::eff_dram_width(i_target, iv_dram_width) );
            FAPI_TRY( mss::eff_num_master_ranks_per_dimm(i_target, iv_master_ranks) );
            FAPI_TRY( mss::eff_dram_row_bits(i_target, iv_rows) );
            FAPI_TRY( mss::eff_dimm_size(i_target, iv_size) );

            // TK: Attribute for slave ranks.
            iv_slave_ranks = 0;

        fapi_try_exit:
            // Not 100% sure what to do here ...
            FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err));
        }

        const fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target;
        uint8_t iv_master_ranks;
        uint8_t iv_slave_ranks;
        uint8_t iv_dram_density;
        uint8_t iv_dram_width;
        uint8_t iv_dram_generation;
        uint8_t iv_dimm_type;
        uint8_t iv_rows;
        uint32_t iv_size;
};

}

}
#endif
<commit_msg>Change comments, return code for mcbist 2 port testing<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/kind.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file dimm.H
/// @brief Encapsulation for dimms of all types
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Craig Hamilton <cchamilt@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP

#ifndef _MSS_DIMM_H_
#define _MSS_DIMM_H_

#include <fapi2.H>

#include <mss_attribute_accessors.H>
#include "../utils/c_str.H"

namespace mss
{

namespace dimm
{

///
/// @class mss::dimm::kind
/// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it?
///
class kind
{
    public:

        kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target):
            iv_target(i_target)
        {
            FAPI_TRY( mss::eff_dram_gen(i_target, iv_dram_generation) );
            FAPI_TRY( mss::eff_dimm_type(i_target, iv_dimm_type) );
            FAPI_TRY( mss::eff_dram_density(i_target, iv_dram_density) );
            FAPI_TRY( mss::eff_dram_width(i_target, iv_dram_width) );
            FAPI_TRY( mss::eff_num_master_ranks_per_dimm(i_target, iv_master_ranks) );
            FAPI_TRY( mss::eff_dram_row_bits(i_target, iv_rows) );
            FAPI_TRY( mss::eff_dimm_size(i_target, iv_size) );

            // TK: Attribute for slave ranks.
            iv_slave_ranks = 0;

            return;

        fapi_try_exit:
            // Not 100% sure what to do here ...
            FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err));
        }

        const fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target;
        uint8_t iv_master_ranks;
        uint8_t iv_slave_ranks;
        uint8_t iv_dram_density;
        uint8_t iv_dram_width;
        uint8_t iv_dram_generation;
        uint8_t iv_dimm_type;
        uint8_t iv_rows;
        uint32_t iv_size;
};

}

}
#endif
<|endoftext|>