<commit_before>#include "node_map.hpp"
#include "node_file_source.hpp"

#include <mbgl/platform/default/headless_display.hpp>
#include <mbgl/map/still_image.hpp>
#include <mbgl/util/exception.hpp>

 #include <unistd.h>

namespace node_mbgl {

struct NodeMap::RenderOptions {
    double zoom = 0;
    double bearing = 0;
    double latitude = 0;
    double longitude = 0;
    unsigned int width = 512;
    unsigned int height = 512;
    float ratio = 1.0f;
    std::vector<std::string> classes;
};

////////////////////////////////////////////////////////////////////////////////////////////////
// Static Node Methods

v8::Persistent<v8::FunctionTemplate> NodeMap::constructorTemplate;

void NodeMap::Init(v8::Handle<v8::Object> target) {
    NanScope();

    v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);
    t->SetClassName(NanNew("Map"));

    NODE_SET_PROTOTYPE_METHOD(t, "setAccessToken", SetAccessToken);
    NODE_SET_PROTOTYPE_METHOD(t, "load", Load);
    NODE_SET_PROTOTYPE_METHOD(t, "render", Render);

    NanAssignPersistent(constructorTemplate, t);

    target->Set(NanNew("Map"), t->GetFunction());
}

NAN_METHOD(NodeMap::New) {
    NanScope();

    if (!args.IsConstructCall()) {
        return NanThrowTypeError("Use the new operator to create new Map objects");
    }

    if (args.Length() < 1 || !NanHasInstance(NodeFileSource::constructorTemplate, args[0])) {
        return NanThrowTypeError("Requires a FileSource as first argument");
    }

    auto source = args[0]->ToObject();

    // Check that request() and cancel() are defined.
    if (!source->Has(NanNew("request")) || !source->Get(NanNew("request"))->IsFunction()) {
        return NanThrowError("FileSource must have a request member function");
    }
    if (!source->Has(NanNew("cancel")) || !source->Get(NanNew("cancel"))->IsFunction()) {
        return NanThrowError("FileSource must have a cancel member function");
    }

    auto map = new NodeMap(args[0]->ToObject());
    map->Wrap(args.This());

    NanReturnValue(args.This());
}

NAN_METHOD(NodeMap::SetAccessToken) {
    NanScope();

    if (args.Length() < 1) {
        return NanThrowError("Requires a string as first argument");
    }

    NanUtf8String token(args[0]);

    auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());

    if (nodeMap->map.isRendering()) {
        return NanThrowError("Map object is currently in use");
    }

    try {
        nodeMap->map.setAccessToken(std::string { *token, size_t(token.length()) });
    } catch (const std::exception &ex) {
        return NanThrowError(ex.what());
    }

    NanReturnUndefined();
}

const std::string StringifyStyle(v8::Handle<v8::Value> styleHandle) {
    NanScope();

    auto JSON = NanGetCurrentContext()->Global()->Get(NanNew("JSON"))->ToObject();
    auto stringify = v8::Handle<v8::Function>::Cast(JSON->Get(NanNew("stringify")));

    return *NanUtf8String(stringify->Call(JSON, 1, &styleHandle));
}

NAN_METHOD(NodeMap::Load) {
    NanScope();

    if (args.Length() < 1) {
        return NanThrowError("Requires a map style as first argument");
    }

    std::string style;

    if (args[0]->IsObject()) {
        style = StringifyStyle(args[0]);
    } else if (args[0]->IsString()) {
        NanUtf8String string(args[0]);
        style = { *string, size_t(string.length()) };
    } else {
        return NanThrowTypeError("First argument must be a string or object");
    }

    auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());

    if (nodeMap->map.isRendering()) {
        return NanThrowError("Map object is currently in use");
    }

    try {
        nodeMap->map.setStyleJSON(style, ".");
    } catch (const std::exception &ex) {
        return NanThrowError(ex.what());
    }

    NanReturnUndefined();
}

std::unique_ptr<NodeMap::RenderOptions> NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
    NanScope();

    auto options = mbgl::util::make_unique<RenderOptions>();

    if (obj->Has(NanNew("zoom"))) { options->zoom = obj->Get(NanNew("zoom"))->NumberValue(); }
    if (obj->Has(NanNew("bearing"))) { options->bearing = obj->Get(NanNew("bearing"))->NumberValue(); }
    if (obj->Has(NanNew("center"))) {
        auto center = obj->Get(NanNew("center")).As<v8::Array>();
        if (center->Length() > 0) { options->latitude = center->Get(0)->NumberValue(); }
        if (center->Length() > 1) { options->longitude = center->Get(1)->NumberValue(); }
    }
    if (obj->Has(NanNew("width"))) { options->width = obj->Get(NanNew("width"))->IntegerValue(); }
    if (obj->Has(NanNew("height"))) { options->height = obj->Get(NanNew("height"))->IntegerValue(); }
    if (obj->Has(NanNew("ratio"))) { options->ratio = obj->Get(NanNew("ratio"))->IntegerValue(); }

    if (obj->Has(NanNew("classes"))) {
        auto classes = obj->Get(NanNew("classes"))->ToObject().As<v8::Array>();
        const int length = classes->Length();
        options->classes.reserve(length);
        for (int i = 0; i < length; i++) {
            options->classes.push_back(std::string { *NanUtf8String(classes->Get(i)->ToString()) });
        }
    }

    return options;
}

NAN_METHOD(NodeMap::Render) {
    NanScope();

    if (args.Length() <= 0 || !args[0]->IsObject()) {
        return NanThrowTypeError("First argument must be an options object");
    }

    if (args.Length() <= 1 || !args[1]->IsFunction()) {
        return NanThrowTypeError("Second argument must be a callback function");
    }

    auto options = ParseOptions(args[0]->ToObject());

    auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());

    if (nodeMap->map.isRendering()) {
        return NanThrowError("Map object is currently in use");
    }

    assert(!nodeMap->callback);
    assert(!nodeMap->image);
    nodeMap->callback = std::unique_ptr<NanCallback>(new NanCallback(args[1].As<v8::Function>()));

    try {
        nodeMap->startRender(std::move(options));
    } catch (mbgl::util::Exception &ex) {
        return NanThrowError(ex.what());
    }

    NanReturnUndefined();
}

void NodeMap::startRender(std::unique_ptr<NodeMap::RenderOptions> options) {
    view.resize(options->width, options->height, options->ratio);
    map.setClasses(options->classes);
    map.setLonLatZoom(options->longitude, options->latitude, options->zoom);
    map.setBearing(options->bearing);

    map.renderStill([this](std::unique_ptr<const mbgl::StillImage> result) {
        assert(!image);
        image = std::move(result);
        uv_async_send(async);
    });

    // Retain this object, otherwise it might get destructed before we are finished rendering the
    // still image.
    Ref();

    // Similarly, we're now waiting for the async to be called, so we need to make sure that it
    // keeps the loop alive.
    uv_ref(reinterpret_cast<uv_handle_t *>(async));
}

void NodeMap::renderFinished() {
    NanScope();

    // We're done with this render call, so we're unrefing so that the loop could close.
    uv_unref(reinterpret_cast<uv_handle_t *>(async));

    // There is no render pending anymore, we the GC could now delete this object if it went out
    // of scope.
    Unref();

    // Move the callback and image out of the way so that the callback can start a new render call.
    auto cb = std::move(callback);
    auto img = std::move(image);
    assert(cb);

    // These have to be empty to be prepared for the next render call.
    assert(!callback);
    assert(!image);

    if (img) {
        v8::Local<v8::Object> result = v8::Object::New();
        result->Set(NanNew("width"), NanNew(img->width));
        result->Set(NanNew("height"), NanNew(img->height));

        v8::Local<v8::Object> pixels = NanNewBufferHandle(
            reinterpret_cast<char *>(img->pixels.get()),
            size_t(img->width) * size_t(img->height) * sizeof(mbgl::StillImage::Pixel),

            // Retain the StillImage object until the buffer is deleted.
            [](char *, void *hint) {
                delete reinterpret_cast<const mbgl::StillImage *>(hint);
            },
            const_cast<mbgl::StillImage *>(img.get())
        );
        img.release();

        result->Set(NanNew("pixels"), pixels);

        v8::Local<v8::Value> argv[] = {
            NanNull(),
            result,
        };
        cb->Call(2, argv);
    } else {
        v8::Local<v8::Value> argv[] = {
            NanError("Didn't get an image")
        };
        cb->Call(1, argv);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
// Instance

std::shared_ptr<mbgl::HeadlessDisplay> sharedDisplay() {
    static auto display = std::make_shared<mbgl::HeadlessDisplay>();
    return display;
}

NodeMap::NodeMap(v8::Handle<v8::Object> source_) :
    view(sharedDisplay()),
    fs(*ObjectWrap::Unwrap<NodeFileSource>(source_)),
    map(view, fs, mbgl::Map::RenderMode::Still),
    async(new uv_async_t) {
    source = v8::Persistent<v8::Object>::New(source_);
    async->data = this;
    uv_async_init(uv_default_loop(), async, [](uv_async_t *as, int) {
        reinterpret_cast<NodeMap *>(as->data)->renderFinished();
    });

    // Make sure the async handle doesn't keep the loop alive.
    uv_unref(reinterpret_cast<uv_handle_t *>(async));
}

NodeMap::~NodeMap() {
    source.Dispose();

    uv_close(reinterpret_cast<uv_handle_t *>(async), [] (uv_handle_t *handle) {
        delete reinterpret_cast<uv_async_t *>(handle);
    });
}

}
<commit_msg>fix setLatLngZooom<commit_after>#include "node_map.hpp"
#include "node_file_source.hpp"

#include <mbgl/platform/default/headless_display.hpp>
#include <mbgl/map/still_image.hpp>
#include <mbgl/util/exception.hpp>

 #include <unistd.h>

namespace node_mbgl {

struct NodeMap::RenderOptions {
    double zoom = 0;
    double bearing = 0;
    double latitude = 0;
    double longitude = 0;
    unsigned int width = 512;
    unsigned int height = 512;
    float ratio = 1.0f;
    std::vector<std::string> classes;
};

////////////////////////////////////////////////////////////////////////////////////////////////
// Static Node Methods

v8::Persistent<v8::FunctionTemplate> NodeMap::constructorTemplate;

void NodeMap::Init(v8::Handle<v8::Object> target) {
    NanScope();

    v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);
    t->SetClassName(NanNew("Map"));

    NODE_SET_PROTOTYPE_METHOD(t, "setAccessToken", SetAccessToken);
    NODE_SET_PROTOTYPE_METHOD(t, "load", Load);
    NODE_SET_PROTOTYPE_METHOD(t, "render", Render);

    NanAssignPersistent(constructorTemplate, t);

    target->Set(NanNew("Map"), t->GetFunction());
}

NAN_METHOD(NodeMap::New) {
    NanScope();

    if (!args.IsConstructCall()) {
        return NanThrowTypeError("Use the new operator to create new Map objects");
    }

    if (args.Length() < 1 || !NanHasInstance(NodeFileSource::constructorTemplate, args[0])) {
        return NanThrowTypeError("Requires a FileSource as first argument");
    }

    auto source = args[0]->ToObject();

    // Check that request() and cancel() are defined.
    if (!source->Has(NanNew("request")) || !source->Get(NanNew("request"))->IsFunction()) {
        return NanThrowError("FileSource must have a request member function");
    }
    if (!source->Has(NanNew("cancel")) || !source->Get(NanNew("cancel"))->IsFunction()) {
        return NanThrowError("FileSource must have a cancel member function");
    }

    auto map = new NodeMap(args[0]->ToObject());
    map->Wrap(args.This());

    NanReturnValue(args.This());
}

NAN_METHOD(NodeMap::SetAccessToken) {
    NanScope();

    if (args.Length() < 1) {
        return NanThrowError("Requires a string as first argument");
    }

    NanUtf8String token(args[0]);

    auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());

    if (nodeMap->map.isRendering()) {
        return NanThrowError("Map object is currently in use");
    }

    try {
        nodeMap->map.setAccessToken(std::string { *token, size_t(token.length()) });
    } catch (const std::exception &ex) {
        return NanThrowError(ex.what());
    }

    NanReturnUndefined();
}

