<commit_before>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Olad.cpp
 * Main file for olad, parses the options, forks if required and runs the
 * daemon.
 * Copyright (C) 2005-2007 Simon Newton
 *
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif

#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif

#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sysexits.h>
#include <unistd.h>
#include <iostream>
#include <string>

#include "ola/Logging.h"
#include "olad/OlaDaemon.h"

using ola::OlaDaemon;
using std::string;
using std::cout;
using std::cerr;
using std::endl;

// the daemon
OlaDaemon *olad;

// options struct
typedef struct {
  ola::log_level level;
  ola::log_output output;
  bool daemon;
  bool help;
  int httpd;
  int http_quit;
  int http_port;
  int rpc_port;
  string http_data_dir;
  string config_dir;
} ola_options;

/*
 * Print a stack trace on seg fault
 */
static void sig_segv(int signo) {
  cout << "Recieved SIGSEGV or SIGBUS" << endl;
  #ifdef HAVE_EXECINFO_H
  enum {STACK_SIZE = 64};
  void *array[STACK_SIZE];
  size_t size = backtrace(array, STACK_SIZE);

  backtrace_symbols_fd(array, size, STDERR_FILENO);
  #endif
  exit(EX_SOFTWARE);
  (void) signo;
}

/*
 * Terminate cleanly on interrupt
 */
static void sig_interupt(int signo) {
  olad->Terminate();
  (void) signo;
}

/*
 * Reload plugins
 */
static void sig_hup(int signo) {
  olad->ReloadPlugins();
  (void) signo;
}

/*
 * Change logging level
 *
 * need to fix race conditions here
 */
static void sig_user1(int signo) {
  ola::IncrementLogLevel();
  (void) signo;
}

/*
 * Set up the interrupt signal
 *
 * @return true on success, false on failure
 */
