<commit_before>/**
 *
 * @copyright
 * ========================================================================
 *	Copyright 2007 FLWOR Foundation
 *
 *	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 *
 *		http://www.apache.org/licenses/LICENSE-2.0
 *
 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.
 * ========================================================================
 *
 * @author John Cowan,Paul Pedersen (pcp071098@yahoo.com)
 * @file context/dynamic_context.cpp
 *
 */

#include <assert.h>
#include <time.h>

#include "store/api/iterator.h"
#include "store/api/temp_seq.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"

#include "system/globalenv.h"
#include "context/dynamic_context.h"
#include "context/static_context.h"
#include "types/root_typemanager.h"
#include "runtime/api/plan_wrapper.h"

using namespace std;
namespace zorba {

bool dynamic_context::static_init = false;

void dynamic_context::init()
{
	if (!dynamic_context::static_init) {
		dynamic_context::static_init = true;
	}
}

dynamic_context::dynamic_context(dynamic_context *parent)
{
	this->parent = parent;
	if(!parent)
	{
    // set the current time
		time_t		t0 = time(NULL);
#if defined (WIN32)
		struct	::tm	gmtm;
    localtime_s(&gmtm, &t0); //thread safe localtime on Windows
#else
		struct	::tm	gmtm;
    localtime_r(&t0, &gmtm); //thread safe localtime on Linux
#endif

		implicit_timezone = 0;

    current_date_time_item = GENV_ITEMFACTORY->createDateTime(gmtm.tm_year, gmtm.tm_mon, gmtm.tm_mday,
                                                              gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec, implicit_timezone);

		ctxt_position = 0;
	}
	else
	{
		current_date_time_item = parent->current_date_time_item;
		implicit_timezone = parent->implicit_timezone;
		default_collection_uri = parent->default_collection_uri;

		ctxt_item = parent->ctxt_item;
		ctxt_position = parent->ctxt_position;
	}
}

dynamic_context::~dynamic_context()
{
	///free the pointers from ctx_value_t from keymap
	checked_vector<hashmap<dctx_value_t>::entry>::const_iterator it;
	const char		*keybuff;//[50];
	const dctx_value_t* val;

	for(it = keymap.begin(); it != keymap.end(); it++)
	{
		///it is an entry
		//keymap.getentryKey(*it, keybuff, sizeof(keybuff)-1);
		keybuff = (*it).key.c_str();
		if(!strncmp(keybuff, "var:", 4))
		{
			val = &(*it).val;
      switch (val->type) {
      case dynamic_context::dctx_value_t::var_iterator_val:
        val->val.var_iterator->removeReference(val->val.var_iterator->getSharedRefCounter()
                                               SYNC_PARAM2(val->val.var_iterator->getRCLock()));
        break;
      case dynamic_context::dctx_value_t::temp_seq_val:
        val->val.temp_seq->removeReference(val->val.temp_seq->getSharedRefCounter()
                                           SYNC_PARAM2(val->val.temp_seq->getRCLock()));
        break;
      default: assert (false);
      }
		}
	}
}

xqp_string dynamic_context::expand_varname(static_context	*sctx, xqp_string qname) const
{
  // TODO: use static_context::qname_internal_key()
  pair<xqp_string, xqp_string> rqname = parse_qname (qname);
  if (rqname.first.empty ())
    return rqname.second + ":";
  if(!sctx) {
    ///actually the whole static context is missing
    ZORBA_ERROR_PARAM( ZorbaError::XPST0001, "entire static context", "");
			return (const char*)NULL;
  }
  return rqname.second + ":" + sctx->lookup_ns(rqname.first);
}

/*______________________________________________________________________
|
|	XQuery 1.0 context
|	[http://www.w3.org/TR/xquery/#id-xq-context-components]
|_______________________________________________________________________*/
/*
pair<xqp_string, xqp_string> parse_qname (xqp_string qname);
xqp_string qname_internal_key2 (xqp_string ns, xqp_string local);

xqp_string dynamic_context::qname_internal_key (QNameItem_t qname) const {
  return qname_internal_key2 (qname->getNamespace (), qname->getLocalName ());
}
xqp_string dynamic_context::qname_internal_key (xqp_string default_ns, xqp_string prefix, xqp_string local) const {
  return qname_internal_key2
    (prefix.empty () ? default_ns : sctx->lookup_ns (prefix), local);
}
xqp_string dynamic_context::qname_internal_key (xqp_string default_ns, xqp_string qname) const {
  pair<xqp_string, xqp_string> rqname = parse_qname (qname);
  return qname_internal_key (default_ns, rqname.first, rqname.second);
}
*/

void dynamic_context::set_context_item(store::Item_t context_item, unsigned long position)
{
	this->ctxt_item = context_item;
	this->ctxt_position = position;
}

store::Item_t dynamic_context::context_item() const
{
	return ctxt_item;
}

unsigned long dynamic_context::context_position()
{
	return ctxt_position;
}

xqtref_t dynamic_context::context_item_type() const
{
	return GENV_TYPESYSTEM.ITEM_TYPE_STAR;
}

void dynamic_context::set_context_item_type(
	xqtref_t v)
{
}

void	dynamic_context::set_current_date_time( const store::Item_t& aDateTimeItem )
{
  this->current_date_time_item = aDateTimeItem;
}

store::Item_t	dynamic_context::get_current_date_time()
{
	return current_date_time_item;
}

void  dynamic_context::set_implicit_timezone(int tzone_seconds)
{
	this->implicit_timezone = tzone_seconds;
}

int  dynamic_context::get_implicit_timezone()
{
#if 0
  // If this is to be taken from the dynamic ctx, it kills optimization
  // (const folding) as datetime code calls this from all over the place.
  return implicit_timezone;
#else
	return 0;
#endif
}

/*
var_name is expanded name localname:nsURI
constructed by static_context::qname_internal_key( .. )
*/
void dynamic_context::add_variable(xqp_string var_name, store::Iterator_t var_iterator)
{
  store::Iterator* lIter = &*var_iterator;
  lIter->addReference(var_iterator->getSharedRefCounter()
                      SYNC_PARAM2(var_iterator->getRCLock()));

  dctx_value_t v;
  v.type = dynamic_context::dctx_value_t::var_iterator_val;
  v.val.var_iterator = lIter;
  keymap.put ("var:" + var_name, v);
}

store::Iterator_t	dynamic_context::get_variable(store::Item_t varname) {
	return lookup_var_iter("var:" + static_context::qname_internal_key (varname));
}

store::Iterator_t dynamic_context::lookup_var_iter(xqp_string key) {
  dctx_value_t val;

  if(!keymap.get (key, val))
	{
    if(parent)
      return parent->lookup_var_iter(key);
    else
      return NULL;///variable not found
	}
  if (val.type == dynamic_context::dctx_value_t::var_iterator_val) {
    store::TempSeq_t seq = GENV_STORE.createTempSeq (val.val.var_iterator);
    val.val.var_iterator->removeReference(val.val.var_iterator->getSharedRefCounter()
                                           SYNC_PARAM2(val.val.var_iterator->getRCLock()));
    seq->addReference(seq->getSharedRefCounter()
                      SYNC_PARAM2(seq->getRCLock()));
    val.type = dynamic_context::dctx_value_t::temp_seq_val;
    val.val.temp_seq = seq.getp();
    keymap.put (key, val);
  }
  return val.val.temp_seq->getIterator ();
}

xqp_string dynamic_context::get_default_collection()
{
	return default_collection_uri;
}

void dynamic_context::set_default_collection(xqp_string default_collection_uri)
{
	this->default_collection_uri = default_collection_uri;
}

}	/* namespace zorba */

<commit_msg>Fixed external vars<commit_after>/**
 *
 * @copyright
 * ========================================================================
 *	Copyright 2007 FLWOR Foundation
 *
 *	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 *
 *		http://www.apache.org/licenses/LICENSE-2.0
 *
 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.
 * ========================================================================
 *
 * @author John Cowan,Paul Pedersen (pcp071098@yahoo.com)
 * @file context/dynamic_context.cpp
 *
 */

#include <assert.h>
#include <time.h>

#include "store/api/iterator.h"
#include "store/api/temp_seq.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"

#include "system/globalenv.h"
#include "context/dynamic_context.h"
#include "context/static_context.h"
#include "types/root_typemanager.h"
#include "runtime/api/plan_wrapper.h"

using namespace std;
namespace zorba {

bool dynamic_context::static_init = false;

void dynamic_context::init()
{
	if (!dynamic_context::static_init) {
		dynamic_context::static_init = true;
	}
}

dynamic_context::dynamic_context(dynamic_context *parent)
{
	this->parent = parent;
	if(!parent)
	{
    // set the current time
		time_t		t0 = time(NULL);
#if defined (WIN32)
		struct	::tm	gmtm;
    localtime_s(&gmtm, &t0); //thread safe localtime on Windows
#else
		struct	::tm	gmtm;
    localtime_r(&t0, &gmtm); //thread safe localtime on Linux
#endif

		implicit_timezone = 0;

    current_date_time_item = GENV_ITEMFACTORY->createDateTime(gmtm.tm_year, gmtm.tm_mon, gmtm.tm_mday,
                                                              gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec, implicit_timezone);

		ctxt_position = 0;
	}
	else
	{
		current_date_time_item = parent->current_date_time_item;
		implicit_timezone = parent->implicit_timezone;
		default_collection_uri = parent->default_collection_uri;

		ctxt_item = parent->ctxt_item;
		ctxt_position = parent->ctxt_position;
	}
}

dynamic_context::~dynamic_context()
{
	///free the pointers from ctx_value_t from keymap
	checked_vector<hashmap<dctx_value_t>::entry>::const_iterator it;
	const char		*keybuff;//[50];
	const dctx_value_t* val;

	for(it = keymap.begin(); it != keymap.end(); it++)
	{
		///it is an entry
		//keymap.getentryKey(*it, keybuff, sizeof(keybuff)-1);
		keybuff = (*it).key.c_str();
		if(!strncmp(keybuff, "var:", 4))
		{
			val = &(*it).val;
      switch (val->type) {
      case dynamic_context::dctx_value_t::var_iterator_val:
        val->val.var_iterator->removeReference(val->val.var_iterator->getSharedRefCounter()
                                               SYNC_PARAM2(val->val.var_iterator->getRCLock()));
        break;
      case dynamic_context::dctx_value_t::temp_seq_val:
        val->val.temp_seq->removeReference(val->val.temp_seq->getSharedRefCounter()
                                           SYNC_PARAM2(val->val.temp_seq->getRCLock()));
        break;
      default: assert (false);
      }
		}
	}
}

xqp_string dynamic_context::expand_varname(static_context	*sctx, xqp_string qname) const
{
  // TODO: use static_context::qname_internal_key()
  pair<xqp_string, xqp_string> rqname = parse_qname (qname);
  if (rqname.first.empty ())
    return rqname.second + ":";
  if(!sctx) {
    ///actually the whole static context is missing
    ZORBA_ERROR_PARAM( ZorbaError::XPST0001, "entire static context", "");
			return (const char*)NULL;
  }
  return rqname.second + ":" + sctx->lookup_ns(rqname.first);
}

/*______________________________________________________________________
|
|	XQuery 1.0 context
|	[http://www.w3.org/TR/xquery/#id-xq-context-components]
|_______________________________________________________________________*/
/*
pair<xqp_string, xqp_string> parse_qname (xqp_string qname);
xqp_string qname_internal_key2 (xqp_string ns, xqp_string local);

xqp_string dynamic_context::qname_internal_key (QNameItem_t qname) const {
  return qname_internal_key2 (qname->getNamespace (), qname->getLocalName ());
}
xqp_string dynamic_context::qname_internal_key (xqp_string default_ns, xqp_string prefix, xqp_string local) const {
  return qname_internal_key2
    (prefix.empty () ? default_ns : sctx->lookup_ns (prefix), local);
}
xqp_string dynamic_context::qname_internal_key (xqp_string default_ns, xqp_string qname) const {
  pair<xqp_string, xqp_string> rqname = parse_qname (qname);
  return qname_internal_key (default_ns, rqname.first, rqname.second);
}
*/

void dynamic_context::set_context_item(store::Item_t context_item, unsigned long position)
{
	this->ctxt_item = context_item;
	this->ctxt_position = position;
}

store::Item_t dynamic_context::context_item() const
{
	return ctxt_item;
}

unsigned long dynamic_context::context_position()
{
	return ctxt_position;
}

xqtref_t dynamic_context::context_item_type() const
{
	return GENV_TYPESYSTEM.ITEM_TYPE_STAR;
}

void dynamic_context::set_context_item_type(
	xqtref_t v)
{
}

void	dynamic_context::set_current_date_time( const store::Item_t& aDateTimeItem )
{
  this->current_date_time_item = aDateTimeItem;
}

store::Item_t	dynamic_context::get_current_date_time()
{
	return current_date_time_item;
}

void  dynamic_context::set_implicit_timezone(int tzone_seconds)
{
	this->implicit_timezone = tzone_seconds;
}

int  dynamic_context::get_implicit_timezone()
{
#if 0
  // If this is to be taken from the dynamic ctx, it kills optimization
  // (const folding) as datetime code calls this from all over the place.
  return implicit_timezone;
#else
	return 0;
#endif
}

/*
var_name is expanded name localname:nsURI
constructed by static_context::qname_internal_key( .. )
*/
void dynamic_context::add_variable(xqp_string var_name, store::Iterator_t var_iterator)
{
  // TODO: lazy conversion to a temp sequence
  dctx_value_t v;
  var_iterator->open ();
  store::TempSeq_t seq = GENV_STORE.createTempSeq (var_iterator.getp());
  var_iterator->close ();
  seq->addReference(seq->getSharedRefCounter()
                    SYNC_PARAM2(seq->getRCLock()));
  v.type = dynamic_context::dctx_value_t::temp_seq_val;
  v.val.temp_seq = seq.getp();
  keymap.put ("var:" + var_name, v);
}

store::Iterator_t	dynamic_context::get_variable(store::Item_t varname) {
	return lookup_var_iter("var:" + static_context::qname_internal_key (varname));
}

store::Iterator_t dynamic_context::lookup_var_iter(xqp_string key) {
  dctx_value_t val;

  if(!keymap.get (key, val))
	{
    if(parent)
      return parent->lookup_var_iter(key);
    else
      return NULL;///variable not found
	}
  assert (val.type == dynamic_context::dctx_value_t::temp_seq_val);
  return val.val.temp_seq->getIterator ();
}

xqp_string dynamic_context::get_default_collection()
{
	return default_collection_uri;
}

void dynamic_context::set_default_collection(xqp_string default_collection_uri)
{
	this->default_collection_uri = default_collection_uri;
}

}	/* namespace zorba */

