<commit_before>
#include <girepository.h>
#include <glib.h>

#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "type.h"
#include "util.h"
#include "value.h"

using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Persistent;
using Nan::New;
using Nan::WeakCallbackType;

namespace GNodeJS {

size_t Boxed::GetSize (GIBaseInfo *boxed_info) {
    GIInfoType i_type = g_base_info_get_type(boxed_info);
    if (i_type == GI_INFO_TYPE_STRUCT) {
        return g_struct_info_get_size((GIStructInfo*)boxed_info);
    } else if (i_type == GI_INFO_TYPE_UNION) {
        return g_union_info_get_size((GIUnionInfo*)boxed_info);
    } else {
        g_assert_not_reached();
    }
}

static bool IsNoArgsConstructor(GIFunctionInfo *info) {
    auto flags = g_function_info_get_flags (info);
    return ((flags & GI_FUNCTION_IS_CONSTRUCTOR) != 0
        && g_callable_info_get_n_args (info) == 0);
}

static GIFunctionInfo* FindBoxedConstructor(GIBaseInfo* info) {
    if (GI_IS_STRUCT_INFO (info)) {
        int n_methods = g_struct_info_get_n_methods (info);
        for (int i = 0; i < n_methods; i++) {
            GIFunctionInfo* fn_info = g_struct_info_get_method (info, i);
            if (IsNoArgsConstructor (fn_info))
                return fn_info;
            g_base_info_unref(fn_info);
        }

        return g_struct_info_find_method(info, "new");
    }
    else {
        int n_methods = g_union_info_get_n_methods (info);
        for (int i = 0; i < n_methods; i++) {
            GIFunctionInfo* fn_info = g_union_info_get_method (info, i);
            if (IsNoArgsConstructor (fn_info))
                return fn_info;
            g_base_info_unref(fn_info);
        }

        return g_union_info_find_method(info, "new");
    }
}

static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info);

static void BoxedConstructor(const Nan::FunctionCallbackInfo<Value> &info) {
    /* See gobject.cc for how this works */
    if (!info.IsConstructCall ()) {
        Nan::ThrowTypeError("Not a construct call");
        return;
    }

    void *boxed = NULL;
    unsigned long size = 0;

    Local<Object> self = info.This ();
    GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value ();
    GType gtype = g_registered_type_info_get_g_type (gi_info);

    if (info[0]->IsExternal ()) {
        /* The External case. This is how WrapperFromBoxed is called. */

        boxed = External::Cast(*info[0])->Value();

    } else {
        /* User code calling `new Pango.AttrList()` */

        size = Boxed::GetSize(gi_info);

        if (size != 0) {
            boxed = g_slice_alloc0(size);
        }
        // TODO(find what to do in these cases)
        /* else {
            GIFunctionInfo* fn_info = FindBoxedConstructor(gi_info);

            if (fn_info != NULL) {

                auto value = CallFunctionInfo (fn_info, info);

                if (value.IsEmpty())
                    return; // did throw

                GIArgument arg;

                if (V8ToGIArgument(gi_info, &arg, value))
                    boxed = arg.v_pointer;
                else
                    return; // did throw

            } else {
                log("constructor not found");
            }
        } */

        if (!boxed) {
            Nan::ThrowError("Boxed allocation failed");
            return;
        }
    }

    self->SetAlignedPointerInInternalField (0, boxed);

    Nan::DefineOwnProperty(self,
            UTF8("__gtype__"),
            Nan::New<Number>(gtype),
            (v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum)
    );

    auto* box = new Boxed();
    box->data = boxed;
    box->size = size;
    box->g_type = gtype;
    box->persistent = new Nan::Persistent<Object>(self);
    box->persistent->SetWeak(box, BoxedDestroyed, Nan::WeakCallbackType::kParameter);
}

static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info) {
    Boxed *box = info.GetParameter();

    if (G_TYPE_IS_BOXED(box->g_type)) {
        g_boxed_free(box->g_type, box->data);
    }
    else if (box->size != 0) {
        // Allocated in ./function.cc @ AllocateArgument
        g_slice_free1(box->size, box->data);
    }
    else if (box->data != NULL) {
        /*
         * TODO(find informations on what to do here. Only seems to be reached for GI.Typelib)
         */
        log("boxed possibly not freed");
    }

    delete box->persistent;
    delete box;
}

Local<FunctionTemplate> GetBoxedTemplate(GIBaseInfo *info, GType gtype) {
    void *data = NULL;

    if (gtype != G_TYPE_NONE) {
        data = g_type_get_qdata(gtype, GNodeJS::template_quark());
    }

    /*
     * Template already created
     */

    if (data) {
        Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data;
        Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate> (*persistent);
        return tpl;
    }

    /*
     * Template not created yet
     */

    auto tpl = New<FunctionTemplate>(BoxedConstructor, New<External>(info));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    if (gtype != G_TYPE_NONE) {
        const char *class_name = g_type_name(gtype);
        tpl->SetClassName (UTF8(class_name));
    } else {
        const char *class_name = g_base_info_get_name (info);
        tpl->SetClassName (UTF8(class_name));
    }

    if (gtype == G_TYPE_NONE)
        return tpl;

    Isolate *isolate = Isolate::GetCurrent();
    auto *persistent = new v8::Persistent<FunctionTemplate>(isolate, tpl);
    persistent->SetWeak(
            g_base_info_ref(info),
            GNodeJS::ClassDestroyed,
            WeakCallbackType::kParameter);

    g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);

    return tpl;
}

Local<Function> MakeBoxedClass(GIBaseInfo *info) {
    GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);

    if (gtype == G_TYPE_NONE) {
        auto moduleCache = GNodeJS::GetModuleCache();
        auto ns   = UTF8 (g_base_info_get_namespace (info));
        auto name = UTF8 (g_base_info_get_name (info));

        if (Nan::HasOwnProperty(moduleCache, ns).FromMaybe(false)) {
            auto module = Nan::Get(moduleCache, ns).ToLocalChecked()->ToObject();

            if (Nan::HasOwnProperty(module, name).FromMaybe(false)) {
                auto constructor = Nan::Get(module, name).ToLocalChecked()->ToObject();
                return Local<Function>::Cast (constructor);
            }
        }
    }

    Local<FunctionTemplate> tpl = GetBoxedTemplate (info, gtype);
    return tpl->GetFunction ();
}

Local<Value> WrapperFromBoxed(GIBaseInfo *info, void *data) {
    if (data == NULL)
        return Nan::Null();

    Local<Function> constructor = MakeBoxedClass (info);

    Local<Value> boxed_external = Nan::New<External> (data);
    Local<Value> args[] = { boxed_external };
    // FIXME(we're not handling failure here)
    MaybeLocal<Object> instance = Nan::NewInstance(constructor, 1, args);
    return instance.ToLocalChecked();
}

void* BoxedFromWrapper(Local<Value> value) {
    Local<Object> object = value->ToObject ();
    g_assert(object->InternalFieldCount() > 0);
    void *boxed = object->GetAlignedPointerFromInternalField(0);
    return boxed;
}

};
<commit_msg>boxed: use annotation constructor<commit_after>
#include <girepository.h>
#include <glib.h>

#include "boxed.h"
#include "debug.h"
#include "error.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "type.h"
#include "util.h"
#include "value.h"

using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Persistent;
using Nan::New;
using Nan::WeakCallbackType;

namespace GNodeJS {

size_t Boxed::GetSize (GIBaseInfo *boxed_info) {
    GIInfoType i_type = g_base_info_get_type(boxed_info);
    if (i_type == GI_INFO_TYPE_STRUCT) {
        return g_struct_info_get_size((GIStructInfo*)boxed_info);
    } else if (i_type == GI_INFO_TYPE_UNION) {
        return g_union_info_get_size((GIUnionInfo*)boxed_info);
    } else {
        g_assert_not_reached();
    }
}

static bool IsNoArgsConstructor(GIFunctionInfo *info) {
    auto flags = g_function_info_get_flags (info);
    return ((flags & GI_FUNCTION_IS_CONSTRUCTOR) != 0
        && g_callable_info_get_n_args (info) == 0);
}

static GIFunctionInfo* FindBoxedConstructor(GIBaseInfo* info) {
    if (GI_IS_STRUCT_INFO (info)) {
        int n_methods = g_struct_info_get_n_methods (info);
        for (int i = 0; i < n_methods; i++) {
            GIFunctionInfo* fn_info = g_struct_info_get_method (info, i);
            if (IsNoArgsConstructor (fn_info))
                return fn_info;
            g_base_info_unref(fn_info);
        }

        return g_struct_info_find_method(info, "new");
    }
    else {
        int n_methods = g_union_info_get_n_methods (info);
        for (int i = 0; i < n_methods; i++) {
            GIFunctionInfo* fn_info = g_union_info_get_method (info, i);
            if (IsNoArgsConstructor (fn_info))
                return fn_info;
            g_base_info_unref(fn_info);
        }

        return g_union_info_find_method(info, "new");
    }
}

static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info);

