<commit_before>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 * Copyright (C) 2013 Apple Inc. All rights reserved.
 *
 * 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 AND ITS CONTRIBUTORS "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 OR ITS 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 "InternalSettings.h"

#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Page.h"
#include "core/frame/Settings.h"
#include "platform/ColorChooser.h"
#include "platform/Supplementable.h"
#include "platform/text/LocaleToScriptMapping.h"

#define InternalSettingsGuardForSettingsReturn(returnValue) \
    if (!settings()) { \
        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
        return returnValue; \
    }

#define InternalSettingsGuardForSettings()  \
    if (!settings()) { \
        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
        return; \
    }

#define InternalSettingsGuardForPage() \
    if (!page()) { \
        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
        return; \
    }

namespace WebCore {

InternalSettings::Backup::Backup(Settings* settings)
    : m_originalCSSExclusionsEnabled(RuntimeEnabledFeatures::cssExclusionsEnabled())
    , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
    , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())
    , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())
    , m_originalCSP(RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled())
    , m_originalOverlayScrollbarsEnabled(RuntimeEnabledFeatures::overlayScrollbarsEnabled())
    , m_originalEditingBehavior(settings->editingBehaviorType())
    , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())
    , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())
    , m_originalAccessibilityFontScaleFactor(settings->accessibilityFontScaleFactor())
    , m_originalMediaTypeOverride(settings->mediaTypeOverride())
    , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())
    , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
    , m_imagesEnabled(settings->imagesEnabled())
    , m_shouldDisplaySubtitles(settings->shouldDisplaySubtitles())
    , m_shouldDisplayCaptions(settings->shouldDisplayCaptions())
    , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())
    , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())
    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->compositorDrivenAcceleratedScrollingEnabled())
    , m_originalLayerSquashingEnabled(settings->layerSquashingEnabled())
    , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())
{
}

void InternalSettings::Backup::restoreTo(Settings* settings)
{
    RuntimeEnabledFeatures::setCSSExclusionsEnabled(m_originalCSSExclusionsEnabled);
    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);
    settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);
    RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);
    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(m_originalCSP);
    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(m_originalOverlayScrollbarsEnabled);
    settings->setEditingBehaviorType(m_originalEditingBehavior);
    settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
    settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
    settings->setAccessibilityFontScaleFactor(m_originalAccessibilityFontScaleFactor);
    settings->setMediaTypeOverride(m_originalMediaTypeOverride);
    settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);
    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);
    settings->setImagesEnabled(m_imagesEnabled);
    settings->setShouldDisplaySubtitles(m_shouldDisplaySubtitles);
    settings->setShouldDisplayCaptions(m_shouldDisplayCaptions);
    settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);
    settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);
    settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);
    settings->setLayerSquashingEnabled(m_originalLayerSquashingEnabled);
    settings->setPasswordGenerationDecorationEnabled(m_originalPasswordGenerationDecorationEnabled);
    settings->genericFontFamilySettings().reset();
}

// We can't use RefCountedSupplement because that would try to make InternalSettings RefCounted
// and InternalSettings is already RefCounted via its base class, InternalSettingsGenerated.
// Instead, we manually make InternalSettings supplement Page.
class InternalSettingsWrapper : public Supplement<Page> {
public:
    explicit InternalSettingsWrapper(Page* page)
        : m_internalSettings(InternalSettings::create(page)) { }
    virtual ~InternalSettingsWrapper() { m_internalSettings->hostDestroyed(); }
#if !ASSERT_DISABLED
    virtual bool isRefCountedWrapper() const OVERRIDE { return true; }
#endif
    InternalSettings* internalSettings() const { return m_internalSettings.get(); }

private:
    RefPtr<InternalSettings> m_internalSettings;
};

const char* InternalSettings::supplementName()
{
    return "InternalSettings";
}

InternalSettings* InternalSettings::from(Page* page)
{
    if (!Supplement<Page>::from(page, supplementName()))
        Supplement<Page>::provideTo(page, supplementName(), adoptPtr(new InternalSettingsWrapper(page)));
    return static_cast<InternalSettingsWrapper*>(Supplement<Page>::from(page, supplementName()))->internalSettings();
}

InternalSettings::~InternalSettings()
{
}

InternalSettings::InternalSettings(Page* page)
    : InternalSettingsGenerated(page)
    , m_page(page)
    , m_backup(&page->settings())
{
}

void InternalSettings::resetToConsistentState()
{
    page()->setPageScaleFactor(1, IntPoint(0, 0));

    m_backup.restoreTo(settings());
    m_backup = Backup(settings());

    InternalSettingsGenerated::resetToConsistentState();
}

Settings* InternalSettings::settings() const
{
    if (!page())
        return 0;
    return &page()->settings();
}

void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setMockScrollbarsEnabled(enabled);
}

void InternalSettings::setAuthorShadowDOMForAnyElementEnabled(bool isEnabled)
{
    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(isEnabled);
}

void InternalSettings::setExperimentalWebSocketEnabled(bool isEnabled)
{
    settings()->setExperimentalWebSocketEnabled(isEnabled);
}

void InternalSettings::setStyleScopedEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setStyleScopedEnabled(enabled);
}

void InternalSettings::setExperimentalContentSecurityPolicyFeaturesEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enabled);
}

void InternalSettings::setOverlayScrollbarsEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
}

void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setTouchEventEmulationEnabled(enabled);
}

void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setViewportEnabled(enabled);
}

// FIXME: This is a temporary flag and should be removed once accelerated
// overflow scroll is ready (crbug.com/254111).
void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);
}

// FIXME: This is a temporary flag and should be removed once squashing is
// ready (crbug.com/261605).
void InternalSettings::setLayerSquashingEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setLayerSquashingEnabled(enabled);
}

void InternalSettings::setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setStandard(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setSerif(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setSansSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setSansSerif(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setFixedFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setFixed(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setCursiveFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setCursive(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setFantasyFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setFantasy(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setPictographFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setPictograph(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setTextAutosizingEnabled(enabled);
}

void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setTextAutosizingWindowSizeOverride(IntSize(width, height));
}

void InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setMediaTypeOverride(mediaType);
}

void InternalSettings::setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setAccessibilityFontScaleFactor(fontScaleFactor);
}

void InternalSettings::setCSSExclusionsEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setCSSExclusionsEnabled(enabled);
}

void InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    if (equalIgnoringCase(editingBehavior, "win"))
        settings()->setEditingBehaviorType(EditingWindowsBehavior);
    else if (equalIgnoringCase(editingBehavior, "mac"))
        settings()->setEditingBehaviorType(EditingMacBehavior);
    else if (equalIgnoringCase(editingBehavior, "unix"))
        settings()->setEditingBehaviorType(EditingUnixBehavior);
    else if (equalIgnoringCase(editingBehavior, "android"))
        settings()->setEditingBehaviorType(EditingAndroidBehavior);
    else
        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
}

void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);
}

void InternalSettings::setImagesEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setImagesEnabled(enabled);
}

void InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setDefaultVideoPosterURL(url);
}

void InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setPasswordGenerationDecorationEnabled(enabled);
}

}
<commit_msg>Improve core/testing/InternalSettings exception messages.<commit_after>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 * Copyright (C) 2013 Apple Inc. All rights reserved.
 *
 * 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 AND ITS CONTRIBUTORS "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 OR ITS 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 "InternalSettings.h"

#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Page.h"
#include "core/frame/Settings.h"
#include "platform/ColorChooser.h"
#include "platform/Supplementable.h"
#include "platform/text/LocaleToScriptMapping.h"

#define InternalSettingsGuardForSettingsReturn(returnValue) \
    if (!settings()) { \
        exceptionState.throwDOMException(InvalidAccessError, "The settings object cannot be obtained."); \
        return returnValue; \
    }

#define InternalSettingsGuardForSettings()  \
    if (!settings()) { \
        exceptionState.throwDOMException(InvalidAccessError, "The settings object cannot be obtained."); \
        return; \
    }

#define InternalSettingsGuardForPage() \
    if (!page()) { \
        exceptionState.throwDOMException(InvalidAccessError, "The page object cannot be obtained."); \
        return; \
    }

namespace WebCore {

InternalSettings::Backup::Backup(Settings* settings)
    : m_originalCSSExclusionsEnabled(RuntimeEnabledFeatures::cssExclusionsEnabled())
    , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
    , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())
    , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())
    , m_originalCSP(RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled())
    , m_originalOverlayScrollbarsEnabled(RuntimeEnabledFeatures::overlayScrollbarsEnabled())
    , m_originalEditingBehavior(settings->editingBehaviorType())
    , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())
    , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())
    , m_originalAccessibilityFontScaleFactor(settings->accessibilityFontScaleFactor())
    , m_originalMediaTypeOverride(settings->mediaTypeOverride())
    , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())
    , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
    , m_imagesEnabled(settings->imagesEnabled())
    , m_shouldDisplaySubtitles(settings->shouldDisplaySubtitles())
    , m_shouldDisplayCaptions(settings->shouldDisplayCaptions())
    , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())
    , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())
    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->compositorDrivenAcceleratedScrollingEnabled())
    , m_originalLayerSquashingEnabled(settings->layerSquashingEnabled())
    , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())
{
}

