<commit_before>#include "littletest.hpp"
#include <curl/curl.h>
#include <string>
#include <map>
#include "httpserver.hpp"

using namespace httpserver;
using namespace std;

size_t writefunc(void *ptr, size_t size, size_t nmemb, std::string *s)
{
    s->append((char*) ptr, size*nmemb);
    return size*nmemb;
}

size_t headerfunc(void *ptr, size_t size, size_t nmemb, map<string, string>* ss)
{
    string s_ptr((char*)ptr, size*nmemb);
    size_t pos = s_ptr.find(":");
    if(pos != string::npos)
        (*ss)[s_ptr.substr(0, pos)] =
            s_ptr.substr(pos + 2, s_ptr.size() - pos - 4);
    return size*nmemb;
}

class simple_resource : public http_resource<simple_resource>
{
    public:
        void render_GET(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_POST(const http_request& req, http_response** res)
        {
            *res = new http_string_response(
                    req.get_arg("arg1")+req.get_arg("arg2"), 200, "text/plain"
            );
        }
};

class header_test_resource : public http_resource<header_test_resource>
{
    public:
        void render_GET(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
            (*res)->set_header("KEY", "VALUE");
        }
};

class complete_test_resource : public http_resource<complete_test_resource>
{
    public:
        void render_GET(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_POST(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_PUT(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_DELETE(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_CONNECT(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
};

LT_BEGIN_SUITE(basic_suite)

    webserver* ws;

    void set_up()
    {
        ws = new webserver(create_webserver(8080));
        ws->start(false);
    }

    void tear_down()
    {
        ws->stop();
        delete ws;
    }
LT_END_SUITE(basic_suite)

LT_BEGIN_AUTO_TEST(basic_suite, read_body)
    simple_resource* resource = new simple_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL *curl = curl_easy_init();
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    LT_CHECK_EQ(s, "OK");
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(read_body)

LT_BEGIN_AUTO_TEST(basic_suite, read_header)
    header_test_resource* resource = new header_test_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    map<string, string> ss;
    CURL *curl = curl_easy_init();
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headerfunc);
    curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &ss);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    LT_CHECK_EQ(s, "OK");
    LT_CHECK_EQ(ss["KEY"], "VALUE");
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(read_header)

LT_BEGIN_AUTO_TEST(basic_suite, complete)
    complete_test_resource* resource = new complete_test_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL* curl;
    CURLcode res;

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "CONNECT");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 0);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(complete)

LT_BEGIN_AUTO_TEST(basic_suite, postprocessor)
    simple_resource* resource = new simple_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL *curl = curl_easy_init();
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "arg1=lib&arg2=httpserver");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    LT_CHECK_EQ(s, "libhttpserver");
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(postprocessor)

LT_BEGIN_AUTO_TEST_ENV()
    AUTORUN_TESTS()
LT_END_AUTO_TEST_ENV()
<commit_msg>Added a new test dedicated to unimplemented methods<commit_after>#include "littletest.hpp"
#include <curl/curl.h>
#include <string>
#include <map>
#include "httpserver.hpp"

using namespace httpserver;
using namespace std;

size_t writefunc(void *ptr, size_t size, size_t nmemb, std::string *s)
{
    s->append((char*) ptr, size*nmemb);
    return size*nmemb;
}

size_t headerfunc(void *ptr, size_t size, size_t nmemb, map<string, string>* ss)
{
    string s_ptr((char*)ptr, size*nmemb);
    size_t pos = s_ptr.find(":");
    if(pos != string::npos)
        (*ss)[s_ptr.substr(0, pos)] =
            s_ptr.substr(pos + 2, s_ptr.size() - pos - 4);
    return size*nmemb;
}

class simple_resource : public http_resource<simple_resource>
{
    public:
        void render_GET(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_POST(const http_request& req, http_response** res)
        {
            *res = new http_string_response(
                    req.get_arg("arg1")+req.get_arg("arg2"), 200, "text/plain"
            );
        }
};

class header_test_resource : public http_resource<header_test_resource>
{
    public:
        void render_GET(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
            (*res)->set_header("KEY", "VALUE");
        }
};

class complete_test_resource : public http_resource<complete_test_resource>
{
    public:
        void render_GET(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_POST(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_PUT(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_DELETE(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
        void render_CONNECT(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
};

class only_render_resource : public http_resource<only_render_resource>
{
    public:
        void render(const http_request& req, http_response** res)
        {
            *res = new http_string_response("OK", 200, "text/plain");
        }
};

LT_BEGIN_SUITE(basic_suite)

    webserver* ws;

    void set_up()
    {
        ws = new webserver(create_webserver(8080));
        ws->start(false);
    }

    void tear_down()
    {
        ws->stop();
        delete ws;
    }
LT_END_SUITE(basic_suite)

LT_BEGIN_AUTO_TEST(basic_suite, read_body)
    simple_resource* resource = new simple_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL *curl = curl_easy_init();
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    LT_CHECK_EQ(s, "OK");
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(read_body)

LT_BEGIN_AUTO_TEST(basic_suite, read_header)
    header_test_resource* resource = new header_test_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    map<string, string> ss;
    CURL *curl = curl_easy_init();
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headerfunc);
    curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &ss);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    LT_CHECK_EQ(s, "OK");
    LT_CHECK_EQ(ss["KEY"], "VALUE");
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(read_header)

LT_BEGIN_AUTO_TEST(basic_suite, complete)
    complete_test_resource* resource = new complete_test_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL* curl;
    CURLcode res;

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "CONNECT");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 0);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(complete)

LT_BEGIN_AUTO_TEST(basic_suite, only_render)
    only_render_resource* resource = new only_render_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL* curl;
    CURLcode res;

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "CONNECT");
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 0);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    curl_easy_cleanup(curl);

LT_END_AUTO_TEST(only_render)

LT_BEGIN_AUTO_TEST(basic_suite, postprocessor)
    simple_resource* resource = new simple_resource();
    ws->register_resource("base", resource);
    curl_global_init(CURL_GLOBAL_ALL);
    std::string s;
    CURL *curl = curl_easy_init();
    CURLcode res;
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/base");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "arg1=lib&arg2=httpserver");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    res = curl_easy_perform(curl);
    LT_ASSERT_EQ(res, 0);
    LT_CHECK_EQ(s, "libhttpserver");
    curl_easy_cleanup(curl);
LT_END_AUTO_TEST(postprocessor)

LT_BEGIN_AUTO_TEST_ENV()
    AUTORUN_TESTS()
LT_END_AUTO_TEST_ENV()
<|endoftext|>


<commit_before>/*
  This file is part of Ingen.
  Copyright 2007-2012 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <string>

#include <gtkmm/eventbox.h>

#include "lv2/lv2plug.in/ns/ext/atom/util.h"

#include "ingen/Configuration.hpp"
#include "ingen/Interface.hpp"
#include "ingen/Log.hpp"
#include "ingen/client/BlockModel.hpp"
#include "ingen/client/GraphModel.hpp"
#include "ingen/client/PluginModel.hpp"
#include "ingen/client/PluginUI.hpp"
#include "raul/Atom.hpp"

#include "App.hpp"
#include "GraphCanvas.hpp"
#include "GraphWindow.hpp"
#include "NodeMenu.hpp"
#include "NodeModule.hpp"
#include "Port.hpp"
#include "RenameWindow.hpp"
#include "Style.hpp"
#include "SubgraphModule.hpp"
#include "WidgetFactory.hpp"
#include "WindowFactory.hpp"
#include "ingen_config.h"

using namespace std;

namespace Ingen {

using namespace Client;

namespace GUI {

NodeModule::NodeModule(GraphCanvas&           canvas,
                       SPtr<const BlockModel> block)
	: Ganv::Module(canvas, block->path().symbol(), 0, 0, true)
	, _block(block)
	, _gui_widget(NULL)
	, _gui_window(NULL)
{
	block->signal_new_port().connect(
		sigc::mem_fun(this, &NodeModule::new_port_view));
	block->signal_removed_port().connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::delete_port_view)));
	block->signal_property().connect(
		sigc::mem_fun(this, &NodeModule::property_changed));
	block->signal_moved().connect(
		sigc::mem_fun(this, &NodeModule::rename));

	signal_event().connect(
		sigc::mem_fun(this, &NodeModule::on_event));

	signal_moved().connect(
		sigc::mem_fun(this, &NodeModule::store_location));

	signal_selected().connect(
		sigc::mem_fun(this, &NodeModule::on_selected));

	const PluginModel* plugin = dynamic_cast<const PluginModel*>(block->plugin());
	if (plugin) {
		plugin->signal_changed().connect(
			sigc::mem_fun(this, &NodeModule::plugin_changed));
	}
}

NodeModule::~NodeModule()
{
	delete _gui_widget;
	delete _gui_window;
}

bool
NodeModule::show_menu(GdkEventButton* ev)
{
	WidgetFactory::get_widget_derived("object_menu", _menu);
	_menu->init(app(), _block);
	_menu->signal_embed_gui.connect(
		sigc::mem_fun(this, &NodeModule::on_embed_gui_toggled));
	_menu->signal_popup_gui.connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));
	_menu->popup(ev->button, ev->time);
	return true;
}

NodeModule*
NodeModule::create(GraphCanvas&           canvas,
                   SPtr<const BlockModel> block,
                   bool                   human)
{
	SPtr<const GraphModel> graph = dynamic_ptr_cast<const GraphModel>(block);

	NodeModule* ret = (graph)
		? new SubgraphModule(canvas, graph)
		: new NodeModule(canvas, block);

	for (const auto& p : block->properties())
		ret->property_changed(p.first, p.second);

	for (const auto& p : block->ports())
		ret->new_port_view(p);

	ret->set_stacked(block->polyphonic());

	if (human)
		ret->show_human_names(human); // FIXME: double port iteration

	return ret;
}

App&
NodeModule::app() const
{
	return ((GraphCanvas*)canvas())->app();
}

void
NodeModule::show_human_names(bool b)
{
	const URIs& uris = app().uris();

	if (b) {
		set_label(block()->label().c_str());
	} else {
		set_label(block()->symbol().c_str());
	}

	for (iterator i = begin(); i != end(); ++i) {
		Ingen::GUI::Port* const port = dynamic_cast<Ingen::GUI::Port*>(*i);
		Glib::ustring label(port->model()->symbol().c_str());
		if (b) {
			const Raul::Atom& name_property = port->model()->get_property(uris.lv2_name);
			if (name_property.type() == uris.forge.String) {
				label = name_property.get_string();
			} else {
				Glib::ustring hn = block()->plugin_model()->port_human_name(
						port->model()->index());
				if (!hn.empty())
					label = hn;
			}
		}
		(*i)->set_label(label.c_str());
	}
}

void
NodeModule::value_changed(uint32_t index, const Raul::Atom& value)
{
	if (!_plugin_ui)
		return;

	float       float_val = 0.0f;
	const URIs& uris      = app().uris();

	if (value.type() == uris.forge.Float) {
		float_val = value.get_float();
		_plugin_ui->port_event(index, 4, 0, &float_val);
	} else if (value.type() == uris.forge.String) {
		_plugin_ui->port_event(
			index, strlen(value.get_string()), 0, value.get_string());
	}
}

void
NodeModule::port_activity(uint32_t index, const Raul::Atom& value)
{
	if (!_plugin_ui)
		return;

	const URIs& uris = app().uris();

	// FIXME: Well, this sucks...
	LV2_Atom* atom = (LV2_Atom*)malloc(sizeof(LV2_Atom) + value.size());
	atom->type = value.type();
	atom->size = value.type();
	memcpy(LV2_ATOM_BODY(atom), value.get_body(), value.size());
	_plugin_ui->port_event(
		index, lv2_atom_total_size(atom), uris.atom_eventTransfer, atom);
	free(atom);
}

void
NodeModule::plugin_changed()
{
	for (iterator p = begin(); p !=end(); ++p)
		dynamic_cast<Ingen::GUI::Port*>(*p)->update_metadata();
}

void
NodeModule::on_embed_gui_toggled(bool embed)
{
	embed_gui(embed);
	app().interface()->set_property(_block->uri(),
	                                app().uris().ingen_uiEmbedded,
	                                app().forge().make(embed));
}

void
NodeModule::embed_gui(bool embed)
{
	if (embed) {
		if (_gui_window) {
			app().log().warn("LV2 GUI already popped up, cannot embed\n");
			return;
		}

		if (!_plugin_ui) {
			const PluginModel* const pm = dynamic_cast<const PluginModel*>(_block->plugin());
			_plugin_ui = pm->ui(app().world(), _block);
		}

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			Gtk::Container* container = new Gtk::EventBox();
			container->set_name("ingen_embedded_node_gui_container");
			container->set_border_width(2.0);
			container->add(*_gui_widget);
			Ganv::Module::embed(container);
		} else {
			app().log().error("Failed to create LV2 UI\n");
		}

		if (_gui_widget) {
			_gui_widget->show_all();
			set_control_values();
		}

	} else { // un-embed
		Ganv::Module::embed(NULL);
		_plugin_ui.reset();
	}
}

void
NodeModule::rename()
{
	if (app().world()->conf().option("port-labels").get_bool() &&
	    !app().world()->conf().option("human-names").get_bool()) {
		set_label(_block->path().symbol());
	}
}

void
NodeModule::new_port_view(SPtr<const PortModel> port)
{
	Port::create(app(), *this, port,
	             app().world()->conf().option("human-names").get_bool());

	port->signal_value_changed().connect(
		sigc::bind<0>(sigc::mem_fun(this, &NodeModule::value_changed),
		              port->index()));

	port->signal_activity().connect(
		sigc::bind<0>(sigc::mem_fun(this, &NodeModule::port_activity),
		              port->index()));
}

Port*
NodeModule::port(SPtr<const PortModel> model)
{
	for (iterator p = begin(); p != end(); ++p) {
		Port* const port = dynamic_cast<Port*>(*p);
		if (port->model() == model)
			return port;
	}
	return NULL;
}

void
NodeModule::delete_port_view(SPtr<const PortModel> model)
{
	Port* p = port(model);
	if (p) {
		delete p;
	} else {
		app().log().warn(Raul::fmt("Failed to find port %1% on module %2%\n")
		                 % model->path() % _block->path());
	}
}

bool
NodeModule::popup_gui()
{
	if (_block->plugin() && _block->plugin()->type() == PluginModel::LV2) {
		if (_plugin_ui) {
			app().log().warn("LV2 GUI already embedded, cannot pop up\n");
			return false;
		}

		const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_block->plugin());
		assert(plugin);

		_plugin_ui = plugin->ui(app().world(), _block);

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			_gui_window = new Gtk::Window();
			if (!_plugin_ui->is_resizable()) {
				_gui_window->set_resizable(false);
			}
			_gui_window->set_title(_block->path() + " UI - Ingen");
			_gui_window->set_role("plugin_ui");
			_gui_window->add(*_gui_widget);
			_gui_widget->show_all();
			set_control_values();

			_gui_window->signal_unmap().connect(
					sigc::mem_fun(this, &NodeModule::on_gui_window_close));
			_gui_window->present();

			return true;
		} else {
			app().log().warn(Raul::fmt("No LV2 GUI for %1%\n") % _block->path());
		}
	}

	return false;
}

void
NodeModule::on_gui_window_close()
{
	delete _gui_window;
	_gui_window = NULL;
	_plugin_ui.reset();
	_gui_widget = NULL;
}

void
NodeModule::set_control_values()
{
	uint32_t index = 0;
	for (const auto& p : _block->ports()) {
		if (app().can_control(p.get())) {
			value_changed(index, p->value());
		}
		++index;
	}
}

bool
NodeModule::on_double_click(GdkEventButton* event)
{
	popup_gui();
	return true;
}

bool
NodeModule::on_event(GdkEvent* ev)
{
	if (ev->type == GDK_BUTTON_PRESS && ev->button.button == 3) {
		return show_menu(&ev->button);
	} else if (ev->type == GDK_2BUTTON_PRESS) {
		return on_double_click(&ev->button);
	}
	return false;
}

void
NodeModule::store_location(double ax, double ay)
{
	const URIs& uris = app().uris();

	const Raul::Atom x(app().forge().make(static_cast<float>(ax)));
	const Raul::Atom y(app().forge().make(static_cast<float>(ay)));

	if (x != _block->get_property(uris.ingen_canvasX) ||
	    y != _block->get_property(uris.ingen_canvasY))
	{
		Resource::Properties remove;
		remove.insert(make_pair(uris.ingen_canvasX,
		                        Resource::Property(uris.wildcard)));
		remove.insert(make_pair(uris.ingen_canvasY,
		                        Resource::Property(uris.wildcard)));
		Resource::Properties add;
		add.insert(make_pair(uris.ingen_canvasX, x));
		add.insert(make_pair(uris.ingen_canvasY, y));
		app().interface()->delta(_block->uri(), remove, add);
	}
}

void
NodeModule::property_changed(const Raul::URI& key, const Raul::Atom& value)
{
	const URIs& uris = app().uris();
	if (value.type() == uris.forge.Float) {
		if (key == uris.ingen_canvasX) {
			move_to(value.get_float(), get_y());
		} else if (key == uris.ingen_canvasY) {
			move_to(get_x(), value.get_float());
		}
	} else if (value.type() == uris.forge.Bool) {
		if (key == uris.ingen_polyphonic) {
			set_stacked(value.get_bool());
		} else if (key == uris.ingen_uiEmbedded) {
			if (value.get_bool() && !_gui_widget) {
				embed_gui(true);
			} else if (!value.get_bool() && _gui_widget) {
				embed_gui(false);
			}
		}
	} else if (value.type() == uris.forge.String) {
		if (key == uris.lv2_name
		    && app().world()->conf().option("human-names").get_bool()) {
			set_label(value.get_string());
		}
	}
}

bool
NodeModule::on_selected(gboolean selected)
{
	GraphWindow* win = app().window_factory()->parent_graph_window(block());
	if (!win) {
		return true;
	}

	if (selected && win->documentation_is_visible()) {
		GraphWindow* win = app().window_factory()->parent_graph_window(block());
		std::string doc;
		bool html = false;
#ifdef HAVE_WEBKIT
		html = true;
#endif
		if (block()->plugin_model()) {
			doc = block()->plugin_model()->documentation(html);
		}
		win->set_documentation(doc, html);
	}

	return true;
}

} // namespace GUI
} // namespace Ingen
<commit_msg>Support directly passing any type of atom to plugin UIs.<commit_after>/*
  This file is part of Ingen.
  Copyright 2007-2012 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <string>

#include <gtkmm/eventbox.h>

#include "lv2/lv2plug.in/ns/ext/atom/util.h"

#include "ingen/Configuration.hpp"
#include "ingen/Interface.hpp"
#include "ingen/Log.hpp"
#include "ingen/client/BlockModel.hpp"
#include "ingen/client/GraphModel.hpp"
#include "ingen/client/PluginModel.hpp"
#include "ingen/client/PluginUI.hpp"
#include "raul/Atom.hpp"

#include "App.hpp"
#include "GraphCanvas.hpp"
#include "GraphWindow.hpp"
#include "NodeMenu.hpp"
#include "NodeModule.hpp"
#include "Port.hpp"
#include "RenameWindow.hpp"
#include "Style.hpp"
#include "SubgraphModule.hpp"
#include "WidgetFactory.hpp"
#include "WindowFactory.hpp"
#include "ingen_config.h"

using namespace std;

namespace Ingen {

using namespace Client;

namespace GUI {

NodeModule::NodeModule(GraphCanvas&           canvas,
                       SPtr<const BlockModel> block)
	: Ganv::Module(canvas, block->path().symbol(), 0, 0, true)
	, _block(block)
	, _gui_widget(NULL)
	, _gui_window(NULL)
{
	block->signal_new_port().connect(
		sigc::mem_fun(this, &NodeModule::new_port_view));
	block->signal_removed_port().connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::delete_port_view)));
	block->signal_property().connect(
		sigc::mem_fun(this, &NodeModule::property_changed));
	block->signal_moved().connect(
		sigc::mem_fun(this, &NodeModule::rename));

	signal_event().connect(
		sigc::mem_fun(this, &NodeModule::on_event));

	signal_moved().connect(
		sigc::mem_fun(this, &NodeModule::store_location));

	signal_selected().connect(
		sigc::mem_fun(this, &NodeModule::on_selected));

	const PluginModel* plugin = dynamic_cast<const PluginModel*>(block->plugin());
	if (plugin) {
		plugin->signal_changed().connect(
			sigc::mem_fun(this, &NodeModule::plugin_changed));
	}
}

NodeModule::~NodeModule()
{
	delete _gui_widget;
	delete _gui_window;
}

bool
NodeModule::show_menu(GdkEventButton* ev)
{
	WidgetFactory::get_widget_derived("object_menu", _menu);
	_menu->init(app(), _block);
	_menu->signal_embed_gui.connect(
		sigc::mem_fun(this, &NodeModule::on_embed_gui_toggled));
	_menu->signal_popup_gui.connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));
	_menu->popup(ev->button, ev->time);
	return true;
}

NodeModule*
NodeModule::create(GraphCanvas&           canvas,
                   SPtr<const BlockModel> block,
                   bool                   human)
{
	SPtr<const GraphModel> graph = dynamic_ptr_cast<const GraphModel>(block);

	NodeModule* ret = (graph)
		? new SubgraphModule(canvas, graph)
		: new NodeModule(canvas, block);

	for (const auto& p : block->properties())
		ret->property_changed(p.first, p.second);

	for (const auto& p : block->ports())
		ret->new_port_view(p);

	ret->set_stacked(block->polyphonic());

	if (human)
		ret->show_human_names(human); // FIXME: double port iteration

	return ret;
}

App&
NodeModule::app() const
{
	return ((GraphCanvas*)canvas())->app();
}

void
NodeModule::show_human_names(bool b)
{
	const URIs& uris = app().uris();

	if (b) {
		set_label(block()->label().c_str());
	} else {
		set_label(block()->symbol().c_str());
	}

	for (iterator i = begin(); i != end(); ++i) {
		Ingen::GUI::Port* const port = dynamic_cast<Ingen::GUI::Port*>(*i);
		Glib::ustring label(port->model()->symbol().c_str());
		if (b) {
			const Raul::Atom& name_property = port->model()->get_property(uris.lv2_name);
			if (name_property.type() == uris.forge.String) {
				label = name_property.get_string();
			} else {
				Glib::ustring hn = block()->plugin_model()->port_human_name(
						port->model()->index());
				if (!hn.empty())
					label = hn;
			}
		}
		(*i)->set_label(label.c_str());
	}
}

void
NodeModule::value_changed(uint32_t index, const Raul::Atom& value)
{
	if (!_plugin_ui)
		return;

	_plugin_ui->port_event(index, value.size(), value.type(), value.get_body());
}

void
NodeModule::port_activity(uint32_t index, const Raul::Atom& value)
{
	if (!_plugin_ui)
		return;

	const URIs& uris = app().uris();

	// FIXME: Well, this sucks...
	LV2_Atom* atom = (LV2_Atom*)malloc(sizeof(LV2_Atom) + value.size());
	atom->type = value.type();
	atom->size = value.type();
	memcpy(LV2_ATOM_BODY(atom), value.get_body(), value.size());
	_plugin_ui->port_event(
		index, lv2_atom_total_size(atom), uris.atom_eventTransfer, atom);
	free(atom);
}

void
NodeModule::plugin_changed()
{
	for (iterator p = begin(); p !=end(); ++p)
		dynamic_cast<Ingen::GUI::Port*>(*p)->update_metadata();
}

void
NodeModule::on_embed_gui_toggled(bool embed)
{
	embed_gui(embed);
	app().interface()->set_property(_block->uri(),
	                                app().uris().ingen_uiEmbedded,
	                                app().forge().make(embed));
}

void
NodeModule::embed_gui(bool embed)
{
	if (embed) {
		if (_gui_window) {
			app().log().warn("LV2 GUI already popped up, cannot embed\n");
			return;
		}

		if (!_plugin_ui) {
			const PluginModel* const pm = dynamic_cast<const PluginModel*>(_block->plugin());
			_plugin_ui = pm->ui(app().world(), _block);
		}

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			Gtk::Container* container = new Gtk::EventBox();
			container->set_name("ingen_embedded_node_gui_container");
			container->set_border_width(2.0);
			container->add(*_gui_widget);
			Ganv::Module::embed(container);
		} else {
			app().log().error("Failed to create LV2 UI\n");
		}

		if (_gui_widget) {
			_gui_widget->show_all();
			set_control_values();
		}

	} else { // un-embed
		Ganv::Module::embed(NULL);
		_plugin_ui.reset();
	}
}

void
NodeModule::rename()
{
	if (app().world()->conf().option("port-labels").get_bool() &&
	    !app().world()->conf().option("human-names").get_bool()) {
		set_label(_block->path().symbol());
	}
}

void
NodeModule::new_port_view(SPtr<const PortModel> port)
{
	Port::create(app(), *this, port,
	             app().world()->conf().option("human-names").get_bool());

	port->signal_value_changed().connect(
		sigc::bind<0>(sigc::mem_fun(this, &NodeModule::value_changed),
		              port->index()));

	port->signal_activity().connect(
		sigc::bind<0>(sigc::mem_fun(this, &NodeModule::port_activity),
		              port->index()));
}

Port*
NodeModule::port(SPtr<const PortModel> model)
{
	for (iterator p = begin(); p != end(); ++p) {
		Port* const port = dynamic_cast<Port*>(*p);
		if (port->model() == model)
			return port;
	}
	return NULL;
}

void
NodeModule::delete_port_view(SPtr<const PortModel> model)
{
	Port* p = port(model);
	if (p) {
		delete p;
	} else {
		app().log().warn(Raul::fmt("Failed to find port %1% on module %2%\n")
		                 % model->path() % _block->path());
	}
}

bool
NodeModule::popup_gui()
{
	if (_block->plugin() && _block->plugin()->type() == PluginModel::LV2) {
		if (_plugin_ui) {
			app().log().warn("LV2 GUI already embedded, cannot pop up\n");
			return false;
		}

		const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_block->plugin());
		assert(plugin);

		_plugin_ui = plugin->ui(app().world(), _block);

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			_gui_window = new Gtk::Window();
			if (!_plugin_ui->is_resizable()) {
				_gui_window->set_resizable(false);
			}
			_gui_window->set_title(_block->path() + " UI - Ingen");
			_gui_window->set_role("plugin_ui");
			_gui_window->add(*_gui_widget);
			_gui_widget->show_all();
			set_control_values();

			_gui_window->signal_unmap().connect(
					sigc::mem_fun(this, &NodeModule::on_gui_window_close));
			_gui_window->present();

			return true;
		} else {
			app().log().warn(Raul::fmt("No LV2 GUI for %1%\n") % _block->path());
		}
	}

	return false;
}

void
NodeModule::on_gui_window_close()
{
	delete _gui_window;
	_gui_window = NULL;
	_plugin_ui.reset();
	_gui_widget = NULL;
}

void
NodeModule::set_control_values()
{
	uint32_t index = 0;
	for (const auto& p : _block->ports()) {
		if (app().can_control(p.get())) {
			value_changed(index, p->value());
		}
		++index;
	}
}

bool
NodeModule::on_double_click(GdkEventButton* event)
{
	popup_gui();
	return true;
}

bool
NodeModule::on_event(GdkEvent* ev)
{
	if (ev->type == GDK_BUTTON_PRESS && ev->button.button == 3) {
		return show_menu(&ev->button);
	} else if (ev->type == GDK_2BUTTON_PRESS) {
		return on_double_click(&ev->button);
	}
	return false;
}

void
NodeModule::store_location(double ax, double ay)
{
	const URIs& uris = app().uris();

	const Raul::Atom x(app().forge().make(static_cast<float>(ax)));
	const Raul::Atom y(app().forge().make(static_cast<float>(ay)));

	if (x != _block->get_property(uris.ingen_canvasX) ||
	    y != _block->get_property(uris.ingen_canvasY))
	{
		Resource::Properties remove;
		remove.insert(make_pair(uris.ingen_canvasX,
		                        Resource::Property(uris.wildcard)));
		remove.insert(make_pair(uris.ingen_canvasY,
		                        Resource::Property(uris.wildcard)));
		Resource::Properties add;
		add.insert(make_pair(uris.ingen_canvasX, x));
		add.insert(make_pair(uris.ingen_canvasY, y));
		app().interface()->delta(_block->uri(), remove, add);
	}
}

void
NodeModule::property_changed(const Raul::URI& key, const Raul::Atom& value)
{
	const URIs& uris = app().uris();
	if (value.type() == uris.forge.Float) {
		if (key == uris.ingen_canvasX) {
			move_to(value.get_float(), get_y());
		} else if (key == uris.ingen_canvasY) {
			move_to(get_x(), value.get_float());
		}
	} else if (value.type() == uris.forge.Bool) {
		if (key == uris.ingen_polyphonic) {
			set_stacked(value.get_bool());
		} else if (key == uris.ingen_uiEmbedded) {
			if (value.get_bool() && !_gui_widget) {
				embed_gui(true);
			} else if (!value.get_bool() && _gui_widget) {
				embed_gui(false);
			}
		}
	} else if (value.type() == uris.forge.String) {
		if (key == uris.lv2_name
		    && app().world()->conf().option("human-names").get_bool()) {
			set_label(value.get_string());
		}
	}
}

bool
NodeModule::on_selected(gboolean selected)
{
	GraphWindow* win = app().window_factory()->parent_graph_window(block());
	if (!win) {
		return true;
	}

	if (selected && win->documentation_is_visible()) {
		GraphWindow* win = app().window_factory()->parent_graph_window(block());
		std::string doc;
		bool html = false;
#ifdef HAVE_WEBKIT
		html = true;
#endif
		if (block()->plugin_model()) {
			doc = block()->plugin_model()->documentation(html);
		}
		win->set_documentation(doc, html);
	}

	return true;
}

} // namespace GUI
} // namespace Ingen
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014-2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include "TableModel.hpp"

typedef QModelIndex Index;

TableModel::TableModel(QObject* parent,
                       const GameDesk* desk):
    QAbstractTableModel(parent), desk_(desk) {
}

int TableModel::rowCount(const Index& /*parent*/) const {
    return desk_->getRowNumber();
}