<|endoftext|>


<commit_before>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "stdafx.h"
#include "ConfigData.h"

bool ConfigData::_instanceFlag = false;
ConfigData* ConfigData::_instance = NULL;

const QString ConfigData::CONFIGURATION_FILE_NAME = "config.ini";

const QString ConfigData::APPLICATION_NAME_IN_SETTINGS = "Ripple";
const QString ConfigData::TOOLING_CONTENT_NAME_IN_SETTINGS = "windowContent";
const QString ConfigData::MAIN_WINDOW_SIZE_NAME_IN_SETTINGS = "windowSize";
const QString ConfigData::MAIN_WINDOW_POSITION_NAME_IN_SETTINGS = "windowPos";
const QString ConfigData::MAIN_WINDOW_STATE_NAME_IN_SETTINGS = "windowState";
const QString ConfigData::LOCAL_STORAGE_PATH_IN_SETTINGS = "localStoragePath";
const QString ConfigData::BUILD_SERVICE_COMMAND_IN_SETTINGS = "buildServiceCommand";
const QString ConfigData::BUILD_SERVICE_PORT_IN_SETTINGS = "buildServicePort";
const QString ConfigData::TOOLING_CONTENT_DEFAULT = "index.html";
const QSize ConfigData::MAIN_WINDOW_SIZE_DEFAULT = QSize(1280, 1024);
const QPoint ConfigData::MAIN_WINDOW_POSITION_DEFAULT = QPoint(0, 0);
const unsigned int ConfigData::MAIN_WINDOW_STATE_DEFAULT = 1;
const QString ConfigData::LOCAL_STORAGE_PATH_DEFAULT = "";
const QString ConfigData::BUILD_SERVICE_COMMAND_DEFAULT = "services/bin/rbd_service.command";
const QString ConfigData::BUILD_SERVICE_PORT_DEFAULT = "9900";

ConfigData::ConfigData(void)
{
#ifdef Q_WS_WIN
	_applicationStoragePath = QString(getenv("APPDATA"));
	_applicationStoragePath += (QDir::separator() + QCoreApplication::organizationName());
	_applicationStoragePath += (QDir::separator() + QCoreApplication::applicationName());
#else
	_applicationStoragePath = QCoreApplication::applicationDirPath();
#endif

	QString config_path(_applicationStoragePath + QDir::separator() + CONFIGURATION_FILE_NAME);
	_settings = new QSettings(config_path, QSettings::IniFormat);

    readSettings();
}

ConfigData::~ConfigData(void)
{
	_instanceFlag = false;
	_instance = NULL;

	delete _settings;
}

ConfigData* ConfigData::getInstance(void)
{
    if (!_instanceFlag)
    {
        _instance = new ConfigData();
        _instanceFlag = true;
        return _instance;
    }
    else
    {
        return _instance;
    }
}

void ConfigData::writeSettings()
{
	_settings->beginGroup(APPLICATION_NAME_IN_SETTINGS);
	_settings->setValue(MAIN_WINDOW_SIZE_NAME_IN_SETTINGS, _mainWindowSize);
	_settings->setValue(MAIN_WINDOW_POSITION_NAME_IN_SETTINGS, _mainWindowPosition);
    _settings->setValue(MAIN_WINDOW_STATE_NAME_IN_SETTINGS, (unsigned int) _mainWindowState);
	_settings->setValue(TOOLING_CONTENT_NAME_IN_SETTINGS, _toolingContent);
	_settings->setValue(LOCAL_STORAGE_PATH_IN_SETTINGS, _localStoragePath);
    _settings->setValue(BUILD_SERVICE_COMMAND_IN_SETTINGS, _buildServiceCommand);
    _settings->setValue(BUILD_SERVICE_PORT_IN_SETTINGS, _buildServicePort);
	_settings->endGroup();
}

void ConfigData::readSettings()
{
	_settings->beginGroup(APPLICATION_NAME_IN_SETTINGS);
	_mainWindowSize = _settings->value(MAIN_WINDOW_SIZE_NAME_IN_SETTINGS, MAIN_WINDOW_SIZE_DEFAULT).toSize();
	_mainWindowPosition = _settings->value(MAIN_WINDOW_POSITION_NAME_IN_SETTINGS, MAIN_WINDOW_POSITION_DEFAULT).toPoint();
    _mainWindowState = (Qt::WindowStates) _settings->value(MAIN_WINDOW_STATE_NAME_IN_SETTINGS, MAIN_WINDOW_STATE_DEFAULT).toUInt();
	_toolingContent = _settings->value(TOOLING_CONTENT_NAME_IN_SETTINGS, TOOLING_CONTENT_DEFAULT).toString();
	_localStoragePath = _settings->value(LOCAL_STORAGE_PATH_IN_SETTINGS, LOCAL_STORAGE_PATH_DEFAULT).toString();
	_buildServiceCommand = _settings->value(BUILD_SERVICE_COMMAND_IN_SETTINGS, BUILD_SERVICE_COMMAND_DEFAULT).toString();
	_buildServicePort = _settings->value(BUILD_SERVICE_PORT_IN_SETTINGS, BUILD_SERVICE_PORT_DEFAULT).toString();
	_settings->endGroup();
}

QString ConfigData::toolingContent()
{
    return _toolingContent;
}

void ConfigData::toolingContent(QString content)
{
    _toolingContent = content;
    writeSettings();
}

QSize ConfigData::windowSize()
{
    return _mainWindowSize;
}

void ConfigData::windowSize(QSize size)
{
    _mainWindowSize = size;
    writeSettings();
}

QPoint ConfigData::windowPosition()
{
    return _mainWindowPosition;
}

void ConfigData::windowPosition(QPoint position)
{
    _mainWindowPosition = position;
    writeSettings();
}

unsigned int ConfigData::windowState()
{
    return _mainWindowState;
}

void ConfigData::windowState(unsigned int state)
{
    _mainWindowState = state;
}

QString ConfigData::localStoragePath()
{
    if (_localStoragePath == "")
        return _applicationStoragePath;
    else
        return _localStoragePath;
}

void ConfigData::localStoragePath(QString path)
{
    _localStoragePath = path;
    writeSettings();
}

QString ConfigData::buildServiceCommand()
{
    return _buildServiceCommand;
}

void ConfigData::buildServiceCommmand(QString cmd)
{
    _buildServiceCommand = cmd;
}

unsigned short ConfigData::buildServicePort()
{
    return _buildServicePort.toUInt();
}

void ConfigData::buildServicePort(unsigned short port)
{
    _buildServicePort = QString::number(port);
}
<commit_msg>Small code cleanup, removed some unneeded casting<commit_after>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "stdafx.h"
#include "ConfigData.h"

bool ConfigData::_instanceFlag = false;
ConfigData* ConfigData::_instance = NULL;

const QString ConfigData::CONFIGURATION_FILE_NAME = "config.ini";

const QString ConfigData::APPLICATION_NAME_IN_SETTINGS = "Ripple";
const QString ConfigData::TOOLING_CONTENT_NAME_IN_SETTINGS = "windowContent";
const QString ConfigData::MAIN_WINDOW_SIZE_NAME_IN_SETTINGS = "windowSize";
const QString ConfigData::MAIN_WINDOW_POSITION_NAME_IN_SETTINGS = "windowPos";
const QString ConfigData::MAIN_WINDOW_STATE_NAME_IN_SETTINGS = "windowState";
const QString ConfigData::LOCAL_STORAGE_PATH_IN_SETTINGS = "localStoragePath";
const QString ConfigData::BUILD_SERVICE_COMMAND_IN_SETTINGS = "buildServiceCommand";
const QString ConfigData::BUILD_SERVICE_PORT_IN_SETTINGS = "buildServicePort";
const QString ConfigData::TOOLING_CONTENT_DEFAULT = "index.html";
const QSize ConfigData::MAIN_WINDOW_SIZE_DEFAULT = QSize(1280, 1024);
const QPoint ConfigData::MAIN_WINDOW_POSITION_DEFAULT = QPoint(0, 0);
const unsigned int ConfigData::MAIN_WINDOW_STATE_DEFAULT = 1;
const QString ConfigData::LOCAL_STORAGE_PATH_DEFAULT = "";
const QString ConfigData::BUILD_SERVICE_COMMAND_DEFAULT = "services/bin/rbd_service.command";
const QString ConfigData::BUILD_SERVICE_PORT_DEFAULT = "9900";

ConfigData::ConfigData(void)
{
#ifdef Q_WS_WIN
	_applicationStoragePath = QString(getenv("APPDATA"));
	_applicationStoragePath += (QDir::separator() + QCoreApplication::organizationName());
	_applicationStoragePath += (QDir::separator() + QCoreApplication::applicationName());
#else
	_applicationStoragePath = QCoreApplication::applicationDirPath();
#endif

	QString config_path(_applicationStoragePath + QDir::separator() + CONFIGURATION_FILE_NAME);
	_settings = new QSettings(config_path, QSettings::IniFormat);

    readSettings();
}

ConfigData::~ConfigData(void)
{
	_instanceFlag = false;
	_instance = NULL;

	delete _settings;
}

ConfigData* ConfigData::getInstance(void)
{
    if (!_instanceFlag)
    {
        _instance = new ConfigData();
        _instanceFlag = true;
        return _instance;
    }
    else
    {
        return _instance;
    }
}

void ConfigData::writeSettings()
{
	_settings->beginGroup(APPLICATION_NAME_IN_SETTINGS);
	_settings->setValue(MAIN_WINDOW_SIZE_NAME_IN_SETTINGS, _mainWindowSize);
	_settings->setValue(MAIN_WINDOW_POSITION_NAME_IN_SETTINGS, _mainWindowPosition);
    _settings->setValue(MAIN_WINDOW_STATE_NAME_IN_SETTINGS, _mainWindowState);
	_settings->setValue(TOOLING_CONTENT_NAME_IN_SETTINGS, _toolingContent);
	_settings->setValue(LOCAL_STORAGE_PATH_IN_SETTINGS, _localStoragePath);
    _settings->setValue(BUILD_SERVICE_COMMAND_IN_SETTINGS, _buildServiceCommand);
    _settings->setValue(BUILD_SERVICE_PORT_IN_SETTINGS, _buildServicePort);
	_settings->endGroup();
}

void ConfigData::readSettings()
{
	_settings->beginGroup(APPLICATION_NAME_IN_SETTINGS);
	_mainWindowSize = _settings->value(MAIN_WINDOW_SIZE_NAME_IN_SETTINGS, MAIN_WINDOW_SIZE_DEFAULT).toSize();
	_mainWindowPosition = _settings->value(MAIN_WINDOW_POSITION_NAME_IN_SETTINGS, MAIN_WINDOW_POSITION_DEFAULT).toPoint();
    _mainWindowState = _settings->value(MAIN_WINDOW_STATE_NAME_IN_SETTINGS, MAIN_WINDOW_STATE_DEFAULT).toUInt();
	_toolingContent = _settings->value(TOOLING_CONTENT_NAME_IN_SETTINGS, TOOLING_CONTENT_DEFAULT).toString();
	_localStoragePath = _settings->value(LOCAL_STORAGE_PATH_IN_SETTINGS, LOCAL_STORAGE_PATH_DEFAULT).toString();
	_buildServiceCommand = _settings->value(BUILD_SERVICE_COMMAND_IN_SETTINGS, BUILD_SERVICE_COMMAND_DEFAULT).toString();
	_buildServicePort = _settings->value(BUILD_SERVICE_PORT_IN_SETTINGS, BUILD_SERVICE_PORT_DEFAULT).toString();
	_settings->endGroup();
}

