<commit_before>/*
* Copyright (C) 2017 by Grapefruit Tech
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/

#ifndef VORPAL_VIDEO_RENDERER_HPP
#define VORPAL_VIDEO_RENDERER_HPP

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <cstdint>
#include <vector>
#include <string>

struct GLFWwindow;

namespace vp
{
    namespace video
    {
        struct QueueFamilyIndices
        {
            int graphicsFamily = -1;
            int presentFamily = -1;

            bool isComplete() const
            {
                 return graphicsFamily >= 0 && presentFamily >= 0;
            }
        };

        struct SwapChainSupportDetails
        {
            VkSurfaceCapabilitiesKHR capabilities;
            std::vector<VkSurfaceFormatKHR> formats;
            std::vector<VkPresentModeKHR> presentModes;
        };

        /** @brief  Vulkan renderer class
         *
         *  Initializes and controls Vulkan API
         */
        class Renderer
        {
        public:
            Renderer();
            ~Renderer();

            Renderer(const Renderer &other) = delete;
            Renderer(const Renderer &&other) = delete;
            Renderer &operator=(const Renderer &other) = delete;
            Renderer &operator=(const Renderer &&other) = delete;

            bool Init();
            void Deinit();
            void Render();
            static void onWindowResized(GLFWwindow* window, int width, int height);
            bool RecreateSwapChain();
        private:
            bool m_isInitialized;
            GLFWwindow *m_pWindow;

            VkInstance m_vkInstance;
            VkPhysicalDevice m_vkPhysicalDevice;
            VkDevice m_vkLogicalDevice;
            VkSwapchainKHR m_vkSwapChain;
            VkQueue m_graphicsQueue;
            VkQueue m_presentQueue;
            VkSurfaceKHR m_vkWindowSurface;
            VkFormat m_swapChainImageFormat;
            VkExtent2D m_swapChainExtent;
            VkPipelineLayout m_pipelineLayout;
            VkPipeline m_graphicsPipeline;
            VkRenderPass m_renderPass;
            VkCommandPool m_commandPool;
            VkSemaphore m_imageAvailableSemaphore;
            VkSemaphore m_renderFinishedSemaphore;
            std::vector<const char*> m_validationLayers;
            std::vector<const char*> m_deviceExtensions;
            VkDebugReportCallbackEXT m_vulkanCallback;
            std::string m_gpuName;
            std::vector<VkImage> m_swapChainImages;
            std::vector<VkImageView> m_swapChainImageViews;
            std::vector<VkFramebuffer> m_swapChainFramebuffers;
            std::vector<VkCommandBuffer> m_commandBuffers;
        #ifdef NDEBUG
            static const bool s_enableValidationLayers = false;
        #else
            static const bool s_enableValidationLayers = true;
        #endif

            bool CreateInstance();
            bool CheckValidationLayerSupport() const;
            bool PickPhysicalDevice();
            bool CreateLogicalDevice();
            bool CreateSurface();
            bool CreateSwapChain();
            bool CreateImageViews();
            bool CreateRenderPass();
            bool CreateGraphicsPipeline();
            bool CreateFramebuffers();
            bool CreateCommandPool();
            bool CreateCommandBuffers();
            bool CreateSemaphores();
            bool CreateShaderModule(const std::vector<uint8_t>& code, VkShaderModule &shaderModule);
            bool IsDeviceSuitable(VkPhysicalDevice device);
            bool CheckDeviceExtensionSupport(VkPhysicalDevice device);
            bool Frame();
            std::vector<const char*> GetRequiredExtensions();
            QueueFamilyIndices FindQueueFamilies(VkPhysicalDevice device);
            SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device);
            VkSurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
            VkPresentModeKHR ChooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes);
            VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
            bool SetupDebugCallback();
            void DestroyDebugReportCallbackEXT();
            void waitAsyncEnd();
            VkResult CreateDebugReportCallbackEXT(const VkDebugReportCallbackCreateInfoEXT* pCreateInfo);
        };
    }
}

#endif // VORPAL_VIDEO_RENDERER_HPP
<commit_msg>Updated header<commit_after>/*
* Copyright (C) 2017 by Grapefruit Tech
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/

#ifndef VORPAL_VIDEO_RENDERER_HPP
#define VORPAL_VIDEO_RENDERER_HPP

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <cstdint>
#include <vector>
#include <string>

struct GLFWwindow;

namespace vp
{
namespace video
{
    struct QueueFamilyIndices
    {
        int graphicsFamily = -1;
        int presentFamily  = -1;

        bool isComplete() const
        {
            return graphicsFamily >= 0 && presentFamily >= 0;
        }
    };

    struct SwapChainSupportDetails
    {
        VkSurfaceCapabilitiesKHR capabilities;
        std::vector<VkSurfaceFormatKHR> formats;
        std::vector<VkPresentModeKHR> presentModes;
    };

    /** @brief  Vulkan renderer class
     *
     *  Initializes and controls Vulkan API
     */
    class Renderer
    {
    public:
        Renderer();
        ~Renderer();

        Renderer(const Renderer& other)  = delete;
        Renderer(const Renderer&& other) = delete;
        Renderer& operator=(const Renderer& other) = delete;
        Renderer& operator=(const Renderer&& other) = delete;

        bool Init();
        void Deinit();
        void Render();
        static void onWindowResized(GLFWwindow* window, int width, int height);
        bool RecreateSwapChain();

    private:
        bool m_isInitialized;
        GLFWwindow* m_pWindow;

        VkInstance m_vkInstance;
        VkPhysicalDevice m_vkPhysicalDevice;
        VkDevice m_vkLogicalDevice;
        VkSwapchainKHR m_vkSwapChain;
        VkQueue m_graphicsQueue;
        VkQueue m_presentQueue;
        VkSurfaceKHR m_vkWindowSurface;
        VkFormat m_swapChainImageFormat;
        VkExtent2D m_swapChainExtent;
        VkPipelineLayout m_pipelineLayout;
        VkPipeline m_graphicsPipeline;
        VkRenderPass m_renderPass;
        VkCommandPool m_commandPool;
        VkSemaphore m_imageAvailableSemaphore;
        VkSemaphore m_renderFinishedSemaphore;
        std::vector<const char*> m_validationLayers;
        std::vector<const char*> m_deviceExtensions;
        VkDebugReportCallbackEXT m_vulkanCallback;
        std::string m_gpuName;
        std::vector<VkImage> m_swapChainImages;
        std::vector<VkImageView> m_swapChainImageViews;
        std::vector<VkFramebuffer> m_swapChainFramebuffers;
        std::vector<VkCommandBuffer> m_commandBuffers;
#ifdef NDEBUG
        static const bool s_enableValidationLayers = false;
#else
        static const bool s_enableValidationLayers = true;
#endif

        bool CreateInstance();
        bool CheckValidationLayerSupport() const;
        bool PickPhysicalDevice();
        bool CreateLogicalDevice();
        bool CreateSurface();
        bool CreateSwapChain();
        bool CreateImageViews();
        bool CreateRenderPass();
        bool CreateGraphicsPipeline();
        bool CreateFramebuffers();
        bool CreateCommandPool();
        bool CreateCommandBuffers();
        bool CreateSemaphores();
        bool CreateShaderModule(const std::vector<uint8_t>& code, VkShaderModule& shaderModule);
        bool IsDeviceSuitable(VkPhysicalDevice device);
        bool CheckDeviceExtensionSupport(VkPhysicalDevice device);
        bool Frame();
        std::vector<const char*> GetRequiredExtensions();
        QueueFamilyIndices FindQueueFamilies(VkPhysicalDevice device);
        SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device);
        VkSurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
        VkPresentModeKHR ChooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes);
        VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
        bool SetupDebugCallback();
        void DestroyDebugReportCallbackEXT();
        void waitAsyncEnd();
        VkResult CreateDebugReportCallbackEXT(const VkDebugReportCallbackCreateInfoEXT* pCreateInfo);
    };
}
}

#endif // VORPAL_VIDEO_RENDERER_HPP
<|endoftext|>


<commit_before>//
// winLAME - a frontend for the LAME encoding engine
// Copyright (c) 2014-2017 Michael Fink
//
// 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
/// \file Path.hpp
/// \brief Path class
//
#pragma once

/// file and folder path class
class Path
{
public:
   // ctors

   /// default ctor
   explicit Path()
   {
      // no further initialisation necessary
   }

   /// ctor that takes a path
   Path(const CString& path)
      :m_path(path)
   {
   }

   // operators

   /// returns CString
   explicit operator const CString&() const { return m_path; }
   /// returns raw string pointer
   explicit operator LPCTSTR() const { return m_path; }

   // getters

   /// converts path to string
   CString ToString() const { return m_path; }

   /// returns filename and extension
   CString FilenameAndExt() const;

   /// returns filename without extension
   CString FilenameOnly() const;

   /// returns folder name, without filename, but ending slash
   CString FolderName() const;

   /// returns short path name (filename in 8.3 format)
   CString ShortPathName() const;

   /// make this path relative to the given root path and returns it
   CString MakeRelativeTo(const CString& rootPath);

   /// returns if stored path is a relative path
   bool IsRelative() const;

   /// returns if path represents a file and if it exists
   bool FileExists() const;

   /// returns if path represents a folder and if it exists
   bool FolderExists() const;

   // methods

   /// canonicalizes path by removing '..', etc.
   bool Canonicalize();

   /// combine path with given second part and return new path
   Path Combine(const CString& part2);