int TableModel::columnCount(
    const Index& /*parent*/) const {
    return desk_->getRowNumber();
}

QVariant TableModel::data(const Index& index,
                          int role) const {
    return QVariant();
}

void TableModel::updateData() {
    reset();
}
<commit_msg>Implementation of TableModel::data()<commit_after>/*
 * Copyright (C) 2014-2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include "TableModel.hpp"

typedef QModelIndex Index;

TableModel::TableModel(QObject* parent,
                       const GameDesk* desk):
    QAbstractTableModel(parent), desk_(desk) {
}

int TableModel::rowCount(const Index& /*parent*/) const {
    return desk_->getRowNumber();
}

int TableModel::columnCount(
    const Index& /*parent*/) const {
    return desk_->getRowNumber();
}

QVariant TableModel::data(const Index& index,
                          int role) const {
    if (role == Qt::DisplayRole) {
        Point pt;
        pt.col = index.column();
        pt.row = index.row();
        return desk_->getDeskNumber(pt);
    }
    return QVariant();
}

void TableModel::updateData() {
    reset();
}
<|endoftext|>


<commit_before>/* Libreoffice-voikko: Linguistic extension for LibreOffice
 * Copyright (C) 2007 - 2009 Harri Pitkänen <hatapitk@iki.fi>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 3 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above.
 ******************************************************************************/

