<commit_before>/*************************************************************************
 *
 *  $RCSfile: FilterContainer.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: tra $ $Date: 2001-06-28 11:13:03 $
 *
 *  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 _FILTER_CONTAINER_HXX_
#define _FILTER_CONTAINER_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#include <vector>

//------------------------------------------------------
// helper class, only useable by OFilterContainer
//------------------------------------------------------

class CFilterContainer
{
public:
    // defines a filter entry which is made of a name and a filter value
    // e.g. 'Text *.txt'
    typedef std::pair< rtl::OUString, rtl::OUString > FILTER_ENTRY_T;

public:
    explicit CFilterContainer( sal_Int32 initSize = 0 );

    // add a new filter
    // returns true if the filter was successfully added
    // returns false if duplicates are not allowed and
    // the filter is already in the container
    sal_Bool SAL_CALL addFilter(
        const ::rtl::OUString& aName,
        const ::rtl::OUString& aFilter,
        sal_Bool bAllowDuplicates = sal_False );

    // delete the specified filter returns true on
    // success and false if the filter was not found
    sal_Bool SAL_CALL delFilter( const ::rtl::OUString& aName );

    // the number of filter already added
    sal_Int32 SAL_CALL numFilter( );

    // clear all entries
    void SAL_CALL empty( );

    // retrieve a filter from the container both methods
    // return true on success and false if the specified
    // filter was not found
    sal_Bool SAL_CALL getFilter( const ::rtl::OUString& aName, ::rtl::OUString& theFilter ) const;
    sal_Bool SAL_CALL getFilter( sal_Int32 aIndex, ::rtl::OUString& theFilter ) const;

    // returns the position of the specified filter or -1
    // if the filter was not found
    sal_Int32 SAL_CALL getFilterPos( const ::rtl::OUString& aName ) const;

    // starts enumerating the filter in the container
    void SAL_CALL beginEnumFilter( );

    // returns true if another filter has been retrieved
    sal_Bool SAL_CALL getNextFilter( FILTER_ENTRY_T& nextFilterEntry );

protected:
    typedef std::vector< FILTER_ENTRY_T > FILTER_VECTOR_T;

private:
    // prevent copy and assignment
    CFilterContainer( const CFilterContainer& );
    CFilterContainer& SAL_CALL operator=( const CFilterContainer& );

    sal_Int32 SAL_CALL getFilterTagPos( const ::rtl::OUString& aName ) const;

private:
    FILTER_VECTOR_T                 m_vFilters;
    FILTER_VECTOR_T::const_iterator m_iter;
    sal_Bool                        m_bIterInitialized;
};

//----------------------------------------------------------------
// a helper function to create a filter buffer in the format
// the Win32 API requires, e.g. "Text\0*.txt\0Doc\0*.doc;*xls\0\0"
//----------------------------------------------------------------

rtl::OUString SAL_CALL makeWinFilterBuffer( CFilterContainer& aFilterContainer );

#endif<commit_msg>INTEGRATION: CWS rt02 (1.1.72); FILE MERGED 2003/10/01 10:41:52 rt 1.1.72.1: #i19697# No newline at end of file<commit_after>/*************************************************************************
 *
 *  $RCSfile: FilterContainer.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 15:52:26 $
 *
 *  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 _FILTER_CONTAINER_HXX_
#define _FILTER_CONTAINER_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#include <vector>

//------------------------------------------------------
// helper class, only useable by OFilterContainer
//------------------------------------------------------

class CFilterContainer
{
public:
    // defines a filter entry which is made of a name and a filter value
    // e.g. 'Text *.txt'
    typedef std::pair< rtl::OUString, rtl::OUString > FILTER_ENTRY_T;

public:
    explicit CFilterContainer( sal_Int32 initSize = 0 );

    // add a new filter
    // returns true if the filter was successfully added
    // returns false if duplicates are not allowed and
    // the filter is already in the container
    sal_Bool SAL_CALL addFilter(
        const ::rtl::OUString& aName,
        const ::rtl::OUString& aFilter,
        sal_Bool bAllowDuplicates = sal_False );

    // delete the specified filter returns true on
    // success and false if the filter was not found
    sal_Bool SAL_CALL delFilter( const ::rtl::OUString& aName );

    // the number of filter already added
    sal_Int32 SAL_CALL numFilter( );

    // clear all entries
    void SAL_CALL empty( );

    // retrieve a filter from the container both methods
    // return true on success and false if the specified
    // filter was not found
    sal_Bool SAL_CALL getFilter( const ::rtl::OUString& aName, ::rtl::OUString& theFilter ) const;
    sal_Bool SAL_CALL getFilter( sal_Int32 aIndex, ::rtl::OUString& theFilter ) const;

    // returns the position of the specified filter or -1
    // if the filter was not found
    sal_Int32 SAL_CALL getFilterPos( const ::rtl::OUString& aName ) const;

    // starts enumerating the filter in the container
    void SAL_CALL beginEnumFilter( );

    // returns true if another filter has been retrieved
    sal_Bool SAL_CALL getNextFilter( FILTER_ENTRY_T& nextFilterEntry );

protected:
    typedef std::vector< FILTER_ENTRY_T > FILTER_VECTOR_T;

private:
    // prevent copy and assignment
    CFilterContainer( const CFilterContainer& );
    CFilterContainer& SAL_CALL operator=( const CFilterContainer& );

    sal_Int32 SAL_CALL getFilterTagPos( const ::rtl::OUString& aName ) const;

private:
    FILTER_VECTOR_T                 m_vFilters;
    FILTER_VECTOR_T::const_iterator m_iter;
    sal_Bool                        m_bIterInitialized;
};

//----------------------------------------------------------------
// a helper function to create a filter buffer in the format
// the Win32 API requires, e.g. "Text\0*.txt\0Doc\0*.doc;*xls\0\0"
//----------------------------------------------------------------

rtl::OUString SAL_CALL makeWinFilterBuffer( CFilterContainer& aFilterContainer );

#endif
<|endoftext|>


<commit_before>#include <Engine.h>

Engine::Engine(const int argc, const char** argv, const std::string& _name) :
        game(_name)
{
    INFO("Initializing Engine with game data in '%s", game.c_str());

    showBuildInfo(argv[0]);

    data_dir = game;

    readConfig();

    INFO("Creating %dx%d render target", renderWidth, renderHeight);
    screen.create(renderWidth, renderHeight);

    createWindow(config.fullscreen);

    spritesMutex.lock();
    INFO("Creating entities");
    player = std::make_shared<Sprite>(data_dir + "/player.yaml");
    player->setPosition(renderWidth * 1 / 2, renderHeight * 3 / 4);
    sprites.push_back(player);
    INFO("Created player");
    enemy = std::make_shared<Sprite>(data_dir + "/enemy.yaml");
    enemy->setPosition(renderWidth * 1 / 2, renderHeight * 1 / 4);
    sprites.push_back(enemy);
    INFO("Created enemy");
    spritesMutex.unlock();

    isReady = true;
    INFO("Initialization Complete");
}

bool Engine::ready() {
    if (isReady) {
        INFO("Game of '%s' is ready", config.name.c_str());
    } else {

    }
    return isReady;
}

bool Engine::run() {
    INFO("Starting a game of '%s'", config.name.c_str());

    INFO("Creating Render thread");
    releaseWindow();
    renderThread = std::make_unique<std::thread>(&Engine::renderLoop, this);

    INFO("Initializing event loop");
    sf::Int32 updateHz = 60;
    sf::Int32 updateWaitTime = 1'000'000 / updateHz;
    sf::Clock gameClock;
    sf::Time elapsedTime;
    sf::Time lastUpdateTime;
    sf::Int64 totalUpdateTime = 0;
    sf::Int64 averageUpdateTime;
    sf::Int32 updateCount = 0;
    INFO("Starting event loop");
    running = true;
    while (running) {
        elapsedTime = gameClock.restart();
        processEvents();
        update(elapsedTime);
        //compute
        lastUpdateTime = gameClock.getElapsedTime();
        totalUpdateTime += lastUpdateTime.asMilliseconds();
        averageUpdateTime = totalUpdateTime / ++updateCount;
        // log the average time per update every 1 seconds
        if (updateCount % (60 * 1) == 0) {
            DBUG("Average update time: %d ms", averageUpdateTime);
        }
        // update at approximately 60 Hz (16666us minus time taken by last update(
        sf::sleep(sf::microseconds(updateWaitTime - lastUpdateTime.asMicroseconds()));
    }
    INFO("Stopped event loop");
    INFO("Joining render thread");
    renderThread->join();
    INFO("Game of '%s' ended successfully", config.name.c_str());
    return true;
}

void Engine::showBuildInfo(const char* name) {
    const uint32_t majorVersion = 0;
    const uint32_t minorVersion = 4;
    const uint32_t revision = 1;

    INFO("%s %d.%d.%d %s %s", name, majorVersion, minorVersion, revision, __DATE__, __TIME__);

    INFO("SFML %d.%d", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);

// what compiler are we using? just because
#ifdef __MINGW32__
#ifdef __MINGW64__
    INFO("MinGW-w64 %d.%d", __MINGW64_VERSION_MAJOR, __MINGW64_VERSION_MINOR);
#else
    INFO("MinGW %d.%d", __MINGW32_MAJOR_VERSION, __MINGW32_MINOR_VERSION);
#endif
#endif

#ifdef __clang__
    INFO("CLang %d.%d.%d", __clang_major__, __clang_minor__, __clang_patchlevel__);
#endif

#ifdef __GNUG__
    INFO("GCC %s", __VERSION__);
#endif

#ifdef MSC_VER
    INFO("Visual C++ %s", _MCS_VER);
#endif
}

void Engine::readConfig() {
    std::string configFilename = data_dir + "/config.yaml";
    INFO("Reading config from '%s'", configFilename.c_str());
    try {
        YAML::Node yamlConfig = YAML::LoadFile(configFilename);
        config.name = yamlConfig["name"].as<std::string>(game);
        config.width = yamlConfig["width"].as<uint32_t>(config.width);
        config.height = yamlConfig["height"].as<uint32_t>(config.height);
        config.fullscreen = yamlConfig["fullscreen"].as<bool>(config.fullscreen);
        config.useDesktopSize = yamlConfig["useDesktopSize"].as<bool>(config.useDesktopSize);
        config.vsync = yamlConfig["vsync"].as<bool>(config.vsync);
        config.deadZone = yamlConfig["deadzone"].as<float>(config.deadZone);
        config.keySpeed = yamlConfig["keySpeed"].as<float>(config.keySpeed);
    } catch (YAML::Exception e) {
        ERR("YAML Exception: %s", e.msg.c_str());
        ERR("Can't load '%s', using sane defaults", configFilename.c_str());
    }
    INFO("Current settings:");
    INFO("\tname = %s", config.name.c_str());
    INFO("\twidth = %d", config.width);
    INFO("\theight = %d", config.height);
    INFO("\tfullscreen = %s", (config.fullscreen ? "true" : "false"));
    INFO("\tuseDesktopSize = %s", (config.useDesktopSize ? "true" : "false"));
    INFO("\tvsync = %s", (config.vsync ? "true" : "false"));
    INFO("\tdeadZone = %f", config.deadZone);
    INFO("\tkeySpeed = %f", config.keySpeed);
}

void Engine::createWindow(bool shouldFullscreen) {
    unsigned int flags = 0;

    lockWindow();

    INFO("Reading config");
    sf::VideoMode mode;
    config.fullscreen = shouldFullscreen;
    if (config.fullscreen) {
        INFO("Going fullscreen");
        window.setMouseCursorVisible(false);
        if (config.useDesktopSize) {
            INFO("Setting fullscreen mode (using desktop size): %dx%d",
                 sf::VideoMode::getDesktopMode().width,
                 sf::VideoMode::getDesktopMode().height);
            mode = sf::VideoMode::getDesktopMode();
        } else {
            INFO("Setting fullscreen mode: %dx%d", config.width, config.height);
            mode = sf::VideoMode(config.width, config.height);
        }
        flags = sf::Style::Fullscreen;
    } else {
        INFO("Setting windowed mode: %dx%d", config.width, config.height);
        window.setMouseCursorVisible(true);
        mode = sf::VideoMode(config.width, config.height);
        flags = sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize;
    }
    INFO("Creating the main window");
    window.create(mode, game, flags);
    if (!window.isOpen()) {
        ERR("Could not create main window");
        exit(EXIT_FAILURE);
    }
    sf::ContextSettings settings = window.getSettings();
    INFO("Using OpenGL %d.%d", settings.majorVersion, settings.minorVersion);

    // initialize the view
    INFO("Setting window view");
    view = window.getDefaultView();
    view.setSize(renderWidth, renderHeight);
    view.setCenter(renderWidth / 2, renderHeight / 2);
    window.setView(view);
    if (config.vsync) {
        INFO("Enabling V-sync");
        window.setVerticalSyncEnabled(true);
    }

    releaseWindow();

    // scale the viewport to maintain good aspect
    adjustAspect(window.getSize());
}

void Engine::adjustAspect(sf::Event::SizeEvent newSize) {
    // save the new window size since this came from a resize event
    // not from a window creation event (initialization or fullscreen toggle)
    config.width = newSize.width;
    config.height = newSize.height;
    INFO("Window resized to: %dx%d", config.width, config.height);
    // do the calculation
    adjustAspect(sf::Vector2u(newSize.width, newSize.height));
}

void Engine::adjustAspect(sf::Vector2u newSize) {
    INFO("Adjusting aspect for window size ", newSize.x, newSize.y);
    // compute the current aspect
    float currentRatio = (float) newSize.x / (float) newSize.y;
    // used to offset and scale the viewport to maintain 16:9 aspect
    float widthScale = 1.0f;
    float widthOffset = 0.0f;
    float heightScale = 1.0f;
    float heightOffset = 0.0f;
    // used to compare and compute aspect ratios
    // for logging
    std::string isSixteenNine = "16:9";
    if (currentRatio > 16.0f / 9.0f) {
        // we are wider
        isSixteenNine = "wide";
        widthScale = newSize.y * (16.0f / 9.0f) / newSize.x;
        widthOffset = (1.0f - widthScale) / 2.0f;
    } else if (currentRatio < 16.0f / 9.0f) {
        // we are narrower
        isSixteenNine = "narrow";
        heightScale = newSize.x * (9.0f / 16.0f) / newSize.y;
        heightOffset = (1.0f - heightScale) / 2.0f;
    }
    lockWindow();
    INFO("Setting %s viewport (wo:%f, ho:%f; ws:%f, hs: %f", isSixteenNine.c_str(),
         widthOffset, heightOffset, widthScale, heightScale);
    view.setViewport(sf::FloatRect(widthOffset, heightOffset, widthScale, heightScale));
    window.setView(view);
    releaseWindow();
}

//#define LOG_WINDOW_MUTEX_LOCKS
void inline Engine::lockWindow() {
#ifdef LOG_WINDOW_MUTEX_LOCKS
    DBUG("Grabbing window lock");
#endif
    windowMutex.lock();
    window.setActive(true);
}

void inline Engine::releaseWindow() {
#ifdef LOG_WINDOW_MUTEX_LOCKS
    DBUG("Releasing window lock");
#endif
    window.setActive(false);
    windowMutex.unlock();
}

void Engine::processEvents() {
    static sf::Event event;

    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                INFO("Window closed");
                running = false;
                break;
            case sf::Event::Resized:
                adjustAspect(event.size);
                break;
            case sf::Event::KeyPressed:
                handleKeyPress(event);
                break;
            case sf::Event::KeyReleased:
                handleKeyRelease(event);
                break;
            default:
                break;
        }
    }
}

void Engine::handleKeyPress(const sf::Event& event) {
    switch (event.key.code) {
        case sf::Keyboard::Escape:
            INFO("Key: Escape: exiting");
            running = false;
            break;
        case sf::Keyboard::Return:
            if (event.key.alt) {
                createWindow(!config.fullscreen);
            }
            break;
        default:
            break;
    }
}

void Engine::handleKeyRelease(const sf::Event& event) {
    switch (event.key.code) {
        default:
            break;
    }
}

void Engine::update(sf::Time elapsed) {
    float x, y = 0;

    // get current state of controls
    float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
    float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
    x = std::fabs(joy0_X) < config.deadZone ? 0 : joy0_X;
    y = std::fabs(joy0_y) < config.deadZone ? 0 : joy0_y;

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
        y += -config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        x += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
        y += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        x += -config.keySpeed;
    }

    spritesMutex.lock();
    player->moveBy(x, y);

    const int millis = elapsed.asMilliseconds();
    for (auto sprite : sprites) {
        sprite->update(millis);
    }

    spritesMutex.unlock();
}

void Engine::renderLoop() {
    INFO("Initializing render loop");
    sf::Clock frameClock;
    sf::Int32 lastFrameTime;
    sf::Int32 averageFrameTime;
    sf::Int32 totalFrameTime = 0;
    sf::Int32 frameCount = 0;
    INFO("Starting render loop");
    while (running) {
        frameClock.restart();
        // blank the render target to black
        screen.clear(sf::Color::Black);
        // render all the normal sprites
        spritesMutex.lock();
        for (const auto sprite : sprites) {
            screen.draw(*sprite);
        }
        spritesMutex.unlock();
        // update the target
        screen.display();
        lockWindow();
        // blank the window to gray
        window.clear(sf::Color(128, 128, 128));
        // copy render target to window
        window.draw(sf::Sprite(screen.getTexture()));
        // update thw window
        window.display();
        releaseWindow();
        lastFrameTime = frameClock.getElapsedTime().asMilliseconds();
        totalFrameTime += lastFrameTime;
        averageFrameTime = totalFrameTime / ++frameCount;
        // log the time per frame every 60 frames (every second if at 60 Hz)
        if (frameCount % (60 * 1) == 0) {
            DBUG("Average frame time: %d ms", averageFrameTime);
        }
    }
    spritesMutex.unlock();
    window.close();
    releaseWindow();
    INFO("Stopped render loop");
}
<commit_msg>Close the window after the render thread is completely done.<commit_after>#include <Engine.h>

Engine::Engine(const int argc, const char** argv, const std::string& _name) :
        game(_name)
{
    INFO("Initializing Engine with game data in '%s", game.c_str());

    showBuildInfo(argv[0]);

    data_dir = game;

    readConfig();

    INFO("Creating %dx%d render target", renderWidth, renderHeight);
    screen.create(renderWidth, renderHeight);

    createWindow(config.fullscreen);

    spritesMutex.lock();
    INFO("Creating entities");
    player = std::make_shared<Sprite>(data_dir + "/player.yaml");
    player->setPosition(renderWidth * 1 / 2, renderHeight * 3 / 4);
    sprites.push_back(player);
    INFO("Created player");
    enemy = std::make_shared<Sprite>(data_dir + "/enemy.yaml");
    enemy->setPosition(renderWidth * 1 / 2, renderHeight * 1 / 4);
    sprites.push_back(enemy);
    INFO("Created enemy");
    spritesMutex.unlock();

    isReady = true;
    INFO("Initialization Complete");
}

bool Engine::ready() {
    if (isReady) {
        INFO("Game of '%s' is ready", config.name.c_str());
    } else {

    }
    return isReady;
}

bool Engine::run() {
    INFO("Starting a game of '%s'", config.name.c_str());

    INFO("Creating Render thread");
    releaseWindow();
    renderThread = std::make_unique<std::thread>(&Engine::renderLoop, this);

    INFO("Initializing event loop");
    sf::Int32 updateHz = 60;
    sf::Int32 updateWaitTime = 1'000'000 / updateHz;
    sf::Clock gameClock;
    sf::Time elapsedTime;
    sf::Time lastUpdateTime;
    sf::Int64 totalUpdateTime = 0;
    sf::Int64 averageUpdateTime;
    sf::Int32 updateCount = 0;
    INFO("Starting event loop");
    running = true;
    while (running) {
        elapsedTime = gameClock.restart();
        processEvents();
        update(elapsedTime);
        //compute
        lastUpdateTime = gameClock.getElapsedTime();
        totalUpdateTime += lastUpdateTime.asMilliseconds();
        averageUpdateTime = totalUpdateTime / ++updateCount;
        // log the average time per update every 1 seconds
        if (updateCount % (60 * 1) == 0) {
            DBUG("Average update time: %d ms", averageUpdateTime);
        }
        // update at approximately 60 Hz (16666us minus time taken by last update(
        sf::sleep(sf::microseconds(updateWaitTime - lastUpdateTime.asMicroseconds()));
    }
    INFO("Stopped event loop");
    renderThread->join();
    INFO("Closing window");
    window.close();
    INFO("Game of '%s' ended successfully", config.name.c_str());
    return true;
}

void Engine::showBuildInfo(const char* name) {
    const uint32_t majorVersion = 0;
    const uint32_t minorVersion = 4;
    const uint32_t revision = 1;

    INFO("%s %d.%d.%d %s %s", name, majorVersion, minorVersion, revision, __DATE__, __TIME__);

    INFO("SFML %d.%d", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);

// what compiler are we using? just because
#ifdef __MINGW32__
#ifdef __MINGW64__
    INFO("MinGW-w64 %d.%d", __MINGW64_VERSION_MAJOR, __MINGW64_VERSION_MINOR);
#else
    INFO("MinGW %d.%d", __MINGW32_MAJOR_VERSION, __MINGW32_MINOR_VERSION);
#endif
#endif

#ifdef __clang__
    INFO("CLang %d.%d.%d", __clang_major__, __clang_minor__, __clang_patchlevel__);
#endif

#ifdef __GNUG__
    INFO("GCC %s", __VERSION__);
#endif

#ifdef MSC_VER
    INFO("Visual C++ %s", _MCS_VER);
#endif
}

void Engine::readConfig() {
    std::string configFilename = data_dir + "/config.yaml";
    INFO("Reading config from '%s'", configFilename.c_str());
    try {
        YAML::Node yamlConfig = YAML::LoadFile(configFilename);
        config.name = yamlConfig["name"].as<std::string>(game);
        config.width = yamlConfig["width"].as<uint32_t>(config.width);
        config.height = yamlConfig["height"].as<uint32_t>(config.height);
        config.fullscreen = yamlConfig["fullscreen"].as<bool>(config.fullscreen);
        config.useDesktopSize = yamlConfig["useDesktopSize"].as<bool>(config.useDesktopSize);
        config.vsync = yamlConfig["vsync"].as<bool>(config.vsync);
        config.deadZone = yamlConfig["deadzone"].as<float>(config.deadZone);
        config.keySpeed = yamlConfig["keySpeed"].as<float>(config.keySpeed);
    } catch (YAML::Exception e) {
        ERR("YAML Exception: %s", e.msg.c_str());
        ERR("Can't load '%s', using sane defaults", configFilename.c_str());
    }
    INFO("Current settings:");
    INFO("\tname = %s", config.name.c_str());
    INFO("\twidth = %d", config.width);
    INFO("\theight = %d", config.height);
    INFO("\tfullscreen = %s", (config.fullscreen ? "true" : "false"));
    INFO("\tuseDesktopSize = %s", (config.useDesktopSize ? "true" : "false"));
    INFO("\tvsync = %s", (config.vsync ? "true" : "false"));
    INFO("\tdeadZone = %f", config.deadZone);
    INFO("\tkeySpeed = %f", config.keySpeed);
}

void Engine::createWindow(bool shouldFullscreen) {
    unsigned int flags = 0;

    lockWindow();

    INFO("Reading config");
    sf::VideoMode mode;
    config.fullscreen = shouldFullscreen;
    if (config.fullscreen) {
        INFO("Going fullscreen");
        window.setMouseCursorVisible(false);
        if (config.useDesktopSize) {
            INFO("Setting fullscreen mode (using desktop size): %dx%d",
                 sf::VideoMode::getDesktopMode().width,
                 sf::VideoMode::getDesktopMode().height);
            mode = sf::VideoMode::getDesktopMode();
        } else {
            INFO("Setting fullscreen mode: %dx%d", config.width, config.height);
            mode = sf::VideoMode(config.width, config.height);
        }
        flags = sf::Style::Fullscreen;
    } else {
        INFO("Setting windowed mode: %dx%d", config.width, config.height);
        window.setMouseCursorVisible(true);
        mode = sf::VideoMode(config.width, config.height);
        flags = sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize;
    }
    INFO("Creating the main window");
    window.create(mode, game, flags);
    if (!window.isOpen()) {
        ERR("Could not create main window");
        exit(EXIT_FAILURE);
    }
    sf::ContextSettings settings = window.getSettings();
    INFO("Using OpenGL %d.%d", settings.majorVersion, settings.minorVersion);

    // initialize the view
    INFO("Setting window view");
    view = window.getDefaultView();
    view.setSize(renderWidth, renderHeight);
    view.setCenter(renderWidth / 2, renderHeight / 2);
    window.setView(view);
    if (config.vsync) {
        INFO("Enabling V-sync");
        window.setVerticalSyncEnabled(true);
    }

    releaseWindow();

    // scale the viewport to maintain good aspect
    adjustAspect(window.getSize());
}

void Engine::adjustAspect(sf::Event::SizeEvent newSize) {
    // save the new window size since this came from a resize event
    // not from a window creation event (initialization or fullscreen toggle)
    config.width = newSize.width;
    config.height = newSize.height;
    INFO("Window resized to: %dx%d", config.width, config.height);
    // do the calculation
    adjustAspect(sf::Vector2u(newSize.width, newSize.height));
}

void Engine::adjustAspect(sf::Vector2u newSize) {
    INFO("Adjusting aspect for window size ", newSize.x, newSize.y);
    // compute the current aspect
    float currentRatio = (float) newSize.x / (float) newSize.y;
    // used to offset and scale the viewport to maintain 16:9 aspect
    float widthScale = 1.0f;
    float widthOffset = 0.0f;
    float heightScale = 1.0f;
    float heightOffset = 0.0f;
    // used to compare and compute aspect ratios
    // for logging
    std::string isSixteenNine = "16:9";
    if (currentRatio > 16.0f / 9.0f) {
        // we are wider
        isSixteenNine = "wide";
        widthScale = newSize.y * (16.0f / 9.0f) / newSize.x;
        widthOffset = (1.0f - widthScale) / 2.0f;
    } else if (currentRatio < 16.0f / 9.0f) {
        // we are narrower
        isSixteenNine = "narrow";
        heightScale = newSize.x * (9.0f / 16.0f) / newSize.y;
        heightOffset = (1.0f - heightScale) / 2.0f;
    }
    lockWindow();
    INFO("Setting %s viewport (wo:%f, ho:%f; ws:%f, hs: %f", isSixteenNine.c_str(),
         widthOffset, heightOffset, widthScale, heightScale);
    view.setViewport(sf::FloatRect(widthOffset, heightOffset, widthScale, heightScale));
    window.setView(view);
    releaseWindow();
}

//#define LOG_WINDOW_MUTEX_LOCKS
void inline Engine::lockWindow() {
#ifdef LOG_WINDOW_MUTEX_LOCKS
    DBUG("Grabbing window lock");
#endif
    windowMutex.lock();
    window.setActive(true);
}

void inline Engine::releaseWindow() {
#ifdef LOG_WINDOW_MUTEX_LOCKS
    DBUG("Releasing window lock");
#endif
    window.setActive(false);
    windowMutex.unlock();
}

void Engine::processEvents() {
    static sf::Event event;

    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                INFO("Window closed");
                running = false;
                break;
            case sf::Event::Resized:
                adjustAspect(event.size);
                break;
            case sf::Event::KeyPressed:
                handleKeyPress(event);
                break;
            case sf::Event::KeyReleased:
                handleKeyRelease(event);
                break;
            default:
                break;
        }
    }
}

void Engine::handleKeyPress(const sf::Event& event) {
    switch (event.key.code) {
        case sf::Keyboard::Escape:
            INFO("Key: Escape: exiting");
            running = false;
            break;
        case sf::Keyboard::Return:
            if (event.key.alt) {
                createWindow(!config.fullscreen);
            }
            break;
        default:
            break;
    }
}

void Engine::handleKeyRelease(const sf::Event& event) {
    switch (event.key.code) {
        default:
            break;
    }
}

void Engine::update(sf::Time elapsed) {
    float x, y = 0;

    // get current state of controls
    float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
    float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
    x = std::fabs(joy0_X) < config.deadZone ? 0 : joy0_X;
    y = std::fabs(joy0_y) < config.deadZone ? 0 : joy0_y;

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
        y += -config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        x += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
        y += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        x += -config.keySpeed;
    }

    spritesMutex.lock();
    player->moveBy(x, y);

    const int millis = elapsed.asMilliseconds();
    for (auto sprite : sprites) {
        sprite->update(millis);
    }

    spritesMutex.unlock();
}

void Engine::renderLoop() {
    INFO("Initializing render loop");
    sf::Clock frameClock;
    sf::Int32 lastFrameTime;
    sf::Int32 averageFrameTime;
    sf::Int32 totalFrameTime = 0;
    sf::Int32 frameCount = 0;
    INFO("Starting render loop");
    while (running) {
        frameClock.restart();
        // blank the render target to black
        screen.clear(sf::Color::Black);
        // render all the normal sprites
        spritesMutex.lock();
        for (const auto sprite : sprites) {
            screen.draw(*sprite);
        }
        spritesMutex.unlock();
        // update the target
        screen.display();
        lockWindow();
        // blank the window to gray
        window.clear(sf::Color(128, 128, 128));
        // copy render target to window
        window.draw(sf::Sprite(screen.getTexture()));
        // update thw window
        window.display();
        releaseWindow();
        lastFrameTime = frameClock.getElapsedTime().asMilliseconds();
        totalFrameTime += lastFrameTime;
        averageFrameTime = totalFrameTime / ++frameCount;
        // log the time per frame every 60 frames (every second if at 60 Hz)
        if (frameCount % (60 * 1) == 0) {
            DBUG("Average frame time: %d ms", averageFrameTime);
        }
    }
    spritesMutex.unlock();
    releaseWindow();
    INFO("Stopped render loop");
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: svdem.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2003-11-05 12:39:54 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <event.hxx>
#include <svapp.hxx>
#include <wrkwin.hxx>
#include <msgbox.hxx>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#ifdef REMOTE_APPSERVER
#include "officeacceptthread.hxx"
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------

// Forward declaration
void Main();

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

SAL_IMPLEMENT_MAIN()
{
    Reference< XMultiServiceFactory > xMS;

    // for this to work make sure an <appname>.ini file is available, you can just copy soffice.ini
    Reference< XComponentContext > xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext();
    xMS = cppu::createRegistryServiceFactory(
                  rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );

#ifdef REMOTE_APPSERVER
    // allow remote clients to connect from any host (0) on the given port
    ::desktop::OOfficeAcceptorThread *pOfficeAcceptThread = new ::desktop::OOfficeAcceptorThread( xMS,
        ::rtl::OUString::createFromAscii("socket,host=0,port=8081;urp;"), false, ::rtl::OUString(), ::rtl::OUString() );
    pOfficeAcceptThread->create();
#endif

    InitVCL( xMS );
    GetpApp()->WaitForClientConnect();  // is a no-op in local case
    ::Main();
    DeInitVCL();

#ifdef REMOTE_APPSERVER
    if( pOfficeAcceptThread )
    {
        pOfficeAcceptThread->stopAccepting();
#ifndef LINUX
        pOfficeAcceptThread->join();
        delete pOfficeAcceptThread;
#endif
        pOfficeAcceptThread = 0;
    }
#endif

    return 0;
}

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

class MyWin : public WorkWindow
{
public:
                MyWin( Window* pParent, WinBits nWinStyle );

    void        MouseMove( const MouseEvent& rMEvt );
    void        MouseButtonDown( const MouseEvent& rMEvt );
    void        MouseButtonUp( const MouseEvent& rMEvt );
    void        KeyInput( const KeyEvent& rKEvt );
    void        KeyUp( const KeyEvent& rKEvt );
    void        Paint( const Rectangle& rRect );
    void        Resize();
};

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

void Main()
{
    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCL - Workbench" ) ) );
    aMainWin.Show();

    Application::Execute();
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle )
{
}

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

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

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

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

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

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

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

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

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

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

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

void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );
}

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

void MyWin::Resize()
{
    WorkWindow::Resize();
}
<commit_msg>INTEGRATION: CWS vclcleanup01 (1.11.22); FILE MERGED 2003/11/28 07:33:10 mt 1.11.22.1: #i22952# Removed App Server code<commit_after>/*************************************************************************
 *
 *  $RCSfile: svdem.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 13:43:32 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <event.hxx>
#include <svapp.hxx>
#include <wrkwin.hxx>
#include <msgbox.hxx>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------

// Forward declaration
void Main();

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

SAL_IMPLEMENT_MAIN()
{
    Reference< XMultiServiceFactory > xMS;

    // for this to work make sure an <appname>.ini file is available, you can just copy soffice.ini
    Reference< XComponentContext > xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext();
    xMS = cppu::createRegistryServiceFactory(
                  rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );

    InitVCL( xMS );
    ::Main();
    DeInitVCL();

    return 0;
}

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

class MyWin : public WorkWindow
{
public:
                MyWin( Window* pParent, WinBits nWinStyle );

    void        MouseMove( const MouseEvent& rMEvt );
    void        MouseButtonDown( const MouseEvent& rMEvt );
    void        MouseButtonUp( const MouseEvent& rMEvt );
    void        KeyInput( const KeyEvent& rKEvt );
    void        KeyUp( const KeyEvent& rKEvt );
    void        Paint( const Rectangle& rRect );
    void        Resize();
};

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

void Main()
{
    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCL - Workbench" ) ) );
    aMainWin.Show();

    Application::Execute();
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle )
{
}

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

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

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

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

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

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

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

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

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

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

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

void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );
}

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

void MyWin::Resize()
{
    WorkWindow::Resize();
}
<|endoftext|>


<commit_before>/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * 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
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "connectionfactory.h"

#ifndef MALIIT_DISABLE_DBUS
#ifdef HAVE_GLIB_DBUS
#include "glibdbusimserverproxy.h"
#include "minputcontextglibdbusconnection.h"
#else
#include "dbusserverconnection.h"
#include "dbusinputcontextconnection.h"
#endif
#endif
#include "mimdirectserverconnection.h"

namespace Maliit {
#ifndef MALIIT_DISABLE_DBUS
namespace DBus {

MImServerConnection *createServerConnectionWithDynamicAddress()
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::DynamicAddress);
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MImServerConnection *createServerConnectionWithFixedAddress(const QString &fixedAddress)
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::FixedAddress(fixedAddress));
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithDynamicAddress()
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new MInputContextGlibDBusConnection(address, false);
#else
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new DBusInputContextConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithFixedAddress(const QString &fixedAddress, bool allowAnonymous)
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new MInputContextGlibDBusConnection(address, allowAnonymous);
#else
    Q_UNUSED(allowAnonymous);
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new DBusInputContextConnection(address);
#endif
}

} // namespace DBus
#endif // MALIIT_DISABLE_DBUS

QSharedPointer<MImServerConnection> createServerConnection(const QString &connectionType)
{
    typedef QSharedPointer<MImServerConnection> ConnectionPtr;
    static QWeakPointer<MImServerConnection> cached_connection;

    if (ConnectionPtr connection = cached_connection.toStrongRef())
        return connection;

    if (connectionType == MALIIT_INPUTCONTEXT_NAME) {
#ifndef MALIIT_DISABLE_DBUS
        const QByteArray overriddenAddress = qgetenv("MALIIT_SERVER_ADDRESS");
        ConnectionPtr connection;

        if (overriddenAddress.isEmpty()) {
            cached_connection = connection = ConnectionPtr(Maliit::DBus::createServerConnectionWithDynamicAddress());
        } else {
            cached_connection = connection = ConnectionPtr(Maliit::DBus::createServerConnectionWithFixedAddress(overriddenAddress));
        }

        return connection;
#else
        qCritical("This connection type to Maliit server is not available since DBus support is disabled");
#endif
    } else if (connectionType == MALIIT_INPUTCONTEXT_NAME"Direct") {
        ConnectionPtr connection(new MImDirectServerConnection);

        cached_connection = connection;

        return connection;
    } else {
        qCritical("Invalid connection type, unable to create connection to Maliit server");

        return ConnectionPtr();
    }
}

} // namespace Maliit
<commit_msg>Print a type of connection we failed to get.<commit_after>/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * 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
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "connectionfactory.h"

#ifndef MALIIT_DISABLE_DBUS
#ifdef HAVE_GLIB_DBUS
#include "glibdbusimserverproxy.h"
#include "minputcontextglibdbusconnection.h"
#else
#include "dbusserverconnection.h"
#include "dbusinputcontextconnection.h"
#endif
#endif
#include "mimdirectserverconnection.h"

namespace Maliit {
#ifndef MALIIT_DISABLE_DBUS
namespace DBus {

MImServerConnection *createServerConnectionWithDynamicAddress()
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::DynamicAddress);
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MImServerConnection *createServerConnectionWithFixedAddress(const QString &fixedAddress)
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::FixedAddress(fixedAddress));
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithDynamicAddress()
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new MInputContextGlibDBusConnection(address, false);
#else
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new DBusInputContextConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithFixedAddress(const QString &fixedAddress, bool allowAnonymous)
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new MInputContextGlibDBusConnection(address, allowAnonymous);
#else
    Q_UNUSED(allowAnonymous);
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new DBusInputContextConnection(address);
#endif
}

} // namespace DBus
#endif // MALIIT_DISABLE_DBUS

QSharedPointer<MImServerConnection> createServerConnection(const QString &connectionType)
{
    typedef QSharedPointer<MImServerConnection> ConnectionPtr;
    static QWeakPointer<MImServerConnection> cached_connection;

    if (ConnectionPtr connection = cached_connection.toStrongRef())
        return connection;

    if (connectionType == MALIIT_INPUTCONTEXT_NAME) {
#ifndef MALIIT_DISABLE_DBUS
        const QByteArray overriddenAddress = qgetenv("MALIIT_SERVER_ADDRESS");
        ConnectionPtr connection;

        if (overriddenAddress.isEmpty()) {
            cached_connection = connection = ConnectionPtr(Maliit::DBus::createServerConnectionWithDynamicAddress());
        } else {
            cached_connection = connection = ConnectionPtr(Maliit::DBus::createServerConnectionWithFixedAddress(overriddenAddress));
        }

        return connection;
#else
        qCritical("This connection type to Maliit server is not available since DBus support is disabled");
#endif
    } else if (connectionType == MALIIT_INPUTCONTEXT_NAME"Direct") {
        ConnectionPtr connection(new MImDirectServerConnection);

        cached_connection = connection;

        return connection;
    } else {
        qCritical() << __PRETTY_FUNCTION__ << "Invalid connection type (" + connectionType + "), unable to create connection to Maliit server";

        return ConnectionPtr();
    }
}

} // namespace Maliit
<|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/std/types.hpp>

namespace ox {

enum class FileType: uint8_t {
	None = 0,
	NormalFile = 1,
	Directory  = 2
};

constexpr const char *toString(FileType t) {
	switch (t) {
		case FileType::NormalFile:
			return "Normal File";
		case FileType::Directory:
			return "Directory";
		default:
			return "";
	}
}

struct FileStat {
	uint64_t inode = 0;
	uint64_t links = 0;
	uint64_t size = 0;
	FileType fileType = FileType::None;
};

}
<commit_msg>[ox/fs] Make toString(FileType) noexcept<commit_after>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/std/types.hpp>

namespace ox {

enum class FileType: uint8_t {
	None = 0,
	NormalFile = 1,
	Directory  = 2
};

constexpr const char *toString(FileType t) noexcept {
	switch (t) {
		case FileType::NormalFile:
			return "Normal File";
		case FileType::Directory:
			return "Directory";
		default:
			return "";
	}
}

struct FileStat {
	uint64_t inode = 0;
	uint64_t links = 0;
	uint64_t size = 0;
	FileType fileType = FileType::None;
};

}
<|endoftext|>


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

#include <uielement/addonstoolbarwrapper.hxx>
#include <threadhelp/guard.hxx>
#include <threadhelp/threadhelpbase.hxx>

#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/ModuleManager.hpp>
#include <com/sun/star/frame/XModuleManager2.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp>
#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
#include <com/sun/star/ui/XUIElementFactory.hpp>

#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <vcl/svapp.hxx>
#include <rtl/ref.hxx>
#include <rtl/ustrbuf.hxx>

#include <macros/generic.hxx>
#include <macros/xinterface.hxx>
#include <macros/xtypeprovider.hxx>
#include <macros/xserviceinfo.hxx>
#include <services.h>

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::util;
using namespace ::com::sun::star::ui;
using namespace framework;

namespace {

class AddonsToolBarFactory :  protected ThreadHelpBase,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                              public ::cppu::WeakImplHelper2< css::lang::XServiceInfo ,
                                                              css::ui::XUIElementFactory >
{
public:
    AddonsToolBarFactory( const css::uno::Reference< css::uno::XComponentContext >& xContext );
    virtual ~AddonsToolBarFactory();

    virtual OUString SAL_CALL getImplementationName()
        throw (css::uno::RuntimeException, std::exception)
    {
        return OUString("com.sun.star.comp.framework.AddonsToolBarFactory");
    }

    virtual sal_Bool SAL_CALL supportsService(OUString const & ServiceName)
        throw (css::uno::RuntimeException, std::exception)
    {
        return cppu::supportsService(this, ServiceName);
    }

    virtual css::uno::Sequence<OUString> SAL_CALL getSupportedServiceNames()
        throw (css::uno::RuntimeException, std::exception)
    {
        css::uno::Sequence< OUString > aSeq(1);
        aSeq[0] = OUString("com.sun.star.ui.ToolBarFactory");
        return aSeq;
    }

    // XUIElementFactory
    virtual css::uno::Reference< css::ui::XUIElement > SAL_CALL createUIElement( const OUString& ResourceURL, const css::uno::Sequence< css::beans::PropertyValue >& Args ) throw ( css::container::NoSuchElementException, css::lang::IllegalArgumentException, css::uno::RuntimeException, std::exception );

    sal_Bool hasButtonsInContext( const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& rPropSeq,
                                  const css::uno::Reference< css::frame::XFrame >& rFrame );

private:
    css::uno::Reference< css::uno::XComponentContext >     m_xContext;
    css::uno::Reference< css::frame::XModuleManager2 >     m_xModuleManager;
};

AddonsToolBarFactory::AddonsToolBarFactory(
    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext ) :
    ThreadHelpBase( &Application::GetSolarMutex() )
    , m_xContext( xContext )
    , m_xModuleManager( ModuleManager::create( xContext ) )
{
}

AddonsToolBarFactory::~AddonsToolBarFactory()
{
}

static sal_Bool IsCorrectContext( const OUString& rModuleIdentifier, const OUString& aContextList )
{
    if ( aContextList.isEmpty() )
        return sal_True;

    if ( !rModuleIdentifier.isEmpty() )
    {
        sal_Int32 nIndex = aContextList.indexOf( rModuleIdentifier );
        return ( nIndex >= 0 );
    }

    return sal_False;
}

sal_Bool AddonsToolBarFactory::hasButtonsInContext(
    const Sequence< Sequence< PropertyValue > >& rPropSeqSeq,
    const Reference< XFrame >& rFrame )
{
    OUString aModuleIdentifier;
    try
    {
        aModuleIdentifier = m_xModuleManager->identify( rFrame );
    }
    catch ( const RuntimeException& )
    {
        throw;
    }
    catch ( const Exception& )
    {
    }

    // Check before we create a toolbar that we have at least one button in
    // the current frame context.
    for ( sal_uInt32 i = 0; i < (sal_uInt32)rPropSeqSeq.getLength(); i++ )
    {
        sal_Bool    bIsButton( sal_True );
        sal_Bool    bIsCorrectContext( sal_False );
        sal_uInt32  nPropChecked( 0 );

        const Sequence< PropertyValue >& rPropSeq = rPropSeqSeq[i];
        for ( sal_uInt32 j = 0; j < (sal_uInt32)rPropSeq.getLength(); j++ )
        {
            if ( rPropSeq[j].Name == "Context" )
            {
                OUString aContextList;
                if ( rPropSeq[j].Value >>= aContextList )
                    bIsCorrectContext = IsCorrectContext( aModuleIdentifier, aContextList );
                nPropChecked++;
            }
            else if ( rPropSeq[j].Name == "URL" )
            {
                OUString aURL;
                rPropSeq[j].Value >>= aURL;
                bIsButton = aURL != "private:separator" ;
                nPropChecked++;
            }

            if ( nPropChecked == 2 )
                break;
        }

        if ( bIsButton && bIsCorrectContext )
            return sal_True;
    }

    return sal_False;
}

// XUIElementFactory
Reference< XUIElement > SAL_CALL AddonsToolBarFactory::createUIElement(
    const OUString& ResourceURL,
    const Sequence< PropertyValue >& Args )
throw ( ::com::sun::star::container::NoSuchElementException,
        ::com::sun::star::lang::IllegalArgumentException,
        ::com::sun::star::uno::RuntimeException, std::exception )
{
    // SAFE
    Guard aLock( m_aLock );

    Sequence< Sequence< PropertyValue > >   aConfigData;
    Reference< XFrame >                     xFrame;
    OUString                           aResourceURL( ResourceURL );

    for ( sal_Int32 n = 0; n < Args.getLength(); n++ )
    {
        if ( Args[n].Name == "ConfigurationData" )
            Args[n].Value >>= aConfigData;
        else if ( Args[n].Name == "Frame" )
            Args[n].Value >>= xFrame;
        else if ( Args[n].Name == "ResourceURL" )
            Args[n].Value >>= aResourceURL;
    }

    if ( !aResourceURL.startsWith("private:resource/toolbar/addon_") )
        throw IllegalArgumentException();

    // Identify frame and determine module identifier to look for context based buttons
    Reference< ::com::sun::star::ui::XUIElement > xToolBar;
    if ( xFrame.is() &&
         ( aConfigData.getLength()> 0 ) &&
         hasButtonsInContext( aConfigData, xFrame ))
    {
        PropertyValue aPropValue;
        Sequence< Any > aPropSeq( 3 );
        aPropValue.Name = "Frame";
        aPropValue.Value <<= xFrame;
        aPropSeq[0] <<= aPropValue;
        aPropValue.Name = "ConfigurationData";
        aPropValue.Value <<= aConfigData;
        aPropSeq[1] <<= aPropValue;
        aPropValue.Name = "ResourceURL";
        aPropValue.Value <<= aResourceURL;
        aPropSeq[2] <<= aPropValue;

        SolarMutexGuard aGuard;
        AddonsToolBarWrapper* pToolBarWrapper = new AddonsToolBarWrapper( m_xContext );
        xToolBar = Reference< ::com::sun::star::ui::XUIElement >( (OWeakObject *)pToolBarWrapper, UNO_QUERY );
        Reference< XInitialization > xInit( xToolBar, UNO_QUERY );
        xInit->initialize( aPropSeq );
    }

    return xToolBar;
}

}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
com_sun_star_comp_framework_AddonsToolBarFactory_get_implementation(
    css::uno::XComponentContext *context,
    css::uno::Sequence<css::uno::Any> const &)
{
    return cppu::acquire(new AddonsToolBarFactory(context));
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Use SolarMutexGuard directly<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <uielement/addonstoolbarwrapper.hxx>

#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/ModuleManager.hpp>
#include <com/sun/star/frame/XModuleManager2.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp>
#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
#include <com/sun/star/ui/XUIElementFactory.hpp>

#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <vcl/svapp.hxx>
#include <rtl/ref.hxx>
#include <rtl/ustrbuf.hxx>

#include <macros/generic.hxx>
#include <macros/xinterface.hxx>
#include <macros/xtypeprovider.hxx>
#include <macros/xserviceinfo.hxx>
#include <services.h>

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::util;
using namespace ::com::sun::star::ui;
using namespace framework;

namespace {

class AddonsToolBarFactory :  public ::cppu::WeakImplHelper2< css::lang::XServiceInfo ,
                                                              css::ui::XUIElementFactory >
{
public:
    AddonsToolBarFactory( const css::uno::Reference< css::uno::XComponentContext >& xContext );
    virtual ~AddonsToolBarFactory();

    virtual OUString SAL_CALL getImplementationName()
        throw (css::uno::RuntimeException, std::exception)
    {
        return OUString("com.sun.star.comp.framework.AddonsToolBarFactory");
    }

    virtual sal_Bool SAL_CALL supportsService(OUString const & ServiceName)
        throw (css::uno::RuntimeException, std::exception)
    {
        return cppu::supportsService(this, ServiceName);
    }

    virtual css::uno::Sequence<OUString> SAL_CALL getSupportedServiceNames()
        throw (css::uno::RuntimeException, std::exception)
    {
        css::uno::Sequence< OUString > aSeq(1);
        aSeq[0] = OUString("com.sun.star.ui.ToolBarFactory");
        return aSeq;
    }

    // XUIElementFactory
    virtual css::uno::Reference< css::ui::XUIElement > SAL_CALL createUIElement( const OUString& ResourceURL, const css::uno::Sequence< css::beans::PropertyValue >& Args ) throw ( css::container::NoSuchElementException, css::lang::IllegalArgumentException, css::uno::RuntimeException, std::exception );

    sal_Bool hasButtonsInContext( const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& rPropSeq,
                                  const css::uno::Reference< css::frame::XFrame >& rFrame );

private:
    css::uno::Reference< css::uno::XComponentContext >     m_xContext;
    css::uno::Reference< css::frame::XModuleManager2 >     m_xModuleManager;
};

AddonsToolBarFactory::AddonsToolBarFactory(
    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext ) :
    m_xContext( xContext )
    , m_xModuleManager( ModuleManager::create( xContext ) )
{
}

AddonsToolBarFactory::~AddonsToolBarFactory()
{
}

static sal_Bool IsCorrectContext( const OUString& rModuleIdentifier, const OUString& aContextList )
{
    if ( aContextList.isEmpty() )
        return sal_True;

    if ( !rModuleIdentifier.isEmpty() )
    {
        sal_Int32 nIndex = aContextList.indexOf( rModuleIdentifier );
        return ( nIndex >= 0 );
    }

    return sal_False;
}

sal_Bool AddonsToolBarFactory::hasButtonsInContext(
    const Sequence< Sequence< PropertyValue > >& rPropSeqSeq,
    const Reference< XFrame >& rFrame )
{
    OUString aModuleIdentifier;
    try
    {
        aModuleIdentifier = m_xModuleManager->identify( rFrame );
    }
    catch ( const RuntimeException& )
    {
        throw;
    }
    catch ( const Exception& )
    {
    }

    // Check before we create a toolbar that we have at least one button in
    // the current frame context.
    for ( sal_uInt32 i = 0; i < (sal_uInt32)rPropSeqSeq.getLength(); i++ )
    {
        sal_Bool    bIsButton( sal_True );
        sal_Bool    bIsCorrectContext( sal_False );
        sal_uInt32  nPropChecked( 0 );

        const Sequence< PropertyValue >& rPropSeq = rPropSeqSeq[i];
        for ( sal_uInt32 j = 0; j < (sal_uInt32)rPropSeq.getLength(); j++ )
        {
            if ( rPropSeq[j].Name == "Context" )
            {
                OUString aContextList;
                if ( rPropSeq[j].Value >>= aContextList )
                    bIsCorrectContext = IsCorrectContext( aModuleIdentifier, aContextList );
                nPropChecked++;
            }
            else if ( rPropSeq[j].Name == "URL" )
            {
                OUString aURL;
                rPropSeq[j].Value >>= aURL;
                bIsButton = aURL != "private:separator" ;
                nPropChecked++;
            }

            if ( nPropChecked == 2 )
                break;
        }

        if ( bIsButton && bIsCorrectContext )
            return sal_True;
    }

    return sal_False;
}

// XUIElementFactory
Reference< XUIElement > SAL_CALL AddonsToolBarFactory::createUIElement(
    const OUString& ResourceURL,
    const Sequence< PropertyValue >& Args )
throw ( ::com::sun::star::container::NoSuchElementException,
        ::com::sun::star::lang::IllegalArgumentException,
        ::com::sun::star::uno::RuntimeException, std::exception )
{
    SolarMutexGuard g;

    Sequence< Sequence< PropertyValue > >   aConfigData;
    Reference< XFrame >                     xFrame;
    OUString                           aResourceURL( ResourceURL );

    for ( sal_Int32 n = 0; n < Args.getLength(); n++ )
    {
        if ( Args[n].Name == "ConfigurationData" )
            Args[n].Value >>= aConfigData;
        else if ( Args[n].Name == "Frame" )
            Args[n].Value >>= xFrame;
        else if ( Args[n].Name == "ResourceURL" )
            Args[n].Value >>= aResourceURL;
    }

    if ( !aResourceURL.startsWith("private:resource/toolbar/addon_") )
        throw IllegalArgumentException();

    // Identify frame and determine module identifier to look for context based buttons
    Reference< ::com::sun::star::ui::XUIElement > xToolBar;
    if ( xFrame.is() &&
         ( aConfigData.getLength()> 0 ) &&
         hasButtonsInContext( aConfigData, xFrame ))
    {
        PropertyValue aPropValue;
        Sequence< Any > aPropSeq( 3 );
        aPropValue.Name = "Frame";
        aPropValue.Value <<= xFrame;
        aPropSeq[0] <<= aPropValue;
        aPropValue.Name = "ConfigurationData";
        aPropValue.Value <<= aConfigData;
        aPropSeq[1] <<= aPropValue;
        aPropValue.Name = "ResourceURL";
        aPropValue.Value <<= aResourceURL;
        aPropSeq[2] <<= aPropValue;

        SolarMutexGuard aGuard;
        AddonsToolBarWrapper* pToolBarWrapper = new AddonsToolBarWrapper( m_xContext );
        xToolBar = Reference< ::com::sun::star::ui::XUIElement >( (OWeakObject *)pToolBarWrapper, UNO_QUERY );
        Reference< XInitialization > xInit( xToolBar, UNO_QUERY );
        xInit->initialize( aPropSeq );
    }

    return xToolBar;
}

}

extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
com_sun_star_comp_framework_AddonsToolBarFactory_get_implementation(
    css::uno::XComponentContext *context,
    css::uno::Sequence<css::uno::Any> const &)
{
    return cppu::acquire(new AddonsToolBarFactory(context));
}

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


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "../qsfwtestutil.h"

#include <QtTest/QtTest>
#include <QtCore>
#include <qservicemanager.h>
#include <qabstractsecuritysession.h>

class TestSession : public QAbstractSecuritySession
{
public:
    TestSession() {}
    virtual ~TestSession(){}

    virtual bool isAllowed(const QStringList& serviceCaps)
    {
        //client must have at least service caps;
        QSet<QString> sub = serviceCaps.toSet() - clientCaps;;
        if (sub.isEmpty())
            return true;
        else
            return false;
    }

    void setClientCaps(const QStringList& capabilities)
    {
        clientCaps = capabilities.toSet();
    }
private:
    QSet<QString> clientCaps;

};

class tst_QAbstractSecuritySession: public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();
    void cleanupTestCase();
    void testSecSessionHandling();
private:
   QString path;
};

void tst_QAbstractSecuritySession::initTestCase()
{
    path = QCoreApplication::applicationDirPath() + "/xmldata/";

    QSfwTestUtil::setupTempUserDb();
    QSfwTestUtil::setupTempSystemDb();

    QSfwTestUtil::removeTempUserDb();
    QSfwTestUtil::removeTempSystemDb();
}

void tst_QAbstractSecuritySession::testSecSessionHandling()
{
    QFile file(path+"testserviceplugin.xml");
    QVERIFY(file.exists());

    QServiceManager mgr;
    QVERIFY(mgr.findServices().isEmpty());
    QVERIFY(mgr.addService(&file));
    QVERIFY(mgr.findServices() == (QStringList()<< "TestService"));

    QServiceFilter simpleFilter;
    simpleFilter.setInterface("com.nokia.qt.ISimpleTypeTest");
    QList<QServiceInterfaceDescriptor> list = mgr.findInterfaces(simpleFilter);
    QVERIFY(list.count() == 1);
    QServiceInterfaceDescriptor simpleDesc = list.at(0);
    QVERIFY(simpleDesc.isValid());
    QVERIFY(simpleDesc.majorVersion() == 1);
    QVERIFY(simpleDesc.minorVersion() == 0);
    QVERIFY(simpleDesc.interfaceName() == QString("com.nokia.qt.ISimpleTypeTest"));
    QCOMPARE(simpleDesc.property(QServiceInterfaceDescriptor::Capabilities).toStringList(),
             QStringList() << "simple");

    QServiceFilter complexFilter;
    complexFilter.setInterface("com.nokia.qt.IComplexTypeTest");
    list = mgr.findInterfaces(complexFilter);
    QVERIFY(list.count() == 1);
    QServiceInterfaceDescriptor complexDesc = list.at(0);
    QVERIFY(complexDesc.isValid());
    QVERIFY(complexDesc.majorVersion() == 2);
    QVERIFY(complexDesc.minorVersion() == 3);
    QVERIFY(complexDesc.interfaceName() == QString("com.nokia.qt.IComplexTypeTest"));
    QCOMPARE(complexDesc.property(QServiceInterfaceDescriptor::Capabilities).toStringList(),
             QStringList() << "complex" << "simple");

    //no QAbstractSecuritySession object
    QObject* o = mgr.loadInterface(simpleDesc, 0, 0 );
    QVERIFY(o);
    delete o;
    o = mgr.loadInterface(complexDesc, 0, 0);
    QVERIFY(o);
    delete o;

    //client does not have any permission
    TestSession* secSession = new TestSession();
    secSession->setClientCaps(QStringList());

    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(!o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(!o);

    //client has simple permission
    secSession->setClientCaps(QStringList() << "simple");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(!o);

    //client has simple and complex permission
    secSession->setClientCaps(QStringList() << "simple" << "complex");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(o);

    //client has simple, complex and advanced permission
    secSession->setClientCaps(QStringList() << "simple" << "complex" << "advanced");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(o);

    //client has unknown capability
    secSession->setClientCaps(QStringList() << "unknown");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(!o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(!o);

}

void tst_QAbstractSecuritySession::cleanupTestCase()
{
    QSfwTestUtil::removeTempUserDb();
    QSfwTestUtil::removeTempSystemDb();
}

QTEST_MAIN(tst_QAbstractSecuritySession)
#include "tst_qabstractsecuritysession.moc"
<commit_msg>Fix memory leaks in tests.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "../qsfwtestutil.h"

#include <QtTest/QtTest>
#include <QtCore>
#include <qservicemanager.h>
#include <qabstractsecuritysession.h>

class TestSession : public QAbstractSecuritySession
{
public:
    TestSession() {}
    virtual ~TestSession(){}

    virtual bool isAllowed(const QStringList& serviceCaps)
    {
        //client must have at least service caps;
        QSet<QString> sub = serviceCaps.toSet() - clientCaps;;
        if (sub.isEmpty())
            return true;
        else
            return false;
    }

    void setClientCaps(const QStringList& capabilities)
    {
        clientCaps = capabilities.toSet();
    }
private:
    QSet<QString> clientCaps;

};

class tst_QAbstractSecuritySession: public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();
    void cleanupTestCase();
    void cleanup();
    void testSecSessionHandling();
private:
   QString path;
};

void tst_QAbstractSecuritySession::initTestCase()
{
    path = QCoreApplication::applicationDirPath() + "/xmldata/";

    QSfwTestUtil::setupTempUserDb();
    QSfwTestUtil::setupTempSystemDb();

    QSfwTestUtil::removeTempUserDb();
    QSfwTestUtil::removeTempSystemDb();
}

void tst_QAbstractSecuritySession::cleanup()
{
    //use QEventLopp::DeferredDeletion
    //QServiceManager::loadInterface makes use of deleteLater() when
    //cleaning up service objects and their respective QPluginLoader
    //we want to force the testcase to run the cleanup code
    QCoreApplication::processEvents(QEventLoop::AllEvents|QEventLoop::DeferredDeletion);
}

void tst_QAbstractSecuritySession::testSecSessionHandling()
{
    QFile file(path+"testserviceplugin.xml");
    QVERIFY(file.exists());

    QServiceManager mgr;
    QVERIFY(mgr.findServices().isEmpty());
    QVERIFY(mgr.addService(&file));
    QVERIFY(mgr.findServices() == (QStringList()<< "TestService"));

    QServiceFilter simpleFilter;
    simpleFilter.setInterface("com.nokia.qt.ISimpleTypeTest");
    QList<QServiceInterfaceDescriptor> list = mgr.findInterfaces(simpleFilter);
    QVERIFY(list.count() == 1);
    QServiceInterfaceDescriptor simpleDesc = list.at(0);
    QVERIFY(simpleDesc.isValid());
    QVERIFY(simpleDesc.majorVersion() == 1);
    QVERIFY(simpleDesc.minorVersion() == 0);
    QVERIFY(simpleDesc.interfaceName() == QString("com.nokia.qt.ISimpleTypeTest"));
    QCOMPARE(simpleDesc.property(QServiceInterfaceDescriptor::Capabilities).toStringList(),
             QStringList() << "simple");

    QServiceFilter complexFilter;
    complexFilter.setInterface("com.nokia.qt.IComplexTypeTest");
    list = mgr.findInterfaces(complexFilter);
    QVERIFY(list.count() == 1);
    QServiceInterfaceDescriptor complexDesc = list.at(0);
    QVERIFY(complexDesc.isValid());
    QVERIFY(complexDesc.majorVersion() == 2);
    QVERIFY(complexDesc.minorVersion() == 3);
    QVERIFY(complexDesc.interfaceName() == QString("com.nokia.qt.IComplexTypeTest"));
    QCOMPARE(complexDesc.property(QServiceInterfaceDescriptor::Capabilities).toStringList(),
             QStringList() << "complex" << "simple");

    //no QAbstractSecuritySession object
    QObject* o = mgr.loadInterface(simpleDesc, 0, 0 );
    QVERIFY(o);
    delete o;
    o = mgr.loadInterface(complexDesc, 0, 0);
    QVERIFY(o);
    delete o;

    //client does not have any permission
    TestSession* secSession = new TestSession();
    secSession->setClientCaps(QStringList());

    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(!o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(!o);

    //client has simple permission
    secSession->setClientCaps(QStringList() << "simple");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(o);
    delete o;
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(!o);

    //client has simple and complex permission
    secSession->setClientCaps(QStringList() << "simple" << "complex");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(o);
    delete o;
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(o);
    delete o;

    //client has simple, complex and advanced permission
    secSession->setClientCaps(QStringList() << "simple" << "complex" << "advanced");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(o);
    delete o;
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(o);
    delete o;

    //client has unknown capability
    secSession->setClientCaps(QStringList() << "unknown");
    o = mgr.loadInterface(simpleDesc, 0, secSession );
    QVERIFY(!o);
    o = mgr.loadInterface(complexDesc, 0, secSession);
    QVERIFY(!o);

    delete secSession;
}

void tst_QAbstractSecuritySession::cleanupTestCase()
{
    QSfwTestUtil::removeTempUserDb();
    QSfwTestUtil::removeTempSystemDb();
}

QTEST_MAIN(tst_QAbstractSecuritySession)
#include "tst_qabstractsecuritysession.moc"
<|endoftext|>