<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <memory>
#include <string>

#include <fb/fbjni.h>
#include <jsi/jsi.h>

#include <jsireact/TurboModuleBinding.h>

#include <react/jni/JMessageQueueThread.h>

#include "TurboModuleManager.h"

namespace facebook {
namespace react {

TurboModuleManager::TurboModuleManager(
  jni::alias_ref<TurboModuleManager::javaobject> jThis,
  jsi::Runtime* rt,
  std::shared_ptr<JSCallInvoker> jsCallInvoker,
  jni::alias_ref<TurboModuleManagerDelegate::javaobject> tmmDelegate
):
  javaPart_(jni::make_global(jThis)),
  runtime_(rt),
  jsCallInvoker_(jsCallInvoker),
  turboModuleManagerDelegate_(jni::make_global(tmmDelegate))
  {}

jni::local_ref<TurboModuleManager::jhybriddata> TurboModuleManager::initHybrid(
  jni::alias_ref<jhybridobject> jThis,
  jlong jsContext,
  jni::alias_ref<JSCallInvokerHolder::javaobject> jsCallInvokerHolder,
  jni::alias_ref<TurboModuleManagerDelegate::javaobject> tmmDelegate
) {
  auto jsCallInvoker = jsCallInvokerHolder->cthis()->getJSCallInvoker();

  return makeCxxInstance(jThis, (jsi::Runtime *) jsContext, jsCallInvoker, tmmDelegate);
}

void TurboModuleManager::registerNatives() {
  registerHybrid({
    makeNativeMethod("initHybrid", TurboModuleManager::initHybrid),
    makeNativeMethod("installJSIBindings", TurboModuleManager::installJSIBindings),
  });
}

void TurboModuleManager::installJSIBindings() {
  if (!runtime_) {
    return; // Runtime doesn't exist when attached to Chrome debugger.
  }
  TurboModuleBinding::install(*runtime_, std::make_shared<TurboModuleBinding>(
      [this](const std::string &name) {
        auto cxxModule = turboModuleManagerDelegate_->cthis()->getTurboModule(name, jsCallInvoker_);
        if (cxxModule) {
          return cxxModule;
        }

        const auto moduleInstance = getJavaModule(name);
        return turboModuleManagerDelegate_->cthis()->getTurboModule(name, moduleInstance, jsCallInvoker_);
      })
  );
}

jni::global_ref<JTurboModule> TurboModuleManager::getJavaModule(std::string name) {
  static auto method = javaClassStatic()->getMethod<jni::alias_ref<JTurboModule>(const std::string&)>("getJavaModule");

  auto module = jni::make_global(method(javaPart_.get(), name));

  return module;
}

} // namespace react
} // namespace facebook
<commit_msg>Only create TurboModule jsi::HostObject if Java module is non-null<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <memory>
#include <string>

#include <fb/fbjni.h>
#include <jsi/jsi.h>

#include <jsireact/TurboModuleBinding.h>

#include <react/jni/JMessageQueueThread.h>

#include "TurboModuleManager.h"

namespace facebook {
namespace react {

TurboModuleManager::TurboModuleManager(
  jni::alias_ref<TurboModuleManager::javaobject> jThis,
  jsi::Runtime* rt,
  std::shared_ptr<JSCallInvoker> jsCallInvoker,
  jni::alias_ref<TurboModuleManagerDelegate::javaobject> tmmDelegate
):
  javaPart_(jni::make_global(jThis)),
  runtime_(rt),
  jsCallInvoker_(jsCallInvoker),
  turboModuleManagerDelegate_(jni::make_global(tmmDelegate))
  {}

jni::local_ref<TurboModuleManager::jhybriddata> TurboModuleManager::initHybrid(
  jni::alias_ref<jhybridobject> jThis,
  jlong jsContext,
  jni::alias_ref<JSCallInvokerHolder::javaobject> jsCallInvokerHolder,
  jni::alias_ref<TurboModuleManagerDelegate::javaobject> tmmDelegate
) {
  auto jsCallInvoker = jsCallInvokerHolder->cthis()->getJSCallInvoker();

  return makeCxxInstance(jThis, (jsi::Runtime *) jsContext, jsCallInvoker, tmmDelegate);
}

void TurboModuleManager::registerNatives() {
  registerHybrid({
    makeNativeMethod("initHybrid", TurboModuleManager::initHybrid),
    makeNativeMethod("installJSIBindings", TurboModuleManager::installJSIBindings),
  });
}

void TurboModuleManager::installJSIBindings() {
  if (!runtime_) {
    return; // Runtime doesn't exist when attached to Chrome debugger.
  }
  TurboModuleBinding::install(*runtime_, std::make_shared<TurboModuleBinding>(
      [this](const std::string &name) {
        auto cxxModule = turboModuleManagerDelegate_->cthis()->getTurboModule(name, jsCallInvoker_);
        if (cxxModule) {
          return cxxModule;
        }

        const auto moduleInstance = getJavaModule(name);

        if (moduleInstance) {
          return turboModuleManagerDelegate_->cthis()->getTurboModule(name, moduleInstance, jsCallInvoker_);
        }

        return std::shared_ptr<TurboModule>(nullptr);
      })
  );
}

jni::global_ref<JTurboModule> TurboModuleManager::getJavaModule(std::string name) {
  static auto method = javaClassStatic()->getMethod<jni::alias_ref<JTurboModule>(const std::string&)>("getJavaModule");

  auto module = jni::make_global(method(javaPart_.get(), name));

  return module;
}

} // namespace react
} // namespace facebook
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * 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.
 *
 **************************************************************************/

/*
 * WGL bindings.
 */

#include <iostream>

#include "glproc.hpp"
#include "glws.hpp"
#include "ws_win32.hpp"

namespace glws {

/*
 * Several WGL functions come in two flavors:
 * - GDI (ChoosePixelFormat, SetPixelFormat, SwapBuffers, etc)
 * - WGL (wglChoosePixelFormat, wglSetPixelFormat, wglSwapBuffers, etc)
 *
 * The GDI entrypoints will inevitably dispatch to the first module named
 * "OPENGL32", loading "C:\Windows\System32\opengl32.dll" if none was loaded so
 * far.
 *
 * In order to use a implementation other than the one installed in the system
 * (when specified via the TRACE_LIBGL environment variable), we need to use
 * WGL entrypoints.
 *
 * See also:
 * - http://www.opengl.org/archives/resources/faq/technical/mswindows.htm
 */
static PFN_WGLCHOOSEPIXELFORMAT pfnChoosePixelFormat = &ChoosePixelFormat;
static PFN_WGLDESCRIBEPIXELFORMAT pfnDescribePixelFormat = &DescribePixelFormat;
static PFN_WGLSETPIXELFORMAT pfnSetPixelFormat = &SetPixelFormat;
static PFN_WGLSWAPBUFFERS pfnSwapBuffers = &SwapBuffers;

class WglDrawable : public Drawable
{
public:
    HWND hWnd;
    HDC hDC;
    PIXELFORMATDESCRIPTOR pfd;
    int iPixelFormat;

    WglDrawable(const Visual *vis, int width, int height, bool pbuffer) :
        Drawable(vis, width, height, pbuffer)
    {
        BOOL bRet;

        hWnd = ws::createWindow("glretrace", width, height);

        hDC = GetDC(hWnd);

        ZeroMemory(&pfd, sizeof pfd);
        pfd.nSize = sizeof pfd;
        pfd.nVersion = 1;
        pfd.iPixelType = PFD_TYPE_RGBA;
        pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
        pfd.cColorBits = 3;
        // XXX: ChoosePixelFormat will return a software pixelformat if we
        // request alpha bits and the hardware driver doesn't advertise any
        // pixel format with alpha bits (e.g. NVIDIA OpenGL driver on 16bpp
        // screens.)
        pfd.cAlphaBits = 1;
        pfd.cDepthBits = 1;
        pfd.cStencilBits = 1;
        pfd.iLayerType = PFD_MAIN_PLANE;

        if (visual->doubleBuffer) {
           pfd.dwFlags |= PFD_DOUBLEBUFFER;
        }

        iPixelFormat = pfnChoosePixelFormat(hDC, &pfd);
        if (iPixelFormat <= 0) {
            std::cerr << "error: ChoosePixelFormat failed\n";
            exit(1);
        }

        pfnDescribePixelFormat(hDC, iPixelFormat, sizeof pfd, &pfd);
        assert(pfd.dwFlags & PFD_SUPPORT_OPENGL);
        if (pfd.dwFlags & PFD_GENERIC_FORMAT) {
            std::cerr << "warning: ChoosePixelFormat returned a pixel format supported by the GDI software implementation\n";
        }

        bRet = pfnSetPixelFormat(hDC, iPixelFormat, &pfd);
        if (!bRet) {
            std::cerr << "error: SetPixelFormat failed\n";
            exit(1);
        }
    }

    ~WglDrawable() {
        ReleaseDC(hWnd, hDC);
        DestroyWindow(hWnd);
    }

    void
    resize(int w, int h) {
        if (w == width && h == height) {
            return;
        }

        Drawable::resize(w, h);

        ws::resizeWindow(hWnd, w, h);
    }

    void show(void) {
        if (visible) {
            return;
        }

        ws::showWindow(hWnd);

        Drawable::show();
    }

    void swapBuffers(void) {
        BOOL bRet;
        bRet = pfnSwapBuffers(hDC);
        if (!bRet) {
            std::cerr << "warning: SwapBuffers failed\n";
        }
    }
};

class WglContext : public Context
{
public:
    HGLRC hglrc;
    WglContext *shareContext;
    bool debug;

    WglContext(const Visual *vis, WglContext *share, bool _debug) :
        Context(vis),
        hglrc(0),
        shareContext(share),
        debug(_debug)
    {}

    ~WglContext() {
        if (hglrc) {
            wglDeleteContext(hglrc);
        }
    }