#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <uno/lbnames.h>
#include <com/sun/star/uno/Reference.hxx>

#include "macros.hxx"
#include "spellchecker/SpellChecker.hxx"
#include "hyphenator/Hyphenator.hxx"
#include "grammar/GrammarChecker.hxx"
#include "settings/SettingsEventHandler.hxx"

using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;

namespace voikko {

extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL
	component_getImplementationEnvironment(sal_Char const ** ppEnvTypeName,
	                                       uno_Environment **) {
	VOIKKO_DEBUG("component_getImplementationEnvironment");
	*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ":unsafe";
}

Reference<XInterface> SAL_CALL regSettingsCreate(const Reference<XComponentContext> & context)
	SAL_THROW((Exception)) {
	return static_cast< ::cppu::OWeakObject * >(new SettingsEventHandler(context));
}

static ::cppu::ImplementationEntry const regEntries[] = {
	{ &SpellChecker::get,
	  &SpellChecker::getImplementationName_static,
	  &SpellChecker::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ &Hyphenator::get,
	  &Hyphenator::getImplementationName_static,
	  &Hyphenator::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ &GrammarChecker::get,
	  &GrammarChecker::getImplementationName_static,
	  &GrammarChecker::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ &regSettingsCreate,
	  &SettingsEventHandler::getImplementationName_static,
	  &SettingsEventHandler::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ 0, 0, 0, 0, 0, 0 }
};

extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL
	component_getFactory(const char * implName, void * serviceManager, void * registryKey) {
	VOIKKO_DEBUG("component_getFactory");
	return ::cppu::component_getFactoryHelper(implName, serviceManager, registryKey, regEntries);
}

}
<commit_msg>Remove SAL_THROW for build compatibility with LibreOffice 4.4<commit_after>/* Libreoffice-voikko: Linguistic extension for LibreOffice
 * Copyright (C) 2007 - 2009 Harri Pitkänen <hatapitk@iki.fi>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * the GNU General Public License Version 3 or later (the "GPL"), in which
 * case the provisions of the GPL are applicable instead of those above.
 ******************************************************************************/

