<commit_before>/*-
 * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
 * All rights reserved.
 *
 * 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
 *    in this position and unchanged.
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) 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 <stdexcept>

#include "gfx.h"

namespace portal {
namespace gfx {

void Gfx::init() {
  initscr();

  if (has_colors() && start_color() == OK) {
    init_pair(Style::Color::none, 0, 0);
    init_pair(Style::Color::black, COLOR_BLACK, 0);
    init_pair(Style::Color::cyan, COLOR_CYAN, 0);
    init_pair(Style::Color::magenta, COLOR_MAGENTA, 0);
    init_pair(Style::Color::red, COLOR_RED, 0);
    init_pair(Style::Color::yellow, COLOR_YELLOW, 0);
    init_pair(Style::Color::blue, COLOR_BLUE, 0);
    init_pair(Style::Color::cyanOnBlue, COLOR_CYAN, COLOR_BLUE);
  } else {
    // XXX Need to deal with B&W terminals
    throw std::runtime_error("Sorry, B&W terminals not supported yet");
  }

  raw();
  noecho();
  keypad(stdscr, TRUE);
  curs_set(0);
  refresh();  // A refresh might seem unnecessary here, but user input is
              // gathered from stdscr via a call to getch, which does an
              // implicit refresh first (don't ask me why...). Hence doing
              // this refresh explicitly avoids a black screen when portal
              // starts. The black screen does not appear afterwards as
              // stdscr is never touched by portal, so curses detects it
              // does not need any subsequent refreshes.
}

// The curses library fails to handle two concurrent threads trying to
// update the display at the same time. This creates a single point of
// entry that prevents this case from happening. Morevover, a try_lock
// is used here instead of just lock, as if a thread is already
// updating the display, we assume there is no need to update it again
// right after, so we skip an update to avoir too frequent refreshes.
void Gfx::update() {
  if (mutex_.try_lock()) {
    doupdate();
    mutex_.unlock();
  }
}

void Gfx::terminate() {
  clear();
  endwin();
}

}
}
<commit_msg>Add support for transparent terminals<commit_after>/*-
 * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
 * All rights reserved.
 *
 * 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
 *    in this position and unchanged.
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) 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 <stdexcept>

#include "gfx.h"

namespace portal {
namespace gfx {

void Gfx::init() {
  initscr();

  if (has_colors() && start_color() == OK) {
    use_default_colors();
    init_pair(Style::Color::none, -1, -1);
    init_pair(Style::Color::black, COLOR_BLACK, -1);
    init_pair(Style::Color::cyan, COLOR_CYAN, -1);
    init_pair(Style::Color::magenta, COLOR_MAGENTA, -1);
    init_pair(Style::Color::red, COLOR_RED, -1);
    init_pair(Style::Color::yellow, COLOR_YELLOW, -1);
    init_pair(Style::Color::blue, COLOR_BLUE, -1);
    init_pair(Style::Color::cyanOnBlue, COLOR_CYAN, COLOR_BLUE);
  } else {
    // XXX Need to deal with B&W terminals
    throw std::runtime_error("Sorry, B&W terminals not supported yet");
  }

  raw();
  noecho();
  keypad(stdscr, TRUE);
  curs_set(0);
  refresh();  // A refresh might seem unnecessary here, but user input is
              // gathered from stdscr via a call to getch, which does an
              // implicit refresh first (don't ask me why...). Hence doing
              // this refresh explicitly avoids a black screen when portal
              // starts. The black screen does not appear afterwards as
              // stdscr is never touched by portal, so curses detects it
              // does not need any subsequent refreshes.
}

// The curses library fails to handle two concurrent threads trying to
// update the display at the same time. This creates a single point of
// entry that prevents this case from happening. Morevover, a try_lock
// is used here instead of just lock, as if a thread is already
// updating the display, we assume there is no need to update it again
// right after, so we skip an update to avoir too frequent refreshes.
void Gfx::update() {
  if (mutex_.try_lock()) {
    doupdate();
    mutex_.unlock();
  }
}

void Gfx::terminate() {
  clear();
  endwin();
}

}
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <map>
#include <string>
#include <limits>

#include "Prefetch.h"
#include "CodeGen_Internal.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Bounds.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "Util.h"

namespace Halide {
namespace Internal {

using std::map;
using std::string;
using std::vector;
using std::stack;

// Prefetch debug levels
int dbg_prefetch0 = 1;
int dbg_prefetch1 = 2;
int dbg_prefetch2 = 3;
int dbg_prefetch3 = 10;

#define MIN(x,y)        (((x)<(y)) ? (x) : (y))
#define MAX(x,y)        (((x)>(y)) ? (x) : (y))

class InjectPrefetch : public IRMutator {
public:
    InjectPrefetch(const map<string, Function> &e)
        : env(e) { }
private:
    const map<string, Function> &env;
    Scope<Interval> scope;
    unsigned long ptmp = 0;   // ID for all tmp vars in a prefetch op

private:
    using IRMutator::visit;

    // Strip down the tuple name, e.g. f.*.var into f
    string tuple_func(const string &name) {
        vector<string> v = split_string(name, ".");
        internal_assert(v.size() > 0);
        return v[0];
    }

    // Strip down the tuple name, e.g. f.*.var into var
    string tuple_var(const string &name) {
        vector<string> v = split_string(name, ".");
        internal_assert(v.size() > 0);
        return v[v.size()-1];
    }

    // Lookup a function in the environment
    Function get_func(const string &name) {
        map<string, Function>::const_iterator iter = env.find(name);
        internal_assert(iter != env.end()) << "function not in environment.\n";
        return iter->second;
    }

    // Determine the static type of a named buffer (if available)
    // Note: the type of input is only known at runtime (use input.elem_size)
    Type get_type(string varname, bool &has_static_type) {
        debug(dbg_prefetch2) << "    getType(" << varname << ")\n";
        Type t = UInt(8);
        map<string, Function>::const_iterator varit = env.find(varname);
        if (varit != env.end()) {
            Function varf = varit->second;
            debug(dbg_prefetch2) << "      found: " << varit->first << "\n";
            if (varf.outputs()) {
                vector<Type> varts = varf.output_types();
                t = varts[0];
                debug(dbg_prefetch2) << "      type: " << t << "\n";
            }
            has_static_type = true;
        } else {
            debug(dbg_prefetch2) << "      could not statically determine type of " << varname
                                 << ", temporarily using: " << t << "\n";
            has_static_type = false;
        }
        return t;
    }

    void visit(const Let *op) {
        Interval in = bounds_of_expr_in_scope(op->value, scope);
        scope.push(op->name, in);
        IRMutator::visit(op);
        scope.pop(op->name);
    }
    void visit(const LetStmt *op) {
        Interval in = bounds_of_expr_in_scope(op->value, scope);
        scope.push(op->name, in);
        IRMutator::visit(op);
        scope.pop(op->name);
    }

    void visit(const For *op) {
        Stmt body = op->body;

        string func_name = tuple_func(op->name);
        string ivar_name = tuple_var(op->name);
        vector<Prefetch> &prefetches = get_func(func_name).schedule().prefetches();

        if (prefetches.empty()) {
            debug(dbg_prefetch2) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
            debug(dbg_prefetch2) << " No prefetch\n";
        } else {
            debug(dbg_prefetch1) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
            debug(dbg_prefetch1) << " Found prefetch directive(s)\n";
        }

        for (const Prefetch &p : prefetches) {
            debug(dbg_prefetch1) << "InjectPrefetch: check ivar:" << p.var << "\n";
            if (p.var == ivar_name) {
                debug(dbg_prefetch0) << " " << func_name
                                     << " prefetch(" << ivar_name << ", " << p.offset << ")\n";

                // Interval prein(op->name, op->name);
                // Add in prefetch offset
                Expr var = Variable::make(Int(32), op->name);
                Interval prein(var + p.offset, var + p.offset);
                scope.push(op->name, prein);

                map<string, Box> boxes;
                boxes = boxes_required(body, scope);

                int cnt = 0;            // Number of prefetch ops generated
                Stmt pstmts;            // Generated prefetch statements
                debug(dbg_prefetch1) << "  boxes required:\n";
                for (auto &b : boxes) {
                    bool do_prefetch = true;
                    const string &varname = b.first;
                    Box &box = b.second;
                    int dims = box.size();
                    bool has_static_type = true;
                    Type t = get_type(varname, has_static_type);
                    debug(dbg_prefetch0) << "  prefetch" << ptmp << ": "
                                         << varname << " (" << t
                                         << (has_static_type ? "" : "dynamic_type")
                                         << ", dims:" << dims << ")\n";
                    for (int i = 0; i < dims; i++) {
                        debug(dbg_prefetch1) << "    ---\n";
                        debug(dbg_prefetch1) << "    box[" << i << "].min: " << box[i].min << "\n";
                        debug(dbg_prefetch1) << "    box[" << i << "].max: " << box[i].max << "\n";
                    }
                    debug(dbg_prefetch1) << "    ---------\n";

                    // TODO: Opt: check box if it should be prefetched?
                    // TODO       - Only prefetch if varying by ivar_name?
                    // TODO       - Don't prefetch if "small" all constant dimensions?
                    // TODO         e.g. see: camera_pipe.cpp corrected matrix(4,3)

                    string pstr = std::to_string(ptmp++);
                    string varname_prefetch_buf = varname + ".prefetch_" + pstr + "_buf";
                    Expr var_prefetch_buf = Variable::make(Int(32), varname_prefetch_buf);

                    // Make the names for accessing the buffer strides
                    vector<Expr> stride_var(dims);
                    for (int i = 0; i < dims; i++) {
                        string istr = std::to_string(i);
                        string stride_name = varname + ".stride." + istr;
#if 0                   // TODO: Determine if the stride varname is defined - check not yet working
                        // if (!scope.contains(stride_name)) [
                        if (env.find(stride_name) == env.end()) {
                            do_prefetch = false;
                            debug(dbg_prefetch0) << "  " << stride_name << " undefined\n";
                            break;
                        }
#endif
                        stride_var[i] = Variable::make(Int(32), stride_name);
                    }

                    // This box should not be prefetched
                    if (!do_prefetch) {
                        debug(dbg_prefetch0) << "  not prefetching " << varname << "\n";
                        continue;
                    }

                    // Make the names for the prefetch box mins & maxes
                    vector<string> min_name(dims), max_name(dims);
                    for (int i = 0; i < dims; i++) {
                        string istr = std::to_string(i);
                        min_name[i] = varname + ".prefetch_" + pstr + "_min_" + istr;
                        max_name[i] = varname + ".prefetch_" + pstr + "_max_" + istr;
                    }
                    vector<Expr> min_var(dims), max_var(dims);
                    for (int i = 0; i < dims; i++) {
                        min_var[i] = Variable::make(Int(32), min_name[i]);
                        max_var[i] = Variable::make(Int(32), max_name[i]);
                    }

                    // Create a buffer_t object for this prefetch.
                    vector<Expr> args(dims*3 + 2);
                    Expr first_elem = Load::make(t, varname, 0, Buffer(), Parameter());
                    args[0] = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);
                    args[1] = make_zero(t);
                    for (int i = 0; i < dims; i++) {
                        args[3*i+2] = min_var[i];
                        args[3*i+3] = max_var[i] - min_var[i] + 1;
                        args[3*i+4] = stride_var[i];
                    }

                    // Inject the prefetch call
                    vector<Expr> args_prefetch(3);
                    args_prefetch[0] = dims;
                    if (has_static_type) {
                        args_prefetch[1] = t.bytes();
                    } else {
                        // Element size for inputs that don't have static types
                        string elem_size_name = varname + ".elem_size";
                        Expr elem_size_var = Variable::make(Int(32), elem_size_name);
                        args_prefetch[1] = elem_size_var;
                    }
                    args_prefetch[2] = var_prefetch_buf;
                    // TODO: Opt: Keep running sum of bytes prefetched on this sequence
                    // TODO: Opt: Keep running sum of number of prefetch instructions issued
                    // TODO       on this sequence? (to not exceed MAX_PREFETCH)
                    // TODO: Opt: Generate control code for prefetch_buffer_t in Prefetch.cpp
                    // TODO       Passing box info through a buffer_t results in ~30 additional stores/loads
                    Stmt stmt_prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_buffer_t,
                                          args_prefetch, Call::Intrinsic));
                    if (cnt == 0) {
                        pstmts = stmt_prefetch;
                    } else {
                        pstmts = Block::make({stmt_prefetch, pstmts});
                    }
                    cnt++;

                    // Inject the create_buffer_t call
                    Expr prefetch_buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,
                                          args, Call::Intrinsic);
                    pstmts = LetStmt::make(varname_prefetch_buf, prefetch_buf, pstmts);

                    // Inject bounds variable assignments
                    for (int i = dims-1; i >= 0; i--) {
                        pstmts = LetStmt::make(max_name[i], box[i].max, pstmts);
                        pstmts = LetStmt::make(min_name[i], box[i].min, pstmts);
                        // stride already defined by input buffer
                    }
                }

                if (cnt) {
#if 1
                    // Guard to not prefetch past the end of the iteration space
                    // TODO: Opt: Use original extent of loop for guard (avoid conservative guard when stripmined)
                    Expr pcond = likely((Variable::make(Int(32), op->name) + p.offset)
                                                        < (op->min + op->extent - 1));
                    Stmt pguard = IfThenElse::make(pcond, pstmts);
                    body = Block::make({pguard, body});

                    debug(dbg_prefetch3) << "    prefetch: (cnt:" << cnt << ")\n";
                    debug(dbg_prefetch3) << pguard << "\n";
#else
                    body = Block::make({pstmts, body});
#endif
                }

                scope.pop(op->name);
            }
        }

        body = mutate(body);
        stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
    }

};

Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env)
{
    size_t read;
    std::string lvl = get_env_variable("HL_DEBUG_PREFETCH", read);
    if (read) {
        int dbg_level = atoi(lvl.c_str());
        dbg_prefetch0 = MAX(dbg_prefetch0 - dbg_level, 0);
        dbg_prefetch1 = MAX(dbg_prefetch1 - dbg_level, 0);
        dbg_prefetch2 = MAX(dbg_prefetch2 - dbg_level, 0);
        dbg_prefetch3 = MAX(dbg_prefetch3 - dbg_level, 0);
    }
    return InjectPrefetch(env).mutate(s);
}

}
}
<commit_msg>Cleanup debug dynamic_type indicator<commit_after>#include <algorithm>
#include <map>
#include <string>
#include <limits>

#include "Prefetch.h"
#include "CodeGen_Internal.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Bounds.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "Util.h"

namespace Halide {
namespace Internal {

using std::map;
using std::string;
using std::vector;
using std::stack;

// Prefetch debug levels
int dbg_prefetch0 = 1;
int dbg_prefetch1 = 2;
int dbg_prefetch2 = 3;
int dbg_prefetch3 = 10;

#define MIN(x,y)        (((x)<(y)) ? (x) : (y))
#define MAX(x,y)        (((x)>(y)) ? (x) : (y))

class InjectPrefetch : public IRMutator {
public:
    InjectPrefetch(const map<string, Function> &e)
        : env(e) { }
private:
    const map<string, Function> &env;
    Scope<Interval> scope;
    unsigned long ptmp = 0;   // ID for all tmp vars in a prefetch op

private:
    using IRMutator::visit;

    // Strip down the tuple name, e.g. f.*.var into f
    string tuple_func(const string &name) {
        vector<string> v = split_string(name, ".");
        internal_assert(v.size() > 0);
        return v[0];
    }

    // Strip down the tuple name, e.g. f.*.var into var
    string tuple_var(const string &name) {
        vector<string> v = split_string(name, ".");
        internal_assert(v.size() > 0);
        return v[v.size()-1];
    }

    // Lookup a function in the environment
    Function get_func(const string &name) {
        map<string, Function>::const_iterator iter = env.find(name);
        internal_assert(iter != env.end()) << "function not in environment.\n";
        return iter->second;
    }

    // Determine the static type of a named buffer (if available)
    // Note: the type of input is only known at runtime (use input.elem_size)
    Type get_type(string varname, bool &has_static_type) {
        debug(dbg_prefetch2) << "    getType(" << varname << ")\n";
        Type t = UInt(8);
        map<string, Function>::const_iterator varit = env.find(varname);
        if (varit != env.end()) {
            Function varf = varit->second;
            debug(dbg_prefetch2) << "      found: " << varit->first << "\n";
            if (varf.outputs()) {
                vector<Type> varts = varf.output_types();
                t = varts[0];
                debug(dbg_prefetch2) << "      type: " << t << "\n";
            }
            has_static_type = true;
        } else {
            debug(dbg_prefetch2) << "      could not statically determine type of " << varname
                                 << ", temporarily using: " << t << "\n";
            has_static_type = false;
        }
        return t;
    }

    void visit(const Let *op) {
        Interval in = bounds_of_expr_in_scope(op->value, scope);
        scope.push(op->name, in);
        IRMutator::visit(op);
        scope.pop(op->name);
    }
    void visit(const LetStmt *op) {
        Interval in = bounds_of_expr_in_scope(op->value, scope);
        scope.push(op->name, in);
        IRMutator::visit(op);
        scope.pop(op->name);
    }

    void visit(const For *op) {
        Stmt body = op->body;

        string func_name = tuple_func(op->name);
        string ivar_name = tuple_var(op->name);
        vector<Prefetch> &prefetches = get_func(func_name).schedule().prefetches();

        if (prefetches.empty()) {
            debug(dbg_prefetch2) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
            debug(dbg_prefetch2) << " No prefetch\n";
        } else {
            debug(dbg_prefetch1) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
            debug(dbg_prefetch1) << " Found prefetch directive(s)\n";
        }

        for (const Prefetch &p : prefetches) {
            debug(dbg_prefetch1) << "InjectPrefetch: check ivar:" << p.var << "\n";
            if (p.var == ivar_name) {
                debug(dbg_prefetch0) << " " << func_name
                                     << " prefetch(" << ivar_name << ", " << p.offset << ")\n";

                // Interval prein(op->name, op->name);
                // Add in prefetch offset
                Expr var = Variable::make(Int(32), op->name);
                Interval prein(var + p.offset, var + p.offset);
                scope.push(op->name, prein);

                map<string, Box> boxes;
                boxes = boxes_required(body, scope);

                int cnt = 0;            // Number of prefetch ops generated
                Stmt pstmts;            // Generated prefetch statements
                debug(dbg_prefetch1) << "  boxes required:\n";
                for (auto &b : boxes) {
                    bool do_prefetch = true;
                    const string &varname = b.first;
                    Box &box = b.second;
                    int dims = box.size();
                    bool has_static_type = true;
                    Type t = get_type(varname, has_static_type);
                    debug(dbg_prefetch0) << "  prefetch" << ptmp << ": "
                                         << varname << " (" << t
                                         << (has_static_type ? "" : ":dynamic_type")
                                         << ", dims:" << dims << ")\n";
                    for (int i = 0; i < dims; i++) {
                        debug(dbg_prefetch1) << "    ---\n";
                        debug(dbg_prefetch1) << "    box[" << i << "].min: " << box[i].min << "\n";
                        debug(dbg_prefetch1) << "    box[" << i << "].max: " << box[i].max << "\n";
                    }
                    debug(dbg_prefetch1) << "    ---------\n";

                    // TODO: Opt: check box if it should be prefetched?
                    // TODO       - Only prefetch if varying by ivar_name?
                    // TODO       - Don't prefetch if "small" all constant dimensions?
                    // TODO         e.g. see: camera_pipe.cpp corrected matrix(4,3)

                    string pstr = std::to_string(ptmp++);
                    string varname_prefetch_buf = varname + ".prefetch_" + pstr + "_buf";
                    Expr var_prefetch_buf = Variable::make(Int(32), varname_prefetch_buf);

                    // Make the names for accessing the buffer strides
                    vector<Expr> stride_var(dims);
                    for (int i = 0; i < dims; i++) {
                        string istr = std::to_string(i);
                        string stride_name = varname + ".stride." + istr;
#if 0                   // TODO: Determine if the stride varname is defined - check not yet working
                        // if (!scope.contains(stride_name)) [
                        if (env.find(stride_name) == env.end()) {
                            do_prefetch = false;
                            debug(dbg_prefetch0) << "  " << stride_name << " undefined\n";
                            break;
                        }
#endif
                        stride_var[i] = Variable::make(Int(32), stride_name);
                    }

                    // This box should not be prefetched
                    if (!do_prefetch) {
                        debug(dbg_prefetch0) << "  not prefetching " << varname << "\n";
                        continue;
                    }

                    // Make the names for the prefetch box mins & maxes
                    vector<string> min_name(dims), max_name(dims);
                    for (int i = 0; i < dims; i++) {
                        string istr = std::to_string(i);
                        min_name[i] = varname + ".prefetch_" + pstr + "_min_" + istr;
                        max_name[i] = varname + ".prefetch_" + pstr + "_max_" + istr;
                    }
                    vector<Expr> min_var(dims), max_var(dims);
                    for (int i = 0; i < dims; i++) {
                        min_var[i] = Variable::make(Int(32), min_name[i]);
                        max_var[i] = Variable::make(Int(32), max_name[i]);
                    }

                    // Create a buffer_t object for this prefetch.
                    vector<Expr> args(dims*3 + 2);
                    Expr first_elem = Load::make(t, varname, 0, Buffer(), Parameter());
                    args[0] = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);
                    args[1] = make_zero(t);
                    for (int i = 0; i < dims; i++) {
                        args[3*i+2] = min_var[i];
                        args[3*i+3] = max_var[i] - min_var[i] + 1;
                        args[3*i+4] = stride_var[i];
                    }

                    // Inject the prefetch call
                    vector<Expr> args_prefetch(3);
                    args_prefetch[0] = dims;
                    if (has_static_type) {
                        args_prefetch[1] = t.bytes();
                    } else {
                        // Element size for inputs that don't have static types
                        string elem_size_name = varname + ".elem_size";
                        Expr elem_size_var = Variable::make(Int(32), elem_size_name);
                        args_prefetch[1] = elem_size_var;
                    }
                    args_prefetch[2] = var_prefetch_buf;
                    // TODO: Opt: Keep running sum of bytes prefetched on this sequence
                    // TODO: Opt: Keep running sum of number of prefetch instructions issued
                    // TODO       on this sequence? (to not exceed MAX_PREFETCH)
                    // TODO: Opt: Generate control code for prefetch_buffer_t in Prefetch.cpp
                    // TODO       Passing box info through a buffer_t results in ~30 additional stores/loads
                    Stmt stmt_prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_buffer_t,
                                          args_prefetch, Call::Intrinsic));

                    if (cnt == 0) {     // First prefetch in sequence
                        pstmts = stmt_prefetch;
                    } else {            // Add to existing sequence
                        pstmts = Block::make({stmt_prefetch, pstmts});
                    }
                    cnt++;

                    // Inject the create_buffer_t call
                    Expr prefetch_buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,
                                          args, Call::Intrinsic);
                    pstmts = LetStmt::make(varname_prefetch_buf, prefetch_buf, pstmts);

                    // Inject bounds variable assignments
                    for (int i = dims-1; i >= 0; i--) {
                        pstmts = LetStmt::make(max_name[i], box[i].max, pstmts);
                        pstmts = LetStmt::make(min_name[i], box[i].min, pstmts);
                        // stride already defined by input buffer
                    }
                }

                if (cnt) {
#if 1
                    // Guard to not prefetch past the end of the iteration space
                    // TODO: Opt: Use original extent of loop for guard (avoid conservative guard when stripmined)
                    Expr pcond = likely((Variable::make(Int(32), op->name) + p.offset)
                                                        < (op->min + op->extent - 1));
                    Stmt pguard = IfThenElse::make(pcond, pstmts);
                    body = Block::make({pguard, body});

                    debug(dbg_prefetch3) << "    prefetch: (cnt:" << cnt << ")\n";
                    debug(dbg_prefetch3) << pguard << "\n";
#else
                    body = Block::make({pstmts, body});
#endif
                }

                scope.pop(op->name);
            }
        }

        body = mutate(body);
        stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
    }

};

Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env)
{
    size_t read;
    std::string lvl = get_env_variable("HL_DEBUG_PREFETCH", read);
    if (read) {
        int dbg_level = atoi(lvl.c_str());
        dbg_prefetch0 = MAX(dbg_prefetch0 - dbg_level, 0);
        dbg_prefetch1 = MAX(dbg_prefetch1 - dbg_level, 0);
        dbg_prefetch2 = MAX(dbg_prefetch2 - dbg_level, 0);
        dbg_prefetch3 = MAX(dbg_prefetch3 - dbg_level, 0);
    }
    return InjectPrefetch(env).mutate(s);
}

}
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/Version.h>

#include <stdio.h>

namespace stingray
{

	Version Version::FromString(const std::string& version)
	{
		unsigned major, minor, build;
		const int parsed = sscanf(version.c_str(), "%u.%u.%u", &major, &minor, &build);
		STINGRAYKIT_CHECK(parsed == 3 || parsed == 2, FormatException(version));
		return Version(major, minor, parsed == 3 ? build : optional<unsigned>());
	}

}
<commit_msg>Revert "Version: fix parsing"<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/Version.h>

#include <stingraykit/string/StringParse.h>

namespace stingray
{

	Version Version::FromString(const std::string& version)
	{
		unsigned major, minor;
		optional<unsigned> build;
		STINGRAYKIT_CHECK(StringParse(version, "%1%.%2%.%3%", major, minor, build) || StringParse(version, "%1%.%2%", major, minor), FormatException(version));
		return Version(major, minor, build);
	}

}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#define MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#include <mjolnir/core/ObserverBase.hpp>
#include <mjolnir/core/Unit.hpp>
#include <iostream>
#include <fstream>
#include <iomanip>

namespace mjolnir
{

template<typename traitsT>
class EnergyObserver final : public ObserverBase<traitsT>
{
  public:
    using base_type         = ObserverBase<traitsT>;
    using traits_type       = typename base_type::traits_type;
    using real_type         = typename base_type::real_type;
    using coordinate_type   = typename base_type::coordinate_type;
    using system_type       = typename base_type::system_type;
    using forcefield_type   = typename base_type::forcefield_type;

  public:

    explicit EnergyObserver(const std::string& filename_prefix)
      : prefix_(filename_prefix), file_name_(filename_prefix + ".ene")
    {
        // clear files and throw an error if the files cannot be opened.
        this->clear_file(this->file_name_);
    }
    ~EnergyObserver() override {}

    void initialize(const std::size_t, const real_type,
                    const system_type&, const forcefield_type& ff) override
    {
        using phys_constants = physics::constants<real_type>;
        std::ofstream ofs(this->file_name_, std::ios::app);
        ofs << "# unit of length : " << phys_constants::length_unit()
            << ", unit of energy : " << phys_constants::energy_unit() << '\n';
        ofs << "# timestep  ";

        const auto names = ff.list_energy_name();
        this->widths_.reserve(names.size());
        for(std::size_t i=0; i<names.size(); ++i)
        {
            ofs << names.at(i) << ' ';
            this->widths_.push_back(names.at(i).size());
        }
        ofs << " kinetic_energy\n";
        return;
    }

    // update column names and widths if forcefield changed.
    void update(const std::size_t,  const real_type,
                const system_type&, const forcefield_type& ff) override
    {
        std::ofstream ofs(this->file_name_, std::ios::app);
        ofs << "# timestep  ";
        const auto names = ff.list_energy_name();
        this->widths_.reserve(names.size());
        for(std::size_t i=0; i<names.size(); ++i)
        {
            ofs << names.at(i) << ' ';
            this->widths_.push_back(names.at(i).size());
        }
        ofs << " kinetic_energy\n";
        return;
    }

    void output(const std::size_t step, const real_type,
                const system_type& sys, const forcefield_type& ff) override
    {
        std::ofstream ofs(this->file_name_, std::ios::app);

        // if the width exceeds, operator<<(std::ostream, std::string) ignores
        // ostream::width and outputs whole string.
        ofs << std::setw(11) << std::left << std::to_string(step) << ' ';

        const auto energies = ff.dump_energy(sys);
        for(std::size_t i=0; i<energies.size(); ++i)
        {
            ofs << std::setw(this->widths_.at(i)) << std::fixed
                << std::right << energies.at(i) << ' ';
        }
        ofs << std::setw(14) << std::right << this->calc_kinetic_energy(sys)
            << '\n';

        return;
    }

    void finalize(const std::size_t, const real_type,
                  const system_type&, const forcefield_type&) override
    {/* do nothing. */}

    std::string const& prefix() const noexcept override {return this->prefix_;}

  private:

    void clear_file(const std::string& fname) const
    {
        std::ofstream ofs(fname);
        if(not ofs.good())
        {
            throw_exception<std::runtime_error>(
                "[error] mjolnir::EnergyObserver: file open error: ", fname);
        }
        return;
    }

    real_type calc_kinetic_energy(const system_type& sys) const
    {
        real_type k = 0.0;
        for(std::size_t i=0; i<sys.size(); ++i)
        {
            k += math::length_sq(sys.velocity(i)) * sys.mass(i);
        }
        return k * 0.5;
    }

  private:

    std::string prefix_;
    std::string file_name_;
    std::vector<std::size_t> widths_; // column width to format energy values
};