    bool
    createARB(HDC hDC) {
        bool required = profile.api != glprofile::API_GL ||
                        profile.versionGreaterOrEqual(3, 1);

        // We need to create context through WGL_ARB_create_context.  This
        // implies binding a temporary context to get the extensions strings
        // and function pointers.

        // This function is only called inside makeCurrent, so we don't need
        // to save and restore the previous current context/drawable.
        BOOL bRet = wglMakeCurrent(hDC, hglrc);
        if (!bRet) {
            std::cerr << "error: wglMakeCurrent failed\n";
            exit(1);
        }

        PFNWGLGETEXTENSIONSSTRINGARBPROC pfnWglGetExtensionsStringARB =
            (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
        if (!pfnWglGetExtensionsStringARB) {
            if (required) {
                std::cerr << "error: WGL_ARB_extensions_string not supported\n";
                exit(1);
            } else {
                return false;
            }
        }
        const char * extensionsString = pfnWglGetExtensionsStringARB(hDC);
        if (!checkExtension("WGL_ARB_create_context", extensionsString)) {
            if (required) {
                std::cerr << "error: WGL_ARB_create_context not supported\n";
                exit(1);
            } else {
                return false;
            }
        }

        PFNWGLCREATECONTEXTATTRIBSARBPROC pfnWglCreateContextAttribsARB =
            (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");
        if (!pfnWglCreateContextAttribsARB) {
            if (required) {
                std::cerr << "error: failed to get pointer to wglCreateContextAttribsARB\n";
                exit(1);
            } else {
                return false;
            }
        }

        wglMakeCurrent(hDC, NULL);

        Attributes<int> attribs;
        int contextFlags = 0;
        if (profile.api == glprofile::API_GL) {
            attribs.add(WGL_CONTEXT_MAJOR_VERSION_ARB, profile.major);
            attribs.add(WGL_CONTEXT_MINOR_VERSION_ARB, profile.minor);
            if (profile.versionGreaterOrEqual(3, 2)) {
                if (!checkExtension("WGL_ARB_create_context_profile", extensionsString)) {
                    assert(required);
                    std::cerr << "error: WGL_ARB_create_context_profile not supported\n";
                    exit(1);
                }
                int profileMask = profile.core ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
                attribs.add(WGL_CONTEXT_PROFILE_MASK_ARB, profileMask);
                if (profile.forwardCompatible) {
                    contextFlags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
                }
            }
        } else if (profile.api == glprofile::API_GLES) {
            if (checkExtension("WGL_EXT_create_context_es_profile", extensionsString)) {
                attribs.add(WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_ES_PROFILE_BIT_EXT);
                attribs.add(WGL_CONTEXT_MAJOR_VERSION_ARB, profile.major);
                attribs.add(WGL_CONTEXT_MINOR_VERSION_ARB, profile.minor);
            } else if (profile.major != 2) {
                std::cerr << "warning: OpenGL ES " << profile.major << " requested but WGL_EXT_create_context_es_profile not supported\n";
            } else if (checkExtension("WGL_EXT_create_context_es2_profile", extensionsString)) {
                assert(profile.major == 2);
                attribs.add(WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_ES2_PROFILE_BIT_EXT);
                attribs.add(WGL_CONTEXT_MAJOR_VERSION_ARB, profile.major);
                attribs.add(WGL_CONTEXT_MINOR_VERSION_ARB, profile.minor);
            } else {
                std::cerr << "warning: OpenGL ES " << profile.major << " requested but WGL_EXT_create_context_es_profile or WGL_EXT_create_context_es2_profile not supported\n";
            }
        } else {
            assert(0);
        }
        if (debug) {
            contextFlags |= WGL_CONTEXT_DEBUG_BIT_ARB;
        }
        if (contextFlags) {
            attribs.add(WGL_CONTEXT_FLAGS_ARB, contextFlags);
        }
        attribs.end();

        HGLRC new_hglrc;
        new_hglrc = pfnWglCreateContextAttribsARB(hDC,
                                                  shareContext ? shareContext->hglrc : 0,
                                                  attribs);
        if (!new_hglrc) {
            if (required) {
                std::cerr << "error: wglCreateContextAttribsARB failed\n";
                exit(1);
            } else {
                return false;
            }
        }

        wglDeleteContext(hglrc);
        hglrc = new_hglrc;

        return true;
    }

    bool
    create(WglDrawable *wglDrawable) {
        if (!hglrc) {
            HDC hDC = wglDrawable->hDC;

            hglrc = wglCreateContext(hDC);
            if (!hglrc) {
                std::cerr << "error: wglCreateContext failed\n";
                exit(1);
            }

            if (shareContext) {
                shareContext->create(wglDrawable);
            }

            if (!createARB(hDC)) {
                if (shareContext) {
                    BOOL bRet;
                    bRet = wglShareLists(shareContext->hglrc,
                                         hglrc);
                    if (!bRet) {
                        std::cerr
                            << "warning: wglShareLists failed: "
                            << std::hex << GetLastError() << std::dec
                            << "\n";
                    }
                }
            }
        }

        return true;
    }

};

void
init(void) {
    /*
     * OpenGL library must be loaded by the time we call GDI.
     */

    const char * libgl_filename = getenv("TRACE_LIBGL");

    if (libgl_filename) {
        _libGlHandle = LoadLibraryA(libgl_filename);
        if (_libGlHandle) {
            pfnChoosePixelFormat = (PFN_WGLCHOOSEPIXELFORMAT)GetProcAddress(_libGlHandle, "wglChoosePixelFormat");
            assert(pfnChoosePixelFormat);
            pfnDescribePixelFormat = (PFN_WGLDESCRIBEPIXELFORMAT)GetProcAddress(_libGlHandle, "wglDescribePixelFormat");
            assert(pfnDescribePixelFormat);
            pfnSetPixelFormat = (PFN_WGLSETPIXELFORMAT)GetProcAddress(_libGlHandle, "wglSetPixelFormat");
            assert(pfnSetPixelFormat);
            pfnSwapBuffers = (PFN_WGLSWAPBUFFERS)GetProcAddress(_libGlHandle, "wglSwapBuffers");
            assert(pfnSwapBuffers);
        }
    } else {
        libgl_filename = "OPENGL32";
        _libGlHandle = LoadLibraryA(libgl_filename);
    }

    if (!_libGlHandle) {
        std::cerr << "error: unable to open " << libgl_filename << "\n";
        exit(1);
    }
}

void
cleanup(void) {
}

Visual *
createVisual(bool doubleBuffer, unsigned samples, Profile profile) {
    Visual *visual = new Visual(profile);

    visual->doubleBuffer = doubleBuffer;

    return visual;
}

Drawable *
createDrawable(const Visual *visual, int width, int height, bool pbuffer)
{
    return new WglDrawable(visual, width, height, pbuffer);
}

Context *
createContext(const Visual *visual, Context *shareContext, bool debug)
{
    return new WglContext(visual, static_cast<WglContext *>(shareContext), debug);
}

bool
makeCurrentInternal(Drawable *drawable, Context *context)
{
    if (!drawable || !context) {
        return wglMakeCurrent(NULL, NULL);
    } else {
        WglDrawable *wglDrawable = static_cast<WglDrawable *>(drawable);
        WglContext *wglContext = static_cast<WglContext *>(context);

        wglContext->create(wglDrawable);

        return wglMakeCurrent(wglDrawable->hDC, wglContext->hglrc);
    }
}

bool
processEvents(void)
{
    return ws::processEvents();
}

} /* namespace glws */
<commit_msg>glws: add WGL PBuffer support<commit_after>/**************************************************************************
 *
 * Copyright 2011 Jose Fonseca
 * 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.
 *
 **************************************************************************/

/*
 * WGL bindings.
 */

#include <iostream>

#include "glproc.hpp"
#include "glws.hpp"
#include "ws_win32.hpp"

#include <GL/wglext.h>

namespace glws {

/*
 * Several WGL functions come in two flavors:
 * - GDI (ChoosePixelFormat, SetPixelFormat, SwapBuffers, etc)
 * - WGL (wglChoosePixelFormat, wglSetPixelFormat, wglSwapBuffers, etc)
 *
 * The GDI entrypoints will inevitably dispatch to the first module named
 * "OPENGL32", loading "C:\Windows\System32\opengl32.dll" if none was loaded so
 * far.
 *
 * In order to use a implementation other than the one installed in the system
 * (when specified via the TRACE_LIBGL environment variable), we need to use
 * WGL entrypoints.
 *
 * See also:
 * - http://www.opengl.org/archives/resources/faq/technical/mswindows.htm
 */
static PFN_WGLCHOOSEPIXELFORMAT pfnChoosePixelFormat = &ChoosePixelFormat;
static PFN_WGLDESCRIBEPIXELFORMAT pfnDescribePixelFormat = &DescribePixelFormat;
static PFN_WGLSETPIXELFORMAT pfnSetPixelFormat = &SetPixelFormat;
static PFN_WGLSWAPBUFFERS pfnSwapBuffers = &SwapBuffers;

#define WGL_PROC(type, func, name) \
    type func = (type) wglGetProcAddress(name); \
    if (!func) { \
        std::cerr << "error: unable to get " << name << " function.\n"; \
        exit(1); \
    }

static bool
is_wgl_ext_supported(const char *ext)
{
    PFNWGLGETEXTENSIONSSTRINGARBPROC pfnWglGetExtensionsStringARB =
        (PFNWGLGETEXTENSIONSSTRINGARBPROC)
        wglGetProcAddress("wglGetExtensionsStringARB");
    if (!pfnWglGetExtensionsStringARB) {
        return false;
    }
    HDC hdc = wglGetCurrentDC();
    const char * extensionsString = pfnWglGetExtensionsStringARB(hdc);
    if (!checkExtension(ext, extensionsString)) {
        std::cerr << "error: " << ext << "extension is not supported.\n";
        return false;
    }
    return true;
}

class WglDrawable : public Drawable
{
public:
    // Only one of hWnd and pbBuffer will be non-zero
    HWND hWnd;
    HPBUFFERARB hPBuffer;
    HDC hDC;

