<commit_before>/*
 ***********************************************************************************************************************
 *
 *  Copyright (c) 2018 Advanced Micro Devices, Inc. All Rights Reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 **********************************************************************************************************************/
#include "core/os/lnx/wayland/waylandWindowSystem.h"
#include "core/os/lnx/lnxDevice.h"
#include "core/os/lnx/lnxImage.h"
#include "core/os/lnx/lnxPlatform.h"
#include "palSwapChain.h"
#include "util/lnx/lnxTimeout.h"
#include "dlfcn.h"

using namespace Util;

#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 392
namespace Pal
{
namespace Linux
{

// =====================================================================================================================
// translate ChNumFormat into WsaFormat
static WsaFormat WlDrmFormat(
    ChNumFormat  format,
    bool         alpha)
{
    WsaFormat wsaFormat = WsaFormatXRGB8888;
    switch (format)
    {
    case ChNumFormat::X8Y8Z8W8_Unorm:
    case ChNumFormat::X8Y8Z8W8_Srgb:
        wsaFormat = alpha ? WsaFormatARGB8888 : WsaFormatXRGB8888;
        break;
    default:
        PAL_ASSERT(!"Not supported format!");
        break;
    }
    return wsaFormat;
}

// =====================================================================================================================
Result WaylandPresentFence::Create(
    const WaylandWindowSystem& windowSystem,
    bool                       initiallySignaled,
    void*                      pPlacementAddr,
    PresentFence**             ppPresentFence)
{
    PAL_ASSERT((pPlacementAddr != nullptr) && (ppPresentFence != nullptr));

    auto*const pPresentFence = PAL_PLACEMENT_NEW(pPlacementAddr) WaylandPresentFence(windowSystem);
    Result     result        = pPresentFence->Init(initiallySignaled);

    if (result == Result::Success)
    {
        *ppPresentFence = pPresentFence;
    }
    else
    {
        pPresentFence->Destroy();
    }

    return result;
}

// =====================================================================================================================
WaylandPresentFence::WaylandPresentFence(
    const WaylandWindowSystem& windowSystem)
    :
    m_windowSystem(windowSystem),
    m_hImage(-1)
{
}

// =====================================================================================================================
WaylandPresentFence::~WaylandPresentFence()
{
}

// =====================================================================================================================
Result WaylandPresentFence::Init(
    bool initiallySignaled)
{
    return Result::Success;
}

// =====================================================================================================================
void WaylandPresentFence::Reset()
{
}

// =====================================================================================================================
Result WaylandPresentFence::Trigger()
{
    return Result::Success;
}

// =====================================================================================================================
// timeout is not needed for now.
Result WaylandPresentFence::WaitForCompletion(
    bool doWait)
{
    Result result = Result::Success;

    if (WaylandWindowSystem::s_pWsaInterface->pfnImageAvailable(m_windowSystem.m_hWsa, m_hImage) != Success)
    {
        result = Result::NotReady;
    }

    return result;
}

WsaInterface* WaylandWindowSystem::s_pWsaInterface = nullptr;

// =====================================================================================================================
// load wayland wsa interface
Result WaylandWindowSystem::LoadWaylandWsa()
{
    Result result = Result::Success;

    if (s_pWsaInterface == nullptr)
    {
        void* pHandle = dlopen("libamdgpu_wsa_wayland.so", RTLD_LAZY);

        if (pHandle == nullptr)
        {
            result = Result::ErrorInitializationFailed;
        }

        if (result == Result::Success)
        {
            s_pWsaInterface = (WsaInterface*)dlsym(pHandle, "WaylandWsaInterface");
        }

        if (s_pWsaInterface == nullptr)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    return result;
}

// =====================================================================================================================
Result WaylandWindowSystem::Create(
    const Device&                 device,
    const WindowSystemCreateInfo& createInfo,
    void*                         pPlacementAddr,
    WindowSystem**                ppWindowSystem)
{
    PAL_ASSERT((pPlacementAddr != nullptr) && (ppWindowSystem != nullptr));

    auto*const pWindowSystem = PAL_PLACEMENT_NEW(pPlacementAddr) WaylandWindowSystem(device, createInfo);
    Result     result        = pWindowSystem->Init();

    if (result == Result::Success)
    {
        *ppWindowSystem = pWindowSystem;
    }
    else
    {
        pWindowSystem->Destroy();
    }

    return result;
}

// =====================================================================================================================
WaylandWindowSystem::WaylandWindowSystem(
    const Device&                 device,
    const WindowSystemCreateInfo& createInfo)
    :
    WindowSystem(createInfo.platform),
    m_device(device),
    m_pDisplay(static_cast<void*>(createInfo.hDisplay)),
    m_pSurface(createInfo.hWindow.pSurface)
{
}

// =====================================================================================================================
WaylandWindowSystem::~WaylandWindowSystem()
{
}

// =====================================================================================================================
Result WaylandWindowSystem::Init()
{
    Result result = Result::Success;

    if (s_pWsaInterface == nullptr)
    {
        result = LoadWaylandWsa();
    }

    if (result == Result::Success)
    {
        uint32 wsaVersion = s_pWsaInterface->pfnQueryVersion();
        if (wsaVersion < WSA_INTERFACE_VER)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    if (result == Result::Success)
    {
        WsaError ret = s_pWsaInterface->pfnCreateWsa(&m_hWsa);

        if (ret != Success)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    if (result == Result::Success)
    {
        WsaError ret = s_pWsaInterface->pfnInitialize(m_hWsa, m_pDisplay, m_pSurface);

        if (ret != Success)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    return result;
}

// =====================================================================================================================
// Interface for the window system to do things related with creating presentable image.
Result WaylandWindowSystem::CreatePresentableImage(
    const Image&   image,
    int32          sharedBufferFd,
    uint32*        pPresentImage)
{
    PAL_ASSERT(s_pWsaInterface);

    Result result = Result::Success;
    const SubresId              subres      = { ImageAspect::Color, 0, 0 };
    const SubResourceInfo*const pSubResInfo = image.SubresourceInfo(subres);

    const uint32 width  = pSubResInfo->extentTexels.width;
    const uint32 height = pSubResInfo->extentTexels.height;
    const uint32 stride = pSubResInfo->rowPitch;
    const uint32 bpp    = pSubResInfo->bitsPerTexel;

    //we should get alpha from create info, now just hard code it temporarily.
    WsaFormat format = WlDrmFormat(pSubResInfo->format.format, false);

    if ((width == 0) || (height == 0) || (stride == 0) || (bpp == 0) || (sharedBufferFd == InvalidFd))
    {
        result = Result::ErrorInvalidValue;
    }

    if (result == Result::Success)
    {
        WsaError ret = s_pWsaInterface->pfnCreateImage(
                               m_hWsa, sharedBufferFd, width, height, format,
                               stride, reinterpret_cast<int32*>(pPresentImage));
        if (ret != Success)
        {
            result = Result::ErrorOutOfMemory;
        }
    }

    return result;
}

// =====================================================================================================================
// Destroy the present image.
void WaylandWindowSystem::DestroyPresentableImage(
    uint32 image)
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    s_pWsaInterface->pfnDestroyImage(image);
}

// =====================================================================================================================
// Present a pixmap on wayland.
Result WaylandWindowSystem::Present(
    uint32             pixmap,
    PresentMode        presentMode,
    PresentFence*      pRenderFence,
    PresentFence*      pIdleFence)
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    WaylandPresentFence*const pWaylandIdleFence = static_cast<WaylandPresentFence*>(pIdleFence);

    pWaylandIdleFence->SetImage(pixmap);
    s_pWsaInterface->pfnPresent(m_hWsa, pixmap, nullptr);

    return Result::Success;
}

// =====================================================================================================================
// Wait until the image is available.
Result WaylandWindowSystem::WaitForLastImagePresented()
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    Result result = Result::Success;
    s_pWsaInterface->pfnWaitForLastImagePresented(m_hWsa);

    return result;
}

// =====================================================================================================================
// Get window information.
Result WaylandWindowSystem::GetWindowGeometry(
    Device*             pDevice,
    OsDisplayHandle     hDisplay,
    OsWindowHandle      hWindow,
    Extent2d*           pExtents)
{
    Result result = Result::Success;

    if (s_pWsaInterface == nullptr)
    {
        result = LoadWaylandWsa();
    }

    if (result == Result::Success)
    {
        s_pWsaInterface->pfnGetWindowGeometry(hDisplay, hWindow.pSurface, &pExtents->width, &pExtents->height);
    }

    return result;
}

// =====================================================================================================================
// Check whether it's presentable.
Result WaylandWindowSystem::DeterminePresentationSupported(
    Device*             pDevice,
    OsDisplayHandle     hDisplay,
    int64               visualId)
{
    return Result::Success;
}

} // Linux
} // Pal
#endif
<commit_msg>Fix PAL_ASSERT to allow Debug build to complete<commit_after>/*
 ***********************************************************************************************************************
 *
 *  Copyright (c) 2018 Advanced Micro Devices, Inc. All Rights Reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 **********************************************************************************************************************/
#include "core/os/lnx/wayland/waylandWindowSystem.h"
#include "core/os/lnx/lnxDevice.h"
#include "core/os/lnx/lnxImage.h"
#include "core/os/lnx/lnxPlatform.h"
#include "palSwapChain.h"
#include "util/lnx/lnxTimeout.h"
#include "dlfcn.h"

using namespace Util;

#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 392
namespace Pal
{
namespace Linux
{

// =====================================================================================================================
// translate ChNumFormat into WsaFormat
static WsaFormat WlDrmFormat(
    ChNumFormat  format,
    bool         alpha)
{
    WsaFormat wsaFormat = WsaFormatXRGB8888;
    switch (format)
    {
    case ChNumFormat::X8Y8Z8W8_Unorm:
    case ChNumFormat::X8Y8Z8W8_Srgb:
        wsaFormat = alpha ? WsaFormatARGB8888 : WsaFormatXRGB8888;
        break;
    default:
        PAL_ASSERT(!"Not supported format!");
        break;
    }
    return wsaFormat;
}

// =====================================================================================================================
Result WaylandPresentFence::Create(
    const WaylandWindowSystem& windowSystem,
    bool                       initiallySignaled,
    void*                      pPlacementAddr,
    PresentFence**             ppPresentFence)
{
    PAL_ASSERT((pPlacementAddr != nullptr) && (ppPresentFence != nullptr));

    auto*const pPresentFence = PAL_PLACEMENT_NEW(pPlacementAddr) WaylandPresentFence(windowSystem);
    Result     result        = pPresentFence->Init(initiallySignaled);

    if (result == Result::Success)
    {
        *ppPresentFence = pPresentFence;
    }
    else
    {
        pPresentFence->Destroy();
    }

    return result;
}

// =====================================================================================================================
WaylandPresentFence::WaylandPresentFence(
    const WaylandWindowSystem& windowSystem)
    :
    m_windowSystem(windowSystem),
    m_hImage(-1)
{
}

// =====================================================================================================================
WaylandPresentFence::~WaylandPresentFence()
{
}

// =====================================================================================================================
Result WaylandPresentFence::Init(
    bool initiallySignaled)
{
    return Result::Success;
}

// =====================================================================================================================
void WaylandPresentFence::Reset()
{
}

// =====================================================================================================================
Result WaylandPresentFence::Trigger()
{
    return Result::Success;
}

// =====================================================================================================================
// timeout is not needed for now.
Result WaylandPresentFence::WaitForCompletion(
    bool doWait)
{
    Result result = Result::Success;

    if (WaylandWindowSystem::s_pWsaInterface->pfnImageAvailable(m_windowSystem.m_hWsa, m_hImage) != Success)
    {
        result = Result::NotReady;
    }

    return result;
}

WsaInterface* WaylandWindowSystem::s_pWsaInterface = nullptr;

// =====================================================================================================================
// load wayland wsa interface
Result WaylandWindowSystem::LoadWaylandWsa()
{
    Result result = Result::Success;

    if (s_pWsaInterface == nullptr)
    {
        void* pHandle = dlopen("libamdgpu_wsa_wayland.so", RTLD_LAZY);

        if (pHandle == nullptr)
        {
            result = Result::ErrorInitializationFailed;
        }

        if (result == Result::Success)
        {
            s_pWsaInterface = (WsaInterface*)dlsym(pHandle, "WaylandWsaInterface");
        }

        if (s_pWsaInterface == nullptr)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    return result;
}

// =====================================================================================================================
Result WaylandWindowSystem::Create(
    const Device&                 device,
    const WindowSystemCreateInfo& createInfo,
    void*                         pPlacementAddr,
    WindowSystem**                ppWindowSystem)
{
    PAL_ASSERT((pPlacementAddr != nullptr) && (ppWindowSystem != nullptr));

    auto*const pWindowSystem = PAL_PLACEMENT_NEW(pPlacementAddr) WaylandWindowSystem(device, createInfo);
    Result     result        = pWindowSystem->Init();

    if (result == Result::Success)
    {
        *ppWindowSystem = pWindowSystem;
    }
    else
    {
        pWindowSystem->Destroy();
    }

    return result;
}

// =====================================================================================================================
WaylandWindowSystem::WaylandWindowSystem(
    const Device&                 device,
    const WindowSystemCreateInfo& createInfo)
    :
    WindowSystem(createInfo.platform),
    m_device(device),
    m_pDisplay(static_cast<void*>(createInfo.hDisplay)),
    m_pSurface(createInfo.hWindow.pSurface)
{
}

// =====================================================================================================================
WaylandWindowSystem::~WaylandWindowSystem()
{
}

// =====================================================================================================================
Result WaylandWindowSystem::Init()
{
    Result result = Result::Success;

    if (s_pWsaInterface == nullptr)
    {
        result = LoadWaylandWsa();
    }

    if (result == Result::Success)
    {
        uint32 wsaVersion = s_pWsaInterface->pfnQueryVersion();
        if (wsaVersion < WSA_INTERFACE_VER)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    if (result == Result::Success)
    {
        WsaError ret = s_pWsaInterface->pfnCreateWsa(&m_hWsa);

        if (ret != Success)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    if (result == Result::Success)
    {
        WsaError ret = s_pWsaInterface->pfnInitialize(m_hWsa, m_pDisplay, m_pSurface);

        if (ret != Success)
        {
            result = Result::ErrorInitializationFailed;
        }
    }

    return result;
}

// =====================================================================================================================
// Interface for the window system to do things related with creating presentable image.
Result WaylandWindowSystem::CreatePresentableImage(
    const Image&   image,
    int32          sharedBufferFd,
    uint32*        pPresentImage)
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    Result result = Result::Success;
    const SubresId              subres      = { ImageAspect::Color, 0, 0 };
    const SubResourceInfo*const pSubResInfo = image.SubresourceInfo(subres);

    const uint32 width  = pSubResInfo->extentTexels.width;
    const uint32 height = pSubResInfo->extentTexels.height;
    const uint32 stride = pSubResInfo->rowPitch;
    const uint32 bpp    = pSubResInfo->bitsPerTexel;

    //we should get alpha from create info, now just hard code it temporarily.
    WsaFormat format = WlDrmFormat(pSubResInfo->format.format, false);

    if ((width == 0) || (height == 0) || (stride == 0) || (bpp == 0) || (sharedBufferFd == InvalidFd))
    {
        result = Result::ErrorInvalidValue;
    }

    if (result == Result::Success)
    {
        WsaError ret = s_pWsaInterface->pfnCreateImage(
                               m_hWsa, sharedBufferFd, width, height, format,
                               stride, reinterpret_cast<int32*>(pPresentImage));
        if (ret != Success)
        {
            result = Result::ErrorOutOfMemory;
        }
    }

    return result;
}

// =====================================================================================================================
// Destroy the present image.
void WaylandWindowSystem::DestroyPresentableImage(
    uint32 image)
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    s_pWsaInterface->pfnDestroyImage(image);
}

// =====================================================================================================================
// Present a pixmap on wayland.
Result WaylandWindowSystem::Present(
    uint32             pixmap,
    PresentMode        presentMode,
    PresentFence*      pRenderFence,
    PresentFence*      pIdleFence)
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    WaylandPresentFence*const pWaylandIdleFence = static_cast<WaylandPresentFence*>(pIdleFence);

    pWaylandIdleFence->SetImage(pixmap);
    s_pWsaInterface->pfnPresent(m_hWsa, pixmap, nullptr);

    return Result::Success;
}

// =====================================================================================================================
// Wait until the image is available.
Result WaylandWindowSystem::WaitForLastImagePresented()
{
    PAL_ASSERT(s_pWsaInterface != nullptr);

    Result result = Result::Success;
    s_pWsaInterface->pfnWaitForLastImagePresented(m_hWsa);

    return result;
}

// =====================================================================================================================
// Get window information.
Result WaylandWindowSystem::GetWindowGeometry(
    Device*             pDevice,
    OsDisplayHandle     hDisplay,
    OsWindowHandle      hWindow,
    Extent2d*           pExtents)
{
    Result result = Result::Success;

    if (s_pWsaInterface == nullptr)
    {
        result = LoadWaylandWsa();
    }

    if (result == Result::Success)
    {
        s_pWsaInterface->pfnGetWindowGeometry(hDisplay, hWindow.pSurface, &pExtents->width, &pExtents->height);
    }

    return result;
}

// =====================================================================================================================
// Check whether it's presentable.
Result WaylandWindowSystem::DeterminePresentationSupported(
    Device*             pDevice,
    OsDisplayHandle     hDisplay,
    int64               visualId)
{
    return Result::Success;
}

} // Linux
} // Pal
#endif
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  mp4duration.cc
 *
 *    Description:  MP4 duration parser - node.js c++ addon
 *
 *        Version:  1.0
 *        Created:  2014/10/24 16时14分34秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  XadillaX (http://xcoder.in/), admin@xcoder.in
 *   Organization:  Touhou Gensokyo
 *
 * =====================================================================================
 */
#include <node.h>
#include <node_buffer.h>
#include "parse.h"
#include <stdio.h>
#include <string.h>
#include <nan.h>
using namespace v8;
using namespace node;

NAN_METHOD(ParseViaBuffer)
{
    NanScope();

    if(args.Length() < 1)
    {
        NanThrowError("Wrong number of arguments.");
    }

    Local<Value> arg = args[0];
    if(!node::Buffer::HasInstance(arg))
    {
        NanThrowError("Bad argument!");
    }

    size_t size = Buffer::Length(arg->ToObject());
    char* pbuf = Buffer::Data(arg->ToObject());
    char* pbuf_end = pbuf + size;

    // check is it mp4
    if(pbuf_end - pbuf < 7)
    {
        NanThrowError("File is too small.");
    }

    char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 };
    for(int i = 0; i < 8; i++)
    {
        if(i == 3) continue;
        if(sign[i] != *(pbuf + i))
        {
            NanThrowError("Broken MP4 file.");
        }
    }

    double file_duration = 0.0f;
    try
    {
        file_duration = ParseDuration(pbuf, pbuf_end);
    }
    catch(...)
    {
        NanThrowError("Broken file or this format is not supported.");
    }

    NanReturnValue(NanNew<Number>(file_duration));
}

NAN_METHOD(ParseViaFile)
{
    NanScope();

    if(args.Length() < 1)
    {
        NanThrowError("Wrong number of arguments.");
    }

    Local<Value> pre_filename = args[0];
    if(!pre_filename->IsString())
    {
        NanThrowError("Filename should be a string.");
    }

    char* filename = *NanAsciiString(args[0]);
    //Local<String>::Cast(args[0])->WriteAscii(filename);

    FILE* fp = fopen(filename, "rb");
    if(NULL == fp)
    {
        NanThrowError("Can't open this file.");
    }

    unsigned int filesize;
    fseek(fp, 0, SEEK_END);
    filesize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char* filebuf = new char[filesize];
    fread(filebuf, filesize, 1, fp);
    fclose(fp);

    const char* pbuf = filebuf;
    const char* pbuf_end = filebuf + filesize;

    // check is it mp4
    if(pbuf_end - pbuf < 7)
    {
        NanThrowError("File is too small.");
    }

    char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 };
    for(int i = 0; i < 8; i++)
    {
        if(i == 3) continue;
        if(sign[i] != *(pbuf + i))
        {
            NanThrowError("Broken MP4 file.");
        }
    }