void InternalSettings::Backup::restoreTo(Settings* settings)
{
    RuntimeEnabledFeatures::setCSSExclusionsEnabled(m_originalCSSExclusionsEnabled);
    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);
    settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);
    RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);
    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(m_originalCSP);
    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(m_originalOverlayScrollbarsEnabled);
    settings->setEditingBehaviorType(m_originalEditingBehavior);
    settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
    settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
    settings->setAccessibilityFontScaleFactor(m_originalAccessibilityFontScaleFactor);
    settings->setMediaTypeOverride(m_originalMediaTypeOverride);
    settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);
    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);
    settings->setImagesEnabled(m_imagesEnabled);
    settings->setShouldDisplaySubtitles(m_shouldDisplaySubtitles);
    settings->setShouldDisplayCaptions(m_shouldDisplayCaptions);
    settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);
    settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);
    settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);
    settings->setLayerSquashingEnabled(m_originalLayerSquashingEnabled);
    settings->setPasswordGenerationDecorationEnabled(m_originalPasswordGenerationDecorationEnabled);
    settings->genericFontFamilySettings().reset();
}

// We can't use RefCountedSupplement because that would try to make InternalSettings RefCounted
// and InternalSettings is already RefCounted via its base class, InternalSettingsGenerated.
// Instead, we manually make InternalSettings supplement Page.
class InternalSettingsWrapper : public Supplement<Page> {
public:
    explicit InternalSettingsWrapper(Page* page)
        : m_internalSettings(InternalSettings::create(page)) { }
    virtual ~InternalSettingsWrapper() { m_internalSettings->hostDestroyed(); }
#if !ASSERT_DISABLED
    virtual bool isRefCountedWrapper() const OVERRIDE { return true; }
#endif
    InternalSettings* internalSettings() const { return m_internalSettings.get(); }

private:
    RefPtr<InternalSettings> m_internalSettings;
};

const char* InternalSettings::supplementName()
{
    return "InternalSettings";
}

InternalSettings* InternalSettings::from(Page* page)
{
    if (!Supplement<Page>::from(page, supplementName()))
        Supplement<Page>::provideTo(page, supplementName(), adoptPtr(new InternalSettingsWrapper(page)));
    return static_cast<InternalSettingsWrapper*>(Supplement<Page>::from(page, supplementName()))->internalSettings();
}

InternalSettings::~InternalSettings()
{
}

InternalSettings::InternalSettings(Page* page)
    : InternalSettingsGenerated(page)
    , m_page(page)
    , m_backup(&page->settings())
{
}

void InternalSettings::resetToConsistentState()
{
    page()->setPageScaleFactor(1, IntPoint(0, 0));

    m_backup.restoreTo(settings());
    m_backup = Backup(settings());

    InternalSettingsGenerated::resetToConsistentState();
}

Settings* InternalSettings::settings() const
{
    if (!page())
        return 0;
    return &page()->settings();
}

void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setMockScrollbarsEnabled(enabled);
}

void InternalSettings::setAuthorShadowDOMForAnyElementEnabled(bool isEnabled)
{
    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(isEnabled);
}

void InternalSettings::setExperimentalWebSocketEnabled(bool isEnabled)
{
    settings()->setExperimentalWebSocketEnabled(isEnabled);
}

void InternalSettings::setStyleScopedEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setStyleScopedEnabled(enabled);
}

void InternalSettings::setExperimentalContentSecurityPolicyFeaturesEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enabled);
}

void InternalSettings::setOverlayScrollbarsEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
}

void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setTouchEventEmulationEnabled(enabled);
}

void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setViewportEnabled(enabled);
}

// FIXME: This is a temporary flag and should be removed once accelerated
// overflow scroll is ready (crbug.com/254111).
void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);
}

// FIXME: This is a temporary flag and should be removed once squashing is
// ready (crbug.com/261605).
void InternalSettings::setLayerSquashingEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setLayerSquashingEnabled(enabled);
}

void InternalSettings::setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setStandard(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setSerif(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setSansSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setSansSerif(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setFixedFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setFixed(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setCursiveFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setCursive(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setFantasyFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setFantasy(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setPictographFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    UScriptCode code = scriptNameToCode(script);
    if (code == USCRIPT_INVALID_CODE)
        return;
    settings()->genericFontFamilySettings().setPictograph(family, code);
    m_page->setNeedsRecalcStyleInAllFrames();
}

void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setTextAutosizingEnabled(enabled);
}

void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setTextAutosizingWindowSizeOverride(IntSize(width, height));
}

void InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setMediaTypeOverride(mediaType);
}

void InternalSettings::setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setAccessibilityFontScaleFactor(fontScaleFactor);
}

void InternalSettings::setCSSExclusionsEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setCSSExclusionsEnabled(enabled);
}

void InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    if (equalIgnoringCase(editingBehavior, "win"))
        settings()->setEditingBehaviorType(EditingWindowsBehavior);
    else if (equalIgnoringCase(editingBehavior, "mac"))
        settings()->setEditingBehaviorType(EditingMacBehavior);
    else if (equalIgnoringCase(editingBehavior, "unix"))
        settings()->setEditingBehaviorType(EditingUnixBehavior);
    else if (equalIgnoringCase(editingBehavior, "android"))
        settings()->setEditingBehaviorType(EditingAndroidBehavior);
    else
        exceptionState.throwDOMException(SyntaxError, "The editing behavior type provided ('" + editingBehavior + "') is invalid.");
}

void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
{
    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);
}

void InternalSettings::setImagesEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setImagesEnabled(enabled);
}

void InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setDefaultVideoPosterURL(url);
}

void InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& exceptionState)
{
    InternalSettingsGuardForSettings();
    settings()->setPasswordGenerationDecorationEnabled(enabled);
}

}
<|endoftext|>


<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef __ANY_VALUE_HPP_INCLUDED
#define __ANY_VALUE_HPP_INCLUDED

#include "datatype.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory>   // std::make_shared, std::shared_ptr
#include <string>   // std::string
#include <stdint.h> // uint32_t etc.
#include <variant>  // std::variant
#include <vector>   // std::vector

namespace yli
{
    namespace ontology
    {
        class Entity;
        class Movable;
        class Universe;
        class World;
        class Scene;
        class Shader;
        class Material;
        class Species;
        class Object;
        class Symbiosis;
        class SymbiontMaterial;
        class SymbiontSpecies;
        class Holobiont;
        class Biont;
        class Font2D;
        class Text2D;
        class VectorFont;
        class Glyph;
        class Text3D;
        class Console;
        class ComputeTask;
    }

    namespace common
    {
        class AnyStruct;
        class SphericalCoordinatesStruct;

        class AnyValue
        {
            public:
                std::string get_datatype() const;
                std::string get_string() const;
                yli::ontology::Entity* get_entity_pointer() const;
                bool set_value(const std::string& value_string);

                // copy constructor.
                AnyValue(const yli::common::AnyValue& original);

                // common constructors.

                AnyValue(); // This constructor initializes `AnyValue` with default values.
                AnyValue(const std::string& type, const std::string& value_string); // This constructor takes also the value as a string.
                AnyValue(const bool bool_value);
                AnyValue(const char char_value);
                AnyValue(const float float_value);
                AnyValue(const double double_value);
                AnyValue(const int32_t int32_t_value);
                AnyValue(const uint32_t uint32_t_value);
                AnyValue(bool* const bool_pointer);
                AnyValue(char* const char_pointer);
                AnyValue(float* const float_pointer);
                AnyValue(double* const double_pointer);
                AnyValue(int32_t* const int32_t_pointer);
                AnyValue(uint32_t* const uint32_t_pointer);
                AnyValue(yli::ontology::Entity* const entity_pointer);
                AnyValue(yli::ontology::Movable* const movable_pointer);
                AnyValue(const yli::ontology::Movable* const const_movable_pointer);
                AnyValue(yli::ontology::Universe* const universe_pointer);
                AnyValue(yli::ontology::World* const world_pointer);
                AnyValue(yli::ontology::Scene* const scene_pointer);
                AnyValue(yli::ontology::Shader* const shader_pointer);
                AnyValue(yli::ontology::Material* const material_pointer);
                AnyValue(yli::ontology::Species* const species_pointer);
                AnyValue(yli::ontology::Object* const object_pointer);
                AnyValue(yli::ontology::Symbiosis* const symbiosis_pointer);
                AnyValue(yli::ontology::SymbiontMaterial* const symbiont_material_pointer);
                AnyValue(yli::ontology::SymbiontSpecies* const symbiont_species_pointer);
                AnyValue(yli::ontology::Holobiont* const holobiont_pointer);
                AnyValue(yli::ontology::Biont* const biont_pointer);
                AnyValue(yli::ontology::Font2D* const font2D_pointer);
                AnyValue(yli::ontology::Text2D* const text2D_pointer);
                AnyValue(yli::ontology::VectorFont* const vector_font_pointer);
                AnyValue(yli::ontology::Glyph* const glyph_pointer);
                AnyValue(yli::ontology::Text3D* const text3D_pointer);
                AnyValue(yli::ontology::Console* const console_pointer);
                AnyValue(yli::ontology::ComputeTask* const compute_task_pointer);
                AnyValue(std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);
                AnyValue(std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);
                AnyValue(yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);
                AnyValue(std::string* const std_string_pointer);
                AnyValue(const std::string* const const_std_string_pointer);
                AnyValue(std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);
                AnyValue(std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);
                AnyValue(std::shared_ptr<glm::vec4> const glm_vec4_shared_ptr);