const std::string StringifyStyle(v8::Handle<v8::Value> styleHandle) {
    NanScope();

    auto JSON = NanGetCurrentContext()->Global()->Get(NanNew("JSON"))->ToObject();
    auto stringify = v8::Handle<v8::Function>::Cast(JSON->Get(NanNew("stringify")));

    return *NanUtf8String(stringify->Call(JSON, 1, &styleHandle));
}

NAN_METHOD(NodeMap::Load) {
    NanScope();

    if (args.Length() < 1) {
        return NanThrowError("Requires a map style as first argument");
    }

    std::string style;

    if (args[0]->IsObject()) {
        style = StringifyStyle(args[0]);
    } else if (args[0]->IsString()) {
        NanUtf8String string(args[0]);
        style = { *string, size_t(string.length()) };
    } else {
        return NanThrowTypeError("First argument must be a string or object");
    }

    auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());

    if (nodeMap->map.isRendering()) {
        return NanThrowError("Map object is currently in use");
    }

    try {
        nodeMap->map.setStyleJSON(style, ".");
    } catch (const std::exception &ex) {
        return NanThrowError(ex.what());
    }

    NanReturnUndefined();
}

std::unique_ptr<NodeMap::RenderOptions> NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
    NanScope();

    auto options = mbgl::util::make_unique<RenderOptions>();

    if (obj->Has(NanNew("zoom"))) { options->zoom = obj->Get(NanNew("zoom"))->NumberValue(); }
    if (obj->Has(NanNew("bearing"))) { options->bearing = obj->Get(NanNew("bearing"))->NumberValue(); }
    if (obj->Has(NanNew("center"))) {
        auto center = obj->Get(NanNew("center")).As<v8::Array>();
        if (center->Length() > 0) { options->latitude = center->Get(0)->NumberValue(); }
        if (center->Length() > 1) { options->longitude = center->Get(1)->NumberValue(); }
    }
    if (obj->Has(NanNew("width"))) { options->width = obj->Get(NanNew("width"))->IntegerValue(); }
    if (obj->Has(NanNew("height"))) { options->height = obj->Get(NanNew("height"))->IntegerValue(); }
    if (obj->Has(NanNew("ratio"))) { options->ratio = obj->Get(NanNew("ratio"))->IntegerValue(); }

    if (obj->Has(NanNew("classes"))) {
        auto classes = obj->Get(NanNew("classes"))->ToObject().As<v8::Array>();
        const int length = classes->Length();
        options->classes.reserve(length);
        for (int i = 0; i < length; i++) {
            options->classes.push_back(std::string { *NanUtf8String(classes->Get(i)->ToString()) });
        }
    }

    return options;
}

NAN_METHOD(NodeMap::Render) {
    NanScope();

    if (args.Length() <= 0 || !args[0]->IsObject()) {
        return NanThrowTypeError("First argument must be an options object");
    }

    if (args.Length() <= 1 || !args[1]->IsFunction()) {
        return NanThrowTypeError("Second argument must be a callback function");
    }

    auto options = ParseOptions(args[0]->ToObject());

    auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());

    if (nodeMap->map.isRendering()) {
        return NanThrowError("Map object is currently in use");
    }

    assert(!nodeMap->callback);
    assert(!nodeMap->image);
    nodeMap->callback = std::unique_ptr<NanCallback>(new NanCallback(args[1].As<v8::Function>()));

    try {
        nodeMap->startRender(std::move(options));
    } catch (mbgl::util::Exception &ex) {
        return NanThrowError(ex.what());
    }

    NanReturnUndefined();
}

void NodeMap::startRender(std::unique_ptr<NodeMap::RenderOptions> options) {
    view.resize(options->width, options->height, options->ratio);
    map.setClasses(options->classes);
    map.setLatLngZoom(mbgl::LatLng(options->longitude, options->latitude), options->zoom);
    map.setBearing(options->bearing);

    map.renderStill([this](std::unique_ptr<const mbgl::StillImage> result) {
        assert(!image);
        image = std::move(result);
        uv_async_send(async);
    });

    // Retain this object, otherwise it might get destructed before we are finished rendering the
    // still image.
    Ref();

    // Similarly, we're now waiting for the async to be called, so we need to make sure that it
    // keeps the loop alive.
    uv_ref(reinterpret_cast<uv_handle_t *>(async));
}