#ifdef MJOLNIR_SEPARATE_BUILD
extern template class EnergyObserver<SimulatorTraits<double, UnlimitedBoundary>       >;
extern template class EnergyObserver<SimulatorTraits<float,  UnlimitedBoundary>       >;
extern template class EnergyObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class EnergyObserver<SimulatorTraits<float,  CuboidalPeriodicBoundary>>;
#endif

} // mjolnir
#endif//MJOLNIR_CORE_ENERGY_OBSERVER_HPP
<commit_msg>feat: output system attributes to .ene file<commit_after>#ifndef MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#define MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#include <mjolnir/core/ObserverBase.hpp>
#include <mjolnir/core/Unit.hpp>
#include <iostream>
#include <fstream>
#include <iomanip>

namespace mjolnir
{

template<typename traitsT>
class EnergyObserver final : public ObserverBase<traitsT>
{
  public:
    using base_type         = ObserverBase<traitsT>;
    using traits_type       = typename base_type::traits_type;
    using real_type         = typename base_type::real_type;
    using coordinate_type   = typename base_type::coordinate_type;
    using system_type       = typename base_type::system_type;
    using forcefield_type   = typename base_type::forcefield_type;

  public:

    explicit EnergyObserver(const std::string& filename_prefix)
      : prefix_(filename_prefix), file_name_(filename_prefix + ".ene")
    {
        // clear files and throw an error if the files cannot be opened.
        this->clear_file(this->file_name_);
    }
    ~EnergyObserver() override {}