   /// adds a backslash at the end of the path
   static void AddEndingBackslash(CString& path);

   /// combine both path parts and return new path
   static Path Combine(const CString& part1, const CString& part2)
   {
      Path path1(part1);
      return path1.Combine(part2);
   }

   /// returns special folder; see CSIDL_* constants
   static CString SpecialFolder(int csidl);

   /// returns the windows folder
   static CString WindowsFolder();

   /// returns the temp folder
   static CString TempFolder();

   /// creates a directory, possibly also creating non-existent parent directories
   static bool CreateDirectoryRecursive(LPCTSTR directoryName);

   // public members

   /// path separator string
   static const TCHAR Separator[2];

   /// path separator character
   static const TCHAR SeparatorCh = _T('\\');

private:
   /// path
   CString m_path;
};
<commit_msg>fixed license block<commit_after>//
// ulib - a collection of useful classes
// Copyright (C) 2014-2017 Michael Fink
//
/// \file Path.hpp Path class
//

#pragma once

/// file and folder path class
class Path
{
public:
   // ctors

   /// default ctor
   explicit Path()
   {
      // no further initialisation necessary
   }

   /// ctor that takes a path
   Path(const CString& path)
      :m_path(path)
   {
   }

   // operators

   /// returns CString
   explicit operator const CString&() const { return m_path; }
   /// returns raw string pointer
   explicit operator LPCTSTR() const { return m_path; }

   // getters

   /// converts path to string
   CString ToString() const { return m_path; }

   /// returns filename and extension
   CString FilenameAndExt() const;

   /// returns filename without extension
   CString FilenameOnly() const;

   /// returns folder name, without filename, but ending slash
   CString FolderName() const;

   /// returns short path name (filename in 8.3 format)
   CString ShortPathName() const;

   /// make this path relative to the given root path and returns it
   CString MakeRelativeTo(const CString& rootPath);

   /// returns if stored path is a relative path
   bool IsRelative() const;

   /// returns if path represents a file and if it exists
   bool FileExists() const;

   /// returns if path represents a folder and if it exists
   bool FolderExists() const;

   // methods

   /// canonicalizes path by removing '..', etc.
   bool Canonicalize();

   /// combine path with given second part and return new path
   Path Combine(const CString& part2);

   /// adds a backslash at the end of the path
   static void AddEndingBackslash(CString& path);

   /// combine both path parts and return new path
   static Path Combine(const CString& part1, const CString& part2)
   {
      Path path1(part1);
      return path1.Combine(part2);
   }

   /// returns special folder; see CSIDL_* constants
   static CString SpecialFolder(int csidl);

   /// returns the windows folder
   static CString WindowsFolder();

   /// returns the temp folder
   static CString TempFolder();

   /// creates a directory, possibly also creating non-existent parent directories
   static bool CreateDirectoryRecursive(LPCTSTR directoryName);

   // public members

   /// path separator string
   static const TCHAR Separator[2];

   /// path separator character
   static const TCHAR SeparatorCh = _T('\\');

private:
   /// path
   CString m_path;
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/page/CreateWindow.h"

#include "core/dom/Document.h"
#include "core/frame/FrameHost.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
#include "core/page/WindowFeatures.h"
#include "platform/network/ResourceRequest.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "platform/weborigin/SecurityPolicy.h"

namespace blink {

static LocalFrame* createWindow(LocalFrame& openerFrame, LocalFrame& lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer, bool& created)
{
    ASSERT(!features.dialog || request.frameName().isEmpty());

    if (!request.frameName().isEmpty() && request.frameName() != "_blank" && policy == NavigationPolicyIgnore) {
        if (LocalFrame* frame = lookupFrame.loader().findFrameForNavigation(request.frameName(), openerFrame.document())) {
            if (request.frameName() != "_self")
                frame->page()->focusController().setFocusedFrame(frame);
            created = false;
            return frame;
        }
    }

    // Sandboxed frames cannot open new auxiliary browsing contexts.
    if (openerFrame.document()->isSandboxed(SandboxPopups)) {
        // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
        openerFrame.document()->addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Blocked opening '" + request.resourceRequest().url().elidedString() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set."));
        return nullptr;
    }

    if (openerFrame.settings() && !openerFrame.settings()->supportsMultipleWindows()) {
        created = false;
        if (!openerFrame.tree().top()->isLocalFrame())
            return nullptr;
        return toLocalFrame(openerFrame.tree().top());
    }

    Page* oldPage = openerFrame.page();
    if (!oldPage)
        return nullptr;

    Page* page = oldPage->chrome().client().createWindow(&openerFrame, request, features, policy, shouldSendReferrer);
    if (!page || !page->mainFrame()->isLocalFrame())
        return nullptr;
    FrameHost* host = &page->frameHost();

    ASSERT(page->mainFrame());
    LocalFrame& frame = *page->deprecatedLocalMainFrame();

    if (request.frameName() != "_blank")
        frame.tree().setName(request.frameName());

    host->chrome().setWindowFeatures(features);

    // 'x' and 'y' specify the location of the window, while 'width' and 'height'
    // specify the size of the viewport. We can only resize the window, so adjust
    // for the difference between the window size and the viewport size.

    FloatRect windowRect = host->chrome().windowRect();
    FloatSize viewportSize = host->chrome().pageRect().size();

    if (features.xSet)
        windowRect.setX(features.x);
    if (features.ySet)
        windowRect.setY(features.y);
    if (features.widthSet)
        windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
    if (features.heightSet)
        windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));

    // Ensure non-NaN values, minimum size as well as being within valid screen area.
    FloatRect newWindowRect = LocalDOMWindow::adjustWindowRect(frame, windowRect);

    host->chrome().setWindowRect(newWindowRect);
    host->chrome().show(policy);

    created = true;
    return &frame;
}

LocalFrame* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
    LocalDOMWindow& callingWindow, LocalFrame& firstFrame, LocalFrame& openerFrame, LocalDOMWindow::PrepareDialogFunction function, void* functionContext)
{
    LocalFrame* activeFrame = callingWindow.frame();
    ASSERT(activeFrame);

    KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, emptyString()) : firstFrame.document()->completeURL(urlString);
    if (!completedURL.isEmpty() && !completedURL.isValid()) {
        // Don't expose client code to invalid URLs.
        callingWindow.printErrorMessage("Unable to open a window with invalid URL '" + completedURL.string() + "'.\n");
        return nullptr;
    }

    FrameLoadRequest frameRequest(callingWindow.document(), completedURL, frameName);

    // Normally, FrameLoader would take care of setting the referrer for a navigation that is
    // triggered from javascript. However, creating a window goes through sufficient processing
    // that it eventually enters FrameLoader as an embedder-initiated navigation. FrameLoader
    // assumes no responsibility for generating an embedder-initiated navigation's referrer,
    // so we need to ensure the proper referrer is set now.
    frameRequest.resourceRequest().setHTTPReferrer(SecurityPolicy::generateReferrer(activeFrame->document()->referrerPolicy(), completedURL, activeFrame->document()->outgoingReferrer()));

    // We pass the opener frame for the lookupFrame in case the active frame is different from
    // the opener frame, and the name references a frame relative to the opener frame.
    bool created;
    LocalFrame* newFrame = createWindow(*activeFrame, openerFrame, frameRequest, windowFeatures, NavigationPolicyIgnore, MaybeSendReferrer, created);
    if (!newFrame)
        return nullptr;

    if (newFrame != &openerFrame && newFrame != openerFrame.tree().top())
        newFrame->loader().forceSandboxFlags(openerFrame.document()->sandboxFlags());

    newFrame->loader().setOpener(&openerFrame);

    if (newFrame->localDOMWindow()->isInsecureScriptAccess(callingWindow, completedURL))
        return newFrame;

    if (function)
        function(newFrame->localDOMWindow(), functionContext);

    if (created)
        newFrame->loader().load(FrameLoadRequest(callingWindow.document(), completedURL));
    else if (!urlString.isEmpty())
        newFrame->navigationScheduler().scheduleLocationChange(callingWindow.document(), completedURL.string(), false);
    return newFrame;
}