    WglDrawable(const Visual *vis, int width, int height, bool pbuffer) :
        Drawable(vis, width, height, pbuffer)
    {
        if (pbuffer) {
            createPbuffer(vis, width, height);
            hWnd = 0;
        }
        else {
            hWnd = ws::createWindow("glretrace", width, height);

            hDC = GetDC(hWnd);

            PIXELFORMATDESCRIPTOR pfd;
            ZeroMemory(&pfd, sizeof pfd);
            pfd.nSize = sizeof pfd;
            pfd.nVersion = 1;
            pfd.iPixelType = PFD_TYPE_RGBA;
            pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
            pfd.cColorBits = 3;
            // XXX: ChoosePixelFormat will return a software pixelformat if we
            // request alpha bits and the hardware driver doesn't advertise any
            // pixel format with alpha bits (e.g. NVIDIA OpenGL driver on 16bpp
            // screens.)
            pfd.cAlphaBits = 1;
            pfd.cDepthBits = 1;
            pfd.cStencilBits = 1;
            pfd.iLayerType = PFD_MAIN_PLANE;

            if (visual->doubleBuffer) {
               pfd.dwFlags |= PFD_DOUBLEBUFFER;
            }

            int iPixelFormat = pfnChoosePixelFormat(hDC, &pfd);
            if (iPixelFormat <= 0) {
                std::cerr << "error: ChoosePixelFormat failed\n";
                exit(1);
            }

            pfnDescribePixelFormat(hDC, iPixelFormat, sizeof pfd, &pfd);
            assert(pfd.dwFlags & PFD_SUPPORT_OPENGL);
            if (pfd.dwFlags & PFD_GENERIC_FORMAT) {
                std::cerr << "warning: ChoosePixelFormat returned a pixel format supported by the GDI software implementation\n";
            }

            BOOL bRet = pfnSetPixelFormat(hDC, iPixelFormat, &pfd);
            if (!bRet) {
                std::cerr << "error: SetPixelFormat failed\n";
                exit(1);
            }

            hPBuffer = 0;
        }
    }

    ~WglDrawable() {
        if (hPBuffer) {
            WGL_PROC(PFNWGLDESTROYPBUFFERARBPROC,
                     pfnwglDestroyPbufferARB, "wglDestroyPbufferARB");
            WGL_PROC(PFNWGLRELEASEPBUFFERDCARBPROC,
                     pfnwglReleasePbufferDCARB, "wglReleasePbufferDCARB");
            pfnwglReleasePbufferDCARB(hPBuffer, hDC);
            pfnwglDestroyPbufferARB(hPBuffer);
        }
        else {
            ReleaseDC(hWnd, hDC);
            DestroyWindow(hWnd);
        }
    }

    void
    resize(int w, int h) {
        if (w == width && h == height) {
            return;
        }

        Drawable::resize(w, h);

        ws::resizeWindow(hWnd, w, h);
    }

    void show(void) {
        if (visible) {
            return;
        }

        ws::showWindow(hWnd);

        Drawable::show();
    }

    void swapBuffers(void) {
        assert(!pbuffer);
        BOOL bRet;
        bRet = pfnSwapBuffers(hDC);
        if (!bRet) {
            std::cerr << "warning: SwapBuffers failed\n";
        }
    }

private:
    bool createPbuffer(const Visual *vis, int width, int height);
};

class WglContext : public Context
{
public:
    HGLRC hglrc;
    WglContext *shareContext;
    bool debug;

    WglContext(const Visual *vis, WglContext *share, bool _debug) :
        Context(vis),
        hglrc(0),
        shareContext(share),
        debug(_debug)
    {}

    ~WglContext() {
        if (hglrc) {
            wglDeleteContext(hglrc);
        }
    }

