<commit_before>/*
 * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <vector>

#include "h2olog.h"

using namespace std;

#define VERSION "0.1.0"
#define POLL_TIMEOUT (-1)

static void usage(void)
{
    printf("h2olog (%s)\n", VERSION);
    printf("-p PID of the H2O server\n");
    printf("-h Print this help and exit\n");
    return;
}

static void show_event_per_sec(h2o_tracer_t *tracer, time_t t0)
{
    time_t t1 = time(NULL);
    int64_t d = t1 - t0;
    if (d > 10) {
        uint64_t c = tracer->count / d;
        if (c > 0) {
            struct tm t;
            localtime_r(&t1, &t);
            char s[100];
            strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S%z", &t);

            fprintf(stderr, "%s %20lu events/s\n", s, c);
            t0 = t1;

            tracer->count = 0;
        }
    }
}

int main(int argc, char **argv)
{
    h2o_tracer_t *tracer;
    if (argc > 1 && strcmp(argv[1], "quic") == 0) {
        tracer = create_quic_tracer();
        --argc;
        ++argv;
    } else {
        tracer = create_http_tracer();
    }

    bool debug = false;
    const char *out_file = nullptr;
    int c;
    pid_t h2o_pid = -1;
    while ((c = getopt(argc, argv, "hvp:t:s:dP:o:")) != -1) {
        switch (c) {
        case 'p':
            h2o_pid = atoi(optarg);
            break;
        case 'o':
            out_file = optarg;
            break;
        case 'd':
            debug = true;
            break;
        case 'h':
            usage();
            exit(EXIT_SUCCESS);
        }
    }

    if (h2o_pid == -1) {
        fprintf(stderr, "Error: -p option is missing\n");
        exit(EXIT_FAILURE);
    }

    if (geteuid() != 0) {
        fprintf(stderr, "Error: root privilege is required\n");
        exit(EXIT_FAILURE);
    }

    if (out_file != nullptr) {
        FILE *out = fopen(out_file, "w");
        if (out == nullptr) {
            fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
            exit(EXIT_FAILURE);
        }
        tracer->out = out;
    } else {
        tracer->out = stdout;
    }

    ebpf::BPF *bpf = new ebpf::BPF();
    std::vector<ebpf::USDT> probes = tracer->init_usdt_probes(h2o_pid);

    ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), {}, probes);
    if (ret.code() != 0) {
        fprintf(stderr, "init: %s\n", ret.msg().c_str());
        return EXIT_FAILURE;
    }

    for (auto &probe : probes) {
        ret = bpf->attach_usdt(probe);
        if (ret.code() != 0) {
            fprintf(stderr, "attach_usdt: %s\n", ret.msg().c_str());
            return EXIT_FAILURE;
        }
    }

    ret = bpf->open_perf_buffer("events", tracer->handle_event, nullptr, &tracer, 64);
    if (ret.code() != 0) {
        fprintf(stderr, "open_perf_buffer: %s\n", ret.msg().c_str());
        return EXIT_FAILURE;
    }

    if (debug) {
        fprintf(stderr, "attaching pid=%d\n", h2o_pid);
    }

    ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
    if (perf_buffer) {
        time_t t0 = time(NULL);

        while (true) {
            perf_buffer->poll(POLL_TIMEOUT);
            fflush(tracer->out);

            if (debug) {
                show_event_per_sec(tracer, t0);
                t0 = time(NULL);
            }
        }
    }

    fprintf(stderr, "Error: failed to get_perf_buffer()\n");
    return EXIT_FAILURE;
}
<commit_msg>fix use of context ptr<commit_after>/*
 * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <vector>

#include "h2olog.h"

using namespace std;

#define VERSION "0.1.0"
#define POLL_TIMEOUT (-1)

static void usage(void)
{
    printf("h2olog (%s)\n", VERSION);
    printf("-p PID of the H2O server\n");
    printf("-h Print this help and exit\n");
    return;
}

static void show_event_per_sec(h2o_tracer_t *tracer, time_t t0)
{
    time_t t1 = time(NULL);
    int64_t d = t1 - t0;
    if (d > 10) {
        uint64_t c = tracer->count / d;
        if (c > 0) {
            struct tm t;
            localtime_r(&t1, &t);
            char s[100];
            strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S%z", &t);

            fprintf(stderr, "%s %20lu events/s\n", s, c);
            t0 = t1;

            tracer->count = 0;
        }
    }
}

int main(int argc, char **argv)
{
    h2o_tracer_t *tracer;
    if (argc > 1 && strcmp(argv[1], "quic") == 0) {
        tracer = create_quic_tracer();
        --argc;
        ++argv;
    } else {
        tracer = create_http_tracer();
    }

    bool debug = false;
    const char *out_file = nullptr;
    int c;
    pid_t h2o_pid = -1;
    while ((c = getopt(argc, argv, "hvp:t:s:dP:o:")) != -1) {
        switch (c) {
        case 'p':
            h2o_pid = atoi(optarg);
            break;
        case 'o':
            out_file = optarg;
            break;
        case 'd':
            debug = true;
            break;
        case 'h':
            usage();
            exit(EXIT_SUCCESS);
        }
    }

    if (h2o_pid == -1) {
        fprintf(stderr, "Error: -p option is missing\n");
        exit(EXIT_FAILURE);
    }

    if (geteuid() != 0) {
        fprintf(stderr, "Error: root privilege is required\n");
        exit(EXIT_FAILURE);
    }

    if (out_file != nullptr) {
        FILE *out = fopen(out_file, "w");
        if (out == nullptr) {
            fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
            exit(EXIT_FAILURE);
        }
        tracer->out = out;
    } else {
        tracer->out = stdout;
    }

    ebpf::BPF *bpf = new ebpf::BPF();
    std::vector<ebpf::USDT> probes = tracer->init_usdt_probes(h2o_pid);

    ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), {}, probes);
    if (ret.code() != 0) {
        fprintf(stderr, "init: %s\n", ret.msg().c_str());
        return EXIT_FAILURE;
    }

    for (auto &probe : probes) {
        ret = bpf->attach_usdt(probe);
        if (ret.code() != 0) {
            fprintf(stderr, "attach_usdt: %s\n", ret.msg().c_str());
            return EXIT_FAILURE;
        }
    }

    ret = bpf->open_perf_buffer("events", tracer->handle_event, nullptr, tracer, 64);
    if (ret.code() != 0) {
        fprintf(stderr, "open_perf_buffer: %s\n", ret.msg().c_str());
        return EXIT_FAILURE;
    }

    if (debug) {
        fprintf(stderr, "attaching pid=%d\n", h2o_pid);
    }

    ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
    if (perf_buffer) {
        time_t t0 = time(NULL);

        while (true) {
            perf_buffer->poll(POLL_TIMEOUT);
            fflush(tracer->out);

            if (debug) {
                show_event_per_sec(tracer, t0);
                t0 = time(NULL);
            }
        }
    }

    fprintf(stderr, "Error: failed to get_perf_buffer()\n");
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before><commit_msg>Hooks<commit_after><|endoftext|>


<commit_before>#include "walk.hpp"

namespace vg {

namespace algorithms {

void for_each_walk(const HandleGraph& graph, size_t k, size_t edge_max,
                   const std::function<void(const walk_t&)>& lambda) {
    graph.for_each_handle([&](const handle_t& h) {
            // for the forward and reverse of this handle
            // walk k bases from the end, so that any walk starting on the node will be represented in the tree we build
            for (auto handle_is_rev : { false, true }) {
                handle_t handle = handle_is_rev ? graph.flip(h) : h;
                std::list<walk_t> walks;
                // for each position in the node, set up a walk with that start position and the node end or walk length as the end position
                // determine next positions
                nid_t handle_id = graph.get_id(handle);
                size_t handle_length = graph.get_length(handle);
                std::string handle_seq = graph.get_sequence(handle);
                for (size_t i = 0; i < handle_length;  ++i) {
                    pos_t begin = make_pos_t(handle_id, handle_is_rev, i);
                    pos_t end = make_pos_t(handle_id, handle_is_rev, std::min(handle_length, i+k));
                    walk_t walk = walk_t(handle_seq.substr(offset(begin), offset(end)-offset(begin)), begin, end, handle);
                    if (walk.seq.size() < k) {
                        size_t next_count = 0;
                        if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
                        //walk.seq.reserve(k); // may reduce allocation costs
                        // follow edges if we haven't completed the walk here
                        if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
                        } else {
                            graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
                                    walks.push_back(walk);
                                    auto& todo = walks.back();
                                    todo.curr = next;
                                    if (next_count > 1) {
                                        ++todo.forks;
                                    }
                            });
                        }
                    } else {
                        walks.push_back(walk);
                    }
                }

                // now expand the walks until they reach k
                while (!walks.empty()) {
                    // first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list
                    auto walks_end = walks.end();
                    for (std::list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) {
                        auto& walk = *q;
                        // did we reach our target length?
                        if (walk.seq.size() == k) {
                            // TODO here check if we are at the beginning of the reverse head or the beginning of the forward tail and would need special handling
                            // establish the context
                            handle_t end_handle = graph.get_handle(id(walk.end), is_rev(walk.end));
                            size_t end_length = graph.get_length(end_handle);
                            // now pass the walk to our callback
                            lambda(walk);
                            q = walks.erase(q);
                        } else {
                            // do we finish in the current node?
                            nid_t curr_id = graph.get_id(walk.curr);
                            size_t curr_length = graph.get_length(walk.curr);
                            bool curr_is_rev = graph.get_is_reverse(walk.curr);
                            std::string curr_seq = graph.get_sequence(walk.curr);
                            size_t take = std::min(curr_length, k-walk.seq.size());
                            walk.end = make_pos_t(curr_id, curr_is_rev, take);
                            walk.seq.append(curr_seq.substr(0,take));
			    walk.path.push_back(walk.curr);
                            if (walk.seq.size() < k) {
                                size_t next_count = 0;
                                if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
                                //walk.seq.reserve(k); // may reduce allocation costs
                                // follow edges if we haven't completed the walk here
                                if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
                                } else {
                                    graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
                                            walks.push_back(walk);
                                            auto& todo = walks.back();
                                            todo.curr = next;
                                            if (next_count > 1) {
                                                ++todo.forks;
                                            }
                                        });
                                }
                                // if not, we need to expand through the node then follow on
                                /*
                                graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
                                        walks.push_back(walk);
                                        auto& todo = walks.back();
                                        todo.curr = next;
                                    });
                                */
                                q = walks.erase(q);
                            } else {
                                if (walk.seq.size() > k) {
                                    assert(walk.seq.size() <= k);
                                }
                            }
                        }
                    }
                }
            }
        }, true);
}