void createWindowForRequest(const FrameLoadRequest& request, LocalFrame& openerFrame, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer)
{
    if (openerFrame.document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
        return;

    if (openerFrame.document() && openerFrame.document()->isSandboxed(SandboxPopups))
        return;

    if (!LocalDOMWindow::allowPopUp(openerFrame))
        return;

    if (policy == NavigationPolicyCurrentTab)
        policy = NavigationPolicyNewForegroundTab;

    WindowFeatures features;
    bool created;
    LocalFrame* newFrame = createWindow(openerFrame, openerFrame, request, features, policy, shouldSendReferrer, created);
    if (!newFrame)
        return;
    if (shouldSendReferrer == MaybeSendReferrer) {
        newFrame->loader().setOpener(&openerFrame);
        newFrame->document()->setReferrerPolicy(openerFrame.document()->referrerPolicy());
    }
    FrameLoadRequest newRequest(0, request.resourceRequest());
    newRequest.setFormState(request.formState());
    newFrame->loader().load(newRequest);
}

} // namespace blink
<commit_msg>Fix a weird focus bug<commit_after>/*
 * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/page/CreateWindow.h"

#include "core/dom/Document.h"
#include "core/frame/FrameHost.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
#include "core/page/WindowFeatures.h"
#include "platform/network/ResourceRequest.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "platform/weborigin/SecurityPolicy.h"

namespace blink {

static LocalFrame* createWindow(LocalFrame& openerFrame, LocalFrame& lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer, bool& created)
{
    ASSERT(!features.dialog || request.frameName().isEmpty());

    if (!request.frameName().isEmpty() && request.frameName() != "_blank" && policy == NavigationPolicyIgnore) {
        if (LocalFrame* frame = lookupFrame.loader().findFrameForNavigation(request.frameName(), openerFrame.document())) {
            if (request.frameName() != "_self") {
                if (FrameHost* host = frame->host()) {
                    if (host == openerFrame.host())
                        frame->page()->focusController().setFocusedFrame(frame);
                    else
                        host->chrome().focus();
                }
            }
            created = false;
            return frame;
        }
    }

    // Sandboxed frames cannot open new auxiliary browsing contexts.
    if (openerFrame.document()->isSandboxed(SandboxPopups)) {
        // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
        openerFrame.document()->addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Blocked opening '" + request.resourceRequest().url().elidedString() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set."));
        return nullptr;
    }

    if (openerFrame.settings() && !openerFrame.settings()->supportsMultipleWindows()) {
        created = false;
        if (!openerFrame.tree().top()->isLocalFrame())
            return nullptr;
        return toLocalFrame(openerFrame.tree().top());
    }

    Page* oldPage = openerFrame.page();
    if (!oldPage)
        return nullptr;

    Page* page = oldPage->chrome().client().createWindow(&openerFrame, request, features, policy, shouldSendReferrer);
    if (!page || !page->mainFrame()->isLocalFrame())
        return nullptr;
    FrameHost* host = &page->frameHost();

    ASSERT(page->mainFrame());
    LocalFrame& frame = *page->deprecatedLocalMainFrame();

    if (request.frameName() != "_blank")
        frame.tree().setName(request.frameName());

    host->chrome().setWindowFeatures(features);

    // 'x' and 'y' specify the location of the window, while 'width' and 'height'
    // specify the size of the viewport. We can only resize the window, so adjust
    // for the difference between the window size and the viewport size.

    FloatRect windowRect = host->chrome().windowRect();
    FloatSize viewportSize = host->chrome().pageRect().size();

    if (features.xSet)
        windowRect.setX(features.x);
    if (features.ySet)
        windowRect.setY(features.y);
    if (features.widthSet)
        windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
    if (features.heightSet)
        windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));

    // Ensure non-NaN values, minimum size as well as being within valid screen area.
    FloatRect newWindowRect = LocalDOMWindow::adjustWindowRect(frame, windowRect);

    host->chrome().setWindowRect(newWindowRect);
    host->chrome().show(policy);

    created = true;
    return &frame;
}

LocalFrame* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
    LocalDOMWindow& callingWindow, LocalFrame& firstFrame, LocalFrame& openerFrame, LocalDOMWindow::PrepareDialogFunction function, void* functionContext)
{
    LocalFrame* activeFrame = callingWindow.frame();
    ASSERT(activeFrame);

    KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, emptyString()) : firstFrame.document()->completeURL(urlString);
    if (!completedURL.isEmpty() && !completedURL.isValid()) {
        // Don't expose client code to invalid URLs.
        callingWindow.printErrorMessage("Unable to open a window with invalid URL '" + completedURL.string() + "'.\n");
        return nullptr;
    }

    FrameLoadRequest frameRequest(callingWindow.document(), completedURL, frameName);

    // Normally, FrameLoader would take care of setting the referrer for a navigation that is
    // triggered from javascript. However, creating a window goes through sufficient processing
    // that it eventually enters FrameLoader as an embedder-initiated navigation. FrameLoader
    // assumes no responsibility for generating an embedder-initiated navigation's referrer,
    // so we need to ensure the proper referrer is set now.
    frameRequest.resourceRequest().setHTTPReferrer(SecurityPolicy::generateReferrer(activeFrame->document()->referrerPolicy(), completedURL, activeFrame->document()->outgoingReferrer()));

    // We pass the opener frame for the lookupFrame in case the active frame is different from
    // the opener frame, and the name references a frame relative to the opener frame.
    bool created;
    LocalFrame* newFrame = createWindow(*activeFrame, openerFrame, frameRequest, windowFeatures, NavigationPolicyIgnore, MaybeSendReferrer, created);
    if (!newFrame)
        return nullptr;

    if (newFrame != &openerFrame && newFrame != openerFrame.tree().top())
        newFrame->loader().forceSandboxFlags(openerFrame.document()->sandboxFlags());

    newFrame->loader().setOpener(&openerFrame);

    if (newFrame->localDOMWindow()->isInsecureScriptAccess(callingWindow, completedURL))
        return newFrame;

    if (function)
        function(newFrame->localDOMWindow(), functionContext);

    if (created)
        newFrame->loader().load(FrameLoadRequest(callingWindow.document(), completedURL));
    else if (!urlString.isEmpty())
        newFrame->navigationScheduler().scheduleLocationChange(callingWindow.document(), completedURL.string(), false);
    return newFrame;
}

void createWindowForRequest(const FrameLoadRequest& request, LocalFrame& openerFrame, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer)
{
    if (openerFrame.document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
        return;

    if (openerFrame.document() && openerFrame.document()->isSandboxed(SandboxPopups))
        return;

    if (!LocalDOMWindow::allowPopUp(openerFrame))
        return;

    if (policy == NavigationPolicyCurrentTab)
        policy = NavigationPolicyNewForegroundTab;

    WindowFeatures features;
    bool created;
    LocalFrame* newFrame = createWindow(openerFrame, openerFrame, request, features, policy, shouldSendReferrer, created);
    if (!newFrame)
        return;
    if (shouldSendReferrer == MaybeSendReferrer) {
        newFrame->loader().setOpener(&openerFrame);
        newFrame->document()->setReferrerPolicy(openerFrame.document()->referrerPolicy());
    }
    FrameLoadRequest newRequest(0, request.resourceRequest());
    newRequest.setFormState(request.formState());
    newFrame->loader().load(newRequest);
}

} // namespace blink
<|endoftext|>


<commit_before>#include <cstdio>
#include <fstream>

#include <SFML/Window/Event.hpp>

#include "inputcatcher.h"
#include "datastructures.h"
#include "renderer.h"
#include "networking/clientnetworker.h"
#include "ingameelements/character.h"
#include "global_constants.h"
#include "global.h"

InputCatcher::InputCatcher()
{
    std::ifstream configfile("config.json");
    config << configfile;
    configfile.close();
}

InputCatcher::~InputCatcher()
{

}

void InputCatcher::run(sf::RenderWindow &window, Gamestate &state, Networker &networker, Renderer &renderer,
                       EntityPtr myself)
{
    InputContainer heldkeys;
    heldkeys.reset();

    Player &player = state.get<Player>(myself);

    sf::Event event;
    // Go through all events that have been stacking up since last time
    while (window.pollEvent(event))
    {
        // FIXME: This newclass thing is an ugly placeholder,
        // when you replace it with a real class menu don't do it like this
        Heroclass newclass = player.heroclass;
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
                break;

            case sf::Event::Resized:
                renderer.WINDOW_WIDTH = event.size.width;
                renderer.WINDOW_HEIGHT = event.size.height;
                renderer.resetcamera();
                break;

            case sf::Event::KeyPressed:
                switch (event.key.code)
                {
                    case sf::Keyboard::Escape:
                        window.close();
                        break;

                    case sf::Keyboard::F9:
                        // Zooming in for sprite analysis purposes
                        if (renderer.VIEWPORT_WIDTH != 960)
                        {
                            renderer.VIEWPORT_WIDTH = 960;
                        }
                        else
                        {
                            renderer.VIEWPORT_WIDTH = 300;
                        }
                        renderer.resetcamera();

                    case sf::Keyboard::Num1:
                        newclass = MCCREE;
                        break;

                    case sf::Keyboard::Num2:
                        newclass = REINHARDT;
                        break;

                    case sf::Keyboard::Num3:
                        newclass = LUCIO;
                        break;

                    default:
                        break;
                }
                if (newclass != player.heroclass)
                {
                    // Player desires a class change
                    if (state.engine.isserver)
                    {
                        player.changeclass(state, newclass);
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(state.findplayerid(player.id));
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                    else
                    {
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                }
                break;

            default:
                // Ignore other events
                break;
        }
    }

    if (sf::Keyboard::isKeyPressed(config.at("jump")) or sf::Keyboard::isKeyPressed(config.at("jump_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("jump")))
    {
        heldkeys.JUMP = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("crouch")) or sf::Keyboard::isKeyPressed(config.at("crouch_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("crouch")))
    {
        heldkeys.CROUCH = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("left")) or sf::Keyboard::isKeyPressed(config.at("left_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("left")))
    {
        heldkeys.LEFT = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("right")) or sf::Keyboard::isKeyPressed(config.at("right_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("right")))
    {
        heldkeys.RIGHT = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("ability1")) or sf::Keyboard::isKeyPressed(config.at("ability1_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("ability1")))
    {
        heldkeys.ABILITY_1 = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("ability2")) or sf::Keyboard::isKeyPressed(config.at("ability2_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("ability2")))
    {
        heldkeys.ABILITY_2 = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("ultimate")) or sf::Keyboard::isKeyPressed(config.at("ultimate_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("ultimate")))
    {
        heldkeys.ULTIMATE = true;
    }
    if (sf::Keyboard::isKeyPressed(config.at("reload")) or sf::Keyboard::isKeyPressed(config.at("reload_alt1"))
        or sf::Keyboard::isKeyPressed(config.at("reload")))
    {
        heldkeys.RELOAD = true;
    }

    if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        heldkeys.PRIMARY_FIRE = true;
    }
    if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
    {
        heldkeys.SECONDARY_FIRE = true;
    }

    if (state.exists(player.character))
    {
        Character &c = player.getcharacter(state);

        sf::Vector2f mousepos = window.mapPixelToCoords(sf::Mouse::getPosition(window));

        // Set the input for our current character
        c.setinput(state, heldkeys, mousepos.x, mousepos.y);

        // If this is a client, send the input off to the server
        if (not state.engine.isserver)
        {
            ClientNetworker &n = reinterpret_cast<ClientNetworker&>(networker);
            n.sendinput(heldkeys, mousepos.x, mousepos.y);
        }
    }
}
<commit_msg>Added cast in input gathering.<commit_after>#include <cstdio>
#include <fstream>

#include <SFML/Window/Event.hpp>

#include "inputcatcher.h"
#include "datastructures.h"
#include "renderer.h"
#include "networking/clientnetworker.h"
#include "ingameelements/character.h"
#include "global_constants.h"
#include "global.h"

InputCatcher::InputCatcher()
{
    std::ifstream configfile("config.json");
    config << configfile;
    configfile.close();
}

InputCatcher::~InputCatcher()
{

}

void InputCatcher::run(sf::RenderWindow &window, Gamestate &state, Networker &networker, Renderer &renderer,
                       EntityPtr myself)
{
    InputContainer heldkeys;
    heldkeys.reset();

    Player &player = state.get<Player>(myself);

    sf::Event event;
    // Go through all events that have been stacking up since last time
    while (window.pollEvent(event))
    {
        // FIXME: This newclass thing is an ugly placeholder,
        // when you replace it with a real class menu don't do it like this
        Heroclass newclass = player.heroclass;
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
                break;

            case sf::Event::Resized:
                renderer.WINDOW_WIDTH = event.size.width;
                renderer.WINDOW_HEIGHT = event.size.height;
                renderer.resetcamera();
                break;

            case sf::Event::KeyPressed:
                switch (event.key.code)
                {
                    case sf::Keyboard::Escape:
                        window.close();
                        break;

                    case sf::Keyboard::F9:
                        // Zooming in for sprite analysis purposes
                        if (renderer.VIEWPORT_WIDTH != 960)
                        {
                            renderer.VIEWPORT_WIDTH = 960;
                        }
                        else
                        {
                            renderer.VIEWPORT_WIDTH = 300;
                        }
                        renderer.resetcamera();

                    case sf::Keyboard::Num1:
                        newclass = MCCREE;
                        break;

                    case sf::Keyboard::Num2:
                        newclass = REINHARDT;
                        break;

                    case sf::Keyboard::Num3:
                        newclass = LUCIO;
                        break;

                    default:
                        break;
                }
                if (newclass != player.heroclass)
                {
                    // Player desires a class change
                    if (state.engine.isserver)
                    {
                        player.changeclass(state, newclass);
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(state.findplayerid(player.id));
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                    else
                    {
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                }
                break;

            default:
                // Ignore other events
                break;
        }
    }

    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("jump")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("jump_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("jump_alt2"))))
    {
        heldkeys.JUMP = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("crouch")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("crouch_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("crouch_alt2"))))
    {
        heldkeys.CROUCH = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("left")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("left_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("left_alt2"))))
    {
        heldkeys.LEFT = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("right")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("right_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("right_alt2"))))
    {
        heldkeys.RIGHT = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ability1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ability1_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ability1_alt2"))))
    {
        heldkeys.ABILITY_1 = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ability2")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ability2_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ability2_alt2"))))
    {
        heldkeys.ABILITY_2 = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ultimate")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ultimate_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("ultimate_alt2"))))
    {
        heldkeys.ULTIMATE = true;
    }
    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("reload")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("reload_alt1")))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(config.at("reload_alt2"))))
    {
        heldkeys.RELOAD = true;
    }

    if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        heldkeys.PRIMARY_FIRE = true;
    }
    if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
    {
        heldkeys.SECONDARY_FIRE = true;
    }

    if (state.exists(player.character))
    {
        Character &c = player.getcharacter(state);

        sf::Vector2f mousepos = window.mapPixelToCoords(sf::Mouse::getPosition(window));

        // Set the input for our current character
        c.setinput(state, heldkeys, mousepos.x, mousepos.y);

        // If this is a client, send the input off to the server
        if (not state.engine.isserver)
        {
            ClientNetworker &n = reinterpret_cast<ClientNetworker&>(networker);
            n.sendinput(heldkeys, mousepos.x, mousepos.y);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * LayerData.hpp
 *
 *  Created on: Jan 31, 2011
 *      Author: manghel
 */