static bool InstallSignals() {
  struct sigaction act, oact;

  act.sa_handler = sig_interupt;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;

  if (sigaction(SIGINT, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGINT";
    return false;
  }

  if (sigaction(SIGTERM, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGTERM";
    return false;
  }

  act.sa_handler = sig_segv;
  if (sigaction(SIGSEGV, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGSEGV";
    return false;
  }
  if (sigaction(SIGBUS, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGSEGV";
    return false;
  }

  act.sa_handler = sig_hup;

  if (sigaction(SIGHUP, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGHUP";
    return false;
  }

  act.sa_handler = sig_user1;

  if (sigaction(SIGUSR1, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGUSR1";
    return false;
  }
  return true;
}

/*
 * Display the help message
 */
static void DisplayHelp() {
  cout <<
  "Usage: olad [options]\n"
  "\n"
  "Start the ola daemon.\n"
  "\n"
  "  -c, --config-dir         Path to the config directory\n"
  "  -d, --http-data-dir      Path to the static content.\n"
  "  -f, --daemon             Fork into background.\n"
  "  -h, --help               Display this help message and exit.\n"
  "  -l, --log-level <level>  Set the logging level 0 .. 4 .\n"
  "  -p, --http-port          Port to run the http server on (default " <<
    ola::OlaServer::DEFAULT_HTTP_PORT << ")\n" <<
  "  -r, --rpc-port           Port to listen for RPCs on (default " <<
    ola::OlaDaemon::DEFAULT_RPC_PORT << ")\n" <<
  "  -s, --syslog             Log to syslog rather than stderr.\n"
  "  --no-http                Don't run the http server\n"
  "  --no-http-quit           Disable the /quit handler\n"
  << endl;
}

/*
 * Parse the command line options
 *
 * @param argc
 * @param argv
 * @param opts  pointer to the options struct
 */
static bool ParseOptions(int argc, char *argv[], ola_options *opts) {
  static struct option long_options[] = {
      {"config-dir", required_argument, 0, 'c'},
      {"help", no_argument, 0, 'h'},
      {"http-data-dir", required_argument, 0, 'd'},
      {"http-port", required_argument, 0, 'p'},
      {"log-level", required_argument, 0, 'l'},
      {"no-daemon", no_argument, 0, 'f'},
      {"no-http", no_argument, &opts->httpd, 0},
      {"no-http-quit", no_argument, &opts->http_quit, 0},
      {"rpc-port", required_argument, 0, 'r'},
      {"syslog", no_argument, 0, 's'},
      {0, 0, 0, 0}
    };

  bool options_valid = true;
  int c, ll;
  int option_index = 0;

  while (1) {
    c = getopt_long(argc, argv, "c:l:p:fd:hsr:", long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
      case 0:
        break;
      case 'c':
        opts->config_dir = optarg;
        break;
      case 'd':
        opts->http_data_dir = optarg;
        break;
      case 'f':
        opts->daemon = true;
        break;
      case 'h':
        opts->help = true;
        break;
      case 's':
        opts->output = ola::OLA_LOG_SYSLOG;
        break;
      case 'l':
        ll = atoi(optarg);
        switch (ll) {
          case 0:
            // nothing is written at this level
            // so this turns logging off
            opts->level = ola::OLA_LOG_NONE;
            break;
          case 1:
            opts->level = ola::OLA_LOG_FATAL;
            break;
          case 2:
            opts->level = ola::OLA_LOG_WARN;
            break;
          case 3:
            opts->level = ola::OLA_LOG_INFO;
            break;
          case 4:
            opts->level = ola::OLA_LOG_DEBUG;
            break;
          default :
            cerr << "Invalid log level " << optarg << endl;
            options_valid = false;
            break;
        }
        break;
      case 'p':
        opts->http_port = atoi(optarg);
        break;
      case 'r':
        opts->rpc_port = atoi(optarg);
        break;
      case '?':
        break;
      default:
       break;
    }
  }
  return options_valid;
}

/*
 * Run as a daemon, logging has been initialized when this is called.
 * This means that logging can't use any persistant FDs.
 */
static int Daemonise() {
  pid_t pid;
  unsigned int i;
  int fd0, fd1, fd2;
  struct rlimit rl;
  struct sigaction sa;

  if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
    OLA_FATAL << "Could not determine file limit";
    exit(EX_OSFILE);
  }

  // fork
  if ((pid = fork()) < 0) {
    OLA_FATAL << "Could not fork\n";
    exit(EX_OSERR);
  } else if (pid != 0) {
    exit(EX_OK);
  }

  // start a new session
  setsid();

  sa.sa_handler = SIG_IGN;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;

  if (sigaction(SIGHUP, &sa, NULL) < 0) {
    OLA_FATAL << "Could not install signal\n";
    exit(EX_OSERR);
  }

  if ((pid= fork()) < 0) {
    OLA_FATAL << "Could not fork\n";
    exit(EX_OSERR);
  } else if (pid != 0) {
    exit(EX_OK);
  }

  // change the current working directory
  if (chdir("/") < 0) {
    OLA_FATAL << "Can't change directory to /";
    exit(EX_OSERR);
  }

  // close all fds
  if (rl.rlim_max == RLIM_INFINITY)
    rl.rlim_max = 1024;
  for (i = 0; i < rl.rlim_max; i++)
    close(i);

  // send stdout, in and err to /dev/null
  fd0 = open("/dev/null", O_RDWR);
  fd1 = dup(0);
  fd2 = dup(0);

  if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
    OLA_FATAL << "Unexpected file descriptors: " << fd0 << ", " << fd1 << ", "
      << fd2;
    exit(EX_OSERR);
  }

  return 0;
}

/*
 * Parse the options, and take action
 *
 * @param argc
 * @param argv
 * @param opts a pointer to the ola_options struct
 */
static void Setup(int argc, char*argv[], ola_options *opts) {
  opts->level = ola::OLA_LOG_WARN;
  opts->output = ola::OLA_LOG_STDERR;
  opts->daemon = false;
  opts->help = false;
  opts->httpd = 1;
  opts->http_quit = 1;
  opts->http_port = ola::OlaServer::DEFAULT_HTTP_PORT;
  opts->rpc_port = ola::OlaDaemon::DEFAULT_RPC_PORT;
  opts->http_data_dir = "";
  opts->config_dir = "";

  if (!ParseOptions(argc, argv, opts)) {
    DisplayHelp();
    exit(EX_USAGE);
  }

  if (opts->help) {
    DisplayHelp();
    exit(EX_OK);
  }

  // setup the logging
  ola::InitLogging(opts->level, opts->output);

  if (opts->daemon)
    Daemonise();
}

static void InitExportMap(ola::ExportMap *export_map, int argc, char*argv[]) {
  struct rlimit rl;
  ola::StringVariable *var = export_map->GetStringVar("binary");
  var->Set(argv[0]);

  var = export_map->GetStringVar("cmd-line");

  std::stringstream out;
  for (int i = 1; i < argc; i++) {
    out << argv[i] << " ";
  }
  var->Set(out.str());

  var = export_map->GetStringVar("fd-limit");
  if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
    var->Set("undertermined");
  } else {
    std::stringstream out;
    out << rl.rlim_cur;
    var->Set(out.str());
  }
}

/*
 * Main
 *
 */
int main(int argc, char *argv[]) {
  ola_options opts;
  ola::ExportMap export_map;
  Setup(argc, argv, &opts);

  if (!geteuid()) {
    OLA_FATAL << "Attempting to run as root, aborting.";
    return -1;
  }

  InitExportMap(&export_map, argc, argv);

  if (!InstallSignals())
    OLA_WARN << "Failed to install signal handlers";

  ola::ola_server_options ola_options;
  ola_options.http_enable = opts.httpd;
  ola_options.http_enable_quit = opts.http_quit;
  ola_options.http_port = opts.http_port;
  ola_options.http_data_dir = opts.http_data_dir;

  olad = new OlaDaemon(ola_options, &export_map, opts.rpc_port,
                       opts.config_dir);
  bool ret = olad->Init();

  if (ret) {
    olad->Run();
  }
  delete olad;
  return ret ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Sort the argument identifier. See also http://code.google.com/p/linux-lighting/issues/detail?id=173#c1 .<commit_after>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Olad.cpp
 * Main file for olad, parses the options, forks if required and runs the
 * daemon.
 * Copyright (C) 2005-2007 Simon Newton
 *
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif

#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif

#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sysexits.h>
#include <unistd.h>
#include <iostream>
#include <string>

#include "ola/Logging.h"
#include "olad/OlaDaemon.h"

using ola::OlaDaemon;
using std::string;
using std::cout;
using std::cerr;
using std::endl;

// the daemon
OlaDaemon *olad;

// options struct
typedef struct {
  ola::log_level level;
  ola::log_output output;
  bool daemon;
  bool help;
  int httpd;
  int http_quit;
  int http_port;
  int rpc_port;
  string http_data_dir;
  string config_dir;
} ola_options;

/*
 * Print a stack trace on seg fault
 */
static void sig_segv(int signo) {
  cout << "Recieved SIGSEGV or SIGBUS" << endl;
  #ifdef HAVE_EXECINFO_H
  enum {STACK_SIZE = 64};
  void *array[STACK_SIZE];
  size_t size = backtrace(array, STACK_SIZE);

  backtrace_symbols_fd(array, size, STDERR_FILENO);
  #endif
  exit(EX_SOFTWARE);
  (void) signo;
}

/*
 * Terminate cleanly on interrupt
 */
static void sig_interupt(int signo) {
  olad->Terminate();
  (void) signo;
}

/*
 * Reload plugins
 */
static void sig_hup(int signo) {
  olad->ReloadPlugins();
  (void) signo;
}

/*
 * Change logging level
 *
 * need to fix race conditions here
 */
static void sig_user1(int signo) {
  ola::IncrementLogLevel();
  (void) signo;
}

/*
 * Set up the interrupt signal
 *
 * @return true on success, false on failure
 */
static bool InstallSignals() {
  struct sigaction act, oact;

  act.sa_handler = sig_interupt;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;

  if (sigaction(SIGINT, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGINT";
    return false;
  }

  if (sigaction(SIGTERM, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGTERM";
    return false;
  }

  act.sa_handler = sig_segv;
  if (sigaction(SIGSEGV, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGSEGV";
    return false;
  }
  if (sigaction(SIGBUS, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGSEGV";
    return false;
  }

  act.sa_handler = sig_hup;

  if (sigaction(SIGHUP, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGHUP";
    return false;
  }

  act.sa_handler = sig_user1;

  if (sigaction(SIGUSR1, &act, &oact) < 0) {
    OLA_WARN << "Failed to install signal SIGUSR1";
    return false;
  }
  return true;
}

/*
 * Display the help message
 */
static void DisplayHelp() {
  cout <<
  "Usage: olad [options]\n"
  "\n"
  "Start the ola daemon.\n"
  "\n"
  "  -c, --config-dir         Path to the config directory\n"
  "  -d, --http-data-dir      Path to the static content.\n"
  "  -f, --daemon             Fork into background.\n"
  "  -h, --help               Display this help message and exit.\n"
  "  -l, --log-level <level>  Set the logging level 0 .. 4 .\n"
  "  -p, --http-port          Port to run the http server on (default " <<
    ola::OlaServer::DEFAULT_HTTP_PORT << ")\n" <<
  "  -r, --rpc-port           Port to listen for RPCs on (default " <<
    ola::OlaDaemon::DEFAULT_RPC_PORT << ")\n" <<
  "  -s, --syslog             Log to syslog rather than stderr.\n"
  "  --no-http                Don't run the http server\n"
  "  --no-http-quit           Disable the /quit handler\n"
  << endl;
}

/*
 * Parse the command line options
 *
 * @param argc
 * @param argv
 * @param opts  pointer to the options struct
 */
static bool ParseOptions(int argc, char *argv[], ola_options *opts) {
  static struct option long_options[] = {
      {"config-dir", required_argument, 0, 'c'},
      {"help", no_argument, 0, 'h'},
      {"http-data-dir", required_argument, 0, 'd'},
      {"http-port", required_argument, 0, 'p'},
      {"log-level", required_argument, 0, 'l'},
      {"no-daemon", no_argument, 0, 'f'},
      {"no-http", no_argument, &opts->httpd, 0},
      {"no-http-quit", no_argument, &opts->http_quit, 0},
      {"rpc-port", required_argument, 0, 'r'},
      {"syslog", no_argument, 0, 's'},
      {0, 0, 0, 0}
    };

  bool options_valid = true;
  int c, ll;
  int option_index = 0;

  while (1) {
    c = getopt_long(argc, argv, "c:d:fhl:p:sr:", long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
      case 0:
        break;
      case 'c':
        opts->config_dir = optarg;
        break;
      case 'd':
        opts->http_data_dir = optarg;
        break;
      case 'f':
        opts->daemon = true;
        break;
      case 'h':
        opts->help = true;
        break;
      case 's':
        opts->output = ola::OLA_LOG_SYSLOG;
        break;
      case 'l':
        ll = atoi(optarg);
        switch (ll) {
          case 0:
            // nothing is written at this level
            // so this turns logging off
            opts->level = ola::OLA_LOG_NONE;
            break;
          case 1:
            opts->level = ola::OLA_LOG_FATAL;
            break;
          case 2:
            opts->level = ola::OLA_LOG_WARN;
            break;
          case 3:
            opts->level = ola::OLA_LOG_INFO;
            break;
          case 4:
            opts->level = ola::OLA_LOG_DEBUG;
            break;
          default :
            cerr << "Invalid log level " << optarg << endl;
            options_valid = false;
            break;
        }
        break;
      case 'p':
        opts->http_port = atoi(optarg);
        break;
      case 'r':
        opts->rpc_port = atoi(optarg);
        break;
      case '?':
        break;
      default:
       break;
    }
  }
  return options_valid;
}

/*
 * Run as a daemon, logging has been initialized when this is called.
 * This means that logging can't use any persistant FDs.
 */
static int Daemonise() {
  pid_t pid;
  unsigned int i;
  int fd0, fd1, fd2;
  struct rlimit rl;
  struct sigaction sa;

  if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
    OLA_FATAL << "Could not determine file limit";
    exit(EX_OSFILE);
  }

  // fork
  if ((pid = fork()) < 0) {
    OLA_FATAL << "Could not fork\n";
    exit(EX_OSERR);
  } else if (pid != 0) {
    exit(EX_OK);
  }

  // start a new session
  setsid();

  sa.sa_handler = SIG_IGN;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;

  if (sigaction(SIGHUP, &sa, NULL) < 0) {
    OLA_FATAL << "Could not install signal\n";
    exit(EX_OSERR);
  }

  if ((pid= fork()) < 0) {
    OLA_FATAL << "Could not fork\n";
    exit(EX_OSERR);
  } else if (pid != 0) {
    exit(EX_OK);
  }

  // change the current working directory
  if (chdir("/") < 0) {
    OLA_FATAL << "Can't change directory to /";
    exit(EX_OSERR);
  }

  // close all fds
  if (rl.rlim_max == RLIM_INFINITY)
    rl.rlim_max = 1024;
  for (i = 0; i < rl.rlim_max; i++)
    close(i);

  // send stdout, in and err to /dev/null
  fd0 = open("/dev/null", O_RDWR);
  fd1 = dup(0);
  fd2 = dup(0);

  if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
    OLA_FATAL << "Unexpected file descriptors: " << fd0 << ", " << fd1 << ", "
      << fd2;
    exit(EX_OSERR);
  }

  return 0;
}

/*
 * Parse the options, and take action
 *
 * @param argc
 * @param argv
 * @param opts a pointer to the ola_options struct
 */
static void Setup(int argc, char*argv[], ola_options *opts) {
  opts->level = ola::OLA_LOG_WARN;
  opts->output = ola::OLA_LOG_STDERR;
  opts->daemon = false;
  opts->help = false;
  opts->httpd = 1;
  opts->http_quit = 1;
  opts->http_port = ola::OlaServer::DEFAULT_HTTP_PORT;
  opts->rpc_port = ola::OlaDaemon::DEFAULT_RPC_PORT;
  opts->http_data_dir = "";
  opts->config_dir = "";

  if (!ParseOptions(argc, argv, opts)) {
    DisplayHelp();
    exit(EX_USAGE);
  }

  if (opts->help) {
    DisplayHelp();
    exit(EX_OK);
  }

  // setup the logging
  ola::InitLogging(opts->level, opts->output);

  if (opts->daemon)
    Daemonise();
}

static void InitExportMap(ola::ExportMap *export_map, int argc, char*argv[]) {
  struct rlimit rl;
  ola::StringVariable *var = export_map->GetStringVar("binary");
  var->Set(argv[0]);

  var = export_map->GetStringVar("cmd-line");

  std::stringstream out;
  for (int i = 1; i < argc; i++) {
    out << argv[i] << " ";
  }
  var->Set(out.str());

  var = export_map->GetStringVar("fd-limit");
  if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
    var->Set("undertermined");
  } else {
    std::stringstream out;
    out << rl.rlim_cur;
    var->Set(out.str());
  }
}

/*
 * Main
 *
 */
int main(int argc, char *argv[]) {
  ola_options opts;
  ola::ExportMap export_map;
  Setup(argc, argv, &opts);

  if (!geteuid()) {
    OLA_FATAL << "Attempting to run as root, aborting.";
    return -1;
  }

  InitExportMap(&export_map, argc, argv);

  if (!InstallSignals())
    OLA_WARN << "Failed to install signal handlers";

  ola::ola_server_options ola_options;
  ola_options.http_enable = opts.httpd;
  ola_options.http_enable_quit = opts.http_quit;
  ola_options.http_port = opts.http_port;
  ola_options.http_data_dir = opts.http_data_dir;

  olad = new OlaDaemon(ola_options, &export_map, opts.rpc_port,
                       opts.config_dir);
  bool ret = olad->Init();

  if (ret) {
    olad->Run();
  }
  delete olad;
  return ret ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QFile>

#include "trikKitInterpreterCommon/trikQtsInterpreter.h"

#include "qrgui/plugins/toolPluginInterface/usedInterfaces/errorReporterInterface.h"

#include <twoDModel/engine/model/timeline.h>

#include <QDebug>

//QScriptValue printRedirect(QScriptContext * context, QScriptEngine * engine)
//{
//	QString result;
//	for (int i = 0; i < context->argumentCount(); ++i) {
//		if (i > 0) {
//			result.append(" ");
//		}

//		result.append(context->argument(i).toString());
//	}
//	if (!engine->isEvaluating())
//		qDebug("stoped evaluating!");
//	//bad: could sigsegv if execution aborted before executed.
//	engine->evaluate(QString("brick.log(\"%1\");").arg(result));

//	return engine->toScriptValue(result);
//}

const QString overrides = "script.random = brick.random;script.wait = brick.wait;script.time = brick.time;\n"
		"print = function() {var res = '';\n"
		"for(var i = 0; i < arguments.length; i++) {res += arguments[i].toString();}\n"
		"brick.log(res);return res;};";

trik::TrikQtsInterpreter::TrikQtsInterpreter(
        const QSharedPointer<trik::robotModel::twoD::TrikTwoDRobotModel> &model
		) : mRunning(false), mBrick(model), mScriptRunner(mBrick, nullptr, nullptr), mErrorReporter(nullptr)
{
	connect(&mBrick, &TrikBrick::error, this, &TrikQtsInterpreter::reportError);
	mScriptRunner.registerUserFunction("print", printRedirect);
//	connect(&mBrick, &TrikBrick::log, [this](const QString &msg){
//		QMetaObject::invokeMethod(this, "reportLog", Q_ARG(const QString &, msg));
//	});
//	auto redirectPrint = [](QScriptContext * ctx, QScriptEngine * eng) -> QScriptValue {
//		const auto txt = ctx->argument(0).toString();
//		eng->globalObject().property("brick").
//		return QScriptValue();
//	};
	//auto &t = dynamic_cast<twoDModel::model::Timeline &>(model->timeline());
	//t.setImmediateMode(true);
	//mScriptRunner.registerUserFunction("print", printRedirect);
	connect(&mScriptRunner, SIGNAL(completed(QString,int)), this, SLOT(scriptFinished(QString,int)));
}

trik::TrikQtsInterpreter::~TrikQtsInterpreter()
{
	abort();
}

void trik::TrikQtsInterpreter::interpretCommand(const QString &script)
{
	mScriptRunner.runDirectCommand(script);
}

void trik::TrikQtsInterpreter::interpretScript(const QString &script)
{
	mRunning = true;
	mScriptRunner.run(overrides + script);
}

void trik::TrikQtsInterpreter::interpretScriptExercise(const QString &script, const QString &inputs)
{
	mRunning = true;
	QString newScript = overrides + initInputs(inputs) + script;
	qDebug() << newScript;
	mScriptRunner.run(newScript);
}

void trik::TrikQtsInterpreter::abort()
{
	//mScriptRunner.abort();
	mBrick.stopWaiting();
	QMetaObject::invokeMethod(&mScriptRunner, "abort"); // just a wild test
	mRunning = false; // reset brick?
}

void trik::TrikQtsInterpreter::init()
{
	mBrick.init();
}

void trik::TrikQtsInterpreter::setErrorReporter(qReal::ErrorReporterInterface &errorReporter)
{
	mErrorReporter = &errorReporter;
}

bool trik::TrikQtsInterpreter::isRunning() const
{
	return mRunning;
}

void trik::TrikQtsInterpreter::reportError(const QString &msg)
{
	mErrorReporter->addError(msg);
//	mBrick.abort(); what if there are more errors?
}

void trik::TrikQtsInterpreter::reportLog(const QString &msg)
{
	mErrorReporter->addInformation("log: " + msg);
}

QString trik::TrikQtsInterpreter::initInputs(const QString &inputs) const
{
	auto jsValToStr = [this](const QJsonValue &val) -> QString {
		switch (val.type()) {
		case QJsonValue::Bool:
			return val.toBool() ? "true" : "false";
		case QJsonValue::Double:
			return QString::number(val.Double);//maybe increase precision
		case QJsonValue::String:
			return QString("\"%1\"").arg(val.toString());
		case QJsonValue::Array:
			return QString(QJsonDocument(val.toArray()).toJson(QJsonDocument::Compact));
		case QJsonValue::Object:
			return QString(QJsonDocument(val.toObject()).toJson(QJsonDocument::Compact));
		default:
			mErrorReporter->addError(QObject::tr("Bogus input values"));
			return "";
		}
	};

	QString result;
	if (!inputs.isNull()) {
		QString val;
		QFile file;
		file.setFileName(inputs);
		if (file.open(QIODevice::ReadOnly)) {
			val = file.readAll();
			file.close();
			QJsonDocument document = QJsonDocument::fromJson(val.toUtf8());
			QJsonObject object = document.object();
			for (const QString &name : object.keys()) {
				QJsonValue value = object[name];
				QString valueStr = jsValToStr(value);
				QString line("var " + name + " = " + valueStr + ";\n");
				result.append(line);
			}
		} else {
			mErrorReporter->addError(QObject::tr("Error: File couldn't open!"));
		}
	}
	return result;
}

void trik::TrikQtsInterpreter::setRunning(bool running)
{
	mRunning = running;
}

void trik::TrikQtsInterpreter::scriptFinished(const QString &error, int scriptId)
{
	Q_UNUSED(scriptId);
	if (!error.isEmpty()) {
		reportError(error);
	}
	if (mRunning) { /// @todo: figure out better place for this check - it should avoid double aborts
		emit completed();
	}
}
<commit_msg>fixup<commit_after>#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QFile>

#include "trikKitInterpreterCommon/trikQtsInterpreter.h"

#include "qrgui/plugins/toolPluginInterface/usedInterfaces/errorReporterInterface.h"

#include <twoDModel/engine/model/timeline.h>

#include <QDebug>

//QScriptValue printRedirect(QScriptContext * context, QScriptEngine * engine)
//{
//	QString result;
//	for (int i = 0; i < context->argumentCount(); ++i) {
//		if (i > 0) {
//			result.append(" ");
//		}

//		result.append(context->argument(i).toString());
//	}
//	if (!engine->isEvaluating())
//		qDebug("stoped evaluating!");
//	//bad: could sigsegv if execution aborted before executed.
//	engine->evaluate(QString("brick.log(\"%1\");").arg(result));

//	return engine->toScriptValue(result);
//}

const QString overrides = "script.random = brick.random;script.wait = brick.wait;script.time = brick.time;\n"
		"print = function() {var res = '';\n"
		"for(var i = 0; i < arguments.length; i++) {res += arguments[i].toString();}\n"
		"brick.log(res);return res;};";

trik::TrikQtsInterpreter::TrikQtsInterpreter(
        const QSharedPointer<trik::robotModel::twoD::TrikTwoDRobotModel> &model
		) : mRunning(false), mBrick(model), mScriptRunner(mBrick, nullptr, nullptr), mErrorReporter(nullptr)
{
	connect(&mBrick, &TrikBrick::error, this, &TrikQtsInterpreter::reportError);
//	mScriptRunner.registerUserFunction("print", printRedirect);
//	connect(&mBrick, &TrikBrick::log, [this](const QString &msg){
//		QMetaObject::invokeMethod(this, "reportLog", Q_ARG(const QString &, msg));
//	});
//	auto redirectPrint = [](QScriptContext * ctx, QScriptEngine * eng) -> QScriptValue {
//		const auto txt = ctx->argument(0).toString();
//		eng->globalObject().property("brick").
//		return QScriptValue();
//	};
	//auto &t = dynamic_cast<twoDModel::model::Timeline &>(model->timeline());
	//t.setImmediateMode(true);
	connect(&mScriptRunner, SIGNAL(completed(QString,int)), this, SLOT(scriptFinished(QString,int)));
}

trik::TrikQtsInterpreter::~TrikQtsInterpreter()
{
	abort();
}

void trik::TrikQtsInterpreter::interpretCommand(const QString &script)
{
	mScriptRunner.runDirectCommand(script);
}

void trik::TrikQtsInterpreter::interpretScript(const QString &script)
{
	mRunning = true;
	mScriptRunner.run(overrides + script);
}

void trik::TrikQtsInterpreter::interpretScriptExercise(const QString &script, const QString &inputs)
{
	mRunning = true;
	QString newScript = overrides + initInputs(inputs) + script;
	qDebug() << newScript;
	mScriptRunner.run(newScript);
}

void trik::TrikQtsInterpreter::abort()
{
	//mScriptRunner.abort();
	mBrick.stopWaiting();
	QMetaObject::invokeMethod(&mScriptRunner, "abort"); // just a wild test
	mRunning = false; // reset brick?
}

void trik::TrikQtsInterpreter::init()
{
	mBrick.init();
}

void trik::TrikQtsInterpreter::setErrorReporter(qReal::ErrorReporterInterface &errorReporter)
{
	mErrorReporter = &errorReporter;
}

bool trik::TrikQtsInterpreter::isRunning() const
{
	return mRunning;
}

void trik::TrikQtsInterpreter::reportError(const QString &msg)
{
	mErrorReporter->addError(msg);
//	mBrick.abort(); what if there are more errors?
}

void trik::TrikQtsInterpreter::reportLog(const QString &msg)
{
	mErrorReporter->addInformation("log: " + msg);
}

QString trik::TrikQtsInterpreter::initInputs(const QString &inputs) const
{
	auto jsValToStr = [this](const QJsonValue &val) -> QString {
		switch (val.type()) {
		case QJsonValue::Bool:
			return val.toBool() ? "true" : "false";
		case QJsonValue::Double:
			return QString::number(val.Double);//maybe increase precision
		case QJsonValue::String:
			return QString("\"%1\"").arg(val.toString());
		case QJsonValue::Array:
			return QString(QJsonDocument(val.toArray()).toJson(QJsonDocument::Compact));
		case QJsonValue::Object:
			return QString(QJsonDocument(val.toObject()).toJson(QJsonDocument::Compact));
		default:
			mErrorReporter->addError(QObject::tr("Bogus input values"));
			return "";
		}
	};

	QString result;
	if (!inputs.isNull()) {
		QString val;
		QFile file;
		file.setFileName(inputs);
		if (file.open(QIODevice::ReadOnly)) {
			val = file.readAll();
			file.close();
			QJsonDocument document = QJsonDocument::fromJson(val.toUtf8());
			QJsonObject object = document.object();
			for (const QString &name : object.keys()) {
				QJsonValue value = object[name];
				QString valueStr = jsValToStr(value);
				QString line("var " + name + " = " + valueStr + ";\n");
				result.append(line);
			}
		} else {
			mErrorReporter->addError(QObject::tr("Error: File couldn't open!"));
		}
	}
	return result;
}

void trik::TrikQtsInterpreter::setRunning(bool running)
{
	mRunning = running;
}

void trik::TrikQtsInterpreter::scriptFinished(const QString &error, int scriptId)
{
	Q_UNUSED(scriptId);
	if (!error.isEmpty()) {
		reportError(error);
	}
	if (mRunning) { /// @todo: figure out better place for this check - it should avoid double aborts
		emit completed();
	}
}
<|endoftext|>


<commit_before>// Berkeley Open Infrastructure for Network Computing
// http://boinc.berkeley.edu
// Copyright (C) 2005 University of California
//
// This is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation;
// either version 2.1 of the License, or (at your option) any later version.
//
// This software 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.
//
// To view the GNU Lesser General Public License visit
// http://www.gnu.org/copyleft/lesser.html
// or write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// This file defines a Fortran wrapper to the BOINC API.

#include "util.h"
#include "boinc_api.h"
#include "graphics_api.h"
#include "str_util.h"   // iza
#include "boinc_zip.h"

// helper class that makes a C-string from a character array and length,
// automatically deleted on destruction

// Fortran strings are passed as character array plus length
class StringFromFortran {
    char* p;
public:
    StringFromFortran(const char* s, int s_len) {
        p = new char[s_len + 1];
        memcpy(p, s, s_len);
        p[s_len] = 0;
    }
    ~StringFromFortran() { delete [] p; }
    operator char* () const { return p; }
};

extern "C" {

    void boinc_init_() {
        boinc_init();
    }

    void boinc_finish_(int* status) {
        boinc_finish(*status);
    }

	void boinc_init_graphics_(){
		//boinc_init_graphics();
	}

	void boinc_finish_graphics_(){
		//boinc_finish_graphics();
	}

    void boinc_is_standalone_(int* result) {
        *result = boinc_is_standalone();
    }

    void boinc_resolve_filename_(
        const char* s, char* t, int* length, int s_len, int t_len
    ) {
        boinc_resolve_filename(StringFromFortran(s, s_len), t, *length);
    }

    void boincrf_(const char* s, char* t, int s_len, int t_len) {
        boinc_resolve_filename(StringFromFortran(s, s_len), t, t_len);
    }

    void boinc_parse_init_data_file_() {
        boinc_parse_init_data_file();
    }

    int boinc_write_init_data_file_() {
        int boinc_write_init_data_file();
    }

// TODO: structs? common?
// extern int	boinc_get_init_data(APP_INIT_DATA&);

    // void boinc_send_trickle_up_(char* s, int s_len)
    // {
    //     boinc_send_trickle_up(StringFromFortran(s,s_len));
    // }

    // void boinc_receive_trickle_down_(char* buf, int len)
    // {
    //     boinc_receive_trickle_down(buf, len);
    // }

    void boinc_time_to_checkpoint_(int* result) {
        *result = boinc_time_to_checkpoint();
    }

    void boinc_checkpoint_completed_() {
        boinc_checkpoint_completed();
    }

    void boinc_fraction_done_(double* d) {
        boinc_fraction_done(*d);
    }

    void boinc_wu_cpu_time_(double* d_out) {
        boinc_wu_cpu_time(*d_out);
    }

   /* void boinc_calling_thread_cpu_time_(double* d1_out, double* d2_out) {
        boinc_calling_thread_cpu_time(*d1_out, *d2_out);
    }*/

}

const char *BOINC_RCSID_4f5153609c = "$Id: boinc_api_fortran.C,v 1.15 2005/03/15 18:35:53 rwalton Exp $";

<commit_msg>use the boinc_api_fortran.cpp from inside the BOINC folder<commit_after><|endoftext|>


<commit_before>/*
 * copyright: (c) RDO-Team, 2009
 * filename : rdoparser_lexer.cpp
 * author   :  ,
 * date     :
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
#include "rdo_lib/rdo_converter/pch.h"
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_converter/rdoparser_lexer.h"
// ===============================================================================

OPEN_RDO_CONVERTER_NAMESPACE

// ----------------------------------------------------------------------------
// ---------- RDOLexer
// ----------------------------------------------------------------------------
#ifdef YY_INTERACTIVE
int RDOLexer::LexerInput(PTR(char) buf, int /* max_size */)
#else
int RDOLexer::LexerInput(PTR(char) buf, int max_size)
#endif
{
	if (m_yyin->eof() || m_yyin->fail())
		return 0;

#ifdef YY_INTERACTIVE
	m_yyin->get(buf[0]);

	if (m_yyin->eof())
		return 0;

	if (m_yyin->bad())
		return -1;

	return 1;
#else
	(void) m_yyin->read(buf, max_size);

	if (m_yyin->bad())
	{
		return -1;
	}
	else
	{
		return m_yyin->gcount();
	}
#endif
}

void RDOLexer::LexerOutput(CPTR(char) buf, int size)
{
	(void) m_yyout->write(buf, size);
}

#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif

void RDOLexer::LexerError(const char msg[])
{
	std::cerr << msg << '\n';
	exit(YY_EXIT_FAILURE);
}

extern "C"
{
	int yywrap(void)
	{
		return 1;
	}
}

CLOSE_RDO_CONVERTER_NAMESPACE
<commit_msg> - исправлена ошибка линковки<commit_after>/*
 * copyright: (c) RDO-Team, 2009
 * filename : rdoparser_lexer.cpp
 * author   :  ,
 * date     :
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
#include "rdo_lib/rdo_converter/pch.h"
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_converter/rdoparser_lexer.h"
// ===============================================================================

OPEN_RDO_CONVERTER_NAMESPACE

// ----------------------------------------------------------------------------
// ---------- RDOLexer
// ----------------------------------------------------------------------------
#ifdef YY_INTERACTIVE
int RDOLexer::LexerInput(PTR(char) buf, int /* max_size */)
#else
int RDOLexer::LexerInput(PTR(char) buf, int max_size)
#endif
{
	if (m_yyin->eof() || m_yyin->fail())
		return 0;

#ifdef YY_INTERACTIVE
	m_yyin->get(buf[0]);

	if (m_yyin->eof())
		return 0;

	if (m_yyin->bad())
		return -1;

	return 1;
#else
	(void) m_yyin->read(buf, max_size);

	if (m_yyin->bad())
	{
		return -1;
	}
	else
	{
		return m_yyin->gcount();
	}
#endif
}

void RDOLexer::LexerOutput(CPTR(char) buf, int size)
{
	(void) m_yyout->write(buf, size);
}

#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif

void RDOLexer::LexerError(const char msg[])
{
	std::cerr << msg << '\n';
	exit(YY_EXIT_FAILURE);
}

extern "C"
{
	int yywrap2(void)
	{
		return 1;
	}
}

CLOSE_RDO_CONVERTER_NAMESPACE
<|endoftext|>


<commit_before>//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a '-print-cfg' analysis pass, which emits the
// cfg.<fnname>.dot file for each function in the program, with a graph of the
// CFG for that function.
//
// The other main feature of this file is that it implements the
// Function::viewCFG method, which is useful for debugging passes which operate
// on the CFG.
//
//===----------------------------------------------------------------------===//

#include "Support/GraphWriter.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/iTerminators.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/CFG.h"
#include <sstream>
#include <fstream>

/// CFGOnly flag - This is used to control whether or not the CFG graph printer
/// prints out the contents of basic blocks or not.  This is acceptable because
/// this code is only really used for debugging purposes.
///
static bool CFGOnly = false;

template<>
struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
  static std::string getGraphName(const Function *F) {
    return "CFG for '" + F->getName() + "' function";
  }

  static std::string getNodeLabel(const BasicBlock *Node,
                                  const Function *Graph) {
    if (CFGOnly && !Node->getName().empty()) return Node->getName() + ":";

    std::ostringstream Out;
    if (CFGOnly) {
      WriteAsOperand(Out, Node, false, true);
      return Out.str();
    }

    Out << *Node;
    std::string OutStr = Out.str();
    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());

    // Process string output to make it nicer...
    for (unsigned i = 0; i != OutStr.length(); ++i)
      if (OutStr[i] == '\n') {                            // Left justify
        OutStr[i] = '\\';
        OutStr.insert(OutStr.begin()+i+1, 'l');
      } else if (OutStr[i] == ';') {                      // Delete comments!
        unsigned Idx = OutStr.find('\n', i+1);            // Find end of line
        OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
        --i;
      }

    return OutStr;
  }

  static std::string getNodeAttributes(const BasicBlock *N) {
    return "fontname=Courier";
  }

  static std::string getEdgeSourceLabel(const BasicBlock *Node,
                                        succ_const_iterator I) {
    // Label source of conditional branches with "T" or "F"
    if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
      if (BI->isConditional())
        return (I == succ_begin(Node)) ? "T" : "F";
    return "";
  }
};

namespace {
  struct CFGPrinter : public FunctionPass {
    virtual bool runOnFunction(Function &F) {
      std::string Filename = "cfg." + F.getName() + ".dot";
      std::cerr << "Writing '" << Filename << "'...";
      std::ofstream File(Filename.c_str());

      if (File.good())
        WriteGraph(File, (const Function*)&F);
      else
        std::cerr << "  error opening file for writing!";
      std::cerr << "\n";
      return false;
    }

    void print(std::ostream &OS) const {}

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }
  };

  RegisterAnalysis<CFGPrinter> P1("print-cfg",
                                  "Print CFG of function to 'dot' file");
};

/// viewCFG - This function is meant for use from the debugger.  You can just
/// say 'call F->viewCFG()' and a ghostview window should pop up from the
/// program, displaying the CFG of the current function.  This depends on there
/// being a 'dot' and 'gv' program in your path.
///
void Function::viewCFG() const {
  std::string Filename = "/tmp/cfg." + getName() + ".dot";
  std::cerr << "Writing '" << Filename << "'... ";
  std::ofstream F(Filename.c_str());

  if (!F.good()) {
    std::cerr << "  error opening file for writing!\n";
    return;
  }

  WriteGraph(F, this);
  F.close();
  std::cerr << "\n";

  std::cerr << "Running 'dot' program... " << std::flush;
  if (system(("dot -Tps " + Filename + " > /tmp/cfg.tempgraph.ps").c_str())) {
    std::cerr << "Error running dot: 'dot' not in path?\n";
  } else {
    std::cerr << "\n";
    system("gv /tmp/cfg.tempgraph.ps");
  }
  system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
}

/// viewCFGOnly - This function is meant for use from the debugger.  It works
/// just like viewCFG, but it does not include the contents of basic blocks
/// into the nodes, just the label.  If you are only interested in the CFG t
/// his can make the graph smaller.
///
void Function::viewCFGOnly() const {
  CFGOnly = true;
  viewCFG();
  CFGOnly = false;
}
<commit_msg>Make sure to print labels on nodes without names<commit_after>//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a '-print-cfg' analysis pass, which emits the
// cfg.<fnname>.dot file for each function in the program, with a graph of the
// CFG for that function.
//
// The other main feature of this file is that it implements the
// Function::viewCFG method, which is useful for debugging passes which operate
// on the CFG.
//
//===----------------------------------------------------------------------===//

#include "Support/GraphWriter.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/iTerminators.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/CFG.h"
#include <sstream>
#include <fstream>

/// CFGOnly flag - This is used to control whether or not the CFG graph printer
/// prints out the contents of basic blocks or not.  This is acceptable because
/// this code is only really used for debugging purposes.
///
static bool CFGOnly = false;

template<>
struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
  static std::string getGraphName(const Function *F) {
    return "CFG for '" + F->getName() + "' function";
  }

  static std::string getNodeLabel(const BasicBlock *Node,
                                  const Function *Graph) {
    if (CFGOnly && !Node->getName().empty())
      return Node->getName() + ":";

    std::ostringstream Out;
    if (CFGOnly) {
      WriteAsOperand(Out, Node, false, true);
      return Out.str();
    }

    if (Node->getName().empty()) {
      WriteAsOperand(Out, Node, false, true);
      Out << ":";
    }

    Out << *Node;
    std::string OutStr = Out.str();
    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());

    // Process string output to make it nicer...
    for (unsigned i = 0; i != OutStr.length(); ++i)
      if (OutStr[i] == '\n') {                            // Left justify
        OutStr[i] = '\\';
        OutStr.insert(OutStr.begin()+i+1, 'l');
      } else if (OutStr[i] == ';') {                      // Delete comments!
        unsigned Idx = OutStr.find('\n', i+1);            // Find end of line
        OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
        --i;
      }

    return OutStr;
  }

  static std::string getNodeAttributes(const BasicBlock *N) {
    return "fontname=Courier";
  }

  static std::string getEdgeSourceLabel(const BasicBlock *Node,
                                        succ_const_iterator I) {
    // Label source of conditional branches with "T" or "F"
    if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
      if (BI->isConditional())
        return (I == succ_begin(Node)) ? "T" : "F";
    return "";
  }
};