static void BoxedConstructor(const Nan::FunctionCallbackInfo<Value> &info) {
    /* See gobject.cc for how this works */
    if (!info.IsConstructCall ()) {
        Nan::ThrowTypeError("Not a construct call");
        return;
    }

    void *boxed = NULL;
    unsigned long size = 0;

    Local<Object> self = info.This ();
    GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value ();
    GType gtype = g_registered_type_info_get_g_type (gi_info);

    if (info[0]->IsExternal ()) {
        /* The External case. This is how WrapperFromBoxed is called. */

        boxed = External::Cast(*info[0])->Value();

    } else {
        /* User code calling `new Pango.AttrList()` */

        size = Boxed::GetSize(gi_info);

        if (size != 0) {
            boxed = g_slice_alloc0(size);
        }
        // TODO(find what to do in these cases)
        else {
            GIFunctionInfo* fn_info = FindBoxedConstructor(gi_info);

            if (fn_info == NULL) {
                Nan::ThrowError("Boxed allocation failed: no constructor found");
                return;
            }

            FunctionInfo func(fn_info);
            GIArgument return_value;
            GError *error = NULL;

            FunctionCall (&func, info, &return_value, &error);

            if (error) {
                Throw::GError ("Boxed constructor failed", error);
                g_error_free (error);
                return;
            }

            boxed = return_value.v_pointer;
        }

        if (!boxed) {
            Nan::ThrowError("Boxed allocation failed");
            return;
        }
    }

    self->SetAlignedPointerInInternalField (0, boxed);

    Nan::DefineOwnProperty(self,
            UTF8("__gtype__"),
            Nan::New<Number>(gtype),
            (v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum)
    );

    auto* box = new Boxed();
    box->data = boxed;
    box->size = size;
    box->g_type = gtype;
    box->persistent = new Nan::Persistent<Object>(self);
    box->persistent->SetWeak(box, BoxedDestroyed, Nan::WeakCallbackType::kParameter);
}

static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info) {
    Boxed *box = info.GetParameter();

    if (G_TYPE_IS_BOXED(box->g_type)) {
        g_boxed_free(box->g_type, box->data);
    }
    else if (box->size != 0) {
        // Allocated in ./function.cc @ AllocateArgument
        g_slice_free1(box->size, box->data);
    }
    else if (box->data != NULL) {
        /*
         * TODO(find informations on what to do here. Only seems to be reached for GI.Typelib)
         */
        log("boxed possibly not freed");
    }

    delete box->persistent;
    delete box;
}

Local<FunctionTemplate> GetBoxedTemplate(GIBaseInfo *info, GType gtype) {
    void *data = NULL;

    if (gtype != G_TYPE_NONE) {
        data = g_type_get_qdata(gtype, GNodeJS::template_quark());
    }

    /*
     * Template already created
     */

    if (data) {
        Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data;
        Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate> (*persistent);
        return tpl;
    }

    /*
     * Template not created yet
     */

    auto tpl = New<FunctionTemplate>(BoxedConstructor, New<External>(info));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    if (gtype != G_TYPE_NONE) {
        const char *class_name = g_type_name(gtype);
        tpl->SetClassName (UTF8(class_name));
    } else {
        const char *class_name = g_base_info_get_name (info);
        tpl->SetClassName (UTF8(class_name));
    }

    if (gtype == G_TYPE_NONE)
        return tpl;

    Isolate *isolate = Isolate::GetCurrent();
    auto *persistent = new v8::Persistent<FunctionTemplate>(isolate, tpl);
    persistent->SetWeak(
            g_base_info_ref(info),
            GNodeJS::ClassDestroyed,
            WeakCallbackType::kParameter);

    g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);

    return tpl;
}

Local<Function> MakeBoxedClass(GIBaseInfo *info) {
    GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);

    if (gtype == G_TYPE_NONE) {
        auto moduleCache = GNodeJS::GetModuleCache();
        auto ns   = UTF8 (g_base_info_get_namespace (info));
        auto name = UTF8 (g_base_info_get_name (info));

        if (Nan::HasOwnProperty(moduleCache, ns).FromMaybe(false)) {
            auto module = Nan::Get(moduleCache, ns).ToLocalChecked()->ToObject();

            if (Nan::HasOwnProperty(module, name).FromMaybe(false)) {
                auto constructor = Nan::Get(module, name).ToLocalChecked()->ToObject();
                return Local<Function>::Cast (constructor);
            }
        }
    }

    Local<FunctionTemplate> tpl = GetBoxedTemplate (info, gtype);
    return tpl->GetFunction ();
}

Local<Value> WrapperFromBoxed(GIBaseInfo *info, void *data) {
    if (data == NULL)
        return Nan::Null();

    Local<Function> constructor = MakeBoxedClass (info);

    Local<Value> boxed_external = Nan::New<External> (data);
    Local<Value> args[] = { boxed_external };
    // FIXME(we're not handling failure here)
    MaybeLocal<Object> instance = Nan::NewInstance(constructor, 1, args);
    return instance.ToLocalChecked();
}

void* BoxedFromWrapper(Local<Value> value) {
    Local<Object> object = value->ToObject ();
    g_assert(object->InternalFieldCount() > 0);
    void *boxed = object->GetAlignedPointerFromInternalField(0);
    return boxed;
}

};
<|endoftext|>


<commit_before>

#include <string>
#include <iostream>
#include "DivisorApplication.hpp"

DivisorApplication::DivisorApplication(std::string &divisorString, mpz_class ws) : divisor(mpz_class(divisorString, 10)), work_size(ws)
{

}

DivisorApplication::DivisorApplication(std::string &divisorString) : divisor(mpz_class(divisorString, 10)), work_size(100000)
{

}

DivisorApplication::DivisorApplication(std::string &divisorString, std::string &workSizeString) : divisor(mpz_class(divisorString, 10)), work_size(mpz_class(workSizeString, 10))
{

}

std::list<Work *> *DivisorApplication::work()
{
	std::list<Work *> *retList = new std::list<Work *>();
	mpz_class square_a = sqrt(divisor);

	// std::cout << square_a.get_str() << std::endl;

	mpz_class numberOfWork = ((square_a / work_size) + 1);
	mpz_class firstWorkSize = work_size;
	mpz_class lastWorkSize = square_a % work_size;
	if(lastWorkSize == 0)
		lastWorkSize = work_size;

	for(mpz_class i=0; i<numberOfWork-1; i++)
	{
		mpz_class beginVal = (i * work_size) + 1;
		// std::cout << i << ": " << beginVal.get_str() << ": " << work_size << std::endl;
		DivisorWork *divWork = new DivisorWork(divisor, beginVal, work_size);
		retList->push_back(divWork);
	}

	mpz_class beginVal = ((numberOfWork-1) * work_size) + 1;
	// std::cout << numberOfWork-1 << ": " << beginVal.get_str() << ": " << lastWorkSize << std::endl;
	DivisorWork *divWork = new DivisorWork(divisor, beginVal, lastWorkSize);
	retList->push_back(divWork);

	return retList;
}

int DivisorApplication::results(std::list<Result *> *listOfResults)
{
	std::list<mpz_class> results;

	for (	auto riter = listOfResults->begin();
			riter != listOfResults->end();
			riter++)
	{
		DivisorResult *divResult = dynamic_cast<DivisorResult *>(*riter);
		std::list<mpz_class> divisorList(divResult->getDivisors());
		results.merge(divisorList);
	}

	std::cout<< "Dividend: " <<divisor<<" Work Size: "<<work_size<<" ";
	// std::cout << divisor << " has " << results.size() << " total divisors.\n";
	// for(auto iter = results.begin();
	//     iter != results.end();
	//     iter++) {
	// std::cout << *iter << " is a divisor\n";
	// }

	return 0;
}

std::string *DivisorApplication::workSerializer(Work &objectToSerialize)
{
	// std::cout<<"In DivisorWork serializer" <<std::endl;
	return objectToSerialize.serialize();
}

Work *DivisorApplication::workDeserializer(const std::string &serializedObject)
{
	// std::cout<<"In DivisorWork deserializer" <<std::endl;
	return DivisorWork::deserialize(serializedObject);
}

std::string *DivisorApplication::resultSerializer(Result &objectToSerialize)
{
	// std::cout<<"In DivisorResult deserializer" <<std::endl;
	return objectToSerialize.serialize();
}

Result *DivisorApplication::resultDeserializer(const std::string &serializedObject)
{
	// std::cout<<"In result deserializer" <<std::endl;
	return DivisorResult::deserialize(serializedObject);
}
<commit_msg>Updates for testing<commit_after>

#include <string>
#include <iostream>
#include "DivisorApplication.hpp"

DivisorApplication::DivisorApplication(std::string &divisorString, mpz_class ws) : divisor(mpz_class(divisorString, 10)), work_size(ws)
{

}

DivisorApplication::DivisorApplication(std::string &divisorString) : divisor(mpz_class(divisorString, 10)), work_size(100000)
{

}

DivisorApplication::DivisorApplication(std::string &divisorString, std::string &workSizeString) : divisor(mpz_class(divisorString, 10)), work_size(mpz_class(workSizeString, 10))
{

}

std::list<Work *> *DivisorApplication::work()
{
	std::list<Work *> *retList = new std::list<Work *>();
	mpz_class square_a = sqrt(divisor);

	// std::cout << square_a.get_str() << std::endl;

	mpz_class numberOfWork = ((square_a / work_size) + 1);
	mpz_class firstWorkSize = work_size;
	mpz_class lastWorkSize = square_a % work_size;
	if(lastWorkSize == 0)
		lastWorkSize = work_size;

	for(mpz_class i=0; i<numberOfWork-1; i++)
	{
		mpz_class beginVal = (i * work_size) + 1;
		// std::cout << i << ": " << beginVal.get_str() << ": " << work_size << std::endl;
		DivisorWork *divWork = new DivisorWork(divisor, beginVal, work_size);
		retList->push_back(divWork);
	}

	mpz_class beginVal = ((numberOfWork-1) * work_size) + 1;
	// std::cout << numberOfWork-1 << ": " << beginVal.get_str() << ": " << lastWorkSize << std::endl;
	DivisorWork *divWork = new DivisorWork(divisor, beginVal, lastWorkSize);
	retList->push_back(divWork);

	return retList;
}