#ifndef LAYERDATA_HPP_
#define LAYERDATA_HPP_

#include "LayerProbe.hpp"
#include "../columns/HyPerCol.hpp"
#include "../include/pv_types.h"
#include "../io/fileio.hpp"
#include <assert.h>

enum DataType{
   VTH = 0;

};
namespace PV {

class LayerData: public LayerProbe {
public:
   LayerData(const char * filename, HyPerCol * hc, HyPerLayer * l, pvdata_t * data, bool append);

   virtual int outputState(float time, HyPerLayer * l) = 0;

protected:
   HyPerCol * parent;
   const pvdata_t * data;
   bool  append;

};

}

#endif /* LAYERDATA_HPP_ */
<commit_msg>Removed DataType (at least temporarily).  There is another enum that already has this information (or should have) in it.<commit_after>/*
 * LayerData.hpp
 *
 *  Created on: Jan 31, 2011
 *      Author: manghel
 */

#ifndef LAYERDATA_HPP_
#define LAYERDATA_HPP_

#include "LayerProbe.hpp"
#include "../columns/HyPerCol.hpp"
#include "../include/pv_types.h"
#include "../io/fileio.hpp"
#include <assert.h>

namespace PV {

class LayerData: public LayerProbe {
public:
   LayerData(const char * filename, HyPerCol * hc, HyPerLayer * l, pvdata_t * data, bool append);

   virtual int outputState(float time, HyPerLayer * l) = 0;

protected:
   HyPerCol * parent;
   const pvdata_t * data;
   bool  append;

};

}

#endif /* LAYERDATA_HPP_ */
<|endoftext|>


<commit_before>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2005-2006 Refractions Research Inc.
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: io/WKTReader.java rev. 1.1 (JTS-1.7)
 *
 **********************************************************************/

#include <geos/io/WKTReader.h>
#include <geos/io/StringTokenizer.h>
#include <geos/io/ParseException.h>
#include <geos/io/CLocalizer.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Point.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequence.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/inline.h>
#include <geos/util.h>

#include <sstream>
#include <string>
#include <cassert>

#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif

#ifdef GEOS_DEBUG
#include <iostream>
#endif

#ifndef GEOS_INLINE
#include <geos/io/WKTReader.inl>
#endif

using namespace std;
using namespace geos::geom;

namespace geos {
namespace io { // geos.io

std::unique_ptr<Geometry>
WKTReader::read(const string& wellKnownText)
{
    CLocalizer clocale;
    StringTokenizer tokenizer(wellKnownText);
    return readGeometryTaggedText(&tokenizer);
}

std::unique_ptr<CoordinateSequence>
WKTReader::getCoordinates(StringTokenizer* tokenizer)
{
    size_t dim;
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->getCoordinateSequenceFactory()->create();
    }

    Coordinate coord;
    getPreciseCoordinate(tokenizer, coord, dim);

    auto coordinates = detail::make_unique<CoordinateArraySequence>(0, dim);
    coordinates->add(coord);

    nextToken = getNextCloserOrComma(tokenizer);
    while(nextToken == ",") {
        getPreciseCoordinate(tokenizer, coord, dim);
        coordinates->add(coord);
        nextToken = getNextCloserOrComma(tokenizer);
    }