#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <uno/lbnames.h>
#include <com/sun/star/uno/Reference.hxx>

#include "macros.hxx"
#include "spellchecker/SpellChecker.hxx"
#include "hyphenator/Hyphenator.hxx"
#include "grammar/GrammarChecker.hxx"
#include "settings/SettingsEventHandler.hxx"

using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;

namespace voikko {

extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL
	component_getImplementationEnvironment(sal_Char const ** ppEnvTypeName,
	                                       uno_Environment **) {
	VOIKKO_DEBUG("component_getImplementationEnvironment");
	*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ":unsafe";
}

Reference<XInterface> SAL_CALL regSettingsCreate(const Reference<XComponentContext> & context) {
	return static_cast< ::cppu::OWeakObject * >(new SettingsEventHandler(context));
}

static ::cppu::ImplementationEntry const regEntries[] = {
	{ &SpellChecker::get,
	  &SpellChecker::getImplementationName_static,
	  &SpellChecker::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ &Hyphenator::get,
	  &Hyphenator::getImplementationName_static,
	  &Hyphenator::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ &GrammarChecker::get,
	  &GrammarChecker::getImplementationName_static,
	  &GrammarChecker::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ &regSettingsCreate,
	  &SettingsEventHandler::getImplementationName_static,
	  &SettingsEventHandler::getSupportedServiceNames_static,
	  &::cppu::createSingleComponentFactory, 0, 0 },
	{ 0, 0, 0, 0, 0, 0 }
};

extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL
	component_getFactory(const char * implName, void * serviceManager, void * registryKey) {
	VOIKKO_DEBUG("component_getFactory");
	return ::cppu::component_getFactoryHelper(implName, serviceManager, registryKey, regEntries);
}

}
<|endoftext|>