int DivisorApplication::results(std::list<Result *> *listOfResults)
{
	std::list<mpz_class> results;

	for (	auto riter = listOfResults->begin();
			riter != listOfResults->end();
			riter++)
	{
		DivisorResult *divResult = dynamic_cast<DivisorResult *>(*riter);
		std::list<mpz_class> divisorList(divResult->getDivisors());
		results.merge(divisorList);
	}

	std::cout<< "Dividend: " <<divisor<<" Work Size: "<<work_size<<" Work Count: "<<mpz_class((sqrt(divisor) / work_size) + 1).get_str()<<" ";
	// std::cout << divisor << " has " << results.size() << " total divisors.\n";
	// for(auto iter = results.begin();
	//     iter != results.end();
	//     iter++) {
	// std::cout << *iter << " is a divisor\n";
	// }

	return 0;
}

std::string *DivisorApplication::workSerializer(Work &objectToSerialize)
{
	// std::cout<<"In DivisorWork serializer" <<std::endl;
	return objectToSerialize.serialize();
}

Work *DivisorApplication::workDeserializer(const std::string &serializedObject)
{
	// std::cout<<"In DivisorWork deserializer" <<std::endl;
	return DivisorWork::deserialize(serializedObject);
}

std::string *DivisorApplication::resultSerializer(Result &objectToSerialize)
{
	// std::cout<<"In DivisorResult deserializer" <<std::endl;
	return objectToSerialize.serialize();
}

Result *DivisorApplication::resultDeserializer(const std::string &serializedObject)
{
	// std::cout<<"In result deserializer" <<std::endl;
	return DivisorResult::deserialize(serializedObject);
}
<|endoftext|>