    void initialize(const std::size_t, const real_type,
                    const system_type& sys, const forcefield_type& ff) override
    {
        using phys_constants = physics::constants<real_type>;
        std::ofstream ofs(this->file_name_, std::ios::app);
        ofs << "# unit of length : " << phys_constants::length_unit()
            << ", unit of energy : " << phys_constants::energy_unit() << '\n';
        ofs << "# timestep  ";

        const auto names = ff.list_energy_name();
        this->widths_.reserve(names.size());
        for(std::size_t i=0; i<names.size(); ++i)
        {
            ofs << names.at(i) << ' ';
            this->widths_.push_back(names.at(i).size());
        }
        ofs << " kinetic_energy";
        for(const auto& attr : sys.attributes())
        {
            ofs << " attribute:" << attr.first;
        }
        ofs << '\n';
        return;
    }

    // update column names and widths if forcefield changed.
    void update(const std::size_t,  const real_type,
                const system_type& sys, const forcefield_type& ff) override
    {
        std::ofstream ofs(this->file_name_, std::ios::app);
        ofs << "# timestep  ";
        const auto names = ff.list_energy_name();
        this->widths_.reserve(names.size());
        for(std::size_t i=0; i<names.size(); ++i)
        {
            ofs << names.at(i) << ' ';
            this->widths_.push_back(names.at(i).size());
        }
        ofs << " kinetic_energy";
        for(const auto& attr : sys.attributes())
        {
            ofs << " attribute:" << attr.first;
        }
        ofs << '\n';
        return;
    }