QString ConfigData::toolingContent()
{
    return _toolingContent;
}

void ConfigData::toolingContent(QString content)
{
    _toolingContent = content;
    writeSettings();
}

QSize ConfigData::windowSize()
{
    return _mainWindowSize;
}

void ConfigData::windowSize(QSize size)
{
    _mainWindowSize = size;
    writeSettings();
}

QPoint ConfigData::windowPosition()
{
    return _mainWindowPosition;
}

void ConfigData::windowPosition(QPoint position)
{
    _mainWindowPosition = position;
    writeSettings();
}

unsigned int ConfigData::windowState()
{
    return _mainWindowState;
}

void ConfigData::windowState(unsigned int state)
{
    _mainWindowState = state;
}

QString ConfigData::localStoragePath()
{
    if (_localStoragePath == "")
        return _applicationStoragePath;
    else
        return _localStoragePath;
}

void ConfigData::localStoragePath(QString path)
{
    _localStoragePath = path;
    writeSettings();
}

QString ConfigData::buildServiceCommand()
{
    return _buildServiceCommand;
}

void ConfigData::buildServiceCommmand(QString cmd)
{
    _buildServiceCommand = cmd;
}

unsigned short ConfigData::buildServicePort()
{
    return _buildServicePort.toUInt();
}

void ConfigData::buildServicePort(unsigned short port)
{
    _buildServicePort = QString::number(port);
}
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Math/MlcpConstraintType.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintData.h"
#include "SurgSim/Physics/Localization.h"

#include "SurgSim/Framework/Assert.h"