<commit_before>/*
 * kPPPlogview: a accounting log system for kPPP
 *
 *            Copyright (C) 1998 Mario Weilguni <mweilguni@kde.org>
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "monthly.h"

#include <klocale.h>
#include <klistview.h>

static void formatBytes(int bytes, QString &result) {
  if(bytes < 1024)
    result.setNum(bytes);
  else if(bytes < 1024*1024)
    result.sprintf(i18n("%0.1f KB"), (float)bytes / 1024.0);
  else
    result.sprintf(i18n("%0.1f MB"), (float)bytes / 1024.0 / 1024.0);
}

static void formatDuration(int seconds, QString &result) {
  if(seconds < 60)
    result.sprintf(i18n("%d s"), seconds);
  else if(seconds < 3600)
    result.sprintf(i18n("%dm %ds"), seconds/60, seconds%60);
  else
    result.sprintf(i18n("%dh %dm %ds"), seconds/3600, (seconds % 3600)/60, seconds%60);
}

MonthlyWidget::MonthlyWidget(QWidget *parent) :
  QWidget(parent)
{
  tl = 0;

  lv = new KListView(this);
  lv->addColumn(i18n("Connection"));
  lv->addColumn(i18n("Day"));
  lv->addColumn(i18n("From"));
  lv->addColumn(i18n("Until"));
  lv->addColumn(i18n("Seconds"));
  lv->addColumn(i18n("Costs"));
  lv->addColumn(i18n("Bytes in"));
  lv->addColumn(i18n("Bytes out"));
  lv->setColumnAlignment(1, AlignRight);
  lv->setColumnAlignment(2, AlignRight);
  lv->setColumnAlignment(3, AlignRight);
  lv->setColumnAlignment(4, AlignRight);
  lv->setColumnAlignment(5, AlignRight);
  lv->setColumnAlignment(6, AlignRight);
  lv->setColumnAlignment(7, AlignRight);
  lv->setAllColumnsShowFocus(true);
  lv->setShowSortIndicator(true);
  lv->setItemMargin(2);
  lv->setSorting(1);
  lv->setMinimumWidth(320);
  lv->setMinimumHeight(200);

  title = new QLabel("X", this);
  QFont f = title->font();
  f.setPointSize(f.pointSize() + 2);
  f.setBold(TRUE);
  title->setFont(f);
  title->setFixedHeight(title->sizeHint().height()*2);

  bbox = new KButtonBox(this, KButtonBox::VERTICAL);
  prev = bbox->addButton(i18n("Prev month"));
  next = bbox->addButton(i18n("Next month"));
  bbox->addStretch(1);
  today = bbox->addButton(i18n("Current month"));

  connect(prev, SIGNAL(released()),
	  this, SLOT(prevMonth()));
  connect(next, SIGNAL(released()),
	  this, SLOT(nextMonth()));
  connect(today, SIGNAL(released()),
	  this, SLOT(currentMonth()));

  bbox->addStretch(8);
  bbox->layout();

  currentMonth();
  layoutWidget();
}

void MonthlyWidget::layoutWidget() {
  if(tl)
    delete tl;
  tl = new QVBoxLayout(this, 10, 10);
  tl->addWidget(title);

  QHBoxLayout *l1 = new QHBoxLayout;
  tl->addLayout(l1, 1);
  l1->addWidget(lv, 1);
  l1->addWidget(bbox);

  tl->activate();
}

int bestlen(QWidget *w, const char *s) {
  return w->fontMetrics().boundingRect(s).width() + 8;
}

void MonthlyWidget::plotMonth() {
  QString months[] = {i18n("January"),
		      i18n("February"),
		      i18n("March"),
		      i18n("April"),
		      i18n("May"),
		      i18n("June"),
		      i18n("July"),
		      i18n("August"),
		      i18n("September"),
		      i18n("October"),
		      i18n("November"),
		      i18n("December")};

  // search the entries for this month
  QString s;
  int lastday = -1;
  QString lastConn = "-";

  // for collecting monthly statistics
  int count = 0;
  double costs = 0;
  int bin = 0, bout = 0;
  int duration = 0;
  QListViewItem* last = 0;

  for(int i = 0; i < (int)logList.count(); i++) {
    LogInfo *li = logList.at(i);

    if(li->from().date().month() == _month && li->from().date().year() == _year) {

      count++;
      costs += li->sessionCosts();
      if(bin >= 0) {
        if(li->bytesIn() < 0)
          bin = -1;
        else
          bin += li->bytesIn();
      }

      if(bout >= 0) {
        if(li->bytesOut() < 0)
          bout = -1;
        else
          bout += li->bytesOut();
      }

      duration += li->from().secsTo(li->until());

      QString bin, bout, b;
      if(li->bytesIn() >= 0)
        formatBytes(li->bytesIn(), bin);
      else
        bin = i18n("n/a");

      if(li->bytesOut() >= 0)
        formatBytes(li->bytesOut(), bout);
      else
        bout = i18n("n/a");

      if(li->bytes() > 0)
        formatBytes(li->bytes(), b);
      else
        b = i18n("n/a");

      QString day;
      QString con;
      if(li->from().date().day() != lastday) {
        day.sprintf("%2d", li->from().date().day());
        lastday = li->from().date().day();
      }

      if(li->connectionName() != lastConn) {
        con = li->connectionName();
        lastConn = li->connectionName();
      } else
        con = " ";

      QString s_duration;
      formatDuration(li->from().secsTo(li->until()),
                     s_duration);

      QString s_lifrom, s_liuntil, s_costs;
      s_lifrom.sprintf("%02d:%02d",
                       li->from().time().hour(), li->from().time().minute());
      s_liuntil.sprintf("%02d:%02d",
                        li->until().time().hour(), li->until().time().minute());
      s_costs.sprintf("%6.2f",
                      li->sessionCosts());

      last = new QListViewItem(lv, con, day, s_lifrom, s_liuntil, s_duration,
                               s_costs, bin, bout);
    }
  }

  if(count) {
    QString s;
    QString _bin, _bout, _b;

    if(bin < 0)
      _bin = i18n("n/a");
    else
      formatBytes(bin, _bin);

    if(bout < 0)
      _bout = i18n("n/a");
    else
      formatBytes(bout, _bout);

    if(bin < 0 || bout < 0)
      _b = i18n("n/a");
    else
      formatBytes(bout + bin, _b);

    QString s_duration;
    formatDuration(duration,
                   s_duration);

    QString s_costs;
    s.sprintf("%6.2f", costs);

#if 0
    last = new QListViewItem(lv, last,
                             i18n("%1 connections").arg(count),
                             " ", " ", " ",
                             s_duration, s_costs, _bin, _bout);
#endif
  }

  QString t;
  if(lv->childCount() > 0)
    t.sprintf(i18n("Connection log for %s %d"),
	      months[_month-1].data(),
	      _year);
  else
    t.sprintf(i18n("No connection log for %s %d available"),
	      months[_month-1].data(),
	      _year);

  title->setText(t.data());
}

void MonthlyWidget::nextMonth() {
  _month++;
  if(_month == 13) {
    _month = 1;
    _year++;
  }
  plotMonth();
}

void MonthlyWidget::prevMonth() {
  _month--;
  if(_month == 0) {
    _month = 12;
    _year--;
  }
  plotMonth();
}

void MonthlyWidget::currentMonth() {
  _month = QDate::currentDate().month();
  _year  = QDate::currentDate().year();
  plotMonth();
}

#include "monthly.moc"
<commit_msg>Cleaned up some of the code (I think).<commit_after>/*
 * kPPPlogview: a accounting log system for kPPP
 *
 *            Copyright (C) 1998 Mario Weilguni <mweilguni@kde.org>
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "monthly.h"

#include <klocale.h>
#include <kglobal.h>
#include <klistview.h>

static void formatBytes(int bytes, QString &result) {
  if(bytes < 1024)
    result.setNum(bytes);
  else if(bytes < 1024*1024)
    result = i18n("%1 KB").arg(KGlobal::locale()->formatNumber((float)bytes / 1024.0, 1));
  else
    result = i18n("%1 MB").arg(KGlobal::locale()->formatNumber((float)bytes / 1024.0 / 1024.0, 1));
}

static void formatDuration(int seconds, QString &result) {
  if(seconds < 60)
    result = i18n("%1 s").arg(seconds);
  else if(seconds < 3600)
    result = i18n("%1m %2s").arg(seconds/60).arg(seconds%60);
  else
    result = i18n("%1h %2m %3s")
        .arg(seconds/3600)
        .arg((seconds % 3600)/60)
        .arg(seconds%60);
}

MonthlyWidget::MonthlyWidget(QWidget *parent) :
  QWidget(parent)
{
  tl = 0;

  lv = new KListView(this);
  lv->addColumn(i18n("Connection"));
  lv->addColumn(i18n("Day"));
  lv->addColumn(i18n("From"));
  lv->addColumn(i18n("Until"));
  lv->addColumn(i18n("Seconds"));
  lv->addColumn(i18n("Costs"));
  lv->addColumn(i18n("Bytes in"));
  lv->addColumn(i18n("Bytes out"));
  lv->setColumnAlignment(1, AlignRight);
  lv->setColumnAlignment(2, AlignRight);
  lv->setColumnAlignment(3, AlignRight);
  lv->setColumnAlignment(4, AlignRight);
  lv->setColumnAlignment(5, AlignRight);
  lv->setColumnAlignment(6, AlignRight);
  lv->setColumnAlignment(7, AlignRight);
  lv->setAllColumnsShowFocus(true);
  lv->setShowSortIndicator(true);
  lv->setItemMargin(2);
  lv->setSorting(1);
  lv->setMinimumWidth(320);
  lv->setMinimumHeight(200);

  title = new QLabel("X", this);
  QFont f = title->font();
  f.setPointSize(f.pointSize() + 2);
  f.setBold(TRUE);
  title->setFont(f);
  title->setFixedHeight(title->sizeHint().height()*2);

  bbox = new KButtonBox(this, KButtonBox::VERTICAL);
  prev = bbox->addButton(i18n("Prev month"));
  next = bbox->addButton(i18n("Next month"));
  bbox->addStretch(1);
  today = bbox->addButton(i18n("Current month"));

  connect(prev, SIGNAL(released()),
	  this, SLOT(prevMonth()));
  connect(next, SIGNAL(released()),
	  this, SLOT(nextMonth()));
  connect(today, SIGNAL(released()),
	  this, SLOT(currentMonth()));

  bbox->addStretch(8);
  bbox->layout();

  currentMonth();
  layoutWidget();
}

void MonthlyWidget::layoutWidget() {
  if(tl)
    delete tl;
  tl = new QVBoxLayout(this, 10, 10);
  tl->addWidget(title);

  QHBoxLayout *l1 = new QHBoxLayout;
  tl->addLayout(l1, 1);
  l1->addWidget(lv, 1);
  l1->addWidget(bbox);

  tl->activate();
}

int bestlen(QWidget *w, const char *s) {
  return w->fontMetrics().boundingRect(s).width() + 8;
}

void MonthlyWidget::plotMonth() {
  QString months[] = {i18n("January"),
		      i18n("February"),
		      i18n("March"),
		      i18n("April"),
		      i18n("May"),
		      i18n("June"),
		      i18n("July"),
		      i18n("August"),
		      i18n("September"),
		      i18n("October"),
		      i18n("November"),
		      i18n("December")};

  // search the entries for this month
  QString s;
  int lastday = -1;
  QString lastConn = "-";

  // for collecting monthly statistics
  int count = 0;
  double costs = 0;
  int bin = 0, bout = 0;
  int duration = 0;
  QListViewItem* last = 0;

  for(int i = 0; i < (int)logList.count(); i++) {
    LogInfo *li = logList.at(i);

    if(li->from().date().month() == _month && li->from().date().year() == _year) {

      count++;
      costs += li->sessionCosts();
      if(bin >= 0) {
        if(li->bytesIn() < 0)
          bin = -1;
        else
          bin += li->bytesIn();
      }

      if(bout >= 0) {
        if(li->bytesOut() < 0)
          bout = -1;
        else
          bout += li->bytesOut();
      }

      duration += li->from().secsTo(li->until());

      QString bin, bout, b;
      if(li->bytesIn() >= 0)
        formatBytes(li->bytesIn(), bin);
      else
        bin = i18n("n/a");

      if(li->bytesOut() >= 0)
        formatBytes(li->bytesOut(), bout);
      else
        bout = i18n("n/a");

      if(li->bytes() > 0)
        formatBytes(li->bytes(), b);
      else
        b = i18n("n/a");

      QString day;
      QString con;
      if(li->from().date().day() != lastday) {
        day.sprintf("%2d", li->from().date().day());
        lastday = li->from().date().day();
      }

      if(li->connectionName() != lastConn) {
        con = li->connectionName();
        lastConn = li->connectionName();
      } else
        con = " ";

      QString s_duration;
      formatDuration(li->from().secsTo(li->until()),
                     s_duration);

      QString s_lifrom, s_liuntil, s_costs;
      s_lifrom = KGlobal::locale()->formatTime(li->from().time(), false);
      s_liuntil = KGlobal::locale()->formatTime(li->until().time(), false);
      s_costs.sprintf("%6.2f",
                      li->sessionCosts());

      last = new QListViewItem(lv, con, day, s_lifrom, s_liuntil, s_duration,
                               s_costs, bin, bout);
    }
  }

  if(count) {
    QString s;
    QString _bin, _bout, _b;

    if(bin < 0)
      _bin = i18n("n/a");
    else
      formatBytes(bin, _bin);

    if(bout < 0)
      _bout = i18n("n/a");
    else
      formatBytes(bout, _bout);

    if(bin < 0 || bout < 0)
      _b = i18n("n/a");
    else
      formatBytes(bout + bin, _b);

    QString s_duration;
    formatDuration(duration,
                   s_duration);

    QString s_costs;
    s.sprintf("%6.2f", costs);

#if 0
    last = new QListViewItem(lv, last,
                             i18n("%1 connections").arg(count),
                             " ", " ", " ",
                             s_duration, s_costs, _bin, _bout);
#endif
  }

  QString t;
  if(lv->childCount() > 0)
    t = i18n("Connection log for %1 %2")
	      .arg(months[_month-1])
	      .arg(_year);
  else
    t = i18n("No connection log for %1 %2 available")
	      .arg(months[_month-1])
	      .arg(_year);

  title->setText(t);
}

void MonthlyWidget::nextMonth() {
  _month++;
  if(_month == 13) {
    _month = 1;
    _year++;
  }
  plotMonth();
}

void MonthlyWidget::prevMonth() {
  _month--;
  if(_month == 0) {
    _month = 12;
    _year--;
  }
  plotMonth();
}

void MonthlyWidget::currentMonth() {
  _month = QDate::currentDate().month();
  _year  = QDate::currentDate().year();
  plotMonth();
}

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


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

#include <string.h>
#include "collectchanges.hxx"

#include "nodechangeinfo.hxx"

#include <osl/diagnose.h>

namespace configmgr
{
    namespace configuration
    {

//-----------------------------------------------------------------------------
// conversion helper function
//-----------------------------------------------------------------------------
bool convertNodeChange(NodeChangeData& aData_, ValueChange const& aChange_)
{
    switch(aChange_.getMode())
    {
    case ValueChange::wasDefault:
    case ValueChange::changeValue:
        aData_.type = NodeChangeData::eSetValue;
        break;

    case ValueChange::setToDefault:
        aData_.type = NodeChangeData::eSetDefault;
        break;

    case ValueChange::changeDefault:
        aData_.type = NodeChangeData::eNoChange; // ??
        break;

    default:
        OSL_ENSURE(false,"Unknown change type found");
        return false;
    }

    aData_.unoData.newValue = aChange_.getNewValue();
    aData_.unoData.oldValue = aChange_.getOldValue();
    return true;
}
//-----------------------------------------------------------------------------

bool convertNodeChange(NodeChangeData& aData_, AddNode const& aChange_)
{
    aData_.type = aChange_.isReplacing()
                    ? NodeChangeData::eReplaceElement
                    : NodeChangeData::eInsertElement;

    return true;
}
//-----------------------------------------------------------------------------

bool convertNodeChange(NodeChangeData& aData_, RemoveNode const& /*aChange_*/)
{
    aData_.type = NodeChangeData::eRemoveElement;

    return true;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// CollectChanges visitor class
//-----------------------------------------------------------------------------

CollectChanges::CollectChanges( NodeChangesInformation& rTargetList_,
                data::Accessor const& _aDataAccessor,
                TreeImpl& rStartTree_, NodeOffset nStartNode_,
                TemplateHolder aElementTemplate_,
                TreeDepth nMaxDepth)
: m_rTargetList(rTargetList_)
, m_aAccessor()
, m_aContextTypeName()
, m_aDataAccessor(_aDataAccessor)
, m_pBaseTree(&rStartTree_)
, m_nBaseNode(nStartNode_)
, m_nDepthLeft( nMaxDepth )
{
    if (aElementTemplate_.is())
        m_aContextTypeName = aElementTemplate_->getName();
}

//-----------------------------------------------------------------------------
CollectChanges::CollectChanges( CollectChanges const& rBase, Path::Component const& rChildName, Name const& aSubTypeName_)
: m_rTargetList(rBase.m_rTargetList)
, m_aAccessor(rBase.m_aAccessor.compose(rChildName))
, m_aContextTypeName(aSubTypeName_)
, m_aDataAccessor(rBase.m_aDataAccessor)
, m_pBaseTree(rBase.m_pBaseTree)
, m_nBaseNode(rBase.m_nBaseNode)
, m_nDepthLeft(childDepth(rBase.m_nDepthLeft))
{
    OSL_ASSERT(rBase.m_nDepthLeft > 0);
}

//-----------------------------------------------------------------------------
inline
Path::Component CollectChanges::implGetNodeName(Change const& aChange_) const
{
    Name aSimpleNodeName = makeName( aChange_.getNodeName(), Name::NoValidate() );

    if (m_aContextTypeName.isEmpty())
    {
        OSL_ENSURE(isSimpleName(aSimpleNodeName),"Unexpected: Found non-simple name without a type");
        return Path::wrapSafeName(aSimpleNodeName);
    }
    else
        return Path::makeCompositeName(aSimpleNodeName, m_aContextTypeName);
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(ValueChange const& aChange_)
{
    NodeChangeInformation aInfo(m_aDataAccessor);

    if ( convertNodeChange( aInfo.change, aChange_ ) &&
         implSetLocation( aInfo.location, aChange_, false ) )
    {
        implAdd( aInfo );
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(AddNode const& aChange_)
{
    NodeChangeInformation aInfo(m_aDataAccessor);

    if ( convertNodeChange( aInfo.change, aChange_ ) &&
         implSetLocation( aInfo.location, aChange_, true ) )
    {
        implAdd( aInfo );
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(RemoveNode const& aChange_)
{
    NodeChangeInformation aInfo(m_aDataAccessor);

    if ( convertNodeChange( aInfo.change, aChange_ ) &&
         implSetLocation( aInfo.location, aChange_, true ) )
    {
        implAdd( aInfo );
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(SubtreeChange const& aChanges_)
{
    if (m_nDepthLeft > 0)
    {
        Name aSubTypeName = makeName( aChanges_.getElementTemplateName(), Name::NoValidate() );

        CollectChanges aSubcollector( *this, implGetNodeName(aChanges_), aSubTypeName );

        aSubcollector.applyToChildren(aChanges_);
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::implAdd(NodeChangeInformation const& aChangeInfo_)
{
    m_rTargetList.push_back(aChangeInfo_);
}

//-----------------------------------------------------------------------------
bool CollectChanges::implSetLocation(NodeChangeLocation& rLocation_, Change const& aOriginal_, bool bSet_) const
{
    NodeID aBaseID(m_pBaseTree,m_nBaseNode);
    if (aBaseID.isEmpty())
        return false;

    rLocation_.setBase( aBaseID );

    if (bSet_ && m_aAccessor.isEmpty()) // It is  a set change affecting the base ...
        rLocation_.setAffected( aBaseID );

    Path::Component aChangeName = implGetNodeName( aOriginal_ );
    rLocation_.setAccessor( m_aAccessor.compose( aChangeName ) );

    return true;
}

// ChangeTreeAction implementations
//-----------------------------------------------------------------------------
void CollectChanges::handle(ValueChange const& aValueNode_)
{
    collectFrom(aValueNode_);
}

//-----------------------------------------------------------------------------
void CollectChanges::handle(AddNode const& aAddNode_)
{
    collectFrom(aAddNode_);
}

//-----------------------------------------------------------------------------
void CollectChanges::handle(RemoveNode const& aRemoveNode_)
{
    collectFrom(aRemoveNode_);
}

//-----------------------------------------------------------------------------
void CollectChanges::handle(SubtreeChange const& aSubtree_)
{
    collectFrom( aSubtree_ );
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

    }
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.8.18); FILE MERGED 2006/09/01 17:20:47 kaib 1.8.18.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: collectchanges.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 15:27:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"

#include <string.h>
#include "collectchanges.hxx"

#include "nodechangeinfo.hxx"

#include <osl/diagnose.h>

namespace configmgr
{
    namespace configuration
    {

//-----------------------------------------------------------------------------
// conversion helper function
//-----------------------------------------------------------------------------
bool convertNodeChange(NodeChangeData& aData_, ValueChange const& aChange_)
{
    switch(aChange_.getMode())
    {
    case ValueChange::wasDefault:
    case ValueChange::changeValue:
        aData_.type = NodeChangeData::eSetValue;
        break;

    case ValueChange::setToDefault:
        aData_.type = NodeChangeData::eSetDefault;
        break;

    case ValueChange::changeDefault:
        aData_.type = NodeChangeData::eNoChange; // ??
        break;

    default:
        OSL_ENSURE(false,"Unknown change type found");
        return false;
    }

    aData_.unoData.newValue = aChange_.getNewValue();
    aData_.unoData.oldValue = aChange_.getOldValue();
    return true;
}
//-----------------------------------------------------------------------------

bool convertNodeChange(NodeChangeData& aData_, AddNode const& aChange_)
{
    aData_.type = aChange_.isReplacing()
                    ? NodeChangeData::eReplaceElement
                    : NodeChangeData::eInsertElement;

    return true;
}
//-----------------------------------------------------------------------------

bool convertNodeChange(NodeChangeData& aData_, RemoveNode const& /*aChange_*/)
{
    aData_.type = NodeChangeData::eRemoveElement;

    return true;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// CollectChanges visitor class
//-----------------------------------------------------------------------------

CollectChanges::CollectChanges( NodeChangesInformation& rTargetList_,
                data::Accessor const& _aDataAccessor,
                TreeImpl& rStartTree_, NodeOffset nStartNode_,
                TemplateHolder aElementTemplate_,
                TreeDepth nMaxDepth)
: m_rTargetList(rTargetList_)
, m_aAccessor()
, m_aContextTypeName()
, m_aDataAccessor(_aDataAccessor)
, m_pBaseTree(&rStartTree_)
, m_nBaseNode(nStartNode_)
, m_nDepthLeft( nMaxDepth )
{
    if (aElementTemplate_.is())
        m_aContextTypeName = aElementTemplate_->getName();
}

//-----------------------------------------------------------------------------
CollectChanges::CollectChanges( CollectChanges const& rBase, Path::Component const& rChildName, Name const& aSubTypeName_)
: m_rTargetList(rBase.m_rTargetList)
, m_aAccessor(rBase.m_aAccessor.compose(rChildName))
, m_aContextTypeName(aSubTypeName_)
, m_aDataAccessor(rBase.m_aDataAccessor)
, m_pBaseTree(rBase.m_pBaseTree)
, m_nBaseNode(rBase.m_nBaseNode)
, m_nDepthLeft(childDepth(rBase.m_nDepthLeft))
{
    OSL_ASSERT(rBase.m_nDepthLeft > 0);
}

//-----------------------------------------------------------------------------
inline
Path::Component CollectChanges::implGetNodeName(Change const& aChange_) const
{
    Name aSimpleNodeName = makeName( aChange_.getNodeName(), Name::NoValidate() );

    if (m_aContextTypeName.isEmpty())
    {
        OSL_ENSURE(isSimpleName(aSimpleNodeName),"Unexpected: Found non-simple name without a type");
        return Path::wrapSafeName(aSimpleNodeName);
    }
    else
        return Path::makeCompositeName(aSimpleNodeName, m_aContextTypeName);
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(ValueChange const& aChange_)
{
    NodeChangeInformation aInfo(m_aDataAccessor);

    if ( convertNodeChange( aInfo.change, aChange_ ) &&
         implSetLocation( aInfo.location, aChange_, false ) )
    {
        implAdd( aInfo );
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(AddNode const& aChange_)
{
    NodeChangeInformation aInfo(m_aDataAccessor);

    if ( convertNodeChange( aInfo.change, aChange_ ) &&
         implSetLocation( aInfo.location, aChange_, true ) )
    {
        implAdd( aInfo );
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(RemoveNode const& aChange_)
{
    NodeChangeInformation aInfo(m_aDataAccessor);

    if ( convertNodeChange( aInfo.change, aChange_ ) &&
         implSetLocation( aInfo.location, aChange_, true ) )
    {
        implAdd( aInfo );
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::collectFrom(SubtreeChange const& aChanges_)
{
    if (m_nDepthLeft > 0)
    {
        Name aSubTypeName = makeName( aChanges_.getElementTemplateName(), Name::NoValidate() );

        CollectChanges aSubcollector( *this, implGetNodeName(aChanges_), aSubTypeName );

        aSubcollector.applyToChildren(aChanges_);
    }
}

//-----------------------------------------------------------------------------
void CollectChanges::implAdd(NodeChangeInformation const& aChangeInfo_)
{
    m_rTargetList.push_back(aChangeInfo_);
}

//-----------------------------------------------------------------------------
bool CollectChanges::implSetLocation(NodeChangeLocation& rLocation_, Change const& aOriginal_, bool bSet_) const
{
    NodeID aBaseID(m_pBaseTree,m_nBaseNode);
    if (aBaseID.isEmpty())
        return false;

    rLocation_.setBase( aBaseID );

    if (bSet_ && m_aAccessor.isEmpty()) // It is  a set change affecting the base ...
        rLocation_.setAffected( aBaseID );

    Path::Component aChangeName = implGetNodeName( aOriginal_ );
    rLocation_.setAccessor( m_aAccessor.compose( aChangeName ) );

    return true;
}

// ChangeTreeAction implementations
//-----------------------------------------------------------------------------
void CollectChanges::handle(ValueChange const& aValueNode_)
{
    collectFrom(aValueNode_);
}

//-----------------------------------------------------------------------------
void CollectChanges::handle(AddNode const& aAddNode_)
{
    collectFrom(aAddNode_);
}

//-----------------------------------------------------------------------------
void CollectChanges::handle(RemoveNode const& aRemoveNode_)
{
    collectFrom(aRemoveNode_);
}

//-----------------------------------------------------------------------------
void CollectChanges::handle(SubtreeChange const& aSubtree_)
{
    collectFrom( aSubtree_ );
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

    }
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <stdio.h>
#include <cppuhelper/factory.hxx>
#include "ZPoolCollection.hxx"

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

//= registration

extern "C"
{

SAL_DLLPUBLIC_EXPORT void* SAL_CALL dbpool2_component_getFactory(const sal_Char* _pImplName, ::com::sun::star::lang::XMultiServiceFactory* _pServiceManager, void* /*_pRegistryKey*/)
{
    void* pRet = NULL;

    if (OPoolCollection::getImplementationName_Static().equalsAscii(_pImplName))
    {
        Reference< XSingleServiceFactory > xFactory(
            ::cppu::createOneInstanceFactory(
                _pServiceManager,
                OPoolCollection::getImplementationName_Static(),
                OPoolCollection::CreateInstance,
                OPoolCollection::getSupportedServiceNames_Static()
            )
        );
        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    return pRet;
}

}   // extern "C"

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix function signature<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <stdio.h>
#include <cppuhelper/factory.hxx>
#include "ZPoolCollection.hxx"

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

//= registration

extern "C"
{

SAL_DLLPUBLIC_EXPORT void* SAL_CALL dbpool2_component_getFactory(const sal_Char* _pImplName, void * _pServiceManager, void* /*_pRegistryKey*/)
{
    void* pRet = NULL;

    if (OPoolCollection::getImplementationName_Static().equalsAscii(_pImplName))
    {
        Reference< XSingleServiceFactory > xFactory(
            ::cppu::createOneInstanceFactory(
                static_cast<css::lang::XMultiServiceFactory *>(
                    _pServiceManager),
                OPoolCollection::getImplementationName_Static(),
                OPoolCollection::CreateInstance,
                OPoolCollection::getSupportedServiceNames_Static()
            )
        );
        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    return pRet;
}

}   // extern "C"

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/plugin_data_remover_impl.h"

#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/synchronization/waitable_event.h"
#include "base/version.h"
#include "content/browser/plugin_process_host.h"
#include "content/browser/plugin_service_impl.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/plugin_messages.h"
#include "content/public/browser/browser_thread.h"
#include "webkit/plugins/npapi/plugin_group.h"

using content::BrowserThread;
using content::ChildProcessHostImpl;

namespace {

const char kFlashMimeType[] = "application/x-shockwave-flash";
// The minimum Flash Player version that implements NPP_ClearSiteData.
const char kMinFlashVersion[] = "10.3";
const int64 kRemovalTimeoutMs = 10000;
const uint64 kClearAllData = 0;

}  // namespace

namespace content {

// static
PluginDataRemover* PluginDataRemover::Create(
    const content::ResourceContext& resource_context) {
  return new PluginDataRemoverImpl(resource_context);
}

// static
bool PluginDataRemover::IsSupported(webkit::WebPluginInfo* plugin) {
  bool allow_wildcard = false;
  std::vector<webkit::WebPluginInfo> plugins;
  PluginService::GetInstance()->GetPluginInfoArray(
      GURL(), kFlashMimeType, allow_wildcard, &plugins, NULL);
  std::vector<webkit::WebPluginInfo>::iterator plugin_it = plugins.begin();
  if (plugin_it == plugins.end())
    return false;
  scoped_ptr<Version> version(
      webkit::npapi::PluginGroup::CreateVersionFromString(plugin_it->version));
  scoped_ptr<Version> min_version(
      Version::GetVersionFromString(kMinFlashVersion));
  bool rv = version.get() && min_version->CompareTo(*version) == -1;
  if (rv)
    *plugin = *plugin_it;
  return rv;
}

}

class PluginDataRemoverImpl::Context
    : public PluginProcessHost::Client,
      public IPC::Channel::Listener,
      public base::RefCountedThreadSafe<Context,
                                        BrowserThread::DeleteOnIOThread> {
 public:
  Context(base::Time begin_time,
          const content::ResourceContext& resource_context)
      : event_(new base::WaitableEvent(true, false)),
        begin_time_(begin_time),
        is_removing_(false),
        resource_context_(resource_context),
        channel_(NULL) {
  }

  virtual ~Context() {
  }

  void Init(const std::string& mime_type) {
    BrowserThread::PostTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&Context::InitOnIOThread, this, mime_type));
    BrowserThread::PostDelayedTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&Context::OnTimeout, this),
        kRemovalTimeoutMs);
  }

  // Initialize on the IO thread.
  void InitOnIOThread(const std::string& mime_type) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    remove_start_time_ = base::Time::Now();
    is_removing_ = true;
    // Balanced in OnChannelOpened or OnError. Exactly one them will eventually
    // be called, so we need to keep this object around until then.
    AddRef();
    PluginServiceImpl::GetInstance()->OpenChannelToNpapiPlugin(
        0, 0, GURL(), GURL(), mime_type, this);
  }

  // Called when a timeout happens in order not to block the client
  // indefinitely.
  void OnTimeout() {
    LOG_IF(ERROR, is_removing_) << "Timed out";
    SignalDone();
  }

  // PluginProcessHost::Client methods.
  virtual int ID() OVERRIDE {
    // Generate a unique identifier for this PluginProcessHostClient.
    return ChildProcessHostImpl::GenerateChildProcessUniqueId();
  }

  virtual bool OffTheRecord() OVERRIDE {
    return false;
  }

  virtual const content::ResourceContext& GetResourceContext() OVERRIDE {
    return resource_context_;
  }

  virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
  }

  virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
  }

  virtual void OnSentPluginChannelRequest() OVERRIDE {
  }

  virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE {
    ConnectToChannel(handle);
    // Balancing the AddRef call.
    Release();
  }

  virtual void OnError() OVERRIDE {
    LOG(DFATAL) << "Couldn't open plugin channel";
    SignalDone();
    // Balancing the AddRef call.
    Release();
  }

  // IPC::Channel::Listener methods.
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
    IPC_BEGIN_MESSAGE_MAP(Context, message)
      IPC_MESSAGE_HANDLER(PluginHostMsg_ClearSiteDataResult,
                          OnClearSiteDataResult)
      IPC_MESSAGE_UNHANDLED_ERROR()
    IPC_END_MESSAGE_MAP()

    return true;
  }

  virtual void OnChannelError() OVERRIDE {
    if (is_removing_) {
      NOTREACHED() << "Channel error";
      SignalDone();
    }
  }

  base::WaitableEvent* event() { return event_.get(); }

 private:
  // Connects the client side of a newly opened plug-in channel.
  void ConnectToChannel(const IPC::ChannelHandle& handle) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

    // If we timed out, don't bother connecting.
    if (!is_removing_)
      return;

    DCHECK(!channel_.get());
    channel_.reset(new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this));
    if (!channel_->Connect()) {
      NOTREACHED() << "Couldn't connect to plugin";
      SignalDone();
      return;
    }

    if (!channel_->Send(new PluginMsg_ClearSiteData(std::string(),
                                                    kClearAllData,
                                                    begin_time_))) {
      NOTREACHED() << "Couldn't send ClearSiteData message";
      SignalDone();
      return;
    }
  }

  // Handles the PluginHostMsg_ClearSiteDataResult message.
  void OnClearSiteDataResult(bool success) {
    LOG_IF(ERROR, !success) << "ClearSiteData returned error";
    UMA_HISTOGRAM_TIMES("ClearPluginData.time",
                        base::Time::Now() - remove_start_time_);
    SignalDone();
  }

  // Signals that we are finished with removing data (successful or not). This
  // method is safe to call multiple times.
  void SignalDone() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    if (!is_removing_)
      return;
    is_removing_ = false;
    event_->Signal();
  }

  scoped_ptr<base::WaitableEvent> event_;
  // The point in time when we start removing data.
  base::Time remove_start_time_;
  // The point in time from which on we remove data.
  base::Time begin_time_;
  bool is_removing_;

  // The resource context for the profile.
  const content::ResourceContext& resource_context_;

  // The channel is NULL until we have opened a connection to the plug-in
  // process.
  scoped_ptr<IPC::Channel> channel_;
};

PluginDataRemoverImpl::PluginDataRemoverImpl(
    const content::ResourceContext& resource_context)
    : mime_type_(kFlashMimeType),
      resource_context_(resource_context) {
}

PluginDataRemoverImpl::~PluginDataRemoverImpl() {
}

base::WaitableEvent* PluginDataRemoverImpl::StartRemoving(
    base::Time begin_time) {
  DCHECK(!context_.get());
  context_ = new Context(begin_time, resource_context_);
  context_->Init(mime_type_);
  return context_->event();
}
<commit_msg>Replace DFATAL with ERROR in PluginDataRemover::OnError.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/plugin_data_remover_impl.h"

#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/synchronization/waitable_event.h"
#include "base/version.h"
#include "content/browser/plugin_process_host.h"
#include "content/browser/plugin_service_impl.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/plugin_messages.h"
#include "content/public/browser/browser_thread.h"
#include "webkit/plugins/npapi/plugin_group.h"

using content::BrowserThread;
using content::ChildProcessHostImpl;

namespace {

const char kFlashMimeType[] = "application/x-shockwave-flash";
// The minimum Flash Player version that implements NPP_ClearSiteData.
const char kMinFlashVersion[] = "10.3";
const int64 kRemovalTimeoutMs = 10000;
const uint64 kClearAllData = 0;

}  // namespace

namespace content {

// static
PluginDataRemover* PluginDataRemover::Create(
    const content::ResourceContext& resource_context) {
  return new PluginDataRemoverImpl(resource_context);
}

// static
bool PluginDataRemover::IsSupported(webkit::WebPluginInfo* plugin) {
  bool allow_wildcard = false;
  std::vector<webkit::WebPluginInfo> plugins;
  PluginService::GetInstance()->GetPluginInfoArray(
      GURL(), kFlashMimeType, allow_wildcard, &plugins, NULL);
  std::vector<webkit::WebPluginInfo>::iterator plugin_it = plugins.begin();
  if (plugin_it == plugins.end())
    return false;
  scoped_ptr<Version> version(
      webkit::npapi::PluginGroup::CreateVersionFromString(plugin_it->version));
  scoped_ptr<Version> min_version(
      Version::GetVersionFromString(kMinFlashVersion));
  bool rv = version.get() && min_version->CompareTo(*version) == -1;
  if (rv)
    *plugin = *plugin_it;
  return rv;
}

}

class PluginDataRemoverImpl::Context
    : public PluginProcessHost::Client,
      public IPC::Channel::Listener,
      public base::RefCountedThreadSafe<Context,
                                        BrowserThread::DeleteOnIOThread> {
 public:
  Context(base::Time begin_time,
          const content::ResourceContext& resource_context)
      : event_(new base::WaitableEvent(true, false)),
        begin_time_(begin_time),
        is_removing_(false),
        resource_context_(resource_context),
        channel_(NULL) {
  }

  virtual ~Context() {
  }

  void Init(const std::string& mime_type) {
    BrowserThread::PostTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&Context::InitOnIOThread, this, mime_type));
    BrowserThread::PostDelayedTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&Context::OnTimeout, this),
        kRemovalTimeoutMs);
  }

  // Initialize on the IO thread.
  void InitOnIOThread(const std::string& mime_type) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    remove_start_time_ = base::Time::Now();
    is_removing_ = true;
    // Balanced in OnChannelOpened or OnError. Exactly one them will eventually
    // be called, so we need to keep this object around until then.
    AddRef();
    PluginServiceImpl::GetInstance()->OpenChannelToNpapiPlugin(
        0, 0, GURL(), GURL(), mime_type, this);
  }

  // Called when a timeout happens in order not to block the client
  // indefinitely.
  void OnTimeout() {
    LOG_IF(ERROR, is_removing_) << "Timed out";
    SignalDone();
  }

  // PluginProcessHost::Client methods.
  virtual int ID() OVERRIDE {
    // Generate a unique identifier for this PluginProcessHostClient.
    return ChildProcessHostImpl::GenerateChildProcessUniqueId();
  }

  virtual bool OffTheRecord() OVERRIDE {
    return false;
  }

  virtual const content::ResourceContext& GetResourceContext() OVERRIDE {
    return resource_context_;
  }

  virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
  }

  virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
  }

  virtual void OnSentPluginChannelRequest() OVERRIDE {
  }

  virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE {
    ConnectToChannel(handle);
    // Balancing the AddRef call.
    Release();
  }

  virtual void OnError() OVERRIDE {
    LOG(ERROR) << "Couldn't open plugin channel";
    SignalDone();
    // Balancing the AddRef call.
    Release();
  }

  // IPC::Channel::Listener methods.
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
    IPC_BEGIN_MESSAGE_MAP(Context, message)
      IPC_MESSAGE_HANDLER(PluginHostMsg_ClearSiteDataResult,
                          OnClearSiteDataResult)
      IPC_MESSAGE_UNHANDLED_ERROR()
    IPC_END_MESSAGE_MAP()

    return true;
  }

  virtual void OnChannelError() OVERRIDE {
    if (is_removing_) {
      NOTREACHED() << "Channel error";
      SignalDone();
    }
  }

  base::WaitableEvent* event() { return event_.get(); }

 private:
  // Connects the client side of a newly opened plug-in channel.
  void ConnectToChannel(const IPC::ChannelHandle& handle) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

    // If we timed out, don't bother connecting.
    if (!is_removing_)
      return;

    DCHECK(!channel_.get());
    channel_.reset(new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this));
    if (!channel_->Connect()) {
      NOTREACHED() << "Couldn't connect to plugin";
      SignalDone();
      return;
    }

    if (!channel_->Send(new PluginMsg_ClearSiteData(std::string(),
                                                    kClearAllData,
                                                    begin_time_))) {
      NOTREACHED() << "Couldn't send ClearSiteData message";
      SignalDone();
      return;
    }
  }

  // Handles the PluginHostMsg_ClearSiteDataResult message.
  void OnClearSiteDataResult(bool success) {
    LOG_IF(ERROR, !success) << "ClearSiteData returned error";
    UMA_HISTOGRAM_TIMES("ClearPluginData.time",
                        base::Time::Now() - remove_start_time_);
    SignalDone();
  }

  // Signals that we are finished with removing data (successful or not). This
  // method is safe to call multiple times.
  void SignalDone() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    if (!is_removing_)
      return;
    is_removing_ = false;
    event_->Signal();
  }

  scoped_ptr<base::WaitableEvent> event_;
  // The point in time when we start removing data.
  base::Time remove_start_time_;
  // The point in time from which on we remove data.
  base::Time begin_time_;
  bool is_removing_;

  // The resource context for the profile.
  const content::ResourceContext& resource_context_;

  // The channel is NULL until we have opened a connection to the plug-in
  // process.
  scoped_ptr<IPC::Channel> channel_;
};