std::ostream& operator<<(std::ostream& out, const walk_t& walk) {
    out << walk.seq << "\t"
        << id(walk.begin) << ":" << (is_rev(walk.begin) ? "-":"") << offset(walk.begin) << "\t";
    return out;
}

uint64_t walk_haplotype_frequency(const HandleGraph& graph,
                                  const gbwt::GBWT& haplotypes,
                                  const walk_t& walk) {
    if (walk.path.empty()) {
        return 0;
    }
    auto& first_step = walk.path.front();
    gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
    gbwt::SearchState search_state = haplotypes.find(start_node);
    for (uint64_t i = 1; i < walk.path.size(); ++i) {
        auto& next = walk.path[i];
        gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
        search_state = haplotypes.extend(search_state, next_node);
        if (search_state.empty()) {
            break;
        }
    }
    return search_state.size();
}

std::vector<std::string> walk_haplotype_names(const HandleGraph& graph,
                                              const gbwt::GBWT& haplotypes,
                                              const walk_t& walk) {
    std::vector<std::string> names;
    if (walk.path.empty()) {
        return names;
    }
    auto& first_step = walk.path.front();
    gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
    gbwt::SearchState search_state = haplotypes.find(start_node);
    for (uint64_t i = 1; i < walk.path.size(); ++i) {
        auto& next = walk.path[i];
        gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
        search_state = haplotypes.extend(search_state, next_node);
        if (search_state.empty()) {
            break;
        }
    }
    assert(haplotypes.hasMetadata() && haplotypes.metadata.hasSampleNames());
    for (auto& thread : haplotypes.locate(search_state)) {
        // not clear why we have to do this, but it's necessary
        // perhaps due to fwd/reverse threads
        auto id = (thread-1)/2; // convert thread id returned by locat to gbwt metadata compatible one
        std::stringstream ss;
        ss << thread_sample(haplotypes, id) << "#" << thread_phase(haplotypes, id);
        names.push_back(ss.str());
    }
    return names;
}

}

}
<commit_msg>correct conversion of thread to path id<commit_after>#include "walk.hpp"

namespace vg {

namespace algorithms {

void for_each_walk(const HandleGraph& graph, size_t k, size_t edge_max,
                   const std::function<void(const walk_t&)>& lambda) {
    graph.for_each_handle([&](const handle_t& h) {
            // for the forward and reverse of this handle
            // walk k bases from the end, so that any walk starting on the node will be represented in the tree we build
            for (auto handle_is_rev : { false, true }) {
                handle_t handle = handle_is_rev ? graph.flip(h) : h;
                std::list<walk_t> walks;
                // for each position in the node, set up a walk with that start position and the node end or walk length as the end position
                // determine next positions
                nid_t handle_id = graph.get_id(handle);
                size_t handle_length = graph.get_length(handle);
                std::string handle_seq = graph.get_sequence(handle);
                for (size_t i = 0; i < handle_length;  ++i) {
                    pos_t begin = make_pos_t(handle_id, handle_is_rev, i);
                    pos_t end = make_pos_t(handle_id, handle_is_rev, std::min(handle_length, i+k));
                    walk_t walk = walk_t(handle_seq.substr(offset(begin), offset(end)-offset(begin)), begin, end, handle);
                    if (walk.seq.size() < k) {
                        size_t next_count = 0;
                        if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
                        //walk.seq.reserve(k); // may reduce allocation costs
                        // follow edges if we haven't completed the walk here
                        if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
                        } else {
                            graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
                                    walks.push_back(walk);
                                    auto& todo = walks.back();
                                    todo.curr = next;
                                    if (next_count > 1) {
                                        ++todo.forks;
                                    }
                            });
                        }
                    } else {
                        walks.push_back(walk);
                    }
                }

                // now expand the walks until they reach k
                while (!walks.empty()) {
                    // first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list
                    auto walks_end = walks.end();
                    for (std::list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) {
                        auto& walk = *q;
                        // did we reach our target length?
                        if (walk.seq.size() == k) {
                            // TODO here check if we are at the beginning of the reverse head or the beginning of the forward tail and would need special handling
                            // establish the context
                            handle_t end_handle = graph.get_handle(id(walk.end), is_rev(walk.end));
                            size_t end_length = graph.get_length(end_handle);
                            // now pass the walk to our callback
                            lambda(walk);
                            q = walks.erase(q);
                        } else {
                            // do we finish in the current node?
                            nid_t curr_id = graph.get_id(walk.curr);
                            size_t curr_length = graph.get_length(walk.curr);
                            bool curr_is_rev = graph.get_is_reverse(walk.curr);
                            std::string curr_seq = graph.get_sequence(walk.curr);
                            size_t take = std::min(curr_length, k-walk.seq.size());
                            walk.end = make_pos_t(curr_id, curr_is_rev, take);
                            walk.seq.append(curr_seq.substr(0,take));
			    walk.path.push_back(walk.curr);
                            if (walk.seq.size() < k) {
                                size_t next_count = 0;
                                if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
                                //walk.seq.reserve(k); // may reduce allocation costs
                                // follow edges if we haven't completed the walk here
                                if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
                                } else {
                                    graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
                                            walks.push_back(walk);
                                            auto& todo = walks.back();
                                            todo.curr = next;
                                            if (next_count > 1) {
                                                ++todo.forks;
                                            }
                                        });
                                }
                                // if not, we need to expand through the node then follow on
                                /*
                                graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
                                        walks.push_back(walk);
                                        auto& todo = walks.back();
                                        todo.curr = next;
                                    });
                                */
                                q = walks.erase(q);
                            } else {
                                if (walk.seq.size() > k) {
                                    assert(walk.seq.size() <= k);
                                }
                            }
                        }
                    }
                }
            }
        }, true);
}

std::ostream& operator<<(std::ostream& out, const walk_t& walk) {
    out << walk.seq << "\t"
        << id(walk.begin) << ":" << (is_rev(walk.begin) ? "-":"") << offset(walk.begin) << "\t";
    return out;
}

uint64_t walk_haplotype_frequency(const HandleGraph& graph,
                                  const gbwt::GBWT& haplotypes,
                                  const walk_t& walk) {
    if (walk.path.empty()) {
        return 0;
    }
    auto& first_step = walk.path.front();
    gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
    gbwt::SearchState search_state = haplotypes.find(start_node);
    for (uint64_t i = 1; i < walk.path.size(); ++i) {
        auto& next = walk.path[i];
        gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
        search_state = haplotypes.extend(search_state, next_node);
        if (search_state.empty()) {
            break;
        }
    }
    return search_state.size();
}

std::vector<std::string> walk_haplotype_names(const HandleGraph& graph,
                                              const gbwt::GBWT& haplotypes,
                                              const walk_t& walk) {
    std::vector<std::string> names;
    if (walk.path.empty()) {
        return names;
    }
    auto& first_step = walk.path.front();
    gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
    gbwt::SearchState search_state = haplotypes.find(start_node);
    for (uint64_t i = 1; i < walk.path.size(); ++i) {
        auto& next = walk.path[i];
        gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
        search_state = haplotypes.extend(search_state, next_node);
        if (search_state.empty()) {
            break;
        }
    }
    assert(haplotypes.hasMetadata() && haplotypes.metadata.hasSampleNames());
    for (auto& thread : haplotypes.locate(search_state)) {
        auto id = gbwt::Path::id(thread);
        std::stringstream ss;
        ss << thread_sample(haplotypes, id) << "#" << thread_phase(haplotypes, id);
        names.push_back(ss.str());
    }
    return names;
}

}

}
<|endoftext|>


<commit_before><commit_msg>Reading of the theme config file<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit 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 "CaptureOptionsDialog.h"

#include <absl/flags/declare.h>
#include <absl/flags/flag.h>

#include <QAbstractButton>
#include <QDialog>
#include <QDialogButtonBox>
#include <QWidget>
#include <QtGui/QValidator>

#include "ClientFlags/ClientFlags.h"
#include "ui_CaptureOptionsDialog.h"