namespace SurgSim
{

namespace Physics
{

Constraint::Constraint(ConstraintType constraintType,
	std::shared_ptr<ConstraintData> data,
	std::shared_ptr<Representation> representation0,
	const SurgSim::DataStructures::Location& location0,
	std::shared_ptr<Representation> representation1,
	const SurgSim::DataStructures::Location& location1)
	: m_active(true)
{
	m_mlcpMap[FIXED_3DPOINT] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
	m_mlcpMap[FIXED_3DROTATION_VECTOR] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
	m_mlcpMap[FRICTIONAL_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONAL_CONSTRAINT;
	m_mlcpMap[FRICTIONLESS_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT;
	m_mlcpMap[FRICTIONAL_SLIDING] = Math::MLCP_BILATERAL_FRICTIONAL_SLIDING_CONSTRAINT;
	m_mlcpMap[FRICTIONLESS_SLIDING] = Math::MLCP_BILATERAL_FRICTIONLESS_SLIDING_CONSTRAINT;
	setInformation(constraintType, data, representation0, location0, representation1, location1);
}

Constraint::~Constraint()
{
}

const std::pair<std::shared_ptr<ConstraintImplementation>, std::shared_ptr<ConstraintImplementation>>&
	Constraint::getImplementations() const
{
	return m_implementations;
}

const std::pair<std::shared_ptr<Localization>, std::shared_ptr<Localization>>& Constraint::getLocalizations() const
{
	return m_localizations;
}

std::shared_ptr<ConstraintData> Constraint::getData() const
{
	return m_data;
}

size_t Constraint::getNumDof() const
{
	return m_numDof;
}

ConstraintType Constraint::getType()
{
	return m_constraintType;
}

void Constraint::build(double dt,
	MlcpPhysicsProblem* mlcp,
	size_t indexOfRepresentation0,
	size_t indexOfRepresentation1,
	size_t indexOfConstraint)
{
	doBuild(dt, *m_data.get(), mlcp, indexOfRepresentation0, indexOfRepresentation1, indexOfConstraint);

	m_implementations.first->build(
		dt,
		*m_data.get(),
		m_localizations.first,
		mlcp,
		indexOfRepresentation0,
		indexOfConstraint,
		CONSTRAINT_POSITIVE_SIDE);

	SurgSim::Math::Vector3d rotationVector1 = SurgSim::Math::Vector3d::Zero();
	SurgSim::Math::Quaterniond q1 = SurgSim::Math::Quaterniond::Identity();
	if (m_constraintType == FIXED_3DROTATION_VECTOR)
	{
		rotationVector1 = mlcp->b.segment<3>(indexOfConstraint);
		if (rotationVector1.norm() > 1e-8)
		{
			q1 = SurgSim::Math::makeRotationQuaternion(rotationVector1.norm(), rotationVector1.normalized());
		}
	}

	m_implementations.second->build(
		dt,
		*m_data.get(),
		m_localizations.second,
		mlcp,
		indexOfRepresentation1,
		indexOfConstraint,
		CONSTRAINT_NEGATIVE_SIDE);

	SurgSim::Math::Vector3d rotationVector2 = SurgSim::Math::Vector3d::Zero();
	SurgSim::Math::Quaterniond q2 = SurgSim::Math::Quaterniond::Identity();
	if (m_constraintType == FIXED_3DROTATION_VECTOR)
	{
		rotationVector2 = rotationVector1 - mlcp->b.segment<3>(indexOfConstraint);
		if (rotationVector2.norm() > 1e-8)
		{
			q2 = SurgSim::Math::makeRotationQuaternion(rotationVector2.norm(), rotationVector2.normalized());
		}
	}

	// Transform the data to have a rotation vector violation as a rotation vector
	if (m_constraintType == FIXED_3DROTATION_VECTOR)
	{
		double angle;
		SurgSim::Math::Vector3d axis;
		SurgSim::Math::computeAngleAndAxis((q1 * q2.inverse()).normalized(), &angle, &axis);

		mlcp->b.segment(indexOfConstraint, this->getNumDof()) = angle * axis;
	}

	mlcp->constraintTypes.push_back(
				(m_constraintType != INVALID_CONSTRAINT) ? m_mlcpMap[m_constraintType] : Math::MLCP_INVALID_CONSTRAINT);
}

bool Constraint::isActive()
{
	return m_active && m_localizations.first->getRepresentation()->isActive() &&
		   m_localizations.second->getRepresentation()->isActive();
}

void Constraint::setActive(bool flag)
{
	m_active = flag;
}

void Constraint::doBuild(double dt,
	const ConstraintData& data,
	MlcpPhysicsProblem* mlcp,
	size_t indexOfRepresentation0,
	size_t indexOfRepresentation1,
	size_t indexOfConstraint)
{
}

void Constraint::setInformation(ConstraintType constraintType,
	std::shared_ptr<ConstraintData> data,
	std::shared_ptr<Representation> representation0,
	const SurgSim::DataStructures::Location& location0,
	std::shared_ptr<Representation> representation1,
	const SurgSim::DataStructures::Location& location1)
{
	m_constraintType = constraintType;
	SURGSIM_ASSERT(data != nullptr) << "ConstraintData can't be nullptr";
	SURGSIM_ASSERT(representation0 != nullptr) << "First representation can't be nullptr";
	SURGSIM_ASSERT(representation1 != nullptr) << "Second representation can't be nullptr";

	auto localization0 = representation0->createLocalization(location0);
	SURGSIM_ASSERT(localization0 != nullptr) << "Could not create localization for " << representation0->getName();

	auto localization1 = representation1->createLocalization(location1);
	SURGSIM_ASSERT(localization1 != nullptr) << "Could not create localization for " << representation1->getName();

	auto implementation0 = representation0->getConstraintImplementation(m_constraintType);
	SURGSIM_ASSERT(implementation0 != nullptr) << "Could not get implementation for " << representation0->getName();

	auto implementation1 = representation1->getConstraintImplementation(m_constraintType);
	SURGSIM_ASSERT(implementation1 != nullptr) << "Could not get implementation for " << representation1->getName();

	SURGSIM_ASSERT(implementation0->getNumDof() == implementation1->getNumDof())
		<< "The number of DOFs does not match between the two implementations";

	m_data = data;
	m_implementations = std::make_pair(implementation0, implementation1);
	m_localizations = std::make_pair(localization0, localization1);
	m_numDof = implementation0->getNumDof();
}

}; // namespace Physics

}; // namespace SurgSim
<commit_msg>Minor change to use Eigen static sub-vector access instead of dynamic<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Math/MlcpConstraintType.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintData.h"
#include "SurgSim/Physics/Localization.h"

#include "SurgSim/Framework/Assert.h"

namespace SurgSim
{

namespace Physics
{

Constraint::Constraint(ConstraintType constraintType,
	std::shared_ptr<ConstraintData> data,
	std::shared_ptr<Representation> representation0,
	const SurgSim::DataStructures::Location& location0,
	std::shared_ptr<Representation> representation1,
	const SurgSim::DataStructures::Location& location1)
	: m_active(true)
{
	m_mlcpMap[FIXED_3DPOINT] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
	m_mlcpMap[FIXED_3DROTATION_VECTOR] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
	m_mlcpMap[FRICTIONAL_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONAL_CONSTRAINT;
	m_mlcpMap[FRICTIONLESS_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT;
	m_mlcpMap[FRICTIONAL_SLIDING] = Math::MLCP_BILATERAL_FRICTIONAL_SLIDING_CONSTRAINT;
	m_mlcpMap[FRICTIONLESS_SLIDING] = Math::MLCP_BILATERAL_FRICTIONLESS_SLIDING_CONSTRAINT;
	setInformation(constraintType, data, representation0, location0, representation1, location1);
}

Constraint::~Constraint()
{
}

const std::pair<std::shared_ptr<ConstraintImplementation>, std::shared_ptr<ConstraintImplementation>>&
	Constraint::getImplementations() const
{
	return m_implementations;
}

const std::pair<std::shared_ptr<Localization>, std::shared_ptr<Localization>>& Constraint::getLocalizations() const
{
	return m_localizations;
}

std::shared_ptr<ConstraintData> Constraint::getData() const
{
	return m_data;
}

size_t Constraint::getNumDof() const
{
	return m_numDof;
}

ConstraintType Constraint::getType()
{
	return m_constraintType;
}

void Constraint::build(double dt,
	MlcpPhysicsProblem* mlcp,
	size_t indexOfRepresentation0,
	size_t indexOfRepresentation1,
	size_t indexOfConstraint)
{
	doBuild(dt, *m_data.get(), mlcp, indexOfRepresentation0, indexOfRepresentation1, indexOfConstraint);

	m_implementations.first->build(
		dt,
		*m_data.get(),
		m_localizations.first,
		mlcp,
		indexOfRepresentation0,
		indexOfConstraint,
		CONSTRAINT_POSITIVE_SIDE);

	SurgSim::Math::Vector3d rotationVector1 = SurgSim::Math::Vector3d::Zero();
	SurgSim::Math::Quaterniond q1 = SurgSim::Math::Quaterniond::Identity();
	if (m_constraintType == FIXED_3DROTATION_VECTOR)
	{
		rotationVector1 = mlcp->b.segment<3>(indexOfConstraint);
		if (rotationVector1.norm() > 1e-8)
		{
			q1 = SurgSim::Math::makeRotationQuaternion(rotationVector1.norm(), rotationVector1.normalized());
		}
	}

	m_implementations.second->build(
		dt,
		*m_data.get(),
		m_localizations.second,
		mlcp,
		indexOfRepresentation1,
		indexOfConstraint,
		CONSTRAINT_NEGATIVE_SIDE);

	SurgSim::Math::Vector3d rotationVector2 = SurgSim::Math::Vector3d::Zero();
	SurgSim::Math::Quaterniond q2 = SurgSim::Math::Quaterniond::Identity();
	if (m_constraintType == FIXED_3DROTATION_VECTOR)
	{
		rotationVector2 = rotationVector1 - mlcp->b.segment<3>(indexOfConstraint);
		if (rotationVector2.norm() > 1e-8)
		{
			q2 = SurgSim::Math::makeRotationQuaternion(rotationVector2.norm(), rotationVector2.normalized());
		}
	}

	// Transform the data to have a rotation vector violation as a rotation vector
	if (m_constraintType == FIXED_3DROTATION_VECTOR)
	{
		double angle;
		SurgSim::Math::Vector3d axis;
		SurgSim::Math::computeAngleAndAxis((q1 * q2.inverse()).normalized(), &angle, &axis);

		mlcp->b.segment<3>(indexOfConstraint) = angle * axis;
	}

	mlcp->constraintTypes.push_back(
				(m_constraintType != INVALID_CONSTRAINT) ? m_mlcpMap[m_constraintType] : Math::MLCP_INVALID_CONSTRAINT);
}

bool Constraint::isActive()
{
	return m_active && m_localizations.first->getRepresentation()->isActive() &&
		   m_localizations.second->getRepresentation()->isActive();
}

void Constraint::setActive(bool flag)
{
	m_active = flag;
}

void Constraint::doBuild(double dt,
	const ConstraintData& data,
	MlcpPhysicsProblem* mlcp,
	size_t indexOfRepresentation0,
	size_t indexOfRepresentation1,
	size_t indexOfConstraint)
{
}

void Constraint::setInformation(ConstraintType constraintType,
	std::shared_ptr<ConstraintData> data,
	std::shared_ptr<Representation> representation0,
	const SurgSim::DataStructures::Location& location0,
	std::shared_ptr<Representation> representation1,
	const SurgSim::DataStructures::Location& location1)
{
	m_constraintType = constraintType;
	SURGSIM_ASSERT(data != nullptr) << "ConstraintData can't be nullptr";
	SURGSIM_ASSERT(representation0 != nullptr) << "First representation can't be nullptr";
	SURGSIM_ASSERT(representation1 != nullptr) << "Second representation can't be nullptr";

	auto localization0 = representation0->createLocalization(location0);
	SURGSIM_ASSERT(localization0 != nullptr) << "Could not create localization for " << representation0->getName();

	auto localization1 = representation1->createLocalization(location1);
	SURGSIM_ASSERT(localization1 != nullptr) << "Could not create localization for " << representation1->getName();

	auto implementation0 = representation0->getConstraintImplementation(m_constraintType);
	SURGSIM_ASSERT(implementation0 != nullptr) << "Could not get implementation for " << representation0->getName();

	auto implementation1 = representation1->getConstraintImplementation(m_constraintType);
	SURGSIM_ASSERT(implementation1 != nullptr) << "Could not get implementation for " << representation1->getName();

	SURGSIM_ASSERT(implementation0->getNumDof() == implementation1->getNumDof())
		<< "The number of DOFs does not match between the two implementations";

	m_data = data;
	m_implementations = std::make_pair(implementation0, implementation1);
	m_localizations = std::make_pair(localization0, localization1);
	m_numDof = implementation0->getNumDof();
}

}; // namespace Physics

}; // namespace SurgSim
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "QmitkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include "mitkRenderWindow.h"
#include <qcursor.h>
#include "mitkDisplayPositionEvent.h"
//##ModelId=3E1EB4410304
mitk::QmitkRenderWindow::QmitkRenderWindow(mitk::BaseRenderer* renderer, QGLFormat glf, QWidget *parent, const char *name)
  : QGLWidget(glf, parent, name), mitk::RenderWindow(name, renderer), m_InitNeeded(false), m_ResizeNeeded(false), m_InResize(false)
{
  InitRenderer();
  setFocusPolicy(QWidget::StrongFocus);
  setMouseTracking(true);
}

//##ModelId=3E1EB4410318
mitk::QmitkRenderWindow::QmitkRenderWindow(mitk::BaseRenderer* renderer, QWidget *parent, const char *name)
: QGLWidget(parent, name), mitk::RenderWindow(name, renderer), m_InitNeeded(false), m_ResizeNeeded(false), m_InResize(false)
{
  InitRenderer();
  setFocusPolicy(QWidget::StrongFocus);
  setMouseTracking(true);
}

//##ModelId=3E1EB441032C
mitk::QmitkRenderWindow::~QmitkRenderWindow()
{

}

void mitk::QmitkRenderWindow::InitRenderer()
{
  m_InitNeeded = true;
  m_ResizeNeeded = true;

  mitk::RenderWindow::InitRenderer();

  this->setAutoBufferSwap( false );
}

/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145903C8
void mitk::QmitkRenderWindow::initializeGL()
{
  m_Renderer->Initialize();
}

/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145A001C
void mitk::QmitkRenderWindow::resizeGL( int w, int h )
{
  if(m_InResize) //@FIXME CRITICAL probably related to VtkSizeBug
    return;
  m_InResize = true;
  if(QGLWidget::isVisible())
  {
    m_Renderer->Resize(w, h);
    updateGL();
  }
  m_InResize = false;
}

/*!
\brief Render the scene
*/
//##ModelId=3E3314590396
void mitk::QmitkRenderWindow::paintGL( )
{
  // Get the native window ID and pass it
  // to the m_Renderer
  // before we render for the first time...
  if(m_InitNeeded)
  {
    WId nId = winId();
    SetWindowId( (void*) nId );
    m_InitNeeded = false;
  }
  else
    // rendering when not visible might cause serious problems (program may hang)
    if(QGLWidget::isVisible())
    {
      m_Renderer->Paint();
    }
}

void mitk::QmitkRenderWindow::showEvent ( QShowEvent * )
{
  // when the widget becomes visible the first time, we need to tell vtk the window size
  if(m_ResizeNeeded)
  {
    m_ResizeNeeded=false;
    m_Renderer->InitSize(width()-40,height()-40);
    //m_Renderer->SetSize(width(),height());
    //    resizeGL(width(),height());
  }
}

//##ModelId=3E3D1D4A00A5
void mitk::QmitkRenderWindow::MakeCurrent()
{
  makeCurrent();
}

void mitk::QmitkRenderWindow::SwapBuffers()
{
  swapBuffers();
};

bool mitk::QmitkRenderWindow::IsSharing () const
{
  return isSharing();
}

//##ModelId=3E6D5DD40306
void mitk::QmitkRenderWindow::mousePressEvent(QMouseEvent *me)
{
  QGLWidget::mousePressEvent(me);
  if (m_Renderer)
  {
    Point2D p; p[0]=me->x(); p[1]=me->y();
    mitk::MouseEvent event(m_Renderer, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    m_Renderer->MousePressEvent(&event);
  }
}

//##ModelId=3E6D5DD4032E
void mitk::QmitkRenderWindow::mouseReleaseEvent(QMouseEvent *me)
{
  QGLWidget::mouseReleaseEvent(me);
  if (m_Renderer)
  {
    Point2D p; p[0]=me->x(); p[1]=me->y();
    mitk::MouseEvent event(m_Renderer, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    m_Renderer->MouseReleaseEvent(&event);
  }
}

//##ModelId=3E6D5DD40356
void mitk::QmitkRenderWindow::mouseMoveEvent(QMouseEvent *me)
{
  QGLWidget::mouseMoveEvent(me);
  if (m_Renderer) {
    Point2D p; p[0]=me->x(); p[1]=me->y();
    mitk::MouseEvent event(m_Renderer, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    m_Renderer->MouseMoveEvent(&event);
  }
}

void mitk::QmitkRenderWindow::wheelEvent(QWheelEvent *we)
{
  we->ignore();
  /*  QGLWidget::wheelEvent(we);
  if (m_Renderer)
    m_Renderer->WheelEvent(we); */
}

//##ModelId=3E6D5DD40388
void mitk::QmitkRenderWindow::keyPressEvent(QKeyEvent *ke)
{
  if (m_Renderer)
  {
    QPoint cp = mapFromGlobal(QCursor::pos());
    mitk::KeyEvent mke(ke->type(), ke->key(), ke->ascii(), ke->state(), ke->text().ascii(), ke->isAutoRepeat(), ke->count(), cp.x(), cp.y(), QCursor::pos().x(), QCursor::pos().y());
    m_Renderer->KeyPressEvent(&mke);
    if(mke.isAccepted())
      ke->accept();
  }
}

//##ModelId=3EF59AD202B7
void mitk::QmitkRenderWindow::Update()
{
  update();
};

void mitk::QmitkRenderWindow::Repaint()
{
  updateGL();
};

//##ModelId=3E6D5DD403B0
void mitk::QmitkRenderWindow::focusInEvent(QFocusEvent*)  {};
//##ModelId=3E6D5DD403E2
void mitk::QmitkRenderWindow::focusOutEvent(QFocusEvent*) {};

//We have to put this in a file containing a class that is directly used
//somewhere. Otherwise, e.g. when put in VtkRenderWindowInteractor.cpp,
//it is removed by the linker.
#include "VtkQRenderWindowInteractor.h"
VtkQRenderWindowInteractorFactory vtkQRenderWindowInteractorFactory;
#include "mitkIncludeFFI.h"
<commit_msg>FIX: compatibility for external version<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "QmitkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include "mitkRenderWindow.h"
#include <qcursor.h>
#include "mitkDisplayPositionEvent.h"
//##ModelId=3E1EB4410304
mitk::QmitkRenderWindow::QmitkRenderWindow(mitk::BaseRenderer* renderer, QGLFormat glf, QWidget *parent, const char *name)
  : QGLWidget(glf, parent, name), mitk::RenderWindow(name, renderer), m_InitNeeded(false), m_ResizeNeeded(false), m_InResize(false)
{
  InitRenderer();
  setFocusPolicy(QWidget::StrongFocus);
  setMouseTracking(true);
}

//##ModelId=3E1EB4410318
mitk::QmitkRenderWindow::QmitkRenderWindow(mitk::BaseRenderer* renderer, QWidget *parent, const char *name)
: QGLWidget(parent, name), mitk::RenderWindow(name, renderer), m_InitNeeded(false), m_ResizeNeeded(false), m_InResize(false)
{
  InitRenderer();
  setFocusPolicy(QWidget::StrongFocus);
  setMouseTracking(true);
}

//##ModelId=3E1EB441032C
mitk::QmitkRenderWindow::~QmitkRenderWindow()
{

}

void mitk::QmitkRenderWindow::InitRenderer()
{
  m_InitNeeded = true;
  m_ResizeNeeded = true;

  mitk::RenderWindow::InitRenderer();

  this->setAutoBufferSwap( false );
}

/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145903C8
void mitk::QmitkRenderWindow::initializeGL()
{
  m_Renderer->Initialize();
}

/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145A001C
void mitk::QmitkRenderWindow::resizeGL( int w, int h )
{
  if(m_InResize) //@FIXME CRITICAL probably related to VtkSizeBug
    return;
  m_InResize = true;
  if(QGLWidget::isVisible())
  {
    m_Renderer->Resize(w, h);
    updateGL();
  }
  m_InResize = false;
}

/*!
\brief Render the scene
*/
//##ModelId=3E3314590396
void mitk::QmitkRenderWindow::paintGL( )
{
  // Get the native window ID and pass it
  // to the m_Renderer
  // before we render for the first time...
  if(m_InitNeeded)
  {
    WId nId = winId();
    SetWindowId( (void*) nId );
    m_InitNeeded = false;
  }
  else
    // rendering when not visible might cause serious problems (program may hang)
    if(QGLWidget::isVisible())
    {
      m_Renderer->Paint();
    }
}

void mitk::QmitkRenderWindow::showEvent ( QShowEvent * )
{
  // when the widget becomes visible the first time, we need to tell vtk the window size
  if(m_ResizeNeeded)
  {
    m_ResizeNeeded=false;
    m_Renderer->InitSize(width()-40,height()-40);
    //m_Renderer->SetSize(width(),height());
    //    resizeGL(width(),height());
  }
}

//##ModelId=3E3D1D4A00A5
void mitk::QmitkRenderWindow::MakeCurrent()
{
  makeCurrent();
}

void mitk::QmitkRenderWindow::SwapBuffers()
{
  swapBuffers();
};

bool mitk::QmitkRenderWindow::IsSharing () const
{
  return isSharing();
}

//##ModelId=3E6D5DD40306
void mitk::QmitkRenderWindow::mousePressEvent(QMouseEvent *me)
{
  QGLWidget::mousePressEvent(me);
  if (m_Renderer)
  {
    Point2D p; p[0]=me->x(); p[1]=me->y();
    mitk::MouseEvent event(m_Renderer, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    m_Renderer->MousePressEvent(&event);
  }
}

//##ModelId=3E6D5DD4032E
void mitk::QmitkRenderWindow::mouseReleaseEvent(QMouseEvent *me)
{
  QGLWidget::mouseReleaseEvent(me);
  if (m_Renderer)
  {
    Point2D p; p[0]=me->x(); p[1]=me->y();
    mitk::MouseEvent event(m_Renderer, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    m_Renderer->MouseReleaseEvent(&event);
  }
}

//##ModelId=3E6D5DD40356
void mitk::QmitkRenderWindow::mouseMoveEvent(QMouseEvent *me)
{
  QGLWidget::mouseMoveEvent(me);
  if (m_Renderer) {
    Point2D p; p[0]=me->x(); p[1]=me->y();
    mitk::MouseEvent event(m_Renderer, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    m_Renderer->MouseMoveEvent(&event);
  }
}

void mitk::QmitkRenderWindow::wheelEvent(QWheelEvent *we)
{
  we->ignore();
  /*  QGLWidget::wheelEvent(we);
  if (m_Renderer)
    m_Renderer->WheelEvent(we); */
}

//##ModelId=3E6D5DD40388
void mitk::QmitkRenderWindow::keyPressEvent(QKeyEvent *ke)
{
  if (m_Renderer)
  {
    QPoint cp = mapFromGlobal(QCursor::pos());
    mitk::KeyEvent mke(ke->type(), ke->key(), ke->ascii(), ke->state(), ke->text().ascii(), ke->isAutoRepeat(), ke->count(), cp.x(), cp.y(), QCursor::pos().x(), QCursor::pos().y());
    m_Renderer->KeyPressEvent(&mke);
    if(mke.isAccepted())
      ke->accept();
  }
}

//##ModelId=3EF59AD202B7
void mitk::QmitkRenderWindow::Update()
{
  update();
};

void mitk::QmitkRenderWindow::Repaint()
{
  updateGL();
};

//##ModelId=3E6D5DD403B0
void mitk::QmitkRenderWindow::focusInEvent(QFocusEvent*)  {};
//##ModelId=3E6D5DD403E2
void mitk::QmitkRenderWindow::focusOutEvent(QFocusEvent*) {};

//We have to put this in a file containing a class that is directly used
//somewhere. Otherwise, e.g. when put in VtkRenderWindowInteractor.cpp,
//it is removed by the linker.
#include "VtkQRenderWindowInteractor.h"
VtkQRenderWindowInteractorFactory vtkQRenderWindowInteractorFactory;
#ifdef MBI_INTERNAL
#include "mitkIncludeFFI.h"
#endif<|endoftext|>


<commit_before>/**
 *  @file result_set_test.cpp
 *  @date 19.12.2014
 *  @author mwarsinsky
 *  @brief
 *
 *  $LastChangedDate$
 *  $LastChangedBy$
 *  $LastChangedRevision$
 *
 */

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit_toolbox/extensions/assert_equal_with_different_types.h>
#include "cpp_odbc/connection.h"
#include "pydbc/connection.h"
#include "mock_classes.h"
#include "pydbc/result_set.h"
#include <sqlext.h>
#include <boost/variant/get.hpp>
#include <cstring>

class result_set_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( result_set_test );

	CPPUNIT_TEST( fetch_without_columns );
	CPPUNIT_TEST( fetch_with_single_string_column );
	CPPUNIT_TEST( fetch_with_single_integer_column );
	CPPUNIT_TEST( constructor_both_types );

CPPUNIT_TEST_SUITE_END();

public:

	void fetch_without_columns();
	void fetch_with_single_string_column();
	void fetch_with_single_integer_column();
	void constructor_both_types();

};

// Registers the fixture with the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( result_set_test );

using pydbc_test::mock_connection;
using pydbc_test::mock_statement;

namespace {

	std::shared_ptr<testing::NiceMock<mock_statement>> prepare_mock_with_columns(std::vector<long> const & column_types)
	{
		auto statement = std::make_shared<testing::NiceMock<mock_statement>>();

		ON_CALL(*statement, do_number_of_columns())
			.WillByDefault(testing::Return(column_types.size()));

		for (std::size_t i = 0; i != column_types.size(); ++i) {
			ON_CALL(*statement, do_get_integer_column_attribute(i + 1, SQL_DESC_TYPE))
				.WillByDefault(testing::Return(column_types[i]));
		}
		return statement;
	}

	/**
	* Change the address of the given target_pointer to point to the third argument of the mocked function
	*/
	ACTION_P(store_pointer_to_buffer_in, target_pointer) {
		*target_pointer = &arg2;
	}

	/**
	 * Set the mock statement to expect calls to bind_buffer. Returns a vector of pointers to buffers
	 * which are bound to the individual columns. These values will be filled when bind_column is called.
	 */
	std::vector<cpp_odbc::multi_value_buffer *> expect_calls_to_bind_buffer(mock_statement & statement, std::vector<SQLSMALLINT> const & expected_bind_types)
	{
		std::vector<cpp_odbc::multi_value_buffer *> buffers(expected_bind_types.size(), nullptr);

		for (std::size_t i = 0; i != expected_bind_types.size(); ++i) {
			EXPECT_CALL(statement, do_bind_column(i + 1, expected_bind_types[0], testing::_))
				.WillOnce(store_pointer_to_buffer_in(&buffers[i]));
		}

		return buffers;
	}

}

void result_set_test::fetch_without_columns()
{
	auto statement = prepare_mock_with_columns({});

	ON_CALL(*statement, do_fetch_next())
		.WillByDefault(testing::Return(true));

	auto result_set = pydbc::result_set(statement);
	CPPUNIT_ASSERT_EQUAL(0, result_set.fetch_one().size());
}

namespace {
	/**
	* @brief Store the given string value as the first value in
	*        the buffer pointed to by pointer_to_buffer
	*/
	ACTION_P2(put_string_value_in_buffer, pointer_to_buffer, value) {
		auto element = (*pointer_to_buffer)[0];
		std::memcpy(element.data_pointer, value.data(), value.size() + 1);
		element.indicator = value.size();
	}
}

void result_set_test::fetch_with_single_string_column()
{
	auto statement = prepare_mock_with_columns({SQL_VARCHAR});
	auto buffers = expect_calls_to_bind_buffer(*statement, {SQL_CHAR});

	auto result_set = pydbc::result_set(statement);
	CPPUNIT_ASSERT(buffers[0] != nullptr);

	std::string const expected_value = "this is a test string";
	EXPECT_CALL(*statement, do_fetch_next())
		.WillOnce(testing::DoAll(
					put_string_value_in_buffer(buffers[0], expected_value),
					testing::Return(true)
				));

	auto row = result_set.fetch_one();
	CPPUNIT_ASSERT_EQUAL(1, row.size());
	CPPUNIT_ASSERT_EQUAL(expected_value, boost::get<std::string>(row[0]));
}

namespace {
	/**
	 * @brief Store the given binary value as the first value in
	 *        the buffer pointed to by pointer_to_buffer
	 */
	ACTION_P2(put_binary_value_in_buffer, pointer_to_buffer, value) {
		auto element = (*pointer_to_buffer)[0];
		std::memcpy(element.data_pointer, &value, sizeof(value));
		element.indicator = sizeof(value);
	}
}

void result_set_test::fetch_with_single_integer_column()
{
	auto statement = prepare_mock_with_columns({SQL_INTEGER});
	auto buffers = expect_calls_to_bind_buffer(*statement, {SQL_C_SBIGINT});

	auto result_set = pydbc::result_set(statement);
	CPPUNIT_ASSERT(buffers[0] != nullptr);

	long const expected_value = 42;
	EXPECT_CALL(*statement, do_fetch_next())
		.WillOnce(testing::DoAll(
					put_binary_value_in_buffer(buffers[0], expected_value),
					testing::Return(true)
				));

	auto row = result_set.fetch_one();
	CPPUNIT_ASSERT_EQUAL(1, row.size());
	CPPUNIT_ASSERT_EQUAL(expected_value, boost::get<long>(row[0]));
}

void result_set_test::constructor_both_types()
{
	auto statement = std::make_shared<testing::NiceMock<mock_statement>>();

	EXPECT_CALL(*statement, do_number_of_columns())
		.WillOnce(testing::Return(2));
	EXPECT_CALL(*statement, do_get_integer_column_attribute(1,SQL_DESC_TYPE))
		.WillOnce(testing::Return(SQL_VARCHAR));
	EXPECT_CALL(*statement, do_get_integer_column_attribute(2,SQL_DESC_TYPE))
		.WillOnce(testing::Return(SQL_INTEGER));
	EXPECT_CALL(*statement, do_bind_column(1, SQL_CHAR, testing::_)).Times(1);
	EXPECT_CALL(*statement, do_bind_column(2, SQL_C_SBIGINT, testing::_)).Times(1);

	auto result_set = pydbc::result_set(statement);
//	CPPUNIT_ASSERT_EQUAL(2, result_set.columns.size());
	CPPUNIT_FAIL("not implemented yet!");
}

<commit_msg>Refactored remaining test so that it works<commit_after>/**
 *  @file result_set_test.cpp
 *  @date 19.12.2014
 *  @author mwarsinsky
 *  @brief
 *
 *  $LastChangedDate$
 *  $LastChangedBy$
 *  $LastChangedRevision$
 *
 */

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit_toolbox/extensions/assert_equal_with_different_types.h>
#include "cpp_odbc/connection.h"
#include "pydbc/connection.h"
#include "mock_classes.h"
#include "pydbc/result_set.h"
#include <sqlext.h>
#include <boost/variant/get.hpp>
#include <cstring>

class result_set_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( result_set_test );

	CPPUNIT_TEST( fetch_without_columns );
	CPPUNIT_TEST( fetch_with_single_string_column );
	CPPUNIT_TEST( fetch_with_single_integer_column );
	CPPUNIT_TEST( fetch_with_multiple_columns );

CPPUNIT_TEST_SUITE_END();

public:

	void fetch_without_columns();
	void fetch_with_single_string_column();
	void fetch_with_single_integer_column();
	void fetch_with_multiple_columns();

};

// Registers the fixture with the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( result_set_test );

using pydbc_test::mock_connection;
using pydbc_test::mock_statement;

namespace {

	std::shared_ptr<testing::NiceMock<mock_statement>> prepare_mock_with_columns(std::vector<long> const & column_types)
	{
		auto statement = std::make_shared<testing::NiceMock<mock_statement>>();

		ON_CALL(*statement, do_number_of_columns())
			.WillByDefault(testing::Return(column_types.size()));

		for (std::size_t i = 0; i != column_types.size(); ++i) {
			ON_CALL(*statement, do_get_integer_column_attribute(i + 1, SQL_DESC_TYPE))
				.WillByDefault(testing::Return(column_types[i]));
		}
		return statement;
	}

	/**
	* Change the address of the given target_pointer to point to the third argument of the mocked function
	*/
	ACTION_P(store_pointer_to_buffer_in, target_pointer) {
		*target_pointer = &arg2;
	}

	/**
	 * Set the mock statement to expect calls to bind_buffer. Returns a vector of pointers to buffers
	 * which are bound to the individual columns. These values will be filled when bind_column is called.
	 */
	std::vector<cpp_odbc::multi_value_buffer *> expect_calls_to_bind_buffer(mock_statement & statement, std::vector<SQLSMALLINT> const & expected_bind_types)
	{
		std::vector<cpp_odbc::multi_value_buffer *> buffers(expected_bind_types.size(), nullptr);

		for (std::size_t i = 0; i != expected_bind_types.size(); ++i) {
			EXPECT_CALL(statement, do_bind_column(i + 1, expected_bind_types[0], testing::_))
				.WillOnce(store_pointer_to_buffer_in(&buffers[i]));
		}

		return buffers;
	}

}

void result_set_test::fetch_without_columns()
{
	auto statement = prepare_mock_with_columns({});

	ON_CALL(*statement, do_fetch_next())
		.WillByDefault(testing::Return(true));

	auto result_set = pydbc::result_set(statement);
	CPPUNIT_ASSERT_EQUAL(0, result_set.fetch_one().size());
}

namespace {
	/**
	* @brief Store the given string value as the first value in
	*        the buffer pointed to by pointer_to_buffer
	*/
	ACTION_P2(put_string_value_in_buffer, pointer_to_buffer, value) {
		auto element = (*pointer_to_buffer)[0];
		std::memcpy(element.data_pointer, value.data(), value.size() + 1);
		element.indicator = value.size();
	}
}

void result_set_test::fetch_with_single_string_column()
{
	auto statement = prepare_mock_with_columns({SQL_VARCHAR});
	auto buffers = expect_calls_to_bind_buffer(*statement, {SQL_CHAR});

	auto result_set = pydbc::result_set(statement);
	CPPUNIT_ASSERT(buffers[0] != nullptr);

	std::string const expected_value = "this is a test string";
	EXPECT_CALL(*statement, do_fetch_next())
		.WillOnce(testing::DoAll(
					put_string_value_in_buffer(buffers[0], expected_value),
					testing::Return(true)
				));

	auto row = result_set.fetch_one();
	CPPUNIT_ASSERT_EQUAL(1, row.size());
	CPPUNIT_ASSERT_EQUAL(expected_value, boost::get<std::string>(row[0]));
}

namespace {
	/**
	 * @brief Store the given binary value as the first value in
	 *        the buffer pointed to by pointer_to_buffer
	 */
	ACTION_P2(put_binary_value_in_buffer, pointer_to_buffer, value) {
		auto element = (*pointer_to_buffer)[0];
		std::memcpy(element.data_pointer, &value, sizeof(value));
		element.indicator = sizeof(value);
	}
}

void result_set_test::fetch_with_single_integer_column()
{
	auto statement = prepare_mock_with_columns({SQL_INTEGER});
	auto buffers = expect_calls_to_bind_buffer(*statement, {SQL_C_SBIGINT});

	auto result_set = pydbc::result_set(statement);
	CPPUNIT_ASSERT(buffers[0] != nullptr);

	long const expected_value = 42;
	EXPECT_CALL(*statement, do_fetch_next())
		.WillOnce(testing::DoAll(
					put_binary_value_in_buffer(buffers[0], expected_value),
					testing::Return(true)
				));

	auto row = result_set.fetch_one();
	CPPUNIT_ASSERT_EQUAL(1, row.size());
	CPPUNIT_ASSERT_EQUAL(expected_value, boost::get<long>(row[0]));
}

void result_set_test::fetch_with_multiple_columns()
{
	auto statement = prepare_mock_with_columns({SQL_INTEGER, SQL_INTEGER});
	auto buffers = expect_calls_to_bind_buffer(*statement, {SQL_C_SBIGINT, SQL_C_SBIGINT});

	auto result_set = pydbc::result_set(statement);

	std::vector<long> expected_values = {42, 17};
	EXPECT_CALL(*statement, do_fetch_next())
		.WillOnce(testing::DoAll(
					put_binary_value_in_buffer(buffers[0], expected_values[0]),
					put_binary_value_in_buffer(buffers[1], expected_values[1]),
					testing::Return(true)
				));

	auto row = result_set.fetch_one();
	CPPUNIT_ASSERT_EQUAL(2, row.size());
	CPPUNIT_ASSERT_EQUAL(expected_values[0], boost::get<long>(row[0]));
	CPPUNIT_ASSERT_EQUAL(expected_values[1], boost::get<long>(row[1]));
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003 Unai Garro <ugarro@users.sourceforge.net>
 */

#include "krecipesview.h"

#include <iostream>

#include <qpainter.h>
#include <qlayout.h>
#include <qsplitter.h>

#include <kurl.h>
#include <kapp.h>
#include <ktrader.h>
#include <klibloader.h>
#include <kmessagebox.h>
#include <krun.h>
#include <klocale.h>
#include <kconfig.h>

#include "setupwizard.h"
#include "recipeinputdialog.h"
#include "recipeviewdialog.h"
#include "selectrecipedialog.h"
#include "ingredientsdialog.h"
#include "propertiesdialog.h"
#include "shoppinglistdialog.h"
#include "dietwizarddialog.h"
#include "categorieseditordialog.h"
#include "authorsdialog.h"
#include "unitsdialog.h"
#include "recipedb.h"
#include "menugroup.h"

KrecipesView::KrecipesView(QWidget *parent)
    : QVBox(parent)
{
    // Init the setup wizard if necessary
    wizard();

    // Initialize Database
    KConfig *config; config=kapp->config(); config->setGroup("Server");
    QString host=config->readEntry( "Host","localhost");
    QString user=config->readEntry( "Username",QString::null);
    QString pass=config->readEntry("Password",QString::null);
    QString dbname=config->readEntry( "DBName", DEFAULT_DB_NAME);
    database=new RecipeDB(host,user,pass,dbname);

    splitter=new QSplitter(this);

    // Set Splitter Parameters
    splitter->setFrameShape( QSplitter::NoFrame );
    splitter->setFrameShadow( QSplitter::Plain );
    splitter->setOrientation( QSplitter::Horizontal );
    splitter->setOpaqueResize();

// Create Left and Right Panels (splitter)

    leftPanel=new MenuGroup(splitter,"leftPanel");
    rightPanel=new QWidgetStack(splitter,"rightPanel");
   leftPanel->setMinimumWidth(22);

    // Design Resizing of the panels
   splitter->setResizeMode(leftPanel,QSplitter::FollowSizeHint);

    // Design Left Panel
    il=new KIconLoader;
    button0=new QPushButton(leftPanel); button0->setFlat(true);
    button0->setIconSet(il->loadIconSet("filefind", KIcon::Small));
    button0->setGeometry(0,0,150,30);

    button1=new QPushButton(leftPanel); button1->setFlat(true);
    button1->setIconSet(il->loadIconSet( "trolley", KIcon::Small ));
	  button1->setGeometry(0,30,150,30);

    button2=new QPushButton(leftPanel); button2->setFlat(true);
    button2->setIconSet(il->loadIconSet( "ingredients", KIcon::Small ));
    button2->setGeometry(0,60,150,30);

    button3=new QPushButton(leftPanel); button3->setFlat(true);
    button3->setIconSet(il->loadIconSet( "properties", KIcon::Small ));
	  button3->setGeometry(0,90,150,30);

    button4=new QPushButton(leftPanel); button4->setFlat(true);
    button4->setIconSet(il->loadIconSet( "units", KIcon::Small ));
	  button4->setGeometry(0,120,150,30);

    button5=new QPushButton(leftPanel); button5->setFlat(true);
    button5->setIconSet(il->loadIconSet( "categories", KIcon::Small ));
	  button5->setGeometry(0,150,150,30);

    button6=new QPushButton(leftPanel); button6->setFlat(true);
    button6->setIconSet(il->loadIconSet( "personal", KIcon::Small ));
	  button6->setGeometry(0,180,150,30);

    // Right Panel Widgets
    inputPanel=new RecipeInputDialog(rightPanel,database); rightPanel->addWidget(inputPanel);
    viewPanel=new RecipeViewDialog(rightPanel,database,1);rightPanel->addWidget(viewPanel);
    selectPanel=new SelectRecipeDialog(rightPanel,database);rightPanel->addWidget(selectPanel);
    ingredientsPanel=new IngredientsDialog(rightPanel,database);rightPanel->addWidget(ingredientsPanel);
    propertiesPanel=new PropertiesDialog(rightPanel,database);rightPanel->addWidget(propertiesPanel);
    unitsPanel=new UnitsDialog(rightPanel,database); rightPanel->addWidget(unitsPanel);
    shoppingListPanel=new ShoppingListDialog(rightPanel,database); rightPanel->addWidget(shoppingListPanel);
    dietPanel=new DietWizardDialog(rightPanel,database);rightPanel->addWidget(dietPanel);
    categoriesPanel=new CategoriesEditorDialog(rightPanel,database); rightPanel->addWidget(categoriesPanel);
    authorsPanel=new AuthorsDialog(rightPanel,database); rightPanel->addWidget(inputPanel);
    rightPanel->addWidget(authorsPanel);

    // i18n
    translate();

    // Initialize Variables
    recipeButton=0;

    // Connect Signals from Left Panel to slotSetPanel()
     connect( leftPanel, SIGNAL(clicked(int)),this, SLOT(slotSetPanel(int)) );
     connect(shoppingListPanel,SIGNAL(wizardClicked()),this,SLOT(slotSetDietWizardPanel()));

    rightPanel->raiseWidget(selectPanel);

    // Retransmit signal to parent to Enable/Disable the Save Button
    connect (inputPanel, SIGNAL(enableSaveOption(bool)), this, SIGNAL(enableSaveOption(bool)));

    // Create a new button when a recipe is unsaved
    connect (inputPanel, SIGNAL(createButton(QWidget*,QString)), this, SLOT(addRecipeButton(QWidget*,QString)));

    // Connect Signals from selectPanel (SelectRecipeDialog)

    connect (selectPanel, SIGNAL(recipeSelected(int,int)),this, SLOT(actionRecipe(int,int)));

    // Resize signal
    connect (leftPanel, SIGNAL(resized(int,int)),this, SLOT(resizeButtons()));

    // Close a recipe when requested (just switch panels)
    connect(inputPanel,SIGNAL(closeRecipe()),this,SLOT(closeRecipe()));

    // Show a recipe when requested (just switch panels)
    connect(inputPanel,SIGNAL(showRecipe(int)),this,SLOT(showRecipe(int)));

    // Add recipe to the shopping list when requested
    connect(inputPanel,SIGNAL(addRecipeToShoppingList(int)),shoppingListPanel,SLOT(addRecipeToShoppingList(int)));
}

KrecipesView::~KrecipesView()
{
delete il; // remove iconloader
}

void KrecipesView::translate(){
  button0->setText(i18n("Find/Edit Recipes"));
  QToolTip::add(button0, i18n("Find/Edit Recipes"));
  button1->setText(i18n("Shopping List"));
  QToolTip::add(button1, i18n("Shopping List"));
  button2->setText(i18n("Ingredients"));
  QToolTip::add(button2, i18n("Ingredients"));
  button3->setText(i18n("Properties"));
  QToolTip::add(button3, i18n("Properties"));
  button4->setText(i18n("Units"));
  QToolTip::add(button4, i18n("Units"));
  button5->setText(i18n("Recipe Categories"));
  QToolTip::add(button5, i18n("Recipe Categories"));
  button6->setText(i18n("Authors"));
  QToolTip::add(button6, i18n("Authors"));
}

void KrecipesView::print(QPainter *p, int height, int width)
{
    // do the actual printing, here
    // p->drawText(etc..)
}

void KrecipesView::slotSetTitle(const QString& title)
{
    emit signalChangeCaption(title);
}

// Function to switch panels
void KrecipesView::slotSetPanel(int w)
{
switch (w)
{
case SelectP: selectPanel->reload(); // Reload data
	this->rightPanel->raiseWidget(selectPanel);
	break;
case ShoppingP: shoppingListPanel->reload(); // Reload data
	this->rightPanel->raiseWidget(shoppingListPanel);
	break;
case IngredientsP: ingredientsPanel->reload();// Reload data
	this->rightPanel->raiseWidget(ingredientsPanel);
	break;
case PropertiesP: propertiesPanel->reload();
	this->rightPanel->raiseWidget(propertiesPanel);
	break;
case UnitsP: unitsPanel->reload(); // Reload data
	this->rightPanel->raiseWidget(unitsPanel);
	break;
case CategoriesP: this->rightPanel->raiseWidget(categoriesPanel);
	break;
case DietWizardP: dietPanel->reload();
	this->rightPanel->raiseWidget(dietPanel);
	break;
case AuthorsP: authorsPanel->reload();
	this->rightPanel->raiseWidget(authorsPanel);
	break;

}

}
void KrecipesView::save(void)
{
inputPanel->save();
}

void KrecipesView::actionRecipe(int recipeID, int action)
{
if (action==0) //Show
	{
	showRecipe(recipeID);
	}
else if (action==1) // Edit
{
	if ( !inputPanel->everythingSaved() )
	{
		switch( KMessageBox::questionYesNoCancel( this,
		  i18n(QString("Recipe \"%1\" contains unsaved changes.\n"
		  "Do you want to save changes made to this recipe before editing another recipe?").arg(recipeButton->text())),
		   i18n("Unsaved changes") ) )
		{
			case KMessageBox::Yes: inputPanel->save(); break;
			case KMessageBox::No: break;
			case KMessageBox::Cancel: return;
		}
	}

	inputPanel->loadRecipe(recipeID);
	rightPanel->raiseWidget(inputPanel);
}
else if (action==2) //Remove
{
database->removeRecipe(recipeID);
selectPanel->reload();
}
}

void KrecipesView::createNewRecipe(void)
{
if ( !inputPanel->everythingSaved() )
{
	switch( KMessageBox::questionYesNoCancel( this,
	  i18n(QString("Recipe \"%1\" contains unsaved changes.\n"
	  "Do you want to save changes made to this recipe before creating a new recipe?").arg(recipeButton->text())),
	   i18n("Unsaved changes") ) )
	{
		case KMessageBox::Yes: inputPanel->save(); break;
		case KMessageBox::No: break;
		case KMessageBox::Cancel: return;
	}
}

inputPanel->newRecipe();
rightPanel->raiseWidget(inputPanel);
}

void KrecipesView::createNewElement(void)
{
if (rightPanel->id(rightPanel->visibleWidget())==4) //Properties Panel is the active one
{
propertiesPanel->createNewProperty();
}
else{
  createNewRecipe();
  }
}

void KrecipesView::wizard(void)
{
KConfig *config=kapp->config();
config->setGroup("Wizard");

bool setupDone=config->readBoolEntry( "SystemSetup",false);
if (!setupDone)
{

bool setupUser,initData,adminEnabled; QString adminUser,adminPass,user,pass,host,client,dbName;
bool isRemote;

SetupWizard *setupWizard=new SetupWizard(this);
if(setupWizard->exec()== QDialog::Accepted)
{
std::cerr<<"Setting up\n";
setupWizard->getOptions(setupUser,initData);

// Setup user if necessary

if (setupUser) // Don't setup user if checkbox of existing user... was set
	{
	std::cerr<<"Setting up user\n";
	setupWizard->getAdminInfo(adminEnabled,adminUser,adminPass);
	setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass);

	if (!adminEnabled) // Use root without password
	{
	std::cerr<<"Using default admin\n";
	adminUser="root";
	adminPass=QString::null;
	}
	if (!isRemote) // Use localhost
	{
	std::cerr<<"Using localhost\n";
	host="localhost";
	client="localhost";
	}

	setupUserPermissions(host,client,dbName,user,pass,adminUser,adminPass);
	}

// Initialize database with data if requested

if (initData)
	{
	setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass);
	initializeData(host,dbName,user,pass); // Populate data as normal user
	}

}
delete setupWizard;
}
}

void KrecipesView::slotSetDietWizardPanel(void)
{
dietPanel->reload();
rightPanel->raiseWidget(dietPanel);
}

void KrecipesView::setupUserPermissions(const QString &host, const QString &client, const QString &dbName, const QString &newUser,const QString &newPass,const QString &adminUser,const QString &adminPass)
{
RecipeDB *db;

if (adminUser!=QString::null)
	{ // Login as admin in the (remote) server and createDB if necessary
	std::cerr<<"Open db as:"<< adminUser.latin1() <<",*** with password ****\n";
	db= new RecipeDB(host,adminUser,adminPass,dbName,true); // true means initialize db structure (It won't destroy data if exists)
	}
	else{ // Login as root with no password
	std::cerr<<"Open db as root, with no password\n";
	db=new RecipeDB(host,"root",QString::null,dbName,true);
	}

db->givePermissions(dbName,newUser,newPass,client); // give permissions to the user

delete db; //it closes the db automatically
}

void KrecipesView::initializeData(const QString &host,const QString &dbName, const QString &user,const QString &pass)
{
RecipeDB *db;
db= new RecipeDB(host,user,pass,dbName);
db->initializeData();
delete db; //it closes the db automatically
}

void KrecipesView::resizeButtons(){
  button0->resize(leftPanel->width(), 30);
  button1->resize(leftPanel->width(), 30);
  button2->resize(leftPanel->width(), 30);
  button3->resize(leftPanel->width(), 30);
  button4->resize(leftPanel->width(), 30);
  button5->resize(leftPanel->width(), 30);
  button6->resize(leftPanel->width(), 30);
  if(recipeButton){
    recipeButton->resize(leftPanel->width(), 30);
  }
}

void KrecipesView::addRecipeButton(QWidget *w,QString title)
{
recipeWidget=w;

if (!recipeButton)
{
	recipeButton=new MenuButton(leftPanel,"recipeButton");
	recipeButton->setFlat(true);recipeButton->setIconSet(il->loadIconSet("filesave",KIcon::Small));
	recipeButton->setGeometry(0,250,150,30);
	recipeButton->setTitle(title);
	recipeButton->resize(leftPanel->width(),30);
	recipeButton->show();
	connect(recipeButton,SIGNAL(clicked()),this,SLOT(switchToRecipe()));
	connect((RecipeInputDialog *)w,SIGNAL(titleChanged(const QString&)),recipeButton,SLOT(setTitle(const QString&)));
}

}

void KrecipesView::switchToRecipe(void)
{
rightPanel->raiseWidget(recipeWidget);
}

void KrecipesView::closeRecipe(void)
{
selectPanel->reload();
rightPanel->raiseWidget(selectPanel);
delete recipeButton; recipeButton=0;
}

void KrecipesView::showRecipe(int recipeID)
{
viewPanel->loadRecipe(recipeID);
rightPanel->raiseWidget(viewPanel);
}

////////////////// Class MenuButton Methods///////////////////

MenuButton::MenuButton(QWidget *parent,const char *name):QPushButton(parent,name)
{
}

MenuButton::~MenuButton()
{
}

void MenuButton::setTitle(const QString &title)
{
  setText(title);
  QToolTip::add(this, title);
}

#include "krecipesview.moc"
<commit_msg>Fix two strings that were incorrectly written for translation<commit_after>/*
 * Copyright (C) 2003 Unai Garro <ugarro@users.sourceforge.net>
 */

#include "krecipesview.h"

#include <iostream>

#include <qpainter.h>
#include <qlayout.h>
#include <qsplitter.h>

#include <kurl.h>
#include <kapp.h>
#include <ktrader.h>
#include <klibloader.h>
#include <kmessagebox.h>
#include <krun.h>
#include <klocale.h>
#include <kconfig.h>

#include "setupwizard.h"
#include "recipeinputdialog.h"
#include "recipeviewdialog.h"
#include "selectrecipedialog.h"
#include "ingredientsdialog.h"
#include "propertiesdialog.h"
#include "shoppinglistdialog.h"
#include "dietwizarddialog.h"
#include "categorieseditordialog.h"
#include "authorsdialog.h"
#include "unitsdialog.h"
#include "recipedb.h"
#include "menugroup.h"

KrecipesView::KrecipesView(QWidget *parent)
    : QVBox(parent)
{
    // Init the setup wizard if necessary
    wizard();

    // Initialize Database
    KConfig *config; config=kapp->config(); config->setGroup("Server");
    QString host=config->readEntry( "Host","localhost");
    QString user=config->readEntry( "Username",QString::null);
    QString pass=config->readEntry("Password",QString::null);
    QString dbname=config->readEntry( "DBName", DEFAULT_DB_NAME);
    database=new RecipeDB(host,user,pass,dbname);

    splitter=new QSplitter(this);

    // Set Splitter Parameters
    splitter->setFrameShape( QSplitter::NoFrame );
    splitter->setFrameShadow( QSplitter::Plain );
    splitter->setOrientation( QSplitter::Horizontal );
    splitter->setOpaqueResize();

// Create Left and Right Panels (splitter)

    leftPanel=new MenuGroup(splitter,"leftPanel");
    rightPanel=new QWidgetStack(splitter,"rightPanel");
   leftPanel->setMinimumWidth(22);

    // Design Resizing of the panels
   splitter->setResizeMode(leftPanel,QSplitter::FollowSizeHint);

    // Design Left Panel
    il=new KIconLoader;
    button0=new QPushButton(leftPanel); button0->setFlat(true);
    button0->setIconSet(il->loadIconSet("filefind", KIcon::Small));
    button0->setGeometry(0,0,150,30);

    button1=new QPushButton(leftPanel); button1->setFlat(true);
    button1->setIconSet(il->loadIconSet( "trolley", KIcon::Small ));
	  button1->setGeometry(0,30,150,30);

    button2=new QPushButton(leftPanel); button2->setFlat(true);
    button2->setIconSet(il->loadIconSet( "ingredients", KIcon::Small ));
    button2->setGeometry(0,60,150,30);

    button3=new QPushButton(leftPanel); button3->setFlat(true);
    button3->setIconSet(il->loadIconSet( "properties", KIcon::Small ));
	  button3->setGeometry(0,90,150,30);

    button4=new QPushButton(leftPanel); button4->setFlat(true);
    button4->setIconSet(il->loadIconSet( "units", KIcon::Small ));
	  button4->setGeometry(0,120,150,30);

    button5=new QPushButton(leftPanel); button5->setFlat(true);
    button5->setIconSet(il->loadIconSet( "categories", KIcon::Small ));
	  button5->setGeometry(0,150,150,30);

    button6=new QPushButton(leftPanel); button6->setFlat(true);
    button6->setIconSet(il->loadIconSet( "personal", KIcon::Small ));
	  button6->setGeometry(0,180,150,30);

    // Right Panel Widgets
    inputPanel=new RecipeInputDialog(rightPanel,database); rightPanel->addWidget(inputPanel);
    viewPanel=new RecipeViewDialog(rightPanel,database,1);rightPanel->addWidget(viewPanel);
    selectPanel=new SelectRecipeDialog(rightPanel,database);rightPanel->addWidget(selectPanel);
    ingredientsPanel=new IngredientsDialog(rightPanel,database);rightPanel->addWidget(ingredientsPanel);
    propertiesPanel=new PropertiesDialog(rightPanel,database);rightPanel->addWidget(propertiesPanel);
    unitsPanel=new UnitsDialog(rightPanel,database); rightPanel->addWidget(unitsPanel);
    shoppingListPanel=new ShoppingListDialog(rightPanel,database); rightPanel->addWidget(shoppingListPanel);
    dietPanel=new DietWizardDialog(rightPanel,database);rightPanel->addWidget(dietPanel);
    categoriesPanel=new CategoriesEditorDialog(rightPanel,database); rightPanel->addWidget(categoriesPanel);
    authorsPanel=new AuthorsDialog(rightPanel,database); rightPanel->addWidget(inputPanel);
    rightPanel->addWidget(authorsPanel);

    // i18n
    translate();

    // Initialize Variables
    recipeButton=0;

    // Connect Signals from Left Panel to slotSetPanel()
     connect( leftPanel, SIGNAL(clicked(int)),this, SLOT(slotSetPanel(int)) );
     connect(shoppingListPanel,SIGNAL(wizardClicked()),this,SLOT(slotSetDietWizardPanel()));

    rightPanel->raiseWidget(selectPanel);

    // Retransmit signal to parent to Enable/Disable the Save Button
    connect (inputPanel, SIGNAL(enableSaveOption(bool)), this, SIGNAL(enableSaveOption(bool)));

    // Create a new button when a recipe is unsaved
    connect (inputPanel, SIGNAL(createButton(QWidget*,QString)), this, SLOT(addRecipeButton(QWidget*,QString)));

    // Connect Signals from selectPanel (SelectRecipeDialog)

    connect (selectPanel, SIGNAL(recipeSelected(int,int)),this, SLOT(actionRecipe(int,int)));

    // Resize signal
    connect (leftPanel, SIGNAL(resized(int,int)),this, SLOT(resizeButtons()));

    // Close a recipe when requested (just switch panels)
    connect(inputPanel,SIGNAL(closeRecipe()),this,SLOT(closeRecipe()));

    // Show a recipe when requested (just switch panels)
    connect(inputPanel,SIGNAL(showRecipe(int)),this,SLOT(showRecipe(int)));

    // Add recipe to the shopping list when requested
    connect(inputPanel,SIGNAL(addRecipeToShoppingList(int)),shoppingListPanel,SLOT(addRecipeToShoppingList(int)));
}

KrecipesView::~KrecipesView()
{
delete il; // remove iconloader
}

void KrecipesView::translate(){
  button0->setText(i18n("Find/Edit Recipes"));
  QToolTip::add(button0, i18n("Find/Edit Recipes"));
  button1->setText(i18n("Shopping List"));
  QToolTip::add(button1, i18n("Shopping List"));
  button2->setText(i18n("Ingredients"));
  QToolTip::add(button2, i18n("Ingredients"));
  button3->setText(i18n("Properties"));
  QToolTip::add(button3, i18n("Properties"));
  button4->setText(i18n("Units"));
  QToolTip::add(button4, i18n("Units"));
  button5->setText(i18n("Recipe Categories"));
  QToolTip::add(button5, i18n("Recipe Categories"));
  button6->setText(i18n("Authors"));
  QToolTip::add(button6, i18n("Authors"));
}

void KrecipesView::print(QPainter *p, int height, int width)
{
    // do the actual printing, here
    // p->drawText(etc..)
}

void KrecipesView::slotSetTitle(const QString& title)
{
    emit signalChangeCaption(title);
}

// Function to switch panels
void KrecipesView::slotSetPanel(int w)
{
switch (w)
{
case SelectP: selectPanel->reload(); // Reload data
	this->rightPanel->raiseWidget(selectPanel);
	break;
case ShoppingP: shoppingListPanel->reload(); // Reload data
	this->rightPanel->raiseWidget(shoppingListPanel);
	break;
case IngredientsP: ingredientsPanel->reload();// Reload data
	this->rightPanel->raiseWidget(ingredientsPanel);
	break;
case PropertiesP: propertiesPanel->reload();
	this->rightPanel->raiseWidget(propertiesPanel);
	break;
case UnitsP: unitsPanel->reload(); // Reload data
	this->rightPanel->raiseWidget(unitsPanel);
	break;
case CategoriesP: this->rightPanel->raiseWidget(categoriesPanel);
	break;
case DietWizardP: dietPanel->reload();
	this->rightPanel->raiseWidget(dietPanel);
	break;
case AuthorsP: authorsPanel->reload();
	this->rightPanel->raiseWidget(authorsPanel);
	break;

}

}
void KrecipesView::save(void)
{
inputPanel->save();
}

void KrecipesView::actionRecipe(int recipeID, int action)
{
if (action==0) //Show
	{
	showRecipe(recipeID);
	}
else if (action==1) // Edit
{
	if ( !inputPanel->everythingSaved() )
	{
		switch( KMessageBox::questionYesNoCancel( this,
		  QString(i18n("Recipe \"%1\" contains unsaved changes.\n"
		  "Do you want to save changes made to this recipe before editing another recipe?")).arg(recipeButton->text()),
		   i18n("Unsaved changes") ) )
		{
			case KMessageBox::Yes: inputPanel->save(); break;
			case KMessageBox::No: break;
			case KMessageBox::Cancel: return;
		}
	}

	inputPanel->loadRecipe(recipeID);
	rightPanel->raiseWidget(inputPanel);
}
else if (action==2) //Remove
{
database->removeRecipe(recipeID);
selectPanel->reload();
}
}

void KrecipesView::createNewRecipe(void)
{
if ( !inputPanel->everythingSaved() )
{
	switch( KMessageBox::questionYesNoCancel( this,
	  QString(i18n("Recipe \"%1\" contains unsaved changes.\n"
	  "Do you want to save changes made to this recipe before creating a new recipe?")).arg(recipeButton->text()),
	   i18n("Unsaved changes") ) )
	{
		case KMessageBox::Yes: inputPanel->save(); break;
		case KMessageBox::No: break;
		case KMessageBox::Cancel: return;
	}
}

inputPanel->newRecipe();
rightPanel->raiseWidget(inputPanel);
}

void KrecipesView::createNewElement(void)
{
if (rightPanel->id(rightPanel->visibleWidget())==4) //Properties Panel is the active one
{
propertiesPanel->createNewProperty();
}
else{
  createNewRecipe();
  }
}

void KrecipesView::wizard(void)
{
KConfig *config=kapp->config();
config->setGroup("Wizard");

bool setupDone=config->readBoolEntry( "SystemSetup",false);
if (!setupDone)
{

bool setupUser,initData,adminEnabled; QString adminUser,adminPass,user,pass,host,client,dbName;
bool isRemote;

SetupWizard *setupWizard=new SetupWizard(this);
if(setupWizard->exec()== QDialog::Accepted)
{
std::cerr<<"Setting up\n";
setupWizard->getOptions(setupUser,initData);

// Setup user if necessary

if (setupUser) // Don't setup user if checkbox of existing user... was set
	{
	std::cerr<<"Setting up user\n";
	setupWizard->getAdminInfo(adminEnabled,adminUser,adminPass);
	setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass);

	if (!adminEnabled) // Use root without password
	{
	std::cerr<<"Using default admin\n";
	adminUser="root";
	adminPass=QString::null;
	}
	if (!isRemote) // Use localhost
	{
	std::cerr<<"Using localhost\n";
	host="localhost";
	client="localhost";
	}

	setupUserPermissions(host,client,dbName,user,pass,adminUser,adminPass);
	}

// Initialize database with data if requested

if (initData)
	{
	setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass);
	initializeData(host,dbName,user,pass); // Populate data as normal user
	}

}
delete setupWizard;
}
}

void KrecipesView::slotSetDietWizardPanel(void)
{
dietPanel->reload();
rightPanel->raiseWidget(dietPanel);
}

void KrecipesView::setupUserPermissions(const QString &host, const QString &client, const QString &dbName, const QString &newUser,const QString &newPass,const QString &adminUser,const QString &adminPass)
{
RecipeDB *db;

if (adminUser!=QString::null)
	{ // Login as admin in the (remote) server and createDB if necessary
	std::cerr<<"Open db as:"<< adminUser.latin1() <<",*** with password ****\n";
	db= new RecipeDB(host,adminUser,adminPass,dbName,true); // true means initialize db structure (It won't destroy data if exists)
	}
	else{ // Login as root with no password
	std::cerr<<"Open db as root, with no password\n";
	db=new RecipeDB(host,"root",QString::null,dbName,true);
	}

db->givePermissions(dbName,newUser,newPass,client); // give permissions to the user

delete db; //it closes the db automatically
}

void KrecipesView::initializeData(const QString &host,const QString &dbName, const QString &user,const QString &pass)
{
RecipeDB *db;
db= new RecipeDB(host,user,pass,dbName);
db->initializeData();
delete db; //it closes the db automatically
}

void KrecipesView::resizeButtons(){
  button0->resize(leftPanel->width(), 30);
  button1->resize(leftPanel->width(), 30);
  button2->resize(leftPanel->width(), 30);
  button3->resize(leftPanel->width(), 30);
  button4->resize(leftPanel->width(), 30);
  button5->resize(leftPanel->width(), 30);
  button6->resize(leftPanel->width(), 30);
  if(recipeButton){
    recipeButton->resize(leftPanel->width(), 30);
  }
}

void KrecipesView::addRecipeButton(QWidget *w,QString title)
{
recipeWidget=w;

if (!recipeButton)
{
	recipeButton=new MenuButton(leftPanel,"recipeButton");
	recipeButton->setFlat(true);recipeButton->setIconSet(il->loadIconSet("filesave",KIcon::Small));
	recipeButton->setGeometry(0,250,150,30);
	recipeButton->setTitle(title);
	recipeButton->resize(leftPanel->width(),30);
	recipeButton->show();
	connect(recipeButton,SIGNAL(clicked()),this,SLOT(switchToRecipe()));
	connect((RecipeInputDialog *)w,SIGNAL(titleChanged(const QString&)),recipeButton,SLOT(setTitle(const QString&)));
}

}

void KrecipesView::switchToRecipe(void)
{
rightPanel->raiseWidget(recipeWidget);
}

void KrecipesView::closeRecipe(void)
{
selectPanel->reload();
rightPanel->raiseWidget(selectPanel);
delete recipeButton; recipeButton=0;
}

void KrecipesView::showRecipe(int recipeID)
{
viewPanel->loadRecipe(recipeID);
rightPanel->raiseWidget(viewPanel);
}

////////////////// Class MenuButton Methods///////////////////

MenuButton::MenuButton(QWidget *parent,const char *name):QPushButton(parent,name)
{
}

MenuButton::~MenuButton()
{
}

void MenuButton::setTitle(const QString &title)
{
  setText(title);
  QToolTip::add(this, title);
}

#include "krecipesview.moc"
<|endoftext|>


<commit_before>// Detect unnecessary boundaries and merge facets

#include "common.h"

int num_points, num_facets;
vector<Point> src, dst;
vector<vector<int>> facets;
vector<Polygon> src_polygons, dst_polygons;

void Input() {
  istringstream is(ReadAllAndRemoveComma(cin));
  is >> num_points;

  src.resize(num_points);
  rep (i, num_points) src[i] = ReadPoint(is);

  is >> num_facets;
  facets.resize(num_facets);
  rep (i, num_facets) {
    int n;
    is >> n;
    facets[i].resize(n);
    for (int &f : facets[i]) is >> f;
  }

  dst.resize(num_points);
  rep (i, num_points) dst[i] = ReadPoint(is);
}

Polygon FacetPolygon(const vector<int> &vs, const vector<Point> &coords) {
  vector<Point> ps;
  for (int v : vs) ps.emplace_back(coords[v]);
  ps.emplace_back(ps[0]);
  Polygon po;
  bg::assign_points(po, ps);
  return po;
}

int main() {
  Input();

  // Construct polygons and force counter clockwise
  src_polygons.resize(num_facets);
  rep (i, num_facets) src_polygons[i] = FacetPolygon(facets[i], src);
  dst_polygons.resize(num_facets);
  rep (i, num_facets) dst_polygons[i] = FacetPolygon(facets[i], dst);

  // Connection
  map<pair<int, int>, vector<int>> edge_to_facets;
  rep (i, num_facets) {
    const auto &f = facets[i];
    rep (j, f.size()) {
      edge_to_facets[MakePairUnordered(f[j], f[(j + 1) % f.size()])]
          .emplace_back(i);
    }
  }

  // Detect unnecessary edges
  set<pii> unnecessary_edges;
  for (const auto &t : edge_to_facets) {
    vector<int> fs = t.second;
    if (fs.size() == 1) continue;
    assert(fs.size() == 2);

    vector<bool> src_ccw(2), dst_ccw(2);
    rep (i, 2) {
      src_ccw[i] = bg::area(src_polygons[fs[i]]) > 0;
      dst_ccw[i] = bg::area(dst_polygons[fs[i]]) > 0;
    }
    if (src_ccw == dst_ccw) {
      cerr << "JOIN: " << fs[0] << "-" << fs[1]
           << "(edge: " << t.first.first << "," << t.first.second << ")" << endl;
      unnecessary_edges.insert(t.first);
    }
  }
  cerr << "unnecessary edges: " << unnecessary_edges.size() << endl;

  // Regions
  vector<vector<int>> adj(num_points);
  for (const auto &f : facets) {
    rep (i, f.size()) {
      int a = f[i], b = f[(i + 1) % f.size()];
      if (unnecessary_edges.count(MakePairUnordered(a, b))) continue;
      adj[a].emplace_back(b);
      adj[b].emplace_back(a);
    }
  }
  for (auto &a : adj) {
    sort(all(a));
    a.erase(unique(all(a)), a.end());
  }
  vector<vector<int>> new_facets = EnumerateRegions(src, adj);
  new_facets.erase(
      remove_if(all(new_facets), [&](const vector<int> &f) -> bool {
          vector<Point> ps(f.size());
          rep (i, f.size()) ps[i] = src[f[i]];
          ps.emplace_back(ps[0]);
          Polygon po;
          bg::assign_points(po, ps);
          return bg::area(po) < 0;
        }), new_facets.end());

  // Output
  cout << num_points << endl;
  rep (i, num_points) cout << src[i].x() << "," << src[i].y() << endl;
  cout << new_facets.size() << endl;
  rep (i, new_facets.size()) {
    cout << new_facets[i].size();
    for (int v : new_facets[i]) cout << " " << v;
    cout << endl;
  }
  rep (i, num_points) cout << dst[i].x() << "," << dst[i].y() << endl;
}
<commit_msg>バグってたorz<commit_after>// Detect unnecessary boundaries and merge facets

#include "common.h"

int num_points, num_facets;
vector<Point> src, dst;
vector<vector<int>> facets;
vector<Polygon> src_polygons, dst_polygons;

void Input() {
  istringstream is(ReadAllAndRemoveComma(cin));
  is >> num_points;

  src.resize(num_points);
  rep (i, num_points) src[i] = ReadPoint(is);

  is >> num_facets;
  facets.resize(num_facets);
  rep (i, num_facets) {
    int n;
    is >> n;
    facets[i].resize(n);
    for (int &f : facets[i]) is >> f;
  }

  dst.resize(num_points);
  rep (i, num_points) dst[i] = ReadPoint(is);
}

Polygon FacetPolygon(const vector<int> &vs, const vector<Point> &coords) {
  vector<Point> ps;
  for (int v : vs) ps.emplace_back(coords[v]);
  ps.emplace_back(ps[0]);
  Polygon po;
  bg::assign_points(po, ps);
  return po;
}

int main() {
  Input();

  // Construct polygons and force counter clockwise
  src_polygons.resize(num_facets);
  rep (i, num_facets) src_polygons[i] = FacetPolygon(facets[i], src);
  dst_polygons.resize(num_facets);
  rep (i, num_facets) dst_polygons[i] = FacetPolygon(facets[i], dst);

  // Connection
  map<pair<int, int>, vector<int>> edge_to_facets;
  rep (i, num_facets) {
    const auto &f = facets[i];
    rep (j, f.size()) {
      edge_to_facets[MakePairUnordered(f[j], f[(j + 1) % f.size()])]
          .emplace_back(i);
    }
  }

  // Detect unnecessary edges
  set<pii> unnecessary_edges;
  for (const auto &t : edge_to_facets) {
    vector<int> fs = t.second;
    if (fs.size() == 1) continue;
    assert(fs.size() == 2);

    vector<bool> src_ccw(2), dst_ccw(2);
    rep (i, 2) {
      src_ccw[i] = bg::area(src_polygons[fs[i]]) > 0;
      dst_ccw[i] = bg::area(dst_polygons[fs[i]]) > 0;
    }
    if ((src_ccw[0] == src_ccw[1]) == (dst_ccw[0] == dst_ccw[1])) {
      cerr << "JOIN: " << fs[0] << "-" << fs[1]
           << "(edge: " << t.first.first << "," << t.first.second << ")" << endl;
      unnecessary_edges.insert(t.first);
    }
  }
  cerr << "unnecessary edges: " << unnecessary_edges.size() << endl;

  // Regions
  vector<vector<int>> adj(num_points);
  for (const auto &f : facets) {
    rep (i, f.size()) {
      int a = f[i], b = f[(i + 1) % f.size()];
      if (unnecessary_edges.count(MakePairUnordered(a, b))) continue;
      adj[a].emplace_back(b);
      adj[b].emplace_back(a);
    }
  }
  for (auto &a : adj) {
    sort(all(a));
    a.erase(unique(all(a)), a.end());
  }
  vector<vector<int>> new_facets = EnumerateRegions(src, adj);
  new_facets.erase(
      remove_if(all(new_facets), [&](const vector<int> &f) -> bool {
          vector<Point> ps(f.size());
          rep (i, f.size()) ps[i] = src[f[i]];
          ps.emplace_back(ps[0]);
          Polygon po;
          bg::assign_points(po, ps);
          return bg::area(po) < 0;
        }), new_facets.end());

  // Output
  cout << num_points << endl;
  rep (i, num_points) cout << src[i].x() << "," << src[i].y() << endl;
  cout << new_facets.size() << endl;
  rep (i, new_facets.size()) {
    cout << new_facets[i].size();
    for (int v : new_facets[i]) cout << " " << v;
    cout << endl;
  }
  rep (i, num_points) cout << dst[i].x() << "," << dst[i].y() << endl;
}
<|endoftext|>