PluginDataRemoverImpl::PluginDataRemoverImpl(
    const content::ResourceContext& resource_context)
    : mime_type_(kFlashMimeType),
      resource_context_(resource_context) {
}

PluginDataRemoverImpl::~PluginDataRemoverImpl() {
}

base::WaitableEvent* PluginDataRemoverImpl::StartRemoving(
    base::Time begin_time) {
  DCHECK(!context_.get());
  context_ = new Context(begin_time, resource_context_);
  context_->Init(mime_type_);
  return context_->event();
}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdoparser_lexer.cpp
  \authors   Барс Александр
  \authors   Урусов Андрей (rdo@rk9.bmstu.ru)
  \date
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOLexer
// --------------------------------------------------------------------------------
RDOLexer::RDOLexer(CREF(LPRDOParser) pParser, PTR(std::istream) yyin, PTR(std::ostream) yyout)
	: yyFlexLexer(yyin, yyout)
	, m_lpval    (NULL       )
	, m_lploc    (NULL       )
	, m_yyin     (yyin       )
	, m_yyout    (yyout      )
	, m_pParser  (pParser    )
	, m_enumEmpty(true       )
	, m_array_param_cnt(0    )
{}

CREF(LPRDOParser) RDOLexer::parser() const
{
	return m_pParser;
}

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

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

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

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

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

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

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