                AnyValue(const std::string& type, const bool bool_value);
                AnyValue(const std::string& type, const char char_value);
                AnyValue(const std::string& type, const float float_value);
                AnyValue(const std::string& type, const double double_value);
                AnyValue(const std::string& type, const int32_t int32_t_value);
                AnyValue(const std::string& type, const uint32_t uint32_t_value);
                AnyValue(const std::string& type, bool* const bool_pointer);
                AnyValue(const std::string& type, char* const char_pointer);
                AnyValue(const std::string& type, float* const float_pointer);
                AnyValue(const std::string& type, double* const double_pointer);
                AnyValue(const std::string& type, int32_t* const int32_t_pointer);
                AnyValue(const std::string& type, uint32_t* const uint32_t_pointer);
                AnyValue(const std::string& type, yli::ontology::Entity* const entity_pointer);
                AnyValue(const std::string& type, yli::ontology::Movable* const movable_pointer);
                AnyValue(const std::string& type, const yli::ontology::Movable* const const_movable_pointer);
                AnyValue(const std::string& type, yli::ontology::Universe* const universe_pointer);
                AnyValue(const std::string& type, yli::ontology::World* const world_pointer);
                AnyValue(const std::string& type, yli::ontology::Scene* const scene_pointer);
                AnyValue(const std::string& type, yli::ontology::Shader* const shader_pointer);
                AnyValue(const std::string& type, yli::ontology::Material* const material_pointer);
                AnyValue(const std::string& type, yli::ontology::Species* const species_pointer);
                AnyValue(const std::string& type, yli::ontology::Object* const object_pointer);
                AnyValue(const std::string& type, yli::ontology::Symbiosis* const symbiosis_pointer);
                AnyValue(const std::string& type, yli::ontology::SymbiontMaterial* const symbiont_material_pointer);
                AnyValue(const std::string& type, yli::ontology::SymbiontSpecies* const symbiont_species_pointer);
                AnyValue(const std::string& type, yli::ontology::Holobiont* const holobiont_pointer);
                AnyValue(const std::string& type, yli::ontology::Biont* const biont_pointer);
                AnyValue(const std::string& type, yli::ontology::Font2D* const font2D_pointer);
                AnyValue(const std::string& type, yli::ontology::Text2D* const text2D_pointer);
                AnyValue(const std::string& type, yli::ontology::VectorFont* const vector_font_pointer);
                AnyValue(const std::string& type, yli::ontology::Glyph* const glyph_pointer);
                AnyValue(const std::string& type, yli::ontology::Text3D* const text3D_pointer);
                AnyValue(const std::string& type, yli::ontology::Console* const console_pointer);
                AnyValue(const std::string& type, yli::ontology::ComputeTask* const compute_task_pointer);
                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);
                AnyValue(const std::string& type, yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);
                AnyValue(const std::string& type, std::string* const std_string_pointer);
                AnyValue(const std::string& type, const std::string* const const_std_string_pointer);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<glm::vec4> const glm_vec3_shared_ptr);

                yli::common::Datatype type;

                std::variant<
                    bool,
                    char,
                    float,
                    double,
                    int32_t,
                    uint32_t,
                    bool*,
                    char*,
                    float*,
                    double*,
                    int32_t*,
                    uint32_t*,
                    yli::ontology::Entity*,
                    yli::ontology::Movable*,
                    const yli::ontology::Movable*,
                    yli::ontology::Universe*,
                    yli::ontology::World*,
                    yli::ontology::Scene*,
                    yli::ontology::Shader*,
                    yli::ontology::Material*,
                    yli::ontology::Species*,
                    yli::ontology::Object*,
                    yli::ontology::Symbiosis*,
                    yli::ontology::SymbiontMaterial*,
                    yli::ontology::SymbiontSpecies*,
                    yli::ontology::Holobiont*,
                    yli::ontology::Biont*,
                    yli::ontology::Font2D*,
                    yli::ontology::Text2D*,
                    yli::ontology::VectorFont*,
                    yli::ontology::Glyph*,
                    yli::ontology::Text3D*,
                    yli::ontology::Console*,
                    yli::ontology::ComputeTask*,
                    std::shared_ptr<yli::common::AnyValue>,
                    std::shared_ptr<yli::common::AnyStruct>,
                    std::shared_ptr<std::vector<int8_t>>,
                    std::shared_ptr<std::vector<uint8_t>>,
                    std::shared_ptr<std::vector<int16_t>>,
                    std::shared_ptr<std::vector<uint16_t>>,
                    std::shared_ptr<std::vector<int32_t>>,
                    std::shared_ptr<std::vector<uint32_t>>,
                    std::shared_ptr<std::vector<float>>,
                    std::shared_ptr<glm::vec3>,
                    std::shared_ptr<glm::vec4>,
                    yli::common::SphericalCoordinatesStruct*,
                    std::string*,
                    const std::string*
                    > data;

            private:
                void set_default_values();
        };
    }
}

#endif
<commit_msg>Bugfix: forward declaration.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2020 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef __ANY_VALUE_HPP_INCLUDED
#define __ANY_VALUE_HPP_INCLUDED

#include "datatype.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory>   // std::make_shared, std::shared_ptr
#include <string>   // std::string
#include <stdint.h> // uint32_t etc.
#include <variant>  // std::variant
#include <vector>   // std::vector

namespace yli
{
    namespace ontology
    {
        class Entity;
        class Movable;
        class Universe;
        class World;
        class Scene;
        class Shader;
        class Material;
        class Species;
        class Object;
        class Symbiosis;
        class SymbiontMaterial;
        class SymbiontSpecies;
        class Holobiont;
        class Biont;
        class Font2D;
        class Text2D;
        class VectorFont;
        class Glyph;
        class Text3D;
        class Console;
        class ComputeTask;
    }

    namespace common
    {
        class AnyStruct;
        struct SphericalCoordinatesStruct;

        class AnyValue
        {
            public:
                std::string get_datatype() const;
                std::string get_string() const;
                yli::ontology::Entity* get_entity_pointer() const;
                bool set_value(const std::string& value_string);

                // copy constructor.
                AnyValue(const yli::common::AnyValue& original);

                // common constructors.

                AnyValue(); // This constructor initializes `AnyValue` with default values.
                AnyValue(const std::string& type, const std::string& value_string); // This constructor takes also the value as a string.
                AnyValue(const bool bool_value);
                AnyValue(const char char_value);
                AnyValue(const float float_value);
                AnyValue(const double double_value);
                AnyValue(const int32_t int32_t_value);
                AnyValue(const uint32_t uint32_t_value);
                AnyValue(bool* const bool_pointer);
                AnyValue(char* const char_pointer);
                AnyValue(float* const float_pointer);
                AnyValue(double* const double_pointer);
                AnyValue(int32_t* const int32_t_pointer);
                AnyValue(uint32_t* const uint32_t_pointer);
                AnyValue(yli::ontology::Entity* const entity_pointer);
                AnyValue(yli::ontology::Movable* const movable_pointer);
                AnyValue(const yli::ontology::Movable* const const_movable_pointer);
                AnyValue(yli::ontology::Universe* const universe_pointer);
                AnyValue(yli::ontology::World* const world_pointer);
                AnyValue(yli::ontology::Scene* const scene_pointer);
                AnyValue(yli::ontology::Shader* const shader_pointer);
                AnyValue(yli::ontology::Material* const material_pointer);
                AnyValue(yli::ontology::Species* const species_pointer);
                AnyValue(yli::ontology::Object* const object_pointer);
                AnyValue(yli::ontology::Symbiosis* const symbiosis_pointer);
                AnyValue(yli::ontology::SymbiontMaterial* const symbiont_material_pointer);
                AnyValue(yli::ontology::SymbiontSpecies* const symbiont_species_pointer);
                AnyValue(yli::ontology::Holobiont* const holobiont_pointer);
                AnyValue(yli::ontology::Biont* const biont_pointer);
                AnyValue(yli::ontology::Font2D* const font2D_pointer);
                AnyValue(yli::ontology::Text2D* const text2D_pointer);
                AnyValue(yli::ontology::VectorFont* const vector_font_pointer);
                AnyValue(yli::ontology::Glyph* const glyph_pointer);
                AnyValue(yli::ontology::Text3D* const text3D_pointer);
                AnyValue(yli::ontology::Console* const console_pointer);
                AnyValue(yli::ontology::ComputeTask* const compute_task_pointer);
                AnyValue(std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);
                AnyValue(std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);
                AnyValue(yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);
                AnyValue(std::string* const std_string_pointer);
                AnyValue(const std::string* const const_std_string_pointer);
                AnyValue(std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);
                AnyValue(std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);
                AnyValue(std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);
                AnyValue(std::shared_ptr<glm::vec4> const glm_vec4_shared_ptr);