namespace orbit_qt {

using orbit_client_data::WineSyscallHandlingMethod;
using orbit_grpc_protos::CaptureOptions;

using DynamicInstrumentationMethod =
    orbit_grpc_protos::CaptureOptions::DynamicInstrumentationMethod;
using UnwindingMethod = orbit_grpc_protos::CaptureOptions::UnwindingMethod;

CaptureOptionsDialog::CaptureOptionsDialog(QWidget* parent)
    : QDialog{parent}, ui_(std::make_unique<Ui::CaptureOptionsDialog>()) {
  ui_->setupUi(this);

  QObject::connect(ui_->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
  QObject::connect(ui_->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
  QObject::connect(ui_->framePointerUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
                   ui_->maxCopyRawStackSizeWidget,
                   [this](bool checked) { ui_->maxCopyRawStackSizeWidget->setEnabled(checked); });
  QObject::connect(ui_->dwarfUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
                   ui_->wineGroupBox,
                   [this](bool checked) { ui_->wineGroupBox->setEnabled(checked); });
  QObject::connect(ui_->collectMemoryInfoCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
                   [this](bool checked) {
                     ui_->memorySamplingPeriodMsLabel->setEnabled(checked);
                     ui_->memorySamplingPeriodMsLineEdit->setEnabled(checked);
                     ui_->memoryWarningThresholdKbLabel->setEnabled(checked);
                     ui_->memoryWarningThresholdKbLineEdit->setEnabled(checked);
                   });

  QObject::connect(ui_->samplingCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
                   [this](bool checked) {
                     ui_->samplingPeriodMsLabel->setEnabled(checked);
                     ui_->samplingPeriodMsDoubleSpinBox->setEnabled(checked);
                     ui_->unwindingMethodGroupBox->setEnabled(checked);
                   });

  ui_->samplingPeriodMsLabel->setEnabled(ui_->samplingCheckBox->isChecked());
  ui_->samplingPeriodMsDoubleSpinBox->setEnabled(ui_->samplingCheckBox->isChecked());
  ui_->unwindingMethodGroupBox->setEnabled(ui_->samplingCheckBox->isChecked());

  ui_->maxCopyRawStackSizeSpinBox->setValue(kMaxCopyRawStackSizeDefaultValue);
  ui_->maxCopyRawStackSizeWidget->setEnabled(ui_->framePointerUnwindingRadioButton->isChecked());

  ui_->localMarkerDepthLineEdit->setValidator(&uint64_validator_);

  ui_->memorySamplingPeriodMsLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memorySamplingPeriodMsLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memoryWarningThresholdKbLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memoryWarningThresholdKbLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memorySamplingPeriodMsLineEdit->setValidator(new UInt64Validator(
      1, std::numeric_limits<uint64_t>::max(), ui_->memorySamplingPeriodMsLineEdit));
  ui_->memoryWarningThresholdKbLineEdit->setValidator(&uint64_validator_);
  if (!absl::GetFlag(FLAGS_enable_warning_threshold)) {
    ui_->memoryWarningThresholdKbLabel->hide();
    ui_->memoryWarningThresholdKbLineEdit->hide();
  }

  if (!absl::GetFlag(FLAGS_devmode)) {
    // TODO(b/198748597): Don't hide samplingCheckBox once disabling sampling completely is exposed.
    ui_->samplingCheckBox->hide();
    ui_->schedulerCheckBox->hide();
    ui_->devModeGroupBox->hide();
    ui_->wineNoneRadioButton->hide();
  }
}

void CaptureOptionsDialog::SetEnableSampling(bool enable_sampling) {
  ui_->samplingCheckBox->setChecked(enable_sampling);
}

bool CaptureOptionsDialog::GetEnableSampling() const { return ui_->samplingCheckBox->isChecked(); }

void CaptureOptionsDialog::SetSamplingPeriodMs(double sampling_period_ms) {
  ui_->samplingPeriodMsDoubleSpinBox->setValue(sampling_period_ms);
}

double CaptureOptionsDialog::GetSamplingPeriodMs() const {
  return ui_->samplingPeriodMsDoubleSpinBox->value();
}

void CaptureOptionsDialog::SetUnwindingMethod(UnwindingMethod unwinding_method) {
  switch (unwinding_method) {
    case CaptureOptions::kDwarf:
      ui_->dwarfUnwindingRadioButton->setChecked(true);
      break;
    case CaptureOptions::kFramePointers:
      ui_->framePointerUnwindingRadioButton->setChecked(true);
      break;
    default:
      ORBIT_UNREACHABLE();
  }
}

UnwindingMethod CaptureOptionsDialog::GetUnwindingMethod() const {
  if (ui_->dwarfUnwindingRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->framePointerUnwindingRadioButton->isChecked());
    return CaptureOptions::kDwarf;
  }
  if (ui_->framePointerUnwindingRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->dwarfUnwindingRadioButton->isChecked());
    return CaptureOptions::kFramePointers;
  }
  ORBIT_UNREACHABLE();
}

void CaptureOptionsDialog::SetMaxCopyRawStackSize(uint16_t stack_dump_size) {
  ORBIT_CHECK(stack_dump_size % 8 == 0);
  ui_->maxCopyRawStackSizeSpinBox->setValue(stack_dump_size);
}

uint16_t CaptureOptionsDialog::GetMaxCopyRawStackSize() const {
  uint16_t result = ui_->maxCopyRawStackSizeSpinBox->value();
  ORBIT_CHECK(result % 8 == 0);
  return result;
}

void CaptureOptionsDialog::SetCollectSchedulerInfo(bool collect_scheduler_info) {
  ui_->schedulerCheckBox->setChecked(collect_scheduler_info);
}

bool CaptureOptionsDialog::GetCollectSchedulerInfo() const {
  return ui_->schedulerCheckBox->isChecked();
}

void CaptureOptionsDialog::SetCollectThreadStates(bool collect_thread_state) {
  ui_->threadStateCheckBox->setChecked(collect_thread_state);
}

bool CaptureOptionsDialog::GetCollectThreadStates() const {
  return ui_->threadStateCheckBox->isChecked();
}

void CaptureOptionsDialog::SetTraceGpuSubmissions(bool trace_gpu_submissions) {
  ui_->gpuSubmissionsCheckBox->setChecked(trace_gpu_submissions);
}

bool CaptureOptionsDialog::GetTraceGpuSubmissions() const {
  return ui_->gpuSubmissionsCheckBox->isChecked();
}

void CaptureOptionsDialog::SetEnableApi(bool enable_api) {
  ui_->apiCheckBox->setChecked(enable_api);
}

bool CaptureOptionsDialog::GetEnableApi() const { return ui_->apiCheckBox->isChecked(); }

void CaptureOptionsDialog::SetDynamicInstrumentationMethod(DynamicInstrumentationMethod method) {
  switch (method) {
    case CaptureOptions::kKernelUprobes:
      ui_->uprobesRadioButton->setChecked(true);
      break;
    case CaptureOptions::kUserSpaceInstrumentation:
      ui_->userSpaceRadioButton->setChecked(true);
      break;
    default:
      ORBIT_UNREACHABLE();
  }
}

DynamicInstrumentationMethod CaptureOptionsDialog::GetDynamicInstrumentationMethod() const {
  if (ui_->uprobesRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->userSpaceRadioButton->isChecked());
    return CaptureOptions::kKernelUprobes;
  }
  if (ui_->userSpaceRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->uprobesRadioButton->isChecked());
    return CaptureOptions::kUserSpaceInstrumentation;
  }
  ORBIT_UNREACHABLE();
}

void CaptureOptionsDialog::SetWineSyscallHandlingMethod(
    orbit_client_data::WineSyscallHandlingMethod method) {
  switch (method) {
    case WineSyscallHandlingMethod::kNoSpecialHandling:
      ui_->wineNoneRadioButton->setChecked(true);
      break;
    case WineSyscallHandlingMethod::kStopUnwinding:
      ui_->wineStopRadioButton->setChecked(true);
      break;
    case WineSyscallHandlingMethod::kRecordUserStack:
      ui_->wineRecordRadioButton->setChecked(true);
      break;
  }
}

WineSyscallHandlingMethod CaptureOptionsDialog::GetWineSyscallHandlingMethod() const {
  if (ui_->wineNoneRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->wineStopRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
    return WineSyscallHandlingMethod::kNoSpecialHandling;
  }
  if (ui_->wineStopRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
    return WineSyscallHandlingMethod::kStopUnwinding;
  }
  if (ui_->wineRecordRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineStopRadioButton->isChecked());
    return WineSyscallHandlingMethod::kRecordUserStack;
  }
  ORBIT_UNREACHABLE();
}

void CaptureOptionsDialog::SetEnableIntrospection(bool enable_introspection) {
  ui_->introspectionCheckBox->setChecked(enable_introspection);
}

bool CaptureOptionsDialog::GetEnableIntrospection() const {
  return ui_->introspectionCheckBox->isChecked();
}

void CaptureOptionsDialog::SetLimitLocalMarkerDepthPerCommandBuffer(
    bool limit_local_marker_depth_per_command_buffer) {
  ui_->localMarkerDepthCheckBox->setChecked(limit_local_marker_depth_per_command_buffer);
}

bool CaptureOptionsDialog::GetLimitLocalMarkerDepthPerCommandBuffer() const {
  return ui_->localMarkerDepthCheckBox->isChecked();
}

void CaptureOptionsDialog::SetMaxLocalMarkerDepthPerCommandBuffer(
    uint64_t local_marker_depth_per_command_buffer) {
  ui_->localMarkerDepthLineEdit->setText(QString::number(local_marker_depth_per_command_buffer));
}

uint64_t CaptureOptionsDialog::GetMaxLocalMarkerDepthPerCommandBuffer() const {
  ORBIT_CHECK(!ui_->localMarkerDepthLineEdit->text().isEmpty());
  bool valid = false;
  uint64_t result = ui_->localMarkerDepthLineEdit->text().toULongLong(&valid);
  ORBIT_CHECK(valid);
  return result;
}

void CaptureOptionsDialog::ResetLocalMarkerDepthLineEdit() {
  if (ui_->localMarkerDepthLineEdit->text().isEmpty()) {
    ui_->localMarkerDepthLineEdit->setText(QString::number(kLocalMarkerDepthDefaultValue));
  }
}

void CaptureOptionsDialog::SetCollectMemoryInfo(bool collect_memory_info) {
  ui_->collectMemoryInfoCheckBox->setChecked(collect_memory_info);
}

bool CaptureOptionsDialog::GetCollectMemoryInfo() const {
  return ui_->collectMemoryInfoCheckBox->isChecked();
}

void CaptureOptionsDialog::SetMemorySamplingPeriodMs(uint64_t memory_sampling_period_ms) {
  ui_->memorySamplingPeriodMsLineEdit->setText(QString::number(memory_sampling_period_ms));
}