    return std::move(coordinates);
}

void
WKTReader::getPreciseCoordinate(StringTokenizer* tokenizer,
                                Coordinate& coord,
                                size_t& dim)
{
    coord.x = getNextNumber(tokenizer);
    coord.y = getNextNumber(tokenizer);
    if(isNumberNext(tokenizer)) {
        coord.z = getNextNumber(tokenizer);
        dim = 3;

        // If there is a fourth value (M) read and discard it.
        if(isNumberNext(tokenizer)) {
            getNextNumber(tokenizer);
        }

    }
    else {
        coord.z = DoubleNotANumber;
        dim = 2;
    }
    precisionModel->makePrecise(coord);
}

bool
WKTReader::isNumberNext(StringTokenizer* tokenizer)
{
    return tokenizer->peekNextToken() == StringTokenizer::TT_NUMBER;
}

double
WKTReader::getNextNumber(StringTokenizer* tokenizer)
{
    int type = tokenizer->nextToken();
    switch(type) {
    case StringTokenizer::TT_EOF:
        throw  ParseException("Expected number but encountered end of stream");
    case StringTokenizer::TT_EOL:
        throw  ParseException("Expected number but encountered end of line");
    case StringTokenizer::TT_NUMBER:
        return tokenizer->getNVal();
    case StringTokenizer::TT_WORD:
        throw  ParseException("Expected number but encountered word", tokenizer->getSVal());
    case '(':
        throw  ParseException("Expected number but encountered '('");
    case ')':
        throw  ParseException("Expected number but encountered ')'");
    case ',':
        throw  ParseException("Expected number but encountered ','");
    }
    assert(0); // Encountered unexpected StreamTokenizer type
    return 0;
}

string
WKTReader::getNextEmptyOrOpener(StringTokenizer* tokenizer)
{
    string nextWord = getNextWord(tokenizer);

    // Skip the Z, M or ZM of an SF1.2 3/4 dim coordinate.
    if(nextWord == "Z" || nextWord == "M" || nextWord == "ZM") {
        nextWord = getNextWord(tokenizer);
    }

    if(nextWord == "EMPTY" || nextWord == "(") {
        return nextWord;
    }
    throw  ParseException("Expected 'Z', 'M', 'ZM', 'EMPTY' or '(' but encountered ", nextWord);
}

string
WKTReader::getNextCloserOrComma(StringTokenizer* tokenizer)
{
    string nextWord = getNextWord(tokenizer);
    if(nextWord == "," || nextWord == ")") {
        return nextWord;
    }
    throw  ParseException("Expected ')' or ',' but encountered", nextWord);
}

string
WKTReader::getNextCloser(StringTokenizer* tokenizer)
{
    string nextWord = getNextWord(tokenizer);
    if(nextWord == ")") {
        return nextWord;
    }
    throw  ParseException("Expected ')' but encountered", nextWord);
}

string
WKTReader::getNextWord(StringTokenizer* tokenizer)
{
    int type = tokenizer->nextToken();
    switch(type) {
    case StringTokenizer::TT_EOF:
        throw  ParseException("Expected word but encountered end of stream");
    case StringTokenizer::TT_EOL:
        throw  ParseException("Expected word but encountered end of line");
    case StringTokenizer::TT_NUMBER:
        throw  ParseException("Expected word but encountered number", tokenizer->getNVal());
    case StringTokenizer::TT_WORD: {
        string word = tokenizer->getSVal();
        int i = static_cast<int>(word.size());

        while(--i >= 0) {
            word[i] = static_cast<char>(toupper(word[i]));
        }
        return word;
    }
    case '(':
        return "(";
    case ')':
        return ")";
    case ',':
        return ",";
    }
    assert(0);
    //throw  ParseException("Encountered unexpected StreamTokenizer type");
    return "";
}

std::unique_ptr<Geometry>
WKTReader::readGeometryTaggedText(StringTokenizer* tokenizer)
{
    string type = getNextWord(tokenizer);
    if(type == "POINT") {
        return readPointText(tokenizer);
    }
    else if(type == "LINESTRING") {
        return readLineStringText(tokenizer);
    }
    else if(type == "LINEARRING") {
        return readLinearRingText(tokenizer);
    }
    else if(type == "POLYGON") {
        return readPolygonText(tokenizer);
    }
    else if(type == "MULTIPOINT") {
        return readMultiPointText(tokenizer);
    }
    else if(type == "MULTILINESTRING") {
        return readMultiLineStringText(tokenizer);
    }
    else if(type == "MULTIPOLYGON") {
        return readMultiPolygonText(tokenizer);
    }
    else if(type == "GEOMETRYCOLLECTION") {
        return readGeometryCollectionText(tokenizer);
    }
    throw ParseException("Unknown type", type);
}

std::unique_ptr<Point>
WKTReader::readPointText(StringTokenizer* tokenizer)
{
    size_t dim;
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createPoint();
    }

    Coordinate coord;
    getPreciseCoordinate(tokenizer, coord, dim);
    getNextCloser(tokenizer);

    return std::unique_ptr<Point>(geometryFactory->createPoint(coord));
}

std::unique_ptr<LineString>
WKTReader::readLineStringText(StringTokenizer* tokenizer)
{
    auto&& coords = getCoordinates(tokenizer);
    return geometryFactory->createLineString(std::move(coords));
}

std::unique_ptr<LinearRing>
WKTReader::readLinearRingText(StringTokenizer* tokenizer)
{
    auto&& coords = getCoordinates(tokenizer);
    return geometryFactory->createLinearRing(std::move(coords));
}

std::unique_ptr<MultiPoint>
WKTReader::readMultiPointText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createMultiPoint();
    }

    int tok = tokenizer->peekNextToken();

    if(tok == StringTokenizer::TT_NUMBER) {
        size_t dim;

        // Try to parse deprecated form "MULTIPOINT(0 0, 1 1)"
        auto coords = detail::make_unique<CoordinateArraySequence>();

        do {
            Coordinate coord;
            getPreciseCoordinate(tokenizer, coord, dim);
            coords->add(coord);
            nextToken = getNextCloserOrComma(tokenizer);
        }
        while(nextToken == ",");

        return std::unique_ptr<MultiPoint>(geometryFactory->createMultiPoint(*coords));
    }

    else if(tok == '(') {
        // Try to parse correct form "MULTIPOINT((0 0), (1 1))"
        std::vector<std::unique_ptr<Point>> points;

        do {
            points.push_back(readPointText(tokenizer));
            nextToken = getNextCloserOrComma(tokenizer);
        } while(nextToken == ",");

        return geometryFactory->createMultiPoint(std::move(points));
    }

    else {
        stringstream err;
        err << "Unexpected token: ";
        switch(tok) {
        case StringTokenizer::TT_WORD:
            err << "WORD " << tokenizer->getSVal();
            break;
        case StringTokenizer::TT_NUMBER:
            err << "NUMBER " << tokenizer->getNVal();
            break;
        case StringTokenizer::TT_EOF:
        case StringTokenizer::TT_EOL:
            err << "EOF or EOL";
            break;
        case '(':
            err << "(";
            break;
        case ')':
            err << ")";
            break;
        case ',':
            err << ",";
            break;
        default:
            err << "??";
            break;
        }
        err << endl;
        throw ParseException(err.str());
    }
}

std::unique_ptr<Polygon>
WKTReader::readPolygonText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createPolygon();
    }

    std::vector<std::unique_ptr<LinearRing>> holes;
    auto shell = readLinearRingText(tokenizer);
    nextToken = getNextCloserOrComma(tokenizer);
    while(nextToken == ",") {
        holes.push_back(readLinearRingText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    }

    return geometryFactory->createPolygon(std::move(shell), std::move(holes));
}

std::unique_ptr<MultiLineString>
WKTReader::readMultiLineStringText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createMultiLineString();
    }

    std::vector<std::unique_ptr<LineString>> lineStrings;
    do {
        lineStrings.push_back(readLineStringText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    } while (nextToken == ",");

    return geometryFactory->createMultiLineString(std::move(lineStrings));
}

std::unique_ptr<MultiPolygon>
WKTReader::readMultiPolygonText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createMultiPolygon();
    }

    std::vector<std::unique_ptr<Polygon>> polygons;
    do {
        polygons.push_back(readPolygonText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    } while(nextToken == ",");

    return geometryFactory->createMultiPolygon(std::move(polygons));
}

std::unique_ptr<GeometryCollection>
WKTReader::readGeometryCollectionText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createGeometryCollection();
    }

    std::vector<std::unique_ptr<Geometry>> geoms;
    do {
        geoms.push_back(readGeometryTaggedText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    } while(nextToken == ",");

    return geometryFactory->createGeometryCollection(std::move(geoms));
}

} // namespace geos.io
} // namespace geos
<commit_msg>WKTReader::getCoordinates: Remove reduntant move<commit_after>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2005-2006 Refractions Research Inc.
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: io/WKTReader.java rev. 1.1 (JTS-1.7)
 *
 **********************************************************************/

#include <geos/io/WKTReader.h>
#include <geos/io/StringTokenizer.h>
#include <geos/io/ParseException.h>
#include <geos/io/CLocalizer.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Point.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequence.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/inline.h>
#include <geos/util.h>

#include <sstream>
#include <string>
#include <cassert>

#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif

#ifdef GEOS_DEBUG
#include <iostream>
#endif

#ifndef GEOS_INLINE
#include <geos/io/WKTReader.inl>
#endif

using namespace std;
using namespace geos::geom;

namespace geos {
namespace io { // geos.io

std::unique_ptr<Geometry>
WKTReader::read(const string& wellKnownText)
{
    CLocalizer clocale;
    StringTokenizer tokenizer(wellKnownText);
    return readGeometryTaggedText(&tokenizer);
}

std::unique_ptr<CoordinateSequence>
WKTReader::getCoordinates(StringTokenizer* tokenizer)
{
    size_t dim;
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->getCoordinateSequenceFactory()->create();
    }

    Coordinate coord;
    getPreciseCoordinate(tokenizer, coord, dim);

    auto coordinates = detail::make_unique<CoordinateArraySequence>(0, dim);
    coordinates->add(coord);

    nextToken = getNextCloserOrComma(tokenizer);
    while(nextToken == ",") {
        getPreciseCoordinate(tokenizer, coord, dim);
        coordinates->add(coord);
        nextToken = getNextCloserOrComma(tokenizer);
    }