    void output(const std::size_t step, const real_type,
                const system_type& sys, const forcefield_type& ff) override
    {
        std::ofstream ofs(this->file_name_, std::ios::app);

        // if the width exceeds, operator<<(std::ostream, std::string) ignores
        // ostream::width and outputs whole string.
        ofs << std::setw(11) << std::left << std::to_string(step) << ' ';

        const auto energies = ff.dump_energy(sys);
        for(std::size_t i=0; i<energies.size(); ++i)
        {
            ofs << std::setw(this->widths_.at(i)) << std::fixed
                << std::right << energies.at(i) << ' ';
        }
        ofs << std::setw(14) << std::right << this->calc_kinetic_energy(sys);
        for(const auto& attr : sys.attributes())
        {
            ofs << ' ' << std::setw(10 + attr.first.size()) << std::right
                << attr.second;
        }
        ofs << '\n';
        return;
    }

    void finalize(const std::size_t, const real_type,
                  const system_type&, const forcefield_type&) override
    {/* do nothing. */}

    std::string const& prefix() const noexcept override {return this->prefix_;}

  private:

    void clear_file(const std::string& fname) const
    {
        std::ofstream ofs(fname);
        if(not ofs.good())
        {
            throw_exception<std::runtime_error>(
                "[error] mjolnir::EnergyObserver: file open error: ", fname);
        }
        return;
    }

    real_type calc_kinetic_energy(const system_type& sys) const
    {
        real_type k = 0.0;
        for(std::size_t i=0; i<sys.size(); ++i)
        {
            k += math::length_sq(sys.velocity(i)) * sys.mass(i);
        }
        return k * 0.5;
    }

  private:

    std::string prefix_;
    std::string file_name_;
    std::vector<std::size_t> widths_; // column width to format energy values
};

#ifdef MJOLNIR_SEPARATE_BUILD
extern template class EnergyObserver<SimulatorTraits<double, UnlimitedBoundary>       >;
extern template class EnergyObserver<SimulatorTraits<float,  UnlimitedBoundary>       >;
extern template class EnergyObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class EnergyObserver<SimulatorTraits<float,  CuboidalPeriodicBoundary>>;
#endif

} // mjolnir
#endif//MJOLNIR_CORE_ENERGY_OBSERVER_HPP
<|endoftext|>


<commit_before>#include <QString>

#include <coreplugin/icore.h>

#include "Settings.h"
#include "Constants.h"

using namespace QtcCppcheck::Constants;
using namespace QtcCppcheck::Internal;

Settings::Settings(bool autoLoad) :
  checkOnBuild_ (false), checkOnSave_ (false),
  checkOnProjectChange_ (false), checkOnFileAdd_ (false),
  checkUnused_ (false), checkInconclusive_ (false),
  showBinaryOutput_ (false),
  showId_ (false),
  popupOnError_ (false), popupOnWarning_ (false)
{
  if (autoLoad)
  {
    load ();
  }
}

void Settings::save()
{
  Q_ASSERT (Core::ICore::settings () != NULL);
  QSettings& settings = *(Core::ICore::settings ());
  settings.beginGroup (QLatin1String (SETTINGS_GROUP));
  settings.setValue (QLatin1String (SETTINGS_BINARY_FILE), binaryFile_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_BUILD), checkOnBuild_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_SAVE), checkOnSave_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE), checkOnProjectChange_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD), checkOnFileAdd_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_UNUSED), checkUnused_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE), checkInconclusive_);
  settings.setValue (QLatin1String (SETTINGS_CUSTOM_PARAMS), customParameters_);
  settings.setValue (QLatin1String (SETTINGS_IGNORE_PATTERNS), ignorePatterns_.join (","));
  settings.setValue (QLatin1String (SETTINGS_SHOW_OUTPUT), showBinaryOutput_);
  settings.setValue (QLatin1String (SETTINGS_SHOW_ID), showId_);
  settings.setValue (QLatin1String (SETTINGS_POPUP_ON_ERROR), popupOnError_);
  settings.setValue (QLatin1String (SETTINGS_POPUP_ON_WARNING), popupOnWarning_);
  settings.endGroup ();
}

void Settings::load()
{
  Q_ASSERT (Core::ICore::settings () != NULL);
  QSettings& settings = *(Core::ICore::settings ());
  settings.beginGroup (QLatin1String (SETTINGS_GROUP));
  binaryFile_ = settings.value (QLatin1String (SETTINGS_BINARY_FILE),
                                QString ()).toString ();
  checkOnBuild_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_BUILD),
                                  false).toBool ();
  checkOnSave_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_SAVE),
                                 false).toBool ();
  checkOnProjectChange_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE),
                                          false).toBool ();
  checkOnFileAdd_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD),
                                    false).toBool ();
  checkUnused_ = settings.value (QLatin1String (SETTINGS_CHECK_UNUSED),
                                 false).toBool ();
  checkInconclusive_ = settings.value (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE),
                                       false).toBool ();
  customParameters_ = settings.value (QLatin1String (SETTINGS_CUSTOM_PARAMS),
                                      QString ()).toString ();
  ignorePatterns_ = settings.value (QLatin1String (SETTINGS_IGNORE_PATTERNS),
                                    QString ()).toString ().split (",", QString::SkipEmptyParts);
  showBinaryOutput_ = settings.value (QLatin1String (SETTINGS_SHOW_OUTPUT),
                                      false).toBool ();
  showId_ = settings.value (QLatin1String (SETTINGS_SHOW_ID),
                                      false).toBool ();
  popupOnError_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_ERROR),
                                      true).toBool ();
  popupOnWarning_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_WARNING),
                                      true).toBool ();
  settings.endGroup ();
}

QString Settings::binaryFile() const
{
  return binaryFile_;
}

void Settings::setBinaryFile(const QString &binaryFile)
{
  binaryFile_ = binaryFile;
}

bool Settings::checkOnBuild() const
{
  return checkOnBuild_;
}

void Settings::setCheckOnBuild(bool checkOnBuild)
{
  checkOnBuild_ = checkOnBuild;
}

bool Settings::checkInconclusive() const
{
  return checkInconclusive_;
}

void Settings::setCheckInconclusive(bool checkInconclusive)
{
  checkInconclusive_ = checkInconclusive;
}

QString Settings::customParameters() const
{
  return customParameters_;
}

void Settings::setCustomParameters(const QString &customParameters)
{
  customParameters_ = customParameters;
}

bool Settings::showBinaryOutput() const
{
  return showBinaryOutput_;
}

void Settings::setShowBinaryOutput(bool showBinaryOutput)
{
  showBinaryOutput_ = showBinaryOutput;
}

bool Settings::showId() const
{
  return showId_;
}

void Settings::setShowId(bool showId)
{
  showId_ = showId;
}

bool Settings::popupOnError() const
{
  return popupOnError_;
}

void Settings::setPopupOnError(bool popupOnError)
{
  popupOnError_ = popupOnError;
}
bool Settings::popupOnWarning() const
{
  return popupOnWarning_;
}

void Settings::setPopupOnWarning(bool popupOnWarning)
{
  popupOnWarning_ = popupOnWarning;
}

QStringList Settings::ignorePatterns() const
{
  return ignorePatterns_;
}

void Settings::setIgnorePatterns(const QStringList &ignorePatterns)
{
  ignorePatterns_ = ignorePatterns;
  for (auto& i: ignorePatterns_)
  {
    i = i.trimmed () ;
  }
}

bool Settings::checkOnProjectChange() const
{
  return checkOnProjectChange_;
}

void Settings::setCheckOnProjectChange(bool checkOnProjectChange)
{
  checkOnProjectChange_ = checkOnProjectChange;
}

bool Settings::checkOnFileAdd() const
{
  return checkOnFileAdd_;
}

void Settings::setCheckOnFileAdd(bool checkOnFileAdd)
{
  checkOnFileAdd_ = checkOnFileAdd;
}

bool Settings::checkUnused() const
{
  return checkUnused_;
}

void Settings::setCheckUnused(bool checkUnused)
{
  checkUnused_ = checkUnused;
}

bool Settings::checkOnSave() const
{
  return checkOnSave_;
}

void Settings::setCheckOnSave(bool checkOnSave)
{
  checkOnSave_ = checkOnSave;
}

<commit_msg>Auto-detect cppcheck in default installation paths<commit_after>#include <QString>

#include <utils/hostosinfo.h>
#include <utils/fileutils.h>