#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif

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

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

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - VS2010 warning fixed<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdoparser_lexer.cpp
  \authors   Барс Александр
  \authors   Урусов Андрей (rdo@rk9.bmstu.ru)
  \date
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOLexer
// --------------------------------------------------------------------------------
RDOLexer::RDOLexer(CREF(LPRDOParser) pParser, PTR(std::istream) yyin, PTR(std::ostream) yyout)
	: yyFlexLexer(yyin, yyout)
	, m_lpval    (NULL       )
	, m_lploc    (NULL       )
	, m_yyin     (yyin       )
	, m_yyout    (yyout      )
	, m_pParser  (pParser    )
	, m_enumEmpty(true       )
	, m_array_param_cnt(0    )
{}

CREF(LPRDOParser) RDOLexer::parser() const
{
	return m_pParser;
}

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

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

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

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

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

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

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

#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif

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

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

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
 * Authors: Silvio Traversaro
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <iDynTree/Core/SpatialInertiaRaw.h>
#include <iDynTree/Core/SpatialForceVector.h>
#include <iDynTree/Core/SpatialMotionVector.h>
#include <iDynTree/Core/PositionRaw.h>
#include <iDynTree/Core/Utils.h>
#include <iDynTree/Core/PrivateUtils.h>

#include <Eigen/Dense>