<commit_before>/*
    This file is part of KXForms.

    Copyright (c) 2005,2006 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "reference.h"

#include <kdebug.h>

#include <QStringList>
#include <QMap>

using namespace KXForms;

Reference::Segment::Segment()
  : mCount( 1 ), mIsAttribute( false )
{
}

Reference::Segment::Segment( const QString &str )
{
  fromString( str );
}

Reference::Segment::Segment( const QString &name, int count )
{
  mName = name;
  mCount = count;
  mIsAttribute = false;
}

void Reference::Segment::setName( const QString &name )
{
  if ( name.startsWith( "@" ) ) {
    mName = name.mid( 1 );
    mIsAttribute = true;
  } else {
    mName = name;
    mIsAttribute = false;
  }
}

void Reference::Segment::fromString( const QString &str )
{
  int pos1 = str.indexOf( "[" );
  int pos2 = str.indexOf( "]" );

  int startPos;
  if ( str.startsWith( "@" ) ) {
    mIsAttribute = true;
    startPos = 1;
  } else {
    mIsAttribute = false;
    startPos = 0;
  }

  if ( pos1 >= 0 ) mName = str.mid( startPos, pos1 - startPos );
  else mName = str.mid( startPos );

  if ( pos1 >= 0 && pos2 > pos1 ) {
    QString count = str.mid( pos1 + 1, pos2 - pos1 - 1 );
    bool ok;
    mCount = count.toInt( &ok );
    if ( !ok ) kError() << "Illegal count in reference '" << str << "'" << endl;
  } else {
    mCount = 1;
  }
}

QString Reference::Segment::toString() const
{
  QString str;
  if ( mIsAttribute ) str += '@';
  str += mName;
  if ( mCount > 0 ) str += '[' + QString::number( mCount ) + ']';

  return str;
}

bool Reference::Segment::operator==( const Segment &s ) const
{
  return mName == s.mName && mCount == s.mCount &&
    mIsAttribute == s.mIsAttribute;
}

bool Reference::Segment::operator!=( const Segment &s ) const
{
  return !( *this == s );
}

bool Reference::Segment::isEmpty() const
{
  return mName.isEmpty();
}

Reference::Reference()
  : mValid( true )
{
}

Reference::Reference( const QString &str )
{
  fromString( str );
}

Reference::Reference( const char *str )
{
  fromString( str );
}

Reference &Reference::append( const Reference::Segment &segment )
{
  mSegments.append( segment );

  return *this;
}

Reference &Reference::append( const Reference &ref )
{
  Segment::List segments = ref.segments();
  Segment::List::ConstIterator it;
  for( it = segments.begin(); it != segments.end(); ++it ) {
    mSegments.append( *it );
  }

  return *this;
}

Reference Reference::operator+( const Reference &ref ) const
{
  Reference r = *this;
  return r.append( ref );
}

Reference Reference::operator+( const Reference::Segment &ref ) const
{
  Reference r = *this;
  return r.append( ref );
}

Reference::Segment::List Reference::segments() const
{
  return mSegments;
}

Reference::Segment &Reference::lastSegment()
{
  return mSegments.last();
}

const Reference::Segment &Reference::lastSegment() const
{
  return mSegments.last();
}

bool Reference::isAbsolute() const
{
  return mAbsolute;
}

bool Reference::isRelative() const{
  return !mAbsolute;
}

void Reference::fromString( const QString &str )
{
  mAbsolute = str.startsWith( "/" );

  QStringList s = str.split( "/" );
  QStringList::ConstIterator it;
  for( it = s.begin(); it != s.end(); ++it ) {
    if( (*it).isEmpty() )
      continue;
    mSegments.append( Segment( *it ) );
  }
}

QString Reference::toString() const
{
  QString str;
  Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    if ( !str.isEmpty() ) str += '/';
    str += (*it).toString();
  }
  if ( mAbsolute ) str.prepend( "/" );
  return str;
}

QString Reference::path() const
{
  QString str;
  Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    if ( !str.isEmpty() ) str += '/';
    str += (*it).name();
  }
  if ( mAbsolute ) str.prepend( "/" );
  return str;
}

bool Reference::isValid() const
{
  return mValid;
}

bool Reference::isEmpty() const
{
  return mSegments.isEmpty();
}

bool Reference::operator==( const Reference &ref ) const
{
  if ( mAbsolute != ref.mAbsolute ) return false;

  Segment::List::ConstIterator it = mSegments.begin();
  Segment::List::ConstIterator it2 = ref.mSegments.begin();
  while( it != mSegments.end() && it2 != ref.mSegments.end() ) {
    if ( *it != *it2 ) return false;
    ++it;
    ++it2;
  }
  if ( it != mSegments.end() || it2 != ref.mSegments.end() ) return false;

  return true;
}

bool Reference::operator!=( const Reference &ref ) const
{
  return !( *this == ref );
}

Reference &Reference::operator=( const QString &str )
{
  fromString( str );
  return *this;
}

Reference &Reference::operator=( const char *str )
{
  fromString( str );
  return *this;
}

QDomElement Reference::apply( const QDomDocument &doc ) const
{
  QDomElement result;

  Reference::Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    Reference::Segment segment = *it;
    if ( result.isNull() ) {
      kDebug() << "ROOT" << endl;
      if ( doc.documentElement().tagName() == segment.name() ) {
        result = doc.documentElement();
        continue;
      } else {
        kError() << "Document element '" << doc.documentElement().tagName() <<
           "' isn't '" << segment.name() << "'" << endl;
        return QDomElement();
      }
    }

    QMap<QString, int> counts;
    QDomNode n;
    for( n = result.firstChild(); !n.isNull(); n = n.nextSibling() ) {
      QDomElement e = n.toElement();
      int count = 1;
      QMap<QString, int>::ConstIterator itCount = counts.find( e.tagName() );
      if ( itCount != counts.end() ) count = itCount.value();
      if ( e.tagName() == segment.name() && count == segment.count() ) {
        result = e;
        break;
      }
      counts.insert( e.tagName(), ++count );
    }
    if ( n.isNull() ) {
      kError() << "Reference::apply(): Unable to find element '" <<
        segment.toString() << "'" << endl;
      return QDomElement();
    }
  }

  return result;
}

QDomElement Reference::applyElement( const QDomElement &context ) const
{
  kDebug() << "Reference::applyElement() " << toString() << " Context: "
    << context.tagName() << endl;

  QDomElement result = context;

  if ( mSegments.count() == 1 && lastSegment().name() == "." ) return result;

  Reference::Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    Reference::Segment segment = *it;

//     kDebug() << "  Segment: " << segment.toString() << " Count: " <<
//       segment.count() << endl;

    QMap<QString, int> counts;
    QDomNode n;
    for( n = result.firstChild(); !n.isNull(); n = n.nextSibling() ) {
      QDomElement e = n.toElement();

//       kDebug() << "  E: " << e.tagName() << endl;

      int count = 1;
      QMap<QString, int>::ConstIterator itCount = counts.find( e.tagName() );
      if ( itCount != counts.end() ) count = itCount.value();

//       kDebug() << "  COUNT: " << count << endl;

      if ( e.tagName() == segment.name() && count == segment.count() ) {
        result = e;
        break;
      }
      counts.insert( e.tagName(), ++count );
    }
    if ( n.isNull() ) {
      kError() << "Reference::apply(): Unable to find element '" <<
        segment.toString() << "'" << endl;
      return QDomElement();
    }
  }

  return result;
}

QDomElement Reference::applyAttributeContext( const QDomElement &context ) const
{
  if ( mSegments.count() == 1 ) {
    return context;
  } else {
    Reference r;
    Segment::List::ConstIterator it = mSegments.begin();
    do {
      r.append( *it );
      ++it;
      Segment::List::ConstIterator it2 = it;
      if ( ++it2 == mSegments.end() ) break;
    } while( it != mSegments.end() );
    return r.applyElement( context );
  }
}

QString Reference::applyString( const QDomElement &context ) const
{
  if( isEmpty() )
    return QString();

  Reference::Segment s = lastSegment();

  QString txt;
  if ( s.isAttribute() ) {
    QDomElement targetElement = applyAttributeContext( context );
    txt = targetElement.attribute( s.name() );
  } else {
    QDomElement e = applyElement( context );
    if( e.isText() )
      txt = e.text();
    else {
      QDomNode child = e.firstChild();
      if( !child.nodeValue().isEmpty() )
        txt = child.nodeValue();
      else
        txt = child.nodeName();
    }
  }

  return txt;
}
<commit_msg>Fix attribute flag when the name is given in the constructor.<commit_after>/*
    This file is part of KXForms.

    Copyright (c) 2005,2006 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "reference.h"

#include <kdebug.h>

#include <QStringList>
#include <QMap>

using namespace KXForms;

Reference::Segment::Segment()
  : mCount( 1 ), mIsAttribute( false )
{
}

Reference::Segment::Segment( const QString &str )
{
  fromString( str );
}

Reference::Segment::Segment( const QString &name, int count )
{
  mCount = count;
  setName( name );
}

void Reference::Segment::setName( const QString &name )
{
  if ( name.startsWith( "@" ) ) {
    mName = name.mid( 1 );
    mIsAttribute = true;
  } else {
    mName = name;
    mIsAttribute = false;
  }
}

void Reference::Segment::fromString( const QString &str )
{
  int pos1 = str.indexOf( "[" );
  int pos2 = str.indexOf( "]" );

  int startPos;
  if ( str.startsWith( "@" ) ) {
    mIsAttribute = true;
    startPos = 1;
  } else {
    mIsAttribute = false;
    startPos = 0;
  }

  if ( pos1 >= 0 ) mName = str.mid( startPos, pos1 - startPos );
  else mName = str.mid( startPos );

  if ( pos1 >= 0 && pos2 > pos1 ) {
    QString count = str.mid( pos1 + 1, pos2 - pos1 - 1 );
    bool ok;
    mCount = count.toInt( &ok );
    if ( !ok ) kError() << "Illegal count in reference '" << str << "'" << endl;
  } else {
    mCount = 1;
  }
}

QString Reference::Segment::toString() const
{
  QString str;
  if ( mIsAttribute ) str += '@';
  str += mName;
  if ( mCount > 0 ) str += '[' + QString::number( mCount ) + ']';

  return str;
}

bool Reference::Segment::operator==( const Segment &s ) const
{
  return mName == s.mName && mCount == s.mCount &&
    mIsAttribute == s.mIsAttribute;
}

bool Reference::Segment::operator!=( const Segment &s ) const
{
  return !( *this == s );
}

bool Reference::Segment::isEmpty() const
{
  return mName.isEmpty();
}

Reference::Reference()
  : mValid( true )
{
}

Reference::Reference( const QString &str )
{
  fromString( str );
}

Reference::Reference( const char *str )
{
  fromString( str );
}

Reference &Reference::append( const Reference::Segment &segment )
{
  mSegments.append( segment );

  return *this;
}

Reference &Reference::append( const Reference &ref )
{
  Segment::List segments = ref.segments();
  Segment::List::ConstIterator it;
  for( it = segments.begin(); it != segments.end(); ++it ) {
    mSegments.append( *it );
  }

  return *this;
}

Reference Reference::operator+( const Reference &ref ) const
{
  Reference r = *this;
  return r.append( ref );
}

Reference Reference::operator+( const Reference::Segment &ref ) const
{
  Reference r = *this;
  return r.append( ref );
}

Reference::Segment::List Reference::segments() const
{
  return mSegments;
}

Reference::Segment &Reference::lastSegment()
{
  return mSegments.last();
}

const Reference::Segment &Reference::lastSegment() const
{
  return mSegments.last();
}

bool Reference::isAbsolute() const
{
  return mAbsolute;
}

bool Reference::isRelative() const{
  return !mAbsolute;
}

void Reference::fromString( const QString &str )
{
  mAbsolute = str.startsWith( "/" );

  QStringList s = str.split( "/" );
  QStringList::ConstIterator it;
  for( it = s.begin(); it != s.end(); ++it ) {
    if( (*it).isEmpty() )
      continue;
    mSegments.append( Segment( *it ) );
  }
}

QString Reference::toString() const
{
  QString str;
  Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    if ( !str.isEmpty() ) str += '/';
    str += (*it).toString();
  }
  if ( mAbsolute ) str.prepend( "/" );
  return str;
}

QString Reference::path() const
{
  QString str;
  Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    if ( !str.isEmpty() ) str += '/';
    str += (*it).name();
  }
  if ( mAbsolute ) str.prepend( "/" );
  return str;
}

bool Reference::isValid() const
{
  return mValid;
}

bool Reference::isEmpty() const
{
  return mSegments.isEmpty();
}

bool Reference::operator==( const Reference &ref ) const
{
  if ( mAbsolute != ref.mAbsolute ) return false;

  Segment::List::ConstIterator it = mSegments.begin();
  Segment::List::ConstIterator it2 = ref.mSegments.begin();
  while( it != mSegments.end() && it2 != ref.mSegments.end() ) {
    if ( *it != *it2 ) return false;
    ++it;
    ++it2;
  }
  if ( it != mSegments.end() || it2 != ref.mSegments.end() ) return false;

  return true;
}

bool Reference::operator!=( const Reference &ref ) const
{
  return !( *this == ref );
}

Reference &Reference::operator=( const QString &str )
{
  fromString( str );
  return *this;
}

Reference &Reference::operator=( const char *str )
{
  fromString( str );
  return *this;
}

QDomElement Reference::apply( const QDomDocument &doc ) const
{
  QDomElement result;

  Reference::Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    Reference::Segment segment = *it;
    if ( result.isNull() ) {
      kDebug() << "ROOT" << endl;
      if ( doc.documentElement().tagName() == segment.name() ) {
        result = doc.documentElement();
        continue;
      } else {
        kError() << "Document element '" << doc.documentElement().tagName() <<
           "' isn't '" << segment.name() << "'" << endl;
        return QDomElement();
      }
    }

    QMap<QString, int> counts;
    QDomNode n;
    for( n = result.firstChild(); !n.isNull(); n = n.nextSibling() ) {
      QDomElement e = n.toElement();
      int count = 1;
      QMap<QString, int>::ConstIterator itCount = counts.find( e.tagName() );
      if ( itCount != counts.end() ) count = itCount.value();
      if ( e.tagName() == segment.name() && count == segment.count() ) {
        result = e;
        break;
      }
      counts.insert( e.tagName(), ++count );
    }
    if ( n.isNull() ) {
      kError() << "Reference::apply(): Unable to find element '" <<
        segment.toString() << "'" << endl;
      return QDomElement();
    }
  }

  return result;
}

QDomElement Reference::applyElement( const QDomElement &context ) const
{
  kDebug() << "Reference::applyElement() " << toString() << " Context: "
    << context.tagName() << endl;

  QDomElement result = context;

  if ( mSegments.count() == 1 && lastSegment().name() == "." ) return result;

  Reference::Segment::List::ConstIterator it;
  for( it = mSegments.begin(); it != mSegments.end(); ++it ) {
    Reference::Segment segment = *it;

//     kDebug() << "  Segment: " << segment.toString() << " Count: " <<
//       segment.count() << endl;

    QMap<QString, int> counts;
    QDomNode n;
    for( n = result.firstChild(); !n.isNull(); n = n.nextSibling() ) {
      QDomElement e = n.toElement();

//       kDebug() << "  E: " << e.tagName() << endl;

      int count = 1;
      QMap<QString, int>::ConstIterator itCount = counts.find( e.tagName() );
      if ( itCount != counts.end() ) count = itCount.value();

//       kDebug() << "  COUNT: " << count << endl;

      if ( e.tagName() == segment.name() && count == segment.count() ) {
        result = e;
        break;
      }
      counts.insert( e.tagName(), ++count );
    }
    if ( n.isNull() ) {
      kError() << "Reference::apply(): Unable to find element '" <<
        segment.toString() << "'" << endl;
      return QDomElement();
    }
  }

  return result;
}

QDomElement Reference::applyAttributeContext( const QDomElement &context ) const
{
  if ( mSegments.count() == 1 ) {
    return context;
  } else {
    Reference r;
    Segment::List::ConstIterator it = mSegments.begin();
    do {
      r.append( *it );
      ++it;
      Segment::List::ConstIterator it2 = it;
      if ( ++it2 == mSegments.end() ) break;
    } while( it != mSegments.end() );
    return r.applyElement( context );
  }
}

QString Reference::applyString( const QDomElement &context ) const
{
  if( isEmpty() )
    return QString();

  Reference::Segment s = lastSegment();

  QString txt;
  if ( s.isAttribute() ) {
    QDomElement targetElement = applyAttributeContext( context );
    txt = targetElement.attribute( s.name() );
  } else {
    QDomElement e = applyElement( context );
    if( e.isText() )
      txt = e.text();
    else {
      QDomNode child = e.firstChild();
      if( !child.nodeValue().isEmpty() )
        txt = child.nodeValue();
      else
        txt = child.nodeName();
    }
  }

  return txt;
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <vector>
#include <string>
// Ex: #include <regex>
#include <fstream>

#include "const.hpp"
#include "renderer.hpp"
#include "printer.hpp"
#include "ram.hpp"
#include "cpu.hpp"
#include "util.hpp"
#include "drawing.hpp"

using namespace std;

// STATIC PUBLIC:
string Renderer::renderState(Printer printerIn, Ram ramIn, Cpu cpuIn) {
    Renderer instance(printerIn, ramIn, cpuIn);

    string out;
    for (string line : Util::splitString(drawing)) {
        string processedLine = instance.insertActualValues(line);
        out += processedLine + "\n";
    }
    out.erase(out.end() - 1);
    return out;
}

// PRIVATE CONSTRUCTOR:
Renderer::Renderer(Printer printerIn, Ram ramIn, Cpu cpuIn) {
    Renderer::printer = printerIn;
    Renderer::ram = ramIn;
    Renderer::cpu = cpuIn;
    switchIndex.clear();
}

// DYNAMIC PRIVATE:
string Renderer::insertActualValues(string lineIn) {
	// Ex: regex alpNum("[0-9a-z]");
	string lineOut;

	for (char cIn : lineIn) {
		char cOut;

		bool charIsALightbulb = (cIn >= 'a' && cIn <= 'z') || (cIn >= '0' && cIn <= '9');
        if (charIsALightbulb) {
            cOut = getLightbulb(cIn);
        } else {
            cOut = cIn;
        }
		lineOut += cOut;
	}
	return lineOut;
}

char Renderer::getLightbulb(char cIn) {
    int i = switchIndex[cIn]++;

    // Ex: regex patRam("[0-9a-e]");

	bool charRepresentsRam = (cIn >= 'a' && cIn <= 'e') || (cIn >= '0' && cIn <= '9');
    if (charRepresentsRam) {
        int j = Util::hexToInt(cIn);
        return getRamAt(j, i);
    }

    switch (cIn) {
        case 'p':
            return Util::getChar(pcIsPointingToAddress(i));
        case 's':
            return Util::getChar(instructionIsPointingToAddress(i));
        case 'r':
            return  Util::getChar(cpu.getRegister().at(i));
        case 'i':
            return Util::getChar(instructionHasId(i));
        case 'o':
            return getFormattedOutput(i);
    }
	//There was an error parsing a drawing file. Problem with char cIn
    return ' ';
}

bool Renderer::pcIsPointingToAddress(int adr) {
    return Util::getInt(cpu.getPc()) == adr;
}

bool Renderer::instructionIsPointingToAddress(int adr) {
    // If execution did't yet start
    if (cpu.getCycle() == 0) {
        return false;
    }
    // If pc is pointing to the last addres (execution reached the end)
    if (Util::getInt(cpu.getPc()) == RAM_SIZE) {
        return false;
    }
    return Util::getInt(cpu.getAddress()) == adr;
}

bool Renderer::instructionHasId(int id) {
    // If execution did't yet start
    if (cpu.getCycle() == 0) {
        return false;
    }
    // If pc is pointing to the last addres (execution reached the end)
    if (Util::getInt(cpu.getPc()) == RAM_SIZE) {
        return false;
    }
    return Util::getInt(cpu.getInstruction()) == id;
}

char Renderer::getFormattedOutput(int i) {
    if (printer.getPrinterOutput().length() <= (unsigned) i) {
        return ' ';
    } else {
        return printer.getPrinterOutput().at(i);
    }
}

char Renderer::getRamAt(int j, int i) {
    return Util::getChar(ram.state.at(j).at(i));
}

<commit_msg>cleanup<commit_after>#include <algorithm>
#include <vector>
#include <string>
#include <fstream>

#include "const.hpp"
#include "renderer.hpp"
#include "printer.hpp"
#include "ram.hpp"
#include "cpu.hpp"
#include "util.hpp"
#include "drawing.hpp"

using namespace std;

// STATIC PUBLIC:
string Renderer::renderState(Printer printerIn, Ram ramIn, Cpu cpuIn) {
    Renderer instance(printerIn, ramIn, cpuIn);

    string out;
    for (string line : Util::splitString(drawing)) {
        string processedLine = instance.insertActualValues(line);
        out += processedLine + "\n";
    }
    out.erase(out.end() - 1);
    return out;
}

// PRIVATE CONSTRUCTOR:
Renderer::Renderer(Printer printerIn, Ram ramIn, Cpu cpuIn) {
    Renderer::printer = printerIn;
    Renderer::ram = ramIn;
    Renderer::cpu = cpuIn;
    switchIndex.clear();
}

// DYNAMIC PRIVATE:
string Renderer::insertActualValues(string lineIn) {
	string lineOut;

	for (char cIn : lineIn) {
		char cOut;

        // Regex: [0-9a-z];
		bool charIsALightbulb = (cIn >= 'a' && cIn <= 'z') || (cIn >= '0' && cIn <= '9');
        if (charIsALightbulb) {
            cOut = getLightbulb(cIn);
        } else {
            cOut = cIn;
        }
		lineOut += cOut;
	}
	return lineOut;
}

char Renderer::getLightbulb(char cIn) {
    int i = switchIndex[cIn]++;

    // Regex: [0-9a-e]
	bool charRepresentsRam = (cIn >= 'a' && cIn <= 'e') || (cIn >= '0' && cIn <= '9');
    if (charRepresentsRam) {
        int j = Util::hexToInt(cIn);
        return getRamAt(j, i);
    }

    switch (cIn) {
        case 'p':
            return Util::getChar(pcIsPointingToAddress(i));
        case 's':
            return Util::getChar(instructionIsPointingToAddress(i));
        case 'r':
            return  Util::getChar(cpu.getRegister().at(i));
        case 'i':
            return Util::getChar(instructionHasId(i));
        case 'o':
            return getFormattedOutput(i);
    }
	//There was an error parsing a drawing file. Problem with char cIn
    return ' ';
}

bool Renderer::pcIsPointingToAddress(int adr) {
    return Util::getInt(cpu.getPc()) == adr;
}

bool Renderer::instructionIsPointingToAddress(int adr) {
    // If execution did't yet start
    if (cpu.getCycle() == 0) {
        return false;
    }
    // If pc is pointing to the last addres (execution reached the end)
    if (Util::getInt(cpu.getPc()) == RAM_SIZE) {
        return false;
    }
    return Util::getInt(cpu.getAddress()) == adr;
}

bool Renderer::instructionHasId(int id) {
    // If execution did't yet start
    if (cpu.getCycle() == 0) {
        return false;
    }
    // If pc is pointing to the last addres (execution reached the end)
    if (Util::getInt(cpu.getPc()) == RAM_SIZE) {
        return false;
    }
    return Util::getInt(cpu.getInstruction()) == id;
}

char Renderer::getFormattedOutput(int i) {
    if (printer.getPrinterOutput().length() <= (unsigned) i) {
        return ' ';
    } else {
        return printer.getPrinterOutput().at(i);
    }
}

char Renderer::getRamAt(int j, int i) {
    return Util::getChar(ram.state.at(j).at(i));
}

<|endoftext|>


<commit_before>/*
  This file is part of the Groupware/KOrganizer integration.

  Requires the Qt and KDE widget libraries, available at no cost at
  http://www.trolltech.com and http://www.kde.org respectively

  Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB
        <info@klaralvdalens-datakonsult.se>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA  02111-1307, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt.  If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
*/