namespace {
  struct CFGPrinter : public FunctionPass {
    virtual bool runOnFunction(Function &F) {
      std::string Filename = "cfg." + F.getName() + ".dot";
      std::cerr << "Writing '" << Filename << "'...";
      std::ofstream File(Filename.c_str());

      if (File.good())
        WriteGraph(File, (const Function*)&F);
      else
        std::cerr << "  error opening file for writing!";
      std::cerr << "\n";
      return false;
    }

    void print(std::ostream &OS) const {}

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }
  };

  RegisterAnalysis<CFGPrinter> P1("print-cfg",
                                  "Print CFG of function to 'dot' file");
};

/// viewCFG - This function is meant for use from the debugger.  You can just
/// say 'call F->viewCFG()' and a ghostview window should pop up from the
/// program, displaying the CFG of the current function.  This depends on there
/// being a 'dot' and 'gv' program in your path.
///
void Function::viewCFG() const {
  std::string Filename = "/tmp/cfg." + getName() + ".dot";
  std::cerr << "Writing '" << Filename << "'... ";
  std::ofstream F(Filename.c_str());

  if (!F.good()) {
    std::cerr << "  error opening file for writing!\n";
    return;
  }

  WriteGraph(F, this);
  F.close();
  std::cerr << "\n";

  std::cerr << "Running 'dot' program... " << std::flush;
  if (system(("dot -Tps " + Filename + " > /tmp/cfg.tempgraph.ps").c_str())) {
    std::cerr << "Error running dot: 'dot' not in path?\n";
  } else {
    std::cerr << "\n";
    system("gv /tmp/cfg.tempgraph.ps");
  }
  system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
}