#include <iostream>
#include <sstream>

#include <cassert>

namespace iDynTree
{

SpatialInertiaRaw::SpatialInertiaRaw()
{
    this->zero();
}

SpatialInertiaRaw::SpatialInertiaRaw(const double mass,
                                     const PositionRaw& com,
                                     const RotationalInertiaRaw& rotInertia): m_mass(mass),
                                                                              m_rotInertia(rotInertia)
{
    for(int i = 0; i < 3; i++ )
    {
        this->m_mcom[i] = this->m_mass*com(i);
    }
}

SpatialInertiaRaw::SpatialInertiaRaw(const SpatialInertiaRaw& other): m_mass(other.m_mass),
                                                                      m_rotInertia(other.m_rotInertia)
{
    for(int i = 0; i < 3; i++ )
    {
        m_mcom[i] = other.m_mcom[i];
    }
}

SpatialInertiaRaw::~SpatialInertiaRaw()
{

}

void SpatialInertiaRaw::fromRotationalInertiaWrtCenterOfMass(const double mass,
                                                        const PositionRaw& com,
                                                        const RotationalInertiaRaw& rotInertiaWrtCom)
{
    this->m_mass = mass;

    for(int i = 0; i < 3; i++ )
    {
        this->m_mcom[i] = this->m_mass*com(i);
    }

    // Here we need to compute the rotational inertia at the com
    // given the one expressed at the frame origin
    // we apply formula 2.63 in Featherstone 2008
    Eigen::Map<Eigen::Matrix3d> linkInertia(this->m_rotInertia.data());
    Eigen::Map<const Eigen::Matrix3d> comInertia(rotInertiaWrtCom.data());
    Eigen::Map<const Eigen::Vector3d> mcom(this->m_mcom);

    linkInertia = comInertia - squareCrossProductMatrix(mcom)/this->m_mass;
}

double SpatialInertiaRaw::getMass() const
{
    return this->m_mass;
}

PositionRaw SpatialInertiaRaw::getCenterOfMass() const
{
    PositionRaw ret;
    ret(0) = this->m_mcom[0]/this->m_mass;
    ret(1) = this->m_mcom[1]/this->m_mass;
    ret(2) = this->m_mcom[2]/this->m_mass;

    return ret;
}

RotationalInertiaRaw SpatialInertiaRaw::getRotationalInertiaWrtFrameOrigin() const
{
    return this->m_rotInertia;
}

RotationalInertiaRaw SpatialInertiaRaw::getRotationalInertiaWrtCenterOfMass() const
{
    RotationalInertiaRaw retComInertia;
    // Here we need to compute the rotational inertia at the com
    // given the one expressed at the frame origin
    // we apply formula 2.63 in Featherstone 2008
    Eigen::Map<const Eigen::Matrix3d> linkInertia(this->m_rotInertia.data());
    Eigen::Map<Eigen::Matrix3d> comInertia(retComInertia.data());
    Eigen::Map<const Eigen::Vector3d> mcom(this->m_mcom);

    comInertia = linkInertia + squareCrossProductMatrix(mcom)/this->m_mass;

    return retComInertia;
}

SpatialInertiaRaw SpatialInertiaRaw::SpatialInertiaRaw::combine(const SpatialInertiaRaw& op1,
                                                                const SpatialInertiaRaw& op2)
{
    SpatialInertiaRaw ret;
    // If the two inertia are expressed with the same orientation
    // and with respect to the same point (and this will be checked by
    // the semantic check) we just need to sum
    // the mass, the first moment of mass and the rotational inertia
    ret.m_mass = op1.m_mass + op2.m_mass;

    Eigen::Map<Eigen::Vector3d> retMcom(ret.m_mcom);
    Eigen::Map<const Eigen::Vector3d> op1Mcom(op1.m_mcom);
    Eigen::Map<const Eigen::Vector3d> op2Mcom(op2.m_mcom);

    retMcom = op1Mcom + op2Mcom;

    Eigen::Map<Eigen::Matrix3d> retRotInertia(ret.m_rotInertia.data());
    Eigen::Map<const Eigen::Matrix3d> op1RotInertia(op1.m_rotInertia.data());
    Eigen::Map<const Eigen::Matrix3d> op2RotInertia(op2.m_rotInertia.data());

    retRotInertia = op1RotInertia + op2RotInertia;

    return ret;
}

SpatialForceVector SpatialInertiaRaw::multiply(const SpatialMotionVector& op) const
{
    SpatialForceVector ret;

    // we call this linearForce and angularForce
    // but please remember that they can also be
    // linear and angular momentum
    Eigen::Map<Eigen::Vector3d> linearForce(ret.getLinearVec3().data());
    Eigen::Map<Eigen::Vector3d> angularForce(ret.getAngularVec3().data());
    Eigen::Map<const Eigen::Vector3d> linearMotion(ret.getLinearVec3().data());
    Eigen::Map<const Eigen::Vector3d> angularMotion(ret.getAngularVec3().data());

    Eigen::Map<const Eigen::Vector3d> mcom(this->m_mcom);
    Eigen::Map<const Eigen::Matrix3d> inertia3d(this->m_rotInertia.data());

    // Implementing the 2.63 formula in Featherstone 2008
    linearForce  = this->m_mass*linearMotion - mcom.cross(angularMotion);
    angularForce = mcom.cross(linearMotion) + inertia3d*(angularMotion);

    return ret;
}

void SpatialInertiaRaw::zero()
{
    m_mass = 0.0;
    for(int i = 0; i < 3; i++ )
    {
        this->m_mcom[i] = 0.0;
    }
    this->m_rotInertia.zero();
}

}
<commit_msg>Fix bug in SpatialInertiaRaw::operator*<commit_after>/*
 * Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
 * Authors: Silvio Traversaro
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <iDynTree/Core/SpatialInertiaRaw.h>
#include <iDynTree/Core/SpatialForceVector.h>
#include <iDynTree/Core/SpatialMotionVector.h>
#include <iDynTree/Core/PositionRaw.h>
#include <iDynTree/Core/Utils.h>
#include <iDynTree/Core/PrivateUtils.h>

#include <Eigen/Dense>

#include <iostream>
#include <sstream>

#include <cassert>

namespace iDynTree
{

SpatialInertiaRaw::SpatialInertiaRaw()
{
    this->zero();
}

SpatialInertiaRaw::SpatialInertiaRaw(const double mass,
                                     const PositionRaw& com,
                                     const RotationalInertiaRaw& rotInertia): m_mass(mass),
                                                                              m_rotInertia(rotInertia)
{
    for(int i = 0; i < 3; i++ )
    {
        this->m_mcom[i] = this->m_mass*com(i);
    }
}

SpatialInertiaRaw::SpatialInertiaRaw(const SpatialInertiaRaw& other): m_mass(other.m_mass),
                                                                      m_rotInertia(other.m_rotInertia)
{
    for(int i = 0; i < 3; i++ )
    {
        m_mcom[i] = other.m_mcom[i];
    }
}

SpatialInertiaRaw::~SpatialInertiaRaw()
{

}

void SpatialInertiaRaw::fromRotationalInertiaWrtCenterOfMass(const double mass,
                                                        const PositionRaw& com,
                                                        const RotationalInertiaRaw& rotInertiaWrtCom)
{
    this->m_mass = mass;

    for(int i = 0; i < 3; i++ )
    {
        this->m_mcom[i] = this->m_mass*com(i);
    }

    // Here we need to compute the rotational inertia at the com
    // given the one expressed at the frame origin
    // we apply formula 2.63 in Featherstone 2008
    Eigen::Map<Eigen::Matrix3d> linkInertia(this->m_rotInertia.data());
    Eigen::Map<const Eigen::Matrix3d> comInertia(rotInertiaWrtCom.data());
    Eigen::Map<const Eigen::Vector3d> mcom(this->m_mcom);

    linkInertia = comInertia - squareCrossProductMatrix(mcom)/this->m_mass;
}

double SpatialInertiaRaw::getMass() const
{
    return this->m_mass;
}

PositionRaw SpatialInertiaRaw::getCenterOfMass() const
{
    PositionRaw ret;
    ret(0) = this->m_mcom[0]/this->m_mass;
    ret(1) = this->m_mcom[1]/this->m_mass;
    ret(2) = this->m_mcom[2]/this->m_mass;

    return ret;
}

RotationalInertiaRaw SpatialInertiaRaw::getRotationalInertiaWrtFrameOrigin() const
{
    return this->m_rotInertia;
}

RotationalInertiaRaw SpatialInertiaRaw::getRotationalInertiaWrtCenterOfMass() const
{
    RotationalInertiaRaw retComInertia;
    // Here we need to compute the rotational inertia at the com
    // given the one expressed at the frame origin
    // we apply formula 2.63 in Featherstone 2008
    Eigen::Map<const Eigen::Matrix3d> linkInertia(this->m_rotInertia.data());
    Eigen::Map<Eigen::Matrix3d> comInertia(retComInertia.data());
    Eigen::Map<const Eigen::Vector3d> mcom(this->m_mcom);

    comInertia = linkInertia + squareCrossProductMatrix(mcom)/this->m_mass;

    return retComInertia;
}

SpatialInertiaRaw SpatialInertiaRaw::SpatialInertiaRaw::combine(const SpatialInertiaRaw& op1,
                                                                const SpatialInertiaRaw& op2)
{
    SpatialInertiaRaw ret;
    // If the two inertia are expressed with the same orientation
    // and with respect to the same point (and this will be checked by
    // the semantic check) we just need to sum
    // the mass, the first moment of mass and the rotational inertia
    ret.m_mass = op1.m_mass + op2.m_mass;

    Eigen::Map<Eigen::Vector3d> retMcom(ret.m_mcom);
    Eigen::Map<const Eigen::Vector3d> op1Mcom(op1.m_mcom);
    Eigen::Map<const Eigen::Vector3d> op2Mcom(op2.m_mcom);

    retMcom = op1Mcom + op2Mcom;

    Eigen::Map<Eigen::Matrix3d> retRotInertia(ret.m_rotInertia.data());
    Eigen::Map<const Eigen::Matrix3d> op1RotInertia(op1.m_rotInertia.data());
    Eigen::Map<const Eigen::Matrix3d> op2RotInertia(op2.m_rotInertia.data());

    retRotInertia = op1RotInertia + op2RotInertia;

    return ret;
}

SpatialForceVector SpatialInertiaRaw::multiply(const SpatialMotionVector& op) const
{
    SpatialForceVector ret;

    // we call this linearForce and angularForce
    // but please remember that they can also be
    // linear and angular momentum
    Eigen::Map<Eigen::Vector3d> linearForce(ret.getLinearVec3().data());
    Eigen::Map<Eigen::Vector3d> angularForce(ret.getAngularVec3().data());
    Eigen::Map<const Eigen::Vector3d> linearMotion(op.getLinearVec3().data());
    Eigen::Map<const Eigen::Vector3d> angularMotion(op.getAngularVec3().data());

    Eigen::Map<const Eigen::Vector3d> mcom(this->m_mcom);
    Eigen::Map<const Eigen::Matrix3d> inertia3d(this->m_rotInertia.data());

    // Implementing the 2.63 formula in Featherstone 2008
    linearForce  = this->m_mass*linearMotion - mcom.cross(angularMotion);
    angularForce = mcom.cross(linearMotion) + inertia3d*(angularMotion);

    return ret;
}

void SpatialInertiaRaw::zero()
{
    m_mass = 0.0;
    for(int i = 0; i < 3; i++ )
    {
        this->m_mcom[i] = 0.0;
    }
    this->m_rotInertia.zero();
}

}
<|endoftext|>