                AnyValue(const std::string& type, const bool bool_value);
                AnyValue(const std::string& type, const char char_value);
                AnyValue(const std::string& type, const float float_value);
                AnyValue(const std::string& type, const double double_value);
                AnyValue(const std::string& type, const int32_t int32_t_value);
                AnyValue(const std::string& type, const uint32_t uint32_t_value);
                AnyValue(const std::string& type, bool* const bool_pointer);
                AnyValue(const std::string& type, char* const char_pointer);
                AnyValue(const std::string& type, float* const float_pointer);
                AnyValue(const std::string& type, double* const double_pointer);
                AnyValue(const std::string& type, int32_t* const int32_t_pointer);
                AnyValue(const std::string& type, uint32_t* const uint32_t_pointer);
                AnyValue(const std::string& type, yli::ontology::Entity* const entity_pointer);
                AnyValue(const std::string& type, yli::ontology::Movable* const movable_pointer);
                AnyValue(const std::string& type, const yli::ontology::Movable* const const_movable_pointer);
                AnyValue(const std::string& type, yli::ontology::Universe* const universe_pointer);
                AnyValue(const std::string& type, yli::ontology::World* const world_pointer);
                AnyValue(const std::string& type, yli::ontology::Scene* const scene_pointer);
                AnyValue(const std::string& type, yli::ontology::Shader* const shader_pointer);
                AnyValue(const std::string& type, yli::ontology::Material* const material_pointer);
                AnyValue(const std::string& type, yli::ontology::Species* const species_pointer);
                AnyValue(const std::string& type, yli::ontology::Object* const object_pointer);
                AnyValue(const std::string& type, yli::ontology::Symbiosis* const symbiosis_pointer);
                AnyValue(const std::string& type, yli::ontology::SymbiontMaterial* const symbiont_material_pointer);
                AnyValue(const std::string& type, yli::ontology::SymbiontSpecies* const symbiont_species_pointer);
                AnyValue(const std::string& type, yli::ontology::Holobiont* const holobiont_pointer);
                AnyValue(const std::string& type, yli::ontology::Biont* const biont_pointer);
                AnyValue(const std::string& type, yli::ontology::Font2D* const font2D_pointer);
                AnyValue(const std::string& type, yli::ontology::Text2D* const text2D_pointer);
                AnyValue(const std::string& type, yli::ontology::VectorFont* const vector_font_pointer);
                AnyValue(const std::string& type, yli::ontology::Glyph* const glyph_pointer);
                AnyValue(const std::string& type, yli::ontology::Text3D* const text3D_pointer);
                AnyValue(const std::string& type, yli::ontology::Console* const console_pointer);
                AnyValue(const std::string& type, yli::ontology::ComputeTask* const compute_task_pointer);
                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);
                AnyValue(const std::string& type, yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);
                AnyValue(const std::string& type, std::string* const std_string_pointer);
                AnyValue(const std::string& type, const std::string* const const_std_string_pointer);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);
                AnyValue(const std::string& type, std::shared_ptr<glm::vec4> const glm_vec3_shared_ptr);

                yli::common::Datatype type;

                std::variant<
                    bool,
                    char,
                    float,
                    double,
                    int32_t,
                    uint32_t,
                    bool*,
                    char*,
                    float*,
                    double*,
                    int32_t*,
                    uint32_t*,
                    yli::ontology::Entity*,
                    yli::ontology::Movable*,
                    const yli::ontology::Movable*,
                    yli::ontology::Universe*,
                    yli::ontology::World*,
                    yli::ontology::Scene*,
                    yli::ontology::Shader*,
                    yli::ontology::Material*,
                    yli::ontology::Species*,
                    yli::ontology::Object*,
                    yli::ontology::Symbiosis*,
                    yli::ontology::SymbiontMaterial*,
                    yli::ontology::SymbiontSpecies*,
                    yli::ontology::Holobiont*,
                    yli::ontology::Biont*,
                    yli::ontology::Font2D*,
                    yli::ontology::Text2D*,
                    yli::ontology::VectorFont*,
                    yli::ontology::Glyph*,
                    yli::ontology::Text3D*,
                    yli::ontology::Console*,
                    yli::ontology::ComputeTask*,
                    std::shared_ptr<yli::common::AnyValue>,
                    std::shared_ptr<yli::common::AnyStruct>,
                    std::shared_ptr<std::vector<int8_t>>,
                    std::shared_ptr<std::vector<uint8_t>>,
                    std::shared_ptr<std::vector<int16_t>>,
                    std::shared_ptr<std::vector<uint16_t>>,
                    std::shared_ptr<std::vector<int32_t>>,
                    std::shared_ptr<std::vector<uint32_t>>,
                    std::shared_ptr<std::vector<float>>,
                    std::shared_ptr<glm::vec3>,
                    std::shared_ptr<glm::vec4>,
                    yli::common::SphericalCoordinatesStruct*,
                    std::string*,
                    const std::string*
                    > data;

            private:
                void set_default_values();
        };
    }
}

#endif
<|endoftext|>


<commit_before>/**
 * @file   libtbshare.cpp
 * @brief  libtbshare entry-point.
 * @author zer0
 * @date   2016-04-17
 * @date   2016-10-14 (Rename: libtbag_test -> libtbtest)
 * @date   2016-10-25 (Rename: libtbtest -> tbshare)
 * @date   2017-04-12 (Rename: tbshare -> libtbshare)
 */

#if defined(USE_LIBTEST_EXPORT)
# if defined(WIN32) || defined(_WIN32)
#  define LIBTBAG_TEST_EXPORT __declspec(dllexport)
# elif defined(__GNUC__)
#  define LIBTBAG_TEST_EXPORT __attribute__((visibility("default")))
# else
#  define LIBTBAG_TEST_EXPORT
# endif
#else // defined(USE_LIBTEST_EXPORT)
# if defined(WIN32) || defined(_WIN32)
#  define LIBTBAG_TEST_EXPORT __declspec(dllimport)
# else
#  define LIBTBAG_TEST_EXPORT
# endif
#endif // defined(TBAG_EXPORT_API)

#if defined(__cplusplus)
extern "C" {
#endif

/* Add function test. */
LIBTBAG_TEST_EXPORT int tbshare_add(int v1, int v2)
{
    return v1 + v2;
}

/* Add function test2. */
LIBTBAG_TEST_EXPORT void tbshare_add2(int v1, int v2, int * result)
{
    if (result != nullptr) {
        *result = v1 + v2;
    }
}

#if defined(__cplusplus)
} /* extern "C" */
#endif

<commit_msg>Trivial commit.<commit_after>/**
 * @file   libtbshare.cpp
 * @brief  libtbshare entry-point.
 * @author zer0
 * @date   2016-04-17
 * @date   2016-10-14 (Rename: libtbag_test -> libtbtest)
 * @date   2016-10-25 (Rename: libtbtest -> tbshare)
 * @date   2017-04-12 (Rename: tbshare -> libtbshare)
 */

#if defined(USE_LIBTEST_EXPORT)
# if defined(WIN32) || defined(_WIN32)
#  define LIBTBAG_TEST_EXPORT __declspec(dllexport)
# elif defined(__GNUC__)
#  define LIBTBAG_TEST_EXPORT __attribute__((visibility("default")))
# else
#  define LIBTBAG_TEST_EXPORT
# endif
#else // defined(USE_LIBTEST_EXPORT)
# if defined(WIN32) || defined(_WIN32)
#  define LIBTBAG_TEST_EXPORT __declspec(dllimport)
# else
#  define LIBTBAG_TEST_EXPORT
# endif
#endif // defined(USE_LIBTEST_EXPORT)

#if defined(__cplusplus)
extern "C" {
#endif

/* Add function test. */
LIBTBAG_TEST_EXPORT int tbshare_add(int v1, int v2)
{
    return v1 + v2;
}

/* Add function test2. */
LIBTBAG_TEST_EXPORT void tbshare_add2(int v1, int v2, int * result)
{
    if (result != nullptr) {
        *result = v1 + v2;
    }
}

#if defined(__cplusplus)
} /* extern "C" */
#endif

<|endoftext|>


<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED

#include "movable.hpp"
#include "parent_module.hpp"
#include "glyph_object_creation.hpp"
#include "text_3d_struct.hpp"

// Include standard headers
#include <cstddef>  // std::size_t
#include <string>   // std::string

namespace yli::ontology
{
    class Universe;
    class Object;
    class ParentModule;
    class MasterModule;
    class VectorFont;

    class Text3D: public yli::ontology::Movable
    {
        public:
            // this method deletes all glyph Objects of this `Text3D`,
            // sets pointer to this `Text3D` to `nullptr`,
            // sets `parent` according to the input (the new `VectorFont`),
            // requests a new `childID` from the new `VectorFont`,
            // and creates all glyph Objects of this `Text3D` with the font data.
            // Note: different fonts may provide glyphs for different Unicodes!
            void bind_to_new_parent(yli::ontology::VectorFont* const new_vector_font_pointer);

            Text3D(
                    yli::ontology::Universe* const universe,
                    const yli::ontology::Text3DStruct& text_3d_struct,
                    yli::ontology::ParentModule* const parent_module,
                    yli::ontology::MasterModule* const master_module)
                : Movable(
                        universe,
                        text_3d_struct,
                        parent_module,
                        master_module),
                parent_of_objects(this)
            {
                // constructor.

                // TODO: `Text3D` constructor also creates each `Object`,
                // and binds each to its corresponding `Glyph` for rendering hierarchy,
                // and also binds each to this `Text3D` for ontological hierarchy.

                this->text_string  = text_3d_struct.text_string;

                // Let's create each glyph `Object` in a loop.

                yli::ontology::create_glyph_objects(this->text_string, this);

                // `yli::ontology::Entity` member variables begin here.
                this->type_string = "yli::ontology::Text3D*";
                this->can_be_erased = true;
            }