/// viewCFGOnly - This function is meant for use from the debugger.  It works
/// just like viewCFG, but it does not include the contents of basic blocks
/// into the nodes, just the label.  If you are only interested in the CFG t
/// his can make the graph smaller.
///
void Function::viewCFGOnly() const {
  CFGOnly = true;
  viewCFG();
  CFGOnly = false;
}
<|endoftext|>


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

#include "callform.hxx"
#include "global.hxx"

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

#include <tools/debug.hxx>
#include <svtools/pathoptions.hxx>

#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>

#pragma hdrstop

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;

// static
void ScGlobal::InitAddIns()
{
    // multi paths separated by semicolons
    SvtPathOptions aPathOpt;
    String aMultiPath = aPathOpt.GetAddinPath();
    if ( aMultiPath.Len() > 0 )
    {
        xub_StrLen nTokens = aMultiPath.GetTokenCount( ';' );
        xub_StrLen nIndex = 0;
        for ( xub_StrLen j=0; j<nTokens; j++ )
        {
            String aPath( aMultiPath.GetToken( 0, ';', nIndex ) );
            if ( aPath.Len() > 0 )
            {
                //  use LocalFileHelper to convert the path to a URL that always points
                //  to the file on the server
                String aUrl;
                if ( utl::LocalFileHelper::ConvertPhysicalNameToURL( aPath, aUrl ) )
                    aPath = aUrl;

                INetURLObject aObj;
                aObj.SetSmartURL( aPath );
                aObj.setFinalSlash();
                try
                {
                    ::ucb::Content aCnt( aObj.GetMainURL(INetURLObject::NO_DECODE),
                        Reference< XCommandEnvironment > () );
                    Reference< sdbc::XResultSet > xResultSet;
                    Sequence< rtl::OUString > aProps;
                    try
                    {
                        xResultSet = aCnt.createCursor(
                            aProps, ::ucb::INCLUDE_DOCUMENTS_ONLY );
                    }
                    catch ( Exception& )
                    {
                        // ucb may throw different exceptions on failure now
                        // no assertion if AddIn directory doesn't exist
                    }

                    if ( xResultSet.is() )
                    {
                        Reference< sdbc::XRow > xRow( xResultSet, UNO_QUERY );
                        Reference< XContentAccess >
                            xContentAccess( xResultSet, UNO_QUERY );
                        try
                        {
                            if ( xResultSet->first() )
                            {
                                do
                                {
#if SUPD>611
                                    rtl::OUString aId( xContentAccess->queryContentIdentifierString() );
#else
                                    rtl::OUString aId( xContentAccess->queryContentIdentfierString() );
#endif
                                    InitExternalFunc( aId );
                                }
                                while ( xResultSet->next() );
                            }
                        }
                        catch ( Exception& )
                        {
                            DBG_ERRORFILE( "ResultSetException catched!" );
                        }
                    }
                }
                catch ( Exception& )
                {
                    DBG_ERRORFILE( "Exception catched!" );
                }
                catch ( ... )
                {

                    DBG_ERRORFILE( "unexpected exception caught!" );
                }
            }
        }
    }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.926); FILE MERGED 2005/09/05 15:01:40 rt 1.8.926.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: globalx.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:26:23 $
 *
 *  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
 *
 ************************************************************************/