void CaptureOptionsDialog::ResetMemorySamplingPeriodMsLineEditWhenEmpty() {
  if (!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty()) return;
  ui_->memorySamplingPeriodMsLineEdit->setText(
      QString::number(kMemorySamplingPeriodMsDefaultValue));
}

uint64_t CaptureOptionsDialog::GetMemorySamplingPeriodMs() const {
  ORBIT_CHECK(!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty());
  bool valid = false;
  uint64_t memory_sampling_period_ms =
      ui_->memorySamplingPeriodMsLineEdit->text().toULongLong(&valid);
  ORBIT_CHECK(valid);
  return memory_sampling_period_ms;
}

void CaptureOptionsDialog::SetMemoryWarningThresholdKb(uint64_t memory_warning_threshold_kb) {
  ui_->memoryWarningThresholdKbLineEdit->setText(QString::number(memory_warning_threshold_kb));
}

void CaptureOptionsDialog::ResetMemoryWarningThresholdKbLineEditWhenEmpty() {
  if (!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty()) return;
  ui_->memoryWarningThresholdKbLineEdit->setText(
      QString::number(kMemoryWarningThresholdKbDefaultValue));
}

uint64_t CaptureOptionsDialog::GetMemoryWarningThresholdKb() const {
  ORBIT_CHECK(!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty());
  bool valid = false;
  uint64_t result = ui_->memoryWarningThresholdKbLineEdit->text().toULongLong(&valid);
  ORBIT_CHECK(valid);
  return result;
}

}  // namespace orbit_qt
<commit_msg>Disable the "Wine" group box on frame- pointer unwinding (#4015)<commit_after>// Copyright (c) 2020 The Orbit 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 "CaptureOptionsDialog.h"

#include <absl/flags/declare.h>
#include <absl/flags/flag.h>

#include <QAbstractButton>
#include <QDialog>
#include <QDialogButtonBox>
#include <QWidget>
#include <QtGui/QValidator>

#include "ClientFlags/ClientFlags.h"
#include "ui_CaptureOptionsDialog.h"

namespace orbit_qt {

using orbit_client_data::WineSyscallHandlingMethod;
using orbit_grpc_protos::CaptureOptions;

using DynamicInstrumentationMethod =
    orbit_grpc_protos::CaptureOptions::DynamicInstrumentationMethod;
using UnwindingMethod = orbit_grpc_protos::CaptureOptions::UnwindingMethod;

CaptureOptionsDialog::CaptureOptionsDialog(QWidget* parent)
    : QDialog{parent}, ui_(std::make_unique<Ui::CaptureOptionsDialog>()) {
  ui_->setupUi(this);

  QObject::connect(ui_->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
  QObject::connect(ui_->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
  QObject::connect(ui_->framePointerUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
                   ui_->maxCopyRawStackSizeWidget,
                   [this](bool checked) { ui_->maxCopyRawStackSizeWidget->setEnabled(checked); });
  QObject::connect(ui_->dwarfUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
                   ui_->wineGroupBox,
                   [this](bool checked) { ui_->wineGroupBox->setEnabled(checked); });
  QObject::connect(ui_->collectMemoryInfoCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
                   [this](bool checked) {
                     ui_->memorySamplingPeriodMsLabel->setEnabled(checked);
                     ui_->memorySamplingPeriodMsLineEdit->setEnabled(checked);
                     ui_->memoryWarningThresholdKbLabel->setEnabled(checked);
                     ui_->memoryWarningThresholdKbLineEdit->setEnabled(checked);
                   });

  QObject::connect(ui_->samplingCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
                   [this](bool checked) {
                     ui_->samplingPeriodMsLabel->setEnabled(checked);
                     ui_->samplingPeriodMsDoubleSpinBox->setEnabled(checked);
                     ui_->unwindingMethodGroupBox->setEnabled(checked);
                   });

  ui_->samplingPeriodMsLabel->setEnabled(ui_->samplingCheckBox->isChecked());
  ui_->samplingPeriodMsDoubleSpinBox->setEnabled(ui_->samplingCheckBox->isChecked());
  ui_->unwindingMethodGroupBox->setEnabled(ui_->samplingCheckBox->isChecked());

  ui_->maxCopyRawStackSizeSpinBox->setValue(kMaxCopyRawStackSizeDefaultValue);
  ui_->maxCopyRawStackSizeWidget->setEnabled(ui_->framePointerUnwindingRadioButton->isChecked());

  ui_->wineGroupBox->setEnabled(ui_->dwarfUnwindingRadioButton->isChecked());

  ui_->localMarkerDepthLineEdit->setValidator(&uint64_validator_);

  ui_->memorySamplingPeriodMsLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memorySamplingPeriodMsLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memoryWarningThresholdKbLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memoryWarningThresholdKbLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
  ui_->memorySamplingPeriodMsLineEdit->setValidator(new UInt64Validator(
      1, std::numeric_limits<uint64_t>::max(), ui_->memorySamplingPeriodMsLineEdit));
  ui_->memoryWarningThresholdKbLineEdit->setValidator(&uint64_validator_);
  if (!absl::GetFlag(FLAGS_enable_warning_threshold)) {
    ui_->memoryWarningThresholdKbLabel->hide();
    ui_->memoryWarningThresholdKbLineEdit->hide();
  }

  if (!absl::GetFlag(FLAGS_devmode)) {
    // TODO(b/198748597): Don't hide samplingCheckBox once disabling sampling completely is exposed.
    ui_->samplingCheckBox->hide();
    ui_->schedulerCheckBox->hide();
    ui_->devModeGroupBox->hide();
    ui_->wineNoneRadioButton->hide();
  }
}

void CaptureOptionsDialog::SetEnableSampling(bool enable_sampling) {
  ui_->samplingCheckBox->setChecked(enable_sampling);
}

bool CaptureOptionsDialog::GetEnableSampling() const { return ui_->samplingCheckBox->isChecked(); }

void CaptureOptionsDialog::SetSamplingPeriodMs(double sampling_period_ms) {
  ui_->samplingPeriodMsDoubleSpinBox->setValue(sampling_period_ms);
}

double CaptureOptionsDialog::GetSamplingPeriodMs() const {
  return ui_->samplingPeriodMsDoubleSpinBox->value();
}

void CaptureOptionsDialog::SetUnwindingMethod(UnwindingMethod unwinding_method) {
  switch (unwinding_method) {
    case CaptureOptions::kDwarf:
      ui_->dwarfUnwindingRadioButton->setChecked(true);
      break;
    case CaptureOptions::kFramePointers:
      ui_->framePointerUnwindingRadioButton->setChecked(true);
      break;
    default:
      ORBIT_UNREACHABLE();
  }
}

UnwindingMethod CaptureOptionsDialog::GetUnwindingMethod() const {
  if (ui_->dwarfUnwindingRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->framePointerUnwindingRadioButton->isChecked());
    return CaptureOptions::kDwarf;
  }
  if (ui_->framePointerUnwindingRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->dwarfUnwindingRadioButton->isChecked());
    return CaptureOptions::kFramePointers;
  }
  ORBIT_UNREACHABLE();
}

void CaptureOptionsDialog::SetMaxCopyRawStackSize(uint16_t stack_dump_size) {
  ORBIT_CHECK(stack_dump_size % 8 == 0);
  ui_->maxCopyRawStackSizeSpinBox->setValue(stack_dump_size);
}

uint16_t CaptureOptionsDialog::GetMaxCopyRawStackSize() const {
  uint16_t result = ui_->maxCopyRawStackSizeSpinBox->value();
  ORBIT_CHECK(result % 8 == 0);
  return result;
}

void CaptureOptionsDialog::SetCollectSchedulerInfo(bool collect_scheduler_info) {
  ui_->schedulerCheckBox->setChecked(collect_scheduler_info);
}

bool CaptureOptionsDialog::GetCollectSchedulerInfo() const {
  return ui_->schedulerCheckBox->isChecked();
}

void CaptureOptionsDialog::SetCollectThreadStates(bool collect_thread_state) {
  ui_->threadStateCheckBox->setChecked(collect_thread_state);
}

bool CaptureOptionsDialog::GetCollectThreadStates() const {
  return ui_->threadStateCheckBox->isChecked();
}

void CaptureOptionsDialog::SetTraceGpuSubmissions(bool trace_gpu_submissions) {
  ui_->gpuSubmissionsCheckBox->setChecked(trace_gpu_submissions);
}

bool CaptureOptionsDialog::GetTraceGpuSubmissions() const {
  return ui_->gpuSubmissionsCheckBox->isChecked();
}

void CaptureOptionsDialog::SetEnableApi(bool enable_api) {
  ui_->apiCheckBox->setChecked(enable_api);
}

bool CaptureOptionsDialog::GetEnableApi() const { return ui_->apiCheckBox->isChecked(); }

void CaptureOptionsDialog::SetDynamicInstrumentationMethod(DynamicInstrumentationMethod method) {
  switch (method) {
    case CaptureOptions::kKernelUprobes:
      ui_->uprobesRadioButton->setChecked(true);
      break;
    case CaptureOptions::kUserSpaceInstrumentation:
      ui_->userSpaceRadioButton->setChecked(true);
      break;
    default:
      ORBIT_UNREACHABLE();
  }
}

DynamicInstrumentationMethod CaptureOptionsDialog::GetDynamicInstrumentationMethod() const {
  if (ui_->uprobesRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->userSpaceRadioButton->isChecked());
    return CaptureOptions::kKernelUprobes;
  }
  if (ui_->userSpaceRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->uprobesRadioButton->isChecked());
    return CaptureOptions::kUserSpaceInstrumentation;
  }
  ORBIT_UNREACHABLE();
}