            Text3D(const Text3D&) = delete;            // Delete copy constructor.
            Text3D& operator=(const Text3D&) = delete; // Delete copy assignment.

            // destructor.
            virtual ~Text3D();

            friend class Object;
            friend void create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* text_3d);

            yli::ontology::ParentModule parent_of_objects;

        private:
            std::size_t get_number_of_children() const override;
            std::size_t get_number_of_descendants() const override;

            std::string text_string;
    };
}

#endif
<commit_msg>Edit whitespace.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED

#include "movable.hpp"
#include "parent_module.hpp"
#include "glyph_object_creation.hpp"
#include "text_3d_struct.hpp"

// Include standard headers
#include <cstddef>  // std::size_t
#include <string>   // std::string

namespace yli::ontology
{
    class Universe;
    class Object;
    class ParentModule;
    class MasterModule;
    class VectorFont;

    class Text3D: public yli::ontology::Movable
    {
        public:
            // this method deletes all glyph Objects of this `Text3D`,
            // sets pointer to this `Text3D` to `nullptr`,
            // sets `parent` according to the input (the new `VectorFont`),
            // requests a new `childID` from the new `VectorFont`,
            // and creates all glyph Objects of this `Text3D` with the font data.
            // Note: different fonts may provide glyphs for different Unicodes!
            void bind_to_new_parent(yli::ontology::VectorFont* const new_vector_font_pointer);

            Text3D(
                    yli::ontology::Universe* const universe,
                    const yli::ontology::Text3DStruct& text_3d_struct,
                    yli::ontology::ParentModule* const parent_module,
                    yli::ontology::MasterModule* const master_module)
                : Movable(
                        universe,
                        text_3d_struct,
                        parent_module,
                        master_module),
                parent_of_objects(this)
            {
                // constructor.

                // TODO: `Text3D` constructor also creates each `Object`,
                // and binds each to its corresponding `Glyph` for rendering hierarchy,
                // and also binds each to this `Text3D` for ontological hierarchy.

                this->text_string = text_3d_struct.text_string;

                // Let's create each glyph `Object` in a loop.

                yli::ontology::create_glyph_objects(this->text_string, this);

                // `yli::ontology::Entity` member variables begin here.
                this->type_string = "yli::ontology::Text3D*";
                this->can_be_erased = true;
            }

            Text3D(const Text3D&) = delete;            // Delete copy constructor.
            Text3D& operator=(const Text3D&) = delete; // Delete copy assignment.

            // destructor.
            virtual ~Text3D();

            friend class Object;
            friend void create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* text_3d);

            yli::ontology::ParentModule parent_of_objects;

        private:
            std::size_t get_number_of_children() const override;
            std::size_t get_number_of_descendants() const override;

            std::string text_string;
    };
}

#endif
<|endoftext|>


<commit_before>/**
 * NMXmlParserExperiment.cc
 *
 *
 * Copyright(c) 2003 Rodrigo Barra
 * All rights reserved.
 */
#include <NMXmlParserExperiment.h>
#include <ClassServer.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exceptions.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <Link.h>
#include <TLB.h>
#include <cxxtest/TestSuite.h>

#include <cstdlib>
using namespace std;

#ifdef WIN32
#include <fcntl.h>
#include <io.h>
#define _S_IREAD 256
#define _S_IWRITE 128
int mkstemp(char *tmpl)
{
	int ret=-1;
	_mktemp(tmpl);
	ret=open(tmpl,O_RDWR|O_BINARY|O_CREAT|O_EXCL|_O_SHORT_LIVED, _S_IREAD|_S_IWRITE);
	return ret;
}

#endif

bool NMXmlParserExperiment::noCheck = false;
char *NMXmlParserExperiment::currentFileName = NULL;
int NMXmlParserExperiment::currentExperiment = -1;

Handle NMXmlParserExperiment::sport = NULL;
Handle NMXmlParserExperiment::soccer = NULL;
Handle NMXmlParserExperiment::link_sport_socker = NULL;
Handle NMXmlParserExperiment::hihger_order_link = NULL;
AtomSpace* NMXmlParserExperiment::atomSpace = NULL;

void NMXmlParserExperiment::initStaticVars() {
	NMXmlParserExperiment::noCheck = false;
	NMXmlParserExperiment::currentFileName = NULL;
	NMXmlParserExperiment::currentExperiment = -1;

	NMXmlParserExperiment::sport = NULL;
	NMXmlParserExperiment::soccer = NULL;
	NMXmlParserExperiment::link_sport_socker = NULL;
	NMXmlParserExperiment::hihger_order_link = NULL;
	NMXmlParserExperiment::atomSpace = NULL;
}

int NMXmlParserExperiment::getNExperiments(){
	return(NNMXMLXMLEXPERIMENTS);
}

void NMXmlParserExperiment::createExperiment(int exp, AtomSpace* as){
	if ((exp < 0) || (exp > NNMXMLXMLEXPERIMENTS)){
	    throw new RuntimeException(TRACE_INFO, "Invalid Experiment\n");
	}

	if (currentExperiment != -1){
		throw new RuntimeException(TRACE_INFO, "Tried to start a new experiment without destroying the last one");
	}

	currentExperiment = exp;

	//currentFileName = strdup("/var/tmp/xmltest.XXXXXX");
	currentFileName = strdup("xmltest.XXXXXX");
    printf("just allocated currentFileName = %s\n", currentFileName);

	int fd = mkstemp(currentFileName);
    printf("after mkstemp currentFileName = %s\n", currentFileName);

	if (fd == -1){
		throw new RuntimeException(TRACE_INFO, "Could not create temporary file\n");
	}

	write(fd, expContents[exp%2], strlen(expContents[exp%2]));

	close(fd);

    if (atomSpace) delete atomSpace;
    atomSpace = as;
}

bool NMXmlParserExperiment::checkExperiment(){
    if (noCheck) {
        return (true);
    }
	if (currentExperiment == -1){
		return(true);
	}
	switch (currentExperiment){
	case 0:
		return(checkExp0());
		break;
	case 1:
		return(checkExp1());
		break;
	}
	return(false);
}

AtomSpace* NMXmlParserExperiment::destroyExperiment(bool cleanup){
	if (currentExperiment == -1){
		return atomSpace;
	}
    printf("currentFileName = %s\n", currentFileName);
	remove(currentFileName);
#ifndef WIN32 // For some reason, this causes error on Windows
	free(currentFileName);
#endif
	currentFileName = NULL;
	currentExperiment = -1;
    if (cleanup) {
    	cleanupAtomSpace();
    }
    return atomSpace;
}

AtomSpace* NMXmlParserExperiment::cleanupAtomSpace(){
    delete atomSpace;
    atomSpace = new AtomSpace();
    return atomSpace;
}

AtomSpace* NMXmlParserExperiment::getAtomSpace(){
    return atomSpace;
}

bool NMXmlParserExperiment::checkExp0()
{
	soccer = atomSpace->getHandle(WORD_NODE, "soccer");
	sport = atomSpace->getHandle(WORD_NODE, "sport");

	TS_ASSERT(soccer != NULL);
	TS_ASSERT(sport != NULL);
	if ((!soccer) || (!sport)){
		return(false);
	}

	std::vector<Handle> handles;
	atomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);

	TS_ASSERT(handles.size() == 1);
	if (handles.size() != 1){
		return(false);
	}
	Atom *atom = TLB::getAtom((Handle)handles[0]);
	link_sport_socker = handles[0];

	TS_ASSERT((atom->getOutgoingSet()[0]) == soccer);
	TS_ASSERT((atom->getOutgoingSet()[1]) == sport);
	if ((atom->getOutgoingSet()[0] != soccer) ||
		(atom->getOutgoingSet()[1] != sport)){
		return(false);
	}

	return(true);
}

bool NMXmlParserExperiment::checkExp1(){

	soccer = atomSpace->getHandle(WORD_NODE, "soccer");
	sport = atomSpace->getHandle(WORD_NODE, "sport");

	TS_ASSERT(soccer != NULL);
	TS_ASSERT(sport != NULL);
	if ((!soccer) || (!sport)){
		return(false);
	}

	HandleEntry* entry = atomSpace->getAtomTable().getHandleSet(INHERITANCE_LINK, true);

	std::vector<Handle> handles;
	atomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);
	TS_ASSERT(handles.size() == 0);

	atomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);
	TS_ASSERT(handles.size() == 2);
	if (handles.size() != 2){
		return(false);
	}

	TS_ASSERT(entry == NULL);

	link_sport_socker = NULL;
	Atom *atom = NULL;
	std::vector<Handle>::iterator it;
	for(it = handles.begin(); it != handles.end(); it++){
		atom = TLB::getAtom((Handle)*it);
		if (atom->getIncomingSet()->getSize() == 1){
			TS_ASSERT(link_sport_socker == NULL);
			link_sport_socker = (Handle)*it;
		}
	}
	handles.clear();

	TS_ASSERT(link_sport_socker != NULL);
	TS_ASSERT((atom->getOutgoingSet()[0]) == soccer);
	TS_ASSERT((atom->getOutgoingSet()[1]) == sport);
	if ((atom->getOutgoingSet()[0] != soccer) ||
		(atom->getOutgoingSet()[1] != sport)){
		return(false);
	}

	atomSpace->getHandleSet(back_inserter(handles), MEMBER_LINK, true);

	TS_ASSERT(handles.size() == 1);
	if (handles.size() != 1){
		return(false);
	}
	atom = TLB::getAtom((Handle)handles[0]);
	hihger_order_link = handles[0];

	TS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);
	TS_ASSERT(atom->getOutgoingSet()[1] == soccer);
	if ((atom->getOutgoingSet()[0] != link_sport_socker) ||
		(atom->getOutgoingSet()[1] != soccer)){
		return(false);
	}