    double file_duration = 0.0f;
    try
    {
        file_duration = ParseDuration(pbuf, pbuf_end);
    }
    catch(...)
    {
        NanThrowError("Broken file or this format is not supported.");
    }

    NanReturnValue(NanNew<Number>(file_duration));
}

void InitAll(Handle<Object> exports)
{
    exports->Set(NanNew<String>("parseByFilename"),
            NanNew<FunctionTemplate>(ParseViaFile)->GetFunction());
    exports->Set(NanNew<String>("parseByBuffer"),
            NanNew<FunctionTemplate>(ParseViaBuffer)->GetFunction());
}

NODE_MODULE(mp4duration, InitAll);

<commit_msg>fix a bug of NanThrowError()<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  mp4duration.cc
 *
 *    Description:  MP4 duration parser - node.js c++ addon
 *
 *        Version:  1.0
 *        Created:  2014/10/24 16时14分34秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  XadillaX (http://xcoder.in/), admin@xcoder.in
 *   Organization:  Touhou Gensokyo
 *
 * =====================================================================================
 */
#include <node.h>
#include <node_buffer.h>
#include "parse.h"
#include <stdio.h>
#include <string.h>
#include <nan.h>
using namespace v8;
using namespace node;

NAN_METHOD(ParseViaBuffer)
{
    NanScope();

    if(args.Length() < 1)
    {
        return NanThrowError("Wrong number of arguments.");
    }

    Local<Value> arg = args[0];
    if(!node::Buffer::HasInstance(arg))
    {
        return NanThrowError("Bad argument!");
    }

    size_t size = Buffer::Length(arg->ToObject());
    char* pbuf = Buffer::Data(arg->ToObject());
    char* pbuf_end = pbuf + size;

    // check is it mp4
    if(pbuf_end - pbuf < 7)
    {
        return NanThrowError("File is too small.");
    }

    char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 };
    for(int i = 0; i < 8; i++)
    {
        if(i == 3) continue;
        if(sign[i] != *(pbuf + i))
        {
            return NanThrowError("Broken MP4 file.");
        }
    }

    double file_duration = 0.0f;
    try
    {
        file_duration = ParseDuration(pbuf, pbuf_end);
    }
    catch(...)
    {
        return NanThrowError("Broken file or this format is not supported.");
    }

    NanReturnValue(NanNew<Number>(file_duration));
}