void NodeMap::renderFinished() {
    NanScope();

    // We're done with this render call, so we're unrefing so that the loop could close.
    uv_unref(reinterpret_cast<uv_handle_t *>(async));

    // There is no render pending anymore, we the GC could now delete this object if it went out
    // of scope.
    Unref();

    // Move the callback and image out of the way so that the callback can start a new render call.
    auto cb = std::move(callback);
    auto img = std::move(image);
    assert(cb);

    // These have to be empty to be prepared for the next render call.
    assert(!callback);
    assert(!image);

    if (img) {
        v8::Local<v8::Object> result = v8::Object::New();
        result->Set(NanNew("width"), NanNew(img->width));
        result->Set(NanNew("height"), NanNew(img->height));

        v8::Local<v8::Object> pixels = NanNewBufferHandle(
            reinterpret_cast<char *>(img->pixels.get()),
            size_t(img->width) * size_t(img->height) * sizeof(mbgl::StillImage::Pixel),

            // Retain the StillImage object until the buffer is deleted.
            [](char *, void *hint) {
                delete reinterpret_cast<const mbgl::StillImage *>(hint);
            },
            const_cast<mbgl::StillImage *>(img.get())
        );
        img.release();

        result->Set(NanNew("pixels"), pixels);

        v8::Local<v8::Value> argv[] = {
            NanNull(),
            result,
        };
        cb->Call(2, argv);
    } else {
        v8::Local<v8::Value> argv[] = {
            NanError("Didn't get an image")
        };
        cb->Call(1, argv);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////
// Instance

std::shared_ptr<mbgl::HeadlessDisplay> sharedDisplay() {
    static auto display = std::make_shared<mbgl::HeadlessDisplay>();
    return display;
}

NodeMap::NodeMap(v8::Handle<v8::Object> source_) :
    view(sharedDisplay()),
    fs(*ObjectWrap::Unwrap<NodeFileSource>(source_)),
    map(view, fs, mbgl::Map::RenderMode::Still),
    async(new uv_async_t) {
    source = v8::Persistent<v8::Object>::New(source_);
    async->data = this;
    uv_async_init(uv_default_loop(), async, [](uv_async_t *as, int) {
        reinterpret_cast<NodeMap *>(as->data)->renderFinished();
    });

    // Make sure the async handle doesn't keep the loop alive.
    uv_unref(reinterpret_cast<uv_handle_t *>(async));
}

NodeMap::~NodeMap() {
    source.Dispose();

    uv_close(reinterpret_cast<uv_handle_t *>(async), [] (uv_handle_t *handle) {
        delete reinterpret_cast<uv_async_t *>(handle);
    });
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rlrcitem.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 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
 *
 ************************************************************************/

// INCLUDE ---------------------------------------------------------------

#ifndef _SFXRECTITEM_HXX
#include <svtools/rectitem.hxx>
#endif

#define ITEMID_LRSPACE  0
#define ITEMID_ULSPACE  0
#define ITEMID_TABSTOP  0
#define ITEMID_PROTECT  0

#include "dialogs.hrc"

#include "ruler.hxx"
#include "lrspitem.hxx"
#include "ulspitem.hxx"
#include "tstpitem.hxx"
#include "protitem.hxx"
#include "rlrcitem.hxx"
#include "rulritem.hxx"
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif

// class SvxRulerItem ----------------------------------------------------

SvxRulerItem::SvxRulerItem(USHORT _nId, SvxRuler &rRul, SfxBindings &rBindings)
: SfxControllerItem(_nId, rBindings),
  rRuler(rRul)
{
}

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

void SvxRulerItem::StateChanged( USHORT nSID, SfxItemState eState,
                                 const SfxPoolItem* pState)
{
    // SFX_ITEM_DONTCARE => pState == -1 => PTR_CAST buff
    if ( eState != SFX_ITEM_AVAILABLE )
        pState = 0;

    switch(nSID)
    {
        // Linker / rechter Seitenrand
        case SID_RULER_LR_MIN_MAX:
        {
            const SfxRectangleItem *pItem = PTR_CAST(SfxRectangleItem, pState);
            rRuler.UpdateFrameMinMax(pItem);
            break;
        }
        case SID_ATTR_LONG_LRSPACE:
        {
            const SvxLongLRSpaceItem *pItem = PTR_CAST(SvxLongLRSpaceItem, pState);
            DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
            rRuler.UpdateFrame(pItem);
            break;
        }
        case SID_ATTR_LONG_ULSPACE:
        {
            const SvxLongULSpaceItem *pItem = PTR_CAST(SvxLongULSpaceItem, pState);
            DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxULSpaceItem erwartet");
            rRuler.UpdateFrame(pItem);
            break;
        }
        case SID_ATTR_TABSTOP_VERTICAL:
        case SID_ATTR_TABSTOP:
        {
            const SvxTabStopItem *pItem = PTR_CAST(SvxTabStopItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxTabStopItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_ATTR_PARA_LRSPACE_VERTICAL:
        case SID_ATTR_PARA_LRSPACE:
        {
            const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
            rRuler.UpdatePara(pItem);
            break;
        }
        case SID_RULER_BORDERS_VERTICAL:
        case SID_RULER_BORDERS:
        case SID_RULER_ROWS:
        case SID_RULER_ROWS_VERTICAL:
        {
            const SvxColumnItem *pItem = PTR_CAST(SvxColumnItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxColumnItem erwartet");
#ifdef DBG_UTIL
            if(pItem)
            {
                if(pItem->IsConsistent())
                    rRuler.Update(pItem, nSID);
                else
                    DBG_ERROR("Spaltenitem corrupted");
            }
            else
                rRuler.Update(pItem, nSID);
#else
            rRuler.Update(pItem, nSID);
#endif
            break;
        }
        case SID_RULER_PAGE_POS:
        {   // Position Seite, Seitenbreite
            const SvxPagePosSizeItem *pItem = PTR_CAST(SvxPagePosSizeItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxPagePosSizeItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_RULER_OBJECT:
        {   // Object-Selektion
            const SvxObjectItem *pItem = PTR_CAST(SvxObjectItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxObjectItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_RULER_PROTECT:
        {
            const SvxProtectItem *pItem = PTR_CAST(SvxProtectItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxProtectItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_RULER_BORDER_DISTANCE:
        {
            const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
            rRuler.UpdateParaBorder(pItem);
        }
        break;
        case SID_RULER_TEXT_RIGHT_TO_LEFT :
        {
            const SfxBoolItem *pItem = PTR_CAST(SfxBoolItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SfxBoolItem erwartet");
            rRuler.UpdateTextRTL(pItem);
        }
        break;
    }
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.7.116); FILE MERGED 2006/09/01 17:46:22 kaib 1.7.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rlrcitem.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 04:36:29 $
 *
 *  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_svx.hxx"

// INCLUDE ---------------------------------------------------------------

#ifndef _SFXRECTITEM_HXX
#include <svtools/rectitem.hxx>
#endif

#define ITEMID_LRSPACE  0
#define ITEMID_ULSPACE  0
#define ITEMID_TABSTOP  0
#define ITEMID_PROTECT  0

#include "dialogs.hrc"

#include "ruler.hxx"
#include "lrspitem.hxx"
#include "ulspitem.hxx"
#include "tstpitem.hxx"
#include "protitem.hxx"
#include "rlrcitem.hxx"
#include "rulritem.hxx"
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif

// class SvxRulerItem ----------------------------------------------------

SvxRulerItem::SvxRulerItem(USHORT _nId, SvxRuler &rRul, SfxBindings &rBindings)
: SfxControllerItem(_nId, rBindings),
  rRuler(rRul)
{
}

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

void SvxRulerItem::StateChanged( USHORT nSID, SfxItemState eState,
                                 const SfxPoolItem* pState)
{
    // SFX_ITEM_DONTCARE => pState == -1 => PTR_CAST buff
    if ( eState != SFX_ITEM_AVAILABLE )
        pState = 0;

    switch(nSID)
    {
        // Linker / rechter Seitenrand
        case SID_RULER_LR_MIN_MAX:
        {
            const SfxRectangleItem *pItem = PTR_CAST(SfxRectangleItem, pState);
            rRuler.UpdateFrameMinMax(pItem);
            break;
        }
        case SID_ATTR_LONG_LRSPACE:
        {
            const SvxLongLRSpaceItem *pItem = PTR_CAST(SvxLongLRSpaceItem, pState);
            DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
            rRuler.UpdateFrame(pItem);
            break;
        }
        case SID_ATTR_LONG_ULSPACE:
        {
            const SvxLongULSpaceItem *pItem = PTR_CAST(SvxLongULSpaceItem, pState);
            DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxULSpaceItem erwartet");
            rRuler.UpdateFrame(pItem);
            break;
        }
        case SID_ATTR_TABSTOP_VERTICAL:
        case SID_ATTR_TABSTOP:
        {
            const SvxTabStopItem *pItem = PTR_CAST(SvxTabStopItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxTabStopItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_ATTR_PARA_LRSPACE_VERTICAL:
        case SID_ATTR_PARA_LRSPACE:
        {
            const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
            rRuler.UpdatePara(pItem);
            break;
        }
        case SID_RULER_BORDERS_VERTICAL:
        case SID_RULER_BORDERS:
        case SID_RULER_ROWS:
        case SID_RULER_ROWS_VERTICAL:
        {
            const SvxColumnItem *pItem = PTR_CAST(SvxColumnItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxColumnItem erwartet");
#ifdef DBG_UTIL
            if(pItem)
            {
                if(pItem->IsConsistent())
                    rRuler.Update(pItem, nSID);
                else
                    DBG_ERROR("Spaltenitem corrupted");
            }
            else
                rRuler.Update(pItem, nSID);
#else
            rRuler.Update(pItem, nSID);
#endif
            break;
        }
        case SID_RULER_PAGE_POS:
        {   // Position Seite, Seitenbreite
            const SvxPagePosSizeItem *pItem = PTR_CAST(SvxPagePosSizeItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxPagePosSizeItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_RULER_OBJECT:
        {   // Object-Selektion
            const SvxObjectItem *pItem = PTR_CAST(SvxObjectItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxObjectItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_RULER_PROTECT:
        {
            const SvxProtectItem *pItem = PTR_CAST(SvxProtectItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxProtectItem erwartet");
            rRuler.Update(pItem);
            break;
        }
        case SID_RULER_BORDER_DISTANCE:
        {
            const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
            rRuler.UpdateParaBorder(pItem);
        }
        break;
        case SID_RULER_TEXT_RIGHT_TO_LEFT :
        {
            const SfxBoolItem *pItem = PTR_CAST(SfxBoolItem, pState);
            DBG_ASSERT(pState?  0 != pItem: TRUE, "SfxBoolItem erwartet");
            rRuler.UpdateTextRTL(pItem);
        }
        break;
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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 "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  void RunStartupTest(const wchar_t* graph, const wchar_t* trace,
      bool test_cold, bool important) {
    const int kNumCycles = 20;

    TimeDelta timings[kNumCycles];
    for (int i = 0; i < kNumCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutableName)));
        ASSERT_TRUE(file_util::EvictFileFromSystemCache(chrome_exe));
#if defined(OS_WIN)
        // TODO(port): these files do not exist on other platforms.
        // Decide what to do.

        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(file_util::EvictFileFromSystemCache(chrome_dll));

        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(file_util::EvictFileFromSystemCache(gears_dll));
#endif  // defined(OS_WIN)
      }

      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
      }
    }

    std::wstring times;
    for (int i = 0; i < kNumCycles; ++i)
      StringAppendF(&times, L"%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, L"", trace, times, L"ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    std::wstring dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    file_util::AppendToPath(&dir, L"reference_build");
    file_util::AppendToPath(&dir, L"chrome");
    browser_directory_ = dir;
  }
};

class StartupFileTest : public StartupTest {
 public:
  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUp() {
    std::wstring file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_util::AppendToPath(&file_url, L"empty.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url);

    pages_ = WideToUTF8(file_url);
  }
};

}  // namespace

TEST_F(StartupTest, Perf) {
  RunStartupTest(L"warm", L"t", false /* not cold */, true /* important */);
}

#if defined(OS_WIN)
// TODO(port): Enable reference tests on other platforms.

TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest(L"warm", L"t_ref", false /* not cold */,
                 true /* important */);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest(L"cold", L"t", true /* cold */, false /* not important */);
}

TEST_F(StartupFileTest, PerfGears) {
  RunStartupTest(L"warm", L"gears", false /* not cold */,
                 false /* not important */);
}

TEST_F(StartupFileTest, PerfColdGears) {
  RunStartupTest(L"cold", L"gears", true /* cold */,
                 false /* not important */);
}

#endif  // defined(OS_WIN)

<commit_msg>Fix startup_test failures on Windows buildbot.<commit_after>// Copyright (c) 2006-2008 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 "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

// Wrapper around EvictFileFromSystemCache to retry 10 times in case of error.
// Apparently needed for Windows buildbots (to workaround an error when
// file is in use).
// TODO(phajdan.jr): Move to test_file_util if we need it in more places.
bool EvictFileFromSystemCacheWrapper(const FilePath& path) {
  for (int i = 0; i < 10; i++) {
    if (file_util::EvictFileFromSystemCache(path))
      return true;
    PlatformThread::Sleep(1000);
  }
  return false;
}

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  void RunStartupTest(const wchar_t* graph, const wchar_t* trace,
      bool test_cold, bool important) {
    const int kNumCycles = 20;

    TimeDelta timings[kNumCycles];
    for (int i = 0; i < kNumCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutableName)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // TODO(port): these files do not exist on other platforms.
        // Decide what to do.

        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));

        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#endif  // defined(OS_WIN)
      }

      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
      }
    }

    std::wstring times;
    for (int i = 0; i < kNumCycles; ++i)
      StringAppendF(&times, L"%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, L"", trace, times, L"ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    std::wstring dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    file_util::AppendToPath(&dir, L"reference_build");
    file_util::AppendToPath(&dir, L"chrome");
    browser_directory_ = dir;
  }
};

class StartupFileTest : public StartupTest {
 public:
  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUp() {
    std::wstring file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_util::AppendToPath(&file_url, L"empty.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url);

    pages_ = WideToUTF8(file_url);
  }
};

}  // namespace

TEST_F(StartupTest, Perf) {
  RunStartupTest(L"warm", L"t", false /* not cold */, true /* important */);
}

#if defined(OS_WIN)
// TODO(port): Enable reference tests on other platforms.

TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest(L"warm", L"t_ref", false /* not cold */,
                 true /* important */);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest(L"cold", L"t", true /* cold */, false /* not important */);
}

TEST_F(StartupFileTest, PerfGears) {
  RunStartupTest(L"warm", L"gears", false /* not cold */,
                 false /* not important */);
}

TEST_F(StartupFileTest, PerfColdGears) {
  RunStartupTest(L"cold", L"gears", true /* cold */,
                 false /* not important */);
}

#endif  // defined(OS_WIN)

<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009-2010 Bastian Holst <bastianholst@gmx.de>
//

#include "MarbleGraphicsItem.h"

#include "MarbleGraphicsItem_p.h"

// Marble
#include "MarbleDebug.h"
#include "ViewportParams.h"

// Qt
#include <QtCore/QList>
#include <QtCore/QSet>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QPixmapCache>
#include <QtGui/QMouseEvent>

using namespace Marble;

MarbleGraphicsItem::MarbleGraphicsItem( MarbleGraphicsItemPrivate *d_ptr )
    : d( d_ptr )
{
}

MarbleGraphicsItem::~MarbleGraphicsItem()
{
    delete d;
}

bool MarbleGraphicsItem::paintEvent( QPainter *painter, const ViewportParams *viewport )
{
    if ( !p()->m_visibility ) {
        return true;
    }

    p()->setProjection( viewport );

    // Remove the pixmap if it has been requested. This prevents QPixmapCache from being used
    // outside the ui thread.
    if ( p()->m_repaintNeeded ) {
        p()->updateChildPositions();
        p()->m_repaintNeeded = false;
        QPixmapCache::remove( p()->m_cacheKey );
    }

    if ( p()->positions().size() == 0 ) {
        return true;
    }

    // At the moment, as GraphicsItems can't be zoomed or rotated ItemCoordinateCache
    // and DeviceCoordianteCache is exactly the same
    if ( ItemCoordinateCache == cacheMode()
         || DeviceCoordinateCache == cacheMode() )
    {
        QPixmap cachePixmap;
        bool pixmapAvailable = QPixmapCache::find( p()->m_cacheKey, &cachePixmap );
        if ( !pixmapAvailable ) {
            QSize neededPixmapSize = size().toSize() + QSize( 1, 1 ); // adding a pixel for rounding errors

            if ( cachePixmap.size() != neededPixmapSize ) {
                if ( size().isValid() && !size().isNull() ) {
                    cachePixmap = QPixmap( neededPixmapSize ).copy();
                }
                else {
                    mDebug() << "Warning: Invalid pixmap size suggested: " << d->m_size;
                }
            }

            cachePixmap.fill( Qt::transparent );
            QPainter pixmapPainter( &cachePixmap );
            // We paint in best quality here, as we only have to paint once.
            pixmapPainter.setRenderHint( QPainter::Antialiasing, true );
            // The cache image will get a 0.5 pixel bounding to save antialiasing effects.
            pixmapPainter.translate( 0.5, 0.5 );
            paint( &pixmapPainter );

            // Paint children
            foreach ( MarbleGraphicsItem *item, p()->m_children ) {
                item->paintEvent( &pixmapPainter, viewport );
            }
            // Update the pixmap in cache
            p()->m_cacheKey = QPixmapCache::insert( cachePixmap );
        }

        foreach( const QPointF& position, p()->positions() ) {
            painter->drawPixmap( position, cachePixmap );
        }
    }
    else {
        foreach( const QPointF& position, p()->positions() ) {
            painter->save();

            painter->translate( position );
            paint( painter );

            // Paint children
            foreach ( MarbleGraphicsItem *item, p()->m_children ) {
                item->paintEvent( painter, viewport );
            }

            painter->restore();
        }
    }

    return true;
}

bool MarbleGraphicsItem::contains( const QPointF& point ) const
{
    foreach( const QRectF& rect, d->boundingRects() ) {
        if( rect.contains( point ) )
            return true;
    }
    return false;
}

QRectF MarbleGraphicsItem::containsRect( const QPointF& point ) const
{
    foreach( const QRectF& rect, d->boundingRects() ) {
        if( rect.contains( point ) )
            return rect;
    }
    return QRectF();
}

QList<QRectF> MarbleGraphicsItemPrivate::boundingRects() const
{
    QList<QRectF> list;

    foreach( QPointF point, positions() ) {
        QRectF rect( point, m_size );
        if( rect.x() < 0 )
            rect.setLeft( 0 );
        if( rect.y() < 0 )
            rect.setTop( 0 );

        list.append( rect );
    }

    return list;
}

QSizeF MarbleGraphicsItem::size() const
{
    return p()->m_size;
}

AbstractMarbleGraphicsLayout *MarbleGraphicsItem::layout() const
{
    return p()->m_layout;
}

void MarbleGraphicsItem::setLayout( AbstractMarbleGraphicsLayout *layout )
{
    // Deleting the old layout
    delete p()->m_layout;
    p()->m_layout = layout;
    update();
}

MarbleGraphicsItem::CacheMode MarbleGraphicsItem::cacheMode() const
{
    return p()->m_cacheMode;
}

void MarbleGraphicsItem::setCacheMode( CacheMode mode )
{
    p()->m_cacheMode = mode;
    if ( p()->m_cacheMode == NoCache ) {
        p()->m_repaintNeeded = true;
    }
}

void MarbleGraphicsItem::update()
{
    p()->m_repaintNeeded = true;

    // Update the parent.
    if ( p()->m_parent ) {
        p()->m_parent->update();
    }
}

bool MarbleGraphicsItem::visible() const
{
    return p()->m_visibility;
}

void MarbleGraphicsItem::setVisible( bool visible )
{
    p()->m_visibility = visible;
}

void MarbleGraphicsItem::hide()
{
    setVisible( false );
}

void MarbleGraphicsItem::show()
{
    setVisible( true );
}

void MarbleGraphicsItem::setSize( const QSizeF& size )
{
    p()->m_size = size;
    update();
}

QSizeF MarbleGraphicsItem::contentSize() const
{
    return size();
}

void MarbleGraphicsItem::setContentSize( const QSizeF& size )
{
    setSize( size );
}

QRectF MarbleGraphicsItem::contentRect() const
{
    return QRectF( QPointF( 0, 0 ), contentSize() );
}

void MarbleGraphicsItem::paint( QPainter *painter )
{
    Q_UNUSED( painter );
}

bool MarbleGraphicsItem::eventFilter( QObject *object, QEvent *e )
{
    if ( ! ( e->type() == QEvent::MouseButtonDblClick
             || e->type() == QEvent::MouseMove
             || e->type() == QEvent::MouseButtonPress
             || e->type() == QEvent::MouseButtonRelease ) )
    {
        return false;
    }

    QMouseEvent *event = static_cast<QMouseEvent*> (e);

    if( !p()->m_children.isEmpty() ) {
        QList<QPointF> absolutePositions = p()->absolutePositions();

        foreach( const QPointF& absolutePosition, absolutePositions ) {
            QPoint shiftedPos = event->pos() - absolutePosition.toPoint();

            if ( QRect( QPoint( 0, 0 ), size().toSize() ).contains( shiftedPos ) ) {
                foreach( MarbleGraphicsItem *child, p()->m_children ) {
                    QList<QRectF> childRects = child->d->boundingRects();

                    foreach( const QRectF& childRect, childRects ) {
                        if( childRect.toRect().contains( shiftedPos ) ) {
                            if( child->eventFilter( object, e ) ) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }

    return false;
}

MarbleGraphicsItemPrivate *MarbleGraphicsItem::p() const
{
    return d;
}

void MarbleGraphicsItem::setProjection( ViewportParams *viewport )
{
    p()->setProjection( viewport );
}
<commit_msg>bail out earlier if item is outside viewport<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009-2010 Bastian Holst <bastianholst@gmx.de>
//

#include "MarbleGraphicsItem.h"

#include "MarbleGraphicsItem_p.h"

// Marble
#include "MarbleDebug.h"
#include "ViewportParams.h"

// Qt
#include <QtCore/QList>
#include <QtCore/QSet>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QPixmapCache>
#include <QtGui/QMouseEvent>

using namespace Marble;

MarbleGraphicsItem::MarbleGraphicsItem( MarbleGraphicsItemPrivate *d_ptr )
    : d( d_ptr )
{
}

MarbleGraphicsItem::~MarbleGraphicsItem()
{
    delete d;
}

bool MarbleGraphicsItem::paintEvent( QPainter *painter, const ViewportParams *viewport )
{
    if ( !p()->m_visibility ) {
        return true;
    }

    p()->setProjection( viewport );

    if ( p()->positions().size() == 0 ) {
        return true;
    }

    // Remove the pixmap if it has been requested. This prevents QPixmapCache from being used
    // outside the ui thread.
    if ( p()->m_repaintNeeded ) {
        p()->updateChildPositions();
        p()->m_repaintNeeded = false;
        QPixmapCache::remove( p()->m_cacheKey );
    }

    // At the moment, as GraphicsItems can't be zoomed or rotated ItemCoordinateCache
    // and DeviceCoordianteCache is exactly the same
    if ( ItemCoordinateCache == cacheMode()
         || DeviceCoordinateCache == cacheMode() )
    {
        QPixmap cachePixmap;
        bool pixmapAvailable = QPixmapCache::find( p()->m_cacheKey, &cachePixmap );
        if ( !pixmapAvailable ) {
            QSize neededPixmapSize = size().toSize() + QSize( 1, 1 ); // adding a pixel for rounding errors

            if ( cachePixmap.size() != neededPixmapSize ) {
                if ( size().isValid() && !size().isNull() ) {
                    cachePixmap = QPixmap( neededPixmapSize ).copy();
                }
                else {
                    mDebug() << "Warning: Invalid pixmap size suggested: " << d->m_size;
                }
            }

            cachePixmap.fill( Qt::transparent );
            QPainter pixmapPainter( &cachePixmap );
            // We paint in best quality here, as we only have to paint once.
            pixmapPainter.setRenderHint( QPainter::Antialiasing, true );
            // The cache image will get a 0.5 pixel bounding to save antialiasing effects.
            pixmapPainter.translate( 0.5, 0.5 );
            paint( &pixmapPainter );

            // Paint children
            foreach ( MarbleGraphicsItem *item, p()->m_children ) {
                item->paintEvent( &pixmapPainter, viewport );
            }
            // Update the pixmap in cache
            p()->m_cacheKey = QPixmapCache::insert( cachePixmap );
        }

        foreach( const QPointF& position, p()->positions() ) {
            painter->drawPixmap( position, cachePixmap );
        }
    }
    else {
        foreach( const QPointF& position, p()->positions() ) {
            painter->save();

            painter->translate( position );
            paint( painter );

            // Paint children
            foreach ( MarbleGraphicsItem *item, p()->m_children ) {
                item->paintEvent( painter, viewport );
            }

            painter->restore();
        }
    }

    return true;
}

bool MarbleGraphicsItem::contains( const QPointF& point ) const
{
    foreach( const QRectF& rect, d->boundingRects() ) {
        if( rect.contains( point ) )
            return true;
    }
    return false;
}

QRectF MarbleGraphicsItem::containsRect( const QPointF& point ) const
{
    foreach( const QRectF& rect, d->boundingRects() ) {
        if( rect.contains( point ) )
            return rect;
    }
    return QRectF();
}

QList<QRectF> MarbleGraphicsItemPrivate::boundingRects() const
{
    QList<QRectF> list;

    foreach( QPointF point, positions() ) {
        QRectF rect( point, m_size );
        if( rect.x() < 0 )
            rect.setLeft( 0 );
        if( rect.y() < 0 )
            rect.setTop( 0 );

        list.append( rect );
    }

    return list;
}

QSizeF MarbleGraphicsItem::size() const
{
    return p()->m_size;
}

AbstractMarbleGraphicsLayout *MarbleGraphicsItem::layout() const
{
    return p()->m_layout;
}

void MarbleGraphicsItem::setLayout( AbstractMarbleGraphicsLayout *layout )
{
    // Deleting the old layout
    delete p()->m_layout;
    p()->m_layout = layout;
    update();
}

MarbleGraphicsItem::CacheMode MarbleGraphicsItem::cacheMode() const
{
    return p()->m_cacheMode;
}

void MarbleGraphicsItem::setCacheMode( CacheMode mode )
{
    p()->m_cacheMode = mode;
    if ( p()->m_cacheMode == NoCache ) {
        p()->m_repaintNeeded = true;
    }
}

void MarbleGraphicsItem::update()
{
    p()->m_repaintNeeded = true;

    // Update the parent.
    if ( p()->m_parent ) {
        p()->m_parent->update();
    }
}

bool MarbleGraphicsItem::visible() const
{
    return p()->m_visibility;
}

void MarbleGraphicsItem::setVisible( bool visible )
{
    p()->m_visibility = visible;
}

void MarbleGraphicsItem::hide()
{
    setVisible( false );
}

void MarbleGraphicsItem::show()
{
    setVisible( true );
}

void MarbleGraphicsItem::setSize( const QSizeF& size )
{
    p()->m_size = size;
    update();
}

QSizeF MarbleGraphicsItem::contentSize() const
{
    return size();
}

void MarbleGraphicsItem::setContentSize( const QSizeF& size )
{
    setSize( size );
}

QRectF MarbleGraphicsItem::contentRect() const
{
    return QRectF( QPointF( 0, 0 ), contentSize() );
}

void MarbleGraphicsItem::paint( QPainter *painter )
{
    Q_UNUSED( painter );
}

bool MarbleGraphicsItem::eventFilter( QObject *object, QEvent *e )
{
    if ( ! ( e->type() == QEvent::MouseButtonDblClick
             || e->type() == QEvent::MouseMove
             || e->type() == QEvent::MouseButtonPress
             || e->type() == QEvent::MouseButtonRelease ) )
    {
        return false;
    }

    QMouseEvent *event = static_cast<QMouseEvent*> (e);

    if( !p()->m_children.isEmpty() ) {
        QList<QPointF> absolutePositions = p()->absolutePositions();

        foreach( const QPointF& absolutePosition, absolutePositions ) {
            QPoint shiftedPos = event->pos() - absolutePosition.toPoint();

            if ( QRect( QPoint( 0, 0 ), size().toSize() ).contains( shiftedPos ) ) {
                foreach( MarbleGraphicsItem *child, p()->m_children ) {
                    QList<QRectF> childRects = child->d->boundingRects();

                    foreach( const QRectF& childRect, childRects ) {
                        if( childRect.toRect().contains( shiftedPos ) ) {
                            if( child->eventFilter( object, e ) ) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }

    return false;
}

MarbleGraphicsItemPrivate *MarbleGraphicsItem::p() const
{
    return d;
}

void MarbleGraphicsItem::setProjection( ViewportParams *viewport )
{
    p()->setProjection( viewport );
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <fstream>
#include <json/json.h>
#include <iostream>
#include <regex>
#include <utils.h>
#include "cmdparse.h"
#include "CmdHandler.h"
#include "lynxbot.h"

CmdHandler::CmdHandler(const char *name, const char *channel,
		const char *token, Moderator *mod, URLParser *urlp,
		EventManager *evtp, Giveaway *givp, ConfigReader *cfgr,
		tw::Authenticator *auth)
	: m_name(name), m_channel(channel), m_token(token), m_modp(mod),
	m_parsep(urlp), m_customCmds(NULL), m_evtp(evtp), m_givp(givp),
	m_cfgr(cfgr), m_auth(auth), m_counting(false), m_gen(m_rd()),
	m_status(EXIT_SUCCESS)
{
	populate_cmd();
	m_poll[0] = '\0';

	m_customCmds = new CustomHandler(&m_defaultCmds, &m_cooldowns,
			m_wheel.cmd(), name, channel);
	if (!m_customCmds->isActive()) {
		fprintf(stderr, "Custom commands will be "
				"disabled for this session\n");
		WAIT_INPUT();
	}

	/* read all responses from file */
	m_responding = utils::readJSON("responses.json", m_responses);
	if (m_responding) {
		/* add response cooldowns to TimerManager */
		for (auto &val : m_responses["responses"])
			m_cooldowns.add('_' + val["name"].asString(),
				val["cooldown"].asInt());
	} else {
		fprintf(stderr, "Failed to read responses.json. "
				"Responses disabled for this session\n");
		WAIT_INPUT();
	}

	/* set all command cooldowns */
	for (auto &p : m_defaultCmds)
		m_cooldowns.add(p.first);
	m_cooldowns.add(m_wheel.name());

	/* read extra 8ball responses */
	utils::split(m_cfgr->get("extra8ballresponses"), '\n', m_eightball);

	/* read fashion.json */
	if (!utils::readJSON("fashion.json", m_fashion))
		fprintf(stderr, "Could not read fashion.json\n");

	populate_help();
}

CmdHandler::~CmdHandler()
{
	delete m_customCmds;
}

/* process_cmd: run message as a bot command and store output in out */
void CmdHandler::process_cmd(char *out, char *nick, char *cmdstr, perm_t p)
{
	struct command c;

	c.nick = nick;
	c.privileges = p;
	if (!parse_cmd(cmdstr, &c)) {
		_sprintf(out, MAX_MSG, "%s", cmderr());
		return;
	}

	switch (source(c.argv[0])) {
	case DEFAULT:
		process_default(out, &c);
		break;
	case CUSTOM:
		process_custom(out, &c);
		break;
	default:
		_sprintf(out, MAX_MSG, "/w %s not a bot command: %s",
				nick, c.argv[0]);
		break;
	}
	free_cmd(&c);
}

/* process_resp: test a message against auto response regexes */
int CmdHandler::process_resp(char *out, char *msg, char *nick)
{
	const std::string message(msg);
	std::regex respreg;
	std::smatch match;
	std::string name, regex;

	*out = '\0';
	if (!m_responding)
		return 0;

	/* test the message against all response regexes */
	for (auto &val : m_responses["responses"]) {
		name = '_' + val["name"].asString();
		regex = val["regex"].asString();

		respreg = std::regex(regex, std::regex::icase);
		if (std::regex_search(message.begin(), message.end(), match,
				respreg) && m_cooldowns.ready(name)) {
			m_cooldowns.setUsed(name);
			_sprintf(out, MAX_MSG, "@%s, %s", nick,
					val["response"].asCString());
			return 1;
		}

	}
	return 0;
}

bool CmdHandler::counting() const
{
	return m_counting;
}

/* count: count message in m_messageCounts */
void CmdHandler::count(const char *nick, const char *message)
{
	std::string msg = message;
	std::transform(msg.begin(), msg.end(), msg.begin(), tolower);

	/* if nick is not found */
	if (std::find(m_usersCounted.begin(), m_usersCounted.end(), nick)
			== m_usersCounted.end()) {
		m_usersCounted.push_back(nick);
		if (m_messageCounts.find(msg) == m_messageCounts.end())
			m_messageCounts.insert({ msg, 1 });
		else
			m_messageCounts.find(msg)->second++;
	}
}

/* process_default: run a default command */
void CmdHandler::process_default(char *out, struct command *c)
{
	if (P_ALSUB(c->privileges) || m_cooldowns.ready(c->argv[0])) {
		m_status = (this->*m_defaultCmds[c->argv[0]])(out, c);
		m_cooldowns.setUsed(c->argv[0]);
	} else {
		_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
				c->nick, c->argv[0]);
		m_status = EXIT_FAILURE;
	}
}

/* process_custom: run a custom command */
void CmdHandler::process_custom(char *out, struct command *c)
{
	Json::Value *ccmd;

	ccmd = m_customCmds->getcom(c->argv[0]);
	if ((*ccmd)["active"].asBool() && (P_ALSUB(c->privileges) ||
				m_cooldowns.ready((*ccmd)["cmd"].asString()))) {
		/* set access time and increase uses */
		(*ccmd)["atime"] = (Json::Int64)time(nullptr);
		(*ccmd)["uses"] = (*ccmd)["uses"].asInt() + 1;
		_sprintf(out, MAX_MSG, "%s",
				m_customCmds->format(ccmd, c->nick).c_str());
		m_cooldowns.setUsed((*ccmd)["cmd"].asString());
		m_customCmds->write();
		m_status = EXIT_SUCCESS;
		return;
	}
	if (!(*ccmd)["active"].asBool()) {
		_sprintf(out, MAX_MSG, "/w %s command is currently inactive: %s",
				c->nick, c->argv[0]);
		m_status = EXIT_FAILURE;
		return;
	}
	_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
			c->nick, c->argv[0]);
	m_status = EXIT_FAILURE;
}

/* source: determine whether cmd is a default or custom command */
uint8_t CmdHandler::source(const char *cmd)
{
	if (m_defaultCmds.find(cmd) != m_defaultCmds.end())
		return DEFAULT;
	if (m_customCmds->isActive()) {
		Json::Value *c;
		if (!(c = m_customCmds->getcom(cmd))->empty())
			return CUSTOM;
	}
	return 0;
}

/* getrsn: print the rsn referred to by text into out */
int CmdHandler::getrsn(char *out, size_t len, const char *text,
		const char *nick, int username)
{
	const char *rsn;
	char *s;

	if (username) {
		if (!(rsn = m_rsns.rsn(text))) {
			_sprintf(out, len, "no RSN set for user %s", text);
			return 0;
		}
	} else {
		if (strcmp(text, ".") == 0) {
			if (!(rsn = m_rsns.rsn(nick))) {
				_sprintf(out, len, "no RSN set for user %s",
						nick);
				return 0;
			}
		} else {
			rsn = text;
		}
	}
	_sprintf(out, len, "%s", rsn);
	while ((s = strchr(out, ' ')))
		*s = '_';
	return 1;
}

/* populateCmds: initialize pointers to all default commands */
void CmdHandler::populate_cmd()
{
	/* regular commands */
	m_defaultCmds["8ball"] = &CmdHandler::eightball;
	m_defaultCmds["about"] = &CmdHandler::about;
	m_defaultCmds["active"] = &CmdHandler::active;
	m_defaultCmds["age"] = &CmdHandler::age;
	m_defaultCmds["calc"] = &CmdHandler::calc;
	m_defaultCmds["cgrep"] = &CmdHandler::cgrep;
	m_defaultCmds["cmdinfo"] = &CmdHandler::cmdinfo;
	m_defaultCmds["cml"] = &CmdHandler::cml;
	m_defaultCmds["commands"] = &CmdHandler::manual;
	m_defaultCmds["duck"] = &CmdHandler::duck;
	m_defaultCmds["ehp"] = &CmdHandler::ehp;
	m_defaultCmds["fashiongen"] = &CmdHandler::fashiongen;
	m_defaultCmds["ge"] = &CmdHandler::ge;
	m_defaultCmds["help"] = &CmdHandler::man;
	m_defaultCmds["level"] = &CmdHandler::level;
	m_defaultCmds["lvl"] = &CmdHandler::level;
	m_defaultCmds["man"] = &CmdHandler::man;
	m_defaultCmds["manual"] = &CmdHandler::manual;
	m_defaultCmds["rsn"] = &CmdHandler::rsn;
	m_defaultCmds["submit"] = &CmdHandler::submit;
	m_defaultCmds["twitter"] = &CmdHandler::twitter;
	m_defaultCmds["uptime"] = &CmdHandler::uptime;
	m_defaultCmds["xp"] = &CmdHandler::xp;
	m_defaultCmds[m_wheel.cmd()] = &CmdHandler::wheel;

	/* moderator commands */
	m_defaultCmds["ac"] = &CmdHandler::addcom;
	m_defaultCmds["addcom"] = &CmdHandler::addcom;
	m_defaultCmds["addrec"] = &CmdHandler::addrec;
	m_defaultCmds["ar"] = &CmdHandler::addrec;
	m_defaultCmds["count"] = &CmdHandler::count;
	m_defaultCmds["dc"] = &CmdHandler::delcom;
	m_defaultCmds["delcom"] = &CmdHandler::delcom;
	m_defaultCmds["delrec"] = &CmdHandler::delrec;
	m_defaultCmds["dr"] = &CmdHandler::delrec;
	m_defaultCmds["ec"] = &CmdHandler::editcom;
	m_defaultCmds["editcom"] = &CmdHandler::editcom;
	m_defaultCmds["er"] = &CmdHandler::editrec;
	m_defaultCmds["editrec"] = &CmdHandler::editrec;
	m_defaultCmds["mod"] = &CmdHandler::mod;
	m_defaultCmds["permit"] = &CmdHandler::permit;
	m_defaultCmds["setgiv"] = &CmdHandler::setgiv;
	m_defaultCmds["setrec"] = &CmdHandler::setrec;
	m_defaultCmds["showrec"] = &CmdHandler::showrec;
	m_defaultCmds["sp"] = &CmdHandler::strawpoll;
	m_defaultCmds["status"] = &CmdHandler::status;
	m_defaultCmds["strawpoll"] = &CmdHandler::strawpoll;
	m_defaultCmds["whitelist"] = &CmdHandler::whitelist;
}

/* populateHelp: fill m_help with manual page names */
void CmdHandler::populate_help()
{
	m_help[m_wheel.cmd()] = "selection-wheel";
	m_help["wheel"] = "selection-wheel";
	m_help["ac"] = "addcom";
	m_help["dc"] = "delcom";
	m_help["ec"] = "editcom";
	m_help["ar"] = "addrec";
	m_help["dr"] = "delrec";
	m_help["er"] = "editrec";
	m_help["lvl"] = "level";
	m_help["sp"] = "strawpoll";
	m_help["automated-responses"] = "automated-responses";
	m_help["responses"] = "automated-responses";
	m_help["custom"] = "custom-commands";
	m_help["custom-commands"] = "custom-commands";
	m_help["giveaway"] = "giveaways";
	m_help["giveaways"] = "giveaways";
	m_help["help"] = "man";
	m_help["mod"] = "moderation";
	m_help["moderation"] = "moderation";
	m_help["moderator"] = "moderation";
	m_help["recurring"] = "recurring-messages";
	m_help["recurring-messages"] = "recurring-messages";
	m_help["rsns"] = "rsn-management";
	m_help["rsn-management"] = "rsn-management";
	m_help["submessage"] = "subscriber-message";
	m_help["tweet"] = "tweet-reader";
	m_help["tweet-reader"] = "tweet-reader";
	m_help["twitter"] = "tweet-reader";
	m_help["twitch"] = "twitch-authorization";
	m_help["twitchauth"] = "twitch-authorization";
	m_help["twitch-autorization"] = "twitch-authorization";
	m_help["auth"] = "twitch-authorization";
	m_help["authorization"] = "twitch-authorization";
}
<commit_msg>Change 'mod' man link to mod command<commit_after>#include <algorithm>
#include <fstream>
#include <json/json.h>
#include <iostream>
#include <regex>
#include <utils.h>
#include "cmdparse.h"
#include "CmdHandler.h"
#include "lynxbot.h"

CmdHandler::CmdHandler(const char *name, const char *channel,
		const char *token, Moderator *mod, URLParser *urlp,
		EventManager *evtp, Giveaway *givp, ConfigReader *cfgr,
		tw::Authenticator *auth)
	: m_name(name), m_channel(channel), m_token(token), m_modp(mod),
	m_parsep(urlp), m_customCmds(NULL), m_evtp(evtp), m_givp(givp),
	m_cfgr(cfgr), m_auth(auth), m_counting(false), m_gen(m_rd()),
	m_status(EXIT_SUCCESS)
{
	populate_cmd();
	m_poll[0] = '\0';

	m_customCmds = new CustomHandler(&m_defaultCmds, &m_cooldowns,
			m_wheel.cmd(), name, channel);
	if (!m_customCmds->isActive()) {
		fprintf(stderr, "Custom commands will be "
				"disabled for this session\n");
		WAIT_INPUT();
	}

	/* read all responses from file */
	m_responding = utils::readJSON("responses.json", m_responses);
	if (m_responding) {
		/* add response cooldowns to TimerManager */
		for (auto &val : m_responses["responses"])
			m_cooldowns.add('_' + val["name"].asString(),
				val["cooldown"].asInt());
	} else {
		fprintf(stderr, "Failed to read responses.json. "
				"Responses disabled for this session\n");
		WAIT_INPUT();
	}

	/* set all command cooldowns */
	for (auto &p : m_defaultCmds)
		m_cooldowns.add(p.first);
	m_cooldowns.add(m_wheel.name());

	/* read extra 8ball responses */
	utils::split(m_cfgr->get("extra8ballresponses"), '\n', m_eightball);

	/* read fashion.json */
	if (!utils::readJSON("fashion.json", m_fashion))
		fprintf(stderr, "Could not read fashion.json\n");

	populate_help();
}

CmdHandler::~CmdHandler()
{
	delete m_customCmds;
}

/* process_cmd: run message as a bot command and store output in out */
void CmdHandler::process_cmd(char *out, char *nick, char *cmdstr, perm_t p)
{
	struct command c;

	c.nick = nick;
	c.privileges = p;
	if (!parse_cmd(cmdstr, &c)) {
		_sprintf(out, MAX_MSG, "%s", cmderr());
		return;
	}

	switch (source(c.argv[0])) {
	case DEFAULT:
		process_default(out, &c);
		break;
	case CUSTOM:
		process_custom(out, &c);
		break;
	default:
		_sprintf(out, MAX_MSG, "/w %s not a bot command: %s",
				nick, c.argv[0]);
		break;
	}
	free_cmd(&c);
}

/* process_resp: test a message against auto response regexes */
int CmdHandler::process_resp(char *out, char *msg, char *nick)
{
	const std::string message(msg);
	std::regex respreg;
	std::smatch match;
	std::string name, regex;

	*out = '\0';
	if (!m_responding)
		return 0;

	/* test the message against all response regexes */
	for (auto &val : m_responses["responses"]) {
		name = '_' + val["name"].asString();
		regex = val["regex"].asString();

		respreg = std::regex(regex, std::regex::icase);
		if (std::regex_search(message.begin(), message.end(), match,
				respreg) && m_cooldowns.ready(name)) {
			m_cooldowns.setUsed(name);
			_sprintf(out, MAX_MSG, "@%s, %s", nick,
					val["response"].asCString());
			return 1;
		}

	}
	return 0;
}

bool CmdHandler::counting() const
{
	return m_counting;
}

/* count: count message in m_messageCounts */
void CmdHandler::count(const char *nick, const char *message)
{
	std::string msg = message;
	std::transform(msg.begin(), msg.end(), msg.begin(), tolower);

	/* if nick is not found */
	if (std::find(m_usersCounted.begin(), m_usersCounted.end(), nick)
			== m_usersCounted.end()) {
		m_usersCounted.push_back(nick);
		if (m_messageCounts.find(msg) == m_messageCounts.end())
			m_messageCounts.insert({ msg, 1 });
		else
			m_messageCounts.find(msg)->second++;
	}
}

/* process_default: run a default command */
void CmdHandler::process_default(char *out, struct command *c)
{
	if (P_ALSUB(c->privileges) || m_cooldowns.ready(c->argv[0])) {
		m_status = (this->*m_defaultCmds[c->argv[0]])(out, c);
		m_cooldowns.setUsed(c->argv[0]);
	} else {
		_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
				c->nick, c->argv[0]);
		m_status = EXIT_FAILURE;
	}
}

/* process_custom: run a custom command */
void CmdHandler::process_custom(char *out, struct command *c)
{
	Json::Value *ccmd;

	ccmd = m_customCmds->getcom(c->argv[0]);
	if ((*ccmd)["active"].asBool() && (P_ALSUB(c->privileges) ||
				m_cooldowns.ready((*ccmd)["cmd"].asString()))) {
		/* set access time and increase uses */
		(*ccmd)["atime"] = (Json::Int64)time(nullptr);
		(*ccmd)["uses"] = (*ccmd)["uses"].asInt() + 1;
		_sprintf(out, MAX_MSG, "%s",
				m_customCmds->format(ccmd, c->nick).c_str());
		m_cooldowns.setUsed((*ccmd)["cmd"].asString());
		m_customCmds->write();
		m_status = EXIT_SUCCESS;
		return;
	}
	if (!(*ccmd)["active"].asBool()) {
		_sprintf(out, MAX_MSG, "/w %s command is currently inactive: %s",
				c->nick, c->argv[0]);
		m_status = EXIT_FAILURE;
		return;
	}
	_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
			c->nick, c->argv[0]);
	m_status = EXIT_FAILURE;
}

/* source: determine whether cmd is a default or custom command */
uint8_t CmdHandler::source(const char *cmd)
{
	if (m_defaultCmds.find(cmd) != m_defaultCmds.end())
		return DEFAULT;
	if (m_customCmds->isActive()) {
		Json::Value *c;
		if (!(c = m_customCmds->getcom(cmd))->empty())
			return CUSTOM;
	}
	return 0;
}

/* getrsn: print the rsn referred to by text into out */
int CmdHandler::getrsn(char *out, size_t len, const char *text,
		const char *nick, int username)
{
	const char *rsn;
	char *s;

	if (username) {
		if (!(rsn = m_rsns.rsn(text))) {
			_sprintf(out, len, "no RSN set for user %s", text);
			return 0;
		}
	} else {
		if (strcmp(text, ".") == 0) {
			if (!(rsn = m_rsns.rsn(nick))) {
				_sprintf(out, len, "no RSN set for user %s",
						nick);
				return 0;
			}
		} else {
			rsn = text;
		}
	}
	_sprintf(out, len, "%s", rsn);
	while ((s = strchr(out, ' ')))
		*s = '_';
	return 1;
}

/* populateCmds: initialize pointers to all default commands */
void CmdHandler::populate_cmd()
{
	/* regular commands */
	m_defaultCmds["8ball"] = &CmdHandler::eightball;
	m_defaultCmds["about"] = &CmdHandler::about;
	m_defaultCmds["active"] = &CmdHandler::active;
	m_defaultCmds["age"] = &CmdHandler::age;
	m_defaultCmds["calc"] = &CmdHandler::calc;
	m_defaultCmds["cgrep"] = &CmdHandler::cgrep;
	m_defaultCmds["cmdinfo"] = &CmdHandler::cmdinfo;
	m_defaultCmds["cml"] = &CmdHandler::cml;
	m_defaultCmds["commands"] = &CmdHandler::manual;
	m_defaultCmds["duck"] = &CmdHandler::duck;
	m_defaultCmds["ehp"] = &CmdHandler::ehp;
	m_defaultCmds["fashiongen"] = &CmdHandler::fashiongen;
	m_defaultCmds["ge"] = &CmdHandler::ge;
	m_defaultCmds["help"] = &CmdHandler::man;
	m_defaultCmds["level"] = &CmdHandler::level;
	m_defaultCmds["lvl"] = &CmdHandler::level;
	m_defaultCmds["man"] = &CmdHandler::man;
	m_defaultCmds["manual"] = &CmdHandler::manual;
	m_defaultCmds["rsn"] = &CmdHandler::rsn;
	m_defaultCmds["submit"] = &CmdHandler::submit;
	m_defaultCmds["twitter"] = &CmdHandler::twitter;
	m_defaultCmds["uptime"] = &CmdHandler::uptime;
	m_defaultCmds["xp"] = &CmdHandler::xp;
	m_defaultCmds[m_wheel.cmd()] = &CmdHandler::wheel;

	/* moderator commands */
	m_defaultCmds["ac"] = &CmdHandler::addcom;
	m_defaultCmds["addcom"] = &CmdHandler::addcom;
	m_defaultCmds["addrec"] = &CmdHandler::addrec;
	m_defaultCmds["ar"] = &CmdHandler::addrec;
	m_defaultCmds["count"] = &CmdHandler::count;
	m_defaultCmds["dc"] = &CmdHandler::delcom;
	m_defaultCmds["delcom"] = &CmdHandler::delcom;
	m_defaultCmds["delrec"] = &CmdHandler::delrec;
	m_defaultCmds["dr"] = &CmdHandler::delrec;
	m_defaultCmds["ec"] = &CmdHandler::editcom;
	m_defaultCmds["editcom"] = &CmdHandler::editcom;
	m_defaultCmds["er"] = &CmdHandler::editrec;
	m_defaultCmds["editrec"] = &CmdHandler::editrec;
	m_defaultCmds["mod"] = &CmdHandler::mod;
	m_defaultCmds["permit"] = &CmdHandler::permit;
	m_defaultCmds["setgiv"] = &CmdHandler::setgiv;
	m_defaultCmds["setrec"] = &CmdHandler::setrec;
	m_defaultCmds["showrec"] = &CmdHandler::showrec;
	m_defaultCmds["sp"] = &CmdHandler::strawpoll;
	m_defaultCmds["status"] = &CmdHandler::status;
	m_defaultCmds["strawpoll"] = &CmdHandler::strawpoll;
	m_defaultCmds["whitelist"] = &CmdHandler::whitelist;
}

/* populateHelp: fill m_help with manual page names */
void CmdHandler::populate_help()
{
	m_help[m_wheel.cmd()] = "selection-wheel";
	m_help["wheel"] = "selection-wheel";
	m_help["ac"] = "addcom";
	m_help["dc"] = "delcom";
	m_help["ec"] = "editcom";
	m_help["ar"] = "addrec";
	m_help["dr"] = "delrec";
	m_help["er"] = "editrec";
	m_help["lvl"] = "level";
	m_help["sp"] = "strawpoll";
	m_help["automated-responses"] = "automated-responses";
	m_help["responses"] = "automated-responses";
	m_help["custom"] = "custom-commands";
	m_help["custom-commands"] = "custom-commands";
	m_help["giveaway"] = "giveaways";
	m_help["giveaways"] = "giveaways";
	m_help["help"] = "man";
	m_help["moderation"] = "moderation";
	m_help["moderator"] = "moderation";
	m_help["recurring"] = "recurring-messages";
	m_help["recurring-messages"] = "recurring-messages";
	m_help["rsns"] = "rsn-management";
	m_help["rsn-management"] = "rsn-management";
	m_help["submessage"] = "subscriber-message";
	m_help["tweet"] = "tweet-reader";
	m_help["tweet-reader"] = "tweet-reader";
	m_help["twitter"] = "tweet-reader";
	m_help["twitch"] = "twitch-authorization";
	m_help["twitchauth"] = "twitch-authorization";
	m_help["twitch-autorization"] = "twitch-authorization";
	m_help["auth"] = "twitch-authorization";
	m_help["authorization"] = "twitch-authorization";
}
<|endoftext|>


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

#ifndef _SVDTXHDL_HXX
#define _SVDTXHDL_HXX

#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif

#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif

//************************************************************
//   Vorausdeklarationen
//************************************************************

class SdrOutliner;
class DrawPortionInfo;
class SdrTextObj;
class SdrObjGroup;
class SdrModel;
class XOutputDevice;

//************************************************************
//   ImpTextPortionHandler
//************************************************************

class ImpTextPortionHandler
{
    VirtualDevice               aVDev;
    Rectangle                   aFormTextBoundRect;
    SdrOutliner&                rOutliner;
    const SdrTextObj&           rTextObj;
    XOutputDevice*          pXOut;

    // Variablen fuer ConvertToPathObj
    SdrObjGroup*                pGroup;
    SdrModel*                   pModel;
    FASTBOOL                    bToPoly;

    // Variablen fuer DrawFitText
    Point                       aPos;
    Fraction                    aXFact;
    Fraction                    aYFact;

    // Variablen fuer DrawTextToPath
    // #101498#
    //Polygon                       aPoly;
    //long                      nTextWidth;
    ULONG                       nParagraph;
    BOOL                        bToLastPoint;
    BOOL                        bDraw;
    void*                       mpRecordPortions;

private:
    // #101498#
    void SortedAddFormTextRecordPortion(DrawPortionInfo* pInfo);
    void DrawFormTextRecordPortions(Polygon aPoly);
    void ClearFormTextRecordPortions();
    sal_uInt32 GetFormTextPortionsLength(OutputDevice* pOut);

public:
    ImpTextPortionHandler(SdrOutliner& rOutln, const SdrTextObj& rTxtObj);

    void ConvertToPathObj(SdrObjGroup& rGroup, FASTBOOL bToPoly);
    void DrawFitText(XOutputDevice& rXOut, const Point& rPos, const Fraction& rXFact);
    void DrawTextToPath(XOutputDevice& rXOut, FASTBOOL bDrawEffect=TRUE);

    // wird von DrawTextToPath() gesetzt:
    const Rectangle& GetFormTextBoundRect() { return aFormTextBoundRect; }

    DECL_LINK(ConvertHdl,DrawPortionInfo*);
    DECL_LINK(FitTextDrawHdl,DrawPortionInfo*);

    // #101498#
    DECL_LINK(FormTextRecordPortionHdl, DrawPortionInfo*);
    //DECL_LINK(FormTextWidthHdl,DrawPortionInfo*);
    //DECL_LINK(FormTextDrawHdl,DrawPortionInfo*);
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDTXHDL_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.596); FILE MERGED 2005/09/05 14:27:28 rt 1.4.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdtxhdl.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:41:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVDTXHDL_HXX
#define _SVDTXHDL_HXX

#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif

#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif

//************************************************************
//   Vorausdeklarationen
//************************************************************

class SdrOutliner;
class DrawPortionInfo;
class SdrTextObj;
class SdrObjGroup;
class SdrModel;
class XOutputDevice;

//************************************************************
//   ImpTextPortionHandler
//************************************************************

class ImpTextPortionHandler
{
    VirtualDevice               aVDev;
    Rectangle                   aFormTextBoundRect;
    SdrOutliner&                rOutliner;
    const SdrTextObj&           rTextObj;
    XOutputDevice*          pXOut;

    // Variablen fuer ConvertToPathObj
    SdrObjGroup*                pGroup;
    SdrModel*                   pModel;
    FASTBOOL                    bToPoly;

    // Variablen fuer DrawFitText
    Point                       aPos;
    Fraction                    aXFact;
    Fraction                    aYFact;

    // Variablen fuer DrawTextToPath
    // #101498#
    //Polygon                       aPoly;
    //long                      nTextWidth;
    ULONG                       nParagraph;
    BOOL                        bToLastPoint;
    BOOL                        bDraw;
    void*                       mpRecordPortions;

private:
    // #101498#
    void SortedAddFormTextRecordPortion(DrawPortionInfo* pInfo);
    void DrawFormTextRecordPortions(Polygon aPoly);
    void ClearFormTextRecordPortions();
    sal_uInt32 GetFormTextPortionsLength(OutputDevice* pOut);

public:
    ImpTextPortionHandler(SdrOutliner& rOutln, const SdrTextObj& rTxtObj);

    void ConvertToPathObj(SdrObjGroup& rGroup, FASTBOOL bToPoly);
    void DrawFitText(XOutputDevice& rXOut, const Point& rPos, const Fraction& rXFact);
    void DrawTextToPath(XOutputDevice& rXOut, FASTBOOL bDrawEffect=TRUE);

    // wird von DrawTextToPath() gesetzt:
    const Rectangle& GetFormTextBoundRect() { return aFormTextBoundRect; }

    DECL_LINK(ConvertHdl,DrawPortionInfo*);
    DECL_LINK(FitTextDrawHdl,DrawPortionInfo*);

    // #101498#
    DECL_LINK(FormTextRecordPortionHdl, DrawPortionInfo*);
    //DECL_LINK(FormTextWidthHdl,DrawPortionInfo*);
    //DECL_LINK(FormTextDrawHdl,DrawPortionInfo*);
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDTXHDL_HXX

<|endoftext|>


<commit_before>#include "DrawAttack.hpp"
#include "States/TitleState.hpp"
#include "States/ServerSelectState.hpp"
#include "States/PlayState.hpp"
#include "States/DisconnectedState.hpp"
#include "States/NameSelectState.hpp"

using namespace cpp3ds;
using namespace TweenEngine;

namespace DrawAttack {

DrawAttack::DrawAttack()
: m_stateStack(State::Context(m_client, m_name, m_data))
{
	textFPS.setColor(Color::Blue);

	m_stateStack.registerState<TitleState>(States::Title);
	m_stateStack.registerState<ServerSelectState>(States::ServerSelect);
	m_stateStack.registerState<NameSelectState>(States::NameSelect);
	m_stateStack.registerState<PlayState>(States::Play);
	m_stateStack.registerState<DisconnectedState>(States::Disconnected);
	m_stateStack.pushState(States::ServerSelect);
}

DrawAttack::~DrawAttack()
{
	// Destructor called when game exits
}

void DrawAttack::update(float delta)
{
	if (m_stateStack.isEmpty())
		exit();

	static int i;
	if (i++ % 10 == 0) {
		textFPS.setString(_("%.1f fps", 1.f / delta));
		textFPS.setPosition(395 - textFPS.getGlobalBounds().width, 200);
	}

	m_stateStack.update(delta);
}

void DrawAttack::processEvent(Event& event)
{
	m_stateStack.processEvent(event);
}

void DrawAttack::renderTopScreen(Window& window)
{
	window.clear(Color::White);
	m_stateStack.renderTopScreen(window);
	window.setView(window.getDefaultView());
	window.draw(textFPS);
}

void DrawAttack::renderBottomScreen(Window& window)
{
	window.clear(Color(100, 100, 220));
	m_stateStack.renderBottomScreen(window);
}

} // namespace DrawAttack
<commit_msg>Fix state stack bug exiting prematurely<commit_after>#include "DrawAttack.hpp"
#include "States/TitleState.hpp"
#include "States/ServerSelectState.hpp"
#include "States/PlayState.hpp"
#include "States/DisconnectedState.hpp"
#include "States/NameSelectState.hpp"

using namespace cpp3ds;
using namespace TweenEngine;

namespace DrawAttack {

DrawAttack::DrawAttack()
: m_stateStack(State::Context(m_client, m_name, m_data))
{
	textFPS.setColor(Color::Blue);

	m_stateStack.registerState<TitleState>(States::Title);
	m_stateStack.registerState<ServerSelectState>(States::ServerSelect);
	m_stateStack.registerState<NameSelectState>(States::NameSelect);
	m_stateStack.registerState<PlayState>(States::Play);
	m_stateStack.registerState<DisconnectedState>(States::Disconnected);
	m_stateStack.pushState(States::ServerSelect);
}

DrawAttack::~DrawAttack()
{
	// Destructor called when game exits
}

void DrawAttack::update(float delta)
{
	// Need to update before checking if empty
	m_stateStack.update(delta);
	if (m_stateStack.isEmpty())
		exit();

	static int i;
	if (i++ % 10 == 0) {
		textFPS.setString(_("%.1f fps", 1.f / delta));
		textFPS.setPosition(395 - textFPS.getGlobalBounds().width, 200);
	}
}

void DrawAttack::processEvent(Event& event)
{
	m_stateStack.processEvent(event);
}

void DrawAttack::renderTopScreen(Window& window)
{
	window.clear(Color::White);
	m_stateStack.renderTopScreen(window);
	window.setView(window.getDefaultView());
	window.draw(textFPS);
}

void DrawAttack::renderBottomScreen(Window& window)
{
	window.clear(Color(100, 100, 220));
	m_stateStack.renderBottomScreen(window);
}

} // namespace DrawAttack
<|endoftext|>


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

#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif

class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;

const UINT32 SWGInventor =  UINT32('S')*0x00000001+
                            UINT32('W')*0x00000100+
                            UINT32('G')*0x00010000;

const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst            = 0x0001;

//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.

class SwFlyDrawObj : public SdrObject
{
    virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();

public:
    TYPEINFO();

    SwFlyDrawObj();
    ~SwFlyDrawObj();

    virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;

    //Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
    //(per Factory).
    virtual UINT32 GetObjInventor()     const;
    virtual UINT16 GetObjIdentifier()   const;
    virtual UINT16 GetObjVersion()      const;
};

//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).

class SwVirtFlyDrawObj : public SdrVirtObj
{
    SwFlyFrm *pFlyFrm;

public:
    TYPEINFO();

    SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
    ~SwVirtFlyDrawObj();

    //Ueberladene Methoden der Basisklasse SdrVirtObj
    virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
    virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
    virtual void     TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;

    //Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
    virtual const Rectangle& GetCurrentBoundRect() const;
    virtual       void       RecalcBoundRect();
    virtual       void       RecalcSnapRect();
    virtual const Rectangle& GetSnapRect()  const;
    virtual       void       SetSnapRect(const Rectangle& rRect);
    virtual       void       NbcSetSnapRect(const Rectangle& rRect);
    virtual const Rectangle& GetLogicRect() const;
    virtual       void       SetLogicRect(const Rectangle& rRect);
    virtual       void       NbcSetLogicRect(const Rectangle& rRect);
    virtual       void       TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
    virtual       void       NbcMove  (const Size& rSiz);
    virtual       void       NbcResize(const Point& rRef, const Fraction& xFact,
                                       const Fraction& yFact);
    virtual       void       Move  (const Size& rSiz);
    virtual       void       Resize(const Point& rRef, const Fraction& xFact,
                                    const Fraction& yFact);

    const SwFrmFmt *GetFmt() const;
          SwFrmFmt *GetFmt();

    // Get Methoden fuer die Fly Verpointerung
          SwFlyFrm* GetFlyFrm()         { return pFlyFrm; }
    const SwFlyFrm* GetFlyFrm() const   { return pFlyFrm; }

    void SetRect() const;

    // ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
    virtual FASTBOOL HasMacro() const;
    virtual SdrObject* CheckMacroHit       (const SdrObjMacroHitRec& rRec) const;
    virtual Pointer    GetMacroPointer     (const SdrObjMacroHitRec& rRec) const;
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.484); FILE MERGED 2005/09/05 13:39:54 rt 1.6.484.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dflyobj.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:44:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _DFLYOBJ_HXX
#define _DFLYOBJ_HXX

#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif

class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;

const UINT32 SWGInventor =  UINT32('S')*0x00000001+
                            UINT32('W')*0x00000100+
                            UINT32('G')*0x00010000;

const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst            = 0x0001;

//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.

class SwFlyDrawObj : public SdrObject
{
    virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();

public:
    TYPEINFO();

    SwFlyDrawObj();
    ~SwFlyDrawObj();

    virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;

    //Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
    //(per Factory).
    virtual UINT32 GetObjInventor()     const;
    virtual UINT16 GetObjIdentifier()   const;
    virtual UINT16 GetObjVersion()      const;
};

//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).

class SwVirtFlyDrawObj : public SdrVirtObj
{
    SwFlyFrm *pFlyFrm;

public:
    TYPEINFO();

    SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
    ~SwVirtFlyDrawObj();

    //Ueberladene Methoden der Basisklasse SdrVirtObj
    virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
    virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
    virtual void     TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;

    //Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
    virtual const Rectangle& GetCurrentBoundRect() const;
    virtual       void       RecalcBoundRect();
    virtual       void       RecalcSnapRect();
    virtual const Rectangle& GetSnapRect()  const;
    virtual       void       SetSnapRect(const Rectangle& rRect);
    virtual       void       NbcSetSnapRect(const Rectangle& rRect);
    virtual const Rectangle& GetLogicRect() const;
    virtual       void       SetLogicRect(const Rectangle& rRect);
    virtual       void       NbcSetLogicRect(const Rectangle& rRect);
    virtual       void       TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
    virtual       void       NbcMove  (const Size& rSiz);
    virtual       void       NbcResize(const Point& rRef, const Fraction& xFact,
                                       const Fraction& yFact);
    virtual       void       Move  (const Size& rSiz);
    virtual       void       Resize(const Point& rRef, const Fraction& xFact,
                                    const Fraction& yFact);

    const SwFrmFmt *GetFmt() const;
          SwFrmFmt *GetFmt();

    // Get Methoden fuer die Fly Verpointerung
          SwFlyFrm* GetFlyFrm()         { return pFlyFrm; }
    const SwFlyFrm* GetFlyFrm() const   { return pFlyFrm; }

    void SetRect() const;

    // ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
    virtual FASTBOOL HasMacro() const;
    virtual SdrObject* CheckMacroHit       (const SdrObjMacroHitRec& rRec) const;
    virtual Pointer    GetMacroPointer     (const SdrObjMacroHitRec& rRec) const;
};

#endif
<|endoftext|>