<commit_before>#include <unordered_map>

#include <QtCore/QString>

#include "lirch_plugin.h"
#include "edict_messages.h"
#include "grinder_messages.h"
#include "core/core_messages.h"
#include "blocker_messages.h"
#include "display_messages.h"

using namespace std;

namespace std
{
	template <>
	struct hash<QString>
	{
		size_t operator()(const QString& v) const
		{
			return std::hash<std::string>()(v.toStdString());
		}
	};
}

QString prefix(const QString &s)
{
	if (s.isEmpty() || s[0]!='/')
		return "";
	return s.left(s.indexOf(' '));
}

QString run_replacers(const unordered_multimap<QString, pair<QRegExp, QString>> &replacements, QString message)
{
	auto range=replacements.equal_range(prefix(message));
	for (auto &i=range.first; i!=range.second; ++i)
		message.replace(i->second.first, i->second.second);
	return message;
}

message handle_me(QString text, QString channel)
{
	if (text=="/me")
		return empty_message::create();
	//Remove the leading "/me "
	return me_edict_message::create(text.remove(0,4), channel);
}

message handle_quit(QString, QString)
{
	shutdown_message::create();
}

message handle_normal(QString text, QString channel)
{
	if (text.startsWith("/say"))
		text.remove(0,5);
	return edict_message::create(text, channel);
}

void run(plugin_pipe p, string name)
{
	p.write(registration_message::create(-30000, name, "raw_edict"));
	p.write(registration_message::create(-30000, name, "register_replacer"));
	p.write(registration_message::create(-30000, name, "register_handler"));
	unordered_multimap<QString, pair<QRegExp, QString>> text_replacements;
	unordered_map<QString, function<message (QString, QString)>> handlers;
	while (true)
	{
		message m=p.blocking_read();
		if (m.type=="shutdown")
		{
			//We don't have any cleanup to do, so just return
			return;
		}
		else if (m.type=="registration_status")
		{
			auto s=dynamic_cast<registration_status *>(m.getdata());
			if (!s)
				continue;
			//Retry 2000 times until we succeed
			if (!s->status)
			{
				if (s->priority>-32000)
					p.write(registration_message::create(s->priority-1, name, s->type));
			}
			else
			{
				if (s->type=="register_handler")
				{
					p.write(register_handler::create("", handle_normal));
					p.write(register_handler::create("/say", handle_normal));
					p.write(register_handler::create("/me", handle_me));
					p.write(register_handler::create("/q", handle_quit));
					p.write(register_handler::create("/quit", handle_quit));
					p.write(replacer_ready::create());
				}
				else if (s->type=="register_replacer")
				{
					p.write(handler_ready::create());
				}
			}
		}
		else if (m.type=="register_replacer")
		{
			auto i=dynamic_cast<register_replacer *>(m.getdata());
			if (!i)
				continue;
			text_replacements.insert({i->command, {i->pattern, i->replacement}});
		}
		else if (m.type=="register_handler")
		{
			auto i=dynamic_cast<register_handler *>(m.getdata());
			if (!i)
				continue;
			handlers.insert({i->command, i->handler});
		}
		else if (m.type=="raw_edict")
		{
			auto e=dynamic_cast<raw_edict_message *>(m.getdata());
			if (!e)
				continue;
			auto &str=e->contents;
			if (str.isEmpty())
				//We don't propagate empty messages (on principle)
				continue;
			auto pre=prefix(str);
			auto mod=run_replacers(text_replacements, str);
			if (prefix(mod)!=pre)
			{
				//Recurse if the type of the message has been changed
				p.write(raw_edict_message::create(mod, e->channel));
				continue;
			}
			if (handlers.count(pre)==0)
				//Nothing can handle this type of message, so complain
				//We should be using tr here since this is a
				//message to be displayed, but I'm not sure
				//which tr to use.
				p.write(notify_display_message::create(e->channel, QString("Unknown message type \"%1\"").arg(pre)));
			else
				p.write(handlers[pre](str, e->channel));
		}
		else
		{
			p.write(m.decrement_priority());
		}
	}
}
<commit_msg>Made the meat grinder use a real type<commit_after>#include <unordered_map>

#include <QtCore/QString>

#include "lirch_plugin.h"
#include "edict_messages.h"
#include "notify_messages.h"
#include "grinder_messages.h"
#include "core/core_messages.h"
#include "blocker_messages.h"
#include "display_messages.h"

using namespace std;

namespace std
{
	template <>
	struct hash<QString>
	{
		size_t operator()(const QString& v) const
		{
			return std::hash<std::string>()(v.toStdString());
		}
	};
}

QString prefix(const QString &s)
{
	if (s.isEmpty() || s[0]!='/')
		return "";
	return s.left(s.indexOf(' '));
}

QString run_replacers(const unordered_multimap<QString, pair<QRegExp, QString>> &replacements, QString message)
{
	auto range=replacements.equal_range(prefix(message));
	for (auto &i=range.first; i!=range.second; ++i)
		message.replace(i->second.first, i->second.second);
	return message;
}

message handle_me(QString text, QString channel)
{
	if (text=="/me")
		return empty_message::create();
	//Remove the leading "/me "
	return me_edict_message::create(text.remove(0,4), channel);
}

message handle_quit(QString, QString)
{
	shutdown_message::create();
}

message handle_normal(QString text, QString channel)
{
	if (text.startsWith("/say"))
		text.remove(0,5);
	return edict_message::create(text, channel);
}