    return coordinates;
}

void
WKTReader::getPreciseCoordinate(StringTokenizer* tokenizer,
                                Coordinate& coord,
                                size_t& dim)
{
    coord.x = getNextNumber(tokenizer);
    coord.y = getNextNumber(tokenizer);
    if(isNumberNext(tokenizer)) {
        coord.z = getNextNumber(tokenizer);
        dim = 3;

        // If there is a fourth value (M) read and discard it.
        if(isNumberNext(tokenizer)) {
            getNextNumber(tokenizer);
        }

    }
    else {
        coord.z = DoubleNotANumber;
        dim = 2;
    }
    precisionModel->makePrecise(coord);
}

bool
WKTReader::isNumberNext(StringTokenizer* tokenizer)
{
    return tokenizer->peekNextToken() == StringTokenizer::TT_NUMBER;
}

double
WKTReader::getNextNumber(StringTokenizer* tokenizer)
{
    int type = tokenizer->nextToken();
    switch(type) {
    case StringTokenizer::TT_EOF:
        throw  ParseException("Expected number but encountered end of stream");
    case StringTokenizer::TT_EOL:
        throw  ParseException("Expected number but encountered end of line");
    case StringTokenizer::TT_NUMBER:
        return tokenizer->getNVal();
    case StringTokenizer::TT_WORD:
        throw  ParseException("Expected number but encountered word", tokenizer->getSVal());
    case '(':
        throw  ParseException("Expected number but encountered '('");
    case ')':
        throw  ParseException("Expected number but encountered ')'");
    case ',':
        throw  ParseException("Expected number but encountered ','");
    }
    assert(0); // Encountered unexpected StreamTokenizer type
    return 0;
}

string
WKTReader::getNextEmptyOrOpener(StringTokenizer* tokenizer)
{
    string nextWord = getNextWord(tokenizer);

    // Skip the Z, M or ZM of an SF1.2 3/4 dim coordinate.
    if(nextWord == "Z" || nextWord == "M" || nextWord == "ZM") {
        nextWord = getNextWord(tokenizer);
    }

    if(nextWord == "EMPTY" || nextWord == "(") {
        return nextWord;
    }
    throw  ParseException("Expected 'Z', 'M', 'ZM', 'EMPTY' or '(' but encountered ", nextWord);
}

string
WKTReader::getNextCloserOrComma(StringTokenizer* tokenizer)
{
    string nextWord = getNextWord(tokenizer);
    if(nextWord == "," || nextWord == ")") {
        return nextWord;
    }
    throw  ParseException("Expected ')' or ',' but encountered", nextWord);
}

string
WKTReader::getNextCloser(StringTokenizer* tokenizer)
{
    string nextWord = getNextWord(tokenizer);
    if(nextWord == ")") {
        return nextWord;
    }
    throw  ParseException("Expected ')' but encountered", nextWord);
}

string
WKTReader::getNextWord(StringTokenizer* tokenizer)
{
    int type = tokenizer->nextToken();
    switch(type) {
    case StringTokenizer::TT_EOF:
        throw  ParseException("Expected word but encountered end of stream");
    case StringTokenizer::TT_EOL:
        throw  ParseException("Expected word but encountered end of line");
    case StringTokenizer::TT_NUMBER:
        throw  ParseException("Expected word but encountered number", tokenizer->getNVal());
    case StringTokenizer::TT_WORD: {
        string word = tokenizer->getSVal();
        int i = static_cast<int>(word.size());

        while(--i >= 0) {
            word[i] = static_cast<char>(toupper(word[i]));
        }
        return word;
    }
    case '(':
        return "(";
    case ')':
        return ")";
    case ',':
        return ",";
    }
    assert(0);
    //throw  ParseException("Encountered unexpected StreamTokenizer type");
    return "";
}

std::unique_ptr<Geometry>
WKTReader::readGeometryTaggedText(StringTokenizer* tokenizer)
{
    string type = getNextWord(tokenizer);
    if(type == "POINT") {
        return readPointText(tokenizer);
    }
    else if(type == "LINESTRING") {
        return readLineStringText(tokenizer);
    }
    else if(type == "LINEARRING") {
        return readLinearRingText(tokenizer);
    }
    else if(type == "POLYGON") {
        return readPolygonText(tokenizer);
    }
    else if(type == "MULTIPOINT") {
        return readMultiPointText(tokenizer);
    }
    else if(type == "MULTILINESTRING") {
        return readMultiLineStringText(tokenizer);
    }
    else if(type == "MULTIPOLYGON") {
        return readMultiPolygonText(tokenizer);
    }
    else if(type == "GEOMETRYCOLLECTION") {
        return readGeometryCollectionText(tokenizer);
    }
    throw ParseException("Unknown type", type);
}

std::unique_ptr<Point>
WKTReader::readPointText(StringTokenizer* tokenizer)
{
    size_t dim;
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createPoint();
    }

    Coordinate coord;
    getPreciseCoordinate(tokenizer, coord, dim);
    getNextCloser(tokenizer);

    return std::unique_ptr<Point>(geometryFactory->createPoint(coord));
}

std::unique_ptr<LineString>
WKTReader::readLineStringText(StringTokenizer* tokenizer)
{
    auto&& coords = getCoordinates(tokenizer);
    return geometryFactory->createLineString(std::move(coords));
}

std::unique_ptr<LinearRing>
WKTReader::readLinearRingText(StringTokenizer* tokenizer)
{
    auto&& coords = getCoordinates(tokenizer);
    return geometryFactory->createLinearRing(std::move(coords));
}

std::unique_ptr<MultiPoint>
WKTReader::readMultiPointText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createMultiPoint();
    }

    int tok = tokenizer->peekNextToken();

    if(tok == StringTokenizer::TT_NUMBER) {
        size_t dim;

        // Try to parse deprecated form "MULTIPOINT(0 0, 1 1)"
        auto coords = detail::make_unique<CoordinateArraySequence>();

        do {
            Coordinate coord;
            getPreciseCoordinate(tokenizer, coord, dim);
            coords->add(coord);
            nextToken = getNextCloserOrComma(tokenizer);
        }
        while(nextToken == ",");

        return std::unique_ptr<MultiPoint>(geometryFactory->createMultiPoint(*coords));
    }

    else if(tok == '(') {
        // Try to parse correct form "MULTIPOINT((0 0), (1 1))"
        std::vector<std::unique_ptr<Point>> points;

        do {
            points.push_back(readPointText(tokenizer));
            nextToken = getNextCloserOrComma(tokenizer);
        } while(nextToken == ",");

        return geometryFactory->createMultiPoint(std::move(points));
    }

    else {
        stringstream err;
        err << "Unexpected token: ";
        switch(tok) {
        case StringTokenizer::TT_WORD:
            err << "WORD " << tokenizer->getSVal();
            break;
        case StringTokenizer::TT_NUMBER:
            err << "NUMBER " << tokenizer->getNVal();
            break;
        case StringTokenizer::TT_EOF:
        case StringTokenizer::TT_EOL:
            err << "EOF or EOL";
            break;
        case '(':
            err << "(";
            break;
        case ')':
            err << ")";
            break;
        case ',':
            err << ",";
            break;
        default:
            err << "??";
            break;
        }
        err << endl;
        throw ParseException(err.str());
    }
}

std::unique_ptr<Polygon>
WKTReader::readPolygonText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createPolygon();
    }

    std::vector<std::unique_ptr<LinearRing>> holes;
    auto shell = readLinearRingText(tokenizer);
    nextToken = getNextCloserOrComma(tokenizer);
    while(nextToken == ",") {
        holes.push_back(readLinearRingText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    }

    return geometryFactory->createPolygon(std::move(shell), std::move(holes));
}

std::unique_ptr<MultiLineString>
WKTReader::readMultiLineStringText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createMultiLineString();
    }

    std::vector<std::unique_ptr<LineString>> lineStrings;
    do {
        lineStrings.push_back(readLineStringText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    } while (nextToken == ",");

    return geometryFactory->createMultiLineString(std::move(lineStrings));
}

std::unique_ptr<MultiPolygon>
WKTReader::readMultiPolygonText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createMultiPolygon();
    }

    std::vector<std::unique_ptr<Polygon>> polygons;
    do {
        polygons.push_back(readPolygonText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    } while(nextToken == ",");

    return geometryFactory->createMultiPolygon(std::move(polygons));
}

std::unique_ptr<GeometryCollection>
WKTReader::readGeometryCollectionText(StringTokenizer* tokenizer)
{
    string nextToken = getNextEmptyOrOpener(tokenizer);
    if(nextToken == "EMPTY") {
        return geometryFactory->createGeometryCollection();
    }

    std::vector<std::unique_ptr<Geometry>> geoms;
    do {
        geoms.push_back(readGeometryTaggedText(tokenizer));
        nextToken = getNextCloserOrComma(tokenizer);
    } while(nextToken == ",");

    return geometryFactory->createGeometryCollection(std::move(geoms));
}

} // namespace geos.io
} // namespace geos
<|endoftext|>


<commit_before>/*
 *  caosVM_compound.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Mon May 31 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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.
 *
 */

#include "caosVM.h"
#include "CompoundAgent.h"
#include "openc2e.h"

/**
 PART (command) part_id (integer)

 set the part number of the TARGed compound agent/vehicle to work on (ANIM/POSE use this, amongst other commands).
*/
void caosVM::c_PART() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(part_id)

	caos_assert(part_id >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);
	caos_assert(a->part(part_id));
	part = part_id;
}

/**
 PART (integer) part_id (integer)

 return 1 if the given part number exists on the target agent, or 0 otherwise.
*/
void caosVM::v_PART() {
	VM_PARAM_INTEGER(part_id)

	caos_assert(part_id >= 0); // TODO: should we do this?
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);
	if (a->part(part_id))
		result.setInt(1);
	else
		result.setInt(0);
}

/**
 PAT: DULL (command) part (integer) sprite (string) first_image (integer) x (integer) y (integer) plane (integer)

 create a new 'dull' part for the TARGed compound agent/vehicle which does nothing but display an image.
 number part ids beginning at 1. x/y/plane are relative to the agent you're working on.
*/
void caosVM::c_PAT_DULL() {
	VM_VERIFY_SIZE(6)
	VM_PARAM_INTEGER(plane)
	VM_PARAM_INTEGER(y)
	VM_PARAM_INTEGER(x)
	VM_PARAM_INTEGER(first_image)
	VM_PARAM_STRING(sprite)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	CompoundPart *p = new DullPart(part, sprite, first_image, x, y, plane);
	a->addPart(p);
}