#include "callform.hxx"
#include "global.hxx"

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

#include <tools/debug.hxx>
#include <svtools/pathoptions.hxx>

#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>

#pragma hdrstop

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;

// static
void ScGlobal::InitAddIns()
{
    // multi paths separated by semicolons
    SvtPathOptions aPathOpt;
    String aMultiPath = aPathOpt.GetAddinPath();
    if ( aMultiPath.Len() > 0 )
    {
        xub_StrLen nTokens = aMultiPath.GetTokenCount( ';' );
        xub_StrLen nIndex = 0;
        for ( xub_StrLen j=0; j<nTokens; j++ )
        {
            String aPath( aMultiPath.GetToken( 0, ';', nIndex ) );
            if ( aPath.Len() > 0 )
            {
                //  use LocalFileHelper to convert the path to a URL that always points
                //  to the file on the server
                String aUrl;
                if ( utl::LocalFileHelper::ConvertPhysicalNameToURL( aPath, aUrl ) )
                    aPath = aUrl;

                INetURLObject aObj;
                aObj.SetSmartURL( aPath );
                aObj.setFinalSlash();
                try
                {
                    ::ucb::Content aCnt( aObj.GetMainURL(INetURLObject::NO_DECODE),
                        Reference< XCommandEnvironment > () );
                    Reference< sdbc::XResultSet > xResultSet;
                    Sequence< rtl::OUString > aProps;
                    try
                    {
                        xResultSet = aCnt.createCursor(
                            aProps, ::ucb::INCLUDE_DOCUMENTS_ONLY );
                    }
                    catch ( Exception& )
                    {
                        // ucb may throw different exceptions on failure now
                        // no assertion if AddIn directory doesn't exist
                    }

                    if ( xResultSet.is() )
                    {
                        Reference< sdbc::XRow > xRow( xResultSet, UNO_QUERY );
                        Reference< XContentAccess >
                            xContentAccess( xResultSet, UNO_QUERY );
                        try
                        {
                            if ( xResultSet->first() )
                            {
                                do
                                {
#if SUPD>611
                                    rtl::OUString aId( xContentAccess->queryContentIdentifierString() );
#else
                                    rtl::OUString aId( xContentAccess->queryContentIdentfierString() );
#endif
                                    InitExternalFunc( aId );
                                }
                                while ( xResultSet->next() );
                            }
                        }
                        catch ( Exception& )
                        {
                            DBG_ERRORFILE( "ResultSetException catched!" );
                        }
                    }
                }
                catch ( Exception& )
                {
                    DBG_ERRORFILE( "Exception catched!" );
                }
                catch ( ... )
                {

                    DBG_ERRORFILE( "unexpected exception caught!" );
                }
            }
        }
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "OSD.h"

#include "../../3RVX/LanguageTranslator.h"
#include "../../3RVX/Logger.h"
#include "../../3RVX/Settings.h"
#include "../resource.h"

void OSD::Initialize() {
    using std::placeholders::_1;

    _osdList = new ListView(LST_OSDS, *this);
    _osdList->OnItemChange = std::bind(&OSD::OnOSDListItemChange, this, _1);

    _volumeIcon = new Checkbox(CHK_VOLICON, *this);
    _subscribeVolEvents = new Checkbox(CHK_MONITORVOL, *this);
    _subscribeVolEvents->OnClick = [this]() {
        _forceLimit->Enabled(_subscribeVolEvents->Checked());
        return true;
    };
    _audioDeviceLabel = new Label(LBL_AUDIODEV, *this);
    _audioDevice = new ComboBox(CMB_AUDIODEV, *this);
    _audioTaperLabel = new Label(LBL_AUDIOTAPER, *this);
    _audioTaper = new ComboBox(CMB_AUDIOTAPER, *this);
    _audioTaperEdit = new EditBox(ED_AUDIOTAPER, *this);
    _limitLabel = new Label(LBL_LIMITER, *this);
    _limitSlider = new Slider(SLD_LIMITER, *this);
    _limitValue = new Label(LBL_LIMITVAL, *this);
    _limitSlider->Buddy(_limitValue);
    _limitSlider->OnSlide = [this]() {
        std::wstring value = std::to_wstring(_limitSlider->Position()) + L"%";
        _limitValue->Text(value);
        return true;
    };
    _forceLimit = new Checkbox(CHK_FORCELIMIT, *this);
    _muteLock = new Checkbox(CHK_MUTELOCK, *this);
    _volumeGroup = new GroupBox(GRP_VOLUME, *this);
    _volumeGroup->AddChildren({
        _volumeIcon,
        _subscribeVolEvents,
        _audioDeviceLabel, _audioDevice,
        _audioTaperLabel, _audioTaper, _audioTaperEdit,
        _limitLabel, _limitSlider, _limitValue,
        _forceLimit,
        _muteLock,
    });

    _ejectIcon = new Checkbox(CHK_EJECTICON, *this);
    _monitorEjectEvents = new Checkbox(CHK_MONITOREJECT, *this);
    _ejectGroup = new GroupBox(GRP_EJECT, *this);
    _ejectGroup->AddChildren({
        _ejectIcon,
        _monitorEjectEvents,
    });

    _brightnessIcon = new Checkbox(CHK_BRIGHTICON, *this);
    _brightnessGroup = new GroupBox(GRP_BRIGHTNESS, *this);
    _brightnessGroup->AddChildren({
        _brightnessIcon,
    });

    _keyboardIcon = new Checkbox(CHK_KEYICON, *this);
    _caps = new Checkbox(CHK_ENABLECAPS, *this);
    _scroll = new Checkbox(CHK_ENABLESCROLL, *this);
    _num = new Checkbox(CHK_ENABLENUM, *this);
    _media = new Checkbox(CHK_ENABLEMK, *this);
    _keyboardGroup = new GroupBox(GRP_KEYBOARD, *this);
    _keyboardGroup->AddChildren({
        _keyboardIcon,
        _caps, _scroll, _num,
        _media,
    });

    /* Define groupbox order */
    GroupBox *groups[] = {
        _volumeGroup,
        _brightnessGroup,
        _ejectGroup,
        _keyboardGroup
    };

    /* Move other groupboxes into position (same as volume) */
    int groupX = _volumeGroup->X();
    int groupY = _volumeGroup->Y();
    for (GroupBox *grp : groups) {
        grp->X(groupX);
        grp->Y(groupY);
        grp->Visible(false);
        _groups.push_back(grp);
    }

}

void OSD::LoadSettings() {
    Settings *settings = Settings::Instance();
    LanguageTranslator *translator = settings->Translator();

    /* Translations */
    _osdStr = translator->Translate(_osdStr);
    _volumeStr = translator->Translate(_volumeStr);
    _brightnessStr = translator->Translate(_brightnessStr);
    _ejectStr = translator->Translate(_ejectStr);
    _keyboardStr = translator->Translate(_keyboardStr);

    _osdList->AddListExStyle(LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
    _osdList->AddColumn(_osdStr, (int) (_osdList->Width() * .97f));
    _osdList->AddItem(_volumeStr);
    _osdList->AddItem(_brightnessStr);
    _osdList->AddItem(_ejectStr);
    _osdList->AddItem(_keyboardStr);
    _osdList->Selection(0);

    _osdList->Checked(0, settings->VolumeOSDEnabled());
    _osdList->Checked(1, settings->BrightnessOSDEnabled());
    _osdList->Checked(2, settings->EjectOSDEnabled());
    _osdList->Checked(3, settings->KeyboardOSDEnabled());

    _volumeIcon->Checked(settings->NotifyIconEnabled());
    _subscribeVolEvents->Checked(settings->SubscribeVolumeEvents());
    _limitSlider->Position((int) (settings->VolumeLimiter() * 100.0f));
    _muteLock->Checked(settings->MuteOnLock());
}

void OSD::SaveSettings() {
    CLOG(L"Saving: OSD");
    Settings *settings = Settings::Instance();

    settings->VolumeOSDEnabled(_osdList->Checked(0));
    settings->BrightnessOSDEnabled(_osdList->Checked(1));
    settings->EjectOSDEnabled(_osdList->Checked(2));
    settings->KeyboardOSDEnabled(_osdList->Checked(3));

    settings->NotifyIconEnabled(_volumeIcon->Checked());
    settings->SubscribeVolumeEvents(_subscribeVolEvents->Checked());
    settings->VolumeLimiter(((float) _limitSlider->Position()) / 100.0f);
    settings->MuteOnLock(_muteLock->Checked());
}

void OSD::ShowGroup(int group) {
    for (GroupBox *grp : _groups) {
        grp->Visible(false);
    }

    GroupBox *showGroup = _groups[group];
    if (_osdList->Checked(group)) {
        showGroup->Enable();
    } else {
        showGroup->Disable();
    }
    showGroup->Visible(true);
}

void OSD::OnOSDListItemChange(NMLISTVIEW *lv) {
    if (lv->uChanged & LVIF_STATE) {
        UINT oSimg = lv->uOldState & LVIS_STATEIMAGEMASK;
        UINT nSimg = lv->uNewState & LVIS_STATEIMAGEMASK;
        if (oSimg != nSimg) {
            /* Checkbox changed */
            if (_osdList->Selection() == lv->iItem) {
                /* Activate the Apply button */
                PropSheet_Changed(GetParent(SettingsTab::DialogHandle()), NULL);

                /* Check state at 0xF000 (1 = un, 2 = check). Shift to check: */
                _groups[lv->iItem]->Enabled((nSimg >> 13) > 0);
            }
        }

        if (lv->uNewState & LVIS_SELECTED) {
            ShowGroup(lv->iItem);
        }
    }
}
<commit_msg>Update volume limiter state check on settings load<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "OSD.h"

#include "../../3RVX/LanguageTranslator.h"
#include "../../3RVX/Logger.h"
#include "../../3RVX/Settings.h"
#include "../resource.h"

void OSD::Initialize() {
    using std::placeholders::_1;

    _osdList = new ListView(LST_OSDS, *this);
    _osdList->OnItemChange = std::bind(&OSD::OnOSDListItemChange, this, _1);

    _volumeIcon = new Checkbox(CHK_VOLICON, *this);
    _subscribeVolEvents = new Checkbox(CHK_MONITORVOL, *this);
    _subscribeVolEvents->OnClick = [this]() {
        _forceLimit->Enabled(_subscribeVolEvents->Checked());
        return true;
    };
    _audioDeviceLabel = new Label(LBL_AUDIODEV, *this);
    _audioDevice = new ComboBox(CMB_AUDIODEV, *this);
    _audioTaperLabel = new Label(LBL_AUDIOTAPER, *this);
    _audioTaper = new ComboBox(CMB_AUDIOTAPER, *this);
    _audioTaperEdit = new EditBox(ED_AUDIOTAPER, *this);
    _limitLabel = new Label(LBL_LIMITER, *this);
    _limitSlider = new Slider(SLD_LIMITER, *this);
    _limitValue = new Label(LBL_LIMITVAL, *this);
    _limitSlider->Buddy(_limitValue);
    _limitSlider->OnSlide = [this]() {
        std::wstring value = std::to_wstring(_limitSlider->Position()) + L"%";
        _limitValue->Text(value);
        return true;
    };
    _forceLimit = new Checkbox(CHK_FORCELIMIT, *this);
    _muteLock = new Checkbox(CHK_MUTELOCK, *this);
    _volumeGroup = new GroupBox(GRP_VOLUME, *this);
    _volumeGroup->AddChildren({
        _volumeIcon,
        _subscribeVolEvents,
        _audioDeviceLabel, _audioDevice,
        _audioTaperLabel, _audioTaper, _audioTaperEdit,
        _limitLabel, _limitSlider, _limitValue,
        _forceLimit,
        _muteLock,
    });

    _ejectIcon = new Checkbox(CHK_EJECTICON, *this);
    _monitorEjectEvents = new Checkbox(CHK_MONITOREJECT, *this);
    _ejectGroup = new GroupBox(GRP_EJECT, *this);
    _ejectGroup->AddChildren({
        _ejectIcon,
        _monitorEjectEvents,
    });

    _brightnessIcon = new Checkbox(CHK_BRIGHTICON, *this);
    _brightnessGroup = new GroupBox(GRP_BRIGHTNESS, *this);
    _brightnessGroup->AddChildren({
        _brightnessIcon,
    });

    _keyboardIcon = new Checkbox(CHK_KEYICON, *this);
    _caps = new Checkbox(CHK_ENABLECAPS, *this);
    _scroll = new Checkbox(CHK_ENABLESCROLL, *this);
    _num = new Checkbox(CHK_ENABLENUM, *this);
    _media = new Checkbox(CHK_ENABLEMK, *this);
    _keyboardGroup = new GroupBox(GRP_KEYBOARD, *this);
    _keyboardGroup->AddChildren({
        _keyboardIcon,
        _caps, _scroll, _num,
        _media,
    });

    /* Define groupbox order */
    GroupBox *groups[] = {
        _volumeGroup,
        _brightnessGroup,
        _ejectGroup,
        _keyboardGroup
    };

    /* Move other groupboxes into position (same as volume) */
    int groupX = _volumeGroup->X();
    int groupY = _volumeGroup->Y();
    for (GroupBox *grp : groups) {
        grp->X(groupX);
        grp->Y(groupY);
        grp->Visible(false);
        _groups.push_back(grp);
    }

}

void OSD::LoadSettings() {
    Settings *settings = Settings::Instance();
    LanguageTranslator *translator = settings->Translator();

    /* Translations */
    _osdStr = translator->Translate(_osdStr);
    _volumeStr = translator->Translate(_volumeStr);
    _brightnessStr = translator->Translate(_brightnessStr);
    _ejectStr = translator->Translate(_ejectStr);
    _keyboardStr = translator->Translate(_keyboardStr);

    _osdList->AddListExStyle(LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
    _osdList->AddColumn(_osdStr, (int) (_osdList->Width() * .97f));
    _osdList->AddItem(_volumeStr);
    _osdList->AddItem(_brightnessStr);
    _osdList->AddItem(_ejectStr);
    _osdList->AddItem(_keyboardStr);
    _osdList->Selection(0);

    _osdList->Checked(0, settings->VolumeOSDEnabled());
    _osdList->Checked(1, settings->BrightnessOSDEnabled());
    _osdList->Checked(2, settings->EjectOSDEnabled());
    _osdList->Checked(3, settings->KeyboardOSDEnabled());

    _volumeIcon->Checked(settings->NotifyIconEnabled());
    _subscribeVolEvents->Checked(settings->SubscribeVolumeEvents());
    _limitSlider->Position((int) (settings->VolumeLimiter() * 100.0f));
    _forceLimit->Enabled(_subscribeVolEvents->Checked());
    _muteLock->Checked(settings->MuteOnLock());
}

void OSD::SaveSettings() {
    CLOG(L"Saving: OSD");
    Settings *settings = Settings::Instance();

    settings->VolumeOSDEnabled(_osdList->Checked(0));
    settings->BrightnessOSDEnabled(_osdList->Checked(1));
    settings->EjectOSDEnabled(_osdList->Checked(2));
    settings->KeyboardOSDEnabled(_osdList->Checked(3));

    settings->NotifyIconEnabled(_volumeIcon->Checked());
    settings->SubscribeVolumeEvents(_subscribeVolEvents->Checked());
    settings->VolumeLimiter(((float) _limitSlider->Position()) / 100.0f);
    settings->MuteOnLock(_muteLock->Checked());
}

void OSD::ShowGroup(int group) {
    for (GroupBox *grp : _groups) {
        grp->Visible(false);
    }

    GroupBox *showGroup = _groups[group];
    if (_osdList->Checked(group)) {
        showGroup->Enable();
    } else {
        showGroup->Disable();
    }
    showGroup->Visible(true);
}

void OSD::OnOSDListItemChange(NMLISTVIEW *lv) {
    if (lv->uChanged & LVIF_STATE) {
        UINT oSimg = lv->uOldState & LVIS_STATEIMAGEMASK;
        UINT nSimg = lv->uNewState & LVIS_STATEIMAGEMASK;
        if (oSimg != nSimg) {
            /* Checkbox changed */
            if (_osdList->Selection() == lv->iItem) {
                /* Activate the Apply button */
                PropSheet_Changed(GetParent(SettingsTab::DialogHandle()), NULL);

                /* Check state at 0xF000 (1 = un, 2 = check). Shift to check: */
                _groups[lv->iItem]->Enabled((nSimg >> 13) > 0);
            }
        }

        if (lv->uNewState & LVIS_SELECTED) {
            ShowGroup(lv->iItem);
        }
    }
}
<|endoftext|>


<commit_before>#include "threaded_scanner.h"

#include "logging.h"

#include "scan/scan_entity.h"

#include "search/ref.h"

#include "XPLMUtilities.h"

ThreadedScanner::ThreadedScanner() {
    worker_thread = std::thread([this]() {
        this->thread_proc();
    });
}

ThreadedScanner::~ThreadedScanner() {
    task_queue.push(ScanTaskMessage{.type = ScanMessageType::QUIT, .path={}});
    worker_thread.join();
}

void ThreadedScanner::scanInitial() {
    task_queue.push(ScanTaskMessage{.type = ScanMessageType::SCAN_INITIAL, .path={}});
}

void ThreadedScanner::scanAircraft(boost::filesystem::path aircraft_directory) {
    task_queue.push(ScanTaskMessage{.type = ScanMessageType::SCAN_AIRCRAFT, .path=std::move(aircraft_directory)});
}

void ThreadedScanner::scanPlugin(boost::filesystem::path plugin_directory) {
    task_queue.push(ScanTaskMessage{.type = ScanMessageType::SCAN_PLUGIN, .path=std::move(plugin_directory)});
}

void ThreadedScanner::thread_proc() {
    while(true) {
        ScanTaskMessage message = task_queue.get_blocking();

        switch(message.type) {
            case ScanMessageType::SCAN_INITIAL: {
                char system_path_c[1000];
                XPLMGetSystemPath(system_path_c);
                boost::filesystem::path system_path(system_path_c);

                { // Blacklist
                    boost::filesystem::path blacklist_path = system_path / "Resources" / "plugins" / "drt_blacklist.txt";
                    blacklist = loadListFile(xplog, blacklist_path);
                    results_queue.push(ScanResults{ref_src_t::BLACKLIST, blacklist});
                }

                { // DR file
                    boost::filesystem::path dr_file = system_path / "Resources" / "plugins" / "DataRefs.txt";
                    std::vector<std::string> dr_refs = loadListFile(xplog, dr_file);
                    results_queue.push(ScanResults{ref_src_t::FILE, dr_refs});
                }

                { // CR file
                    boost::filesystem::path cr_file = system_path / "Resources" / "plugins" / "Commands.txt";
                    std::vector<std::string> cr_refs = loadListFile(xplog, cr_file);
                    results_queue.push(ScanResults{ref_src_t::FILE, cr_refs});
                }

                { // FWL
                    boost::filesystem::path fwl_scripts_dir = system_path / "Resources" / "plugins" / "FlyWithLua" / "Scripts";
                    std::vector<std::string> script_refs = scanLuaFolder(xplog, fwl_scripts_dir);
                    results_queue.push(ScanResults{ref_src_t::FILE, script_refs});
                }
            }
                break;
            case ScanMessageType::SCAN_PLUGIN: {
                results_queue.push(ScanResults{ref_src_t::BLACKLIST, blacklist});
                std::vector<std::string> plugin_refs = ::scanPluginFolder(xplog, message.path);
                results_queue.push(ScanResults{ref_src_t::PLUGIN, plugin_refs});
            }
                break;
            case ScanMessageType::SCAN_AIRCRAFT: {
                results_queue.push(ScanResults{ref_src_t::BLACKLIST, blacklist});
                std::vector<std::string> aircraft_refs = ::scanAircraft(xplog, message.path);
                results_queue.push(ScanResults{ref_src_t::AIRCRAFT, aircraft_refs});
            }
                break;
            case ScanMessageType::QUIT:
                return;
        }
    }
}
<commit_msg>Remove more initializers that aren't MSVC compatible.<commit_after>#include "threaded_scanner.h"

#include "logging.h"

#include "scan/scan_entity.h"

#include "search/ref.h"

#include "XPLMUtilities.h"

ThreadedScanner::ThreadedScanner() {
    worker_thread = std::thread([this]() {
        this->thread_proc();
    });
}

ThreadedScanner::~ThreadedScanner() {
    task_queue.push(ScanTaskMessage{ScanMessageType::QUIT, {}});
    worker_thread.join();
}

void ThreadedScanner::scanInitial() {
    task_queue.push(ScanTaskMessage{ScanMessageType::SCAN_INITIAL, {}});
}

void ThreadedScanner::scanAircraft(boost::filesystem::path aircraft_directory) {
    task_queue.push(ScanTaskMessage{ScanMessageType::SCAN_AIRCRAFT, std::move(aircraft_directory)});
}

void ThreadedScanner::scanPlugin(boost::filesystem::path plugin_directory) {
    task_queue.push(ScanTaskMessage{ScanMessageType::SCAN_PLUGIN, std::move(plugin_directory)});
}

void ThreadedScanner::thread_proc() {
    while(true) {
        ScanTaskMessage message = task_queue.get_blocking();

        switch(message.type) {
            case ScanMessageType::SCAN_INITIAL: {
                char system_path_c[1000];
                XPLMGetSystemPath(system_path_c);
                boost::filesystem::path system_path(system_path_c);

                { // Blacklist
                    boost::filesystem::path blacklist_path = system_path / "Resources" / "plugins" / "drt_blacklist.txt";
                    blacklist = loadListFile(xplog, blacklist_path);
                    results_queue.push(ScanResults{ref_src_t::BLACKLIST, blacklist});
                }

                { // DR file
                    boost::filesystem::path dr_file = system_path / "Resources" / "plugins" / "DataRefs.txt";
                    std::vector<std::string> dr_refs = loadListFile(xplog, dr_file);
                    results_queue.push(ScanResults{ref_src_t::FILE, dr_refs});
                }

                { // CR file
                    boost::filesystem::path cr_file = system_path / "Resources" / "plugins" / "Commands.txt";
                    std::vector<std::string> cr_refs = loadListFile(xplog, cr_file);
                    results_queue.push(ScanResults{ref_src_t::FILE, cr_refs});
                }

                { // FWL
                    boost::filesystem::path fwl_scripts_dir = system_path / "Resources" / "plugins" / "FlyWithLua" / "Scripts";
                    std::vector<std::string> script_refs = scanLuaFolder(xplog, fwl_scripts_dir);
                    results_queue.push(ScanResults{ref_src_t::FILE, script_refs});
                }
            }
                break;
            case ScanMessageType::SCAN_PLUGIN: {
                results_queue.push(ScanResults{ref_src_t::BLACKLIST, blacklist});
                std::vector<std::string> plugin_refs = ::scanPluginFolder(xplog, message.path);
                results_queue.push(ScanResults{ref_src_t::PLUGIN, plugin_refs});
            }
                break;
            case ScanMessageType::SCAN_AIRCRAFT: {
                results_queue.push(ScanResults{ref_src_t::BLACKLIST, blacklist});
                std::vector<std::string> aircraft_refs = ::scanAircraft(xplog, message.path);
                results_queue.push(ScanResults{ref_src_t::AIRCRAFT, aircraft_refs});
            }
                break;
            case ScanMessageType::QUIT:
                return;
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "OSD.h"

#include "../../3RVX/LanguageTranslator.h"
#include "../../3RVX/Logger.h"
#include "../../3RVX/Settings.h"
#include "../resource.h"

void OSD::Initialize() {
    using std::placeholders::_1;

    _osdList = new ListView(LST_OSDS, *this);
    _osdList->OnItemChange = std::bind(&OSD::OnOSDListItemChange, this, _1);

    _volumeIcon = new Checkbox(CHK_VOLICON, *this);
    _subscribeVolEvents = new Checkbox(CHK_MONITORVOL, *this);
    _subscribeVolEvents->OnClick = [this]() {
        _forceLimit->Enabled(_subscribeVolEvents->Checked());
        return true;
    };
    _audioDeviceLabel = new Label(LBL_AUDIODEV, *this);
    _audioDevice = new ComboBox(CMB_AUDIODEV, *this);
    _audioTaperLabel = new Label(LBL_AUDIOTAPER, *this);
    _audioTaper = new ComboBox(CMB_AUDIOTAPER, *this);
    _audioTaperEdit = new EditBox(ED_AUDIOTAPER, *this);
    _limitLabel = new Label(LBL_LIMITER, *this);
    _limitSlider = new Slider(SLD_LIMITER, *this);
    _limitValue = new Label(LBL_LIMITVAL, *this);
    _limitSlider->Buddy(_limitValue);
    _limitSlider->OnSlide = [this]() {
        std::wstring value = std::to_wstring(_limitSlider->Position()) + L"%";
        _limitValue->Text(value);
        return true;
    };
    _forceLimit = new Checkbox(CHK_FORCELIMIT, *this);
    _muteLock = new Checkbox(CHK_MUTELOCK, *this);
    _volumeGroup = new GroupBox(GRP_VOLUME, *this);
    _volumeGroup->AddChildren({
        _volumeIcon,
        _subscribeVolEvents,
        _audioDeviceLabel, _audioDevice,
        _audioTaperLabel, _audioTaper, _audioTaperEdit,
        _limitLabel, _limitSlider, _limitValue,
        _forceLimit,
        _muteLock,
    });

    _ejectIcon = new Checkbox(CHK_EJECTICON, *this);
    _subscribeEjectEvents = new Checkbox(CHK_SUBSCRIBEEJECT, *this);
    _ejectGroup = new GroupBox(GRP_EJECT, *this);
    _ejectGroup->AddChildren({
        _ejectIcon,
        _subscribeEjectEvents,
    });

    _brightnessIcon = new Checkbox(CHK_BRIGHTICON, *this);
    _brightnessGroup = new GroupBox(GRP_BRIGHTNESS, *this);
    _brightnessGroup->AddChildren({
        _brightnessIcon,
    });

    _keyboardIcon = new Checkbox(CHK_KEYICON, *this);
    _caps = new Checkbox(CHK_ENABLECAPS, *this);
    _scroll = new Checkbox(CHK_ENABLESCROLL, *this);
    _num = new Checkbox(CHK_ENABLENUM, *this);
    _media = new Checkbox(CHK_ENABLEMK, *this);
    _keyboardGroup = new GroupBox(GRP_KEYBOARD, *this);
    _keyboardGroup->AddChildren({
        _keyboardIcon,
        _caps, _scroll, _num,
        _media,
    });

    /* Define groupbox order */
    GroupBox *groups[] = {
        _volumeGroup,
        _brightnessGroup,
        _ejectGroup,
        _keyboardGroup
    };

    /* Move other groupboxes into position (same as volume) */
    int groupX = _volumeGroup->X();
    int groupY = _volumeGroup->Y();
    for (GroupBox *grp : groups) {
        grp->X(groupX);
        grp->Y(groupY);
        grp->Visible(false);
        _groups.push_back(grp);
    }
}

void OSD::LoadSettings() {
    Settings *settings = Settings::Instance();
    LanguageTranslator *translator = settings->Translator();

    /* Translations */
    _osdStr = translator->Translate(_osdStr);
    _volumeStr = translator->Translate(_volumeStr);
    _brightnessStr = translator->Translate(_brightnessStr);
    _ejectStr = translator->Translate(_ejectStr);
    _keyboardStr = translator->Translate(_keyboardStr);

    _osdList->AddListExStyle(LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
    _osdList->AddColumn(_osdStr, (int) (_osdList->Width() * .97f));
    _osdList->AddItem(_volumeStr);
    _osdList->AddItem(_brightnessStr);
    _osdList->AddItem(_ejectStr);
    _osdList->AddItem(_keyboardStr);
    _osdList->Selection(0);

    _osdList->Checked(0, settings->VolumeOSDEnabled());
    _osdList->Checked(1, settings->BrightnessOSDEnabled());
    _osdList->Checked(2, settings->EjectOSDEnabled());
    _osdList->Checked(3, settings->KeyboardOSDEnabled());

    _volumeIcon->Checked(settings->NotifyIconEnabled());
    _subscribeVolEvents->Checked(settings->SubscribeVolumeEvents());
    _limitSlider->Position((int) (settings->VolumeLimiter() * 100.0f));
    _forceLimit->Enabled(_subscribeVolEvents->Checked());
    _muteLock->Checked(settings->MuteOnLock());

    _subscribeEjectEvents->Checked(settings->SubscribeEjectEvents());
}

void OSD::SaveSettings() {
    CLOG(L"Saving: OSD");
    Settings *settings = Settings::Instance();

    settings->VolumeOSDEnabled(_osdList->Checked(0));
    settings->BrightnessOSDEnabled(_osdList->Checked(1));
    settings->EjectOSDEnabled(_osdList->Checked(2));
    settings->KeyboardOSDEnabled(_osdList->Checked(3));

    settings->NotifyIconEnabled(_volumeIcon->Checked());
    settings->SubscribeVolumeEvents(_subscribeVolEvents->Checked());
    settings->VolumeLimiter(((float) _limitSlider->Position()) / 100.0f);
    settings->MuteOnLock(_muteLock->Checked());

    settings->SubscribeEjectEvents(_subscribeEjectEvents->Checked());
}

void OSD::ShowGroup(int group) {
    for (GroupBox *grp : _groups) {
        grp->Visible(false);
    }

    GroupBox *showGroup = _groups[group];
    if (_osdList->Checked(group)) {
        showGroup->Enable();
    } else {
        showGroup->Disable();
    }
    showGroup->Visible(true);
}

void OSD::OnOSDListItemChange(NMLISTVIEW *lv) {
    if (lv->uChanged & LVIF_STATE) {
        UINT oSimg = lv->uOldState & LVIS_STATEIMAGEMASK;
        UINT nSimg = lv->uNewState & LVIS_STATEIMAGEMASK;
        if (oSimg != nSimg) {
            /* Checkbox changed */
            if (_osdList->Selection() == lv->iItem) {
                /* Activate the Apply button */
                PropSheet_Changed(GetParent(SettingsTab::DialogHandle()), NULL);

                /* Check state at 0xF000 (1 = un, 2 = check). Shift to check: */
                _groups[lv->iItem]->Enabled((nSimg >> 13) > 0);
            }
        }

        if (lv->uNewState & LVIS_SELECTED) {
            ShowGroup(lv->iItem);
        }
    }
}
<commit_msg>Populate taper levels<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "OSD.h"

#include "../../3RVX/LanguageTranslator.h"
#include "../../3RVX/Logger.h"
#include "../../3RVX/Settings.h"
#include "../resource.h"

void OSD::Initialize() {
    using std::placeholders::_1;

    _osdList = new ListView(LST_OSDS, *this);
    _osdList->OnItemChange = std::bind(&OSD::OnOSDListItemChange, this, _1);

    _volumeIcon = new Checkbox(CHK_VOLICON, *this);
    _subscribeVolEvents = new Checkbox(CHK_MONITORVOL, *this);
    _subscribeVolEvents->OnClick = [this]() {
        _forceLimit->Enabled(_subscribeVolEvents->Checked());
        return true;
    };
    _audioDeviceLabel = new Label(LBL_AUDIODEV, *this);
    _audioDevice = new ComboBox(CMB_AUDIODEV, *this);
    _audioTaperLabel = new Label(LBL_AUDIOTAPER, *this);
    _audioTaper = new ComboBox(CMB_AUDIOTAPER, *this);
    _audioTaperEdit = new EditBox(ED_AUDIOTAPER, *this);
    _limitLabel = new Label(LBL_LIMITER, *this);
    _limitSlider = new Slider(SLD_LIMITER, *this);
    _limitValue = new Label(LBL_LIMITVAL, *this);
    _limitSlider->Buddy(_limitValue);
    _limitSlider->OnSlide = [this]() {
        std::wstring value = std::to_wstring(_limitSlider->Position()) + L"%";
        _limitValue->Text(value);
        return true;
    };
    _forceLimit = new Checkbox(CHK_FORCELIMIT, *this);
    _muteLock = new Checkbox(CHK_MUTELOCK, *this);
    _volumeGroup = new GroupBox(GRP_VOLUME, *this);
    _volumeGroup->AddChildren({
        _volumeIcon,
        _subscribeVolEvents,
        _audioDeviceLabel, _audioDevice,
        _audioTaperLabel, _audioTaper, _audioTaperEdit,
        _limitLabel, _limitSlider, _limitValue,
        _forceLimit,
        _muteLock,
    });

    _ejectIcon = new Checkbox(CHK_EJECTICON, *this);
    _subscribeEjectEvents = new Checkbox(CHK_SUBSCRIBEEJECT, *this);
    _ejectGroup = new GroupBox(GRP_EJECT, *this);
    _ejectGroup->AddChildren({
        _ejectIcon,
        _subscribeEjectEvents,
    });

    _brightnessIcon = new Checkbox(CHK_BRIGHTICON, *this);
    _brightnessGroup = new GroupBox(GRP_BRIGHTNESS, *this);
    _brightnessGroup->AddChildren({
        _brightnessIcon,
    });

    _keyboardIcon = new Checkbox(CHK_KEYICON, *this);
    _caps = new Checkbox(CHK_ENABLECAPS, *this);
    _scroll = new Checkbox(CHK_ENABLESCROLL, *this);
    _num = new Checkbox(CHK_ENABLENUM, *this);
    _media = new Checkbox(CHK_ENABLEMK, *this);
    _keyboardGroup = new GroupBox(GRP_KEYBOARD, *this);
    _keyboardGroup->AddChildren({
        _keyboardIcon,
        _caps, _scroll, _num,
        _media,
    });

    /* Define groupbox order */
    GroupBox *groups[] = {
        _volumeGroup,
        _brightnessGroup,
        _ejectGroup,
        _keyboardGroup
    };

    /* Move other groupboxes into position (same as volume) */
    int groupX = _volumeGroup->X();
    int groupY = _volumeGroup->Y();
    for (GroupBox *grp : groups) {
        grp->X(groupX);
        grp->Y(groupY);
        grp->Visible(false);
        _groups.push_back(grp);
    }
}

void OSD::LoadSettings() {
    Settings *settings = Settings::Instance();
    LanguageTranslator *translator = settings->Translator();

    /* Translations */
    _osdStr = translator->Translate(_osdStr);
    _volumeStr = translator->Translate(_volumeStr);
    _brightnessStr = translator->Translate(_brightnessStr);
    _ejectStr = translator->Translate(_ejectStr);
    _keyboardStr = translator->Translate(_keyboardStr);

    for (std::wstring level : settings->TaperLevelNames) {
        _audioTaper->AddItem(translator->Translate(level));
    }
    _osdList->AddListExStyle(LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
    _osdList->AddColumn(_osdStr, (int) (_osdList->Width() * .97f));
    _osdList->AddItem(_volumeStr);
    _osdList->AddItem(_brightnessStr);
    _osdList->AddItem(_ejectStr);
    _osdList->AddItem(_keyboardStr);
    _osdList->Selection(0);

    _osdList->Checked(0, settings->VolumeOSDEnabled());
    _osdList->Checked(1, settings->BrightnessOSDEnabled());
    _osdList->Checked(2, settings->EjectOSDEnabled());
    _osdList->Checked(3, settings->KeyboardOSDEnabled());

    _volumeIcon->Checked(settings->NotifyIconEnabled());
    _subscribeVolEvents->Checked(settings->SubscribeVolumeEvents());
    _limitSlider->Position((int) (settings->VolumeLimiter() * 100.0f));
    _forceLimit->Enabled(_subscribeVolEvents->Checked());
    _muteLock->Checked(settings->MuteOnLock());

    _subscribeEjectEvents->Checked(settings->SubscribeEjectEvents());
}

void OSD::SaveSettings() {
    CLOG(L"Saving: OSD");
    Settings *settings = Settings::Instance();

    settings->VolumeOSDEnabled(_osdList->Checked(0));
    settings->BrightnessOSDEnabled(_osdList->Checked(1));
    settings->EjectOSDEnabled(_osdList->Checked(2));
    settings->KeyboardOSDEnabled(_osdList->Checked(3));

    settings->NotifyIconEnabled(_volumeIcon->Checked());
    settings->SubscribeVolumeEvents(_subscribeVolEvents->Checked());
    settings->VolumeLimiter(((float) _limitSlider->Position()) / 100.0f);
    settings->MuteOnLock(_muteLock->Checked());

    settings->SubscribeEjectEvents(_subscribeEjectEvents->Checked());
}

void OSD::ShowGroup(int group) {
    for (GroupBox *grp : _groups) {
        grp->Visible(false);
    }

    GroupBox *showGroup = _groups[group];
    if (_osdList->Checked(group)) {
        showGroup->Enable();
    } else {
        showGroup->Disable();
    }
    showGroup->Visible(true);
}

void OSD::OnOSDListItemChange(NMLISTVIEW *lv) {
    if (lv->uChanged & LVIF_STATE) {
        UINT oSimg = lv->uOldState & LVIS_STATEIMAGEMASK;
        UINT nSimg = lv->uNewState & LVIS_STATEIMAGEMASK;
        if (oSimg != nSimg) {
            /* Checkbox changed */
            if (_osdList->Selection() == lv->iItem) {
                /* Activate the Apply button */
                PropSheet_Changed(GetParent(SettingsTab::DialogHandle()), NULL);

                /* Check state at 0xF000 (1 = un, 2 = check). Shift to check: */
                _groups[lv->iItem]->Enabled((nSimg >> 13) > 0);
            }
        }

        if (lv->uNewState & LVIS_SELECTED) {
            ShowGroup(lv->iItem);
        }
    }
}
<|endoftext|>