#include <coreplugin/icore.h>

#include "Settings.h"
#include "Constants.h"

using namespace QtcCppcheck::Constants;
using namespace QtcCppcheck::Internal;

Settings::Settings(bool autoLoad) :
  checkOnBuild_ (false), checkOnSave_ (false),
  checkOnProjectChange_ (false), checkOnFileAdd_ (false),
  checkUnused_ (false), checkInconclusive_ (false),
  showBinaryOutput_ (false),
  showId_ (false),
  popupOnError_ (false), popupOnWarning_ (false)
{
  if (autoLoad)
  {
    load ();
  }
}

void Settings::save()
{
  Q_ASSERT (Core::ICore::settings () != NULL);
  QSettings& settings = *(Core::ICore::settings ());
  settings.beginGroup (QLatin1String (SETTINGS_GROUP));
  settings.setValue (QLatin1String (SETTINGS_BINARY_FILE), binaryFile_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_BUILD), checkOnBuild_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_SAVE), checkOnSave_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE), checkOnProjectChange_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD), checkOnFileAdd_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_UNUSED), checkUnused_);
  settings.setValue (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE), checkInconclusive_);
  settings.setValue (QLatin1String (SETTINGS_CUSTOM_PARAMS), customParameters_);
  settings.setValue (QLatin1String (SETTINGS_IGNORE_PATTERNS), ignorePatterns_.join (","));
  settings.setValue (QLatin1String (SETTINGS_SHOW_OUTPUT), showBinaryOutput_);
  settings.setValue (QLatin1String (SETTINGS_SHOW_ID), showId_);
  settings.setValue (QLatin1String (SETTINGS_POPUP_ON_ERROR), popupOnError_);
  settings.setValue (QLatin1String (SETTINGS_POPUP_ON_WARNING), popupOnWarning_);
  settings.endGroup ();
}

static QString defaultBinary()
{
  QString res;
  if (Utils::HostOsInfo::isWindowsHost())
  {
    res = Utils::FileName::fromUserInput(QLatin1String(qgetenv("ProgramFiles")))
        .appendPath("Cppcheck/cppcheck.exe").toString();
  }
  else
  {
    res = "/usr/bin/cppcheck";
  }
  return QFile::exists(res) ? res : QString();
}

void Settings::load()
{
  Q_ASSERT (Core::ICore::settings () != NULL);
  QSettings& settings = *(Core::ICore::settings ());
  settings.beginGroup (QLatin1String (SETTINGS_GROUP));
  binaryFile_ = settings.value (QLatin1String (SETTINGS_BINARY_FILE),
                                QString ()).toString ();
  checkOnBuild_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_BUILD),
                                  false).toBool ();
  checkOnSave_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_SAVE),
                                 false).toBool ();
  checkOnProjectChange_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_PROJECT_CHANGE),
                                          false).toBool ();
  checkOnFileAdd_ = settings.value (QLatin1String (SETTINGS_CHECK_ON_FILE_ADD),
                                    false).toBool ();
  checkUnused_ = settings.value (QLatin1String (SETTINGS_CHECK_UNUSED),
                                 false).toBool ();
  checkInconclusive_ = settings.value (QLatin1String (SETTINGS_CHECK_INCONCLUSIVE),
                                       false).toBool ();
  customParameters_ = settings.value (QLatin1String (SETTINGS_CUSTOM_PARAMS),
                                      QString ()).toString ();
  ignorePatterns_ = settings.value (QLatin1String (SETTINGS_IGNORE_PATTERNS),
                                    QString ()).toString ().split (",", QString::SkipEmptyParts);
  showBinaryOutput_ = settings.value (QLatin1String (SETTINGS_SHOW_OUTPUT),
                                      false).toBool ();
  showId_ = settings.value (QLatin1String (SETTINGS_SHOW_ID),
                                      false).toBool ();
  popupOnError_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_ERROR),
                                      true).toBool ();
  popupOnWarning_ = settings.value (QLatin1String (SETTINGS_POPUP_ON_WARNING),
                                      true).toBool ();
  settings.endGroup ();
  if (binaryFile_.isEmpty())
    binaryFile_ = defaultBinary();
}

QString Settings::binaryFile() const
{
  return binaryFile_;
}

void Settings::setBinaryFile(const QString &binaryFile)
{
  binaryFile_ = binaryFile;
}

bool Settings::checkOnBuild() const
{
  return checkOnBuild_;
}

void Settings::setCheckOnBuild(bool checkOnBuild)
{
  checkOnBuild_ = checkOnBuild;
}

bool Settings::checkInconclusive() const
{
  return checkInconclusive_;
}

void Settings::setCheckInconclusive(bool checkInconclusive)
{
  checkInconclusive_ = checkInconclusive;
}

QString Settings::customParameters() const
{
  return customParameters_;
}

void Settings::setCustomParameters(const QString &customParameters)
{
  customParameters_ = customParameters;
}

bool Settings::showBinaryOutput() const
{
  return showBinaryOutput_;
}

void Settings::setShowBinaryOutput(bool showBinaryOutput)
{
  showBinaryOutput_ = showBinaryOutput;
}

bool Settings::showId() const
{
  return showId_;
}

void Settings::setShowId(bool showId)
{
  showId_ = showId;
}

bool Settings::popupOnError() const
{
  return popupOnError_;
}

void Settings::setPopupOnError(bool popupOnError)
{
  popupOnError_ = popupOnError;
}
bool Settings::popupOnWarning() const
{
  return popupOnWarning_;
}

void Settings::setPopupOnWarning(bool popupOnWarning)
{
  popupOnWarning_ = popupOnWarning;
}

QStringList Settings::ignorePatterns() const
{
  return ignorePatterns_;
}

void Settings::setIgnorePatterns(const QStringList &ignorePatterns)
{
  ignorePatterns_ = ignorePatterns;
  for (auto& i: ignorePatterns_)
  {
    i = i.trimmed () ;
  }
}

bool Settings::checkOnProjectChange() const
{
  return checkOnProjectChange_;
}

void Settings::setCheckOnProjectChange(bool checkOnProjectChange)
{
  checkOnProjectChange_ = checkOnProjectChange;
}

bool Settings::checkOnFileAdd() const
{
  return checkOnFileAdd_;
}

void Settings::setCheckOnFileAdd(bool checkOnFileAdd)
{
  checkOnFileAdd_ = checkOnFileAdd;
}

bool Settings::checkUnused() const
{
  return checkUnused_;
}

void Settings::setCheckUnused(bool checkUnused)
{
  checkUnused_ = checkUnused;
}

bool Settings::checkOnSave() const
{
  return checkOnSave_;
}

void Settings::setCheckOnSave(bool checkOnSave)
{
  checkOnSave_ = checkOnSave;
}

<|endoftext|>


<commit_before>//
// This file contains the class InputDialog.
// An InputDialog object prompts for an input string using a simple
// dialog box. The InputDialog class is also a good example of how
// to use the ROOT GUI classes via the interpreter. Since interpreted
// classes can not call virtual functions via base class pointers, all
// GUI objects are used by composition instead of by inheritance.
//
// This file contains also some utility functions that use
// the InputDialog class to either get a string, integer or
// floating point number. There are also two functions showing
// how to use the file open and save dialogs. The utility functions are:
//
// const char *OpenFileDialog()
// const char *SaveFileDialog()
// const char *GetStringDialog(const char *prompt, const char *defval)
// Int_t GetIntegerDialog(const char *prompt, Int_t defval)
// Float_t GetFloatDialog(const char *prompt, Float_t defval)
//
// To use the InputDialog class and the utility functions you just
// have to load the Dialogs.C file as follows:
// .L Dialogs.C
//
// Now you can use them like:
// {
//    const char *file = OpenFileDialog();
//    Int_t run   = GetIntegerDialog("Give run number:", 0);
//    Int_t event = GetIntegerDialog("Give event number:", 0);
//    printf("analyse run %d, event %d from file %s\n", run ,event, file);
// }
//

///////////////////////////////////////////////////////////////////////////
//                                                                       //
// Input Dialog Widget                                                   //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

class InputDialog {

private:
   TGTransientFrame *fDialog;  // transient frame, main dialog window
   TGTextEntry      *fTE;      // text entry widget containing
   TList            *fWidgets; // keep track of widgets to be deleted in dtor
   char             *fRetStr;  // address to store return string

public:
   InputDialog(const char *prompt, const char *defval, char *retstr);
   ~InputDialog();
   void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
};

InputDialog::~InputDialog()
{
   // Cleanup dialog.

   fWidgets->Delete();
   delete fWidgets;

   delete fTE;
   delete fDialog;
}

InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr)
{
   // Create simple input dialog.

   fWidgets = new TList;

   TGWindow *main = gClient->GetRoot();
   fDialog = new TGTransientFrame(main, main, 10, 10);

   // command to be executed by buttons and text entry widget
   char cmd[128];
   sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this);

   // create prompt label and textentry widget
   TGLabel *label = new TGLabel(fDialog, prompt);
   fWidgets->Add(label);

   TGTextBuffer *tbuf = new TGTextBuffer(256);  //will be deleted by TGtextEntry
   tbuf->AddText(0, defval);

   fTE = new TGTextEntry(fDialog, tbuf);
   fTE->Resize(260, fTE->GetDefaultHeight());
   fTE->SetCommand(cmd);

   TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0);
   TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5);
   fWidgets->Add(l1);
   fWidgets->Add(l2);

   fDialog->AddFrame(label, l1);
   fDialog->AddFrame(fTE, l2);

   // create frame and layout hints for Ok and Cancel buttons
   TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth);
   TGLayoutHints     *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0);

   // put hf as last in list to be deleted
   fWidgets->Add(l3);

   // create OK and Cancel buttons in their own frame (hf)
   UInt_t  nb = 0, width = 0, height = 0;
   TGTextButton *b;

   b = new TGTextButton(hf, "&Ok", cmd, 1);
   fWidgets->Add(b);
   b->Associate(fDialog);
   hf->AddFrame(b, l3);
   height = b->GetDefaultHeight();
   width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;

   b = new TGTextButton(hf, "&Cancel", cmd, 2);
   fWidgets->Add(b);
   b->Associate(fDialog);
   hf->AddFrame(b, l3);
   height = b->GetDefaultHeight();
   width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;

   // place button frame (hf) at the bottom
   TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5);
   fWidgets->Add(l4);
   fWidgets->Add(hf);

   fDialog->AddFrame(hf, l4);

   // keep buttons centered and with the same width
   hf->Resize((width + 20) * nb, height);

   // set dialog title
   fDialog->SetWindowName("Get Input");

   // map all widgets and calculate size of dialog
   fDialog->MapSubwindows();

   width  = fDialog->GetDefaultWidth();
   height = fDialog->GetDefaultHeight();

   fDialog->Resize(width, height);

   // position relative to the parent window (which is the root window)
   Window_t wdum;
   int      ax, ay;

   gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(),
                          (((TGFrame *) main)->GetWidth() - width) >> 1,
                          (((TGFrame *) main)->GetHeight() - height) >> 1,
                          ax, ay, wdum);
   fDialog->Move(ax, ay);
   fDialog->SetWMPosition(ax, ay);

   // make the message box non-resizable
   fDialog->SetWMSize(width, height);
   fDialog->SetWMSizeHints(width, height, width, height, 0, 0);

   fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |
                                       kMWMDecorMinimize | kMWMDecorMenu,
                        kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |
                                       kMWMFuncMinimize,
                        kMWMInputModeless);

   // popup dialog and wait till user replies
   fDialog->MapWindow();

   fRetStr = retstr;

   gClient->WaitFor(fDialog);
}