#include "kogroupware.h"
#include "freebusymanager.h"
#include "calendarview.h"
#include "mailscheduler.h"
#include "koprefs.h"
#include <libkdepim/email.h>
#include <libkcal/attendee.h>
#include <libkcal/journal.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kdirwatch.h>
#include <qfile.h>
#include <qregexp.h>
#include <qdir.h>
#include <qtimer.h>

FreeBusyManager *KOGroupware::mFreeBusyManager = 0;

KOGroupware *KOGroupware::mInstance = 0;

KOGroupware *KOGroupware::create( CalendarView *view,
                                  KCal::CalendarResources *calendar )
{
  if( !mInstance )
    mInstance = new KOGroupware( view, calendar );
  return mInstance;
}

KOGroupware *KOGroupware::instance()
{
  // Doesn't create, that is the task of create()
  Q_ASSERT( mInstance );
  return mInstance;
}

KOGroupware::KOGroupware( CalendarView* view, KCal::CalendarResources* cal )
  : QObject( 0, "kmgroupware_instance" ), mView( view ), mCalendar( cal )
{
  // Temporary hack: Wait one minute before starting the scheduling handling
  // This is because we need the full calendars to be loaded first
  // TODO: GET RID OF THIS!!! The real fix is to listen for the resources
  // being all done loading and start the scheduling after that. Even
  // better fix would be that we would be able to locate the resource
  // an event is saved in even though the resource is deactivated
  //QTimer::singleShot( 60000, this, SLOT( slotStartScheduling() ) );

  // It could be that the hack ^ is not needed after all. Test that for
  // a while. *sigh* - experimenting programming is bad
  slotStartScheduling();
}