void CaptureOptionsDialog::SetWineSyscallHandlingMethod(
    orbit_client_data::WineSyscallHandlingMethod method) {
  switch (method) {
    case WineSyscallHandlingMethod::kNoSpecialHandling:
      ui_->wineNoneRadioButton->setChecked(true);
      break;
    case WineSyscallHandlingMethod::kStopUnwinding:
      ui_->wineStopRadioButton->setChecked(true);
      break;
    case WineSyscallHandlingMethod::kRecordUserStack:
      ui_->wineRecordRadioButton->setChecked(true);
      break;
  }
}

WineSyscallHandlingMethod CaptureOptionsDialog::GetWineSyscallHandlingMethod() const {
  if (ui_->wineNoneRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->wineStopRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
    return WineSyscallHandlingMethod::kNoSpecialHandling;
  }
  if (ui_->wineStopRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
    return WineSyscallHandlingMethod::kStopUnwinding;
  }
  if (ui_->wineRecordRadioButton->isChecked()) {
    ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineStopRadioButton->isChecked());
    return WineSyscallHandlingMethod::kRecordUserStack;
  }
  ORBIT_UNREACHABLE();
}

void CaptureOptionsDialog::SetEnableIntrospection(bool enable_introspection) {
  ui_->introspectionCheckBox->setChecked(enable_introspection);
}

bool CaptureOptionsDialog::GetEnableIntrospection() const {
  return ui_->introspectionCheckBox->isChecked();
}

void CaptureOptionsDialog::SetLimitLocalMarkerDepthPerCommandBuffer(
    bool limit_local_marker_depth_per_command_buffer) {
  ui_->localMarkerDepthCheckBox->setChecked(limit_local_marker_depth_per_command_buffer);
}

bool CaptureOptionsDialog::GetLimitLocalMarkerDepthPerCommandBuffer() const {
  return ui_->localMarkerDepthCheckBox->isChecked();
}

void CaptureOptionsDialog::SetMaxLocalMarkerDepthPerCommandBuffer(
    uint64_t local_marker_depth_per_command_buffer) {
  ui_->localMarkerDepthLineEdit->setText(QString::number(local_marker_depth_per_command_buffer));
}

uint64_t CaptureOptionsDialog::GetMaxLocalMarkerDepthPerCommandBuffer() const {
  ORBIT_CHECK(!ui_->localMarkerDepthLineEdit->text().isEmpty());
  bool valid = false;
  uint64_t result = ui_->localMarkerDepthLineEdit->text().toULongLong(&valid);
  ORBIT_CHECK(valid);
  return result;
}

void CaptureOptionsDialog::ResetLocalMarkerDepthLineEdit() {
  if (ui_->localMarkerDepthLineEdit->text().isEmpty()) {
    ui_->localMarkerDepthLineEdit->setText(QString::number(kLocalMarkerDepthDefaultValue));
  }
}

void CaptureOptionsDialog::SetCollectMemoryInfo(bool collect_memory_info) {
  ui_->collectMemoryInfoCheckBox->setChecked(collect_memory_info);
}

bool CaptureOptionsDialog::GetCollectMemoryInfo() const {
  return ui_->collectMemoryInfoCheckBox->isChecked();
}

void CaptureOptionsDialog::SetMemorySamplingPeriodMs(uint64_t memory_sampling_period_ms) {
  ui_->memorySamplingPeriodMsLineEdit->setText(QString::number(memory_sampling_period_ms));
}

void CaptureOptionsDialog::ResetMemorySamplingPeriodMsLineEditWhenEmpty() {
  if (!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty()) return;
  ui_->memorySamplingPeriodMsLineEdit->setText(
      QString::number(kMemorySamplingPeriodMsDefaultValue));
}

uint64_t CaptureOptionsDialog::GetMemorySamplingPeriodMs() const {
  ORBIT_CHECK(!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty());
  bool valid = false;
  uint64_t memory_sampling_period_ms =
      ui_->memorySamplingPeriodMsLineEdit->text().toULongLong(&valid);
  ORBIT_CHECK(valid);
  return memory_sampling_period_ms;
}

void CaptureOptionsDialog::SetMemoryWarningThresholdKb(uint64_t memory_warning_threshold_kb) {
  ui_->memoryWarningThresholdKbLineEdit->setText(QString::number(memory_warning_threshold_kb));
}

void CaptureOptionsDialog::ResetMemoryWarningThresholdKbLineEditWhenEmpty() {
  if (!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty()) return;
  ui_->memoryWarningThresholdKbLineEdit->setText(
      QString::number(kMemoryWarningThresholdKbDefaultValue));
}

uint64_t CaptureOptionsDialog::GetMemoryWarningThresholdKb() const {
  ORBIT_CHECK(!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty());
  bool valid = false;
  uint64_t result = ui_->memoryWarningThresholdKbLineEdit->text().toULongLong(&valid);
  ORBIT_CHECK(valid);
  return result;
}

}  // namespace orbit_qt
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <tools/rc.h>

#include <vcl/event.hxx>
#include <vcl/layout.hxx>
#include <vcl/svapp.hxx>
#include <vcl/tabpage.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/settings.hxx>

#include <svdata.hxx>

#include <com/sun/star/accessibility/XAccessible.hpp>

void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
    if ( !(nStyle & WB_NODIALOGCONTROL) )
        nStyle |= WB_DIALOGCONTROL;

    Window::ImplInit( pParent, nStyle, NULL );

    ImplInitSettings();

    // if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background
    // otherwise they will paint with a wrong background
    if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
        EnableChildTransparentMode( true );
}

void TabPage::ImplInitSettings()
{
    Window* pParent = GetParent();
    if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
    {
        EnableChildTransparentMode( true );
        SetParentClipMode( PARENTCLIPMODE_NOCLIP );
        SetPaintTransparent( true );
        SetBackground();
    }
    else
    {
        EnableChildTransparentMode( false );
        SetParentClipMode( 0 );
        SetPaintTransparent( false );

        if ( IsControlBackground() )
            SetBackground( GetControlBackground() );
        else
            SetBackground( pParent->GetBackground() );
    }
}

TabPage::TabPage( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_TABPAGE )
{
    ImplInit( pParent, nStyle );
}

TabPage::TabPage( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_TABPAGE )
{
    rResId.SetRT( RSC_TABPAGE );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle );
    ImplLoadRes(rResId);

    if ( !(nStyle & WB_HIDE) )
        Show();
}

TabPage::TabPage(Window *pParent, const OString& rID, const OUString& rUIXMLDescription)
    : Window(WINDOW_TABPAGE)
{
    ImplInit(pParent, 0);
    m_pUIBuilder = new VclBuilder(this, getUIRootDir(), rUIXMLDescription, rID);
}

void TabPage::StateChanged( StateChangedType nType )
{
    Window::StateChanged( nType );

    if ( nType == STATE_CHANGE_INITSHOW )
    {
        if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
            ImplWindowAutoMnemonic( this );
        // FIXME: no layouting, workaround some clipping issues
        ImplAdjustNWFSizes();
    }
    else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
    {
        ImplInitSettings();
        Invalidate();
    }
}

void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
    Window::DataChanged( rDCEvt );

    if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
         (rDCEvt.GetFlags() & SETTINGS_STYLE) )
    {
        ImplInitSettings();
        Invalidate();
    }
}

void TabPage::Paint( const Rectangle& )
{
    // draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)
    if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
    {
        const ImplControlValue aControlValue;

        ControlState nState = CTRL_STATE_ENABLED;
        int part = PART_ENTIRE_CONTROL;
        if ( !IsEnabled() )
            nState &= ~CTRL_STATE_ENABLED;
        if ( HasFocus() )
            nState |= CTRL_STATE_FOCUSED;
        Point aPoint;
        // pass the whole window region to NWF as the tab body might be a gradient or bitmap
        // that has to be scaled properly, clipping makes sure that we do not paint too much
        Rectangle aCtrlRegion( aPoint, GetOutputSizePixel() );
        DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,
                aControlValue, OUString() );
    }
}

void TabPage::Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong )
{
    Point aPos = pDev->LogicToPixel( rPos );
    Size aSize = pDev->LogicToPixel( rSize );

    Wallpaper aWallpaper = GetBackground();
    if ( !aWallpaper.IsBitmap() )
        ImplInitSettings();

    pDev->Push();
    pDev->SetMapMode();
    pDev->SetLineColor();

    if ( aWallpaper.IsBitmap() )
        pDev->DrawBitmapEx( aPos, aSize, aWallpaper.GetBitmap() );
    else
    {
        if( aWallpaper.GetColor() == COL_AUTO )
            pDev->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );
        else
            pDev->SetFillColor( aWallpaper.GetColor() );
        pDev->DrawRect( Rectangle( aPos, aSize ) );
    }

    pDev->Pop();
}

void TabPage::ActivatePage()
{
}

void TabPage::DeactivatePage()
{
}

OString TabPage::GetConfigId() const
{
    OString sId(GetHelpId());
    if (sId.isEmpty() && isLayoutEnabled(this))
        sId = GetWindow(WINDOW_FIRSTCHILD)->GetHelpId();
    return sId;
}

Size TabPage::GetOptimalSize() const
{
    if (isLayoutEnabled(this))
        return VclContainer::getLayoutRequisition(*GetWindow(WINDOW_FIRSTCHILD));
    return getLegacyBestSizeForChildren(*this);
}

void TabPage::SetPosSizePixel(const Point& rAllocPos, const Size& rAllocation)
{
    Window::SetPosSizePixel(rAllocPos, rAllocation);
    if (isLayoutEnabled(this))
        VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}

void TabPage::SetSizePixel(const Size& rAllocation)
{
    Window::SetSizePixel(rAllocation);
    if (isLayoutEnabled(this))
        VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}

void TabPage::SetPosPixel(const Point& rAllocPos)
{
    Window::SetPosPixel(rAllocPos);
    if (isLayoutEnabled(this))
        VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), GetOutputSizePixel());
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Related: fdo#81457 skip setting an empty allocation<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <tools/rc.h>