/**
 PAT: BUTT (command) part (integer) sprite (string) first_image (integer) image_count (integer) x (integer) y (integer) plane (integer) hoveranim (byte-string) messageid (integer) option (integer)

 creates a new 'button' part for the TARGed compound agent/vehicle
 number part ids beginning at 1. x/y/plane are relative to the agent you're working on.
 hoveranim is the animation to use when the part is mouseovered - see ANIM for details
 messageid is the message sent when the button is clicked - _p1_ of the message is set to the part number
 if option is 1, mouseclicks/hovers only apply to non-transparent areas. otherwise, option should be 0.
*/
void caosVM::c_PAT_BUTT() {
	VM_VERIFY_SIZE(10)
	VM_PARAM_INTEGER(option)
	VM_PARAM_INTEGER(messageid)
	VM_PARAM_BYTESTR(hoveranim)
	VM_PARAM_INTEGER(plane)
	VM_PARAM_INTEGER(y)
	VM_PARAM_INTEGER(x)
	VM_PARAM_INTEGER(image_count)
	VM_PARAM_INTEGER(first_image)
	VM_PARAM_STRING(sprite)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert((option == 0) || (option == 1));
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	// TODO TODO TODO we don't take image_count!!
	CompoundPart *p = new ButtonPart(part, sprite, first_image, x, y, plane, hoveranim, messageid, option);
	a->addPart(p);
}

/**
 PAT: FIXD (command) part (integer) sprite (string) first_image (integer) image_count (integer) x (integer) y (integer) plane (integer) fontsprite (string)
 %status maybe
*/
void caosVM::c_PAT_FIXD() {
	VM_PARAM_STRING(fontsprite)
	VM_PARAM_INTEGER(plane)
	VM_PARAM_INTEGER(y)
	VM_PARAM_INTEGER(x)
	VM_PARAM_INTEGER(image_count)
	VM_PARAM_INTEGER(first_image)
	VM_PARAM_STRING(sprite)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	// TODO TODO TODO we don't take image_count!!
	CompoundPart *p = new FixedTextPart(part, sprite, first_image, x, y, plane, fontsprite);
	a->addPart(p);
}

/**
 PAT: KILL (command) part (integer)

 kill the specified part of the TARGed compound agent/vehicle
*/
void caosVM::c_PAT_KILL() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	a->delPart(part);
}

/**
 FCUS (command)

 focus current targeted part, which must be a PAT: TEXT
 if target is null, then unfocus current part
*/
void caosVM::c_FCUS() {
	VM_VERIFY_SIZE(0)

	if (!targ) {
		// TODO
	} else {
		CompoundAgent *c = dynamic_cast<CompoundAgent *>(targ.get());
		caos_assert(c);
		TextEntryPart *p = dynamic_cast<TextEntryPart *>(c->part(part));
		caos_assert(p);
		// TODO
	}
}

/**
 FRMT (command) left_margin (integer) top_margin (integer) right_margin (integer) button_margin (integer) line_spacing (integer) char_spacing (integer) justification (integer)
 %status stub

 alters the appearance of the target text part. the spacing values and margins are to be specified in pixels. justification can be 0 for left, 1 for right, 2 for center, 4 for bottom, 8 for middle or 16 for 'last page scroll' (TODO?), and you can add these together (except 0/1 are mutually exclusive, obviously).
*/
void caosVM::c_FRMT() {
	VM_PARAM_INTEGER(justification)
	VM_PARAM_INTEGER(char_spacing)
	VM_PARAM_INTEGER(line_spacing)
	VM_PARAM_INTEGER(bottom_margin)
	VM_PARAM_INTEGER(right_margin)
	VM_PARAM_INTEGER(top_margin)
	VM_PARAM_INTEGER(left_margin)

	caos_assert(targ);
	CompoundAgent *c = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(c);
	/*TextPart *p = dynamic_cast<TextPart *>(c->part(part));
	caos_assert(p);*/

	// TODO
}

/**
 PTXT (command) text (string)
 %status stub

 sets the text of the current text part
*/
void caosVM::c_PTXT() {
	VM_PARAM_STRING(text)

	caos_assert(targ);
	CompoundAgent *c = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(c);
	/*TextPart *p = dynamic_cast<TextPart *>(c->part(part));
	caos_assert(p);*/

	// TODO
}

/*
 PTXT (string)
 %status stub

 returns the text of the current text part
*/
void caosVM::v_PTXT() {
	result.setString(""); // TODO
}

/* vim: set noet: */
<commit_msg>sigh.<commit_after>/*
 *  caosVM_compound.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Mon May 31 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  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.
 *
 */

#include "caosVM.h"
#include "CompoundAgent.h"
#include "openc2e.h"

/**
 PART (command) part_id (integer)

 set the part number of the TARGed compound agent/vehicle to work on (ANIM/POSE use this, amongst other commands).
*/
void caosVM::c_PART() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(part_id)

	caos_assert(part_id >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);
	caos_assert(a->part(part_id));
	part = part_id;
}

/**
 PART (integer) part_id (integer)

 return 1 if the given part number exists on the target agent, or 0 otherwise.
*/
void caosVM::v_PART() {
	VM_PARAM_INTEGER(part_id)

	caos_assert(part_id >= 0); // TODO: should we do this?
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);
	if (a->part(part_id))
		result.setInt(1);
	else
		result.setInt(0);
}

/**
 PAT: DULL (command) part (integer) sprite (string) first_image (integer) x (integer) y (integer) plane (integer)

 create a new 'dull' part for the TARGed compound agent/vehicle which does nothing but display an image.
 number part ids beginning at 1. x/y/plane are relative to the agent you're working on.
*/
void caosVM::c_PAT_DULL() {
	VM_VERIFY_SIZE(6)
	VM_PARAM_INTEGER(plane)
	VM_PARAM_INTEGER(y)
	VM_PARAM_INTEGER(x)
	VM_PARAM_INTEGER(first_image)
	VM_PARAM_STRING(sprite)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	CompoundPart *p = new DullPart(part, sprite, first_image, x, y, plane);
	a->addPart(p);
}

/**
 PAT: BUTT (command) part (integer) sprite (string) first_image (integer) image_count (integer) x (integer) y (integer) plane (integer) hoveranim (byte-string) messageid (integer) option (integer)

 creates a new 'button' part for the TARGed compound agent/vehicle
 number part ids beginning at 1. x/y/plane are relative to the agent you're working on.
 hoveranim is the animation to use when the part is mouseovered - see ANIM for details
 messageid is the message sent when the button is clicked - _p1_ of the message is set to the part number
 if option is 1, mouseclicks/hovers only apply to non-transparent areas. otherwise, option should be 0.
*/
void caosVM::c_PAT_BUTT() {
	VM_VERIFY_SIZE(10)
	VM_PARAM_INTEGER(option)
	VM_PARAM_INTEGER(messageid)
	VM_PARAM_BYTESTR(hoveranim)
	VM_PARAM_INTEGER(plane)
	VM_PARAM_INTEGER(y)
	VM_PARAM_INTEGER(x)
	VM_PARAM_INTEGER(image_count)
	VM_PARAM_INTEGER(first_image)
	VM_PARAM_STRING(sprite)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert((option == 0) || (option == 1));
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	// TODO TODO TODO we don't take image_count!!
	CompoundPart *p = new ButtonPart(part, sprite, first_image, x, y, plane, hoveranim, messageid, option);
	a->addPart(p);
}

/**
 PAT: FIXD (command) part (integer) sprite (string) first_image (integer) image_count (integer) x (integer) y (integer) plane (integer) fontsprite (string)
 %status maybe
*/
void caosVM::c_PAT_FIXD() {
	VM_PARAM_STRING(fontsprite)
	VM_PARAM_INTEGER(plane)
	VM_PARAM_INTEGER(y)
	VM_PARAM_INTEGER(x)
	VM_PARAM_INTEGER(image_count)
	VM_PARAM_INTEGER(first_image)
	VM_PARAM_STRING(sprite)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	// TODO TODO TODO we don't take image_count!!
	CompoundPart *p = new FixedTextPart(part, sprite, first_image, x, y, plane, fontsprite);
	a->addPart(p);
}

/**
 PAT: KILL (command) part (integer)

 kill the specified part of the TARGed compound agent/vehicle
*/
void caosVM::c_PAT_KILL() {
	VM_VERIFY_SIZE(1)
	VM_PARAM_INTEGER(part)

	caos_assert(part >= 0);
	caos_assert(targ);
	CompoundAgent *a = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(a);

	a->delPart(part);
}

/**
 FCUS (command)

 focus current targeted part, which must be a PAT: TEXT
 if target is null, then unfocus current part
*/
void caosVM::c_FCUS() {
	VM_VERIFY_SIZE(0)

	if (!targ) {
		// TODO
	} else {
		CompoundAgent *c = dynamic_cast<CompoundAgent *>(targ.get());
		caos_assert(c);
		TextEntryPart *p = dynamic_cast<TextEntryPart *>(c->part(part));
		caos_assert(p);
		// TODO
	}
}