NAN_METHOD(ParseViaFile)
{
    NanScope();

    if(args.Length() < 1)
    {
        return NanThrowError("Wrong number of arguments.");
    }

    Local<Value> pre_filename = args[0];
    if(!pre_filename->IsString())
    {
        return NanThrowError("Filename should be a string.");
    }

    char* filename = *NanAsciiString(args[0]);

    FILE* fp = fopen(filename, "rb");
    if(NULL == fp)
    {
        return NanThrowError("Can't open this file.");
    }

    unsigned int filesize;
    fseek(fp, 0, SEEK_END);
    filesize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char* filebuf = new char[filesize];
    fread(filebuf, filesize, 1, fp);
    fclose(fp);

    const char* pbuf = filebuf;
    const char* pbuf_end = filebuf + filesize;

    // check is it mp4
    if(pbuf_end - pbuf < 7)
    {
        return NanThrowError("File is too small.");
    }

    char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 };
    for(int i = 0; i < 8; i++)
    {
        if(i == 3) continue;
        if(sign[i] != *(pbuf + i))
        {
            return NanThrowError("Broken MP4 file.");
        }
    }

    double file_duration = 0.0f;
    try
    {
        file_duration = ParseDuration(pbuf, pbuf_end);
    }
    catch(...)
    {
        return NanThrowError("Broken file or this format is not supported.");
    }

    NanReturnValue(NanNew<Number>(file_duration));
}

void InitAll(Handle<Object> exports)
{
    exports->Set(NanNew<String>("parseByFilename"),
            NanNew<FunctionTemplate>(ParseViaFile)->GetFunction());
    exports->Set(NanNew<String>("parseByBuffer"),
            NanNew<FunctionTemplate>(ParseViaBuffer)->GetFunction());
}

NODE_MODULE(mp4duration, InitAll);

<|endoftext|>


<commit_before>#include <iostream>
#include "GL/glew.h"

#include "pbge/gfx/VBO.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/ShaderUniform.h"
#include "pbge/gfx/UniformSet.h"

#include "pbge/gfx/OpenGL/GLGraphic.h"
#include "pbge/gfx/OpenGL/GLDrawController.h"

using namespace pbge;

GLDrawController::GLDrawController(GLGraphic * _ogl) {
    this->ogl = _ogl;
    coreSupported = false;
    arbSupported = false;
    extSupported = false;
}

void GLDrawController::initialize() {
    if(GLEW_VERSION_3_1 || GLEW_VERSION_3_2 || GLEW_VERSION_3_3 || GLEW_VERSION_4_0) {
        coreSupported = true;
    }
    if(GLEW_ARB_draw_instanced) {
        arbSupported = true;
    }
    if(GLEW_EXT_draw_instanced) {
        extSupported = true;
    }
}

void GLDrawController::draw(Model * model) {
    model->beforeRender(ogl);
    callRender(model);
    model->afterRender(ogl);
}

void GLDrawController::draw(Model * model, int times) {
    model->beforeRender(ogl);
    UniformSet uniforms;
    ogl->pushUniforms(&uniforms);
    // FIXME: replace by getInt
    UniformFloat * instanceID = uniforms.getFloat("instanceID");
    for(int i = 0; i < times; i++) {
        instanceID->setValue((float)i);
        callRender(model);
    }
    ogl->popUniforms();
    model->afterRender(ogl);
}

void GLDrawController::drawVBOModel(VBOModel *model) {
    bindVBO(model->getVBO());
    glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
    unbindVBO(model->getVBO());
}

// Instanced Rendering optimization if possible
void GLDrawController::drawVBOModel(VBOModel *model, int times) {
    bindVBO(model->getVBO());
    if(coreSupported) {

    } else if(arbSupported) {
        glDrawArraysInstancedARB(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
    } else {
        for(int i = 0; i < times; i++) {
            glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
        }
    }
    unbindVBO(model->getVBO());
}

void GLDrawController::callRender(Model * model) {
    model->render(ogl);
}

#define ATTRIB_POINTER_OFFSET(offset) ((GLbyte *)NULL + (offset))

void GLDrawController::bindVBO(VertexBuffer * buffer) {
    glEnable(GL_VERTEX_ARRAY);
    buffer->getBuffer()->bindOn(Buffer::VertexBuffer);
    std::vector<VertexAttrib>::iterator attr;
    std::vector<VertexAttrib> & attribs = buffer->getAttribs();
    for(attr = attribs.begin(); attr != attribs.end(); attr++) {
        if(attr->getType() == VertexAttrib::VERTEX) {
            glEnableClientState(GL_VERTEX_ARRAY);
            glVertexPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        }
        else if (attr->getType() == VertexAttrib::NORMAL) {
            glEnableClientState(GL_NORMAL_ARRAY);
            glNormalPointer(GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        } else if(attr->getType() == VertexAttrib::COLOR) {
            glEnableClientState(GL_COLOR_ARRAY);
            glColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        } else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
            glEnableClientState(GL_SECONDARY_COLOR_ARRAY);
            glSecondaryColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        } else if(attr->getType() == VertexAttrib::TEXCOORD) {
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            glTexCoordPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        }
    }
}

#undef ATTRIB_POINTER_OFFSET

void GLDrawController::unbindVBO(VertexBuffer * buffer) {
    std::vector<VertexAttrib>::iterator attr;
    std::vector<VertexAttrib> & attribs = buffer->getAttribs();
    for(attr = attribs.begin(); attr != attribs.end(); attr++) {
        if(attr->getType() == VertexAttrib::VERTEX) {
            glDisableClientState(GL_VERTEX_ARRAY);
        }
        else if (attr->getType() == VertexAttrib::NORMAL) {
            glDisableClientState(GL_NORMAL_ARRAY);
        } else if(attr->getType() == VertexAttrib::COLOR) {
            glDisableClientState(GL_COLOR_ARRAY);
        } else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
            glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
        } else if(attr->getType() == VertexAttrib::TEXCOORD) {
            glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        }
    }
    buffer->getBuffer()->unbind();
    glDisable(GL_VERTEX_ARRAY);
}
<commit_msg>core instanced rendering implementation<commit_after>#include <iostream>
#include "GL/glew.h"

#include "pbge/gfx/VBO.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/ShaderUniform.h"
#include "pbge/gfx/UniformSet.h"

#include "pbge/gfx/OpenGL/GLGraphic.h"
#include "pbge/gfx/OpenGL/GLDrawController.h"

using namespace pbge;

GLDrawController::GLDrawController(GLGraphic * _ogl) {
    this->ogl = _ogl;
    coreSupported = false;
    arbSupported = false;
    extSupported = false;
}

void GLDrawController::initialize() {
    if(GLEW_VERSION_3_1 || GLEW_VERSION_3_2 || GLEW_VERSION_3_3 || GLEW_VERSION_4_0) {
        coreSupported = true;
    }
    if(GLEW_ARB_draw_instanced) {
        arbSupported = true;
    }
    if(GLEW_EXT_draw_instanced) {
        extSupported = true;
    }
}

void GLDrawController::draw(Model * model) {
    model->beforeRender(ogl);
    callRender(model);
    model->afterRender(ogl);
}

void GLDrawController::draw(Model * model, int times) {
    model->beforeRender(ogl);
    UniformSet uniforms;
    ogl->pushUniforms(&uniforms);
    // FIXME: replace by getInt
    UniformFloat * instanceID = uniforms.getFloat("instanceID");
    for(int i = 0; i < times; i++) {
        instanceID->setValue((float)i);
        callRender(model);
    }
    ogl->popUniforms();
    model->afterRender(ogl);
}

void GLDrawController::drawVBOModel(VBOModel *model) {
    bindVBO(model->getVBO());
    glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
    unbindVBO(model->getVBO());
}