/*
	entry = atomSpace->getAtomTable()->getHandleSet(INHERITANCE_LINK, true);

	TS_ASSERT(entry->getSize() == 2);
	if (entry->getSize() != 2){
		delete entry;
		return(false);
	}

	link_sport_socker = NULL;
	Atom *atom = NULL;

	HandleEntry *it = entry;
	while (it){
		atom = it->getAtom();
		if (atom->getIncomingSet()->getSize() == 1){
			TS_ASSERT(link_sport_socker == NULL);
			link_sport_socker = it->handle;
		}
		it = it->next;
	}
	delete entry;

	TS_ASSERT(link_sport_socker != NULL);

	TS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[0]) == soccer);
	TS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[1]) == sport);
	if ((atom->getOutgoingSet()[0] != soccer) ||
		(atom->getOutgoingSet()[1] != sport)){
		return(false);
	}

	entry = atomSpace->getAtomTable()->getHandleSet(MEMBER_LINK, true);

	TS_ASSERT(entry->getSize() == 1);
	if (entry->getSize() != 1){
		delete entry;
		return(false);
	}
	atom = entry->getAtom();
	hihger_order_link = entry->handle;
	delete entry;

	TS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);
	TS_ASSERT(atom->getOutgoingSet()[1] == soccer);
	if ((atom->getOutgoingSet()[0] != link_sport_socker) ||
		(atom->getOutgoingSet()[1] != soccer)){
		return(false);
	}
*/
	return(true);
}

char *NMXmlParserExperiment::expContents[NNMXMLXMLEXPERIMENTS] = {
"<?xml version=\"1.0\"?> \
<list> \
<tagdescription> \
<tag name=\"WordNode\" value=\"WordNode\"/> \
<tag name=\"InheritanceLink\" value=\"InheritanceLink\"/> \
</tagdescription> \
<WordNode name=\"soccer\" timestamp=\"3422826\"/> \
<WordNode name=\"sport\" timestamp=\"3422826\"/> \
<InheritanceLink hyp=\"hyp_1\" strength=\"1.0\" confidence=\"0.95\"> \
<Element name=\"soccer\" class=\"WordNode\"/> \
<Element name=\"sport\" class=\"WordNode\"/> \
</InheritanceLink> \
<InheritanceLink hyp=\"hyp_1\" strength=\"1.0\" confidence=\"0.95\"> \
<Element name=\"soccer\" class=\"WordNode\"/> \
<Element name=\"sport\" class=\"WordNode\"/> \
</InheritanceLink> \
</list>"
/* UNCOMMENT TO USE HYPOTHETICAL ATOMTABLE
,
"<?xml version=\"1.0\"?> \
<list> \
<tagdescription> \
<tag name=\"WordNode\" value=\"WordNode\"/> \
<tag name=\"InheritanceLink\" value=\"InheritanceLink\"/> \
<tag name=\"MemberLink\" value=\"MemberLink\"/> \
</tagdescription> \
<WordNode name=\"soccer\" timestamp=\"3422827\"/> \
<WordNode name=\"sport\" timestamp=\"3422827\"/> \
<MemberLink strength=\"0.50\" confidence=\"0.80\"> \
  <InheritanceLink hyp=\"hyp_1\" strength=\"1.0\" confidence=\"0.95\"> \
    <Element name=\"soccer\" class=\"WordNode\"/> \
    <Element name=\"sport\" class=\"WordNode\"/> \
  </InheritanceLink> \
  <Element name=\"soccer\" class=\"WordNode\"/> \
</MemberLink> \
<InheritanceLink hyp=\"hyp_2\" strength=\"1.0\" confidence=\"0.95\"> \
  <Element name=\"soccer\" class=\"WordNode\"/> \
  <Element name=\"sport\" class=\"WordNode\"/> \
</InheritanceLink> \
</list>"
*/
};
<commit_msg>fix a few places where handles are used inappropriately<commit_after>/**
 * NMXmlParserExperiment.cc
 *
 *
 * Copyright(c) 2003 Rodrigo Barra
 * All rights reserved.
 */
#include <NMXmlParserExperiment.h>
#include <ClassServer.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exceptions.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <Link.h>
#include <TLB.h>
#include <cxxtest/TestSuite.h>

#include <cstdlib>
using namespace std;

#ifdef WIN32
#include <fcntl.h>
#include <io.h>
#define _S_IREAD 256
#define _S_IWRITE 128
int mkstemp(char *tmpl)
{
	int ret=-1;
	_mktemp(tmpl);
	ret=open(tmpl,O_RDWR|O_BINARY|O_CREAT|O_EXCL|_O_SHORT_LIVED, _S_IREAD|_S_IWRITE);
	return ret;
}

#endif

bool NMXmlParserExperiment::noCheck = false;
char *NMXmlParserExperiment::currentFileName = NULL;
int NMXmlParserExperiment::currentExperiment = -1;

Handle NMXmlParserExperiment::sport = UNDEFINED_HANDLE;
Handle NMXmlParserExperiment::soccer = UNDEFINED_HANDLE;
Handle NMXmlParserExperiment::link_sport_socker = UNDEFINED_HANDLE;
Handle NMXmlParserExperiment::hihger_order_link = UNDEFINED_HANDLE;
AtomSpace* NMXmlParserExperiment::atomSpace = NULL;

void NMXmlParserExperiment::initStaticVars() {
	NMXmlParserExperiment::noCheck = false;
	NMXmlParserExperiment::currentFileName = NULL;
	NMXmlParserExperiment::currentExperiment = -1;

	NMXmlParserExperiment::sport = UNDEFINED_HANDLE;
	NMXmlParserExperiment::soccer = UNDEFINED_HANDLE;
	NMXmlParserExperiment::link_sport_socker = UNDEFINED_HANDLE;
	NMXmlParserExperiment::hihger_order_link = UNDEFINED_HANDLE;
	NMXmlParserExperiment::atomSpace = NULL;
}

int NMXmlParserExperiment::getNExperiments(){
	return(NNMXMLXMLEXPERIMENTS);
}

void NMXmlParserExperiment::createExperiment(int exp, AtomSpace* as){
	if ((exp < 0) || (exp > NNMXMLXMLEXPERIMENTS)){
	    throw new RuntimeException(TRACE_INFO, "Invalid Experiment\n");
	}

	if (currentExperiment != -1){
		throw new RuntimeException(TRACE_INFO, "Tried to start a new experiment without destroying the last one");
	}

	currentExperiment = exp;

	//currentFileName = strdup("/var/tmp/xmltest.XXXXXX");
	currentFileName = strdup("xmltest.XXXXXX");
    printf("just allocated currentFileName = %s\n", currentFileName);

	int fd = mkstemp(currentFileName);
    printf("after mkstemp currentFileName = %s\n", currentFileName);

	if (fd == -1){
		throw new RuntimeException(TRACE_INFO, "Could not create temporary file\n");
	}

	write(fd, expContents[exp%2], strlen(expContents[exp%2]));

	close(fd);

    if (atomSpace) delete atomSpace;
    atomSpace = as;
}

bool NMXmlParserExperiment::checkExperiment(){
    if (noCheck) {
        return (true);
    }
	if (currentExperiment == -1){
		return(true);
	}
	switch (currentExperiment){
	case 0:
		return(checkExp0());
		break;
	case 1:
		return(checkExp1());
		break;
	}
	return(false);
}

AtomSpace* NMXmlParserExperiment::destroyExperiment(bool cleanup){
	if (currentExperiment == -1){
		return atomSpace;
	}
    printf("currentFileName = %s\n", currentFileName);
	remove(currentFileName);
#ifndef WIN32 // For some reason, this causes error on Windows
	free(currentFileName);
#endif
	currentFileName = NULL;
	currentExperiment = -1;
    if (cleanup) {
    	cleanupAtomSpace();
    }
    return atomSpace;
}

AtomSpace* NMXmlParserExperiment::cleanupAtomSpace(){
    delete atomSpace;
    atomSpace = new AtomSpace();
    return atomSpace;
}

AtomSpace* NMXmlParserExperiment::getAtomSpace(){
    return atomSpace;
}