void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
   // Handle button and text enter events

   switch (GET_MSG(msg)) {
      case kC_COMMAND:
         switch (GET_SUBMSG(msg)) {
             case kCM_BUTTON:
                switch (parm1) {
                   case 1:
                      // here copy the string from text buffer to return variable
                      strcpy(fRetStr, fTE->GetBuffer()->GetString());
                      delete this;
                      break;

                   case 2:
                      fRetStr[0] = 0;
                      delete this;
                      break;
                 }
              default:
                 break;
          }
          break;

       case kC_TEXTENTRY:
         switch (GET_SUBMSG(msg)) {
             case kTE_ENTER:
                // here copy the string from text buffer to return variable
                strcpy(fRetStr, fTE->GetBuffer()->GetString());
                delete this;
                break;
             default:
                break;
          }
          break;

       default:
          break;
   }
}

//--- Utility Functions --------------------------------------------------------

const char *OpenFileDialog()
{
   // Prompt for file to be opened. Depending on navigation in
   // dialog the current working directory can be changed.
   // The returned file name is always with respect to the
   // current directory.

   const char *gOpenAsTypes[] = {
      "Macro files",  "*.C",
      "ROOT files",   "*.root",
      "PostScript",   "*.ps",
      "Encapsulated PostScript", "*.eps",
      "Gif files",    "*.gif",
      "All files",    "*",
       0,              0
   };

   static TGFileInfo fi;
   fi.fFileTypes = gOpenAsTypes;
   new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi);

   return fi.fFilename;
}

const char *SaveFileDialog()
{
   // Prompt for file to be saved. Depending on navigation in
   // dialog the current working directory can be changed.
   // The returned file name is always with respect to the
   // current directory.

   const char *gSaveAsTypes[] = {
      "Macro files",  "*.C",
      "ROOT files",   "*.root",
      "PostScript",   "*.ps",
      "Encapsulated PostScript", "*.eps",
      "Gif files",    "*.gif",
      "All files",    "*",
       0,              0
   };

   static TGFileInfo fi;
   fi.fFileTypes = gSaveAsTypes;
   new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi);

   return fi.fFilename;
}

const char *GetStringDialog(const char *prompt, const char *defval)
{
   // Prompt for string. The typed in string is returned.

   static char answer[128];

   new InputDialog(prompt, defval, answer);

   return answer;
}

Int_t GetIntegerDialog(const char *prompt, Int_t defval)
{
   // Prompt for integer. The typed in integer is returned.

   static char answer[32];

   char defv[32];
   sprintf(defv, "%d", defval);

   new InputDialog(prompt, defv, answer);

   return atoi(answer);
}

Float_t GetFloatDialog(const char *prompt, Float_t defval)
{
   // Prompt for float. The typed in float is returned.

   static char answer[32];

   char defv[32];
   sprintf(defv, "%f", defval);

   new InputDialog(prompt, defv, answer);

   return atof(answer);
}
<commit_msg>Fix Jira #ROOT-8404 macro Dialogs.C does not compile and crashes<commit_after>//
// This file contains the class InputDialog.
// An InputDialog object prompts for an input string using a simple
// dialog box. The InputDialog class is also a good example of how
// to use the ROOT GUI classes via the interpreter. Since interpreted
// classes can not call virtual functions via base class pointers, all
// GUI objects are used by composition instead of by inheritance.
//
// This file contains also some utility functions that use
// the InputDialog class to either get a string, integer or
// floating point number. There are also two functions showing
// how to use the file open and save dialogs. The utility functions are:
//
// const char *OpenFileDialog()
// const char *SaveFileDialog()
// const char *GetStringDialog(const char *prompt, const char *defval)
// Int_t GetIntegerDialog(const char *prompt, Int_t defval)
// Float_t GetFloatDialog(const char *prompt, Float_t defval)
//
// To use the InputDialog class and the utility functions you just
// have to load the Dialogs.C file as follows:
// .L Dialogs.C
//
// Now you can use them like:
// {
//    const char *file = OpenFileDialog();
//    Int_t run   = GetIntegerDialog("Give run number:", 0);
//    Int_t event = GetIntegerDialog("Give event number:", 0);
//    printf("analyse run %d, event %d from file %s\n", run ,event, file);
// }
//

#include "TList.h"
#include "TGLabel.h"
#include "TGButton.h"
#include "TGText.h"
#include "TGFileDialog.h"
#include "TGTextEntry.h"

///////////////////////////////////////////////////////////////////////////
//                                                                       //
// Input Dialog Widget                                                   //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

class InputDialog {

private:
   TGTransientFrame *fDialog;  // transient frame, main dialog window
   TGTextEntry      *fTE;      // text entry widget containing
   char             *fRetStr;  // address to store return string

public:
   InputDialog(const char *prompt, const char *defval, char *retstr);
   ~InputDialog();
   void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
};

InputDialog::~InputDialog()
{
   // Cleanup dialog.

   fDialog->DeleteWindow();  // cleanup and delete fDialog
}

InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr)
{
   // Create simple input dialog.

   const TGWindow *main = gClient->GetRoot();
   fDialog = new TGTransientFrame(main, main, 10, 10);
   fDialog->SetCleanup(kDeepCleanup);

   // command to be executed by buttons and text entry widget
   char cmd[128];
   sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this);

   // create prompt label and textentry widget
   TGLabel *label = new TGLabel(fDialog, prompt);

   TGTextBuffer *tbuf = new TGTextBuffer(256);  //will be deleted by TGtextEntry
   tbuf->AddText(0, defval);

   fTE = new TGTextEntry(fDialog, tbuf);
   fTE->Resize(260, fTE->GetDefaultHeight());
   fTE->SetCommand(cmd);

   TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0);
   TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5);

   fDialog->AddFrame(label, l1);
   fDialog->AddFrame(fTE, l2);

   // create frame and layout hints for Ok and Cancel buttons
   TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth);
   TGLayoutHints     *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0);

   // create OK and Cancel buttons in their own frame (hf)
   UInt_t  nb = 0, width = 0, height = 0;
   TGTextButton *b;

   b = new TGTextButton(hf, "&Ok", cmd, 1);
   b->Associate(fDialog);
   hf->AddFrame(b, l3);
   height = b->GetDefaultHeight();
   width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;

   b = new TGTextButton(hf, "&Cancel", cmd, 2);
   b->Associate(fDialog);
   hf->AddFrame(b, l3);
   height = b->GetDefaultHeight();
   width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;

   // place button frame (hf) at the bottom
   TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5);

   fDialog->AddFrame(hf, l4);

   // keep buttons centered and with the same width
   hf->Resize((width + 20) * nb, height);

   // set dialog title
   fDialog->SetWindowName("Get Input");

   // map all widgets and calculate size of dialog
   fDialog->MapSubwindows();

   width  = fDialog->GetDefaultWidth();
   height = fDialog->GetDefaultHeight();

   fDialog->Resize(width, height);

   // position relative to the parent window (which is the root window)
   Window_t wdum;
   int      ax, ay;

   gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(),
                          (((TGFrame *) main)->GetWidth() - width) >> 1,
                          (((TGFrame *) main)->GetHeight() - height) >> 1,
                          ax, ay, wdum);
   fDialog->Move(ax, ay);
   fDialog->SetWMPosition(ax, ay);

   // make the message box non-resizable
   fDialog->SetWMSize(width, height);
   fDialog->SetWMSizeHints(width, height, width, height, 0, 0);

   fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |
                                       kMWMDecorMinimize | kMWMDecorMenu,
                        kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |
                                       kMWMFuncMinimize,
                        kMWMInputModeless);

   // popup dialog and wait till user replies
   fDialog->MapWindow();

   fRetStr = retstr;

   gClient->WaitFor(fDialog);
}

void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
   // Handle button and text enter events

   switch (GET_MSG(msg)) {
      case kC_COMMAND:
         switch (GET_SUBMSG(msg)) {
             case kCM_BUTTON:
                switch (parm1) {
                   case 1:
                      // here copy the string from text buffer to return variable
                      strcpy(fRetStr, fTE->GetBuffer()->GetString());
                      delete this;
                      break;

                   case 2:
                      fRetStr[0] = 0;
                      delete this;
                      break;
                 }
              default:
                 break;
          }
          break;

       case kC_TEXTENTRY:
         switch (GET_SUBMSG(msg)) {
             case kTE_ENTER:
                // here copy the string from text buffer to return variable
                strcpy(fRetStr, fTE->GetBuffer()->GetString());
                delete this;
                break;
             default:
                break;
          }
          break;

       default:
          break;
   }
}

//--- Utility Functions --------------------------------------------------------