void run(plugin_pipe p, string name)
{
	p.write(registration_message::create(-30000, name, "raw_edict"));
	p.write(registration_message::create(-30000, name, "register_replacer"));
	p.write(registration_message::create(-30000, name, "register_handler"));
	unordered_multimap<QString, pair<QRegExp, QString>> text_replacements;
	unordered_map<QString, function<message (QString, QString)>> handlers;
	while (true)
	{
		message m=p.blocking_read();
		if (m.type=="shutdown")
		{
			//We don't have any cleanup to do, so just return
			return;
		}
		else if (m.type=="registration_status")
		{
			auto s=dynamic_cast<registration_status *>(m.getdata());
			if (!s)
				continue;
			//Retry 2000 times until we succeed
			if (!s->status)
			{
				if (s->priority>-32000)
					p.write(registration_message::create(s->priority-1, name, s->type));
			}
			else
			{
				if (s->type=="register_handler")
				{
					p.write(register_handler::create("", handle_normal));
					p.write(register_handler::create("/say", handle_normal));
					p.write(register_handler::create("/me", handle_me));
					p.write(register_handler::create("/q", handle_quit));
					p.write(register_handler::create("/quit", handle_quit));
					p.write(replacer_ready::create());
				}
				else if (s->type=="register_replacer")
				{
					p.write(handler_ready::create());
				}
			}
		}
		else if (m.type=="register_replacer")
		{
			auto i=dynamic_cast<register_replacer *>(m.getdata());
			if (!i)
				continue;
			text_replacements.insert({i->command, {i->pattern, i->replacement}});
		}
		else if (m.type=="register_handler")
		{
			auto i=dynamic_cast<register_handler *>(m.getdata());
			if (!i)
				continue;
			handlers.insert({i->command, i->handler});
		}
		else if (m.type=="raw_edict")
		{
			auto e=dynamic_cast<raw_edict_message *>(m.getdata());
			if (!e)
				continue;
			auto &str=e->contents;
			if (str.isEmpty())
				//We don't propagate empty messages (on principle)
				continue;
			auto pre=prefix(str);
			auto mod=run_replacers(text_replacements, str);
			if (prefix(mod)!=pre)
			{
				//Recurse if the type of the message has been changed
				p.write(raw_edict_message::create(mod, e->channel));
				continue;
			}
			if (handlers.count(pre)==0)
				//Nothing can handle this type of message, so complain
				//We should be using tr here since this is a
				//message to be displayed, but I'm not sure
				//which tr to use.
				p.write(local_notify_message::create(e->channel, QString("Unknown message type \"%1\"").arg(pre)));
			else
				p.write(handlers[pre](str, e->channel));
		}
		else
		{
			p.write(m.decrement_priority());
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>Uncomment line setting operation mode of partInt components of RooProdPdf using current operation mode.<commit_after><|endoftext|>


<commit_before>#include "MultilineTextDialog.h"
#include "ui_MultilineTextDialog.h"

#include <QAbstractButton>

MultilineTextDialog::MultilineTextDialog(QWidget *parent)
	: QDialog(parent)
	, ui(new Ui::MultilineTextDialog)
{
	ui->setupUi(this);
}

MultilineTextDialog::~MultilineTextDialog()
{
	delete ui;
}

void MultilineTextDialog::setReadOnly(bool value)
{
	ui->plainTextEdit->setReadOnly(value);
}

void MultilineTextDialog::setText(const QString &text)
{
	ui->plainTextEdit->setPlainText(text);
}

QString MultilineTextDialog::getText() const
{
	return ui->plainTextEdit->toPlainText();
}

void MultilineTextDialog::on_buttonBox_clicked(QAbstractButton *button)
{
	switch (ui->buttonBox->buttonRole(button))
	{
		case QDialogButtonBox::AcceptRole:
			accept();
			break;

		case QDialogButtonBox::RejectRole:
			reject();
			break;

		default:
			break;
	}
}
<commit_msg>Fix MultilineTextDialog system buttons<commit_after>#include "MultilineTextDialog.h"
#include "ui_MultilineTextDialog.h"

#include <QAbstractButton>

MultilineTextDialog::MultilineTextDialog(QWidget *parent)
	: QDialog(parent)
	, ui(new Ui::MultilineTextDialog)
{
	ui->setupUi(this);

	setWindowFlags((windowFlags() & ~(Qt::WindowContextHelpButtonHint | Qt::WindowMinMaxButtonsHint)));
}

MultilineTextDialog::~MultilineTextDialog()
{
	delete ui;
}

void MultilineTextDialog::setReadOnly(bool value)
{
	ui->plainTextEdit->setReadOnly(value);
}

void MultilineTextDialog::setText(const QString &text)
{
	ui->plainTextEdit->setPlainText(text);
}

QString MultilineTextDialog::getText() const
{
	return ui->plainTextEdit->toPlainText();
}

void MultilineTextDialog::on_buttonBox_clicked(QAbstractButton *button)
{
	switch (ui->buttonBox->buttonRole(button))
	{
		case QDialogButtonBox::AcceptRole:
			accept();
			break;

		case QDialogButtonBox::RejectRole:
			reject();
			break;

		default:
			break;
	}
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/md5.h>

#include "fcgiapp.h"

#include "rgw_access.h"
#include "rgw_acl.h"
#include "rgw_user.h"
#include "rgw_op.h"
#include "rgw_rest.h"

#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>

#include "include/types.h"
#include "common/base64.h"
#include "common/BackTrace.h"

using namespace std;

#define CGI_PRINTF(stream, format, ...) do { \
   fprintf(stderr, format, __VA_ARGS__); \
   FCGX_FPrintF(stream, format, __VA_ARGS__); \
} while (0)

/*
 * ?get the canonical amazon-style header for something?
 */
static void get_canon_amz_hdr(struct req_state *s, string& dest)
{
  dest = "";
  map<string, string>::iterator iter;
  for (iter = s->x_amz_map.begin(); iter != s->x_amz_map.end(); ++iter) {
    dest.append(iter->first);
    dest.append(":");
    dest.append(iter->second);
    dest.append("\n");
  }
}

/*
 * ?get the canonical representation of the object's location
 */
static void get_canon_resource(struct req_state *s, string& dest)
{
  if (s->host_bucket) {
    dest = "/";
    dest.append(s->host_bucket);
  }

  dest.append(s->path_name_url.c_str());

  string& sub = s->args.get_sub_resource();
  if (sub.size() > 0) {
    dest.append("?");
    dest.append(sub);
  }
}

/*
 * get the header authentication  information required to
 * compute a request's signature
 */
static void get_auth_header(struct req_state *s, string& dest, bool qsr)
{
  dest = "";
  if (s->method)
    dest = s->method;
  dest.append("\n");

  const char *md5 = FCGX_GetParam("HTTP_CONTENT_MD5", s->fcgx->envp);
  if (md5)
    dest.append(md5);
  dest.append("\n");

  const char *type = FCGX_GetParam("CONTENT_TYPE", s->fcgx->envp);
  if (type)
    dest.append(type);
  dest.append("\n");

  string date;
  if (qsr) {
    date = s->args.get("Expires");
  } else {
    const char *str = FCGX_GetParam("HTTP_DATE", s->fcgx->envp);
    if (str)
      date = str;
  }

  if (date.size())
      dest.append(date);
  dest.append("\n");

  string canon_amz_hdr;
  get_canon_amz_hdr(s, canon_amz_hdr);
  dest.append(canon_amz_hdr);

  string canon_resource;
  get_canon_resource(s, canon_resource);
  dest.append(canon_resource);
}

/*
 * calculate the sha1 value of a given msg and key
 */
static void calc_hmac_sha1(const char *key, int key_len,
                           const char *msg, int msg_len,
                           char *dest, int *len) /* dest should be large enough to hold result */
{
  char hex_str[128];
  unsigned char *result = HMAC(EVP_sha1(), key, key_len, (const unsigned char *)msg,
                               msg_len, (unsigned char *)dest, (unsigned int *)len);

  buf_to_hex(result, *len, hex_str);

  cerr << "hmac=" << hex_str << std::endl;
}

/*
 * verify that a signed request comes from the keyholder
 * by checking the signature against our locally-computed version
 */
static bool verify_signature(struct req_state *s)
{
  bool qsr = false;
  string auth_id;
  string auth_sign;

  if (!s->http_auth || !(*s->http_auth)) {
    auth_id = s->args.get("AWSAccessKeyId");
    if (auth_id.size()) {
      url_decode(s->args.get("Signature"), auth_sign);

      string date = s->args.get("Expires");
      time_t exp = atoll(date.c_str());
      time_t now;
      time(&now);
      if (now >= exp)
        return false;

      qsr = true;
    } else {
      /* anonymous access */
      rgw_get_anon_user(s->user);
      return true;
    }
  } else {
    if (strncmp(s->http_auth, "AWS ", 4))
      return false;
    string auth_str(s->http_auth + 4);
    int pos = auth_str.find(':');
    if (pos < 0)
      return false;

    auth_id = auth_str.substr(0, pos);
    auth_sign = auth_str.substr(pos + 1);
  }

  /* first get the user info */
  if (rgw_get_user_info(auth_id, s->user) < 0) {
    cerr << "error reading user info, uid=" << auth_id << " can't authenticate" << std::endl;
    return false;
  }

  /* now verify signature */

  string auth_hdr;
  get_auth_header(s, auth_hdr, qsr);
  cerr << "auth_hdr:" << std::endl << auth_hdr << std::endl;

  const char *key = s->user.secret_key.c_str();
  int key_len = strlen(key);

  char hmac_sha1[EVP_MAX_MD_SIZE];
  int len;
  calc_hmac_sha1(key, key_len, auth_hdr.c_str(), auth_hdr.size(), hmac_sha1, &len);

  char b64[64]; /* 64 is really enough */
  int ret = encode_base64(hmac_sha1, len, b64, sizeof(b64));
  if (ret < 0) {
    cerr << "encode_base64 failed" << std::endl;
    return false;
  }

  cerr << "b64=" << b64 << std::endl;
  cerr << "auth_sign=" << auth_sign << std::endl;
  cerr << "compare=" << auth_sign.compare(b64) << std::endl;
  return (auth_sign.compare(b64) == 0);
}

static sighandler_t sighandler_segv;
static sighandler_t sighandler_usr1;

/*
 * ?print out the C++ errors to log in case it fails
 */
static void sigsegv_handler(int signum)
{
  BackTrace bt(0);
  bt.print(cerr);

  signal(SIGSEGV, sighandler_segv);
}

static void godown_handler(int signum)
{
  FCGX_ShutdownPending();
  signal(SIGUSR1, sighandler_usr1);
}

/*
 * start up the RADOS connection and then handle HTTP messages as they come in
 */
int main(int argc, char *argv[])
{
  struct req_state s;
  struct fcgx_state fcgx;
  RGWHandler_REST rgwhandler;

  if (!RGWAccess::init_storage_provider("rados", argc, argv)) {
    cerr << "couldn't init storage provider" << std::endl;
    return 5; //EIO
  }

  sighandler_segv = signal(SIGSEGV, sigsegv_handler);
  sighandler_usr1 = signal(SIGUSR1, godown_handler);

  while (FCGX_Accept(&fcgx.in, &fcgx.out, &fcgx.err, &fcgx.envp) >= 0)
  {
    rgwhandler.init_state(&s, &fcgx);

    int ret = read_acls(&s);
    if (ret < 0) {
      switch (ret) {
      case -ENOENT:
        break;
      default:
        cerr << "could not read acls" << " ret=" << ret << std::endl;
        abort_early(&s, -EPERM);
        continue;
      }
    }
    ret = verify_signature(&s);
    if (!ret) {
      cerr << "signature DOESN'T match" << std::endl;
      abort_early(&s, -EPERM);
      continue;
    }

    ret = rgwhandler.read_permissions();
    if (ret < 0) {
      abort_early(&s, ret);
      continue;
    }

    RGWOp *op = rgwhandler.get_op();
    if (op) {
      op->execute();
    }
  }
  return 0;
}

<commit_msg>rgw: exit after 5 seconds from SIGUSR1 anyway<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/md5.h>

#include "fcgiapp.h"

#include "rgw_access.h"
#include "rgw_acl.h"
#include "rgw_user.h"
#include "rgw_op.h"
#include "rgw_rest.h"

#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>

#include "include/types.h"
#include "common/base64.h"
#include "common/BackTrace.h"

using namespace std;

#define CGI_PRINTF(stream, format, ...) do { \
   fprintf(stderr, format, __VA_ARGS__); \
   FCGX_FPrintF(stream, format, __VA_ARGS__); \
} while (0)

/*
 * ?get the canonical amazon-style header for something?
 */
static void get_canon_amz_hdr(struct req_state *s, string& dest)
{
  dest = "";
  map<string, string>::iterator iter;
  for (iter = s->x_amz_map.begin(); iter != s->x_amz_map.end(); ++iter) {
    dest.append(iter->first);
    dest.append(":");
    dest.append(iter->second);
    dest.append("\n");
  }
}

/*
 * ?get the canonical representation of the object's location
 */
static void get_canon_resource(struct req_state *s, string& dest)
{
  if (s->host_bucket) {
    dest = "/";
    dest.append(s->host_bucket);
  }

  dest.append(s->path_name_url.c_str());

  string& sub = s->args.get_sub_resource();
  if (sub.size() > 0) {
    dest.append("?");
    dest.append(sub);
  }
}

/*
 * get the header authentication  information required to
 * compute a request's signature
 */
static void get_auth_header(struct req_state *s, string& dest, bool qsr)
{
  dest = "";
  if (s->method)
    dest = s->method;
  dest.append("\n");

  const char *md5 = FCGX_GetParam("HTTP_CONTENT_MD5", s->fcgx->envp);
  if (md5)
    dest.append(md5);
  dest.append("\n");

  const char *type = FCGX_GetParam("CONTENT_TYPE", s->fcgx->envp);
  if (type)
    dest.append(type);
  dest.append("\n");

  string date;
  if (qsr) {
    date = s->args.get("Expires");
  } else {
    const char *str = FCGX_GetParam("HTTP_DATE", s->fcgx->envp);
    if (str)
      date = str;
  }

  if (date.size())
      dest.append(date);
  dest.append("\n");

  string canon_amz_hdr;
  get_canon_amz_hdr(s, canon_amz_hdr);
  dest.append(canon_amz_hdr);

  string canon_resource;
  get_canon_resource(s, canon_resource);
  dest.append(canon_resource);
}

/*
 * calculate the sha1 value of a given msg and key
 */
static void calc_hmac_sha1(const char *key, int key_len,
                           const char *msg, int msg_len,
                           char *dest, int *len) /* dest should be large enough to hold result */
{
  char hex_str[128];
  unsigned char *result = HMAC(EVP_sha1(), key, key_len, (const unsigned char *)msg,
                               msg_len, (unsigned char *)dest, (unsigned int *)len);

  buf_to_hex(result, *len, hex_str);

  cerr << "hmac=" << hex_str << std::endl;
}

/*
 * verify that a signed request comes from the keyholder
 * by checking the signature against our locally-computed version
 */
static bool verify_signature(struct req_state *s)
{
  bool qsr = false;
  string auth_id;
  string auth_sign;

  if (!s->http_auth || !(*s->http_auth)) {
    auth_id = s->args.get("AWSAccessKeyId");
    if (auth_id.size()) {
      url_decode(s->args.get("Signature"), auth_sign);

      string date = s->args.get("Expires");
      time_t exp = atoll(date.c_str());
      time_t now;
      time(&now);
      if (now >= exp)
        return false;

      qsr = true;
    } else {
      /* anonymous access */
      rgw_get_anon_user(s->user);
      return true;
    }
  } else {
    if (strncmp(s->http_auth, "AWS ", 4))
      return false;
    string auth_str(s->http_auth + 4);
    int pos = auth_str.find(':');
    if (pos < 0)
      return false;

    auth_id = auth_str.substr(0, pos);
    auth_sign = auth_str.substr(pos + 1);
  }

  /* first get the user info */
  if (rgw_get_user_info(auth_id, s->user) < 0) {
    cerr << "error reading user info, uid=" << auth_id << " can't authenticate" << std::endl;
    return false;
  }

  /* now verify signature */

  string auth_hdr;
  get_auth_header(s, auth_hdr, qsr);
  cerr << "auth_hdr:" << std::endl << auth_hdr << std::endl;

  const char *key = s->user.secret_key.c_str();
  int key_len = strlen(key);

  char hmac_sha1[EVP_MAX_MD_SIZE];
  int len;
  calc_hmac_sha1(key, key_len, auth_hdr.c_str(), auth_hdr.size(), hmac_sha1, &len);

  char b64[64]; /* 64 is really enough */
  int ret = encode_base64(hmac_sha1, len, b64, sizeof(b64));
  if (ret < 0) {
    cerr << "encode_base64 failed" << std::endl;
    return false;
  }

  cerr << "b64=" << b64 << std::endl;
  cerr << "auth_sign=" << auth_sign << std::endl;
  cerr << "compare=" << auth_sign.compare(b64) << std::endl;
  return (auth_sign.compare(b64) == 0);
}

static sighandler_t sighandler_segv;
static sighandler_t sighandler_usr1;
static sighandler_t sighandler_alrm;

/*
 * ?print out the C++ errors to log in case it fails
 */
static void sigsegv_handler(int signum)
{
  BackTrace bt(0);
  bt.print(cerr);

  signal(signum, sighandler_segv);
}

static void godown_handler(int signum)
{
  FCGX_ShutdownPending();
  signal(signum, sighandler_usr1);
  alarm(5);
}

static void godown_alarm(int signum)
{
  _exit(0);
}

/*
 * start up the RADOS connection and then handle HTTP messages as they come in
 */
int main(int argc, char *argv[])
{
  struct req_state s;
  struct fcgx_state fcgx;
  RGWHandler_REST rgwhandler;

  if (!RGWAccess::init_storage_provider("rados", argc, argv)) {
    cerr << "couldn't init storage provider" << std::endl;
    return 5; //EIO
  }

  sighandler_segv = signal(SIGSEGV, sigsegv_handler);
  sighandler_usr1 = signal(SIGUSR1, godown_handler);
  sighandler_alrm = signal(SIGALRM, godown_alarm);

  while (FCGX_Accept(&fcgx.in, &fcgx.out, &fcgx.err, &fcgx.envp) >= 0)
  {
    rgwhandler.init_state(&s, &fcgx);

    int ret = read_acls(&s);
    if (ret < 0) {
      switch (ret) {
      case -ENOENT:
        break;
      default:
        cerr << "could not read acls" << " ret=" << ret << std::endl;
        abort_early(&s, -EPERM);
        continue;
      }
    }
    ret = verify_signature(&s);
    if (!ret) {
      cerr << "signature DOESN'T match" << std::endl;
      abort_early(&s, -EPERM);
      continue;
    }

    ret = rgwhandler.read_permissions();
    if (ret < 0) {
      abort_early(&s, ret);
      continue;
    }

    RGWOp *op = rgwhandler.get_op();
    if (op) {
      op->execute();
    }
  }
  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gridwizard.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:30:01 $
 *
 *  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 _EXTENSIONS_DBP_GRIDWIZARD_HXX_
#define _EXTENSIONS_DBP_GRIDWIZARD_HXX_

#ifndef _EXTENSIONS_DBP_CONTROLWIZARD_HXX
#include "controlwizard.hxx"
#endif
#ifndef _EXTENSIONS_DBP_COMMONPAGESDBP_HXX_
#include "commonpagesdbp.hxx"
#endif

//.........................................................................
namespace dbp
{
//.........................................................................

    //=====================================================================
    //= OGridSettings
    //=====================================================================
    struct OGridSettings : public OControlWizardSettings
    {
        ::com::sun::star::uno::Sequence< ::rtl::OUString >      aSelectedFields;
    };

    //=====================================================================
    //= OGridWizard
    //=====================================================================
    class OGridWizard : public OControlWizard
    {
    protected:
        OGridSettings   m_aSettings;
        sal_Bool        m_bHadDataSelection : 1;

    public:
        OGridWizard(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObjectModel,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
        );

        OGridSettings& getSettings() { return m_aSettings; }

    protected:
        // OWizardMachine overridables
        virtual ::svt::OWizardPage* createPage( WizardState _nState );
        virtual WizardState         determineNextState( WizardState _nCurrentState );
        virtual void                enterState( WizardState _nState );
        virtual sal_Bool            leaveState( WizardState _nState );

        virtual sal_Bool onFinish(sal_Int32 _nResult);

        virtual sal_Bool approveControl(sal_Int16 _nClassId);

    protected:
        void implApplySettings();
    };

    //=====================================================================
    //= OGridPage
    //=====================================================================
    class OGridPage : public OControlWizardPage
    {
    public:
        OGridPage( OGridWizard* _pParent, const ResId& _rId ) : OControlWizardPage(_pParent, _rId) { }

    protected:
        OGridSettings& getSettings() { return static_cast<OGridWizard*>(getDialog())->getSettings(); }
    };

    //=====================================================================
    //= OGridFieldsSelection
    //=====================================================================
    class OGridFieldsSelection : public OGridPage
    {
    protected:
        FixedLine       m_aFrame;
        FixedText       m_aExistFieldsLabel;
        ListBox         m_aExistFields;
        PushButton      m_aSelectOne;
        PushButton      m_aSelectAll;
        PushButton      m_aDeselectOne;
        PushButton      m_aDeselectAll;
        FixedText       m_aSelFieldsLabel;
        ListBox         m_aSelFields;

    public:
        OGridFieldsSelection( OGridWizard* _pParent );

    protected:
        // TabPage overridables
        virtual void ActivatePage();

        // OWizardPage overridables
        virtual void        initializePage();
        virtual sal_Bool    commitPage(COMMIT_REASON _eReason);
        sal_Bool            determineNextButtonState();

    protected:
        DECL_LINK(OnMoveOneEntry, PushButton*);
        DECL_LINK(OnMoveAllEntries, PushButton*);
        DECL_LINK(OnEntrySelected, ListBox*);
        DECL_LINK(OnEntryDoubleClicked, ListBox*);

        void implCheckButtons();
        void implApplySettings();

        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > implGetColumns(sal_Bool _bShowError = sal_True);
    };

//.........................................................................
}   // namespace dbp
//.........................................................................

#endif // _EXTENSIONS_DBP_GRIDWIZARD_HXX_

<commit_msg>INTEGRATION: CWS odbmacros2 (1.4.424); FILE MERGED 2008/02/11 11:14:55 fs 1.4.424.3: IWizardPage is COMMIT_REASON is deprecated - replace usages with CommitPageReason, while I have an svtools-incompatible CWS 2008/01/30 13:19:50 fs 1.4.424.2: canAdvance made const 2008/01/15 09:52:42 fs 1.4.424.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gridwizard.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 18:41:06 $
 *
 *  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 _EXTENSIONS_DBP_GRIDWIZARD_HXX_
#define _EXTENSIONS_DBP_GRIDWIZARD_HXX_

#ifndef _EXTENSIONS_DBP_CONTROLWIZARD_HXX
#include "controlwizard.hxx"
#endif
#ifndef _EXTENSIONS_DBP_COMMONPAGESDBP_HXX_
#include "commonpagesdbp.hxx"
#endif

//.........................................................................
namespace dbp
{
//.........................................................................

    //=====================================================================
    //= OGridSettings
    //=====================================================================
    struct OGridSettings : public OControlWizardSettings
    {
        ::com::sun::star::uno::Sequence< ::rtl::OUString >      aSelectedFields;
    };

    //=====================================================================
    //= OGridWizard
    //=====================================================================
    class OGridWizard : public OControlWizard
    {
    protected:
        OGridSettings   m_aSettings;
        sal_Bool        m_bHadDataSelection : 1;

    public:
        OGridWizard(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObjectModel,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
        );

        OGridSettings& getSettings() { return m_aSettings; }

    protected:
        // OWizardMachine overridables
        virtual ::svt::OWizardPage* createPage( WizardState _nState );
        virtual WizardState         determineNextState( WizardState _nCurrentState ) const;
        virtual void                enterState( WizardState _nState );
        virtual sal_Bool            leaveState( WizardState _nState );

        virtual sal_Bool onFinish(sal_Int32 _nResult);

        virtual sal_Bool approveControl(sal_Int16 _nClassId);

    protected:
        void implApplySettings();
    };

    //=====================================================================
    //= OGridPage
    //=====================================================================
    class OGridPage : public OControlWizardPage
    {
    public:
        OGridPage( OGridWizard* _pParent, const ResId& _rId ) : OControlWizardPage(_pParent, _rId) { }

    protected:
        OGridSettings& getSettings() { return static_cast<OGridWizard*>(getDialog())->getSettings(); }
    };

    //=====================================================================
    //= OGridFieldsSelection
    //=====================================================================
    class OGridFieldsSelection : public OGridPage
    {
    protected:
        FixedLine       m_aFrame;
        FixedText       m_aExistFieldsLabel;
        ListBox         m_aExistFields;
        PushButton      m_aSelectOne;
        PushButton      m_aSelectAll;
        PushButton      m_aDeselectOne;
        PushButton      m_aDeselectAll;
        FixedText       m_aSelFieldsLabel;
        ListBox         m_aSelFields;

    public:
        OGridFieldsSelection( OGridWizard* _pParent );

    protected:
        // TabPage overridables
        virtual void ActivatePage();

        // OWizardPage overridables
        virtual void        initializePage();
        virtual sal_Bool    commitPage( CommitPageReason _eReason );
        virtual bool        canAdvance() const;

    protected:
        DECL_LINK(OnMoveOneEntry, PushButton*);
        DECL_LINK(OnMoveAllEntries, PushButton*);
        DECL_LINK(OnEntrySelected, ListBox*);
        DECL_LINK(OnEntryDoubleClicked, ListBox*);

        void implCheckButtons();
        void implApplySettings();

        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > implGetColumns(sal_Bool _bShowError = sal_True);
    };

//.........................................................................
}   // namespace dbp
//.........................................................................

#endif // _EXTENSIONS_DBP_GRIDWIZARD_HXX_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: docholder.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 20:01:16 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DOCHOLDER_HXX_
#define _DOCHOLDER_HXX_

#include "common.h"

#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <drafts/com/sun/star/frame/XLayoutManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_
#include <com/sun/star/util/XCloseListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFYLISTENER_HPP_
#include <com/sun/star/util/XModifyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif

class EmbedDocument_Impl;
class Interceptor;
class CIIAObj;

namespace winwrap {
    class CHatchWin;
}

class DocumentHolder :
    public ::cppu::WeakImplHelper4<
                        ::com::sun::star::util::XCloseListener,
                          ::com::sun::star::frame::XTerminateListener,
                        ::com::sun::star::util::XModifyListener,
                        ::drafts::com::sun::star::ui::XDockingAreaAcceptor>
{
private:
    BOOL                        m_bAllowInPlace;
    LPOLEINPLACESITE            m_pIOleIPSite;
    LPOLEINPLACEFRAME           m_pIOleIPFrame;
    LPOLEINPLACEUIWINDOW        m_pIOleIPUIWindow;
    winwrap::CHatchWin*         m_pCHatchWin;

    EmbedDocument_Impl*         m_pOLEInterface;
    Interceptor*                m_pInterceptor;
    CIIAObj*                    m_pImpIOleIPActiveObject;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;

    RECT                          m_aBorder;

    // contains top level system window data
    bool                          m_bOnDeactivate;
    HWND                          m_hWndxWinParent;
    HWND                          m_hWndxWinCont;
    HMENU                         m_nMenuHandle;
    HMENU                         m_nMenuShared;
    HOLEMENU                      m_nOLEMenu;
    com::sun::star::uno::Reference<
        com::sun::star::awt::XWindow> m_xEditWindow;

    com::sun::star::uno::Reference<
        com::sun::star::awt::XWindow> m_xContainerWindow;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XModel > m_xDocument;

    ::com::sun::star::uno::Reference<
    ::drafts::com::sun::star::frame::XLayoutManager> m_xLayoutManager;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XFrame > m_xFrame;

    ::rtl::OUString m_aContainerName,m_aDocumentNamePart,m_aFilterName;

    CComPtr< IDispatch > m_pIDispatch;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XFrame > DocumentFrame();

public:

    // the instance to which we belong
    static HINSTANCE m_hInstance;

    HWND GetEditWindowParentHandle() const
    {
        return m_hWndxWinParent;
    }

    void SetContainerWindowHandle(HWND hWndxWinCont)
    {
        m_hWndxWinCont = hWndxWinCont;
    }

    DocumentHolder(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::lang::XMultiServiceFactory >& xFactory,
        EmbedDocument_Impl *pOLEInterface);

    ~DocumentHolder();

    // Methods for inplace activation

    BOOL isActive() const;
    void DisableInplaceActivation(BOOL);
    HRESULT InPlaceActivate(LPOLECLIENTSITE,BOOL);
    void InPlaceDeactivate(void);
    HRESULT UIActivate();
    void UIDeactivate();
    BOOL InPlaceMenuCreate(void);
    BOOL InPlaceMenuDestroy(void);

    void OpenIntoWindow(void);
    BOOL Undo(void);

    // further methods

    void SetDocument(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::frame::XModel >& xDoc
    );

    void CloseDocument();
    void CloseFrame();
    void ClearInterceptor();
    void FreeOffice();

    void resizeWin( const SIZEL& rNewSize );

    void setTitle(const rtl::OUString& aDocumentName);
    rtl::OUString getTitle() const { return m_aDocumentNamePart; }

    void setContainerName(const rtl::OUString& aContainerName);
    rtl::OUString getContainerName() const { return m_aContainerName; }
    void OnPosRectChanged(LPRECT lpRect) const;
    void show();

    /** hides the document window, even in case of an external container
     *  side managed window.
     */

    void hide();

    IDispatch* GetIDispatch();

    HRESULT GetDocumentBorder( RECT *pRect );
    // HRESULT SetVisArea( const RECTL *pRect );
    // HRESULT GetVisArea( RECTL *pRect );
    HRESULT SetExtent( const SIZEL *pSize );
    HRESULT GetExtent( SIZEL *pSize );
    // sets extension on the hatchwindow
    HRESULT SetContRects(LPCRECT pRect);
    HRESULT SetObjectRects(LPCRECT aRect, LPCRECT aClip);

    HWND GetTopMostWinHandle() const
    {
        return m_hWndxWinParent;
     }

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XModel >
    GetDocument() const
    {
        return m_xDocument;
    }

    // XEventListener
    virtual void SAL_CALL
    disposing( const com::sun::star::lang::EventObject& aSource );

    // XCloseListener
    virtual void SAL_CALL
    queryClosing(
        const com::sun::star::lang::EventObject& aSource,
        sal_Bool bGetsOwnership
    )
        throw(
            ::com::sun::star::util::CloseVetoException
        );

    virtual void SAL_CALL
    notifyClosing(
        const com::sun::star::lang::EventObject& aSource
    );

    // XTerminateListener
    virtual void SAL_CALL
    queryTermination(
        const com::sun::star::lang::EventObject& aSource
    )
        throw(
            ::com::sun::star::frame::TerminationVetoException
        );

    virtual void SAL_CALL
    notifyTermination(
        const com::sun::star::lang::EventObject& aSource
    );

    // XModifyListener
    virtual void SAL_CALL
    modified(
        const ::com::sun::star::lang::EventObject& aEvent
    )
        throw (
            ::com::sun::star::uno::RuntimeException
        );

    // XDockingAreaAcceptor

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::awt::XWindow> SAL_CALL
    getContainerWindow(
    )
        throw (
            ::com::sun::star::uno::RuntimeException
        );

    virtual sal_Bool SAL_CALL
    requestDockingAreaSpace(
        const ::com::sun::star::awt::Rectangle& RequestedSpace
    )
        throw(
            ::com::sun::star::uno::RuntimeException
        );

    virtual void SAL_CALL
    setDockingAreaSpace(
        const ::com::sun::star::awt::Rectangle& BorderSpace
    )
        throw (
            ::com::sun::star::uno::RuntimeException
        );
};

#endif

<commit_msg>INTEGRATION: CWS removedrafts (1.14.8); FILE MERGED 2005/02/17 12:41:54 cd 1.14.8.1: #i42557# move UNOIDL types from drafts to com<commit_after>/*************************************************************************
 *
 *  $RCSfile: docholder.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:53:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DOCHOLDER_HXX_
#define _DOCHOLDER_HXX_

#include "common.h"

#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <com/sun/star/frame/XLayoutManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_
#include <com/sun/star/util/XCloseListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFYLISTENER_HPP_
#include <com/sun/star/util/XModifyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif

class EmbedDocument_Impl;
class Interceptor;
class CIIAObj;

namespace winwrap {
    class CHatchWin;
}

class DocumentHolder :
    public ::cppu::WeakImplHelper4<
                        ::com::sun::star::util::XCloseListener,
                          ::com::sun::star::frame::XTerminateListener,
                        ::com::sun::star::util::XModifyListener,
                        ::com::sun::star::ui::XDockingAreaAcceptor>
{
private:
    BOOL                        m_bAllowInPlace;
    LPOLEINPLACESITE            m_pIOleIPSite;
    LPOLEINPLACEFRAME           m_pIOleIPFrame;
    LPOLEINPLACEUIWINDOW        m_pIOleIPUIWindow;
    winwrap::CHatchWin*         m_pCHatchWin;

    EmbedDocument_Impl*         m_pOLEInterface;
    Interceptor*                m_pInterceptor;
    CIIAObj*                    m_pImpIOleIPActiveObject;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;

    RECT                          m_aBorder;

    // contains top level system window data
    bool                          m_bOnDeactivate;
    HWND                          m_hWndxWinParent;
    HWND                          m_hWndxWinCont;
    HMENU                         m_nMenuHandle;
    HMENU                         m_nMenuShared;
    HOLEMENU                      m_nOLEMenu;
    com::sun::star::uno::Reference<
        com::sun::star::awt::XWindow> m_xEditWindow;

    com::sun::star::uno::Reference<
        com::sun::star::awt::XWindow> m_xContainerWindow;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XModel > m_xDocument;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XLayoutManager> m_xLayoutManager;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XFrame > m_xFrame;

    ::rtl::OUString m_aContainerName,m_aDocumentNamePart,m_aFilterName;

    CComPtr< IDispatch > m_pIDispatch;

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XFrame > DocumentFrame();

public:

    // the instance to which we belong
    static HINSTANCE m_hInstance;

    HWND GetEditWindowParentHandle() const
    {
        return m_hWndxWinParent;
    }

    void SetContainerWindowHandle(HWND hWndxWinCont)
    {
        m_hWndxWinCont = hWndxWinCont;
    }

    DocumentHolder(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::lang::XMultiServiceFactory >& xFactory,
        EmbedDocument_Impl *pOLEInterface);

    ~DocumentHolder();

    // Methods for inplace activation

    BOOL isActive() const;
    void DisableInplaceActivation(BOOL);
    HRESULT InPlaceActivate(LPOLECLIENTSITE,BOOL);
    void InPlaceDeactivate(void);
    HRESULT UIActivate();
    void UIDeactivate();
    BOOL InPlaceMenuCreate(void);
    BOOL InPlaceMenuDestroy(void);

    void OpenIntoWindow(void);
    BOOL Undo(void);

    // further methods

    void SetDocument(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::frame::XModel >& xDoc
    );

    void CloseDocument();
    void CloseFrame();
    void ClearInterceptor();
    void FreeOffice();

    void resizeWin( const SIZEL& rNewSize );

    void setTitle(const rtl::OUString& aDocumentName);
    rtl::OUString getTitle() const { return m_aDocumentNamePart; }

    void setContainerName(const rtl::OUString& aContainerName);
    rtl::OUString getContainerName() const { return m_aContainerName; }
    void OnPosRectChanged(LPRECT lpRect) const;
    void show();

    /** hides the document window, even in case of an external container
     *  side managed window.
     */

    void hide();

    IDispatch* GetIDispatch();

    HRESULT GetDocumentBorder( RECT *pRect );
    // HRESULT SetVisArea( const RECTL *pRect );
    // HRESULT GetVisArea( RECTL *pRect );
    HRESULT SetExtent( const SIZEL *pSize );
    HRESULT GetExtent( SIZEL *pSize );
    // sets extension on the hatchwindow
    HRESULT SetContRects(LPCRECT pRect);
    HRESULT SetObjectRects(LPCRECT aRect, LPCRECT aClip);

    HWND GetTopMostWinHandle() const
    {
        return m_hWndxWinParent;
     }

    ::com::sun::star::uno::Reference<
    ::com::sun::star::frame::XModel >
    GetDocument() const
    {
        return m_xDocument;
    }

    // XEventListener
    virtual void SAL_CALL
    disposing( const com::sun::star::lang::EventObject& aSource );

    // XCloseListener
    virtual void SAL_CALL
    queryClosing(
        const com::sun::star::lang::EventObject& aSource,
        sal_Bool bGetsOwnership
    )
        throw(
            ::com::sun::star::util::CloseVetoException
        );

    virtual void SAL_CALL
    notifyClosing(
        const com::sun::star::lang::EventObject& aSource
    );

    // XTerminateListener
    virtual void SAL_CALL
    queryTermination(
        const com::sun::star::lang::EventObject& aSource
    )
        throw(
            ::com::sun::star::frame::TerminationVetoException
        );

    virtual void SAL_CALL
    notifyTermination(
        const com::sun::star::lang::EventObject& aSource
    );

    // XModifyListener
    virtual void SAL_CALL
    modified(
        const ::com::sun::star::lang::EventObject& aEvent
    )
        throw (
            ::com::sun::star::uno::RuntimeException
        );

    // XDockingAreaAcceptor

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::awt::XWindow> SAL_CALL
    getContainerWindow(
    )
        throw (
            ::com::sun::star::uno::RuntimeException
        );

    virtual sal_Bool SAL_CALL
    requestDockingAreaSpace(
        const ::com::sun::star::awt::Rectangle& RequestedSpace
    )
        throw(
            ::com::sun::star::uno::RuntimeException
        );

    virtual void SAL_CALL
    setDockingAreaSpace(
        const ::com::sun::star::awt::Rectangle& BorderSpace
    )
        throw (
            ::com::sun::star::uno::RuntimeException
        );
};

#endif

<|endoftext|>


<commit_before>// -*- mode: c++; coding: utf-8 -*-
/*! @file exclusivity.cpp
    @brief Inplementation of Exclusivity class
*/
#include "exclusivity.hpp"

#include <functional>
#include <unordered_map>
#include <csignal>

#include <boost/dynamic_bitset.hpp>

#include <cxxwtils/debug.hpp>
#include <cxxwtils/exception.hpp>
#include <cxxwtils/iostr.hpp>
#include <cxxwtils/numeric.hpp>
#include <cxxwtils/math.hpp>
#include <cxxwtils/eigen.hpp>
#include <cxxwtils/itertools.hpp>
#include <cxxwtils/gz.hpp>

namespace {
    bool SIGINT_RAISED = false;
}

namespace likeligrid {

const std::vector<double> ExclusivityModel::STEPS_ = {0.4, 0.2, 0.1, 0.05, 0.02, 0.01};
const std::vector<size_t> ExclusivityModel::BREAKS_ = {5, 5, 5, 6, 5, 5};

ExclusivityModel::ExclusivityModel(std::istream& genotypes,
    const size_t max_sites,
    const size_t max_results):
    names_(wtl::read_header(genotypes)),
    genotypes_(wtl::eigen::read_array<size_t>(genotypes, names_.size())),
    max_results_(max_results)
    {HERE;

    const ArrayXu raw_s_sample = genotypes_.rowwise().sum().array();
    nsam_with_s_.assign(raw_s_sample.maxCoeff() + 1, 0);
    for (Eigen::Index i=0; i<raw_s_sample.size(); ++i) {
        ++nsam_with_s_[raw_s_sample[i]];
    }
    std::cerr << "Original N_s: " << nsam_with_s_ << std::endl;
    if (nsam_with_s_.size() - 1 < max_sites) {
        std::cerr << "Note: -s is too large" << std::endl;
    } else {
        nsam_with_s_.resize(max_sites + 1);
        std::cerr << "Filtered N_s: " << nsam_with_s_ << std::endl;
    }
    const auto final_max_s = nsam_with_s_.size() - 1;
    genotypes_ = wtl::eigen::filter(genotypes_, raw_s_sample <= final_max_s);

    const Eigen::ArrayXd s_pathway = genotypes_.colwise().sum().cast<double>();
    w_pathway_ = s_pathway / s_pathway.sum();
    a_pathway_ = genotypes_.unaryExpr([](size_t x){
        if (x > 0) {return --x;} else {return x;}
    }).colwise().sum().cast<double>();
    lnp_const_ = (s_pathway * w_pathway_.log()).sum();
    for (Eigen::Index i=0; i<genotypes_.rows(); ++i) {
        auto v = wtl::eigen::valarray(genotypes_.row(i));
        lnp_const_ += std::log(wtl::polynomial(v));
    }
    std::cerr << "s_pathway_: " << s_pathway.transpose() << std::endl;
    std::cerr << "w_pathway_: " << w_pathway_.transpose() << std::endl;
    std::cerr << "a_pathway_: " << a_pathway_.transpose() << std::endl;
    std::cerr << "lnp_const_: " << lnp_const_ << std::endl;

    index_iters_.reserve(nsam_with_s_.size());
    std::vector<size_t> indices(genotypes_.cols());
    std::iota(std::begin(indices), std::end(indices), 0);
    for (size_t s=0; s<=nsam_with_s_.size(); ++s) {
        index_iters_.emplace_back(std::vector<std::vector<size_t>>(s, indices));
    }
    std::signal(SIGINT, [](int signum){
        if (signum == SIGINT) SIGINT_RAISED = true;
        // TODO: how to handle other signum?
    });
}

inline std::vector<Eigen::ArrayXd>
make_vicinity(const Eigen::ArrayXd& center, const size_t breaks, const double radius, const double max=1.0) {
    std::vector<Eigen::ArrayXd> axes;
    axes.reserve(center.size());
    for (const double x: wtl::eigen::vector(center)){
        Eigen::ArrayXd axis = Eigen::ArrayXd::LinSpaced(breaks, x + radius, x - radius);
        axes.push_back(wtl::eigen::filter(axis, (0.0 < axis) * (axis < max)));
    }
    return axes;
}

void ExclusivityModel::run(const std::string& infile) {HERE;
    init_axes(infile);
    if (stage_ == STEPS_.size()) {
        std::cerr << "Done: step size = " << STEPS_.back() << std::endl;
        --stage_;
        max_results_ = -1;
        if (true) {
            axes_.assign(names_.size(), Eigen::ArrayXd::LinSpaced(100, 1.0, 0.01));
            run_impl(name_outfile("uniaxis"), wtl::itertools::uniaxis(axes_, mle_params_));
        } else {
            //TODO
            const auto axes = make_vicinity(mle_params_, 21, 1.0);
            const auto vicinity = make_vicinity(mle_params_, 3, 0.01, 1.2);
            run_impl(name_outfile("prototype"), wtl::itertools::prototype(axes, vicinity));
        }
        return;
    }
    const std::string outfile = name_outfile(infile);
    if (read_results(outfile) && start_ == 0) {
        std::cerr << outfile << " is already completed:" << std::endl;
        run(outfile);
        return;
    }
    std::cerr << "Start: " << start_ << std::endl;
    for (size_t j=0; j<names_.size(); ++j) {
        std::cerr << names_[j] << ": " << axes_[j].transpose() << std::endl;
    }
    run_impl(outfile, wtl::itertools::product(axes_));
    if (outfile != "/dev/null") {
        run(outfile);
    }
}

void ExclusivityModel::init_axes(const std::string& infile) {HERE;
    if (mle_params_.size() > 0 || read_results(infile)) {
        std::cerr << mle_params_.transpose() << std::endl;
        if (start_ > 0) {
            throw std::runtime_error("infile must be a complete result");
        }
        axes_ = make_vicinity(mle_params_, BREAKS_.at(stage_), STEPS_.at(stage_), 2.0);
        ++stage_;
    } else {
        const double step = STEPS_[0];
        const size_t breaks = BREAKS_[0];
        axes_.assign(names_.size(), Eigen::VectorXd::LinSpaced(breaks, 2.0, step).array());
    }
}

std::string ExclusivityModel::name_outfile(const std::string& infile) const {HERE;
    std::string prefix = "output";
    if (infile == "/dev/null") {
        return infile;
    } else if (!infile.empty()) {
        prefix = wtl::split(infile, "-")[0];
    }
    std::ostringstream oss(prefix, std::ios::ate);
    oss << "-s" << nsam_with_s_.size() - 1
        << "-step" << STEPS_.at(stage_)
        << ".tsv.gz";
    return oss.str();
}

void ExclusivityModel::run_impl(const std::string& outfile, wtl::itertools::Generator<Eigen::ArrayXd>&& gen) {HERE;
    std::cerr << "\nWriting to " << outfile << std::endl;
    const auto max_count = gen.max_count();
    auto buffer = wtl::make_oss();
    wtl::ogzstream fout(outfile);
    buffer << "##max_count=" << max_count << "\n";
    buffer << "##max_sites=" << nsam_with_s_.size() - 1 << "\n";
    buffer << "##step=" << STEPS_.at(stage_) << "\n";
    buffer << "loglik\t" << wtl::join(names_, "\t") << "\n";
    double max_ll = std::numeric_limits<double>::lowest();
    for (const auto& params: gen(start_)) {
        if (gen.count() % 10000 == 0) {  // snapshot for long run
            std::cerr << "\r" << gen.count() << " in " << max_count << std::flush;
            fout << buffer.str();
            fout.strict_sync();
            buffer.str("");
        }

        double loglik = 0.0;
        loglik += (a_pathway_ * params.log()).sum();
        for (size_t s=0; s<nsam_with_s_.size(); ++s) {
            loglik -= nsam_with_s_[s] * std::log(calc_denom(w_pathway_, params, s));
        }

        buffer << (loglik += lnp_const_) << "\t"
               << wtl::join(wtl::eigen::vector(params), "\t") << "\n";
        if (loglik > max_ll) {
            max_ll = loglik;
            mle_params_ = params;
        }
        if (SIGINT_RAISED) {throw wtl::ExitSuccess("KeyboardInterrupt");}
    }
    fout << buffer.str();
}

double ExclusivityModel::calc_denom(
    const Eigen::ArrayXd& w_pathway,
    const Eigen::ArrayXd& x_pathway,
    const size_t num_mutations) {

    if (num_mutations < 2) return 1.0;
    auto& iter = index_iters_[num_mutations];
    double sum_prob = 0.0;
    boost::dynamic_bitset<> bits(x_pathway.size());
    for (const auto& indices: iter()) {
        double p = 1.0;
        for (const auto j: indices) {
            p *= w_pathway[j];
            if (bits[j]) p *= x_pathway[j];
            bits.set(j);
        }
        sum_prob += p;
        bits.reset();
    }
    iter.reset();
    return sum_prob;
}

std::ostream& ExclusivityModel::write_genotypes(std::ostream& ost, const bool header) const {HERE;
    if (header) {ost << wtl::join(names_, "\t") << "\n";}
    return ost << genotypes_.format(wtl::eigen::tsv());
}

bool ExclusivityModel::read_results(const std::string& infile) {HERE;
    wtl::igzstream ist(infile);
    if (!ist || infile == "/dev/null") return false;
    std::cerr << "Reading: " << infile << std::endl;
    const size_t max_count = read_metadata(ist);
    start_ = read_body(ist);
    if (start_ == max_count) start_ = 0;
    return true;
}

size_t ExclusivityModel::read_metadata(std::istream& ist) {HERE;
    std::string buffer;
    std::getline(ist, buffer);
    const size_t max_count = std::stoul(wtl::split(buffer, "=")[1]);
    std::getline(ist, buffer);
    const size_t max_sites = std::stoul(wtl::split(buffer, "=")[1]);
    if (nsam_with_s_.size() - 1 != max_sites) {
        std::cerr << "Note: -s is different between arg and file\n";
    }
    std::getline(ist, buffer);
    const double step = std::stod(wtl::split(buffer, "=")[1]);
    auto pred = std::bind(wtl::equal<double>, std::placeholders::_1, step);
    const auto it = std::find_if(STEPS_.begin(), STEPS_.end(), pred);
    if (it == STEPS_.end()) throw std::runtime_error("invalid step size");
    stage_ = it - STEPS_.begin();
    return max_count;
}

size_t ExclusivityModel::read_body(std::istream& ist) {HERE;
    std::string buffer;
    ist >> buffer; // loglik
    std::getline(ist, buffer); // header
    buffer.erase(0, 1); // \t
    if (names_ != wtl::split(buffer, "\t")) {
        std::cerr << names_ << std::endl;
        std::cerr << wtl::split(buffer, "\t") << std::endl;
        throw std::runtime_error("Column names are wrong");
    }
    size_t i = 0;
    double max_ll = std::numeric_limits<double>::lowest();
    while (std::getline(ist, buffer)) {
        std::istringstream iss(buffer);
        std::istream_iterator<double> it(iss);
        if (*it > max_ll) {
            max_ll = *it;
            mle_params_ = wtl::eigen::ArrayX(std::vector<double>(++it, std::istream_iterator<double>()));
        }
    }
    return i;
}

void ExclusivityModel::unit_test() {HERE;
    std::string geno = "A\tB\n0\t1\n1\t0\n1\t1\n0\t2\n";
    std::istringstream iss(geno);
    ExclusivityModel model(iss);
    model.write_genotypes(std::cerr);
    model.run("/dev/null");
}

} // namespace likeligrid
<commit_msg>Fix resuming function<commit_after>// -*- mode: c++; coding: utf-8 -*-
/*! @file exclusivity.cpp
    @brief Inplementation of Exclusivity class
*/
#include "exclusivity.hpp"

#include <functional>
#include <unordered_map>
#include <csignal>

#include <boost/dynamic_bitset.hpp>

#include <cxxwtils/debug.hpp>
#include <cxxwtils/exception.hpp>
#include <cxxwtils/iostr.hpp>
#include <cxxwtils/numeric.hpp>
#include <cxxwtils/math.hpp>
#include <cxxwtils/eigen.hpp>
#include <cxxwtils/itertools.hpp>
#include <cxxwtils/gz.hpp>

namespace {
    bool SIGINT_RAISED = false;
}

namespace likeligrid {

const std::vector<double> ExclusivityModel::STEPS_ = {0.4, 0.2, 0.1, 0.05, 0.02, 0.01};
const std::vector<size_t> ExclusivityModel::BREAKS_ = {5, 5, 5, 6, 5, 5};

ExclusivityModel::ExclusivityModel(std::istream& genotypes,
    const size_t max_sites,
    const size_t max_results):
    names_(wtl::read_header(genotypes)),
    genotypes_(wtl::eigen::read_array<size_t>(genotypes, names_.size())),
    max_results_(max_results)
    {HERE;

    const ArrayXu raw_s_sample = genotypes_.rowwise().sum().array();
    nsam_with_s_.assign(raw_s_sample.maxCoeff() + 1, 0);
    for (Eigen::Index i=0; i<raw_s_sample.size(); ++i) {
        ++nsam_with_s_[raw_s_sample[i]];
    }
    std::cerr << "Original N_s: " << nsam_with_s_ << std::endl;
    if (nsam_with_s_.size() - 1 < max_sites) {
        std::cerr << "Note: -s is too large" << std::endl;
    } else {
        nsam_with_s_.resize(max_sites + 1);
        std::cerr << "Filtered N_s: " << nsam_with_s_ << std::endl;
    }
    const auto final_max_s = nsam_with_s_.size() - 1;
    genotypes_ = wtl::eigen::filter(genotypes_, raw_s_sample <= final_max_s);

    const Eigen::ArrayXd s_pathway = genotypes_.colwise().sum().cast<double>();
    w_pathway_ = s_pathway / s_pathway.sum();
    a_pathway_ = genotypes_.unaryExpr([](size_t x){
        if (x > 0) {return --x;} else {return x;}
    }).colwise().sum().cast<double>();
    lnp_const_ = (s_pathway * w_pathway_.log()).sum();
    for (Eigen::Index i=0; i<genotypes_.rows(); ++i) {
        auto v = wtl::eigen::valarray(genotypes_.row(i));
        lnp_const_ += std::log(wtl::polynomial(v));
    }
    std::cerr << "s_pathway_: " << s_pathway.transpose() << std::endl;
    std::cerr << "w_pathway_: " << w_pathway_.transpose() << std::endl;
    std::cerr << "a_pathway_: " << a_pathway_.transpose() << std::endl;
    std::cerr << "lnp_const_: " << lnp_const_ << std::endl;

    index_iters_.reserve(nsam_with_s_.size());
    std::vector<size_t> indices(genotypes_.cols());
    std::iota(std::begin(indices), std::end(indices), 0);
    for (size_t s=0; s<=nsam_with_s_.size(); ++s) {
        index_iters_.emplace_back(std::vector<std::vector<size_t>>(s, indices));
    }
    std::signal(SIGINT, [](int signum){
        if (signum == SIGINT) SIGINT_RAISED = true;
        // TODO: how to handle other signum?
    });
}

inline std::vector<Eigen::ArrayXd>
make_vicinity(const Eigen::ArrayXd& center, const size_t breaks, const double radius, const double max=1.0) {
    std::vector<Eigen::ArrayXd> axes;
    axes.reserve(center.size());
    for (const double x: wtl::eigen::vector(center)){
        Eigen::ArrayXd axis = Eigen::ArrayXd::LinSpaced(breaks, x + radius, x - radius);
        axes.push_back(wtl::eigen::filter(axis, (0.0 < axis) * (axis < max)));
    }
    return axes;
}

void ExclusivityModel::run(const std::string& infile) {HERE;
    init_axes(infile);
    if (stage_ == STEPS_.size()) {
        std::cerr << "Done: step size = " << STEPS_.back() << std::endl;
        --stage_;
        max_results_ = -1;
        if (true) {
            axes_.assign(names_.size(), Eigen::ArrayXd::LinSpaced(100, 1.0, 0.01));
            run_impl(name_outfile("uniaxis"), wtl::itertools::uniaxis(axes_, mle_params_));
        } else {
            //TODO
            const auto axes = make_vicinity(mle_params_, 21, 1.0);
            const auto vicinity = make_vicinity(mle_params_, 3, 0.01, 1.2);
            run_impl(name_outfile("prototype"), wtl::itertools::prototype(axes, vicinity));
        }
        return;
    }
    const std::string outfile = name_outfile(infile);
    if (read_results(outfile) && start_ == 0) {
        std::cerr << outfile << " is already completed:" << std::endl;
        run(outfile);
        return;
    }
    std::cerr << "Start: " << start_ << std::endl;
    for (size_t j=0; j<names_.size(); ++j) {
        std::cerr << names_[j] << ": " << axes_[j].transpose() << std::endl;
    }
    run_impl(outfile, wtl::itertools::product(axes_));
    if (outfile != "/dev/null") {
        run(outfile);
    }
}

void ExclusivityModel::init_axes(const std::string& infile) {HERE;
    if (mle_params_.size() > 0 || read_results(infile)) {
        std::cerr << mle_params_.transpose() << std::endl;
        if (start_ > 0) {
            throw std::runtime_error("infile must be a complete result");
        }
        axes_ = make_vicinity(mle_params_, BREAKS_.at(stage_), STEPS_.at(stage_), 2.0);
        ++stage_;
    } else {
        const double step = STEPS_[0];
        const size_t breaks = BREAKS_[0];
        axes_.assign(names_.size(), Eigen::VectorXd::LinSpaced(breaks, 2.0, step).array());
    }
}

std::string ExclusivityModel::name_outfile(const std::string& infile) const {HERE;
    std::string prefix = "output";
    if (infile == "/dev/null") {
        return infile;
    } else if (!infile.empty()) {
        prefix = wtl::split(infile, "-")[0];
    }
    std::ostringstream oss(prefix, std::ios::ate);
    oss << "-s" << nsam_with_s_.size() - 1
        << "-step" << STEPS_.at(stage_)
        << ".tsv.gz";
    return oss.str();
}

void ExclusivityModel::run_impl(const std::string& outfile, wtl::itertools::Generator<Eigen::ArrayXd>&& gen) {HERE;
    const auto max_count = gen.max_count();
    auto buffer = wtl::make_oss();
    std::ios::openmode mode = std::ios::out;
    if (start_ == 0) {
        buffer << "##max_count=" << max_count << "\n";
        buffer << "##max_sites=" << nsam_with_s_.size() - 1 << "\n";
        buffer << "##step=" << STEPS_.at(stage_) << "\n";
        buffer << "loglik\t" << wtl::join(names_, "\t") << "\n";
    } else {
        mode |= std::ios::app;
    }
    std::cerr << "\nWriting to " << outfile << std::endl;
    wtl::ogzstream fout(outfile, mode);
    double max_ll = std::numeric_limits<double>::lowest();
    for (const auto& params: gen(start_)) {
        if (gen.count() % 10000 == 0) {  // snapshot for long run
            std::cerr << "\r" << gen.count() << " in " << max_count << std::flush;
            fout << buffer.str();
            fout.strict_sync();
            buffer.str("");
        }

        double loglik = 0.0;
        loglik += (a_pathway_ * params.log()).sum();
        for (size_t s=0; s<nsam_with_s_.size(); ++s) {
            loglik -= nsam_with_s_[s] * std::log(calc_denom(w_pathway_, params, s));
        }

        buffer << (loglik += lnp_const_) << "\t"
               << wtl::join(wtl::eigen::vector(params), "\t") << "\n";
        if (loglik > max_ll) {
            max_ll = loglik;
            mle_params_ = params;
        }
        if (SIGINT_RAISED) {throw wtl::ExitSuccess("KeyboardInterrupt");}
    }
    fout << buffer.str();
}

double ExclusivityModel::calc_denom(
    const Eigen::ArrayXd& w_pathway,
    const Eigen::ArrayXd& x_pathway,
    const size_t num_mutations) {

    if (num_mutations < 2) return 1.0;
    auto& iter = index_iters_[num_mutations];
    double sum_prob = 0.0;
    boost::dynamic_bitset<> bits(x_pathway.size());
    for (const auto& indices: iter()) {
        double p = 1.0;
        for (const auto j: indices) {
            p *= w_pathway[j];
            if (bits[j]) p *= x_pathway[j];
            bits.set(j);
        }
        sum_prob += p;
        bits.reset();
    }
    iter.reset();
    return sum_prob;
}

std::ostream& ExclusivityModel::write_genotypes(std::ostream& ost, const bool header) const {HERE;
    if (header) {ost << wtl::join(names_, "\t") << "\n";}
    return ost << genotypes_.format(wtl::eigen::tsv());
}

bool ExclusivityModel::read_results(const std::string& infile) {HERE;
    wtl::igzstream ist(infile);
    if (!ist || infile == "/dev/null") return false;
    std::cerr << "Reading: " << infile << std::endl;
    const size_t max_count = read_metadata(ist);
    start_ = read_body(ist);
    if (start_ == max_count) start_ = 0;
    return true;
}

size_t ExclusivityModel::read_metadata(std::istream& ist) {HERE;
    std::string buffer;
    std::getline(ist, buffer);
    const size_t max_count = std::stoul(wtl::split(buffer, "=")[1]);
    std::getline(ist, buffer);
    const size_t max_sites = std::stoul(wtl::split(buffer, "=")[1]);
    if (nsam_with_s_.size() - 1 != max_sites) {
        std::cerr << "Note: -s is different between arg and file\n";
    }
    std::getline(ist, buffer);
    const double step = std::stod(wtl::split(buffer, "=")[1]);
    auto pred = std::bind(wtl::equal<double>, std::placeholders::_1, step);
    const auto it = std::find_if(STEPS_.begin(), STEPS_.end(), pred);
    if (it == STEPS_.end()) throw std::runtime_error("invalid step size");
    stage_ = it - STEPS_.begin();
    return max_count;
}

size_t ExclusivityModel::read_body(std::istream& ist) {HERE;
    std::string buffer;
    ist >> buffer; // loglik
    std::getline(ist, buffer); // header
    buffer.erase(0, 1); // \t
    if (names_ != wtl::split(buffer, "\t")) {
        std::cerr << names_ << std::endl;
        std::cerr << wtl::split(buffer, "\t") << std::endl;
        throw std::runtime_error("Column names are wrong");
    }
    size_t i = 0;
    double max_ll = std::numeric_limits<double>::lowest();
    while (std::getline(ist, buffer)) {
        ++i;
        std::istringstream iss(buffer);
        std::istream_iterator<double> it(iss);
        if (*it > max_ll) {
            max_ll = *it;
            mle_params_ = wtl::eigen::ArrayX(std::vector<double>(++it, std::istream_iterator<double>()));
        }
    }
    return i;
}

void ExclusivityModel::unit_test() {HERE;
    std::string geno = "A\tB\n0\t1\n1\t0\n1\t1\n0\t2\n";
    std::istringstream iss(geno);
    ExclusivityModel model(iss);
    model.write_genotypes(std::cerr);
    model.run("/dev/null");
}

} // namespace likeligrid
<|endoftext|>


<commit_before>#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

#include "ros_visitor.hpp"

#include <QStandardPaths>
#include <algorithm>
#include <filesystem>
#include <memory>
#include <nlohmann/json_fwd.hpp>
#include <regex>
#include <string>

#include "cognitive_function.hpp"
#include "inja/inja.hpp"
#include "node.hpp"

using namespace std;
namespace fs = std::filesystem;

vector<string> split(string s, const char separator) {
    istringstream ss;
    ss.str(s);
    string segment;
    std::vector<std::string> seglist;
    while (std::getline(ss, segment, separator)) {
        seglist.push_back(segment);
    }
    return seglist;
}

RosVisitor::RosVisitor(const Architecture& architecture, const string& ws_path)
    : Visitor(architecture), ws_path(ws_path) {
    fs::path tpl_path;

    for (auto p :
         QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)) {
        tpl_path = fs::path(p.toStdString()) / "templates" / "ros";
        cout << "Looking for ROS templates in " << tpl_path << endl;

        if (fs::exists(tpl_path)) {
            break;
        }
    }

    if (!tpl_path.empty()) {
        cout << "Using ROS templates found at " << tpl_path << endl;
        env_ = make_unique<inja::Environment>(
            (tpl_path / "default").string() + fs::path::preferred_separator,
            ws_path + fs::path::preferred_separator);

        env_->set_line_statement("$$$$$");
        env_->set_trim_blocks(true);
        env_->set_lstrip_blocks(true);

        env_main_node_ = make_unique<inja::Environment>(
            (tpl_path / "main_node").string() + fs::path::preferred_separator,
            ws_path + fs::path::preferred_separator);

        env_main_node_->set_line_statement("$$$$$");
        env_main_node_->set_trim_blocks(true);
        env_main_node_->set_lstrip_blocks(true);
    } else {
        cout << "[EE] ROS templates not found! Can not generate ROS nodes."
             << endl;
    }
}

void RosVisitor::startUp() {
    data_["path"] = ws_path;
    data_["name"] = architecture.name;
    data_["id"] = make_id(architecture.name);
    data_["boxology_version"] = STR(BOXOLOGY_VERSION);
    data_["version"] = architecture.version;
    data_["description"] = architecture.description;
}

void RosVisitor::tearDown() {
    if (!env_) return;

    ///////////////////////////////////////////////////////
    // Create parent node with main launchfile
    //
    vector<string> main_node_tpls{"package.xml", "CMakeLists.txt",
                                  "launch/start_all.launch"};

    auto id = make_id(architecture.name);
    auto rel_path = fs::path("src") / id;
    auto abs_path = fs::path(ws_path) / rel_path;
    auto launch_path = abs_path / "launch";
    fs::create_directories(launch_path);  // will also create 'path'

    for (const auto& file : main_node_tpls) {
        auto tpl = env_main_node_->parse_template(file);
        env_main_node_->write(tpl, data_, (rel_path / file).string());
    }

    ///////////////////////////////////////////////////////
    // Create all the nodes
    //
    vector<string> default_tpls{"package.xml", "CMakeLists.txt",
                                "src/main.cpp"};

    for (auto node : data_["nodes"]) {
        string id(node["id"]);
        cout << "Generating " << node["name"] << " as node [" << id << "]..."
             << endl;

        auto rel_path = fs::path("src") / id;
        auto abs_path = fs::path(ws_path) / rel_path;
        auto src_path = abs_path / "src";
        fs::create_directories(src_path);  // will also create 'path'

        for (const auto& file : default_tpls) {
            auto tpl = env_->parse_template(file);
            // cout << "\t- " << (abs_path / file).string() << endl;
            env_->write(tpl, node, (rel_path / file).string());
        }
    }

    cout << "Generation of ROS nodes complete. The generated nodes can be "
            "found in "
         << ws_path << endl;
}

void RosVisitor::beginNodes() {}

void RosVisitor::onNode(shared_ptr<const Node> node) {
    // ignore TF nodes
    if (node->name() == "TF" || node->name() == "tf") return;

    nlohmann::json jnode;

    auto name = node->name().substr(0, node->name().find("["));

    jnode["id"] = make_id(name);
    jnode["name"] = name;
    jnode["label"] = COGNITIVE_FUNCTION_NAMES.at(node->cognitive_function());

    jnode["dependencies"] = nlohmann::json::array();

    jnode["boxology_version"] = STR(BOXOLOGY_VERSION);

    if (node->sub_architecture) {
        jnode["version"] = node->sub_architecture->version;
        jnode["description"] = node->sub_architecture->description;
    } else {
        jnode["version"] = "1.0.0";
        jnode["description"] = "";
    }

    //////////////////////////////////////////////
    // Ports
    //
    jnode["inputs"] = nlohmann::json::array();
    jnode["outputs"] = nlohmann::json::array();
    for (auto p : node->ports()) {
        nlohmann::json jport;

        bool isInput = (p->direction == Port::Direction::IN);

        auto name = p->name;

        regex topic_regex("`(.*)` \\[(.*)\\]", regex_constants::ECMAScript);
        smatch topic_matches;
        regex tf_regex("`tf: (.*)`", regex_constants::ECMAScript);
        smatch tf_matches;

        if (regex_search(name, topic_matches, topic_regex)) {
            jport["type"] = "topic";
            jport["topic"] = topic_matches[1];
            jport["short"] = split(jport["topic"], '/').back();
            auto type = split(topic_matches[2], '/');
            jport["datatype"] = {type.front(), type.back()};
            jnode["dependencies"].push_back({type.front(), type.back()});

            cout << "[II] Node " << jnode["id"] << ": "
                 << (isInput ? "subscribes to" : "publishes") << " topic "
                 << jport["topic"] << " (short: " << jport["shorttopic"]
                 << ") of type " << jport["type"] << endl;

        } else if (regex_search(name, tf_matches, tf_regex)) {
            jport["type"] = "tf";
            jport["frame"] = tf_matches[1];

            if (isInput) {
                jport["datatype"] = {"tf", "transform_listener"};
            }else {
                jport["datatype"] = {"tf", "transform_broadcaster"};
            }
            jnode["dependencies"].push_back(jport["datatype"]);

            cout << "[II] Node " << jnode["id"] << ": "
                 << (isInput ? "listen to" : "broadcasts") << " TF frame "
                 << jport["frame"] << endl;
        } else {
            jport["type"] = "undefined";
            jport["description"] = name;
            jport["topic"] = make_id(name);
            jport["short"] = make_id(name);
            jport["datatype"] = {"std_msgs", "Empty"};
            jnode["dependencies"].push_back(jport["datatype"]);
        }

        if (isInput) {
            jnode["inputs"].push_back(jport);
        } else {
            jnode["outputs"].push_back(jport);
        }
    }

    data_["nodes"].push_back(jnode);

    nodes_.push_back(node);
}

void RosVisitor::endNodes() {}

void RosVisitor::beginConnections() {}

void RosVisitor::onConnection(shared_ptr<const Connection> connection) {}

<commit_msg>[ros] ensure dependencies are added only once<commit_after>#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

#include "ros_visitor.hpp"

#include <QStandardPaths>
#include <algorithm>
#include <filesystem>
#include <memory>
#include <nlohmann/json_fwd.hpp>
#include <regex>
#include <string>

#include "cognitive_function.hpp"
#include "inja/inja.hpp"
#include "node.hpp"

using namespace std;
namespace fs = std::filesystem;

vector<string> split(string s, const char separator) {
    istringstream ss;
    ss.str(s);
    string segment;
    std::vector<std::string> seglist;
    while (std::getline(ss, segment, separator)) {
        seglist.push_back(segment);
    }
    return seglist;
}

bool contains(const nlohmann::json& container, const nlohmann::json& value) {
    for (const auto& i : container) {
        if (i[0] == value[0] && i[1] == value[1]) {
            return true;
        }
    }
    return false;
}

RosVisitor::RosVisitor(const Architecture& architecture, const string& ws_path)
    : Visitor(architecture), ws_path(ws_path) {
    fs::path tpl_path;

    for (auto p :
         QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)) {
        tpl_path = fs::path(p.toStdString()) / "templates" / "ros";
        cout << "Looking for ROS templates in " << tpl_path << endl;

        if (fs::exists(tpl_path)) {
            break;
        }
    }

    if (!tpl_path.empty()) {
        cout << "Using ROS templates found at " << tpl_path << endl;
        env_ = make_unique<inja::Environment>(
            (tpl_path / "default").string() + fs::path::preferred_separator,
            ws_path + fs::path::preferred_separator);

        env_->set_line_statement("$$$$$");
        env_->set_trim_blocks(true);
        env_->set_lstrip_blocks(true);

        env_main_node_ = make_unique<inja::Environment>(
            (tpl_path / "main_node").string() + fs::path::preferred_separator,
            ws_path + fs::path::preferred_separator);

        env_main_node_->set_line_statement("$$$$$");
        env_main_node_->set_trim_blocks(true);
        env_main_node_->set_lstrip_blocks(true);
    } else {
        cout << "[EE] ROS templates not found! Can not generate ROS nodes."
             << endl;
    }
}

void RosVisitor::startUp() {
    data_["path"] = ws_path;
    data_["name"] = architecture.name;
    data_["id"] = make_id(architecture.name);
    data_["boxology_version"] = STR(BOXOLOGY_VERSION);
    data_["version"] = architecture.version;
    data_["description"] = architecture.description;
}

void RosVisitor::tearDown() {
    if (!env_) return;

    ///////////////////////////////////////////////////////
    // Create parent node with main launchfile
    //
    vector<string> main_node_tpls{"package.xml", "CMakeLists.txt",
                                  "launch/start_all.launch"};

    auto id = make_id(architecture.name);
    auto rel_path = fs::path("src") / id;
    auto abs_path = fs::path(ws_path) / rel_path;
    auto launch_path = abs_path / "launch";
    fs::create_directories(launch_path);  // will also create 'path'

    for (const auto& file : main_node_tpls) {
        auto tpl = env_main_node_->parse_template(file);
        env_main_node_->write(tpl, data_, (rel_path / file).string());
    }

    ///////////////////////////////////////////////////////
    // Create all the nodes
    //
    vector<string> default_tpls{"package.xml", "CMakeLists.txt",
                                "src/main.cpp"};

    for (auto node : data_["nodes"]) {
        string id(node["id"]);
        cout << "Generating " << node["name"] << " as node [" << id << "]..."
             << endl;

        auto rel_path = fs::path("src") / id;
        auto abs_path = fs::path(ws_path) / rel_path;
        auto src_path = abs_path / "src";
        fs::create_directories(src_path);  // will also create 'path'

        for (const auto& file : default_tpls) {
            auto tpl = env_->parse_template(file);
            // cout << "\t- " << (abs_path / file).string() << endl;
            env_->write(tpl, node, (rel_path / file).string());
        }
    }

    cout << "Generation of ROS nodes complete. The generated nodes can be "
            "found in "
         << ws_path << endl;
}

void RosVisitor::beginNodes() {}

void RosVisitor::onNode(shared_ptr<const Node> node) {
    // ignore TF nodes
    if (node->name() == "TF" || node->name() == "tf") return;

    nlohmann::json jnode;

    auto name = node->name().substr(0, node->name().find("["));

    jnode["id"] = make_id(name);
    jnode["name"] = name;
    jnode["label"] = COGNITIVE_FUNCTION_NAMES.at(node->cognitive_function());

    jnode["dependencies"] = nlohmann::json::array();

    jnode["boxology_version"] = STR(BOXOLOGY_VERSION);

    if (node->sub_architecture) {
        jnode["version"] = node->sub_architecture->version;
        jnode["description"] = node->sub_architecture->description;
    } else {
        jnode["version"] = "1.0.0";
        jnode["description"] = "";
    }

    //////////////////////////////////////////////
    // Ports
    //
    jnode["inputs"] = nlohmann::json::array();
    jnode["outputs"] = nlohmann::json::array();
    for (auto p : node->ports()) {
        nlohmann::json jport;

        bool isInput = (p->direction == Port::Direction::IN);

        auto name = p->name;

        regex topic_regex("`(.*)` \\[(.*)\\]", regex_constants::ECMAScript);
        smatch topic_matches;
        regex tf_regex("`tf: (.*)`", regex_constants::ECMAScript);
        smatch tf_matches;

        if (regex_search(name, topic_matches, topic_regex)) {
            jport["type"] = "topic";
            jport["topic"] = topic_matches[1];
            jport["short"] = split(jport["topic"], '/').back();
            auto type = split(topic_matches[2], '/');
            jport["datatype"] = {type.front(), type.back()};
            if (!contains(jnode["dependencies"],jport["datatype"])) {
                jnode["dependencies"].push_back(jport["datatype"]);
            }

            cout << "[II] Node " << jnode["id"] << ": "
                 << (isInput ? "subscribes to" : "publishes") << " topic "
                 << jport["topic"] << " (short: " << jport["shorttopic"]
                 << ") of type " << jport["type"] << endl;

        } else if (regex_search(name, tf_matches, tf_regex)) {
            jport["type"] = "tf";
            jport["frame"] = tf_matches[1];

            if (isInput) {
                jport["datatype"] = {"tf", "transform_listener"};
            }else {
                jport["datatype"] = {"tf", "transform_broadcaster"};
            }
            if (!contains(jnode["dependencies"],jport["datatype"])) {
                jnode["dependencies"].push_back(jport["datatype"]);
            }

            cout << "[II] Node " << jnode["id"] << ": "
                 << (isInput ? "listen to" : "broadcasts") << " TF frame "
                 << jport["frame"] << endl;
        } else {
            jport["type"] = "undefined";
            jport["description"] = name;
            jport["topic"] = make_id(name);
            jport["short"] = make_id(name);
            jport["datatype"] = {"std_msgs", "Empty"};
            if (!contains(jnode["dependencies"], jport["datatype"])) {
                jnode["dependencies"].push_back(jport["datatype"]);
            }

        }

        if (isInput) {
            jnode["inputs"].push_back(jport);
        } else {
            jnode["outputs"].push_back(jport);
        }
    }

    data_["nodes"].push_back(jnode);

    nodes_.push_back(node);
}

void RosVisitor::endNodes() {}

void RosVisitor::beginConnections() {}

void RosVisitor::onConnection(shared_ptr<const Connection> connection) {}

<|endoftext|>