// Instanced Rendering optimization if possible
void GLDrawController::drawVBOModel(VBOModel *model, int times) {
    bindVBO(model->getVBO());
    if(coreSupported) {
        glDrawArraysInstanced(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
    } else if(arbSupported) {
        glDrawArraysInstancedARB(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
    } else if(extSupported) {
        // ......
    } else {
        for(int i = 0; i < times; i++) {
            glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
        }
    }
    unbindVBO(model->getVBO());
}

void GLDrawController::callRender(Model * model) {
    model->render(ogl);
}

#define ATTRIB_POINTER_OFFSET(offset) ((GLbyte *)NULL + (offset))

void GLDrawController::bindVBO(VertexBuffer * buffer) {
    glEnable(GL_VERTEX_ARRAY);
    buffer->getBuffer()->bindOn(Buffer::VertexBuffer);
    std::vector<VertexAttrib>::iterator attr;
    std::vector<VertexAttrib> & attribs = buffer->getAttribs();
    for(attr = attribs.begin(); attr != attribs.end(); attr++) {
        if(attr->getType() == VertexAttrib::VERTEX) {
            glEnableClientState(GL_VERTEX_ARRAY);
            glVertexPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        }
        else if (attr->getType() == VertexAttrib::NORMAL) {
            glEnableClientState(GL_NORMAL_ARRAY);
            glNormalPointer(GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        } else if(attr->getType() == VertexAttrib::COLOR) {
            glEnableClientState(GL_COLOR_ARRAY);
            glColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        } else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
            glEnableClientState(GL_SECONDARY_COLOR_ARRAY);
            glSecondaryColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        } else if(attr->getType() == VertexAttrib::TEXCOORD) {
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            glTexCoordPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
        }
    }
}

#undef ATTRIB_POINTER_OFFSET

void GLDrawController::unbindVBO(VertexBuffer * buffer) {
    std::vector<VertexAttrib>::iterator attr;
    std::vector<VertexAttrib> & attribs = buffer->getAttribs();
    for(attr = attribs.begin(); attr != attribs.end(); attr++) {
        if(attr->getType() == VertexAttrib::VERTEX) {
            glDisableClientState(GL_VERTEX_ARRAY);
        }
        else if (attr->getType() == VertexAttrib::NORMAL) {
            glDisableClientState(GL_NORMAL_ARRAY);
        } else if(attr->getType() == VertexAttrib::COLOR) {
            glDisableClientState(GL_COLOR_ARRAY);
        } else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
            glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
        } else if(attr->getType() == VertexAttrib::TEXCOORD) {
            glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        }
    }
    buffer->getBuffer()->unbind();
    glDisable(GL_VERTEX_ARRAY);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>

class TestCase {
	public:
  	TestCase (const std::string& testName) : testName(testName) {;}

    virtual std::string getTestName() const {return testName;}
    virtual void runTest() const = 0;

  private:
    std::string testName;
};

class TestSet {
	public:
		static TestSet& getTestSet() {
    	static TestSet* tset = new TestSet();
      return *tset;
    }

    void addTest(const TestCase* b) {
			tests.push_back(b);
    	std::cout << "adding test " << b->getTestName() << std::endl;
    }

		void run() {
			for (size_t i = 0; i < tests.size(); ++i) {
				tests[i]->runTest();
			}
		}

	private:
		std::vector<const TestCase*> tests;
  	TestSet()  {;}
    ~TestSet()  {;}
};

class TestCaseAdder {
	public:
  	TestCaseAdder(const TestCase* b) {
    	TestSet::getTestSet().addTest(b);
   	}

    ~TestCaseAdder() { }
};

#define TEST(NAME)                                                    \
	class NAME : public TestCase {                                      \
    public:                                                           \
    	NAME(const std::string& testName) : TestCase( testName ) { ; }  \
      virtual void runTest() const;                                   \
    private:                                                          \
      static TestCaseAdder adder;                                     \
  };                                                                  \
  TestCaseAdder NAME::adder(new NAME(#NAME));                         \
  void NAME::runTest() const

<commit_msg>improved code documentation in TinyTest.hpp<commit_after>#include <iostream>
#include <string>
#include <vector>

/******************************************************************************
 **       Classes for definition, and automagic detection of test cases      **
 ******************************************************************************/

/**
 * \brief TODO
 */
class TestCase {
	public:
  	TestCase (const std::string& testName) : testName(testName) {;}
  	virtual ~TestCase();

    virtual std::string getTestName() const {return testName;}
    virtual void runTest() const = 0;

  private:
    std::string testName;
};

/**
 * \brief TODO
 */
class TestSet {
	public:
		static TestSet& getTestSet() {
    	static TestSet* tset = new TestSet();
      return *tset;
    }

    void addTest(const TestCase* b) {
			tests.push_back(b);
    	std::cout << "adding test " << b->getTestName() << std::endl;
    }

		void run() {
			for (size_t i = 0; i < tests.size(); ++i) {
				tests[i]->runTest();
			}
		}

	private:
		std::vector<const TestCase*> tests;
  	TestSet()  {;}
    ~TestSet()  {;}
};

/**
 * \brief TODO
 */
class TestCaseAdder {
	public:
  	TestCaseAdder(const TestCase* b) {
    	TestSet::getTestSet().addTest(b);
   	}

    ~TestCaseAdder() { }
};

/******************************************************************************
 **                   Macros for test case definition                        **
 ******************************************************************************/

#define TEST(NAME)                                                    \
	class NAME : public TestCase {                                      \
    public:                                                           \
    	NAME(const std::string& testName) : TestCase( testName ) { ; }  \
      virtual void runTest() const;                                   \
    private:                                                          \
      static TestCaseAdder adder;                                     \
  };                                                                  \
  TestCaseAdder NAME::adder(new NAME(#NAME));                         \
  void NAME::runTest() const

/******************************************************************************
 **               Macros for testing conditions in test cases                **
 ******************************************************************************/

<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.
    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "datenavigator.h"

#include <calendarsystem/kcalendarsystem.h>

#include "kocore.h"

#include <kdebug.h>

using namespace KCal;

DateNavigator::DateNavigator( QObject *parent, const char *name )
  : QObject( parent, name )
{
  mSelectedDates.append( QDate::currentDate() );
}

DateNavigator::~DateNavigator()
{
}

DateList DateNavigator::selectedDates()
{
  return mSelectedDates;
}

int DateNavigator::datesCount() const
{
  return mSelectedDates.count();
}

void DateNavigator::selectDates( const DateList& dateList )
{
  if (dateList.count() > 0) {
    mSelectedDates = dateList;

    emitSelected();
  }
}

void DateNavigator::selectDate( const QDate &date )
{
  QDate d = date;

  if ( !d.isValid() ) {
    kdDebug() << "DateNavigator::selectDates(QDate): an invalid date was passed as a parameter!" << endl;
    d = QDate::currentDate();
  }

  mSelectedDates.clear();
  mSelectedDates.append( d );

  emitSelected();
}

void DateNavigator::selectDates( int count )
{
  selectDates( mSelectedDates.first(), count );
}

void DateNavigator::selectDates( const QDate &d, int count )
{
  DateList dates;

  int i;
  for( i = 0; i < count; ++i ) {
    dates.append( d.addDays( i ) );
  }

  mSelectedDates = dates;

  emitSelected();
}

void DateNavigator::selectWeekByDay( int weekDay, const QDate &d )
{
  int dateCount = mSelectedDates.count();
  bool weekStart = ( weekDay == KGlobal::locale()->weekStartDay() );
  if ( weekStart && dateCount == 5 ) selectWorkWeek( d );
  else if ( weekStart && dateCount == 7 ) selectWeek( d );
  else selectDates( d, dateCount );
}

void DateNavigator::selectWeek()
{
  selectWeek( mSelectedDates.first() );
}

void DateNavigator::selectWeek( const QDate &d )
{
  QDate firstDate;

  int dayOfWeek = KOCore::self()->calendarSystem()->dayOfTheWeek( d );

  firstDate = d.addDays( KGlobal::locale()->weekStartDay() - dayOfWeek );

  selectDates( firstDate, 7 );
}

void DateNavigator::selectWorkWeek()
{
  selectWorkWeek( mSelectedDates.first() );
}

void DateNavigator::selectWorkWeek( const QDate &d )
{
  QDate firstDate;

  int dayOfWeek = KOCore::self()->calendarSystem()->dayOfTheWeek( d );

  firstDate = d.addDays( KGlobal::locale()->weekStartDay() - dayOfWeek );

  selectDates( firstDate, 5 );
}

void DateNavigator::selectToday()
{
  QDate d = QDate::currentDate();

  int dateCount = mSelectedDates.count();

  if ( dateCount == 5 ) selectWorkWeek( d );
  else if ( dateCount == 7 ) selectWeek( d );
  else selectDates( d, dateCount );
}

void DateNavigator::selectPreviousYear()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();
  KOCore::self()->calendarSystem()->previousYearDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectPreviousMonth()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();
  KOCore::self()->calendarSystem()->previousMonthDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectNextMonth()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();

  KOCore::self()->calendarSystem()->nextMonthDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectNextYear()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();
  KOCore::self()->calendarSystem()->nextYearDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectPrevious()
{
  int offset = -7;
  if ( datesCount() == 1 ) {
    offset = -1;
  }

  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );
}

void DateNavigator::selectNext()
{
  int offset = 7;
  if ( datesCount() == 1 ) {
    offset = 1;
  }

  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );
}

void DateNavigator::emitSelected()
{
  emit datesSelected( mSelectedDates );
}

#include "datenavigator.moc"
<commit_msg>Fix date navigation for week starting on Sunday.<commit_after>/*
    This file is part of KOrganizer.
    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "datenavigator.h"

#include <calendarsystem/kcalendarsystem.h>

#include "kocore.h"

#include <kdebug.h>

using namespace KCal;

DateNavigator::DateNavigator( QObject *parent, const char *name )
  : QObject( parent, name )
{
  mSelectedDates.append( QDate::currentDate() );
}

DateNavigator::~DateNavigator()
{
}

DateList DateNavigator::selectedDates()
{
  return mSelectedDates;
}

int DateNavigator::datesCount() const
{
  return mSelectedDates.count();
}

void DateNavigator::selectDates( const DateList& dateList )
{
  if (dateList.count() > 0) {
    mSelectedDates = dateList;

    emitSelected();
  }
}

void DateNavigator::selectDate( const QDate &date )
{
  QDate d = date;

  if ( !d.isValid() ) {
    kdDebug() << "DateNavigator::selectDates(QDate): an invalid date was passed as a parameter!" << endl;
    d = QDate::currentDate();
  }

  mSelectedDates.clear();
  mSelectedDates.append( d );

  emitSelected();
}

void DateNavigator::selectDates( int count )
{
  selectDates( mSelectedDates.first(), count );
}

void DateNavigator::selectDates( const QDate &d, int count )
{
  DateList dates;

  int i;
  for( i = 0; i < count; ++i ) {
    dates.append( d.addDays( i ) );
  }

  mSelectedDates = dates;

  emitSelected();
}

void DateNavigator::selectWeekByDay( int weekDay, const QDate &d )
{
  int dateCount = mSelectedDates.count();
  bool weekStart = ( weekDay == KGlobal::locale()->weekStartDay() );
  if ( weekDay == 1 && dateCount == 5 ) selectWorkWeek( d );
  else if ( weekStart && dateCount == 7 ) selectWeek( d );
  else selectDates( d, dateCount );
}

void DateNavigator::selectWeek()
{
  selectWeek( mSelectedDates.first() );
}

void DateNavigator::selectWeek( const QDate &d )
{
  int dayOfWeek = KOCore::self()->calendarSystem()->dayOfTheWeek( d );

  int weekStart = KGlobal::locale()->weekStartDay();

  QDate firstDate = d.addDays( weekStart - dayOfWeek );

  if ( weekStart != 1 && dayOfWeek < weekStart ) {
    firstDate = firstDate.addDays( -7 );
  }

  selectDates( firstDate, 7 );
}

void DateNavigator::selectWorkWeek()
{
  selectWorkWeek( mSelectedDates.first() );
}

void DateNavigator::selectWorkWeek( const QDate &d )
{
  int dayOfWeek = KOCore::self()->calendarSystem()->dayOfTheWeek( d );

  QDate firstDate = d.addDays( 1 - dayOfWeek );

  int weekStart = KGlobal::locale()->weekStartDay();
  if ( weekStart != 1 && dayOfWeek >= weekStart ) {
    firstDate = firstDate.addDays( 7 );
  }

  selectDates( firstDate, 5 );
}

void DateNavigator::selectToday()
{
  QDate d = QDate::currentDate();

  int dateCount = mSelectedDates.count();

  if ( dateCount == 5 ) selectWorkWeek( d );
  else if ( dateCount == 7 ) selectWeek( d );
  else selectDates( d, dateCount );
}

void DateNavigator::selectPreviousYear()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();
  KOCore::self()->calendarSystem()->previousYearDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectPreviousMonth()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();
  KOCore::self()->calendarSystem()->previousMonthDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectNextMonth()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();

  KOCore::self()->calendarSystem()->nextMonthDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectNextYear()
{
  QDate firstSelected = mSelectedDates.first();
  int weekDay = firstSelected.dayOfWeek();
  KOCore::self()->calendarSystem()->nextYearDate( firstSelected );

  selectWeekByDay( weekDay, firstSelected );
}

void DateNavigator::selectPrevious()
{
  int offset = -7;
  if ( datesCount() == 1 ) {
    offset = -1;
  }

  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );
}

void DateNavigator::selectNext()
{
  int offset = 7;
  if ( datesCount() == 1 ) {
    offset = 1;
  }

  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );
}

void DateNavigator::emitSelected()
{
  emit datesSelected( mSelectedDates );
}

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


<commit_before>#include <node.h>
#include <node_events.h>
#include <v8.h>
#include <ev.h>

#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include <CoreServices/CoreServices.h>

#define MAXPATH 1024

typedef struct s_evt *p_evt;
struct s_evt {
	FSEventStreamEventFlags flags;
	FSEventStreamEventId evtid;
	char path[MAXPATH + 1];
	p_evt next;
};
static v8::Persistent<v8::FunctionTemplate> constructor_template;
namespace node_fsevents {
	using namespace v8;
	using namespace node;
	class NodeFSEvents : node::ObjectWrap {
		public:

			static void Initialize(v8::Handle<v8::Object> target) {
				HandleScope scope;
			  Local<FunctionTemplate> t = FunctionTemplate::New(NodeFSEvents::New);
			  constructor_template = Persistent<FunctionTemplate>::New(t);
			  constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
			  constructor_template->SetClassName(String::NewSymbol("FSEvents"));
				Local<Function> constructor = constructor_template->GetFunction();

				constructor->Set(String::New("kFSEventStreamEventFlagNone"), Integer::New(0x00000000));
				constructor->Set(String::New("kFSEventStreamEventFlagMustScanSubDirs"), Integer::New(0x00000001));
			  constructor->Set(String::New("kFSEventStreamEventFlagUserDropped"), Integer::New(0x00000002));
				constructor->Set(String::New("kFSEventStreamEventFlagKernelDropped"), Integer::New(0x00000004));
				constructor->Set(String::New("kFSEventStreamEventFlagEventIdsWrapped"), Integer::New(0x00000008));
				constructor->Set(String::New("kFSEventStreamEventFlagHistoryDone"), Integer::New(0x00000010));
				constructor->Set(String::New("kFSEventStreamEventFlagRootChanged"), Integer::New(0x00000020));
				constructor->Set(String::New("kFSEventStreamEventFlagMount"), Integer::New(0x00000040));
				constructor->Set(String::New("kFSEventStreamEventFlagUnmount"), Integer::New(0x00000080));

				target->Set(String::NewSymbol("FSEvents"), constructor);
			}
			static v8::Handle<v8::Value> New(const v8::Arguments& args) {
			  if (!args.IsConstructCall()) {
			    return FromConstructorTemplate(constructor_template, args);
			  }

			  HandleScope scope;

			  if (args.Length() < 1 || !args[0]->IsString()) {
			    return ThrowException(String::New("Bad arguments"));
			  }

				String::Utf8Value pathname(args[0]->ToString());

				FSEventStreamEventId since = kFSEventStreamEventIdSinceNow;
				if ((args.Length() > 1) && (args[1]->IsInt32())) {
					since = args[1]->Int32Value();
				}
			  NodeFSEvents *nativeobj = new NodeFSEvents(*pathname, since);
			  nativeobj->Wrap(args.Holder());

			  return args.This();
			}

			NodeFSEvents(const char *path, FSEventStreamEventId since) : ObjectWrap() {
				first = NULL;
				last = NULL;
				pathname = strncpy(pathname, path ? path : "/", MAXPATH);
				sinceWhen = since;
				pthread_mutex_init(&mutex, NULL);
				ev_async_init(&watcher, NodeFSEvents::Poll);
				watcher.data = this;
				ev_async_start (EV_DEFAULT_UC_ &watcher);
				pthread_create(&thread, NULL, &NodeFSEvents::Run, this);
			}

			~NodeFSEvents() {
				CFRunLoopStop(runLoop);
				pthread_join(thread, NULL);
				pthread_mutex_destroy(&mutex);
				free(this->pathname);
				ev_async_stop(EV_DEFAULT_UC_ &watcher);
			}

			static void *Run(void *data) {
				NodeFSEvents *This = (NodeFSEvents *)data;
				CFStringRef dir_names[1];
				dir_names[0] = CFStringCreateWithCString(NULL, This->pathname, kCFStringEncodingUTF8);
				CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&dir_names, 1, NULL);
			  FSEventStreamContext context = { 0, data, NULL, NULL, NULL };
				FSEventStreamRef stream = FSEventStreamCreate(NULL, &NodeFSEvents::Event, &context, pathsToWatch, This->sinceWhen, (CFAbsoluteTime) 0.1, kFSEventStreamCreateFlagNone | kFSEventStreamCreateFlagWatchRoot);
				This->runLoop = CFRunLoopGetCurrent();
				FSEventStreamScheduleWithRunLoop(stream, This->runLoop, kCFRunLoopDefaultMode);
				FSEventStreamStart(stream);
				CFRunLoopRun();
				FSEventStreamStop(stream);
				FSEventStreamUnscheduleFromRunLoop(stream, This->runLoop, kCFRunLoopDefaultMode);
				FSEventStreamInvalidate(stream);
				FSEventStreamRelease(stream);
				pthread_exit(NULL);
			}
			static void Event(ConstFSEventStreamRef streamRef, void *userData, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) {
				NodeFSEvents *This = static_cast<NodeFSEvents*>(userData);
				char **paths = static_cast<char**>(eventPaths);
				size_t idx;
				p_evt item;
				pthread_mutex_lock(&(This->mutex));
				for (idx=0; idx < numEvents; idx++) {
					item = (p_evt)malloc(sizeof(struct s_evt));
					item->next = NULL;
					strncpy(item->path, paths[idx],MAXPATH);
					item->flags = eventFlags[idx];
					item->evtid = eventIds[idx];
					if (!This->first) This->first = item;
					if (This->last) {
						This->last->next = item;
					}
					This->last = item;
				}
				pthread_mutex_unlock(&(This->mutex));
				ev_async_send (EV_DEFAULT_UC_ &(This->watcher));
			}
			static void Poll(EV_P_ ev_async *w, int revents) {
				NodeFSEvents *This = static_cast<NodeFSEvents*>(w->data);
				HandleScope scope;
				TryCatch try_catch;
				Local<Value> callback_v = This->handle_->Get(String::New("emit"));
				Local<Function> callback = Local<Function>::Cast(callback_v);
				p_evt item;
				pthread_mutex_lock(&(This->mutex));
				item = This->first;
				v8::Handle<v8::Value> args[4];
				args[0] = v8::String::New("change");
				while (item) {
					This->first = item->next;
					args[1] = v8::String::New(item->path ? item->path : "");
					args[2] = v8::Integer::New(item->flags);
					args[3] = v8::Integer::New(item->evtid);
					callback->Call(This->handle_, 4, args);
					free(item);
					item = This->first;
				}
				This->first = NULL;
				This->last = NULL;
				pthread_mutex_unlock(&(This->mutex));
			}

			char pathname[MAXPATH + 1];
			CFRunLoopRef runLoop;
			p_evt last;
			p_evt first;
			ev_async watcher;
			pthread_t thread;
			pthread_mutex_t mutex;
			FSEventStreamEventId sinceWhen;
	};
	extern "C" void init(v8::Handle<v8::Object> target) {
		node_fsevents::NodeFSEvents::Initialize(target);
	}
}

<commit_msg>Stupid Error<commit_after>#include <node.h>
#include <node_events.h>
#include <v8.h>
#include <ev.h>

#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include <CoreServices/CoreServices.h>

#define MAXPATH 1024

typedef struct s_evt *p_evt;
struct s_evt {
	FSEventStreamEventFlags flags;
	FSEventStreamEventId evtid;
	char path[MAXPATH + 1];
	p_evt next;
};
static v8::Persistent<v8::FunctionTemplate> constructor_template;
namespace node_fsevents {
	using namespace v8;
	using namespace node;
	class NodeFSEvents : node::ObjectWrap {
		public:

			static void Initialize(v8::Handle<v8::Object> target) {
				HandleScope scope;
			  Local<FunctionTemplate> t = FunctionTemplate::New(NodeFSEvents::New);
			  constructor_template = Persistent<FunctionTemplate>::New(t);
			  constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
			  constructor_template->SetClassName(String::NewSymbol("FSEvents"));
				Local<Function> constructor = constructor_template->GetFunction();

				constructor->Set(String::New("kFSEventStreamEventFlagNone"), Integer::New(0x00000000));
				constructor->Set(String::New("kFSEventStreamEventFlagMustScanSubDirs"), Integer::New(0x00000001));
			  constructor->Set(String::New("kFSEventStreamEventFlagUserDropped"), Integer::New(0x00000002));
				constructor->Set(String::New("kFSEventStreamEventFlagKernelDropped"), Integer::New(0x00000004));
				constructor->Set(String::New("kFSEventStreamEventFlagEventIdsWrapped"), Integer::New(0x00000008));
				constructor->Set(String::New("kFSEventStreamEventFlagHistoryDone"), Integer::New(0x00000010));
				constructor->Set(String::New("kFSEventStreamEventFlagRootChanged"), Integer::New(0x00000020));
				constructor->Set(String::New("kFSEventStreamEventFlagMount"), Integer::New(0x00000040));
				constructor->Set(String::New("kFSEventStreamEventFlagUnmount"), Integer::New(0x00000080));

				target->Set(String::NewSymbol("FSEvents"), constructor);
			}
			static v8::Handle<v8::Value> New(const v8::Arguments& args) {
			  if (!args.IsConstructCall()) {
			    return FromConstructorTemplate(constructor_template, args);
			  }

			  HandleScope scope;

			  if (args.Length() < 1 || !args[0]->IsString()) {
			    return ThrowException(String::New("Bad arguments"));
			  }

				String::Utf8Value pathname(args[0]->ToString());

				FSEventStreamEventId since = kFSEventStreamEventIdSinceNow;
				if ((args.Length() > 1) && (args[1]->IsInt32())) {
					since = args[1]->Int32Value();
				}
			  NodeFSEvents *nativeobj = new NodeFSEvents(*pathname, since);
			  nativeobj->Wrap(args.Holder());

			  return args.This();
			}

			NodeFSEvents(const char *path, FSEventStreamEventId since) : ObjectWrap() {
				first = NULL;
				last = NULL;
				strncpy(pathname, path ? path : "/", MAXPATH);
				sinceWhen = since;
				pthread_mutex_init(&mutex, NULL);
				ev_async_init(&watcher, NodeFSEvents::Poll);
				watcher.data = this;
				ev_async_start (EV_DEFAULT_UC_ &watcher);
				pthread_create(&thread, NULL, &NodeFSEvents::Run, this);
			}

			~NodeFSEvents() {
				CFRunLoopStop(runLoop);
				pthread_join(thread, NULL);
				pthread_mutex_destroy(&mutex);
				free(this->pathname);
				ev_async_stop(EV_DEFAULT_UC_ &watcher);
			}

			static void *Run(void *data) {
				NodeFSEvents *This = (NodeFSEvents *)data;
				CFStringRef dir_names[1];
				dir_names[0] = CFStringCreateWithCString(NULL, This->pathname, kCFStringEncodingUTF8);
				CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&dir_names, 1, NULL);
			  FSEventStreamContext context = { 0, data, NULL, NULL, NULL };
				FSEventStreamRef stream = FSEventStreamCreate(NULL, &NodeFSEvents::Event, &context, pathsToWatch, This->sinceWhen, (CFAbsoluteTime) 0.1, kFSEventStreamCreateFlagNone | kFSEventStreamCreateFlagWatchRoot);
				This->runLoop = CFRunLoopGetCurrent();
				FSEventStreamScheduleWithRunLoop(stream, This->runLoop, kCFRunLoopDefaultMode);
				FSEventStreamStart(stream);
				CFRunLoopRun();
				FSEventStreamStop(stream);
				FSEventStreamUnscheduleFromRunLoop(stream, This->runLoop, kCFRunLoopDefaultMode);
				FSEventStreamInvalidate(stream);
				FSEventStreamRelease(stream);
				pthread_exit(NULL);
			}
			static void Event(ConstFSEventStreamRef streamRef, void *userData, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) {
				NodeFSEvents *This = static_cast<NodeFSEvents*>(userData);
				char **paths = static_cast<char**>(eventPaths);
				size_t idx;
				p_evt item;
				pthread_mutex_lock(&(This->mutex));
				for (idx=0; idx < numEvents; idx++) {
					item = (p_evt)malloc(sizeof(struct s_evt));
					item->next = NULL;
					strncpy(item->path, paths[idx],MAXPATH);
					item->flags = eventFlags[idx];
					item->evtid = eventIds[idx];
					if (!This->first) This->first = item;
					if (This->last) {
						This->last->next = item;
					}
					This->last = item;
				}
				pthread_mutex_unlock(&(This->mutex));
				ev_async_send (EV_DEFAULT_UC_ &(This->watcher));
			}
			static void Poll(EV_P_ ev_async *w, int revents) {
				NodeFSEvents *This = static_cast<NodeFSEvents*>(w->data);
				HandleScope scope;
				TryCatch try_catch;
				Local<Value> callback_v = This->handle_->Get(String::New("emit"));
				Local<Function> callback = Local<Function>::Cast(callback_v);
				p_evt item;
				pthread_mutex_lock(&(This->mutex));
				item = This->first;
				v8::Handle<v8::Value> args[4];
				args[0] = v8::String::New("change");
				while (item) {
					This->first = item->next;
					args[1] = v8::String::New(item->path ? item->path : "");
					args[2] = v8::Integer::New(item->flags);
					args[3] = v8::Integer::New(item->evtid);
					callback->Call(This->handle_, 4, args);
					free(item);
					item = This->first;
				}
				This->first = NULL;
				This->last = NULL;
				pthread_mutex_unlock(&(This->mutex));
			}

			char pathname[MAXPATH + 1];
			CFRunLoopRef runLoop;
			p_evt last;
			p_evt first;
			ev_async watcher;
			pthread_t thread;
			pthread_mutex_t mutex;
			FSEventStreamEventId sinceWhen;
	};
	extern "C" void init(v8::Handle<v8::Object> target) {
		node_fsevents::NodeFSEvents::Initialize(target);
	}
}

<|endoftext|>


<commit_before>/**
 * @file noise.cpp
 * @brief  Brief description of file.
 *
 */

#include <math.h>
#include <angort/angort.h>
#include "../hashgets.h"
#include "../wrappers.h"
#include "perlin.h"

using namespace angort;

static WrapperType<PerlinNoise> tPerlin("PLNT");

%type perlin tPerlin PerlinNoise

%name noise
%shared

%wordargs makeperlin h (hash -- perlin) make new perlin noise object
{
    PerlinNoise *n = new PerlinNoise();
    n->mPersistence = hgetfloatdef(p0,"persistence",0.5);
    n->mOctaves = hgetintdef(p0,"octaves",2);
    tPerlin.set(a->pushval(),n);
}

%wordargs get nA|perlin (float perlin -- float) get a value
{
    a->pushFloat(p1->get(p0));
}

%init
{
    fprintf(stderr,"Initialising NOISE plugin, %s %s\n",__DATE__,__TIME__);
}
<commit_msg>Noise doc.<commit_after>/**
 * @file noise.cpp
 * @brief  Brief description of file.
 *
 */

#include <math.h>
#include <angort/angort.h>
#include "../hashgets.h"
#include "../wrappers.h"
#include "perlin.h"

using namespace angort;

static WrapperType<PerlinNoise> tPerlin("PLNT");

%type perlin tPerlin PerlinNoise

%name noise
%shared

%wordargs makeperlin h (hash -- perlin) make new perlin noise object
Create a new perlin noise generator object. The hash may contain
two values: persistence and octaves. Read up on the algorithm to see
what these actually mean.
{
    PerlinNoise *n = new PerlinNoise();
    n->mPersistence = hgetfloatdef(p0,"persistence",0.5);
    n->mOctaves = hgetintdef(p0,"octaves",2);
    tPerlin.set(a->pushval(),n);
}

%wordargs get nA|perlin (float perlin -- float) get a value
Generate a value from a perlin noise generator, given an input (typically
a time or spatial coordinate).
{
    a->pushFloat(p1->get(p0));
}

%init
{
    fprintf(stderr,"Initialising NOISE plugin, %s %s\n",__DATE__,__TIME__);
}
<|endoftext|>


<commit_before>// For stat, getcwd
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <fcntl.h>

// For bad_alloc
#include <exception>

#include <boost/filesystem.hpp>
#include <boost/format.hpp>

#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
#include <runner/raise.hh>

namespace object
{
  using boost::format;

  /*------------.
  | C++ methods |
  `------------*/

  const Path::value_type& Path::value_get() const
  {
    return path_;
  }

  /*-------------.
  | Urbi methods |
  `-------------*/

  // Construction

  Path::Path()
    : path_("/")
  {
    proto_add(proto);
  }

  Path::Path(rPath model)
    : path_(model->value_get())
  {
    proto_add(model);
  }

  Path::Path(const std::string& value)
    : path_(value)
  {
    proto_add(proto ? proto : object_class);
  }

  void Path::init(const std::string& path)
  {
    path_ = path;
  }

  // Global informations

  rPath Path::cwd()
  {
    return new Path(boost::filesystem::current_path().string());
  }

  // Stats

  bool Path::absolute()
  {
    return path_.absolute_get();
  }

  bool Path::exists()
  {
    struct stat dummy;

    if (!::stat(path_.to_string().c_str(), &dummy))
      return true;

    handle_any_error();
  }

  struct stat Path::stat()
  {
    struct stat res;

    if (::stat(path_.to_string().c_str(), &res))
      handle_any_error();

    return res;
  }

  bool Path::is_dir()
  {
    return stat().st_mode & S_IFDIR;
  }

  bool Path::is_reg()
  {
    return stat().st_mode & S_IFREG;
  }

  bool Path::readable()
  {
    int fd = ::open(path_.to_string().c_str(), O_RDONLY | O_LARGEFILE);

    if (fd != -1)
    {
      close(fd);
      return true;
    }
    else if (errno == EACCES)
      return false;

    handle_any_error();
  }

  bool Path::writable()
  {
    int fd = ::open(path_.to_string().c_str(),
                    O_WRONLY | O_LARGEFILE | O_APPEND);

    if (fd != -1)
    {
      close(fd);
      return true;
    }
    // EROFS = file is on a read only file system.
    else if (errno == EACCES || errno == EROFS)
      return false;

    handle_any_error();
  }

  // Operations

  std::string Path::basename()
  {
    return path_.basename();
  }

  rPath Path::cd()
  {
    if (chdir(as_string().c_str()))
      handle_any_error();
    return cwd();
  }

  rPath Path::concat(rPath other)
  {
    return new Path(path_ / (*other).path_);
  }

  std::string Path::dirname()
  {
    return path_.dirname();
  }

  rObject Path::open()
  {
    if (is_dir())
      return new Directory(path_);
    if (is_reg())
      return new File(path_);
    runner::raise_primitive_error(str(format("Unsupported file type: %s.") %
				      path_));
  }

  // Conversions

  std::string Path::as_string()
  {
    return path_.to_string();
  }

  std::string Path::as_printable()
  {
    return str(format("\"%s\"") % as_string());
  }

  rList Path::as_list()
  {
    List::value_type res;
    foreach (const std::string& c, path_.components())
      res << new String(c);
    return new List(res);
  }

  /*--------.
  | Details |
  `--------*/

  void Path::handle_any_error()
  {
    runner::raise_primitive_error(str(format("%1%: %2%") %
				      strerror(errno) % path_));
  }

  /*---------------.
  | Binding system |
  `---------------*/

  void Path::initialize(CxxObject::Binder<Path>& bind)
  {
    bind(SYMBOL(absolute), &Path::absolute);
    bind(SYMBOL(asList), &Path::as_list);
    bind(SYMBOL(asPrintable), &Path::as_printable);
    bind(SYMBOL(asString), &Path::as_string);
    bind(SYMBOL(basename), &Path::basename);
    bind(SYMBOL(cd), &Path::cd);
    bind(SYMBOL(cwd), &Path::cwd);
    bind(SYMBOL(dirname), &Path::dirname);
    bind(SYMBOL(exists), &Path::exists);
    bind(SYMBOL(init), &Path::init);
    bind(SYMBOL(isDir), &Path::is_dir);
    bind(SYMBOL(isReg), &Path::is_reg);
    bind(SYMBOL(open), &Path::open);
    bind(SYMBOL(readable), &Path::readable);
    bind(SYMBOL(SLASH), &Path::concat);
    bind(SYMBOL(writable), &Path::writable);
  }

  rObject
  Path::proto_make()
  {
#ifdef WIN32
    return new Path("C:\\");
#else
    return new Path("/");
#endif
  }

  URBI_CXX_OBJECT_REGISTER(Path);
}
<commit_msg>Do not throw an error if path is nonexistent.<commit_after>// For stat, getcwd
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <fcntl.h>

// For bad_alloc
#include <exception>

#include <boost/filesystem.hpp>
#include <boost/format.hpp>

#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
#include <runner/raise.hh>

namespace object
{
  using boost::format;

  /*------------.
  | C++ methods |
  `------------*/

  const Path::value_type& Path::value_get() const
  {
    return path_;
  }

  /*-------------.
  | Urbi methods |
  `-------------*/

  // Construction

  Path::Path()
    : path_("/")
  {
    proto_add(proto);
  }

  Path::Path(rPath model)
    : path_(model->value_get())
  {
    proto_add(model);
  }

  Path::Path(const std::string& value)
    : path_(value)
  {
    proto_add(proto ? proto : object_class);
  }

  void Path::init(const std::string& path)
  {
    path_ = path;
  }

  // Global informations

  rPath Path::cwd()
  {
    return new Path(boost::filesystem::current_path().string());
  }

  // Stats

  bool Path::absolute()
  {
    return path_.absolute_get();
  }

  bool Path::exists()
  {
    struct stat dummy;
    return !::stat(path_.to_string().c_str(), &dummy);
  }

  struct stat Path::stat()
  {
    struct stat res;

    if (::stat(path_.to_string().c_str(), &res))
      handle_any_error();

    return res;
  }

  bool Path::is_dir()
  {
    return stat().st_mode & S_IFDIR;
  }

  bool Path::is_reg()
  {
    return stat().st_mode & S_IFREG;
  }

  bool Path::readable()
  {
    int fd = ::open(path_.to_string().c_str(), O_RDONLY | O_LARGEFILE);

    if (fd != -1)
    {
      close(fd);
      return true;
    }
    else if (errno == EACCES)
      return false;

    handle_any_error();
  }

  bool Path::writable()
  {
    int fd = ::open(path_.to_string().c_str(),
                    O_WRONLY | O_LARGEFILE | O_APPEND);

    if (fd != -1)
    {
      close(fd);
      return true;
    }
    // EROFS = file is on a read only file system.
    else if (errno == EACCES || errno == EROFS)
      return false;

    handle_any_error();
  }

  // Operations

  std::string Path::basename()
  {
    return path_.basename();
  }

  rPath Path::cd()
  {
    if (chdir(as_string().c_str()))
      handle_any_error();
    return cwd();
  }

  rPath Path::concat(rPath other)
  {
    return new Path(path_ / (*other).path_);
  }

  std::string Path::dirname()
  {
    return path_.dirname();
  }

  rObject Path::open()
  {
    if (is_dir())
      return new Directory(path_);
    if (is_reg())
      return new File(path_);
    runner::raise_primitive_error(str(format("Unsupported file type: %s.") %
				      path_));
  }

  // Conversions

  std::string Path::as_string()
  {
    return path_.to_string();
  }

  std::string Path::as_printable()
  {
    return str(format("\"%s\"") % as_string());
  }

  rList Path::as_list()
  {
    List::value_type res;
    foreach (const std::string& c, path_.components())
      res << new String(c);
    return new List(res);
  }

  /*--------.
  | Details |
  `--------*/

  void Path::handle_any_error()
  {
    runner::raise_primitive_error(str(format("%1%: %2%") %
				      strerror(errno) % path_));
  }

  /*---------------.
  | Binding system |
  `---------------*/

  void Path::initialize(CxxObject::Binder<Path>& bind)
  {
    bind(SYMBOL(absolute), &Path::absolute);
    bind(SYMBOL(asList), &Path::as_list);
    bind(SYMBOL(asPrintable), &Path::as_printable);
    bind(SYMBOL(asString), &Path::as_string);
    bind(SYMBOL(basename), &Path::basename);
    bind(SYMBOL(cd), &Path::cd);
    bind(SYMBOL(cwd), &Path::cwd);
    bind(SYMBOL(dirname), &Path::dirname);
    bind(SYMBOL(exists), &Path::exists);
    bind(SYMBOL(init), &Path::init);
    bind(SYMBOL(isDir), &Path::is_dir);
    bind(SYMBOL(isReg), &Path::is_reg);
    bind(SYMBOL(open), &Path::open);
    bind(SYMBOL(readable), &Path::readable);
    bind(SYMBOL(SLASH), &Path::concat);
    bind(SYMBOL(writable), &Path::writable);
  }

  rObject
  Path::proto_make()
  {
#ifdef WIN32
    return new Path("C:\\");
#else
    return new Path("/");
#endif
  }

  URBI_CXX_OBJECT_REGISTER(Path);
}
<|endoftext|>


<commit_before>#include "VisPlugin.h"
#include <cairo/cairo.h>
#include <cmath>
#include <iostream>

using std::cout;
using std::endl;

class MFCC: public VisPlugin {

private:
    static const double pi = 3.14159265358979323846264338327950288;
    void IDCT(double **feats, double **results, unsigned int filters,
        unsigned int frames)
    {
      double matrix[filters][filters];
      for (unsigned int k=0; k<filters; k++)
      {
        for (unsigned int j=1; j<filters; j++)
        {
          matrix[k][j] = sqrt(2./(double)filters)*cos(pi/filters*j*(k+0.5));
        }
      }

      double min = 0;
      double max = 0;
      for (unsigned int frame=0; frame<frames; frame++)
      {
        for (unsigned int k=0; k<filters; k++)
        {
          results[frame][k] = sqrt(2)/2*feats[frame][0];
          for (unsigned int j=1; j<filters; j++)
            results[frame][k] += matrix[k][j]*feats[frame][j];
          if (results[frame][k] < min) min=results[frame][k];
          if (results[frame][k] > max) max=results[frame][k];
        }
      }
    }

public:

    virtual double getVersion() const {
        return 0.1;
    }

    virtual int ARGB(Plugin::FeatureSet features, int width,
        int height, unsigned char *bitmap)
    {
      unsigned int frames = features[0].size();
      unsigned int filters = features[0].at(0).values.size();

      double **feats;
      double **results;
      feats = new double*[frames];
      results = new double*[frames];
      for (unsigned int i=0; i<frames; i++) {
        results[i] = new double[filters];
        feats[i] = new double[filters];
      }

      for (unsigned int i=0; i<frames; i++) {
        for (unsigned int j=0; j<filters; j++) {
          feats[i][j] = features[0].at(i).values.at(j);
        }
      }

      IDCT(feats, results, filters, frames);

      // find min/max values
      double min=0;
      double max=1;
      for (unsigned int i=0; i<frames; i++)
      {
        for (unsigned int j=0; j<filters; j++)
        {
          if (results[i][j] < min) min=results[i][j];
          if (results[i][j] > max) max=results[i][j];
        }
      }

      // set up cairo surface
      cairo_surface_t *surface;
      cairo_format_t format = CAIRO_FORMAT_ARGB32;
      int stride = cairo_format_stride_for_width(format, width);
      surface = cairo_image_surface_create_for_data (bitmap, format, width,
          height, stride);

      // set up cairo context
      cairo_t *cr;
      cr = cairo_create(surface);
      cairo_scale(cr, width, height);
      cairo_set_source_rgba(cr, 1, 1, 1, 1);
      cairo_paint(cr);

      // start line in bottom left corner
      cairo_set_line_width(cr, 0);
      cairo_set_source_rgba(cr, 0, 0, 0, 1);
      cairo_move_to(cr, 0, 1);

      // draw amplitude
      frames = features[0].size();
      for (unsigned int frame=0; frame<frames; frame++)
      {
        for (unsigned int k=0; k<filters; k++)
        {
          double value = (results[frame][k]-min)/(max-min);
          cairo_set_source_rgba(cr, 1.-value,
                                    1.-value,
                                    1.-value, 1);
          cairo_rectangle(cr, (double)frame/(double)frames,
                              (double)k/(double)filters,
                              1.0/(double)frames,
                              1.0/(double)filters);
          cairo_fill(cr);
        }
      }

      // clean up
      cairo_destroy(cr);
      cairo_surface_destroy (surface);

      return 0;
    }

    virtual VampOutputList getVampPlugins()
    {
      VampOutputList pluginList;

      VampPlugin qmMFCC = {"qm-vamp-plugins:qm-mfcc", 0, 0};
      VampOutput mfcc = {qmMFCC, "coefficients"};

      pluginList.push_back(mfcc);
      return pluginList;
    }
};

extern "C" VisPlugin* create() {
    return new MFCC;
}

extern "C" void destroy(VisPlugin* p) {
    delete p;
}
<commit_msg>Commented out IDCT stuff in MFCC plugin for now.<commit_after>#include "VisPlugin.h"
#include <cairo/cairo.h>
#include <cmath>
#include <iostream>

using std::cout;
using std::endl;

class MFCC: public VisPlugin {

private:

    static const double pi = 3.14159265358979323846264338327950288;

    void IDCT(double **feats, double **results, unsigned int filters,
        unsigned int frames)
    {
      double matrix[filters][filters];
      for (unsigned int k=0; k<filters; k++)
      {
        for (unsigned int j=1; j<filters; j++)
        {
          matrix[k][j] = sqrt(2./(double)filters)*cos(pi/filters*j*(k+0.5));
        }
      }

      double min = 0;
      double max = 0;
      for (unsigned int frame=0; frame<frames; frame++)
      {
        for (unsigned int k=0; k<filters; k++)
        {
          results[frame][k] = sqrt(2)/2*feats[frame][0];
          for (unsigned int j=1; j<filters; j++)
            results[frame][k] += matrix[k][j]*feats[frame][j];
          if (results[frame][k] < min) min=results[frame][k];
          if (results[frame][k] > max) max=results[frame][k];
        }
      }
    }

public:

    virtual double getVersion() const {
        return 0.1;
    }

    virtual int ARGB(Plugin::FeatureSet features, int width,
        int height, unsigned char *bitmap)
    {
      unsigned int frames = features[0].size();
      unsigned int filters = features[0].at(0).values.size();

      //double **feats;
      double **results;
      //feats = new double*[frames];
      results = new double*[frames];
      for (unsigned int i=0; i<frames; i++) {
        results[i] = new double[filters];
        //feats[i] = new double[filters];
      }

      for (unsigned int i=0; i<frames; i++) {
        for (unsigned int j=0; j<filters; j++) {
          //feats[i][j] = features[0].at(i).values.at(j);
          results[i][j] = features[0].at(i).values.at(j);
        }
      }

      //IDCT(feats, results, filters, frames);

      // find min/max values
      double min=0;
      double max=1;
      for (unsigned int i=0; i<frames; i++)
      {
        for (unsigned int j=0; j<filters; j++)
        {
          if (results[i][j] < min) min=results[i][j];
          if (results[i][j] > max) max=results[i][j];
        }
      }

      // set up cairo surface
      cairo_surface_t *surface;
      cairo_format_t format = CAIRO_FORMAT_ARGB32;
      int stride = cairo_format_stride_for_width(format, width);
      surface = cairo_image_surface_create_for_data (bitmap, format, width,
          height, stride);

      // set up cairo context
      cairo_t *cr;
      cr = cairo_create(surface);
      cairo_scale(cr, width, height);
      cairo_set_source_rgba(cr, 1, 1, 1, 1);
      cairo_paint(cr);

      // start line in bottom left corner
      cairo_set_line_width(cr, 0);
      cairo_set_source_rgba(cr, 0, 0, 0, 1);
      cairo_move_to(cr, 0, 1);

      // draw amplitude
      frames = features[0].size();
      for (unsigned int frame=0; frame<frames; frame++)
      {
        for (unsigned int k=0; k<filters; k++)
        {
          double value = (results[frame][k]-min)/(max-min);
          cairo_set_source_rgba(cr, 1.-value,
                                    1.-value,
                                    1.-value, 1);
          cairo_rectangle(cr, (double)frame/(double)frames,
                              (double)k/(double)filters,
                              1.0/(double)frames,
                              1.0/(double)filters);
          cairo_fill(cr);
        }
      }

      // clean up
      cairo_destroy(cr);
      cairo_surface_destroy (surface);

      return 0;
    }

    virtual VampOutputList getVampPlugins()
    {
      VampOutputList pluginList;

      VampPlugin qmMFCC = {"qm-vamp-plugins:qm-mfcc", 0, 0};
      VampOutput mfcc = {qmMFCC, "coefficients"};

      pluginList.push_back(mfcc);
      return pluginList;
    }
};

extern "C" VisPlugin* create() {
    return new MFCC;
}

extern "C" void destroy(VisPlugin* p) {
    delete p;
}
<|endoftext|>


<commit_before>#include "nwg_common_socket_include.h"

#include <cstring>

#include "nwg_acceptor.h"
#include "nwg_evcb.h"

#include "nwg_object.h"
#include "nwg_handler.h"
#include "nwg_protocolcodec.h"

namespace Nwg
{

Acceptor::Acceptor(int port, const Service *service)
    : Service(service),
      _port(port),
      _listenerFd(-1),
      _listenerEvent(nullptr),
      _listenerEventArg(nullptr)
{
}

Acceptor::~Acceptor()
{
    if (_listenerEventArg != nullptr) {
        delete _listenerEventArg;
    }
}

void Acceptor::setPort(int port) { _port = port; }
int Acceptor::getPort() { return _port; }

void Acceptor::listen(bool dispatch)
{
#ifdef _WIN32
    do {
        WORD wVersionRequested;
        WSADATA wsaData;
        int err;

        wVersionRequested = MAKEWORD(2, 2);

        err = WSAStartup(wVersionRequested, &wsaData);
        if (err != 0) {
            printf("WSAStartup failed with error: %d\n", err);
            return;
        }
    } while(0);
#endif /* _WIN32 */

    struct sockaddr_in sin;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family      = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port        = htons(_port);

    _listenerFd = ::socket(AF_INET, SOCK_STREAM, 0);
    evutil_make_socket_nonblocking(_listenerFd);

#ifdef __unix__
    do {
        int one = 1;
        ::setsockopt(_listenerFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    } while(0);
#endif /* __unix__ */

    if (::bind(_listenerFd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
        perror("bind()");
        return;
    }

    if (::listen(_listenerFd, 16) < 0) {
        perror("listen()");
        return;
    }

    _listenerEventArg = new ListenerEventArg();
    _listenerEventArg->base     = _base;
    _listenerEventArg->acceptor = this;

    _listenerEvent = event_new(_base, _listenerFd,
            EV_READ | EV_PERSIST,
            EVCB::doAccept,
            (void *) _listenerEventArg);

    event_add(_listenerEvent, NULL);

    if (dispatch) {
        event_base_dispatch(_base);
    }
}

} /* namespace Nwg */
<commit_msg>Update Nwg::Acceptor's destructor<commit_after>#include "nwg_common_socket_include.h"

#include <cstring>

#include "nwg_acceptor.h"
#include "nwg_evcb.h"

#include "nwg_object.h"
#include "nwg_handler.h"
#include "nwg_protocolcodec.h"

namespace Nwg
{

Acceptor::Acceptor(int port, const Service *service)
    : Service(service),
      _port(port),
      _listenerFd(-1),
      _listenerEvent(nullptr),
      _listenerEventArg(nullptr)
{
}

Acceptor::~Acceptor()
{
    if (_listenerEventArg != nullptr) {
        delete _listenerEventArg;
    }

    event_del(_listenerEvent);
    ::close(_listenerFd);
}

void Acceptor::setPort(int port) { _port = port; }
int Acceptor::getPort() { return _port; }

void Acceptor::listen(bool dispatch)
{
#ifdef _WIN32
    do {
        WORD wVersionRequested;
        WSADATA wsaData;
        int err;

        wVersionRequested = MAKEWORD(2, 2);

        err = WSAStartup(wVersionRequested, &wsaData);
        if (err != 0) {
            printf("WSAStartup failed with error: %d\n", err);
            return;
        }
    } while(0);
#endif /* _WIN32 */

    struct sockaddr_in sin;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family      = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port        = htons(_port);

    _listenerFd = ::socket(AF_INET, SOCK_STREAM, 0);
    evutil_make_socket_nonblocking(_listenerFd);

#ifdef __unix__
    do {
        int one = 1;
        ::setsockopt(_listenerFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    } while(0);
#endif /* __unix__ */

    if (::bind(_listenerFd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
        perror("bind()");
        return;
    }

    if (::listen(_listenerFd, 16) < 0) {
        perror("listen()");
        return;
    }

    _listenerEventArg = new ListenerEventArg();
    _listenerEventArg->base     = _base;
    _listenerEventArg->acceptor = this;

    _listenerEvent = event_new(_base, _listenerFd,
            EV_READ | EV_PERSIST,
            EVCB::doAccept,
            (void *) _listenerEventArg);

    event_add(_listenerEvent, NULL);

    if (dispatch) {
        event_base_dispatch(_base);
    }
}

} /* namespace Nwg */
<|endoftext|>