FreeBusyManager *KOGroupware::freeBusyManager()
{
  if ( !mFreeBusyManager ) {
    mFreeBusyManager = new FreeBusyManager( this, "freebusymanager" );
    mFreeBusyManager->setCalendar( mCalendar );
    connect( mCalendar, SIGNAL( calendarChanged() ),
             mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) );
  }

  return mFreeBusyManager;
}

void KOGroupware::slotStartScheduling()
{
  // Set up the dir watch of the three incoming dirs
  KDirWatch* watcher = KDirWatch::self();
  watcher->addDir( locateLocal( "data", "korganizer/income.accepted/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.tentative/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.cancel/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.reply/" ) );
  connect( watcher, SIGNAL( dirty( const QString& ) ),
           this, SLOT( incomingDirChanged( const QString& ) ) );
  // Now set the ball rolling
  incomingDirChanged( locateLocal( "data", "korganizer/income.accepted/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.tentative/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.cancel/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.reply/" ) );
}

void KOGroupware::incomingDirChanged( const QString& path )
{
  const QString incomingDirName = locateLocal( "data","korganizer/" )
                                  + "income.";
  if ( !path.startsWith( incomingDirName ) ) {
    //kdDebug(5850) << "incomingDirChanged: Wrong dir " << path << endl;
    return;
  }
  QString action = path.mid( incomingDirName.length() );
  while ( action.length() > 0 && action[ action.length()-1 ] == '/' )
    // Strip slashes at the end
    action.truncate( action.length()-1 );

  // Handle accepted invitations
  QDir dir( path );
  const QStringList files = dir.entryList( QDir::Files );
  if ( files.isEmpty() )
    // No more files here
    return;

  // Read the file and remove it
  QFile f( path + "/" + files[0] );
  if (!f.open(IO_ReadOnly)) {
    kdError(5850) << "Can't open file '" << files[0] << "'" << endl;
    return;
  }
  QTextStream t(&f);
  t.setEncoding( QTextStream::UnicodeUTF8 );
  // Read the receiver email address
  QString receiver = t.readLine();
  if ( receiver == "Receiver Not Searched" )
    // The receiver was never checked
    receiver = QString::null;
  else
    // There should be an email address in here
    receiver = KPIM::getEmailAddr( receiver );
  // Read the iCal
  QString iCal = t.read();

  f.remove();

  kdDebug(5850) << "Received this for scheduling (" << action << ")\n"
                << "Receiver: " << receiver << "\niCal:\n" << iCal << endl;
  ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal );
  if ( !message ) {
    QString errorMessage;
    if (mFormat.exception())
      errorMessage = i18n( "Error message: %1" ).arg( mFormat.exception()->message() );
    kdDebug(5850) << "MailScheduler::retrieveTransactions() Error parsing "
                  << errorMessage << endl;
    KMessageBox::detailedError( mView,
        i18n("Error while processing an invitation or update."),
        errorMessage );
    return;
  }

  KCal::Scheduler::Method method =
    static_cast<KCal::Scheduler::Method>( message->method() );
  KCal::ScheduleMessage::Status status = message->status();
  KCal::Incidence* incidence =
    dynamic_cast<KCal::Incidence*>( message->event() );
  KCal::MailScheduler scheduler( mCalendar );
  if ( action.startsWith( "accepted" ) || action.startsWith( "tentative" ) ) {
    // Find myself and set my status. This can't be done in the scheduler,
    // since this does not know the choice I made in the KMail bpf
    KCal::Attendee::List attendees = incidence->attendees();
    KCal::Attendee::List::ConstIterator it;
    for ( it = attendees.begin(); it != attendees.end(); ++it ) {
      if( (*it)->email() == receiver ) {
        if ( action.startsWith( "accepted" ) )
          (*it)->setStatus( KCal::Attendee::Accepted );
        else
          (*it)->setStatus( KCal::Attendee::Tentative );
        break;
      }
    }
    scheduler.acceptTransaction( incidence, method, status, receiver );
  } else if ( action.startsWith( "cancel" ) )
    // Delete the old incidence, if one is present
    mCalendar->deleteIncidence( incidence );
  else if ( action.startsWith( "reply" ) )
    scheduler.acceptTransaction( incidence, method, status );
  else
    kdError(5850) << "Unknown incoming action " << action << endl;
  mView->updateView();
}

/* This function sends mails if necessary, and makes sure the user really
 * want to change his calendar.
 *
 * Return true means accept the changes
 * Return false means revert the changes
 */
bool KOGroupware::sendICalMessage( QWidget* parent,
                                   KCal::Scheduler::Method method,
                                   Incidence* incidence, bool isDeleting,
                                   bool statusChanged )
{
  // If there are no attendees, don't bother
  if( incidence->attendees().isEmpty() )
    return true;

  bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() );
  int rc = 0;
  /*
   * There are two scenarios:
   * o "we" are the organizer, where "we" means any of the identities or mail
   *   addresses known to Kontact/PIM. If there are attendees, we need to mail
   *   them all, even if one or more of them are also "us". Otherwise there
   *   would be no way to invite a resource or our boss, other identities we
   *   also manage.
   * o "we: are not the organizer, which means we changed the completion status
   *   of a todo, or we changed our attendee status from, say, tentative to
   *   accepted. In both cases we only mail the organizer. All other changes
   *   bring us out of sync with the organizer, so we won't mail, if the user
   *   insists on applying them.
   */

  if ( isOrganizer ) {
    /* We are the organizer. If there is more than one attendee, or if there is
     * only one, and it's not the same as the organizer, ask the user to send
     * mail. */
    if ( incidence->attendees().count() > 1
        || incidence->attendees().first()->email() != incidence->organizer().email() ) {
      QString type;
      if( incidence->type() == "Event") type = i18n("event");
      else if( incidence->type() == "Todo" ) type = i18n("task");
      else if( incidence->type() == "Journal" ) type = i18n("journal entry");
      else type = incidence->type();
      QString txt = i18n( "This %1 includes other people. "
          "Should email be sent out to the attendees?" )
        .arg( type );
      rc = KMessageBox::questionYesNoCancel( parent, txt,
          i18n("Group scheduling email") );
    } else {
      return true;
    }
  } else if( incidence->type() == "Todo" ) {
    if( method == Scheduler::Request )
      // This is an update to be sent to the organizer
      method = Scheduler::Reply;

    // Ask if the user wants to tell the organizer about the current status
    QString txt = i18n( "Do you want to send a status update to the "
                        "organizer of this task?");
    rc = KMessageBox::questionYesNo( parent, txt );
  } else if( incidence->type() == "Event" ) {
    QString txt;
    if ( statusChanged && method == Scheduler::Request ) {
      txt = i18n( "Your status as an attendee of this event "
          "changed. Do you want to send a status update to the "
          "organizer of this event?" );
      method = Scheduler::Reply;
      rc = KMessageBox::questionYesNo( parent, txt );
    } else {
      if( isDeleting )
        txt = i18n( "You are not the organizer of this event. "
            "Deleting it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to delete it?" );
      else
        txt = i18n( "You are not the organizer of this event. "
            "Editing it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to edit it?" );
      rc = KMessageBox::questionYesNo( parent, txt );
      return ( rc == KMessageBox::Yes );
    }
  } else {
    kdWarning(5850) << "Groupware messages for Journals are not implemented yet!" << endl;
    return true;
  }
  if( rc == KMessageBox::Yes ) {
    // We will be sending out a message here. Now make sure there is
    // some summary
    if( incidence->summary().isEmpty() )
      incidence->setSummary( i18n("<No summary given>") );

    // Send the mail
    KCal::MailScheduler scheduler( mCalendar );
    scheduler.performTransaction( incidence, method );

    return true;
  } else if( rc == KMessageBox::No )
    return true;
  else
    return false;
}