const char *OpenFileDialog()
{
   // Prompt for file to be opened. Depending on navigation in
   // dialog the current working directory can be changed.
   // The returned file name is always with respect to the
   // current directory.

   const char *gOpenAsTypes[] = {
      "Macro files",  "*.C",
      "ROOT files",   "*.root",
      "PostScript",   "*.ps",
      "Encapsulated PostScript", "*.eps",
      "Gif files",    "*.gif",
      "All files",    "*",
       0,              0
   };

   static TGFileInfo fi;
   fi.fFileTypes = gOpenAsTypes;
   new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi);

   return fi.fFilename;
}

const char *SaveFileDialog()
{
   // Prompt for file to be saved. Depending on navigation in
   // dialog the current working directory can be changed.
   // The returned file name is always with respect to the
   // current directory.

   const char *gSaveAsTypes[] = {
      "Macro files",  "*.C",
      "ROOT files",   "*.root",
      "PostScript",   "*.ps",
      "Encapsulated PostScript", "*.eps",
      "Gif files",    "*.gif",
      "All files",    "*",
       0,              0
   };

   static TGFileInfo fi;
   fi.fFileTypes = gSaveAsTypes;
   new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi);

   return fi.fFilename;
}

const char *GetStringDialog(const char *prompt, const char *defval)
{
   // Prompt for string. The typed in string is returned.

   static char answer[128];

   new InputDialog(prompt, defval, answer);

   return answer;
}

Int_t GetIntegerDialog(const char *prompt, Int_t defval)
{
   // Prompt for integer. The typed in integer is returned.

   static char answer[32];

   char defv[32];
   sprintf(defv, "%d", defval);

   new InputDialog(prompt, defv, answer);

   return atoi(answer);
}

Float_t GetFloatDialog(const char *prompt, Float_t defval)
{
   // Prompt for float. The typed in float is returned.

   static char answer[32];

   char defv[32];
   sprintf(defv, "%f", defval);

   new InputDialog(prompt, defv, answer);

   return atof(answer);
}
<|endoftext|>


<commit_before>/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#include <map>
#include <string>
#include <utility>

#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/map.hpp>

#include "support/conf/options.hh"
#include "support/conf/pn_format.hh"
#include "support/util/paths.hh"