/**
 FRMT (command) left_margin (integer) top_margin (integer) right_margin (integer) button_margin (integer) line_spacing (integer) char_spacing (integer) justification (integer)
 %status stub

 alters the appearance of the target text part. the spacing values and margins are to be specified in pixels. justification can be 0 for left, 1 for right, 2 for center, 4 for bottom, 8 for middle or 16 for 'last page scroll' (TODO?), and you can add these together (except 0/1 are mutually exclusive, obviously).
*/
void caosVM::c_FRMT() {
	VM_PARAM_INTEGER(justification)
	VM_PARAM_INTEGER(char_spacing)
	VM_PARAM_INTEGER(line_spacing)
	VM_PARAM_INTEGER(bottom_margin)
	VM_PARAM_INTEGER(right_margin)
	VM_PARAM_INTEGER(top_margin)
	VM_PARAM_INTEGER(left_margin)

	caos_assert(targ);
	CompoundAgent *c = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(c);
	/*TextPart *p = dynamic_cast<TextPart *>(c->part(part));
	caos_assert(p);*/

	// TODO
}

/**
 PTXT (command) text (string)
 %status stub

 sets the text of the current text part
*/
void caosVM::c_PTXT() {
	VM_PARAM_STRING(text)

	caos_assert(targ);
	CompoundAgent *c = dynamic_cast<CompoundAgent *>(targ.get());
	caos_assert(c);
	/*TextPart *p = dynamic_cast<TextPart *>(c->part(part));
	caos_assert(p);*/

	// TODO
}

/**
 PTXT (string)
 %status stub

 returns the text of the current text part
*/
void caosVM::v_PTXT() {
	result.setString(""); // TODO
}

/* vim: set noet: */
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <fnordmetric/util/exceptionhandler.h>
#include <fnordmetric/util/runtimeexception.h>

namespace fnord {
namespace util {

using fnordmetric::util::RuntimeException;

CatchAndPrintExceptionHandler::CatchAndPrintExceptionHandler(
    Logger* logger) :
    logger_(logger) {}

void CatchAndPrintExceptionHandler::onException(
    const std::exception& error) const {
  logger_->exception("ERROR", "Uncaught exception", error);
}

CatchAndAbortExceptionHandler::CatchAndAbortExceptionHandler(
    const std::string& message) :
    message_(message) {}

void CatchAndAbortExceptionHandler::onException(
    const std::exception& error) const {
  fprintf(stderr, "%s\n\n", message_.c_str()); // FIXPAUL

  try {
    auto rte = dynamic_cast<const RuntimeException&>(error);
    rte.debugPrint();
  } catch (const std::exception& cast_error) {
    fprintf(stderr, "foreign exception: %s\n", error.what());
  }

  fprintf(stderr, "Aborting...\n");
  abort(); // core dump if enabled
}

static std::string globalEHandlerMessage;
static void globalEHandler() {
  fprintf(stderr, "%s\n", globalEHandlerMessage.c_str());

  try {
    throw;
  } catch (const std::exception& e) {
    try {
      auto rte = dynamic_cast<const RuntimeException&>(e);
      rte.debugPrint();
      exit(1);
    } catch (...) {
      /* fallthrough */
    }
  } catch (...) {
    /* fallthrough */
  }

  abort();
}

void CatchAndAbortExceptionHandler::installGlobalHandlers() {
  globalEHandlerMessage = message_;
  std::set_terminate(&globalEHandler);
  std::set_unexpected(&globalEHandler);
}

}
}
<commit_msg>make the global CatchAndAbortException handler more verbose<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <fnordmetric/util/exceptionhandler.h>
#include <fnordmetric/util/runtimeexception.h>

namespace fnord {
namespace util {

using fnordmetric::util::RuntimeException;

CatchAndPrintExceptionHandler::CatchAndPrintExceptionHandler(
    Logger* logger) :
    logger_(logger) {}

void CatchAndPrintExceptionHandler::onException(
    const std::exception& error) const {
  logger_->exception("ERROR", "Uncaught exception", error);
}

CatchAndAbortExceptionHandler::CatchAndAbortExceptionHandler(
    const std::string& message) :
    message_(message) {}

void CatchAndAbortExceptionHandler::onException(
    const std::exception& error) const {
  fprintf(stderr, "%s\n\n", message_.c_str()); // FIXPAUL

  try {
    auto rte = dynamic_cast<const RuntimeException&>(error);
    rte.debugPrint();
  } catch (const std::exception& cast_error) {
    fprintf(stderr, "foreign exception: %s\n", error.what());
  }

  fprintf(stderr, "Aborting...\n");
  abort(); // core dump if enabled
}

static std::string globalEHandlerMessage;
static void globalEHandler() {
  fprintf(stderr, "%s\n", globalEHandlerMessage.c_str());

  try {
    throw;
  } catch (const std::exception& e) {
    try {
      auto rte = dynamic_cast<const RuntimeException&>(e);
      rte.debugPrint();
      exit(1);
    } catch (...) {
      fprintf(stderr, "foreign exception: %s\n", e.what());
      /* fallthrough */
    }
  } catch (...) {
    /* fallthrough */
  }

  abort();
}

void CatchAndAbortExceptionHandler::installGlobalHandlers() {
  globalEHandlerMessage = message_;
  std::set_terminate(&globalEHandler);
  std::set_unexpected(&globalEHandler);
}

}
}
<|endoftext|>


<commit_before><commit_msg>Added more keys to KeyboardTest<commit_after><|endoftext|>


<commit_before>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP

namespace viennagrid
{

    namespace storage
    {

        template<typename container_type>
        class container_range_wrapper
        {
        public:

            container_range_wrapper(container_type & _container) : container(_container) {}

            typedef typename container_type::size_type size_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename container_type::reverse_iterator reverse_iterator;
            typedef typename container_type::const_reverse_iterator const_reverse_iterator;

            iterator begin() { return container.begin(); }
            const_iterator begin() const { return container.begin(); }
            iterator end() { return container.end(); }
            const_iterator end() const { return container.end(); }

            reverse_iterator rbegin() { return container.rbegin(); }
            const_reverse_iterator rbegin() const { return container.rbegin(); }
            reverse_iterator rend() { return container.rend(); }
            const_reverse_iterator rend() const { return container.rend(); }

            reference front() { return container.front(); }
            const_reference front() const { return container.front(); }
            reference back() { return container.back(); }
            const_reference back() const { return container.back(); }

            reference operator[] (size_type index) { return container[index]; }
            const_reference operator[] (size_type index) const { return container[index]; }

            bool empty() const { return container.empty(); }
            size_type size() const { return container.size(); }

        private:

            container_type & container;
        };

        template<typename iterator_type>
        class forward_iterator_range
        {
        public:

            forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}

            typedef typename iterator_type::T value_type;

            typedef typename iterator_type::Reference reference;
            typedef const typename iterator_type::Reference const_reference;

            typedef typename iterator_type::Pointer pointer;
            typedef const typename iterator_type::Pointer const_pointer;

            typedef iterator_type iterator;
            typedef const iterator_type const_iterator;

            iterator begin() { return first; }
            const_iterator begin() const { return first; }
            iterator end() { return last; }
            const_iterator end() const { return last; }

            reference front() { return *first; }
            const_reference front() const { return *first; }
            reference back() { iterator_type tmp = last; return *(--tmp); }
            const_reference back() const { iterator_type tmp = last; return *(--tmp); }

            bool empty() const { first == last; }

        private:
            iterator_type first;
            iterator_type last;
        };

    }

}

#endif

<commit_msg>small bugfix (missing return)<commit_after>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP

namespace viennagrid
{

    namespace storage
    {

        template<typename container_type>
        class container_range_wrapper
        {
        public:

            container_range_wrapper(container_type & _container) : container(_container) {}

            typedef typename container_type::size_type size_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename container_type::reverse_iterator reverse_iterator;
            typedef typename container_type::const_reverse_iterator const_reverse_iterator;

            iterator begin() { return container.begin(); }
            const_iterator begin() const { return container.begin(); }
            iterator end() { return container.end(); }
            const_iterator end() const { return container.end(); }

            reverse_iterator rbegin() { return container.rbegin(); }
            const_reverse_iterator rbegin() const { return container.rbegin(); }
            reverse_iterator rend() { return container.rend(); }
            const_reverse_iterator rend() const { return container.rend(); }

            reference front() { return container.front(); }
            const_reference front() const { return container.front(); }
            reference back() { return container.back(); }
            const_reference back() const { return container.back(); }

            reference operator[] (size_type index) { return container[index]; }
            const_reference operator[] (size_type index) const { return container[index]; }

            bool empty() const { return container.empty(); }
            size_type size() const { return container.size(); }

        private:

            container_type & container;
        };

        template<typename iterator_type>
        class forward_iterator_range
        {
        public:

            forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}

            typedef typename iterator_type::T value_type;

            typedef typename iterator_type::Reference reference;
            typedef const typename iterator_type::Reference const_reference;

            typedef typename iterator_type::Pointer pointer;
            typedef const typename iterator_type::Pointer const_pointer;

            typedef iterator_type iterator;
            typedef const iterator_type const_iterator;

            iterator begin() { return first; }
            const_iterator begin() const { return first; }
            iterator end() { return last; }
            const_iterator end() const { return last; }

            reference front() { return *first; }
            const_reference front() const { return *first; }
            reference back() { iterator_type tmp = last; return *(--tmp); }
            const_reference back() const { iterator_type tmp = last; return *(--tmp); }

            bool empty() const { return first == last; }

        private:
            iterator_type first;
            iterator_type last;
        };

    }

}

#endif

<|endoftext|>