bool NMXmlParserExperiment::checkExp0()
{
	soccer = atomSpace->getHandle(WORD_NODE, "soccer");
	sport = atomSpace->getHandle(WORD_NODE, "sport");

	TS_ASSERT(TLB::isValidHandle(soccer));
	TS_ASSERT(TLB::isValidHandle(sport));
	if (TLB::isInvalidHandle(soccer) || TLB::isInvalidHandle(sport)){
		return(false);
	}

	std::vector<Handle> handles;
	atomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);

	TS_ASSERT(handles.size() == 1);
	if (handles.size() != 1){
		return(false);
	}
	Atom *atom = TLB::getAtom(handles[0]);
	link_sport_socker = handles[0];

	TS_ASSERT((atom->getOutgoingSet()[0]) == soccer);
	TS_ASSERT((atom->getOutgoingSet()[1]) == sport);
	if ((atom->getOutgoingSet()[0] != soccer) ||
		(atom->getOutgoingSet()[1] != sport)){
		return(false);
	}

	return(true);
}

bool NMXmlParserExperiment::checkExp1(){

	soccer = atomSpace->getHandle(WORD_NODE, "soccer");
	sport = atomSpace->getHandle(WORD_NODE, "sport");

	TS_ASSERT(TLB::isValidHandle(soccer));
	TS_ASSERT(TLB::isValidHandle(sport));
	if (TLB::isInvalidHandle(soccer) || TLB::isInvalidHandle(sport)){
		return(false);
	}

	HandleEntry* entry = atomSpace->getAtomTable().getHandleSet(INHERITANCE_LINK, true);

	std::vector<Handle> handles;
	atomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);
	TS_ASSERT(handles.size() == 0);

	atomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);
	TS_ASSERT(handles.size() == 2);
	if (handles.size() != 2){
		return(false);
	}

	TS_ASSERT(entry == NULL);

	link_sport_socker = NULL;
	Atom *atom = NULL;
	std::vector<Handle>::iterator it;
	for(it = handles.begin(); it != handles.end(); it++){
		atom = TLB::getAtom((Handle)*it);
		if (atom->getIncomingSet()->getSize() == 1){
			TS_ASSERT(TLB::isInvalidHandle(link_sport_socker));
			link_sport_socker = *it;
		}
	}
	handles.clear();

	TS_ASSERT(TLB::isValidHandle(link_sport_socker));
	TS_ASSERT((atom->getOutgoingSet()[0]) == soccer);
	TS_ASSERT((atom->getOutgoingSet()[1]) == sport);
	if ((atom->getOutgoingSet()[0] != soccer) ||
		(atom->getOutgoingSet()[1] != sport)){
		return(false);
	}

	atomSpace->getHandleSet(back_inserter(handles), MEMBER_LINK, true);

	TS_ASSERT(handles.size() == 1);
	if (handles.size() != 1){
		return(false);
	}
	atom = TLB::getAtom(handles[0]);
	hihger_order_link = handles[0];

	TS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);
	TS_ASSERT(atom->getOutgoingSet()[1] == soccer);
	if ((atom->getOutgoingSet()[0] != link_sport_socker) ||
		(atom->getOutgoingSet()[1] != soccer)){
		return(false);
	}

/*
	entry = atomSpace->getAtomTable()->getHandleSet(INHERITANCE_LINK, true);

	TS_ASSERT(entry->getSize() == 2);
	if (entry->getSize() != 2){
		delete entry;
		return(false);
	}

	link_sport_socker = NULL;
	Atom *atom = NULL;

	HandleEntry *it = entry;
	while (it){
		atom = it->getAtom();
		if (atom->getIncomingSet()->getSize() == 1){
			TS_ASSERT(TLB::isInvalidHandle(link_sport_socker));
			link_sport_socker = it->handle;
		}
		it = it->next;
	}
	delete entry;

	TS_ASSERT(link_sport_socker != NULL);

	TS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[0]) == soccer);
	TS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[1]) == sport);
	if ((atom->getOutgoingSet()[0] != soccer) ||
		(atom->getOutgoingSet()[1] != sport)){
		return(false);
	}

	entry = atomSpace->getAtomTable()->getHandleSet(MEMBER_LINK, true);

	TS_ASSERT(entry->getSize() == 1);
	if (entry->getSize() != 1){
		delete entry;
		return(false);
	}
	atom = entry->getAtom();
	hihger_order_link = entry->handle;
	delete entry;

	TS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);
	TS_ASSERT(atom->getOutgoingSet()[1] == soccer);
	if ((atom->getOutgoingSet()[0] != link_sport_socker) ||
		(atom->getOutgoingSet()[1] != soccer)){
		return(false);
	}
*/
	return(true);
}

char *NMXmlParserExperiment::expContents[NNMXMLXMLEXPERIMENTS] = {
"<?xml version=\"1.0\"?> \
<list> \
<tagdescription> \
<tag name=\"WordNode\" value=\"WordNode\"/> \
<tag name=\"InheritanceLink\" value=\"InheritanceLink\"/> \
</tagdescription> \
<WordNode name=\"soccer\" timestamp=\"3422826\"/> \
<WordNode name=\"sport\" timestamp=\"3422826\"/> \
<InheritanceLink hyp=\"hyp_1\" strength=\"1.0\" confidence=\"0.95\"> \
<Element name=\"soccer\" class=\"WordNode\"/> \
<Element name=\"sport\" class=\"WordNode\"/> \
</InheritanceLink> \
<InheritanceLink hyp=\"hyp_1\" strength=\"1.0\" confidence=\"0.95\"> \
<Element name=\"soccer\" class=\"WordNode\"/> \
<Element name=\"sport\" class=\"WordNode\"/> \
</InheritanceLink> \
</list>"
/* UNCOMMENT TO USE HYPOTHETICAL ATOMTABLE
,
"<?xml version=\"1.0\"?> \
<list> \
<tagdescription> \
<tag name=\"WordNode\" value=\"WordNode\"/> \
<tag name=\"InheritanceLink\" value=\"InheritanceLink\"/> \
<tag name=\"MemberLink\" value=\"MemberLink\"/> \
</tagdescription> \
<WordNode name=\"soccer\" timestamp=\"3422827\"/> \
<WordNode name=\"sport\" timestamp=\"3422827\"/> \
<MemberLink strength=\"0.50\" confidence=\"0.80\"> \
  <InheritanceLink hyp=\"hyp_1\" strength=\"1.0\" confidence=\"0.95\"> \
    <Element name=\"soccer\" class=\"WordNode\"/> \
    <Element name=\"sport\" class=\"WordNode\"/> \
  </InheritanceLink> \
  <Element name=\"soccer\" class=\"WordNode\"/> \
</MemberLink> \
<InheritanceLink hyp=\"hyp_2\" strength=\"1.0\" confidence=\"0.95\"> \
  <Element name=\"soccer\" class=\"WordNode\"/> \
  <Element name=\"sport\" class=\"WordNode\"/> \
</InheritanceLink> \
</list>"
*/
};
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreRoot.h"
#include "OgreLogManager.h"
#include "OgreRenderSystem.h"
#include "OgreImageCodec.h"
#include "OgreException.h"
#include "OgreStringConverter.h"
#include "OgreWin32RenderTexture.h"
#include "OgreWin32GLSupport.h"
#include "OgreWin32Context.h"

namespace Ogre {

     Win32PBuffer::Win32PBuffer(PixelComponentType format, size_t width, size_t height):
        GLPBuffer(format, width, height),
        mContext(0)
    {
        createPBuffer();

        // Create context
        mContext = new Win32Context(mHDC, mGlrc);
#if 0
        if(mUseBind)
        {
            // Bind texture
            glBindTextureEXT(GL_TEXTURE_2D, static_cast<GLTexture*>(mTexture.get())->getGLID());
            wglBindTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);
        }
#endif
    }
     Win32PBuffer::~Win32PBuffer()
    {
#if 0
        if(mUseBind)
        {
            // Unbind texture
            glBindTextureEXT(GL_TEXTURE_2D,
                static_cast<GLTexture*>(mTexture.get())->getGLID());
            glBindTextureEXT(GL_TEXTURE_2D,
                static_cast<GLTexture*>(mTexture.get())->getGLID());
            wglReleaseTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);
        }