#include <vcl/event.hxx>
#include <vcl/layout.hxx>
#include <vcl/svapp.hxx>
#include <vcl/tabpage.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/settings.hxx>

#include <svdata.hxx>

#include <com/sun/star/accessibility/XAccessible.hpp>

void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
    if ( !(nStyle & WB_NODIALOGCONTROL) )
        nStyle |= WB_DIALOGCONTROL;

    Window::ImplInit( pParent, nStyle, NULL );

    ImplInitSettings();

    // if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background
    // otherwise they will paint with a wrong background
    if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
        EnableChildTransparentMode( true );
}

void TabPage::ImplInitSettings()
{
    Window* pParent = GetParent();
    if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
    {
        EnableChildTransparentMode( true );
        SetParentClipMode( PARENTCLIPMODE_NOCLIP );
        SetPaintTransparent( true );
        SetBackground();
    }
    else
    {
        EnableChildTransparentMode( false );
        SetParentClipMode( 0 );
        SetPaintTransparent( false );

        if ( IsControlBackground() )
            SetBackground( GetControlBackground() );
        else
            SetBackground( pParent->GetBackground() );
    }
}

TabPage::TabPage( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_TABPAGE )
{
    ImplInit( pParent, nStyle );
}

TabPage::TabPage( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_TABPAGE )
{
    rResId.SetRT( RSC_TABPAGE );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle );
    ImplLoadRes(rResId);

    if ( !(nStyle & WB_HIDE) )
        Show();
}

TabPage::TabPage(Window *pParent, const OString& rID, const OUString& rUIXMLDescription)
    : Window(WINDOW_TABPAGE)
{
    ImplInit(pParent, 0);
    m_pUIBuilder = new VclBuilder(this, getUIRootDir(), rUIXMLDescription, rID);
}

void TabPage::StateChanged( StateChangedType nType )
{
    Window::StateChanged( nType );

    if ( nType == STATE_CHANGE_INITSHOW )
    {
        if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
            ImplWindowAutoMnemonic( this );
        // FIXME: no layouting, workaround some clipping issues
        ImplAdjustNWFSizes();
    }
    else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
    {
        ImplInitSettings();
        Invalidate();
    }
}

void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
    Window::DataChanged( rDCEvt );

    if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
         (rDCEvt.GetFlags() & SETTINGS_STYLE) )
    {
        ImplInitSettings();
        Invalidate();
    }
}

void TabPage::Paint( const Rectangle& )
{
    // draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)
    if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
    {
        const ImplControlValue aControlValue;

        ControlState nState = CTRL_STATE_ENABLED;
        int part = PART_ENTIRE_CONTROL;
        if ( !IsEnabled() )
            nState &= ~CTRL_STATE_ENABLED;
        if ( HasFocus() )
            nState |= CTRL_STATE_FOCUSED;
        Point aPoint;
        // pass the whole window region to NWF as the tab body might be a gradient or bitmap
        // that has to be scaled properly, clipping makes sure that we do not paint too much
        Rectangle aCtrlRegion( aPoint, GetOutputSizePixel() );
        DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,
                aControlValue, OUString() );
    }
}

void TabPage::Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong )
{
    Point aPos = pDev->LogicToPixel( rPos );
    Size aSize = pDev->LogicToPixel( rSize );

    Wallpaper aWallpaper = GetBackground();
    if ( !aWallpaper.IsBitmap() )
        ImplInitSettings();

    pDev->Push();
    pDev->SetMapMode();
    pDev->SetLineColor();

    if ( aWallpaper.IsBitmap() )
        pDev->DrawBitmapEx( aPos, aSize, aWallpaper.GetBitmap() );
    else
    {
        if( aWallpaper.GetColor() == COL_AUTO )
            pDev->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );
        else
            pDev->SetFillColor( aWallpaper.GetColor() );
        pDev->DrawRect( Rectangle( aPos, aSize ) );
    }

    pDev->Pop();
}

void TabPage::ActivatePage()
{
}

void TabPage::DeactivatePage()
{
}

OString TabPage::GetConfigId() const
{
    OString sId(GetHelpId());
    if (sId.isEmpty() && isLayoutEnabled(this))
        sId = GetWindow(WINDOW_FIRSTCHILD)->GetHelpId();
    return sId;
}

Size TabPage::GetOptimalSize() const
{
    if (isLayoutEnabled(this))
        return VclContainer::getLayoutRequisition(*GetWindow(WINDOW_FIRSTCHILD));
    return getLegacyBestSizeForChildren(*this);
}

void TabPage::SetPosSizePixel(const Point& rAllocPos, const Size& rAllocation)
{
    Window::SetPosSizePixel(rAllocPos, rAllocation);
    if (isLayoutEnabled(this) && rAllocation.Width() && rAllocation.Height())
        VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}

void TabPage::SetSizePixel(const Size& rAllocation)
{
    Window::SetSizePixel(rAllocation);
    if (isLayoutEnabled(this) && rAllocation.Width() && rAllocation.Height())
        VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}

void TabPage::SetPosPixel(const Point& rAllocPos)
{
    Window::SetPosPixel(rAllocPos);
    Size aAllocation(GetOutputSizePixel());
    if (isLayoutEnabled(this) && aAllocation.Width() && aAllocation.Height())
    {
        VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), aAllocation);
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
* Copyright 2014 Christian Loose <christian.loose@hamburg.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) 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.
*
* (3) The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "htmltemplate.h"

#include <QFile>

HtmlTemplate::HtmlTemplate()
{
	QFile f(":/template.html");
	if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
		htmlTemplate = f.readAll();
	}
}

QString HtmlTemplate::render(const QString &body, RenderOptions options) const
{
	// add scrollbar synchronization
	options |= Template::ScrollbarSynchronization;

	return renderAsHtml(QString(), body, options);
}

QString HtmlTemplate::exportAsHtml(const QString &header, const QString &body, RenderOptions options) const
{
	// clear code highlighting option since it depends on the resource file
	options &= ~Template::CodeHighlighting;

	return renderAsHtml(header, body, options);
}

QString HtmlTemplate::renderAsHtml(const QString &header, const QString &body, Template::RenderOptions options) const
{
	if (htmlTemplate.isEmpty()) {
		return body;
	}

	QString htmlHeader = buildHtmlHeader(options);
	htmlHeader += header;

	return QString(htmlTemplate)
			.replace(QLatin1String("<!--__HTML_HEADER__-->"), htmlHeader)
			.replace(QLatin1String("<!--__HTML_CONTENT__-->"), body);
}

QString HtmlTemplate::buildHtmlHeader(RenderOptions options) const
{
	QString header;

	// add javascript for scrollbar synchronization
	if (options.testFlag(Template::ScrollbarSynchronization)) {
		header += "<script type=\"text/javascript\">window.onscroll = function() { mainwin.webViewScrolled(); }; </script>\n";
	}

	// add MathJax.js script to HTML header
	if (options.testFlag(Template::MathSupport)) {
		header += "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>\n";
	}

	// add Highlight.js script to HTML header
	if (options.testFlag(Template::CodeHighlighting)) {
		header += QString("<link rel=\"stylesheet\" href=\"qrc:/scripts/highlight.js/styles/%1.css\">\n").arg(codeHighlightingStyle());
		header += "<script src=\"qrc:/scripts/highlight.js/highlight.pack.js\"></script>\n";
		header += "<script>hljs.initHighlightingOnLoad();</script>\n";
	}

	return header;
}