    bool
    createARB(HDC hDC) {
        bool required = profile.api != glprofile::API_GL ||
                        profile.versionGreaterOrEqual(3, 1);

        // We need to create context through WGL_ARB_create_context.  This
        // implies binding a temporary context to get the extensions strings
        // and function pointers.

        // This function is only called inside makeCurrent, so we don't need
        // to save and restore the previous current context/drawable.
        BOOL bRet = wglMakeCurrent(hDC, hglrc);
        if (!bRet) {
            std::cerr << "error: wglMakeCurrent failed\n";
            exit(1);
        }

        PFNWGLGETEXTENSIONSSTRINGARBPROC pfnWglGetExtensionsStringARB =
            (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
        if (!pfnWglGetExtensionsStringARB) {
            if (required) {
                std::cerr << "error: WGL_ARB_extensions_string not supported\n";
                exit(1);
            } else {
                return false;
            }
        }
        const char * extensionsString = pfnWglGetExtensionsStringARB(hDC);
        if (!checkExtension("WGL_ARB_create_context", extensionsString)) {
            if (required) {
                std::cerr << "error: WGL_ARB_create_context not supported\n";
                exit(1);
            } else {
                return false;
            }
        }

        PFNWGLCREATECONTEXTATTRIBSARBPROC pfnWglCreateContextAttribsARB =
            (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");
        if (!pfnWglCreateContextAttribsARB) {
            if (required) {
                std::cerr << "error: failed to get pointer to wglCreateContextAttribsARB\n";
                exit(1);
            } else {
                return false;
            }
        }

        wglMakeCurrent(hDC, NULL);

        Attributes<int> attribs;
        int contextFlags = 0;
        if (profile.api == glprofile::API_GL) {
            attribs.add(WGL_CONTEXT_MAJOR_VERSION_ARB, profile.major);
            attribs.add(WGL_CONTEXT_MINOR_VERSION_ARB, profile.minor);
            if (profile.versionGreaterOrEqual(3, 2)) {
                if (!checkExtension("WGL_ARB_create_context_profile", extensionsString)) {
                    assert(required);
                    std::cerr << "error: WGL_ARB_create_context_profile not supported\n";
                    exit(1);
                }
                int profileMask = profile.core ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
                attribs.add(WGL_CONTEXT_PROFILE_MASK_ARB, profileMask);
                if (profile.forwardCompatible) {
                    contextFlags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
                }
            }
        } else if (profile.api == glprofile::API_GLES) {
            if (checkExtension("WGL_EXT_create_context_es_profile", extensionsString)) {
                attribs.add(WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_ES_PROFILE_BIT_EXT);
                attribs.add(WGL_CONTEXT_MAJOR_VERSION_ARB, profile.major);
                attribs.add(WGL_CONTEXT_MINOR_VERSION_ARB, profile.minor);
            } else if (profile.major != 2) {
                std::cerr << "warning: OpenGL ES " << profile.major << " requested but WGL_EXT_create_context_es_profile not supported\n";
            } else if (checkExtension("WGL_EXT_create_context_es2_profile", extensionsString)) {
                assert(profile.major == 2);
                attribs.add(WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_ES2_PROFILE_BIT_EXT);
                attribs.add(WGL_CONTEXT_MAJOR_VERSION_ARB, profile.major);
                attribs.add(WGL_CONTEXT_MINOR_VERSION_ARB, profile.minor);
            } else {
                std::cerr << "warning: OpenGL ES " << profile.major << " requested but WGL_EXT_create_context_es_profile or WGL_EXT_create_context_es2_profile not supported\n";
            }
        } else {
            assert(0);
        }
        if (debug) {
            contextFlags |= WGL_CONTEXT_DEBUG_BIT_ARB;
        }
        if (contextFlags) {
            attribs.add(WGL_CONTEXT_FLAGS_ARB, contextFlags);
        }
        attribs.end();

        HGLRC new_hglrc;
        new_hglrc = pfnWglCreateContextAttribsARB(hDC,
                                                  shareContext ? shareContext->hglrc : 0,
                                                  attribs);
        if (!new_hglrc) {
            if (required) {
                std::cerr << "error: wglCreateContextAttribsARB failed\n";
                exit(1);
            } else {
                return false;
            }
        }

        wglDeleteContext(hglrc);
        hglrc = new_hglrc;

        return true;
    }

    bool
    create(WglDrawable *wglDrawable) {
        if (!hglrc) {
            HDC hDC = wglDrawable->hDC;

            hglrc = wglCreateContext(hDC);
            if (!hglrc) {
                std::cerr << "error: wglCreateContext failed\n";
                exit(1);
            }

            if (shareContext) {
                shareContext->create(wglDrawable);
            }

            if (!createARB(hDC)) {
                if (shareContext) {
                    BOOL bRet;
                    bRet = wglShareLists(shareContext->hglrc,
                                         hglrc);
                    if (!bRet) {
                        std::cerr
                            << "warning: wglShareLists failed: "
                            << std::hex << GetLastError() << std::dec
                            << "\n";
                    }
                }
            }
        }

        return true;
    }

};

void
init(void) {
    /*
     * OpenGL library must be loaded by the time we call GDI.
     */

    const char * libgl_filename = getenv("TRACE_LIBGL");

    if (libgl_filename) {
        _libGlHandle = LoadLibraryA(libgl_filename);
        if (_libGlHandle) {
            pfnChoosePixelFormat = (PFN_WGLCHOOSEPIXELFORMAT)GetProcAddress(_libGlHandle, "wglChoosePixelFormat");
            assert(pfnChoosePixelFormat);
            pfnDescribePixelFormat = (PFN_WGLDESCRIBEPIXELFORMAT)GetProcAddress(_libGlHandle, "wglDescribePixelFormat");
            assert(pfnDescribePixelFormat);
            pfnSetPixelFormat = (PFN_WGLSETPIXELFORMAT)GetProcAddress(_libGlHandle, "wglSetPixelFormat");
            assert(pfnSetPixelFormat);
            pfnSwapBuffers = (PFN_WGLSWAPBUFFERS)GetProcAddress(_libGlHandle, "wglSwapBuffers");
            assert(pfnSwapBuffers);
        }
    } else {
        libgl_filename = "OPENGL32";
        _libGlHandle = LoadLibraryA(libgl_filename);
    }

    if (!_libGlHandle) {
        std::cerr << "error: unable to open " << libgl_filename << "\n";
        exit(1);
    }
}

void
cleanup(void) {
}

Visual *
createVisual(bool doubleBuffer, unsigned samples, Profile profile) {
    Visual *visual = new Visual(profile);

    visual->doubleBuffer = doubleBuffer;

    return visual;
}

Drawable *
createDrawable(const Visual *visual, int width, int height,
               const glws::pbuffer_info *info)
{
    return new WglDrawable(visual, width, height, info);
}

Context *
createContext(const Visual *visual, Context *shareContext, bool debug)
{
    return new WglContext(visual, static_cast<WglContext *>(shareContext), debug);
}

bool
makeCurrentInternal(Drawable *drawable, Context *context)
{
    if (!drawable || !context) {
        return wglMakeCurrent(NULL, NULL);
    } else {
        WglDrawable *wglDrawable = static_cast<WglDrawable *>(drawable);
        WglContext *wglContext = static_cast<WglContext *>(context);

        wglContext->create(wglDrawable);

        return wglMakeCurrent(wglDrawable->hDC, wglContext->hglrc);
    }
}

bool
processEvents(void)
{
    return ws::processEvents();
}

bool
glws::WglDrawable::createPbuffer(const Visual *vis, int width, int height)
{
    if (!is_wgl_ext_supported("WGL_ARB_pbuffer")) {
        exit(1);
        return false;
    }

    WGL_PROC(PFNWGLCREATEPBUFFERARBPROC,
             pfnwglCreatePbufferARB, "wglCreatePbufferARB");
    WGL_PROC(PFNWGLGETPBUFFERDCARBPROC,
             pfnwglGetPbufferDCARB, "wglGetPbufferDCARB");
    WGL_PROC(PFNWGLCHOOSEPIXELFORMATARBPROC,
             pfnwglChoosePixelFormatARB, "wglChoosePixelFormatARB");

    // choose pixel format
    Attributes<int> attribs;
    attribs.add(WGL_DRAW_TO_PBUFFER_ARB, true);
    attribs.add(WGL_DEPTH_BITS_ARB, 24);
    attribs.add(WGL_STENCIL_BITS_ARB, 8);
    attribs.add(WGL_RED_BITS_ARB, 8);
    attribs.add(WGL_GREEN_BITS_ARB, 8);
    attribs.add(WGL_BLUE_BITS_ARB, 8);
    attribs.add(WGL_ALPHA_BITS_ARB, 8);
    attribs.add(WGL_COLOR_BITS_ARB, 32);
    attribs.end();

    int pixelFormats[20];
    UINT numPixelFormats;
    HDC hdc = wglGetCurrentDC();
    if (!pfnwglChoosePixelFormatARB(hdc, attribs, NULL,
                                    20, pixelFormats,
                                    &numPixelFormats)) {
        std::cerr << "error: wglChoosePixelFormatARB failed.\n";
        exit(1);
    }

    // create pbuffer
    Attributes<int> pbAttribs;
    // No attribs yet
    pbAttribs.end();

    hPBuffer = pfnwglCreatePbufferARB(hdc, pixelFormats[0],
                                      width, height, pbAttribs);
    if (!hPBuffer) {
        std::cerr << "error: wglCreatePbufferARB failed (format "
                  << pixelFormats[0] << ")\n";
        DWORD er = GetLastError();
        std::cerr << "error code " << er << "\n";
        exit(1);
    }
    hDC = pfnwglGetPbufferDCARB(hPBuffer);
    if (!hDC) {
        std::cerr << "error: wglGetPbufferDCARB failed\n";
        exit(1);
    }

    return true;
}

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


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

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

#ifndef _SV_SALPIXMAPUTILS_HXX
    #include <salpixmaputils.hxx>
#endif

// =======================================================================

// =======================================================================

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

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

#include "salpixmaputils.hxx"

// =======================================================================

// =======================================================================

<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2004 by Allan Sandfeld Jensen
                           (C) 2002 - 2008 by Scott Wheeler (id3v2header.cpp)
    email                : kde@carewolf.org
 ***************************************************************************/

/***************************************************************************
 *   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., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <iostream>
#include <bitset>

#include <tstring.h>
#include <tdebug.h>

#include "apefooter.h"

using namespace TagLib;
using namespace APE;

class Footer::FooterPrivate
{
public:
  FooterPrivate() : version(0),
                    footerPresent(true),
                    headerPresent(false),
                    isHeader(false),
                    itemCount(0),
                    tagSize(0) {}

  ~FooterPrivate() {}

  uint version;

  bool footerPresent;
  bool headerPresent;

  bool isHeader;

  uint itemCount;
  uint tagSize;

  static const uint size = 32;
};

////////////////////////////////////////////////////////////////////////////////
// static members
////////////////////////////////////////////////////////////////////////////////

TagLib::uint Footer::size()
{
  return FooterPrivate::size;
}

ByteVector Footer::fileIdentifier()
{
  return ByteVector::fromCString("APETAGEX");
}

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

Footer::Footer()
{
  d = new FooterPrivate;
}

Footer::Footer(const ByteVector &data)
{
  d = new FooterPrivate;
  parse(data);
}

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

TagLib::uint Footer::version() const
{
  return d->version;
}

bool Footer::headerPresent() const
{
  return d->headerPresent;
}

bool Footer::footerPresent() const
{
  return d->footerPresent;
}

bool Footer::isHeader() const
{
  return d->isHeader;
}

void Footer::setHeaderPresent(bool b) const
{
  d->headerPresent = b;
}

TagLib::uint Footer::itemCount() const
{
  return d->itemCount;
}

void Footer::setItemCount(uint s)
{
  d->itemCount = s;
}

TagLib::uint Footer::tagSize() const
{
  return d->tagSize;
}

TagLib::uint Footer::completeTagSize() const
{
  if(d->headerPresent)
    return d->tagSize + d->size;
  else
    return d->tagSize;
}

void Footer::setTagSize(uint s)
{
  d->tagSize = s;
}

void Footer::setData(const ByteVector &data)
{
  parse(data);
}

ByteVector Footer::renderFooter() const
{
    return render(false);
}

ByteVector Footer::renderHeader() const
{
    if (!d->headerPresent) return ByteVector();

    return render(true);
}

////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////

void Footer::parse(const ByteVector &data)
{
  if(data.size() < size())
    return;

  // The first eight bytes, data[0..7], are the File Identifier, "APETAGEX".

  // Read the version number

  d->version = data.mid(8, 4).toUInt(false);

  // Read the tag size

  d->tagSize = data.mid(12, 4).toUInt(false);

  // Read the item count

  d->itemCount = data.mid(16, 4).toUInt(false);

  // Read the flags

  std::bitset<32> flags(TAGLIB_CONSTRUCT_BITSET(data.mid(20, 4).toUInt(false)));

  d->headerPresent = flags[31];
  d->footerPresent = !flags[30];
  d->isHeader = flags[29];

}

ByteVector Footer::render(bool isHeader) const
{
  ByteVector v;

  // add the file identifier -- "APETAGEX"

  v.append(fileIdentifier());

  // add the version number -- we always render a 2.000 tag regardless of what
  // the tag originally was.

  v.append(ByteVector::fromUInt(2000, false));

  // add the tag size

  v.append(ByteVector::fromUInt(d->tagSize, false));

  // add the item count

  v.append(ByteVector::fromUInt(d->itemCount, false));

  // render and add the flags

  std::bitset<32> flags;

  flags[31] = d->headerPresent;
  flags[30] = false; // footer is always present
  flags[29] = isHeader;

  v.append(ByteVector::fromUInt(flags.to_ulong(), false));

  // add the reserved 64bit

  v.append(ByteVector::fromLongLong(0));

  return v;
}
<commit_msg>Resolve scope resolution for APE::Footer definitions in apefooter.cpp<commit_after>/***************************************************************************
    copyright            : (C) 2004 by Allan Sandfeld Jensen
                           (C) 2002 - 2008 by Scott Wheeler (id3v2header.cpp)
    email                : kde@carewolf.org
 ***************************************************************************/

/***************************************************************************
 *   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., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <iostream>
#include <bitset>

#include <tstring.h>
#include <tdebug.h>

#include "apefooter.h"

using namespace TagLib;
using namespace APE;

class APE::Footer::FooterPrivate
{
public:
  FooterPrivate() : version(0),
                    footerPresent(true),
                    headerPresent(false),
                    isHeader(false),
                    itemCount(0),
                    tagSize(0) {}

  ~FooterPrivate() {}

  uint version;

  bool footerPresent;
  bool headerPresent;

  bool isHeader;

  uint itemCount;
  uint tagSize;

  static const uint size = 32;
};

////////////////////////////////////////////////////////////////////////////////
// static members
////////////////////////////////////////////////////////////////////////////////

TagLib::uint APE::Footer::size()
{
  return FooterPrivate::size;
}

ByteVector APE::Footer::fileIdentifier()
{
  return ByteVector::fromCString("APETAGEX");
}

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

APE::Footer::Footer()
{
  d = new FooterPrivate;
}

APE::Footer::Footer(const ByteVector &data)
{
  d = new FooterPrivate;
  parse(data);
}

APE::Footer::~Footer()
{
  delete d;
}

TagLib::uint APE::Footer::version() const
{
  return d->version;
}

bool APE::Footer::headerPresent() const
{
  return d->headerPresent;
}

bool APE::Footer::footerPresent() const
{
  return d->footerPresent;
}

bool APE::Footer::isHeader() const
{
  return d->isHeader;
}

void APE::Footer::setHeaderPresent(bool b) const
{
  d->headerPresent = b;
}

TagLib::uint APE::Footer::itemCount() const
{
  return d->itemCount;
}

void APE::Footer::setItemCount(uint s)
{
  d->itemCount = s;
}

TagLib::uint APE::Footer::tagSize() const
{
  return d->tagSize;
}

TagLib::uint APE::Footer::completeTagSize() const
{
  if(d->headerPresent)
    return d->tagSize + d->size;
  else
    return d->tagSize;
}

void APE::Footer::setTagSize(uint s)
{
  d->tagSize = s;
}

void APE::Footer::setData(const ByteVector &data)
{
  parse(data);
}

ByteVector APE::Footer::renderFooter() const
{
    return render(false);
}

ByteVector APE::Footer::renderHeader() const
{
    if (!d->headerPresent) return ByteVector();

    return render(true);
}

////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////

void APE::Footer::parse(const ByteVector &data)
{
  if(data.size() < size())
    return;

  // The first eight bytes, data[0..7], are the File Identifier, "APETAGEX".

  // Read the version number

  d->version = data.mid(8, 4).toUInt(false);

  // Read the tag size

  d->tagSize = data.mid(12, 4).toUInt(false);

  // Read the item count

  d->itemCount = data.mid(16, 4).toUInt(false);

  // Read the flags

  std::bitset<32> flags(TAGLIB_CONSTRUCT_BITSET(data.mid(20, 4).toUInt(false)));

  d->headerPresent = flags[31];
  d->footerPresent = !flags[30];
  d->isHeader = flags[29];

}

ByteVector APE::Footer::render(bool isHeader) const
{
  ByteVector v;

  // add the file identifier -- "APETAGEX"

  v.append(fileIdentifier());

  // add the version number -- we always render a 2.000 tag regardless of what
  // the tag originally was.

  v.append(ByteVector::fromUInt(2000, false));

  // add the tag size

  v.append(ByteVector::fromUInt(d->tagSize, false));

  // add the item count

  v.append(ByteVector::fromUInt(d->itemCount, false));

  // render and add the flags

  std::bitset<32> flags;

  flags[31] = d->headerPresent;
  flags[30] = false; // footer is always present
  flags[29] = isHeader;

  v.append(ByteVector::fromUInt(flags.to_ulong(), false));

  // add the reserved 64bit

  v.append(ByteVector::fromLongLong(0));

  return v;
}
<|endoftext|>


<commit_before>#include "kernel.h"
#include "raster.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "polygon.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "pixeliterator.h"
#include "mastercatalog.h"
#include "assignment.h"

using namespace Ilwis;
using namespace BaseOperations;

Assignment::Assignment() : _number(rILLEGAL)
{
}

Assignment::Assignment(quint64 metaid, const Ilwis::OperationExpression &expr) :
    OperationImplementation(metaid, expr),
    _number(rILLEGAL)
{
}

bool Assignment::assignFeatureCoverage(ExecutionContext *ctx) {

    IFeatureCoverage outputFC = _outputObj.get<FeatureCoverage>();
    IFeatureCoverage inputFC = _inputObj.get<FeatureCoverage>();
    FeatureIterator iterIn(inputFC);
    for_each(iterIn, iterIn.end(), [&](FeatureInterface& feature){
        outputFC->newFeatureFrom(feature);
    });

    return true;
}

bool Assignment::assignGridCoverage(ExecutionContext *ctx) {
    IGridCoverage outputGC = _outputObj.get<GridCoverage>();
    std::function<bool(const Box3D<qint32>)> Assign = [&](const Box3D<qint32> box ) -> bool {
        IGridCoverage inputGC = _inputObj.get<GridCoverage>();
        PixelIterator iterIn(inputGC, box);
        PixelIterator iterOut(outputGC, box);

        double v_in = 0;
        //TODO in principle the stl::copy should work but as yet there is no overload yet(20130621) for
        // + and - operator which is required for this
        //stl::copy(iterIn, iterIn.end(), iterOut);
        for_each(iterOut, iterOut.end(), [&](double& v){
            v_in = *iterIn;
            if ( v_in != rUNDEF) {
                v = v_in;
            }
            ++iterIn;
            ++iterOut;
        });
        return true;
    };

    return  OperationHelper::execute(ctx, Assign, outputGC);

}

bool Assignment::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;
    bool res = false;
    if ( _number != rILLEGAL) {

    } else {
        if ( _inputObj.isValid()) {
            if ( _inputObj->ilwisType() == itGRIDCOVERAGE) {
                if((res = assignGridCoverage(ctx)) == true)
                    setOutput<GridCoverage>(ctx, symTable);
            }
            if ( (_inputObj->ilwisType() & itFEATURECOVERAGE)!= 0) {
                if((res = assignFeatureCoverage(ctx)) == true)
                    setOutput<FeatureCoverage>(ctx, symTable);
            }
        }
    }
    return res;
}

Ilwis::OperationImplementation *Assignment::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Assignment(metaid, expr);
}

Ilwis::OperationImplementation::State Assignment::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 1) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"assignment","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }

    bool ok;
    _number = _expression.parm(0).value().toDouble(&ok);
    if ( !ok) {
        _number = rILLEGAL;
        QString coverage = _expression.parm(0).value();
        Resource res = mastercatalog()->name2Resource(coverage);
        if ( !res.isValid()) {
            ERROR1(ERR_COULD_NOT_OPEN_READING_1,coverage);
            return sPREPAREFAILED;
        }
        _inputObj.prepare(coverage, res.ilwisType());
        OperationHelper helper;
        _outputObj = helper.initialize(_inputObj, res.ilwisType(), _expression.parm(0),
                                       itGRIDSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF | itDOMAIN | itTABLE);
        QString outname = _expression.parm(0,false).value();
        if ( outname != sUNDEF)
            _outputObj->setName(outname);
    } else {
        _varName = _expression.parm(0,false).value();
    }

    return sPREPARED;
}

quint64 Assignment::createMetadata()
{
    QString url = QString("ilwis://operations/assignment");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","assignment");
    res.addProperty("syntax","assignment(thing)");
    res.addProperty("inparameters","1");
    res.addProperty("pin_1_type", itANY);
    res.addProperty("pin_1_name", TR("input thing"));
    res.addProperty("pin_1_desc",TR("input thing"));
    res.addProperty("pout_1_type", itANY);
    res.addProperty("pout_1_name", TR("copied thing"));
    res.addProperty("pout_1_desc",TR(""));
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();

}
<commit_msg>removed unneeded parameyter<commit_after>#include "kernel.h"
#include "raster.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "polygon.h"
#include "geometry.h"
#include "feature.h"
#include "featurecoverage.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "pixeliterator.h"
#include "mastercatalog.h"
#include "assignment.h"

using namespace Ilwis;
using namespace BaseOperations;

Assignment::Assignment() : _number(rILLEGAL)
{
}

Assignment::Assignment(quint64 metaid, const Ilwis::OperationExpression &expr) :
    OperationImplementation(metaid, expr),
    _number(rILLEGAL)
{
}

bool Assignment::assignFeatureCoverage(ExecutionContext *ctx) {

    IFeatureCoverage outputFC = _outputObj.get<FeatureCoverage>();
    IFeatureCoverage inputFC = _inputObj.get<FeatureCoverage>();
    FeatureIterator iterIn(inputFC);
    for_each(iterIn, iterIn.end(), [&](FeatureInterface& feature){
        outputFC->newFeatureFrom(feature);
    });

    return true;
}

bool Assignment::assignGridCoverage(ExecutionContext *ctx) {
    IGridCoverage outputGC = _outputObj.get<GridCoverage>();
    std::function<bool(const Box3D<qint32>)> Assign = [&](const Box3D<qint32> box ) -> bool {
        IGridCoverage inputGC = _inputObj.get<GridCoverage>();
        PixelIterator iterIn(inputGC, box);
        PixelIterator iterOut(outputGC, box);

        double v_in = 0;
        //TODO in principle the stl::copy should work but as yet there is no overload yet(20130621) for
        // + and - operator which is required for this
        //stl::copy(iterIn, iterIn.end(), iterOut);
        for_each(iterOut, iterOut.end(), [&](double& v){
            v_in = *iterIn;
            if ( v_in != rUNDEF) {
                v = v_in;
            }
            ++iterIn;
            ++iterOut;
        });
        return true;
    };

    return  OperationHelper::execute(ctx, Assign, outputGC);

}

bool Assignment::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;
    bool res = false;
    if ( _number != rILLEGAL) {

    } else {
        if ( _inputObj.isValid()) {
            if ( _inputObj->ilwisType() == itGRIDCOVERAGE) {
                if((res = assignGridCoverage(ctx)) == true)
                    setOutput<GridCoverage>(ctx, symTable);
            }
            if ( (_inputObj->ilwisType() & itFEATURECOVERAGE)!= 0) {
                if((res = assignFeatureCoverage(ctx)) == true)
                    setOutput<FeatureCoverage>(ctx, symTable);
            }
        }
    }
    return res;
}

Ilwis::OperationImplementation *Assignment::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Assignment(metaid, expr);
}

Ilwis::OperationImplementation::State Assignment::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 1) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"assignment","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }

    bool ok;
    _number = _expression.parm(0).value().toDouble(&ok);
    if ( !ok) {
        _number = rILLEGAL;
        QString coverage = _expression.parm(0).value();
        Resource res = mastercatalog()->name2Resource(coverage);
        if ( !res.isValid()) {
            ERROR1(ERR_COULD_NOT_OPEN_READING_1,coverage);
            return sPREPAREFAILED;
        }
        _inputObj.prepare(coverage, res.ilwisType());
        OperationHelper helper;
        _outputObj = helper.initialize(_inputObj, res.ilwisType(),
                                       itGRIDSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF | itDOMAIN | itTABLE);
        QString outname = _expression.parm(0,false).value();
        if ( outname != sUNDEF)
            _outputObj->setName(outname);
    } else {
        _varName = _expression.parm(0,false).value();
    }

    return sPREPARED;
}

quint64 Assignment::createMetadata()
{
    QString url = QString("ilwis://operations/assignment");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","assignment");
    res.addProperty("syntax","assignment(thing)");
    res.addProperty("inparameters","1");
    res.addProperty("pin_1_type", itANY);
    res.addProperty("pin_1_name", TR("input thing"));
    res.addProperty("pin_1_desc",TR("input thing"));
    res.addProperty("pout_1_type", itANY);
    res.addProperty("pout_1_name", TR("copied thing"));
    res.addProperty("pout_1_desc",TR(""));
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();

}
<|endoftext|>


<commit_before>// Copyright Steinwurf ApS 2011-2012.
// Distributed under the "STEINWURF RESEARCH LICENSE 1.0".
// See accompanying file LICENSE.rst or
// http://www.steinwurf.com/licensing

#pragma once

#include <ctime>
#include <cstdint>
#include <cstdio>

#include <gauge/gauge.hpp>

/// A test block represents an encoder and decoder pair
template<class Encoder, class Decoder>
struct throughput_benchmark : public gauge::time_benchmark
{
    void init()
    {
        m_factor = 1;
        gauge::time_benchmark::init();
    }

    void start()
    {
        m_encoded_symbols = 0;
        m_recovered_symbols = 0;
        m_processed_symbols = 0;
        gauge::time_benchmark::start();
    }

    void stop()
    {
        gauge::time_benchmark::stop();
    }

    double measurement()
    {
        // Get the time spent per iteration
        double time = gauge::time_benchmark::measurement();

        //printf("Coding time: %.3f us\n", time);

        gauge::config_set cs = get_current_configuration();
        std::string type = cs.get_value<std::string>("type");
        uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");

        // The number of bytes {en|de}coded
        uint64_t total_bytes = 0;

        if (type == "decoder")
        {
            total_bytes = m_recovered_symbols * symbol_size;
        }
        else if (type == "encoder")
        {
            total_bytes = m_encoded_symbols * symbol_size;
        }
        else
        {
            assert(0);
        }

        // The bytes per iteration
        uint64_t bytes =
            total_bytes / gauge::time_benchmark::iteration_count();

        return bytes / time; // MB/s for each iteration
    }

    void store_run(tables::table& results)
    {
        if (!results.has_column("goodput"))
            results.add_column("goodput");

        results.set_value("goodput", measurement());

        gauge::config_set cs = get_current_configuration();
        std::string type = cs.get_value<std::string>("type");

        if (type == "decoder")
        {
            if (!results.has_column("extra_symbols"))
                results.add_column("extra_symbols");

            uint32_t erased_symbols = cs.get_value<uint32_t>("erased_symbols");
            uint32_t extra_symbols = m_processed_symbols - erased_symbols;
            results.set_value("extra_symbols", extra_symbols);
        }
    }

    bool needs_warmup_iteration()
    {
        return false;
    }

    bool accept_measurement()
    {
        gauge::config_set cs = get_current_configuration();

        std::string type = cs.get_value<std::string>("type");

        if (type == "decoder")
        {
            // If we are benchmarking a decoder, we only accept
            // the measurement if the decoding was successful
            if (m_decoder->is_complete() == false)
            {
                return false;
            }
            // At this point, the output data should be equal to the input data
            assert(m_decoder->verify_data(m_encoder));
        }

        // Force a single iteration (repeated tests produce unstable results)
        return true;
        //return gauge::time_benchmark::accept_measurement();
    }

    std::string unit_text() const
    {
        return "MB/s";
    }

    void get_options(gauge::po::variables_map& options)
    {
        auto symbols = options["symbols"].as<std::vector<uint32_t> >();
        auto loss_rate = options["loss_rate"].as<std::vector<double> >();
        auto symbol_size = options["symbol_size"].as<std::vector<uint32_t> >();
        auto types = options["type"].as<std::vector<std::string> >();

        assert(symbols.size() > 0);
        assert(loss_rate.size() > 0);
        assert(symbol_size.size() > 0);
        assert(types.size() > 0);

        for (const auto& s : symbols)
        {
            for (const auto& r : loss_rate)
            {
                for (const auto& p : symbol_size)
                {
                    // Symbol size must be a multiple of 32
                    assert(p % 32 == 0);

                    for (const auto& t : types)
                    {
                        gauge::config_set cs;
                        cs.set_value<uint32_t>("symbols", s);
                        cs.set_value<uint32_t>("symbol_size", p);
                        cs.set_value<double>("loss_rate", r);
                        cs.set_value<std::string>("type", t);

                        uint32_t encoded = (uint32_t)std::ceil(s * r);
                        cs.set_value<uint32_t>("encoded_symbols", encoded);

                        add_configuration(cs);
                    }
                }
            }
        }
    }

    void setup()
    {
        gauge::config_set cs = get_current_configuration();

        uint32_t symbols = cs.get_value<uint32_t>("symbols");
        uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");
        uint32_t encoded_symbols = cs.get_value<uint32_t>("encoded_symbols");

        m_encoder = std::make_shared<Encoder>(
            symbols, symbol_size, encoded_symbols);
        m_decoder = std::make_shared<Decoder>(
            symbols, symbol_size, encoded_symbols);
    }

    void encode_payloads()
    {
        m_encoder->encode_all();
        m_encoded_symbols += m_encoder->payload_count();
    }

    void decode_payloads()
    {
        m_processed_symbols += m_decoder->decode_all(m_encoder);

        gauge::config_set cs = get_current_configuration();
        uint32_t encoded_symbols = cs.get_value<uint32_t>("encoded_symbols");

        if (m_decoder->is_complete())
        {
            m_recovered_symbols += encoded_symbols;
        }
    }

    /// Run the encoder
    void run_encode()
    {
        // The clock is running
        RUN
        {
            encode_payloads();
        }
    }

    /// Run the decoder
    void run_decode()
    {
        // Encode some data
        encode_payloads();

        // The clock is running
        RUN
        {
            // Decode the payloads
            decode_payloads();
        }
    }

    void run_benchmark()
    {
        gauge::config_set cs = get_current_configuration();

        std::string type = cs.get_value<std::string>("type");

        if (type == "encoder")
        {
            run_encode();
        }
        else if (type == "decoder")
        {
            run_decode();
        }
        else
        {
            assert(0);
        }
    }

protected:

    /// The encoder
    std::shared_ptr<Encoder> m_encoder;

    /// The decoder
    std::shared_ptr<Decoder> m_decoder;

    /// The number of symbols encoded
    uint32_t m_encoded_symbols;

    /// The number of symbols decoded
    uint32_t m_recovered_symbols;

    /// The number of symbols processed by the decoder
    uint32_t m_processed_symbols;

    /// Multiplication factor for payload_count
    uint32_t m_factor;
};
<commit_msg>Fix throughput_benchmark.hpp<commit_after>// Copyright Steinwurf ApS 2011-2012.
// Distributed under the "STEINWURF RESEARCH LICENSE 1.0".
// See accompanying file LICENSE.rst or
// http://www.steinwurf.com/licensing

#pragma once

#include <ctime>
#include <cstdint>
#include <cstdio>

#include <gauge/gauge.hpp>

/// A test block represents an encoder and decoder pair
template<class Encoder, class Decoder>
struct throughput_benchmark : public gauge::time_benchmark
{
    void init()
    {
        m_factor = 1;
        gauge::time_benchmark::init();
    }

    void start()
    {
        m_encoded_symbols = 0;
        m_recovered_symbols = 0;
        m_processed_symbols = 0;
        gauge::time_benchmark::start();
    }

    void stop()
    {
        gauge::time_benchmark::stop();
    }

    double measurement()
    {
        // Get the time spent per iteration
        double time = gauge::time_benchmark::measurement();

        //printf("Coding time: %.3f us\n", time);

        gauge::config_set cs = get_current_configuration();
        std::string type = cs.get_value<std::string>("type");
        uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");

        // The number of bytes {en|de}coded
        uint64_t total_bytes = 0;

        if (type == "decoder")
        {
            total_bytes = m_recovered_symbols * symbol_size;
        }
        else if (type == "encoder")
        {
            total_bytes = m_encoded_symbols * symbol_size;
        }
        else
        {
            assert(0);
        }

        // The bytes per iteration
        uint64_t bytes =
            total_bytes / gauge::time_benchmark::iteration_count();

        return bytes / time; // MB/s for each iteration
    }

    void store_run(tables::table& results)
    {
        if (!results.has_column("goodput"))
            results.add_column("goodput");

        results.set_value("goodput", measurement());

        gauge::config_set cs = get_current_configuration();
        std::string type = cs.get_value<std::string>("type");

        if (type == "decoder")
        {
            if (!results.has_column("extra_symbols"))
                results.add_column("extra_symbols");

            uint32_t erased_symbols = cs.get_value<uint32_t>("erased_symbols");
            uint32_t extra_symbols = m_processed_symbols - erased_symbols;
            results.set_value("extra_symbols", extra_symbols);
        }
    }

    bool needs_warmup_iteration()
    {
        return false;
    }

    bool accept_measurement()
    {
        gauge::config_set cs = get_current_configuration();

        std::string type = cs.get_value<std::string>("type");

        if (type == "decoder")
        {
            // If we are benchmarking a decoder, we only accept
            // the measurement if the decoding was successful
            if (m_decoder->is_complete() == false)
            {
                return false;
            }
            // At this point, the output data should be equal to the input data
            assert(m_decoder->verify_data(m_encoder));
        }

        // Force a single iteration (repeated tests produce unstable results)
        return true;
        //return gauge::time_benchmark::accept_measurement();
    }

    std::string unit_text() const
    {
        return "MB/s";
    }

    void get_options(gauge::po::variables_map& options)
    {
        auto symbols = options["symbols"].as<std::vector<uint32_t> >();
        auto loss_rate = options["loss_rate"].as<std::vector<double> >();
        auto symbol_size = options["symbol_size"].as<std::vector<uint32_t> >();
        auto types = options["type"].as<std::vector<std::string> >();

        assert(symbols.size() > 0);
        assert(loss_rate.size() > 0);
        assert(symbol_size.size() > 0);
        assert(types.size() > 0);

        for (const auto& s : symbols)
        {
            for (const auto& r : loss_rate)
            {
                for (const auto& p : symbol_size)
                {
                    // Symbol size must be a multiple of 32
                    assert(p % 32 == 0);

                    for (const auto& t : types)
                    {
                        gauge::config_set cs;
                        cs.set_value<uint32_t>("symbols", s);
                        cs.set_value<uint32_t>("symbol_size", p);
                        cs.set_value<double>("loss_rate", r);
                        cs.set_value<std::string>("type", t);

                        uint32_t erased = (uint32_t)std::ceil(s * r);
                        cs.set_value<uint32_t>("erased_symbols", erased);

                        add_configuration(cs);
                    }
                }
            }
        }
    }

    void setup()
    {
        gauge::config_set cs = get_current_configuration();

        uint32_t symbols = cs.get_value<uint32_t>("symbols");
        uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");
        uint32_t erased_symbols = cs.get_value<uint32_t>("erased_symbols");

        m_encoder = std::make_shared<Encoder>(
            symbols, symbol_size, erased_symbols);
        m_decoder = std::make_shared<Decoder>(
            symbols, symbol_size, erased_symbols);
    }

    void encode_payloads()
    {
        m_encoder->encode_all();
        m_encoded_symbols += m_encoder->payload_count();
    }

    void decode_payloads()
    {
        m_processed_symbols += m_decoder->decode_all(m_encoder);

        gauge::config_set cs = get_current_configuration();
        uint32_t erased_symbols = cs.get_value<uint32_t>("erased_symbols");

        if (m_decoder->is_complete())
        {
            m_recovered_symbols += erased_symbols;
        }
    }

    /// Run the encoder
    void run_encode()
    {
        // The clock is running
        RUN
        {
            encode_payloads();
        }
    }

    /// Run the decoder
    void run_decode()
    {
        // Encode some data
        encode_payloads();

        // The clock is running
        RUN
        {
            // Decode the payloads
            decode_payloads();
        }
    }

    void run_benchmark()
    {
        gauge::config_set cs = get_current_configuration();

        std::string type = cs.get_value<std::string>("type");

        if (type == "encoder")
        {
            run_encode();
        }
        else if (type == "decoder")
        {
            run_decode();
        }
        else
        {
            assert(0);
        }
    }

protected:

    /// The encoder
    std::shared_ptr<Encoder> m_encoder;

    /// The decoder
    std::shared_ptr<Decoder> m_decoder;

    /// The number of symbols encoded
    uint32_t m_encoded_symbols;

    /// The number of symbols decoded
    uint32_t m_recovered_symbols;

    /// The number of symbols processed by the decoder
    uint32_t m_processed_symbols;

    /// Multiplication factor for payload_count
    uint32_t m_factor;
};
<|endoftext|>


<commit_before>/** s3tee.cc
    Jeremy Barnes, 4 September 2012
    Copyright (c) 2012 Datacratic.  All rights reserved.

    Implementation of the "tee" command that can write its data to an
    s3 bucket.
*/

#include "soa/service/s3.h"
#include "jml/utils/filter_streams.h"
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include <poll.h>

namespace po = boost::program_options;

using namespace std;
using namespace Datacratic;
using namespace ML;

int main(int argc, char* argv[])
{
    ios::sync_with_stdio(true);

    vector<string> outputFiles;
    string localFile;
    string s3KeyId;
    string s3Key;

    po::options_description desc("Main options");
    desc.add_options()
        ("output-uri,o", po::value(&outputFiles), "Output files/uris (can have multiple file/s3://bucket/object)")
        ("s3-key-id,I", po::value<string>(&s3KeyId), "S3 key id")
        ("s3-key,K", po::value<string>(&s3Key), "S3 key")
        ("help,h", "Produce help message");

    po::positional_options_description pos;
    pos.add("output-uri", -1);
    po::variables_map vm;
    bool showHelp = false;

    try{
        po::parsed_options parsed = po::command_line_parser(argc, argv)
            .options(desc)
            .positional(pos)
            .run();
        po::store(parsed, vm);
        po::notify(vm);
    }catch(const std::exception & exc){
        //invalid command line param
        cerr << "command line parsing error: " << exc.what() << endl;
        showHelp = true;
    }

    //If one of the options is set to 'help'...
    if (showHelp || vm.count("help")){
        //Display the options_description
        cout << desc << "\n";
        return showHelp ? 1 : 0;
    }

    if (s3KeyId != "")
        registerS3Buckets(s3KeyId, s3Key);

    std::vector<filter_ostream> streams;
    streams.reserve(outputFiles.size() + 1);

    streams.emplace_back("-");

    for (auto f: outputFiles)
        streams.emplace_back(f);

    size_t bufSize = 4096 * 16;
    char buf[bufSize];

    for (;;) {
        ssize_t res = read(0, buf, bufSize);
        if (res == 0)
            break;
        if (res == -1 && errno == EINTR)
            continue;
        if (res == -1)
            throw ML::Exception(errno, "read");
        for (unsigned s = 0;  s < streams.size();  ++s)
            streams[s].write(buf, res);
        streams[0] << std::flush;
    }

    return 0;
}

<commit_msg>Registers only the needed buckets rather than going through registerS3Buckets<commit_after>/** s3tee.cc
    Jeremy Barnes, 4 September 2012
    Copyright (c) 2012 Datacratic.  All rights reserved.

    Implementation of the "tee" command that can write its data to an
    s3 bucket.
*/

#include "soa/service/s3.h"
#include "jml/utils/filter_streams.h"
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include <poll.h>

namespace po = boost::program_options;

using namespace std;
using namespace Datacratic;
using namespace ML;

int main(int argc, char* argv[])
{
    ios::sync_with_stdio(true);

    vector<string> outputFiles;
    string localFile;
    string s3KeyId;
    string s3Key;

    po::options_description desc("Main options");
    desc.add_options()
        ("output-uri,o", po::value(&outputFiles), "Output files/uris (can have multiple file/s3://bucket/object)")
        ("s3-key-id,I", po::value<string>(&s3KeyId), "S3 key id")
        ("s3-key,K", po::value<string>(&s3Key), "S3 key")
        ("help,h", "Produce help message");

    po::positional_options_description pos;
    pos.add("output-uri", -1);
    po::variables_map vm;
    bool showHelp = false;

    try{
        po::parsed_options parsed = po::command_line_parser(argc, argv)
            .options(desc)
            .positional(pos)
            .run();
        po::store(parsed, vm);
        po::notify(vm);
    }catch(const std::exception & exc){
        //invalid command line param
        cerr << "command line parsing error: " << exc.what() << endl;
        showHelp = true;
    }

    //If one of the options is set to 'help'...
    if (showHelp || vm.count("help")){
        //Display the options_description
        cout << desc << "\n";
        return showHelp ? 1 : 0;
    }

    for (auto f: outputFiles){
        if(f.substr(0, 5) == "s3://"){
            size_t pos = f.substr(5).find("/");
            registerS3Bucket(f.substr(5, pos), s3KeyId, s3Key);
        }
    }

    std::vector<filter_ostream> streams;
    streams.reserve(outputFiles.size() + 1);

    streams.emplace_back("-");

    for (auto f: outputFiles)
        streams.emplace_back(f);

    size_t bufSize = 4096 * 16;
    char buf[bufSize];

    for (;;) {
        ssize_t res = read(0, buf, bufSize);
        if (res == 0)
            break;
        if (res == -1 && errno == EINTR)
            continue;
        if (res == -1)
            throw ML::Exception(errno, "read");
        for (unsigned s = 0;  s < streams.size();  ++s)
            streams[s].write(buf, res);
        streams[0] << std::flush;
    }

    return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include "acmacs-base/text-style.hh"

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

namespace acmacs
{
    class PointShape
    {
     public:
        enum Shape {Circle, Box, Triangle};

        PointShape() : mShape{Circle} {}
        PointShape(const PointShape&) = default;
        PointShape(Shape aShape) : mShape{aShape} {}
        PointShape(std::string aShape) { from(aShape); }
        PointShape(std::string_view aShape) { from(aShape); }
        PointShape& operator=(const PointShape&) = default;
        PointShape& operator=(Shape aShape) { mShape = aShape; return *this; }
        PointShape& operator=(std::string aShape) { from(aShape); return *this; }
        [[nodiscard]] bool operator==(const PointShape& ps) const { return mShape == ps.mShape; }
        [[nodiscard]] bool operator!=(const PointShape& ps) const { return mShape != ps.mShape; }

        operator Shape() const { return mShape; }

        operator std::string() const
            {
                switch(mShape) {
                  case Circle:
                      return "CIRCLE";
                  case Box:
                      return "BOX";
                  case Triangle:
                      return "TRIANGLE";
                }
                return "CIRCLE"; // gcc 7.2 wants this
            }

     private:
        Shape mShape;

        void from(std::string_view aShape)
            {
                if (!aShape.empty()) {
                    switch (aShape.front()) {
                      case 'C':
                      case 'c':
                          mShape = Circle;
                          break;
                      case 'B':
                      case 'b':
                      case 'R': // rectangle
                      case 'r':
                          mShape = Box;
                          break;
                      case 'T':
                      case 't':
                          mShape = Triangle;
                          break;
                      default:
                          std::runtime_error("Unrecognized point shape: " + std::string(aShape));
                    }
                }
                else {
                    std::runtime_error("Unrecognized empty point shape");
                }
            }

    }; // class PointShape

    inline std::string to_string(const PointShape& shape) { return shape; }

    template <> inline std::string to_string(const acmacs::internal::field_optional_with_default<PointShape>& shape)
    {
        if (shape.is_default())
            return acmacs::to_string(*shape) + "(default)";
        else
            return acmacs::to_string(*shape);
    }

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

    class PointStyle
    {
      public:
        template <typename T> using field = acmacs::internal::field_optional_with_default<T>;

        [[nodiscard]] bool operator==(const PointStyle& rhs) const
        {
            return shown == rhs.shown && fill == rhs.fill && outline == rhs.outline && outline_width == rhs.outline_width && size == rhs.size && rotation == rhs.rotation && aspect == rhs.aspect &&
                   shape == rhs.shape && label == rhs.label && label_text == rhs.label_text;
        }
        [[nodiscard]] bool operator!=(const PointStyle& rhs) const { return !operator==(rhs); }

        field<bool> shown{true};
        field<Color> fill{TRANSPARENT};
        field<Color> outline{BLACK};
        field<Pixels> outline_width{Pixels{1.0}};
        field<Pixels> size{Pixels{5.0}};
        field<Rotation> rotation{NoRotation};
        field<Aspect> aspect{AspectNormal};
        field<PointShape> shape;
        LabelStyle label;
        field<std::string> label_text;

        PointStyle& scale(double aScale) { size = static_cast<Pixels>(size) * aScale; return *this; }
        PointStyle& scale_outline(double aScale) { outline_width = static_cast<Pixels>(outline_width) * aScale; return *this; }

    }; // class PointStyle

    inline std::string to_string(const PointStyle& style)
    {
        return to_string(style.shape) + " shown:" + to_string(style.shown) + " F:" + to_string(style.fill) + " O:" + to_string(style.outline) + " o:" + to_string(style.outline_width) +
                " S:" + to_string(style.size) + ' ' + to_string(style.aspect) + ' ' + to_string(style.rotation) + " label:[" + to_string(style.label) + "] t:" + to_string(style.label_text);
    }

      // for debugging
    inline std::string equality_report(const PointStyle& s1, const PointStyle& s2)
    {
        return "shown:" + to_string(s1.shown == s2.shown) + " fill:" + to_string(s1.fill == s2.fill) + " outline:" + to_string(s1.outline == s2.outline) +
               " outline_width:" + to_string(s1.outline_width == s2.outline_width) + " size:" + to_string(s1.size == s2.size) + " rotation:" + to_string(s1.rotation == s2.rotation) +
               " aspect:" + to_string(s1.aspect == s2.aspect) + " shape:" + to_string(s1.shape == s2.shape) + " label:" + to_string(s1.label == s2.label) +
               " label_text:" + to_string(s1.label_text == s2.label_text);
    }

    inline std::ostream& operator<<(std::ostream& s, const acmacs::PointShape& shape) { return s << to_string(shape); }

    inline std::ostream& operator<<(std::ostream& s, const acmacs::PointStyle& style) { return s << to_string(style); }

} // namespace acmacs

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

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs::PointStyles<commit_after>#pragma once

#include "acmacs-base/text-style.hh"

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

namespace acmacs
{
    class PointShape
    {
     public:
        enum Shape {Circle, Box, Triangle};

        PointShape() : mShape{Circle} {}
        PointShape(const PointShape&) = default;
        PointShape(Shape aShape) : mShape{aShape} {}
        PointShape(std::string aShape) { from(aShape); }
        PointShape(std::string_view aShape) { from(aShape); }
        PointShape& operator=(const PointShape&) = default;
        PointShape& operator=(Shape aShape) { mShape = aShape; return *this; }
        PointShape& operator=(std::string aShape) { from(aShape); return *this; }
        [[nodiscard]] bool operator==(const PointShape& ps) const { return mShape == ps.mShape; }
        [[nodiscard]] bool operator!=(const PointShape& ps) const { return mShape != ps.mShape; }

        operator Shape() const { return mShape; }

        operator std::string() const
            {
                switch(mShape) {
                  case Circle:
                      return "CIRCLE";
                  case Box:
                      return "BOX";
                  case Triangle:
                      return "TRIANGLE";
                }
                return "CIRCLE"; // gcc 7.2 wants this
            }

     private:
        Shape mShape;

        void from(std::string_view aShape)
            {
                if (!aShape.empty()) {
                    switch (aShape.front()) {
                      case 'C':
                      case 'c':
                          mShape = Circle;
                          break;
                      case 'B':
                      case 'b':
                      case 'R': // rectangle
                      case 'r':
                          mShape = Box;
                          break;
                      case 'T':
                      case 't':
                          mShape = Triangle;
                          break;
                      default:
                          std::runtime_error("Unrecognized point shape: " + std::string(aShape));
                    }
                }
                else {
                    std::runtime_error("Unrecognized empty point shape");
                }
            }

    }; // class PointShape

    inline std::string to_string(const PointShape& shape) { return shape; }

    template <> inline std::string to_string(const acmacs::internal::field_optional_with_default<PointShape>& shape)
    {
        if (shape.is_default())
            return acmacs::to_string(*shape) + "(default)";
        else
            return acmacs::to_string(*shape);
    }

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

    class PointStyle
    {
      public:
        template <typename T> using field = acmacs::internal::field_optional_with_default<T>;

        [[nodiscard]] bool operator==(const PointStyle& rhs) const
        {
            return shown == rhs.shown && fill == rhs.fill && outline == rhs.outline && outline_width == rhs.outline_width && size == rhs.size && rotation == rhs.rotation && aspect == rhs.aspect &&
                   shape == rhs.shape && label == rhs.label && label_text == rhs.label_text;
        }
        [[nodiscard]] bool operator!=(const PointStyle& rhs) const { return !operator==(rhs); }

        field<bool> shown{true};
        field<Color> fill{TRANSPARENT};
        field<Color> outline{BLACK};
        field<Pixels> outline_width{Pixels{1.0}};
        field<Pixels> size{Pixels{5.0}};
        field<Rotation> rotation{NoRotation};
        field<Aspect> aspect{AspectNormal};
        field<PointShape> shape;
        LabelStyle label;
        field<std::string> label_text;

        PointStyle& scale(double aScale) { size = static_cast<Pixels>(size) * aScale; return *this; }
        PointStyle& scale_outline(double aScale) { outline_width = static_cast<Pixels>(outline_width) * aScale; return *this; }

    }; // class PointStyle

    inline std::string to_string(const PointStyle& style)
    {
        return to_string(style.shape) + " shown:" + to_string(style.shown) + " F:" + to_string(style.fill) + " O:" + to_string(style.outline) + " o:" + to_string(style.outline_width) +
                " S:" + to_string(style.size) + ' ' + to_string(style.aspect) + ' ' + to_string(style.rotation) + " label:[" + to_string(style.label) + "] t:" + to_string(style.label_text);
    }

      // for debugging
    inline std::string equality_report(const PointStyle& s1, const PointStyle& s2)
    {
        return "shown:" + to_string(s1.shown == s2.shown) + " fill:" + to_string(s1.fill == s2.fill) + " outline:" + to_string(s1.outline == s2.outline) +
               " outline_width:" + to_string(s1.outline_width == s2.outline_width) + " size:" + to_string(s1.size == s2.size) + " rotation:" + to_string(s1.rotation == s2.rotation) +
               " aspect:" + to_string(s1.aspect == s2.aspect) + " shape:" + to_string(s1.shape == s2.shape) + " label:" + to_string(s1.label == s2.label) +
               " label_text:" + to_string(s1.label_text == s2.label_text);
    }

    inline std::ostream& operator<<(std::ostream& s, const acmacs::PointShape& shape) { return s << to_string(shape); }

    inline std::ostream& operator<<(std::ostream& s, const acmacs::PointStyle& style) { return s << to_string(style); }

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

    class PointStyles
    {
     public:
        PointStyles() = default;
        PointStyles(const PointStyles&) = delete;
        virtual ~PointStyles() = default;

        virtual size_t number_of_points() const = 0;
        virtual bool empty() const = 0;
        virtual PointStyle style(size_t aPointNo) const = 0;

    }; // class PointStyles

} // namespace acmacs

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

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/sha1_hash.hpp>
#include <boost/python.hpp>

void bind_sha1_hash()
{
    using namespace boost::python;
    using namespace libtorrent;

    class_<sha1_hash>("sha1_hash")
        .def(self == self)
        .def(self != self)
        .def(self < self)
        .def(self_ns::str(self))
        .def(init<char const*>())
        .def("clear", &sha1_hash::clear)
        .def("is_all_zeros", &sha1_hash::is_all_zeros)
        .def("to_string", &sha1_hash::to_string)
//        .def("__getitem__", &sha1_hash::opreator[])
        ;

    scope().attr("big_number") = scope().attr("sha1_hash");
    scope().attr("peer_id") = scope().attr("peer_id");
}

<commit_msg>fix typo in python binding<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/sha1_hash.hpp>
#include <boost/python.hpp>

void bind_sha1_hash()
{
    using namespace boost::python;
    using namespace libtorrent;

    class_<sha1_hash>("sha1_hash")
        .def(self == self)
        .def(self != self)
        .def(self < self)
        .def(self_ns::str(self))
        .def(init<char const*>())
        .def("clear", &sha1_hash::clear)
        .def("is_all_zeros", &sha1_hash::is_all_zeros)
        .def("to_string", &sha1_hash::to_string)
//        .def("__getitem__", &sha1_hash::opreator[])
        ;

    scope().attr("big_number") = scope().attr("sha1_hash");
    scope().attr("peer_id") = scope().attr("sha1_hash");
}

<|endoftext|>