#endif
        // Unregister and destroy mContext
        delete mContext;

        // Destroy pbuffer
        destroyPBuffer();
    }

    void Win32PBuffer::createPBuffer()
    {

        // Process format
        int bits=0;
        bool isFloat=false;
#if 0
        bool hasAlpha=true;
#endif
        switch(mFormat)
        {
            case PCT_BYTE:
                bits=8; isFloat=false;
                break;
            case PCT_SHORT:
                bits=16; isFloat=false;
                break;
            case PCT_FLOAT16:
                bits=16; isFloat=true;
                break;
            case PCT_FLOAT32:
                bits=32; isFloat=true;
                break;
            default: break;
        };
        LogManager::getSingleton().logMessage(
            " Win32PBuffer::Creating PBuffer of format bits="+
            StringConverter::toString(bits)+
            " float="+StringConverter::toString(isFloat)
        );

        HDC old_hdc = wglGetCurrentDC();
        HGLRC old_context = wglGetCurrentContext();

        // Bind to RGB or RGBA texture
        int bttype = 0;
#if 0
        if(mUseBind)
        {
            // Only provide bind type when actually binding
            bttype = PixelUtil::hasAlpha(mInternalFormat)?
                WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB;
        }
        int texformat = hasAlpha?
            WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB;
#endif
        // Make a float buffer?
        int pixeltype = isFloat?
            WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB;

        int attrib[] = {
            WGL_RED_BITS_ARB,bits,
            WGL_GREEN_BITS_ARB,bits,
            WGL_BLUE_BITS_ARB,bits,
            WGL_ALPHA_BITS_ARB,bits,
            WGL_STENCIL_BITS_ARB,1,
            WGL_DEPTH_BITS_ARB,15,
            WGL_DRAW_TO_PBUFFER_ARB,true,
            WGL_SUPPORT_OPENGL_ARB,true,
            WGL_PIXEL_TYPE_ARB,pixeltype,
            //WGL_DOUBLE_BUFFER_ARB,true,
            //WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, // Make sure it is accelerated
            bttype,true, // must be last, as bttype can be zero
            0
        };
        int pattrib_default[] = {
            0
        };
#if 0
        int pattrib_bind[] = {
            WGL_TEXTURE_FORMAT_ARB, texformat,
            WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,
            WGL_PBUFFER_LARGEST_ARB, true,
            0
        };
#endif
        int format;
        unsigned int count;

        // Choose suitable pixel format
        wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count);
        if(count == 0)
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglChoosePixelFormatARB() failed", " Win32PBuffer::createPBuffer");

        // Analyse pixel format
        const int piAttributes[]={
                WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB,
                WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB
        };
        int piValues[sizeof(piAttributes)/sizeof(const int)];
        wglGetPixelFormatAttribivARB(old_hdc,format,0,sizeof(piAttributes)/sizeof(const int),piAttributes,piValues);

        LogManager::getSingleton().stream()
            << " Win32PBuffer::PBuffer -- Chosen pixel format rgba="
            << piValues[0] << ","
            << piValues[1] << ","
            << piValues[2] << ","
            << piValues[3]
            << " depth=" << piValues[4]
            << " stencil=" << piValues[5];

        mPBuffer = wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default);
        if(!mPBuffer)
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreatePbufferARB() failed", " Win32PBuffer::createPBuffer");

        mHDC = wglGetPbufferDCARB(mPBuffer);
        if(!mHDC) {
            wglDestroyPbufferARB(mPBuffer);
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglGetPbufferDCARB() failed", " Win32PBuffer::createPBuffer");
        }

        mGlrc = wglCreateContext(mHDC);
        if(!mGlrc) {
            wglReleasePbufferDCARB(mPBuffer,mHDC);
            wglDestroyPbufferARB(mPBuffer);
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext() failed", " Win32PBuffer::createPBuffer");
        }

        if(!wglShareLists(old_context,mGlrc)) {
            wglDeleteContext(mGlrc);
            wglReleasePbufferDCARB(mPBuffer,mHDC);
            wglDestroyPbufferARB(mPBuffer);
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed", " Win32PBuffer::createPBuffer");
        }

        // Query real width and height
        int iWidth, iHeight;
        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth);
        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight);
        mWidth = iWidth;
        mHeight = iHeight;
        LogManager::getSingleton().stream()
            << "Win32RenderTexture::PBuffer created -- Real dimensions "
            << mWidth << "x" << mHeight;
    }
    void Win32PBuffer::destroyPBuffer()
    {
        wglDeleteContext(mGlrc);
        wglReleasePbufferDCARB(mPBuffer,mHDC);
        wglDestroyPbufferARB(mPBuffer);
    }

}
<commit_msg>GLSupport: disable PBuffers on Win32 for now<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreRoot.h"
#include "OgreLogManager.h"
#include "OgreRenderSystem.h"
#include "OgreImageCodec.h"
#include "OgreException.h"
#include "OgreStringConverter.h"
#include "OgreWin32RenderTexture.h"
#include "OgreWin32GLSupport.h"
#include "OgreWin32Context.h"

namespace Ogre {

     Win32PBuffer::Win32PBuffer(PixelComponentType format, size_t width, size_t height):
        GLPBuffer(format, width, height),
        mContext(0)
    {
        createPBuffer();

        // Create context
        mContext = new Win32Context(mHDC, mGlrc);
#if 0
        if(mUseBind)
        {
            // Bind texture
            glBindTextureEXT(GL_TEXTURE_2D, static_cast<GLTexture*>(mTexture.get())->getGLID());
            wglBindTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);
        }
#endif
    }
     Win32PBuffer::~Win32PBuffer()
    {
#if 0
        if(mUseBind)
        {
            // Unbind texture
            glBindTextureEXT(GL_TEXTURE_2D,
                static_cast<GLTexture*>(mTexture.get())->getGLID());
            glBindTextureEXT(GL_TEXTURE_2D,
                static_cast<GLTexture*>(mTexture.get())->getGLID());
            wglReleaseTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);
        }
#endif
        // Unregister and destroy mContext
        delete mContext;

        // Destroy pbuffer
        destroyPBuffer();
    }

    void Win32PBuffer::createPBuffer()
    {

        // Process format
        int bits=0;
        bool isFloat=false;
#if 0
        bool hasAlpha=true;
#endif
        switch(mFormat)
        {
            case PCT_BYTE:
                bits=8; isFloat=false;
                break;
            case PCT_SHORT:
                bits=16; isFloat=false;
                break;
            case PCT_FLOAT16:
                bits=16; isFloat=true;
                break;
            case PCT_FLOAT32:
                bits=32; isFloat=true;
                break;
            default: break;
        };
        LogManager::getSingleton().logMessage(
            " Win32PBuffer::Creating PBuffer of format bits="+
            StringConverter::toString(bits)+
            " float="+StringConverter::toString(isFloat)
        );

        HDC old_hdc = wglGetCurrentDC();
        HGLRC old_context = wglGetCurrentContext();

        // Bind to RGB or RGBA texture
        int bttype = 0;
#if 0
        if(mUseBind)
        {
            // Only provide bind type when actually binding
            bttype = PixelUtil::hasAlpha(mInternalFormat)?
                WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB;
        }
        int texformat = hasAlpha?
            WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB;
#endif
        // Make a float buffer?
        int pixeltype = isFloat?
            WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB;

        int attrib[] = {
            WGL_RED_BITS_ARB,bits,
            WGL_GREEN_BITS_ARB,bits,
            WGL_BLUE_BITS_ARB,bits,
            WGL_ALPHA_BITS_ARB,bits,
            WGL_STENCIL_BITS_ARB,1,
            WGL_DEPTH_BITS_ARB,15,
            WGL_DRAW_TO_PBUFFER_ARB,true,
            WGL_SUPPORT_OPENGL_ARB,true,
            WGL_PIXEL_TYPE_ARB,pixeltype,
            //WGL_DOUBLE_BUFFER_ARB,true,
            //WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, // Make sure it is accelerated
            bttype,true, // must be last, as bttype can be zero
            0
        };
        int pattrib_default[] = {
            0
        };
#if 0
        int pattrib_bind[] = {
            WGL_TEXTURE_FORMAT_ARB, texformat,
            WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,
            WGL_PBUFFER_LARGEST_ARB, true,
            0
        };
#endif
        int format;
        unsigned int count;

        PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");

        // Choose suitable pixel format
        wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count);
        if(count == 0)
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglChoosePixelFormatARB() failed", " Win32PBuffer::createPBuffer");

        // Analyse pixel format
        const int piAttributes[]={
                WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB,
                WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB
        };
        int piValues[sizeof(piAttributes)/sizeof(const int)];

        PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribivARB");
        wglGetPixelFormatAttribiv(old_hdc,format,0,sizeof(piAttributes)/sizeof(const int),piAttributes,piValues);

        LogManager::getSingleton().stream()
            << " Win32PBuffer::PBuffer -- Chosen pixel format rgba="
            << piValues[0] << ","
            << piValues[1] << ","
            << piValues[2] << ","
            << piValues[3]
            << " depth=" << piValues[4]
            << " stencil=" << piValues[5];
        // FIXME lookup procaddress
        mPBuffer = 0;//wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default);
        if(!mPBuffer)
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreatePbufferARB() failed", " Win32PBuffer::createPBuffer");
#if 0
        mHDC = wglGetPbufferDCARB(mPBuffer);
        if(!mHDC) {
            wglDestroyPbufferARB(mPBuffer);
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglGetPbufferDCARB() failed", " Win32PBuffer::createPBuffer");
        }

        mGlrc = wglCreateContext(mHDC);
        if(!mGlrc) {
            wglReleasePbufferDCARB(mPBuffer,mHDC);
            wglDestroyPbufferARB(mPBuffer);
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext() failed", " Win32PBuffer::createPBuffer");
        }

        if(!wglShareLists(old_context,mGlrc)) {
            wglDeleteContext(mGlrc);
            wglReleasePbufferDCARB(mPBuffer,mHDC);
            wglDestroyPbufferARB(mPBuffer);
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed", " Win32PBuffer::createPBuffer");
        }

        // Query real width and height
        int iWidth, iHeight;
        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth);
        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight);
        mWidth = iWidth;
        mHeight = iHeight;
        LogManager::getSingleton().stream()
            << "Win32RenderTexture::PBuffer created -- Real dimensions "
            << mWidth << "x" << mHeight;
#endif
    }
    void Win32PBuffer::destroyPBuffer()
    {
        wglDeleteContext(mGlrc);
        // FIXME lookup procaddress
#if 0
        wglReleasePbufferDCARB(mPBuffer,mHDC);
        wglDestroyPbufferARB(mPBuffer);
#endif
    }

}
<|endoftext|>