<commit_msg>Removed writing htmltemplate to filesystem<commit_after>/*
* Copyright 2014 Christian Loose <christian.loose@hamburg.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) 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.
*
* (3) The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "htmltemplate.h"

#include <QFile>

HtmlTemplate::HtmlTemplate()
{
}

QString HtmlTemplate::render(const QString &body, RenderOptions options) const
{
	// add scrollbar synchronization
	options |= Template::ScrollbarSynchronization;

	return renderAsHtml(QString(), body, options);
}

QString HtmlTemplate::exportAsHtml(const QString &header, const QString &body, RenderOptions options) const
{
	// clear code highlighting option since it depends on the resource file
	options &= ~Template::CodeHighlighting;

	return renderAsHtml(header, body, options);
}

QString HtmlTemplate::renderAsHtml(const QString &header, const QString &body, Template::RenderOptions options) const
{
	if (htmlTemplate.isEmpty()) {
		return body;
	}

	QString htmlHeader = buildHtmlHeader(options);
	htmlHeader += header;

	return QString(htmlTemplate)
			.replace(QLatin1String("<!--__HTML_HEADER__-->"), htmlHeader)
			.replace(QLatin1String("<!--__HTML_CONTENT__-->"), body);
}

QString HtmlTemplate::buildHtmlHeader(RenderOptions options) const
{
	QString header;

	// add javascript for scrollbar synchronization
	if (options.testFlag(Template::ScrollbarSynchronization)) {
		header += "<script type=\"text/javascript\">window.onscroll = function() { mainwin.webViewScrolled(); }; </script>\n";
	}

	// add MathJax.js script to HTML header
	if (options.testFlag(Template::MathSupport)) {
		header += "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>\n";
	}

	// add Highlight.js script to HTML header
	if (options.testFlag(Template::CodeHighlighting)) {
		header += QString("<link rel=\"stylesheet\" href=\"qrc:/scripts/highlight.js/styles/%1.css\">\n").arg(codeHighlightingStyle());
		header += "<script src=\"qrc:/scripts/highlight.js/highlight.pack.js\"></script>\n";
		header += "<script>hljs.initHighlightingOnLoad();</script>\n";
	}

	return header;
}

<|endoftext|>


<commit_before>//
// Created by patryk on 10.12.16.
//
#include <gtest/gtest.h>
#include <zinot-utils/zimesh-json/ZimeshJsonReader.hpp>

class ZimeshJsonTest : public ::testing::Test
{
protected:
   Zimesh::ZimeshJsonDao zimeshJsonDao;
};

TEST_F(ZimeshJsonTest, loading)
{
   EXPECT_TRUE(Zimesh::ZimeshJsonReader::loadFromJson("media/models/table.json", zimeshJsonDao));
   Zimesh::ZimeshJsonDao & dao = zimeshJsonDao;
}
<commit_msg>Fixed testing Zimesh JSON loader<commit_after>//
// Created by patryk on 10.12.16.
//
#include <gtest/gtest.h>
#include <zinot-utils/zimesh-json/ZimeshJsonReader.hpp>

class ZimeshJsonTest : public ::testing::Test
{
protected:
   Zimesh::ZimeshJsonDao zimeshJsonDao;
};

TEST_F(ZimeshJsonTest, loading)
{
   EXPECT_TRUE(Zimesh::ZimeshJsonReader::loadFromJson("media/models/table/table.json", zimeshJsonDao));
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * 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 copyright holders 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
 * OWNER OR CONTRIBUTORS 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.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_FAULTS_HH__
#define __ARCH_X86_FAULTS_HH__

#include <string>

#include "base/bitunion.hh"
#include "base/misc.hh"
#include "sim/faults.hh"
#include "sim/tlb.hh"

namespace X86ISA
{
    // Base class for all x86 "faults" where faults is in the m5 sense
    class X86FaultBase : public FaultBase
    {
      protected:
        const char * faultName;
        const char * mnem;
        uint8_t vector;
        uint64_t errorCode;

        X86FaultBase(const char * _faultName, const char * _mnem,
                     const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
            : faultName(_faultName), mnem(_mnem),
              vector(_vector), errorCode(_errorCode)
        {
        }

        const char * name() const
        {
            return faultName;
        }

        virtual bool isBenign()
        {
            return true;
        }

        virtual const char * mnemonic() const
        {
            return mnem;
        }

        virtual bool isSoft()
        {
            return false;
        }

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);

        virtual std::string describe() const;
    };

    // Base class for x86 faults which behave as if the underlying instruction
    // didn't happen.
    class X86Fault : public X86FaultBase
    {
      protected:
        X86Fault(const char * name, const char * mnem,
                 const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, vector, _errorCode)
        {}
    };

    // Base class for x86 traps which behave as if the underlying instruction
    // completed.
    class X86Trap : public X86FaultBase
    {
      protected:
        X86Trap(const char * name, const char * mnem,
                const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, vector, _errorCode)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    // Base class for x86 aborts which seem to be catastrophic failures.
    class X86Abort : public X86FaultBase
    {
      protected:
        X86Abort(const char * name, const char * mnem,
                const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, vector, _errorCode)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    // Base class for x86 interrupts.
    class X86Interrupt : public X86FaultBase
    {
      protected:
        X86Interrupt(const char * name, const char * mnem,
                const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, _vector, _errorCode)
        {}
    };

    class UnimpInstFault : public FaultBase
    {
      public:
        const char * name() const
        {
            return "unimplemented_micro";
        }

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr)
        {
            panic("Unimplemented instruction!");
        }
    };

    // Below is a summary of the interrupt/exception information in the
    // architecture manuals.

    // Class  |  Type    | vector |               Cause                 | mnem
    //------------------------------------------------------------------------
    //Contrib   Fault     0         Divide-by-Zero-Error                  #DE
    //Benign    Either    1         Debug                                 #DB
    //Benign    Interrupt 2         Non-Maskable-Interrupt                #NMI
    //Benign    Trap      3         Breakpoint                            #BP
    //Benign    Trap      4         Overflow                              #OF
    //Benign    Fault     5         Bound-Range                           #BR
    //Benign    Fault     6         Invalid-Opcode                        #UD
    //Benign    Fault     7         Device-Not-Available                  #NM
    //Benign    Abort     8         Double-Fault                          #DF
    //                    9         Coprocessor-Segment-Overrun
    //Contrib   Fault     10        Invalid-TSS                           #TS
    //Contrib   Fault     11        Segment-Not-Present                   #NP
    //Contrib   Fault     12        Stack                                 #SS
    //Contrib   Fault     13        General-Protection                    #GP
    //Either    Fault     14        Page-Fault                            #PF
    //                    15        Reserved
    //Benign    Fault     16        x87 Floating-Point Exception Pending  #MF
    //Benign    Fault     17        Alignment-Check                       #AC
    //Benign    Abort     18        Machine-Check                         #MC
    //Benign    Fault     19        SIMD Floating-Point                   #XF
    //                    20-29     Reserved
    //Contrib   ?         30        Security Exception                    #SX
    //                    31        Reserved
    //Benign    Interrupt 0-255     External Interrupts                   #INTR
    //Benign    Interrupt 0-255     Software Interrupts                   INTn

    class DivideByZero : public X86Fault
    {
      public:
        DivideByZero() :
            X86Fault("Divide-by-Zero-Error", "#DE", 0)
        {}
    };

    class DebugException : public X86FaultBase
    {
      public:
        DebugException() :
            X86FaultBase("Debug", "#DB", 1)
        {}
    };

    class NonMaskableInterrupt : public X86Interrupt
    {
      public:
        NonMaskableInterrupt(uint8_t _vector) :
            X86Interrupt("Non Maskable Interrupt", "#NMI", 2, _vector)
        {}
    };

    class Breakpoint : public X86Trap
    {
      public:
        Breakpoint() :
            X86Trap("Breakpoint", "#BP", 3)
        {}
    };

    class OverflowTrap : public X86Trap
    {
      public:
        OverflowTrap() :
            X86Trap("Overflow", "#OF", 4)
        {}
    };

    class BoundRange : public X86Fault
    {
      public:
        BoundRange() :
            X86Fault("Bound-Range", "#BR", 5)
        {}
    };

    class InvalidOpcode : public X86Fault
    {
      public:
        InvalidOpcode() :
            X86Fault("Invalid-Opcode", "#UD", 6)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    class DeviceNotAvailable : public X86Fault
    {
      public:
        DeviceNotAvailable() :
            X86Fault("Device-Not-Available", "#NM", 7)
        {}
    };

    class DoubleFault : public X86Abort
    {
      public:
        DoubleFault() :
            X86Abort("Double-Fault", "#DF", 8, 0)
        {}
    };

    class InvalidTSS : public X86Fault
    {
      public:
        InvalidTSS(uint32_t _errorCode) :
            X86Fault("Invalid-TSS", "#TS", 10, _errorCode)
        {}
    };

    class SegmentNotPresent : public X86Fault
    {
      public:
        SegmentNotPresent(uint32_t _errorCode) :
            X86Fault("Segment-Not-Present", "#NP", 11, _errorCode)
        {}
    };

    class StackFault : public X86Fault
    {
      public:
        StackFault(uint32_t _errorCode) :
            X86Fault("Stack", "#SS", 12, _errorCode)
        {}
    };

    class GeneralProtection : public X86Fault
    {
      public:
        GeneralProtection(uint32_t _errorCode) :
            X86Fault("General-Protection", "#GP", 13, _errorCode)
        {}
    };

    class PageFault : public X86Fault
    {
      protected:
        BitUnion32(PageFaultErrorCode)
            Bitfield<0> present;
            Bitfield<1> write;
            Bitfield<2> user;
            Bitfield<3> reserved;
            Bitfield<4> fetch;
        EndBitUnion(PageFaultErrorCode)

        Addr addr;

      public:
        PageFault(Addr _addr, uint32_t _errorCode) :
            X86Fault("Page-Fault", "#PF", 14, _errorCode), addr(_addr)
        {}

        PageFault(Addr _addr, bool present, BaseTLB::Mode mode,
                bool user, bool reserved) :
            X86Fault("Page-Fault", "#PF", 14, 0), addr(_addr)
        {
            PageFaultErrorCode code = 0;
            code.present = present;
            code.write = (mode == BaseTLB::Write);
            code.user = user;
            code.reserved = reserved;
            code.fetch = (mode == BaseTLB::Execute);
            errorCode = code;
        }

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);

        virtual std::string describe() const;
    };

    class X87FpExceptionPending : public X86Fault
    {
      public:
        X87FpExceptionPending() :
            X86Fault("x87 Floating-Point Exception Pending", "#MF", 16)
        {}
    };

    class AlignmentCheck : public X86Fault
    {
      public:
        AlignmentCheck() :
            X86Fault("Alignment-Check", "#AC", 17, 0)
        {}
    };

    class MachineCheck : public X86Abort
    {
      public:
        MachineCheck() :
            X86Abort("Machine-Check", "#MC", 18)
        {}
    };

    class SIMDFloatingPointFault : public X86Fault
    {
      public:
        SIMDFloatingPointFault() :
            X86Fault("SIMD Floating-Point", "#XF", 19)
        {}
    };

    class SecurityException : public X86FaultBase
    {
      public:
        SecurityException() :
            X86FaultBase("Security Exception", "#SX", 30)
        {}
    };

    class ExternalInterrupt : public X86Interrupt
    {
      public:
        ExternalInterrupt(uint8_t _vector) :
            X86Interrupt("External Interrupt", "#INTR", _vector)
        {}
    };

    class SystemManagementInterrupt : public X86Interrupt
    {
      public:
        SystemManagementInterrupt() :
            X86Interrupt("System Management Interrupt", "#SMI", 0)
        {}
    };

    class InitInterrupt : public X86Interrupt
    {
      public:
        InitInterrupt(uint8_t _vector) :
            X86Interrupt("INIT Interrupt", "#INIT", _vector)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    class StartupInterrupt : public X86Interrupt
    {
      public:
        StartupInterrupt(uint8_t _vector) :
            X86Interrupt("Startup Interrupt", "#SIPI", _vector)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    class SoftwareInterrupt : public X86Interrupt
    {
      public:
        SoftwareInterrupt(uint8_t _vector) :
            X86Interrupt("Software Interrupt", "#INTR", _vector)
        {}

        bool isSoft()
        {
            return true;
        }
    };
}

#endif // __ARCH_X86_FAULTS_HH__
<commit_msg>x86: Expose the interrupt vector in faults<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * 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 copyright holders 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
 * OWNER OR CONTRIBUTORS 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.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_FAULTS_HH__
#define __ARCH_X86_FAULTS_HH__

#include <string>

#include "base/bitunion.hh"
#include "base/misc.hh"
#include "sim/faults.hh"
#include "sim/tlb.hh"

namespace X86ISA
{
    // Base class for all x86 "faults" where faults is in the m5 sense
    class X86FaultBase : public FaultBase
    {
      protected:
        const char * faultName;
        const char * mnem;
        uint8_t vector;
        uint64_t errorCode;

        X86FaultBase(const char * _faultName, const char * _mnem,
                     const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
            : faultName(_faultName), mnem(_mnem),
              vector(_vector), errorCode(_errorCode)
        {
        }

        const char * name() const
        {
            return faultName;
        }

        virtual bool isBenign()
        {
            return true;
        }

        virtual const char * mnemonic() const
        {
            return mnem;
        }

        virtual bool isSoft()
        {
            return false;
        }

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);

        virtual std::string describe() const;

      public:
        /**
         * Get the vector of an interrupt.
         *
         * @return interrupt vector number.
         */
        virtual uint8_t getVector() const { return vector; }
    };

    // Base class for x86 faults which behave as if the underlying instruction
    // didn't happen.
    class X86Fault : public X86FaultBase
    {
      protected:
        X86Fault(const char * name, const char * mnem,
                 const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, vector, _errorCode)
        {}
    };

    // Base class for x86 traps which behave as if the underlying instruction
    // completed.
    class X86Trap : public X86FaultBase
    {
      protected:
        X86Trap(const char * name, const char * mnem,
                const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, vector, _errorCode)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    // Base class for x86 aborts which seem to be catastrophic failures.
    class X86Abort : public X86FaultBase
    {
      protected:
        X86Abort(const char * name, const char * mnem,
                const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, vector, _errorCode)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    // Base class for x86 interrupts.
    class X86Interrupt : public X86FaultBase
    {
      protected:
        X86Interrupt(const char * name, const char * mnem,
                const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
            : X86FaultBase(name, mnem, _vector, _errorCode)
        {}
    };

    class UnimpInstFault : public FaultBase
    {
      public:
        const char * name() const
        {
            return "unimplemented_micro";
        }

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr)
        {
            panic("Unimplemented instruction!");
        }
    };

    // Below is a summary of the interrupt/exception information in the
    // architecture manuals.

    // Class  |  Type    | vector |               Cause                 | mnem
    //------------------------------------------------------------------------
    //Contrib   Fault     0         Divide-by-Zero-Error                  #DE
    //Benign    Either    1         Debug                                 #DB
    //Benign    Interrupt 2         Non-Maskable-Interrupt                #NMI
    //Benign    Trap      3         Breakpoint                            #BP
    //Benign    Trap      4         Overflow                              #OF
    //Benign    Fault     5         Bound-Range                           #BR
    //Benign    Fault     6         Invalid-Opcode                        #UD
    //Benign    Fault     7         Device-Not-Available                  #NM
    //Benign    Abort     8         Double-Fault                          #DF
    //                    9         Coprocessor-Segment-Overrun
    //Contrib   Fault     10        Invalid-TSS                           #TS
    //Contrib   Fault     11        Segment-Not-Present                   #NP
    //Contrib   Fault     12        Stack                                 #SS
    //Contrib   Fault     13        General-Protection                    #GP
    //Either    Fault     14        Page-Fault                            #PF
    //                    15        Reserved
    //Benign    Fault     16        x87 Floating-Point Exception Pending  #MF
    //Benign    Fault     17        Alignment-Check                       #AC
    //Benign    Abort     18        Machine-Check                         #MC
    //Benign    Fault     19        SIMD Floating-Point                   #XF
    //                    20-29     Reserved
    //Contrib   ?         30        Security Exception                    #SX
    //                    31        Reserved
    //Benign    Interrupt 0-255     External Interrupts                   #INTR
    //Benign    Interrupt 0-255     Software Interrupts                   INTn

    class DivideByZero : public X86Fault
    {
      public:
        DivideByZero() :
            X86Fault("Divide-by-Zero-Error", "#DE", 0)
        {}
    };

    class DebugException : public X86FaultBase
    {
      public:
        DebugException() :
            X86FaultBase("Debug", "#DB", 1)
        {}
    };

    class NonMaskableInterrupt : public X86Interrupt
    {
      public:
        NonMaskableInterrupt(uint8_t _vector) :
            X86Interrupt("Non Maskable Interrupt", "#NMI", 2, _vector)
        {}
    };

    class Breakpoint : public X86Trap
    {
      public:
        Breakpoint() :
            X86Trap("Breakpoint", "#BP", 3)
        {}
    };

    class OverflowTrap : public X86Trap
    {
      public:
        OverflowTrap() :
            X86Trap("Overflow", "#OF", 4)
        {}
    };

    class BoundRange : public X86Fault
    {
      public:
        BoundRange() :
            X86Fault("Bound-Range", "#BR", 5)
        {}
    };

    class InvalidOpcode : public X86Fault
    {
      public:
        InvalidOpcode() :
            X86Fault("Invalid-Opcode", "#UD", 6)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    class DeviceNotAvailable : public X86Fault
    {
      public:
        DeviceNotAvailable() :
            X86Fault("Device-Not-Available", "#NM", 7)
        {}
    };

    class DoubleFault : public X86Abort
    {
      public:
        DoubleFault() :
            X86Abort("Double-Fault", "#DF", 8, 0)
        {}
    };

    class InvalidTSS : public X86Fault
    {
      public:
        InvalidTSS(uint32_t _errorCode) :
            X86Fault("Invalid-TSS", "#TS", 10, _errorCode)
        {}
    };

    class SegmentNotPresent : public X86Fault
    {
      public:
        SegmentNotPresent(uint32_t _errorCode) :
            X86Fault("Segment-Not-Present", "#NP", 11, _errorCode)
        {}
    };

    class StackFault : public X86Fault
    {
      public:
        StackFault(uint32_t _errorCode) :
            X86Fault("Stack", "#SS", 12, _errorCode)
        {}
    };

    class GeneralProtection : public X86Fault
    {
      public:
        GeneralProtection(uint32_t _errorCode) :
            X86Fault("General-Protection", "#GP", 13, _errorCode)
        {}
    };

    class PageFault : public X86Fault
    {
      protected:
        BitUnion32(PageFaultErrorCode)
            Bitfield<0> present;
            Bitfield<1> write;
            Bitfield<2> user;
            Bitfield<3> reserved;
            Bitfield<4> fetch;
        EndBitUnion(PageFaultErrorCode)

        Addr addr;

      public:
        PageFault(Addr _addr, uint32_t _errorCode) :
            X86Fault("Page-Fault", "#PF", 14, _errorCode), addr(_addr)
        {}

        PageFault(Addr _addr, bool present, BaseTLB::Mode mode,
                bool user, bool reserved) :
            X86Fault("Page-Fault", "#PF", 14, 0), addr(_addr)
        {
            PageFaultErrorCode code = 0;
            code.present = present;
            code.write = (mode == BaseTLB::Write);
            code.user = user;
            code.reserved = reserved;
            code.fetch = (mode == BaseTLB::Execute);
            errorCode = code;
        }

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);

        virtual std::string describe() const;
    };

    class X87FpExceptionPending : public X86Fault
    {
      public:
        X87FpExceptionPending() :
            X86Fault("x87 Floating-Point Exception Pending", "#MF", 16)
        {}
    };

    class AlignmentCheck : public X86Fault
    {
      public:
        AlignmentCheck() :
            X86Fault("Alignment-Check", "#AC", 17, 0)
        {}
    };

    class MachineCheck : public X86Abort
    {
      public:
        MachineCheck() :
            X86Abort("Machine-Check", "#MC", 18)
        {}
    };

    class SIMDFloatingPointFault : public X86Fault
    {
      public:
        SIMDFloatingPointFault() :
            X86Fault("SIMD Floating-Point", "#XF", 19)
        {}
    };

    class SecurityException : public X86FaultBase
    {
      public:
        SecurityException() :
            X86FaultBase("Security Exception", "#SX", 30)
        {}
    };

    class ExternalInterrupt : public X86Interrupt
    {
      public:
        ExternalInterrupt(uint8_t _vector) :
            X86Interrupt("External Interrupt", "#INTR", _vector)
        {}
    };

    class SystemManagementInterrupt : public X86Interrupt
    {
      public:
        SystemManagementInterrupt() :
            X86Interrupt("System Management Interrupt", "#SMI", 0)
        {}
    };

    class InitInterrupt : public X86Interrupt
    {
      public:
        InitInterrupt(uint8_t _vector) :
            X86Interrupt("INIT Interrupt", "#INIT", _vector)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    class StartupInterrupt : public X86Interrupt
    {
      public:
        StartupInterrupt(uint8_t _vector) :
            X86Interrupt("Startup Interrupt", "#SIPI", _vector)
        {}

        void invoke(ThreadContext * tc,
                StaticInstPtr inst = StaticInst::nullStaticInstPtr);
    };

    class SoftwareInterrupt : public X86Interrupt
    {
      public:
        SoftwareInterrupt(uint8_t _vector) :
            X86Interrupt("Software Interrupt", "#INTR", _vector)
        {}

        bool isSoft()
        {
            return true;
        }
    };
}

#endif // __ARCH_X86_FAULTS_HH__
<|endoftext|>