namespace pnmc { namespace conf {

namespace po = boost::program_options;

/*------------------------------------------------------------------------------------------------*/

static const auto pn_input_str   = "input";
static const auto format_map = std::map<std::string, pn_format>
  { std::make_pair("ndr" , pn_format::ndr)
  , std::make_pair("net" , pn_format::net)
  , std::make_pair("nupn", pn_format::nupn)
  , std::make_pair("pnml", pn_format::pnml)
  };

static const auto possible_format_values = []
{
  using namespace boost::adaptors;
  return "Petri net format [" + boost::algorithm::join(format_map | map_keys, "|") + "]";
}();

/*------------------------------------------------------------------------------------------------*/

po::options_description
pn_input_options()
{
  po::options_description options{"Petri net file format options"};
  options.add_options()
    (pn_input_str, po::value<std::string>()->default_value("net"), possible_format_values.c_str());
  return options;
}

/*------------------------------------------------------------------------------------------------*/

static
pn_format
pn_format_from_options(const po::variables_map& vm)
{
  const auto s = vm[pn_input_str].as<std::string>();
  const auto search = format_map.find(s);
  if (search != end(format_map))
  {
    return search->second;
  }
  else
  {
    throw po::error("Invalid input format " + s);
  }
}

/*------------------------------------------------------------------------------------------------*/

parsers::pn_configuration
configure_pn_parser(const boost::program_options::variables_map& vm)
{
  parsers::pn_configuration conf;
  if (vm["input-file"].as<std::string>() != "-")
  {
    conf.file = util::in_file(vm["input-file"].as<std::string>());
  }
  conf.file_type = pn_format_from_options(vm);
  return conf;
}

/*------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------*/

static const auto properties_input_str = "properties-file";

po::options_description
properties_input_options()
{
  po::options_description options{"Properties file format options"};
  options.add_options()
    (properties_input_str, po::value<std::string>(), "Path to properties file");
  return options;
}

/*------------------------------------------------------------------------------------------------*/

parsers::properties_configuration
configure_properties_parser(const boost::program_options::variables_map& vm)
{
  parsers::properties_configuration conf;
  if (vm.count(properties_input_str))
  {
    conf.file = util::in_file(vm[properties_input_str].as<std::string>());
  }
  return conf;
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace pnmc::conf
<commit_msg>Change --input to --format<commit_after>/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#include <map>
#include <string>
#include <utility>

#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/map.hpp>

#include "support/conf/options.hh"
#include "support/conf/pn_format.hh"
#include "support/util/paths.hh"

namespace pnmc { namespace conf {

namespace po = boost::program_options;

/*------------------------------------------------------------------------------------------------*/

static const auto pn_format_str   = "format";
static const auto format_map = std::map<std::string, pn_format>
  { std::make_pair("ndr" , pn_format::ndr)
  , std::make_pair("net" , pn_format::net)
  , std::make_pair("nupn", pn_format::nupn)
  , std::make_pair("pnml", pn_format::pnml)
  };

static const auto possible_format_values = []
{
  using namespace boost::adaptors;
  return "Petri net format [" + boost::algorithm::join(format_map | map_keys, "|") + "]";
}();

/*------------------------------------------------------------------------------------------------*/

po::options_description
pn_input_options()
{
  po::options_description options{"Petri net file format options"};
  options.add_options()
    (pn_format_str, po::value<std::string>()->default_value("net"), possible_format_values.c_str());
  return options;
}

/*------------------------------------------------------------------------------------------------*/

static
pn_format
pn_format_from_options(const po::variables_map& vm)
{
  const auto s = vm[pn_format_str].as<std::string>();
  const auto search = format_map.find(s);
  if (search != end(format_map))
  {
    return search->second;
  }
  else
  {
    throw po::error("Invalid input format " + s);
  }
}

/*------------------------------------------------------------------------------------------------*/

parsers::pn_configuration
configure_pn_parser(const boost::program_options::variables_map& vm)
{
  parsers::pn_configuration conf;
  if (vm["input-file"].as<std::string>() != "-")
  {
    conf.file = util::in_file(vm["input-file"].as<std::string>());
  }
  conf.file_type = pn_format_from_options(vm);
  return conf;
}

/*------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------*/

static const auto properties_input_str = "properties-file";

po::options_description
properties_input_options()
{
  po::options_description options{"Properties file format options"};
  options.add_options()
    (properties_input_str, po::value<std::string>(), "Path to properties file");
  return options;
}

/*------------------------------------------------------------------------------------------------*/

parsers::properties_configuration
configure_properties_parser(const boost::program_options::variables_map& vm)
{
  parsers::properties_configuration conf;
  if (vm.count(properties_input_str))
  {
    conf.file = util::in_file(vm[properties_input_str].as<std::string>());
  }
  return conf;
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace pnmc::conf
<|endoftext|>


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

// include ---------------------------------------------------------------

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_METRIC_HXX
#include <vcl/metric.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif

#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#include <map>

#ifndef _SHL_HXX
#include <tools/shl.hxx> //add CHINA001
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx> //add CHINA001
#endif
#ifndef _SV_SOUND_HXX
#include <vcl/sound.hxx> //add CHINA001
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx> //add CHINA001
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx> //add CHINA001
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx> //add CHINA001
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx> //add CHINA001
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx> //add CHINA001
#endif
#ifndef _SV_METRIC_HXX
#include <vcl/metric.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class SubsetMap;
class SvxCharMapData;

// define ----------------------------------------------------------------

#ifdef MAC
#define CHARMAP_MAXLEN  28
#define COLUMN_COUNT    28
#define ROW_COUNT        8
#else
#define CHARMAP_MAXLEN  32
#define COLUMN_COUNT    16
#define ROW_COUNT        8
#endif

namespace svx
{
    struct SvxShowCharSetItem;
    class SvxShowCharSetVirtualAcc;
}

// class SvxShowCharSet --------------------------------------------------

class SVX_DLLPUBLIC SvxShowCharSet : public Control
{
public:
                    SvxShowCharSet( Window* pParent, const ResId& rResId );
                    ~SvxShowCharSet();

    void            SetFont( const Font& rFont );

    void            SelectCharacter( sal_uInt32 cNew, BOOL bFocus = FALSE );
    sal_UCS4        GetSelectCharacter() const;

    Link            GetDoubleClickHdl() const { return aDoubleClkHdl; }
    void            SetDoubleClickHdl( const Link& rLink ) { aDoubleClkHdl = rLink; }
    Link            GetSelectHdl() const { return aSelectHdl; }
    void            SetSelectHdl( const Link& rHdl ) { aSelectHdl = rHdl; }
    Link            GetHighlightHdl() const { return aHighHdl; }
    void            SetHighlightHdl( const Link& rHdl ) { aHighHdl = rHdl; }
    Link            GetPreSelectHdl() const { return aHighHdl; }
    void            SetPreSelectHdl( const Link& rHdl ) { aPreSelectHdl = rHdl; }

#ifdef _SVX_CHARMAP_CXX_
    ::svx::SvxShowCharSetItem*  ImplGetItem( int _nPos );
    int                         FirstInView( void) const;
    int                         LastInView( void) const;
    int                         PixelToMapIndex( const Point&) const;
    void                        SelectIndex( int index, BOOL bFocus = FALSE );
    void                        DeSelect();
    inline sal_Bool             IsSelected(USHORT _nPos) const { return _nPos == nSelectedIndex; }
    inline USHORT               GetSelectIndexId() const { return sal::static_int_cast<USHORT>(nSelectedIndex); }
    USHORT                      GetRowPos(USHORT _nPos) const;
    USHORT                      GetColumnPos(USHORT _nPos) const;

    void                        ImplFireAccessibleEvent( short nEventId,
                                                         const ::com::sun::star::uno::Any& rOldValue,
                                                         const ::com::sun::star::uno::Any& rNewValue );
    ScrollBar*                  getScrollBar();
    void                        ReleaseAccessible();
    sal_Int32                   getMaxCharCount() const;
#endif // _SVX_CHARMAP_CXX_

protected:
    virtual void    Paint( const Rectangle& );
    virtual void    MouseButtonDown( const MouseEvent& rMEvt );
    virtual void    MouseButtonUp( const MouseEvent& rMEvt );
    virtual void    MouseMove( const MouseEvent& rMEvt );
    virtual void    Command( const CommandEvent& rCEvt );
    virtual void    KeyInput( const KeyEvent& rKEvt );
    virtual void    GetFocus();
    virtual void    LoseFocus();
    virtual void    StateChanged( StateChangedType nStateChange );
    virtual void    DataChanged( const DataChangedEvent& rDCEvt );

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

private:
    typedef ::std::map<sal_Int32, ::svx::SvxShowCharSetItem*> ItemsMap;
    ItemsMap        m_aItems;
    Link            aDoubleClkHdl;
    Link            aSelectHdl;
    Link            aHighHdl;
    Link            aPreSelectHdl;
    ::svx::SvxShowCharSetVirtualAcc*    m_pAccessible;
    ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > m_xAccessible;
    long            nX;
    long            nY;
    BOOL            bDrag;

    sal_Int32       nSelectedIndex;

    FontCharMap     maFontCharMap;
    ScrollBar       aVscrollSB;
    Size            aOrigSize;
    Point           aOrigPos;

private:
    void            DrawChars_Impl( int n1, int n2);
    void            InitSettings( BOOL bForeground, BOOL bBackground);
    // abstraction layers are: Unicode<->MapIndex<->Pixel
    Point           MapIndexToPixel( int) const;
//#if 0 // _SOLAR__PRIVATE
    DECL_LINK( VscrollHdl, ScrollBar* );
//#endif
};

// class SvxShowText =====================================================

class SVX_DLLPUBLIC SvxShowText : public Control
{
public:
                    SvxShowText( Window* pParent,
                                 const ResId& rResId,
                                 BOOL bCenter = FALSE );
                    ~SvxShowText();

    void            SetFont( const Font& rFont );
    void            SetText( const String& rText );

protected:
    virtual void    Paint( const Rectangle& );

private:
    long            mnY;
    BOOL            mbCenter;

};

class SVX_DLLPUBLIC SvxCharMapData
{
public:
                    SvxCharMapData( class SfxModalDialog* pDialog, BOOL bOne_ );

    void            SetCharFont( const Font& rFont );

private:
friend class SvxCharacterMap;
    SfxModalDialog* mpDialog;

    SvxShowCharSet  aShowSet;
//    Edit            aShowText;
    SvxShowText     aShowText;
    OKButton        aOKBtn;
    CancelButton    aCancelBtn;
    HelpButton      aHelpBtn;
    PushButton      aDeleteBtn;
    FixedText       aFontText;
    ListBox         aFontLB;
    FixedText       aSubsetText;
    ListBox         aSubsetLB;
    FixedText       aSymbolText;
    SvxShowText     aShowChar;
    FixedText       aCharCodeText;

    Font            aFont;
    BOOL            bOne;
    const SubsetMap* pSubsetMap;

    DECL_LINK( OKHdl, OKButton* );
    DECL_LINK( FontSelectHdl, ListBox* );
    DECL_LINK( SubsetSelectHdl, ListBox* );
    DECL_LINK( CharDoubleClickHdl, Control* pControl );
    DECL_LINK( CharSelectHdl, Control* pControl );
    DECL_LINK( CharHighlightHdl, Control* pControl );
    DECL_LINK( CharPreSelectHdl, Control* pControl );
    DECL_LINK( DeleteHdl, PushButton* pBtn );
};
#endif

<commit_msg>INTEGRATION: CWS vcl78 (1.2.56); FILE MERGED 2007/05/07 17:48:27 pl 1.2.56.1: #i76832# fix special character dialog<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: charmap.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2007-06-11 14:23:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_CHARMAP_HXX
#define _SVX_CHARMAP_HXX

// include ---------------------------------------------------------------

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_METRIC_HXX
#include <vcl/metric.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif

#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#include <map>

#ifndef _SHL_HXX
#include <tools/shl.hxx> //add CHINA001
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx> //add CHINA001
#endif
#ifndef _SV_SOUND_HXX
#include <vcl/sound.hxx> //add CHINA001
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx> //add CHINA001
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx> //add CHINA001
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx> //add CHINA001
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx> //add CHINA001
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx> //add CHINA001
#endif
#ifndef _SV_METRIC_HXX
#include <vcl/metric.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class SubsetMap;
class SvxCharMapData;

// define ----------------------------------------------------------------

#ifdef MAC
#define CHARMAP_MAXLEN  28
#define COLUMN_COUNT    28
#define ROW_COUNT        8
#else
#define CHARMAP_MAXLEN  32
#define COLUMN_COUNT    16
#define ROW_COUNT        8
#endif

namespace svx
{
    struct SvxShowCharSetItem;
    class SvxShowCharSetVirtualAcc;
}

// class SvxShowCharSet --------------------------------------------------

class SVX_DLLPUBLIC SvxShowCharSet : public Control
{
public:
                    SvxShowCharSet( Window* pParent, const ResId& rResId );
                    ~SvxShowCharSet();

    void            SetFont( const Font& rFont );

    void            SelectCharacter( sal_uInt32 cNew, BOOL bFocus = FALSE );
    sal_UCS4        GetSelectCharacter() const;

    Link            GetDoubleClickHdl() const { return aDoubleClkHdl; }
    void            SetDoubleClickHdl( const Link& rLink ) { aDoubleClkHdl = rLink; }
    Link            GetSelectHdl() const { return aSelectHdl; }
    void            SetSelectHdl( const Link& rHdl ) { aSelectHdl = rHdl; }
    Link            GetHighlightHdl() const { return aHighHdl; }
    void            SetHighlightHdl( const Link& rHdl ) { aHighHdl = rHdl; }
    Link            GetPreSelectHdl() const { return aHighHdl; }
    void            SetPreSelectHdl( const Link& rHdl ) { aPreSelectHdl = rHdl; }

#ifdef _SVX_CHARMAP_CXX_
    ::svx::SvxShowCharSetItem*  ImplGetItem( int _nPos );
    int                         FirstInView( void) const;
    int                         LastInView( void) const;
    int                         PixelToMapIndex( const Point&) const;
    void                        SelectIndex( int index, BOOL bFocus = FALSE );
    void                        DeSelect();
    inline sal_Bool             IsSelected(USHORT _nPos) const { return _nPos == nSelectedIndex; }
    inline USHORT               GetSelectIndexId() const { return sal::static_int_cast<USHORT>(nSelectedIndex); }
    USHORT                      GetRowPos(USHORT _nPos) const;
    USHORT                      GetColumnPos(USHORT _nPos) const;

    void                        ImplFireAccessibleEvent( short nEventId,
                                                         const ::com::sun::star::uno::Any& rOldValue,
                                                         const ::com::sun::star::uno::Any& rNewValue );
    ScrollBar*                  getScrollBar();
    void                        ReleaseAccessible();
    sal_Int32                   getMaxCharCount() const;
#endif // _SVX_CHARMAP_CXX_

protected:
    virtual void    Paint( const Rectangle& );
    virtual void    MouseButtonDown( const MouseEvent& rMEvt );
    virtual void    MouseButtonUp( const MouseEvent& rMEvt );
    virtual void    MouseMove( const MouseEvent& rMEvt );
    virtual void    Command( const CommandEvent& rCEvt );
    virtual void    KeyInput( const KeyEvent& rKEvt );
    virtual void    GetFocus();
    virtual void    LoseFocus();
    virtual void    StateChanged( StateChangedType nStateChange );
    virtual void    DataChanged( const DataChangedEvent& rDCEvt );

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

private:
    typedef ::std::map<sal_Int32, ::svx::SvxShowCharSetItem*> ItemsMap;
    ItemsMap        m_aItems;
    Link            aDoubleClkHdl;
    Link            aSelectHdl;
    Link            aHighHdl;
    Link            aPreSelectHdl;
    ::svx::SvxShowCharSetVirtualAcc*    m_pAccessible;
    ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > m_xAccessible;
    long            nX;
    long            nY;
    BOOL            bDrag;

    sal_Int32       nSelectedIndex;

    FontCharMap     maFontCharMap;
    ScrollBar       aVscrollSB;
    Size            aOrigSize;
    Point           aOrigPos;

private:
    void            DrawChars_Impl( int n1, int n2);
    void            InitSettings( BOOL bForeground, BOOL bBackground);
    // abstraction layers are: Unicode<->MapIndex<->Pixel
    Point           MapIndexToPixel( int) const;
//#if 0 // _SOLAR__PRIVATE
    DECL_LINK( VscrollHdl, ScrollBar* );
//#endif
};

// class SvxShowText =====================================================

class SVX_DLLPUBLIC SvxShowText : public Control
{
public:
                    SvxShowText( Window* pParent,
                                 const ResId& rResId,
                                 BOOL bCenter = FALSE );
                    ~SvxShowText();

    void            SetFont( const Font& rFont );
    void            SetText( const String& rText );

protected:
    virtual void    Paint( const Rectangle& );

private:
    long            mnY;
    BOOL            mbCenter;

};

class SVX_DLLPUBLIC SvxCharMapData
{
public:
                    SvxCharMapData( class SfxModalDialog* pDialog, BOOL bOne_, ResMgr* pResContext );

    void            SetCharFont( const Font& rFont );

private:
friend class SvxCharacterMap;
    SfxModalDialog* mpDialog;

    SvxShowCharSet  aShowSet;
//    Edit            aShowText;
    SvxShowText     aShowText;
    OKButton        aOKBtn;
    CancelButton    aCancelBtn;
    HelpButton      aHelpBtn;
    PushButton      aDeleteBtn;
    FixedText       aFontText;
    ListBox         aFontLB;
    FixedText       aSubsetText;
    ListBox         aSubsetLB;
    FixedText       aSymbolText;
    SvxShowText     aShowChar;
    FixedText       aCharCodeText;

    Font            aFont;
    BOOL            bOne;
    const SubsetMap* pSubsetMap;

    DECL_LINK( OKHdl, OKButton* );
    DECL_LINK( FontSelectHdl, ListBox* );
    DECL_LINK( SubsetSelectHdl, ListBox* );
    DECL_LINK( CharDoubleClickHdl, Control* pControl );
    DECL_LINK( CharSelectHdl, Control* pControl );
    DECL_LINK( CharHighlightHdl, Control* pControl );
    DECL_LINK( CharPreSelectHdl, Control* pControl );
    DECL_LINK( DeleteHdl, PushButton* pBtn );
};
#endif

<|endoftext|>