#include "kogroupware.moc"
<commit_msg>Don't circumvent the scheduler when handling cancel messages, because otherwise proper schedulingID conversion does not happen.  (proko2 issue1109)<commit_after>/*
  This file is part of the Groupware/KOrganizer integration.

  Requires the Qt and KDE widget libraries, available at no cost at
  http://www.trolltech.com and http://www.kde.org respectively

  Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB
        <info@klaralvdalens-datakonsult.se>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA  02111-1307, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt.  If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
*/

#include "kogroupware.h"
#include "freebusymanager.h"
#include "calendarview.h"
#include "mailscheduler.h"
#include "koprefs.h"
#include <libkdepim/email.h>
#include <libkcal/attendee.h>
#include <libkcal/journal.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kdirwatch.h>
#include <qfile.h>
#include <qregexp.h>
#include <qdir.h>
#include <qtimer.h>

FreeBusyManager *KOGroupware::mFreeBusyManager = 0;

KOGroupware *KOGroupware::mInstance = 0;

KOGroupware *KOGroupware::create( CalendarView *view,
                                  KCal::CalendarResources *calendar )
{
  if( !mInstance )
    mInstance = new KOGroupware( view, calendar );
  return mInstance;
}

KOGroupware *KOGroupware::instance()
{
  // Doesn't create, that is the task of create()
  Q_ASSERT( mInstance );
  return mInstance;
}

KOGroupware::KOGroupware( CalendarView* view, KCal::CalendarResources* cal )
  : QObject( 0, "kmgroupware_instance" ), mView( view ), mCalendar( cal )
{
  // Temporary hack: Wait one minute before starting the scheduling handling
  // This is because we need the full calendars to be loaded first
  // TODO: GET RID OF THIS!!! The real fix is to listen for the resources
  // being all done loading and start the scheduling after that. Even
  // better fix would be that we would be able to locate the resource
  // an event is saved in even though the resource is deactivated
  //QTimer::singleShot( 60000, this, SLOT( slotStartScheduling() ) );

  // It could be that the hack ^ is not needed after all. Test that for
  // a while. *sigh* - experimenting programming is bad
  slotStartScheduling();
}

FreeBusyManager *KOGroupware::freeBusyManager()
{
  if ( !mFreeBusyManager ) {
    mFreeBusyManager = new FreeBusyManager( this, "freebusymanager" );
    mFreeBusyManager->setCalendar( mCalendar );
    connect( mCalendar, SIGNAL( calendarChanged() ),
             mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) );
  }

  return mFreeBusyManager;
}

void KOGroupware::slotStartScheduling()
{
  // Set up the dir watch of the three incoming dirs
  KDirWatch* watcher = KDirWatch::self();
  watcher->addDir( locateLocal( "data", "korganizer/income.accepted/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.tentative/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.cancel/" ) );
  watcher->addDir( locateLocal( "data", "korganizer/income.reply/" ) );
  connect( watcher, SIGNAL( dirty( const QString& ) ),
           this, SLOT( incomingDirChanged( const QString& ) ) );
  // Now set the ball rolling
  incomingDirChanged( locateLocal( "data", "korganizer/income.accepted/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.tentative/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.cancel/" ) );
  incomingDirChanged( locateLocal( "data", "korganizer/income.reply/" ) );
}

void KOGroupware::incomingDirChanged( const QString& path )
{
  const QString incomingDirName = locateLocal( "data","korganizer/" )
                                  + "income.";
  if ( !path.startsWith( incomingDirName ) ) {
    //kdDebug(5850) << "incomingDirChanged: Wrong dir " << path << endl;
    return;
  }
  QString action = path.mid( incomingDirName.length() );
  while ( action.length() > 0 && action[ action.length()-1 ] == '/' )
    // Strip slashes at the end
    action.truncate( action.length()-1 );

  // Handle accepted invitations
  QDir dir( path );
  const QStringList files = dir.entryList( QDir::Files );
  if ( files.isEmpty() )
    // No more files here
    return;

  // Read the file and remove it
  QFile f( path + "/" + files[0] );
  if (!f.open(IO_ReadOnly)) {
    kdError(5850) << "Can't open file '" << files[0] << "'" << endl;
    return;
  }
  QTextStream t(&f);
  t.setEncoding( QTextStream::UnicodeUTF8 );
  // Read the receiver email address
  QString receiver = t.readLine();
  if ( receiver == "Receiver Not Searched" )
    // The receiver was never checked
    receiver = QString::null;
  else
    // There should be an email address in here
    receiver = KPIM::getEmailAddr( receiver );
  // Read the iCal
  QString iCal = t.read();

  f.remove();

  kdDebug(5850) << "Received this for scheduling (" << action << ")\n"
                << "Receiver: " << receiver << "\niCal:\n" << iCal << endl;
  ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal );
  if ( !message ) {
    QString errorMessage;
    if (mFormat.exception())
      errorMessage = i18n( "Error message: %1" ).arg( mFormat.exception()->message() );
    kdDebug(5850) << "MailScheduler::retrieveTransactions() Error parsing "
                  << errorMessage << endl;
    KMessageBox::detailedError( mView,
        i18n("Error while processing an invitation or update."),
        errorMessage );
    return;
  }

  KCal::Scheduler::Method method =
    static_cast<KCal::Scheduler::Method>( message->method() );
  KCal::ScheduleMessage::Status status = message->status();
  KCal::Incidence* incidence =
    dynamic_cast<KCal::Incidence*>( message->event() );
  KCal::MailScheduler scheduler( mCalendar );
  if ( action.startsWith( "accepted" ) || action.startsWith( "tentative" ) ) {
    // Find myself and set my status. This can't be done in the scheduler,
    // since this does not know the choice I made in the KMail bpf
    KCal::Attendee::List attendees = incidence->attendees();
    KCal::Attendee::List::ConstIterator it;
    for ( it = attendees.begin(); it != attendees.end(); ++it ) {
      if( (*it)->email() == receiver ) {
        if ( action.startsWith( "accepted" ) )
          (*it)->setStatus( KCal::Attendee::Accepted );
        else
          (*it)->setStatus( KCal::Attendee::Tentative );
        break;
      }
    }
    scheduler.acceptTransaction( incidence, method, status, receiver );
  } else if ( action.startsWith( "cancel" ) )
    // Delete the old incidence, if one is present
    scheduler.acceptTransaction( incidence, KCal::Scheduler::Cancel, status );
  else if ( action.startsWith( "reply" ) )
    scheduler.acceptTransaction( incidence, method, status );
  else
    kdError(5850) << "Unknown incoming action " << action << endl;
  mView->updateView();
}

/* This function sends mails if necessary, and makes sure the user really
 * want to change his calendar.
 *
 * Return true means accept the changes
 * Return false means revert the changes
 */
bool KOGroupware::sendICalMessage( QWidget* parent,
                                   KCal::Scheduler::Method method,
                                   Incidence* incidence, bool isDeleting,
                                   bool statusChanged )
{
  // If there are no attendees, don't bother
  if( incidence->attendees().isEmpty() )
    return true;

  bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() );
  int rc = 0;
  /*
   * There are two scenarios:
   * o "we" are the organizer, where "we" means any of the identities or mail
   *   addresses known to Kontact/PIM. If there are attendees, we need to mail
   *   them all, even if one or more of them are also "us". Otherwise there
   *   would be no way to invite a resource or our boss, other identities we
   *   also manage.
   * o "we: are not the organizer, which means we changed the completion status
   *   of a todo, or we changed our attendee status from, say, tentative to
   *   accepted. In both cases we only mail the organizer. All other changes
   *   bring us out of sync with the organizer, so we won't mail, if the user
   *   insists on applying them.
   */

  if ( isOrganizer ) {
    /* We are the organizer. If there is more than one attendee, or if there is
     * only one, and it's not the same as the organizer, ask the user to send
     * mail. */
    if ( incidence->attendees().count() > 1
        || incidence->attendees().first()->email() != incidence->organizer().email() ) {
      QString type;
      if( incidence->type() == "Event") type = i18n("event");
      else if( incidence->type() == "Todo" ) type = i18n("task");
      else if( incidence->type() == "Journal" ) type = i18n("journal entry");
      else type = incidence->type();
      QString txt = i18n( "This %1 includes other people. "
          "Should email be sent out to the attendees?" )
        .arg( type );
      rc = KMessageBox::questionYesNoCancel( parent, txt,
          i18n("Group scheduling email") );
    } else {
      return true;
    }
  } else if( incidence->type() == "Todo" ) {
    if( method == Scheduler::Request )
      // This is an update to be sent to the organizer
      method = Scheduler::Reply;

    // Ask if the user wants to tell the organizer about the current status
    QString txt = i18n( "Do you want to send a status update to the "
                        "organizer of this task?");
    rc = KMessageBox::questionYesNo( parent, txt );
  } else if( incidence->type() == "Event" ) {
    QString txt;
    if ( statusChanged && method == Scheduler::Request ) {
      txt = i18n( "Your status as an attendee of this event "
          "changed. Do you want to send a status update to the "
          "organizer of this event?" );
      method = Scheduler::Reply;
      rc = KMessageBox::questionYesNo( parent, txt );
    } else {
      if( isDeleting )
        txt = i18n( "You are not the organizer of this event. "
            "Deleting it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to delete it?" );
      else
        txt = i18n( "You are not the organizer of this event. "
            "Editing it will bring your calendar out of sync "
            "with the organizers calendar. Do you really want "
            "to edit it?" );
      rc = KMessageBox::questionYesNo( parent, txt );
      return ( rc == KMessageBox::Yes );
    }
  } else {
    kdWarning(5850) << "Groupware messages for Journals are not implemented yet!" << endl;
    return true;
  }
  if( rc == KMessageBox::Yes ) {
    // We will be sending out a message here. Now make sure there is
    // some summary
    if( incidence->summary().isEmpty() )
      incidence->setSummary( i18n("<No summary given>") );

    // Send the mail
    KCal::MailScheduler scheduler( mCalendar );
    scheduler.performTransaction( incidence, method );

    return true;
  } else if( rc == KMessageBox::No )
    return true;
  else
    return false;
}

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