<commit_before>/*
 * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
 *
 * 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.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * 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 "core/inspector/InspectorFrontendHost.h"

#include "bindings/core/v8/ScriptFunctionCall.h"
#include "bindings/core/v8/ScriptState.h"
#include "core/clipboard/Pasteboard.h"
#include "core/dom/ExecutionContext.h"
#include "core/events/Event.h"
#include "core/events/EventTarget.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendClient.h"
#include "core/loader/FrameLoader.h"
#include "core/page/ContextMenuController.h"
#include "core/page/ContextMenuProvider.h"
#include "core/page/Page.h"
#include "core/rendering/RenderTheme.h"
#include "platform/ContextMenu.h"
#include "platform/ContextMenuItem.h"
#include "platform/SharedBuffer.h"
#include "platform/UserGestureIndicator.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceRequest.h"
#include "platform/network/ResourceResponse.h"

namespace blink {

class FrontendMenuProvider FINAL : public ContextMenuProvider {
public:
    static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)
    {
        return adoptRef(new FrontendMenuProvider(frontendHost, frontendApiObject, items));
    }

    void disconnect()
    {
        m_frontendApiObject = ScriptValue();
        m_frontendHost = 0;
    }

private:
    FrontendMenuProvider(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)
        : m_frontendHost(frontendHost)
        , m_frontendApiObject(frontendApiObject)
        , m_items(items)
    {
    }

    virtual ~FrontendMenuProvider()
    {
        contextMenuCleared();
    }

    virtual void populateContextMenu(ContextMenu* menu) OVERRIDE
    {
        for (size_t i = 0; i < m_items.size(); ++i)
            menu->appendItem(m_items[i]);
    }

    virtual void contextMenuItemSelected(const ContextMenuItem* item) OVERRIDE
    {
        if (m_frontendHost) {
            UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
            int itemNumber = item->action() - ContextMenuItemBaseCustomTag;

            ScriptFunctionCall function(m_frontendApiObject, "contextMenuItemSelected");
            function.appendArgument(itemNumber);
            function.call();
        }
    }

    virtual void contextMenuCleared() OVERRIDE
    {
        if (m_frontendHost) {
            ScriptFunctionCall function(m_frontendApiObject, "contextMenuCleared");
            function.call();

            m_frontendHost->m_menuProvider = 0;
        }
        m_items.clear();
        m_frontendHost = 0;
    }

    InspectorFrontendHost* m_frontendHost;
    ScriptValue m_frontendApiObject;
    Vector<ContextMenuItem> m_items;
};

InspectorFrontendHost::InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage)
    : m_client(client)
    , m_frontendPage(frontendPage)
    , m_menuProvider(0)
{
    ScriptWrappable::init(this);
}

InspectorFrontendHost::~InspectorFrontendHost()
{
    ASSERT(!m_client);
}

void InspectorFrontendHost::trace(Visitor* visitor)
{
    visitor->trace(m_frontendPage);
}

void InspectorFrontendHost::disconnectClient()
{
    m_client = 0;
    if (m_menuProvider)
        m_menuProvider->disconnect();
    m_frontendPage = nullptr;
}

void InspectorFrontendHost::setZoomFactor(float zoom)
{
    m_frontendPage->deprecatedLocalMainFrame()->setPageAndTextZoomFactors(zoom, 1);
}

float InspectorFrontendHost::zoomFactor()
{
    return m_frontendPage->deprecatedLocalMainFrame()->pageZoomFactor();
}

void InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)
{
    m_frontendPage->inspectorController().setInjectedScriptForOrigin(origin, script);
}

void InspectorFrontendHost::copyText(const String& text)
{
    Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace);
}

static String escapeUnicodeNonCharacters(const String& str)
{
    const UChar nonChar = 0xD800;

    unsigned i = 0;
    while (i < str.length() && str[i] < nonChar)
        ++i;
    if (i == str.length())
        return str;

    StringBuilder dst;
    dst.append(str, 0, i);
    for (; i < str.length(); ++i) {
        UChar c = str[i];
        if (c >= nonChar) {
            unsigned symbol = static_cast<unsigned>(c);
            String symbolCode = String::format("\\u%04X", symbol);
            dst.append(symbolCode);
        } else {
            dst.append(c);
        }
    }
    return dst.toString();
}

void InspectorFrontendHost::sendMessageToBackend(const String& message)
{
    if (m_client)
        m_client->sendMessageToBackend(escapeUnicodeNonCharacters(message));
}

void InspectorFrontendHost::sendMessageToEmbedder(const String& message)
{
    if (m_client)
        m_client->sendMessageToEmbedder(escapeUnicodeNonCharacters(message));
}

void InspectorFrontendHost::showContextMenu(Page* page, float x, float y, const Vector<ContextMenuItem>& items)
{
    ASSERT(m_frontendPage);
    ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());
    ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject("InspectorFrontendAPI");
    ASSERT(frontendApiObject.isObject());

    RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);
    m_menuProvider = menuProvider.get();
    float zoom = page->deprecatedLocalMainFrame()->pageZoomFactor();
    page->inspectorController().showContextMenu(x * zoom, y * zoom, menuProvider);
}

void InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items)
{
    if (!event)
        return;

    ASSERT(m_frontendPage);
    ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());
    ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject("InspectorFrontendAPI");
    ASSERT(frontendApiObject.isObject());

    Page* targetPage = m_frontendPage;
    if (event->target() && event->target()->executionContext() && event->target()->executionContext()->executingWindow()) {
        LocalDOMWindow* window = event->target()->executionContext()->executingWindow();
        if (window->document() && window->document()->page())
            targetPage = window->document()->page();
    }

    RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);
    targetPage->contextMenuController().showContextMenu(event, menuProvider);
    m_menuProvider = menuProvider.get();
}

String InspectorFrontendHost::getSelectionBackgroundColor()
{
    return RenderTheme::theme().activeSelectionBackgroundColor().serialized();
}

String InspectorFrontendHost::getSelectionForegroundColor()
{
    return RenderTheme::theme().activeSelectionForegroundColor().serialized();
}

bool InspectorFrontendHost::isUnderTest()
{
    return m_client && m_client->isUnderTest();
}

bool InspectorFrontendHost::isHostedMode()
{
    return false;
}

} // namespace blink
<commit_msg>[DevTools] Speculative fix for crash in InspectorFrontendHost::zoomFactor.<commit_after>/*
 * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
 *
 * 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.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * 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 "core/inspector/InspectorFrontendHost.h"

#include "bindings/core/v8/ScriptFunctionCall.h"
#include "bindings/core/v8/ScriptState.h"
#include "core/clipboard/Pasteboard.h"
#include "core/dom/ExecutionContext.h"
#include "core/events/Event.h"
#include "core/events/EventTarget.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendClient.h"
#include "core/loader/FrameLoader.h"
#include "core/page/ContextMenuController.h"
#include "core/page/ContextMenuProvider.h"
#include "core/page/Page.h"
#include "core/rendering/RenderTheme.h"
#include "platform/ContextMenu.h"
#include "platform/ContextMenuItem.h"
#include "platform/SharedBuffer.h"
#include "platform/UserGestureIndicator.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceRequest.h"
#include "platform/network/ResourceResponse.h"

namespace blink {

class FrontendMenuProvider FINAL : public ContextMenuProvider {
public:
    static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)
    {
        return adoptRef(new FrontendMenuProvider(frontendHost, frontendApiObject, items));
    }

    void disconnect()
    {
        m_frontendApiObject = ScriptValue();
        m_frontendHost = 0;
    }

private:
    FrontendMenuProvider(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)
        : m_frontendHost(frontendHost)
        , m_frontendApiObject(frontendApiObject)
        , m_items(items)
    {
    }

    virtual ~FrontendMenuProvider()
    {
        contextMenuCleared();
    }

    virtual void populateContextMenu(ContextMenu* menu) OVERRIDE
    {
        for (size_t i = 0; i < m_items.size(); ++i)
            menu->appendItem(m_items[i]);
    }

    virtual void contextMenuItemSelected(const ContextMenuItem* item) OVERRIDE
    {
        if (m_frontendHost) {
            UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
            int itemNumber = item->action() - ContextMenuItemBaseCustomTag;

            ScriptFunctionCall function(m_frontendApiObject, "contextMenuItemSelected");
            function.appendArgument(itemNumber);
            function.call();
        }
    }

    virtual void contextMenuCleared() OVERRIDE
    {
        if (m_frontendHost) {
            ScriptFunctionCall function(m_frontendApiObject, "contextMenuCleared");
            function.call();

            m_frontendHost->m_menuProvider = 0;
        }
        m_items.clear();
        m_frontendHost = 0;
    }

    InspectorFrontendHost* m_frontendHost;
    ScriptValue m_frontendApiObject;
    Vector<ContextMenuItem> m_items;
};

InspectorFrontendHost::InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage)
    : m_client(client)
    , m_frontendPage(frontendPage)
    , m_menuProvider(0)
{
    ScriptWrappable::init(this);
}

InspectorFrontendHost::~InspectorFrontendHost()
{
    ASSERT(!m_client);
}

void InspectorFrontendHost::trace(Visitor* visitor)
{
    visitor->trace(m_frontendPage);
}

void InspectorFrontendHost::disconnectClient()
{
    m_client = 0;
    if (m_menuProvider)
        m_menuProvider->disconnect();
    m_frontendPage = nullptr;
}

void InspectorFrontendHost::setZoomFactor(float zoom)
{
    if (LocalFrame* frame = m_frontendPage->deprecatedLocalMainFrame())
        frame->setPageAndTextZoomFactors(zoom, 1);
}

float InspectorFrontendHost::zoomFactor()
{
    if (LocalFrame* frame = m_frontendPage->deprecatedLocalMainFrame())
        return frame->pageZoomFactor();
    return 1;
}

void InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)
{
    m_frontendPage->inspectorController().setInjectedScriptForOrigin(origin, script);
}

void InspectorFrontendHost::copyText(const String& text)
{
    Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace);
}

static String escapeUnicodeNonCharacters(const String& str)
{
    const UChar nonChar = 0xD800;

    unsigned i = 0;
    while (i < str.length() && str[i] < nonChar)
        ++i;
    if (i == str.length())
        return str;

    StringBuilder dst;
    dst.append(str, 0, i);
    for (; i < str.length(); ++i) {
        UChar c = str[i];
        if (c >= nonChar) {
            unsigned symbol = static_cast<unsigned>(c);
            String symbolCode = String::format("\\u%04X", symbol);
            dst.append(symbolCode);
        } else {
            dst.append(c);
        }
    }
    return dst.toString();
}

void InspectorFrontendHost::sendMessageToBackend(const String& message)
{
    if (m_client)
        m_client->sendMessageToBackend(escapeUnicodeNonCharacters(message));
}

void InspectorFrontendHost::sendMessageToEmbedder(const String& message)
{
    if (m_client)
        m_client->sendMessageToEmbedder(escapeUnicodeNonCharacters(message));
}

void InspectorFrontendHost::showContextMenu(Page* page, float x, float y, const Vector<ContextMenuItem>& items)
{
    ASSERT(m_frontendPage);
    ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());
    ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject("InspectorFrontendAPI");
    ASSERT(frontendApiObject.isObject());

    RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);
    m_menuProvider = menuProvider.get();
    float zoom = page->deprecatedLocalMainFrame()->pageZoomFactor();
    page->inspectorController().showContextMenu(x * zoom, y * zoom, menuProvider);
}

void InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items)
{
    if (!event)
        return;

    ASSERT(m_frontendPage);
    ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());
    ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject("InspectorFrontendAPI");
    ASSERT(frontendApiObject.isObject());

    Page* targetPage = m_frontendPage;
    if (event->target() && event->target()->executionContext() && event->target()->executionContext()->executingWindow()) {
        LocalDOMWindow* window = event->target()->executionContext()->executingWindow();
        if (window->document() && window->document()->page())
            targetPage = window->document()->page();
    }

    RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);
    targetPage->contextMenuController().showContextMenu(event, menuProvider);
    m_menuProvider = menuProvider.get();
}

String InspectorFrontendHost::getSelectionBackgroundColor()
{
    return RenderTheme::theme().activeSelectionBackgroundColor().serialized();
}

String InspectorFrontendHost::getSelectionForegroundColor()
{
    return RenderTheme::theme().activeSelectionForegroundColor().serialized();
}

bool InspectorFrontendHost::isUnderTest()
{
    return m_client && m_client->isUnderTest();
}

bool InspectorFrontendHost::isHostedMode()
{
    return false;
}

} // namespace blink
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 * Copyright (C) 2011 Ericsson AB. 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 INC. 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 INC. 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 "MediaStreamTrack.h"

#if ENABLE(MEDIA_STREAM)

#include "Event.h"
#include "MediaStreamCenter.h"
#include "MediaStreamComponent.h"

namespace WebCore {

PassRefPtr<MediaStreamTrack> MediaStreamTrack::create(ScriptExecutionContext* context, MediaStreamComponent* component)
{
    RefPtr<MediaStreamTrack> track = adoptRef(new MediaStreamTrack(context, component));
    track->suspendIfNeeded();
    return track.release();
}

MediaStreamTrack::MediaStreamTrack(ScriptExecutionContext* context, MediaStreamComponent* component)
    : ActiveDOMObject(context)
    , m_stopped(false)
    , m_component(component)
{
    m_component->source()->addObserver(this);
}

MediaStreamTrack::~MediaStreamTrack()
{
    m_component->source()->removeObserver(this);
}

String MediaStreamTrack::kind() const
{
    DEFINE_STATIC_LOCAL(String, audioKind, (ASCIILiteral("audio")));
    DEFINE_STATIC_LOCAL(String, videoKind, (ASCIILiteral("video")));

    switch (m_component->source()->type()) {
    case MediaStreamSource::TypeAudio:
        return audioKind;
    case MediaStreamSource::TypeVideo:
        return videoKind;
    }

    ASSERT_NOT_REACHED();
    return audioKind;
}

String MediaStreamTrack::id() const
{
    return m_component->id();
}

String MediaStreamTrack::label() const
{
    return m_component->source()->name();
}

bool MediaStreamTrack::enabled() const
{
    return m_component->enabled();
}

void MediaStreamTrack::setEnabled(bool enabled)
{
    if (m_stopped || enabled == m_component->enabled())
        return;

    m_component->setEnabled(enabled);

    if (m_component->stream()->ended())
        return;

    MediaStreamCenter::instance().didSetMediaStreamTrackEnabled(m_component->stream(), m_component.get());
}

String MediaStreamTrack::readyState() const
{
    if (m_stopped)
        return ASCIILiteral("ended");

    switch (m_component->source()->readyState()) {
    case MediaStreamSource::ReadyStateLive:
        return ASCIILiteral("live");
    case MediaStreamSource::ReadyStateMuted:
        return ASCIILiteral("muted");
    case MediaStreamSource::ReadyStateEnded:
        return ASCIILiteral("ended");
    }

    ASSERT_NOT_REACHED();
    return String();
}

bool MediaStreamTrack::ended() const
{
    return m_stopped || (m_component->source()->readyState() == MediaStreamSource::ReadyStateEnded);
}

void MediaStreamTrack::sourceChangedState()
{
    if (m_stopped)
        return;

    switch (m_component->source()->readyState()) {
    case MediaStreamSource::ReadyStateLive:
        dispatchEvent(Event::create(eventNames().unmuteEvent, false, false));
        break;
    case MediaStreamSource::ReadyStateMuted:
        dispatchEvent(Event::create(eventNames().muteEvent, false, false));
        break;
    case MediaStreamSource::ReadyStateEnded:
        dispatchEvent(Event::create(eventNames().endedEvent, false, false));
        didEndTrack();
        break;
    }
}

void MediaStreamTrack::didEndTrack()
{
    MediaStreamDescriptorClient* client = m_component->stream()->client();
    if (!client)
        return;

    client->trackEnded();
}

MediaStreamComponent* MediaStreamTrack::component()
{
    return m_component.get();
}

void MediaStreamTrack::stop()
{
    m_stopped = true;
    didEndTrack();
}

const AtomicString& MediaStreamTrack::interfaceName() const
{
    return eventNames().interfaceForMediaStreamTrack;
}

ScriptExecutionContext* MediaStreamTrack::scriptExecutionContext() const
{
    return ActiveDOMObject::scriptExecutionContext();
}

EventTargetData* MediaStreamTrack::eventTargetData()
{
    return &m_eventTargetData;
}

EventTargetData* MediaStreamTrack::ensureEventTargetData()
{
    return &m_eventTargetData;
}

} // namespace WebCore

#endif // ENABLE(MEDIA_STREAM)
<commit_msg>MediaStream API: Stop means stop Removing notification functionality from MediaStreamTrack::stop because the world is being torn down.<commit_after>/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 * Copyright (C) 2011 Ericsson AB. 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 INC. 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 INC. 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 "MediaStreamTrack.h"

#if ENABLE(MEDIA_STREAM)

#include "Event.h"
#include "MediaStreamCenter.h"
#include "MediaStreamComponent.h"

namespace WebCore {

PassRefPtr<MediaStreamTrack> MediaStreamTrack::create(ScriptExecutionContext* context, MediaStreamComponent* component)
{
    RefPtr<MediaStreamTrack> track = adoptRef(new MediaStreamTrack(context, component));
    track->suspendIfNeeded();
    return track.release();
}

MediaStreamTrack::MediaStreamTrack(ScriptExecutionContext* context, MediaStreamComponent* component)
    : ActiveDOMObject(context)
    , m_stopped(false)
    , m_component(component)
{
    m_component->source()->addObserver(this);
}

MediaStreamTrack::~MediaStreamTrack()
{
    m_component->source()->removeObserver(this);
}

String MediaStreamTrack::kind() const
{
    DEFINE_STATIC_LOCAL(String, audioKind, (ASCIILiteral("audio")));
    DEFINE_STATIC_LOCAL(String, videoKind, (ASCIILiteral("video")));

    switch (m_component->source()->type()) {
    case MediaStreamSource::TypeAudio:
        return audioKind;
    case MediaStreamSource::TypeVideo:
        return videoKind;
    }

    ASSERT_NOT_REACHED();
    return audioKind;
}

String MediaStreamTrack::id() const
{
    return m_component->id();
}

String MediaStreamTrack::label() const
{
    return m_component->source()->name();
}

bool MediaStreamTrack::enabled() const
{
    return m_component->enabled();
}

void MediaStreamTrack::setEnabled(bool enabled)
{
    if (m_stopped || enabled == m_component->enabled())
        return;

    m_component->setEnabled(enabled);

    if (m_component->stream()->ended())
        return;

    MediaStreamCenter::instance().didSetMediaStreamTrackEnabled(m_component->stream(), m_component.get());
}

String MediaStreamTrack::readyState() const
{
    if (m_stopped)
        return ASCIILiteral("ended");

    switch (m_component->source()->readyState()) {
    case MediaStreamSource::ReadyStateLive:
        return ASCIILiteral("live");
    case MediaStreamSource::ReadyStateMuted:
        return ASCIILiteral("muted");
    case MediaStreamSource::ReadyStateEnded:
        return ASCIILiteral("ended");
    }

    ASSERT_NOT_REACHED();
    return String();
}

bool MediaStreamTrack::ended() const
{
    return m_stopped || (m_component->source()->readyState() == MediaStreamSource::ReadyStateEnded);
}

void MediaStreamTrack::sourceChangedState()
{
    if (m_stopped)
        return;

    switch (m_component->source()->readyState()) {
    case MediaStreamSource::ReadyStateLive:
        dispatchEvent(Event::create(eventNames().unmuteEvent, false, false));
        break;
    case MediaStreamSource::ReadyStateMuted:
        dispatchEvent(Event::create(eventNames().muteEvent, false, false));
        break;
    case MediaStreamSource::ReadyStateEnded:
        dispatchEvent(Event::create(eventNames().endedEvent, false, false));
        didEndTrack();
        break;
    }
}

void MediaStreamTrack::didEndTrack()
{
    MediaStreamDescriptorClient* client = m_component->stream()->client();
    if (!client)
        return;

    client->trackEnded();
}

MediaStreamComponent* MediaStreamTrack::component()
{
    return m_component.get();
}

void MediaStreamTrack::stop()
{
    m_stopped = true;
}

const AtomicString& MediaStreamTrack::interfaceName() const
{
    return eventNames().interfaceForMediaStreamTrack;
}

ScriptExecutionContext* MediaStreamTrack::scriptExecutionContext() const
{
    return ActiveDOMObject::scriptExecutionContext();
}

EventTargetData* MediaStreamTrack::eventTargetData()
{
    return &m_eventTargetData;
}

EventTargetData* MediaStreamTrack::ensureEventTargetData()
{
    return &m_eventTargetData;
}

} // namespace WebCore

#endif // ENABLE(MEDIA_STREAM)
<|endoftext|>


<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2010 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/RequestableChannelClassSpec>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT RequestableChannelClassSpec::Private : public QSharedData
{
    Private(const RequestableChannelClass &rcc)
        : rcc(rcc) {}

    RequestableChannelClass rcc;
};

RequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClass &rcc)
    : mPriv(new Private(rcc))
{
}

RequestableChannelClassSpec::RequestableChannelClassSpec()
{
}

RequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClassSpec &other)
    : mPriv(other.mPriv)
{
}

RequestableChannelClassSpec::~RequestableChannelClassSpec()
{
}

RequestableChannelClassSpec RequestableChannelClassSpec::textChat()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::textChatroom()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeRoom);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaAudioCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialVideo"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCallWithAudio()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialVideo"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::fileTransfer()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChat()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatWithInvitees()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroom()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeRoom);

        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroomWithInvitees()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeRoom);

        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCallWithInvitees()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearch()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServer()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Server"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithLimit()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Limit"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServerAndLimit()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Server"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Limit"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec &RequestableChannelClassSpec::operator=(const RequestableChannelClassSpec &other)
{
    this->mPriv = other.mPriv;
    return *this;
}

bool RequestableChannelClassSpec::operator==(const RequestableChannelClassSpec &other) const
{
    if (!isValid()) {
        return false;
    }

    return mPriv->rcc == other.mPriv->rcc;
}

bool RequestableChannelClassSpec::supports(const RequestableChannelClassSpec &other) const
{
    if (!isValid()) {
        return false;
    }

    if (mPriv->rcc.fixedProperties == other.fixedProperties()) {
        foreach (const QString &prop, other.allowedProperties()) {
            if (!mPriv->rcc.allowedProperties.contains(prop)) {
                return false;
            }
        }
        return true;
    }
    return false;
}

QString RequestableChannelClassSpec::channelType() const
{
    if (!isValid()) {
        return QString();
    }
    return qdbus_cast<QString>(mPriv->rcc.fixedProperties.value(
                QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")));
}

bool RequestableChannelClassSpec::hasTargetHandleType() const
{
    if (!isValid()) {
        return false;
    }
    return mPriv->rcc.fixedProperties.contains(
            QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"));
}

HandleType RequestableChannelClassSpec::targetHandleType() const
{
    if (!hasTargetHandleType()) {
        return (HandleType) -1;
    }
    return (HandleType) qdbus_cast<uint>(mPriv->rcc.fixedProperties.value(
                QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")));
}

bool RequestableChannelClassSpec::hasFixedProperty(const QString &name) const
{
    if (!isValid()) {
        return false;
    }
    return mPriv->rcc.fixedProperties.contains(name);
}

QVariant RequestableChannelClassSpec::fixedProperty(const QString &name) const
{
    if (!isValid()) {
        return QVariant();
    }
    return mPriv->rcc.fixedProperties.value(name);
}

QVariantMap RequestableChannelClassSpec::fixedProperties() const
{
    if (!isValid()) {
        return QVariantMap();
    }
    return mPriv->rcc.fixedProperties;
}

bool RequestableChannelClassSpec::allowsProperty(const QString &name) const
{
    if (!isValid()) {
        return false;
    }
    return mPriv->rcc.allowedProperties.contains(name);
}

QStringList RequestableChannelClassSpec::allowedProperties() const
{
    if (!isValid()) {
        return QStringList();
    }
    return mPriv->rcc.allowedProperties;
}

RequestableChannelClass RequestableChannelClassSpec::bareClass() const
{
    return isValid() ? mPriv->rcc : RequestableChannelClass();
}

} // Tp
<commit_msg>RequestableChannelClassSpec: Return true in operator== if both instances are invalid and false if only one of them is.<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2010 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/RequestableChannelClassSpec>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT RequestableChannelClassSpec::Private : public QSharedData
{
    Private(const RequestableChannelClass &rcc)
        : rcc(rcc) {}

    RequestableChannelClass rcc;
};

RequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClass &rcc)
    : mPriv(new Private(rcc))
{
}

RequestableChannelClassSpec::RequestableChannelClassSpec()
{
}

RequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClassSpec &other)
    : mPriv(other.mPriv)
{
}

RequestableChannelClassSpec::~RequestableChannelClassSpec()
{
}

RequestableChannelClassSpec RequestableChannelClassSpec::textChat()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::textChatroom()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeRoom);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaAudioCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialVideo"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCallWithAudio()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialAudio"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(".InitialVideo"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::fileTransfer()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeContact);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChat()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatWithInvitees()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroom()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeRoom);

        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroomWithInvitees()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_TEXT);
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".TargetHandleType"),
                (uint) HandleTypeRoom);

        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCall()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCallWithInvitees()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearch()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServer()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Server"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithLimit()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Limit"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServerAndLimit()
{
    static RequestableChannelClassSpec spec;

    if (!spec.isValid()) {
        RequestableChannelClass rcc;
        rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(".ChannelType"),
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Server"));
        rcc.allowedProperties.append(
                TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(".Limit"));
        spec = RequestableChannelClassSpec(rcc);
    }

    return spec;
}

RequestableChannelClassSpec &RequestableChannelClassSpec::operator=(const RequestableChannelClassSpec &other)
{
    this->mPriv = other.mPriv;
    return *this;
}

bool RequestableChannelClassSpec::operator==(const RequestableChannelClassSpec &other) const
{
    if (!isValid() || !other.isValid()) {
        if (!isValid() && !other.isValid()) {
            return true;
        }
        return false;
    }

    return mPriv->rcc == other.mPriv->rcc;
}

bool RequestableChannelClassSpec::supports(const RequestableChannelClassSpec &other) const
{
    if (!isValid()) {
        return false;
    }

    if (mPriv->rcc.fixedProperties == other.fixedProperties()) {
        foreach (const QString &prop, other.allowedProperties()) {
            if (!mPriv->rcc.allowedProperties.contains(prop)) {
                return false;
            }
        }
        return true;
    }
    return false;
}

QString RequestableChannelClassSpec::channelType() const
{
    if (!isValid()) {
        return QString();
    }
    return qdbus_cast<QString>(mPriv->rcc.fixedProperties.value(
                QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")));
}

bool RequestableChannelClassSpec::hasTargetHandleType() const
{
    if (!isValid()) {
        return false;
    }
    return mPriv->rcc.fixedProperties.contains(
            QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"));
}

HandleType RequestableChannelClassSpec::targetHandleType() const
{
    if (!hasTargetHandleType()) {
        return (HandleType) -1;
    }
    return (HandleType) qdbus_cast<uint>(mPriv->rcc.fixedProperties.value(
                QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")));
}

bool RequestableChannelClassSpec::hasFixedProperty(const QString &name) const
{
    if (!isValid()) {
        return false;
    }
    return mPriv->rcc.fixedProperties.contains(name);
}

QVariant RequestableChannelClassSpec::fixedProperty(const QString &name) const
{
    if (!isValid()) {
        return QVariant();
    }
    return mPriv->rcc.fixedProperties.value(name);
}

QVariantMap RequestableChannelClassSpec::fixedProperties() const
{
    if (!isValid()) {
        return QVariantMap();
    }
    return mPriv->rcc.fixedProperties;
}

bool RequestableChannelClassSpec::allowsProperty(const QString &name) const
{
    if (!isValid()) {
        return false;
    }
    return mPriv->rcc.allowedProperties.contains(name);
}

QStringList RequestableChannelClassSpec::allowedProperties() const
{
    if (!isValid()) {
        return QStringList();
    }
    return mPriv->rcc.allowedProperties;
}

RequestableChannelClass RequestableChannelClassSpec::bareClass() const
{
    return isValid() ? mPriv->rcc : RequestableChannelClass();
}

} // Tp
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkLBFGSOptimizerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

=========================================================================*/

#include <itkLBFGSOptimizer.h>
#include <itkPoint.h>

/**
 *  The objectif function is the quadratic form:
 *
 *  1/2 x^T A x - b^T x
 *
 *  Where A is represented as an itkMatrix and
 *  b is represented as a itkVector
 *
 *  The system in this example is:
 *
 *     | 3  2 ||x|   | 2|   |0|
 *     | 2  6 ||y| + |-8| = |0|
 *
 *
 *   the solution is the vector | 2 -2 |
 *
 */
class CostFunction : public itk::LightObject
{
public:

  typedef CostFunction Self;
  typedef itk::LightObject  Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;
  itkNewMacro( Self );

  enum { SpaceDimension=2 };
  typedef itk::Point<double,SpaceDimension> ParametersType;
  typedef itk::Point<double,SpaceDimension> DerivativeType;
  typedef double MeasureType ;

  CostFunction()
  {
  }

  const ParametersType & GetParameters(void) const
  {
    return m_Parameters;
  }

  double GetValue( const ParametersType & position ) const
  {

    m_Parameters = position;

    double x = position[0];
    double y = position[1];

    std::cout << "GetValue ( " ;
    std::cout << x << " , " << y;
    std::cout << ") = ";

    double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;

    std::cout << val << std::endl;

    return val;
  }

  DerivativeType GetDerivative( const ParametersType & position ) const
  {

    double x = position[0];
    double y = position[1];

    std::cout << "GetDerivative ( " ;
    std::cout << x << " , " << y;
    std::cout << ") = ";

    DerivativeType grad;
    grad[0] = 3*x + 2*y -2;
    grad[1] = 2*x + 6*y +8;
    std::cout << "(" ;
    std::cout << grad[0] <<" , ";
    std::cout << grad[1] << ")" << std::endl;
    return grad;
  }

private:

  mutable ParametersType m_Parameters;

};

int main()
{
  std::cout << "Conjugate Gradient Optimizer Test \n \n";

  typedef  itk::LBFGSOptimizer<
                                CostFunction >  OptimizerType;

  typedef  OptimizerType::InternalOptimizerType  vnlOptimizerType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction adaptor
  CostFunction costFunction;

  itkOptimizer->SetCostFunction( &costFunction );

  const double F_Tolerance      = 1e-3;  // Function value tolerance
  const double G_Tolerance      = 1e-4;  // Gradient magnitude tolerance
  const double X_Tolerance      = 1e-8;  // Search space tolerance
  const double Epsilon_Function = 1e-10; // Step
  const int    Max_Iterations   =   100; // Maximum number of iterations

  vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer();

  vnlOptimizer.set_f_tolerance( F_Tolerance );
  vnlOptimizer.set_g_tolerance( G_Tolerance );
  vnlOptimizer.set_x_tolerance( X_Tolerance );
  vnlOptimizer.set_epsilon_function( Epsilon_Function );
  vnlOptimizer.set_max_function_evals( Max_Iterations );

  vnlOptimizer.set_check_derivatives( 3 );

  const unsigned int SpaceDimension = 2;
  typedef itk::Point<double,SpaceDimension> ParametersType;
  ParametersType initialValue;

  // We start not so far from  | 2 -2 |
  initialValue[0] =  100;
  initialValue[1] = -100;

  itkOptimizer->SetInitialPosition( initialValue );
  itkOptimizer->StartOptimization();

  std::cout << "End condition   = " << vnlOptimizer.get_failure_code()    << std::endl;
  std::cout << "Number of iters = " << vnlOptimizer.get_num_iterations()  << std::endl;
  std::cout << "Number of evals = " << vnlOptimizer.get_num_evaluations() << std::endl;
  std::cout << std::endl;

  ParametersType finalValue = costFunction.GetParameters();

  std::cout << "Solution        = (";
  std::cout << finalValue[0] << "," ;
  std::cout << finalValue[1] << ")" << std::endl;

  return 0;

}

<commit_msg>ENH: Added test for numerical precision<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkLBFGSOptimizerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

=========================================================================*/

#include <itkLBFGSOptimizer.h>
#include <itkPoint.h>

/**
 *  The objectif function is the quadratic form:
 *
 *  1/2 x^T A x - b^T x
 *
 *  Where A is represented as an itkMatrix and
 *  b is represented as a itkVector
 *
 *  The system in this example is:
 *
 *     | 3  2 ||x|   | 2|   |0|
 *     | 2  6 ||y| + |-8| = |0|
 *
 *
 *   the solution is the vector | 2 -2 |
 *
 */
class CostFunction : public itk::LightObject
{
public:

  typedef CostFunction Self;
  typedef itk::LightObject  Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;
  itkNewMacro( Self );

  enum { SpaceDimension=2 };
  typedef itk::Point<double,SpaceDimension> ParametersType;
  typedef itk::Point<double,SpaceDimension> DerivativeType;
  typedef double MeasureType ;

  CostFunction()
  {
  }

  const ParametersType & GetParameters(void) const
  {
    return m_Parameters;
  }

  double GetValue( const ParametersType & position ) const
  {

    m_Parameters = position;

    double x = position[0];
    double y = position[1];

    std::cout << "GetValue ( " ;
    std::cout << x << " , " << y;
    std::cout << ") = ";

    double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;

    std::cout << val << std::endl;

    return val;
  }

  DerivativeType GetDerivative( const ParametersType & position ) const
  {

    double x = position[0];
    double y = position[1];

    std::cout << "GetDerivative ( " ;
    std::cout << x << " , " << y;
    std::cout << ") = ";

    DerivativeType grad;
    grad[0] = 3*x + 2*y -2;
    grad[1] = 2*x + 6*y +8;
    std::cout << "(" ;
    std::cout << grad[0] <<" , ";
    std::cout << grad[1] << ")" << std::endl;
    return grad;
  }

private:

  mutable ParametersType m_Parameters;

};

int main()
{
  std::cout << "Conjugate Gradient Optimizer Test \n \n";

  typedef  itk::LBFGSOptimizer<
                                CostFunction >  OptimizerType;

  typedef  OptimizerType::InternalOptimizerType  vnlOptimizerType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction adaptor
  CostFunction costFunction;

  itkOptimizer->SetCostFunction( &costFunction );

  const double F_Tolerance      = 1e-3;  // Function value tolerance
  const double G_Tolerance      = 1e-4;  // Gradient magnitude tolerance
  const double X_Tolerance      = 1e-8;  // Search space tolerance
  const double Epsilon_Function = 1e-10; // Step
  const int    Max_Iterations   =   100; // Maximum number of iterations

  vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer();

  vnlOptimizer.set_f_tolerance( F_Tolerance );
  vnlOptimizer.set_g_tolerance( G_Tolerance );
  vnlOptimizer.set_x_tolerance( X_Tolerance );
  vnlOptimizer.set_epsilon_function( Epsilon_Function );
  vnlOptimizer.set_max_function_evals( Max_Iterations );

  vnlOptimizer.set_check_derivatives( 3 );

  const unsigned int SpaceDimension = 2;
  typedef itk::Point<double,SpaceDimension> ParametersType;
  ParametersType initialValue;

  // We start not so far from  | 2 -2 |
  initialValue[0] =  100;
  initialValue[1] = -100;

  itkOptimizer->SetInitialPosition( initialValue );
  itkOptimizer->StartOptimization();

  std::cout << "End condition   = " << vnlOptimizer.get_failure_code()    << std::endl;
  std::cout << "Number of iters = " << vnlOptimizer.get_num_iterations()  << std::endl;
  std::cout << "Number of evals = " << vnlOptimizer.get_num_evaluations() << std::endl;
  std::cout << std::endl;

  ParametersType finalPosition;
  finalPosition = costFunction.GetParameters();
  std::cout << "Solution        = (";
  std::cout << finalPosition[0] << "," ;
  std::cout << finalPosition[1] << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  bool pass = true;
  double trueParameters[2] = { 2, -2 };
  for( unsigned int j = 0; j < 2; j++ )
    {
    if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
      pass = false;
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}

<|endoftext|>


<commit_before>#include "game.h"
#include "player.h"
#include <iostream>
#include <ctime>
#include <cstdlib>

int main(int argc, char **argv)
{
	srand(time(0)); //Random numbers.
	Game game;
	Player player;
	Player player2; //Unused if we dont have isTwoHumanPlayer set.

	char piece = '-';	//current players player piece.

	if (argc < 2) {
		std::cout << "Please enter how many players you would like. 1 or 2.\n";
		std::cout << "Also enter which piece player one is. NO spaces\n";
		std::cout << "Example: ./tictactoe 20 for two player game, random piece.\n";
		std::cout << "Additional help will come when I'm closer to releasing game fully...\n";
		return 0;
	}

	//Welcome message/banner
	std::cout << "\n\nW E L C O M E  T O  T I C  T A C  T O E\n\n";

	if (strtol(argv[1], NULL, 10) == 20) {
		std::cout << "Starting 2 player game, random pieces.\n";
		std::cout << "Chosing random piece...\n";
		if (game.get_random_num(100) % 2 == 0) {
			player.playerPiece = 'X';
			player2.playerPiece = 'O';
			std::cout << "Player one, your piece is " << player.playerPiece << "\n";
			std::cout << "Player two, your piece is " << player2.playerPiece << "\n";
			player.isTwoHumanPlayer = true;
		} else {
			std::cout << "Player one, your piece is O\n";
			std::cout << "Player two, your piece is X\n";
			player.playerPiece = 'O';
			player2.playerPiece = 'X';
			player.isTwoHumanPlayer = true;
		}
	}

	if (strtol(argv[1], NULL, 10) == 21) {
		std::cout << "Starting 2 player game, player on is X.\n";
		player.playerPiece = 'X';
		player2.playerPiece = 'O';
		player.isTwoHumanPlayer = true;
	}

	if (strtol(argv[1], NULL, 10) == 22) {
		std::cout << "Starting 2 player game, player one is O.\n";
		player.playerPiece = 'O';
		player2.playerPiece = 'X';
		player.isTwoHumanPlayer = true;
	}

	while (game.isRunning) {
		//Time to play the game!
		int userInput = 0;

		if (player.isTwoHumanPlayer) {
			if (player.isPlayerTurn) {
				piece = player.playerPiece;
				std::cout << "Player one, enter the number of the square you want.\n";
				userInput = player.get_input();
				if (userInput == -1) {
					std::cout << "\n\nExiting the game on grounds of user error or request.\n\n";;
					return -1;
				}

				if  (game.make_move(userInput, player.playerPiece) == 1) {
					std::cout << "Overlap detected... \n";
					std::cout << "Player 1, try again.\n";
					player.isPlayerTurn = true;
				}
				player.isPlayerTurn = false;
			} else {
				piece = player2.playerPiece;
				std::cout << "Player two, enter the number of the square you want.\n";
				userInput = player.get_input();
				if (userInput == -1) {
					std::cout << "\n\nExiting the game on grounds of user error or request.\n\n";;
					return -1;
				}

				if  (game.make_move(userInput, player.playerPiece) == 1) {
					std::cout << "Overlap detected... \n";
					std::cout << "Player 2, try again.\n";
					player.isPlayerTurn = false;
				}
				player.isPlayerTurn = true;
			}
		}
		game.print_board();

		//Whoever wins first wins first, there is no other option.
		//You cannot tie for win in tic tac toe, but you can draw
		//and/or stalemate the game. <--- happens regularly... stalemates :Z
		/*
		if (game.is_victory(player.playerPiece)) {
			std::cout << "\n\nPlayer one wins!\n\n";
			std::cout << "Now exiting on grounds of happy victory ;)\n\n";
			return 0;
		}

		if (game.is_victory(player2.playerPiece)) {
			std::cout << "\n\nPlayer two wins!\n\n";
			std::cout << "Now exiting on grounds of happy victory ;)\n\n";
			return 0;
		}
		*/
		if (game.isStalemate) {
			std::cout << "\n\nNobody wins!\n\n";
			std::cout << "Now exiting on grounds of an angry stalemate. ARgh!\n\n";
		}
	}
}

<commit_msg>Picking up where I left off. Fixing bugs, stalemate detection, etc.<commit_after>#include "game.h"
#include "player.h"
#include <iostream>
#include <ctime>
#include <cstdlib>

int main(int argc, char **argv)
{
	srand(time(0)); //Random numbers.
	Game game;
	Player player;
	Player player2; //Unused if we dont have isTwoHumanPlayer set.

	char piece = '-';	//current players player piece.

	if (argc < 2) {
		std::cout << "Please enter how many players you would like. 1 or 2.\n";
		std::cout << "Also enter which piece player one is. NO spaces\n";
		std::cout << "Example: ./tictactoe 20 for two player game, random piece.\n";
		std::cout << "Additional help will come when I'm closer to releasing game fully...\n";
		return 0;
	}

	//Welcome message/banner
	std::cout << "\n\nW E L C O M E  T O  T I C  T A C  T O E\n\n";

	if (strtol(argv[1], NULL, 10) == 20) {
		std::cout << "Starting 2 player game, random pieces.\n";
		std::cout << "Chosing random piece...\n";
		if (game.get_random_num(100) % 2 == 0) {
			player.playerPiece = 'X';
			player2.playerPiece = 'O';
			std::cout << "Player one, your piece is " << player.playerPiece << "\n";
			std::cout << "Player two, your piece is " << player2.playerPiece << "\n";
			player.isTwoHumanPlayer = true;
		} else {
			std::cout << "Player one, your piece is O\n";
			std::cout << "Player two, your piece is X\n";
			player.playerPiece = 'O';
			player2.playerPiece = 'X';
			player.isTwoHumanPlayer = true;
		}
	}

	if (strtol(argv[1], NULL, 10) == 21) {
		std::cout << "Starting 2 player game, player on is X.\n";
		player.playerPiece = 'X';
		player2.playerPiece = 'O';
		player.isTwoHumanPlayer = true;
	}

	if (strtol(argv[1], NULL, 10) == 22) {
		std::cout << "Starting 2 player game, player one is O.\n";
		player.playerPiece = 'O';
		player2.playerPiece = 'X';
		player.isTwoHumanPlayer = true;
	}

	while (game.isRunning) {
		//Time to play the game!
		int userInput = 0;

		if (player.isTwoHumanPlayer) {
			if (player.isPlayerTurn) {
				piece = player.playerPiece;
				std::cout << "Player one, enter the number of the square you want.\n";
				userInput = player.get_input();
				if  (game.make_move(userInput, player.playerPiece) == 1) {
					std::cout << "Overlap detected... \n";
					std::cout << "Player 1, try again.\n";
					player.isPlayerTurn = true;
				} else {
					player.isPlayerTurn = false;
				}
			} else {
				piece = player2.playerPiece;
				std::cout << "Player two, enter the number of the square you want.\n";
				userInput = player.get_input();
				if  (game.make_move(userInput, player2.playerPiece) == 1) {
					std::cout << "Overlap detected... \n";
					std::cout << "Player 2, try again.\n";
					player.isPlayerTurn = false;
				} else {
					player.isPlayerTurn = true;
				}
			}
		}
		game.print_board();

		//Whoever wins first wins first, there is no other option.
		//You cannot tie for win in tic tac toe, but you can draw
		//and/or stalemate the game. <--- happens regularly... stalemates :Z
		/*
		if (game.is_victory(player.playerPiece)) {
			std::cout << "\n\nPlayer one wins!\n\n";
			std::cout << "Now exiting on grounds of happy victory ;)\n\n";
			return 0;
		}

		if (game.is_victory(player2.playerPiece)) {
			std::cout << "\n\nPlayer two wins!\n\n";
			std::cout << "Now exiting on grounds of happy victory ;)\n\n";
			return 0;
		}
		*/
		if (game.isStalemate) {
			std::cout << "\n\nNobody wins!\n\n";
			std::cout << "Now exiting on grounds of an angry stalemate. ARgh!\n\n";
		}
	}
}

<|endoftext|>


<commit_before>/*
 * This file is part of `et engine`
 * Copyright 2009-2013 by Sergey Reznik
 * Please, do not modify content without approval.
 *
 */

#include <et/core/tools.h>
#include <et/app/backgroundthread.h>

using namespace et;

BackgroundRunLoop::BackgroundRunLoop() :
	_owner(nullptr) { }

void BackgroundRunLoop::setOwner(BackgroundThread* owner)
	{ _owner = owner; }

void BackgroundRunLoop::addTask(Task* t, float delay)
{
	RunLoop::addTask(t, delay);
	_owner->resume();
}

BackgroundThread::BackgroundThread()
{
	_runLoop.setOwner(this);
}

ThreadResult BackgroundThread::main()
{
	while (running())
	{
		if (_runLoop.hasTasks())
			_runLoop.update(queryContiniousTimeInMilliSeconds());
		else
			suspend();
	}

	return 0;
}
<commit_msg>background thread fix<commit_after>/*
 * This file is part of `et engine`
 * Copyright 2009-2013 by Sergey Reznik
 * Please, do not modify content without approval.
 *
 */

#include <et/core/tools.h>
#include <et/app/backgroundthread.h>

using namespace et;

BackgroundRunLoop::BackgroundRunLoop() :
	_owner(nullptr) { }

void BackgroundRunLoop::setOwner(BackgroundThread* owner)
	{ _owner = owner; }

void BackgroundRunLoop::addTask(Task* t, float delay)
{
	RunLoop::update(queryContiniousTimeInMilliSeconds());
	RunLoop::addTask(t, delay);

	_owner->resume();
}

BackgroundThread::BackgroundThread()
{
	_runLoop.setOwner(this);
}

ThreadResult BackgroundThread::main()
{
	while (running())
	{
		if (_runLoop.hasTasks())
			_runLoop.update(queryContiniousTimeInMilliSeconds());
		else
			suspend();
	}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Return kTRUE since kFALSE indicates to Root v6-18-04 real problems<commit_after><|endoftext|>


<commit_before>/*=============================================================================
	MIDIDriver.cpp

=============================================================================*/
/*
	Copyright: 	 Copyright 2000 Apple Computer, Inc. All rights reserved.

	Disclaimer:	IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
			("Apple") in consideration of your agreement to the following terms, and your
			use, installation, modification or redistribution of this Apple software
			constitutes acceptance of these terms.  If you do not agree with these terms,
			please do not use, install, modify or redistribute this Apple software.

			In consideration of your agreement to abide by the following terms, and subject
			to these terms, Apple grants you a personal, non-exclusive license, under Apples
			copyrights in this original Apple software (the "Apple Software"), to use,
			reproduce, modify and redistribute the Apple Software, with or without
			modifications, in source and/or binary forms; provided that if you redistribute
			the Apple Software in its entirety and without modifications, you must retain
			this notice and the following text and disclaimers in all such redistributions of
			the Apple Software.  Neither the name, trademarks, service marks or logos of
			Apple Computer, Inc. may be used to endorse or promote products derived from the
			Apple Software without specific prior written permission from Apple.  Except as
			expressly stated in this notice, no other rights or licenses, express or implied,
			are granted by Apple herein, including but not limited to any patent rights that
			may be infringed by your derivative works or by other works in which the Apple
			Software may be incorporated.

			The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
			WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
			WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
			PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
			COMBINATION WITH YOUR PRODUCTS.

			IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
			CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
			GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
			ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
			OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
			(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
			ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// A CFPlugin MIDIDriver using a C interface to CFPlugin, but calling a C++ class to do the work.

#include "MIDIDriverClass.h"

// Implementation of the IUnknown QueryInterface function.
static HRESULT MIDIDriverQueryInterface(MIDIDriverRef ref, REFIID iid, LPVOID *ppv)
{
	// Create a CoreFoundation UUIDRef for the requested interface.
	CFUUIDRef interfaceID = CFUUIDCreateFromUUIDBytes( NULL, iid );

#if V2_MIDI_DRIVER_SUPPORT
	if (CFEqual(interfaceID, kMIDIDriverInterface2ID)) {
		// If the MIDIDriverInterface was requested, bump the ref count,
		// set the ppv parameter equal to the instance, and
		// return good status.
		MIDIDriver *self = GetMIDIDriver(ref);
		self->mInterface->AddRef(ref);
		*ppv = &self->mInterface;
		CFRelease(interfaceID);
		self->mVersion = 2;
#if MIDI_WEAK_LINK_TO_V2_CALLS
		InitMIDIWeakLinks();
#endif
		return S_OK;
	}
#endif

#if V1_MIDI_DRIVER_SUPPORT
	// Test the requested ID against the valid interfaces.
	if (CFEqual(interfaceID, kMIDIDriverInterfaceID)) {
		// If the MIDIDriverInterface was requested, bump the ref count,
		// set the ppv parameter equal to the instance, and
		// return good status.
		MIDIDriver *self = GetMIDIDriver(ref);
		self->mInterface->AddRef(ref);
		*ppv = &self->mInterface;
		CFRelease(interfaceID);
		self->mVersion = 1;
		return S_OK;
	}
#endif

	if (CFEqual(interfaceID, IUnknownUUID)) {
		MIDIDriver *self = GetMIDIDriver(ref);
		self->mInterface->AddRef(ref);
		*ppv = &self->mInterface;
		CFRelease(interfaceID);
		return S_OK;
	}

	// Requested interface unknown, bail with error.
	*ppv = NULL;
	CFRelease(interfaceID);
	return E_NOINTERFACE;
}
// return value ppv is a pointer to a pointer to the interface

// Implementation of reference counting for this type.
// Whenever an interface is requested, bump the refCount for
// the instance. NOTE: returning the refcount is a convention
// but is not required so don't rely on it.
static ULONG MIDIDriverAddRef(MIDIDriverRef ref)
{
	MIDIDriver *self = GetMIDIDriver(ref);

	return ++self->mRefCount;
}

// When an interface is released, decrement the refCount.
// If the refCount goes to zero, deallocate the instance.
static ULONG MIDIDriverRelease(MIDIDriverRef ref)
{
	MIDIDriver *self = GetMIDIDriver(ref);

	if (--self->mRefCount == 0) {
		delete self;
		return 0;
	} else
		return self->mRefCount;
}

OSStatus	MIDIDriverFindDevices(MIDIDriverRef self, MIDIDeviceListRef devList)
{
	return GetMIDIDriver(self)->FindDevices(devList);
}

OSStatus	MIDIDriverStart(MIDIDriverRef self, MIDIDeviceListRef devList)
{
	return GetMIDIDriver(self)->Start(devList);
}

OSStatus	MIDIDriverStop(MIDIDriverRef self)
{
	return GetMIDIDriver(self)->Stop();
}

OSStatus	MIDIDriverConfigure(MIDIDriverRef self, MIDIDeviceRef device)
{
	return GetMIDIDriver(self)->Configure(device);
}

OSStatus	MIDIDriverSend(MIDIDriverRef self, const MIDIPacketList *pktlist,
				void *destRefCon1, void *destRefCon2)
{
	return GetMIDIDriver(self)->Send(pktlist, destRefCon1, destRefCon2);
}

OSStatus	MIDIDriverEnableSource(MIDIDriverRef self, MIDIEndpointRef src, Boolean enabled)
{
	return GetMIDIDriver(self)->EnableSource(src, enabled);
}

OSStatus	MIDIDriverFlush(MIDIDriverRef self, MIDIEndpointRef dest, void *destRefCon1, void *destRefCon2)
{
	return GetMIDIDriver(self)->Flush(dest, destRefCon1, destRefCon2);
}

OSStatus	MIDIDriverMonitor(MIDIDriverRef self, MIDIEndpointRef dest, const MIDIPacketList *pktlist)
{
	return GetMIDIDriver(self)->Monitor(dest, pktlist);
}

// The MIDIDriverInterface function table.
static MIDIDriverInterface MIDIDriverInterfaceFtbl = {
	NULL, // Required padding for COM
	//
	// These are the required COM functions
	// NOTE: Warnings here about conversion from MIDIDriverInterface** to void* are nothing to worry about
	// (although yucky)
	MIDIDriverQueryInterface,
	MIDIDriverAddRef,
	MIDIDriverRelease,
	//
	// These are the MIDIDriver methods
	MIDIDriverFindDevices,
	MIDIDriverStart,
	MIDIDriverStop,
	MIDIDriverConfigure,
	MIDIDriverSend,
	MIDIDriverEnableSource,
	MIDIDriverFlush,
	MIDIDriverMonitor
};

MIDIDriver::MIDIDriver(CFUUIDRef factoryID)
{
	// Point to the function table
	mInterface = &MIDIDriverInterfaceFtbl;

	// Retain and keep an open instance refcount for each factory.
	mFactoryID = factoryID;
	CFPlugInAddInstanceForFactory(factoryID);

	mRefCount = 1;
	mVersion = 0;
}

MIDIDriver::~MIDIDriver()
{
	if (mFactoryID) {
		CFPlugInRemoveInstanceForFactory(mFactoryID);
		// CFRelease(mFactoryID); this came from CFUUIDGetConstantUUIDWithBytes which
		// says that it is immortal and should never be released
	}
}
<commit_msg>A little bit of casting to avoid compiler warnings.<commit_after>/*=============================================================================
	MIDIDriver.cpp

=============================================================================*/
/*
	Copyright: 	 Copyright 2000 Apple Computer, Inc. All rights reserved.

	Disclaimer:	IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
			("Apple") in consideration of your agreement to the following terms, and your
			use, installation, modification or redistribution of this Apple software
			constitutes acceptance of these terms.  If you do not agree with these terms,
			please do not use, install, modify or redistribute this Apple software.

			In consideration of your agreement to abide by the following terms, and subject
			to these terms, Apple grants you a personal, non-exclusive license, under Apples
			copyrights in this original Apple software (the "Apple Software"), to use,
			reproduce, modify and redistribute the Apple Software, with or without
			modifications, in source and/or binary forms; provided that if you redistribute
			the Apple Software in its entirety and without modifications, you must retain
			this notice and the following text and disclaimers in all such redistributions of
			the Apple Software.  Neither the name, trademarks, service marks or logos of
			Apple Computer, Inc. may be used to endorse or promote products derived from the
			Apple Software without specific prior written permission from Apple.  Except as
			expressly stated in this notice, no other rights or licenses, express or implied,
			are granted by Apple herein, including but not limited to any patent rights that
			may be infringed by your derivative works or by other works in which the Apple
			Software may be incorporated.

			The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
			WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
			WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
			PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
			COMBINATION WITH YOUR PRODUCTS.

			IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
			CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
			GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
			ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
			OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
			(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
			ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// A CFPlugin MIDIDriver using a C interface to CFPlugin, but calling a C++ class to do the work.

#include "MIDIDriverClass.h"

// Implementation of the IUnknown QueryInterface function.
static HRESULT MIDIDriverQueryInterface(void *thisPointer, REFIID iid, LPVOID *ppv)
{
	MIDIDriverRef ref = (MIDIDriverRef)thisPointer;

	// Create a CoreFoundation UUIDRef for the requested interface.
	CFUUIDRef interfaceID = CFUUIDCreateFromUUIDBytes( NULL, iid );

#if V2_MIDI_DRIVER_SUPPORT
	if (CFEqual(interfaceID, kMIDIDriverInterface2ID)) {
		// If the MIDIDriverInterface was requested, bump the ref count,
		// set the ppv parameter equal to the instance, and
		// return good status.
		MIDIDriver *self = GetMIDIDriver(ref);
		self->mInterface->AddRef(ref);
		*ppv = &self->mInterface;
		CFRelease(interfaceID);
		self->mVersion = 2;
#if MIDI_WEAK_LINK_TO_V2_CALLS
		InitMIDIWeakLinks();
#endif
		return S_OK;
	}
#endif

#if V1_MIDI_DRIVER_SUPPORT
	// Test the requested ID against the valid interfaces.
	if (CFEqual(interfaceID, kMIDIDriverInterfaceID)) {
		// If the MIDIDriverInterface was requested, bump the ref count,
		// set the ppv parameter equal to the instance, and
		// return good status.
		MIDIDriver *self = GetMIDIDriver(ref);
		self->mInterface->AddRef(ref);
		*ppv = &self->mInterface;
		CFRelease(interfaceID);
		self->mVersion = 1;
		return S_OK;
	}
#endif

	if (CFEqual(interfaceID, IUnknownUUID)) {
		MIDIDriver *self = GetMIDIDriver(ref);
		self->mInterface->AddRef(ref);
		*ppv = &self->mInterface;
		CFRelease(interfaceID);
		return S_OK;
	}

	// Requested interface unknown, bail with error.
	*ppv = NULL;
	CFRelease(interfaceID);
	return E_NOINTERFACE;
}
// return value ppv is a pointer to a pointer to the interface

// Implementation of reference counting for this type.
// Whenever an interface is requested, bump the refCount for
// the instance. NOTE: returning the refcount is a convention
// but is not required so don't rely on it.
static ULONG MIDIDriverAddRef(void *thisPointer)
{
	MIDIDriver *self = GetMIDIDriver((MIDIDriverRef)thisPointer);

	return ++self->mRefCount;
}

// When an interface is released, decrement the refCount.
// If the refCount goes to zero, deallocate the instance.
static ULONG MIDIDriverRelease(void *thisPointer)
{
	MIDIDriver *self = GetMIDIDriver((MIDIDriverRef)thisPointer);

	if (--self->mRefCount == 0) {
		delete self;
		return 0;
	} else
		return self->mRefCount;
}

OSStatus	MIDIDriverFindDevices(MIDIDriverRef self, MIDIDeviceListRef devList)
{
	return GetMIDIDriver(self)->FindDevices(devList);
}

OSStatus	MIDIDriverStart(MIDIDriverRef self, MIDIDeviceListRef devList)
{
	return GetMIDIDriver(self)->Start(devList);
}

OSStatus	MIDIDriverStop(MIDIDriverRef self)
{
	return GetMIDIDriver(self)->Stop();
}

OSStatus	MIDIDriverConfigure(MIDIDriverRef self, MIDIDeviceRef device)
{
	return GetMIDIDriver(self)->Configure(device);
}

OSStatus	MIDIDriverSend(MIDIDriverRef self, const MIDIPacketList *pktlist,
				void *destRefCon1, void *destRefCon2)
{
	return GetMIDIDriver(self)->Send(pktlist, destRefCon1, destRefCon2);
}

OSStatus	MIDIDriverEnableSource(MIDIDriverRef self, MIDIEndpointRef src, Boolean enabled)
{
	return GetMIDIDriver(self)->EnableSource(src, enabled);
}

OSStatus	MIDIDriverFlush(MIDIDriverRef self, MIDIEndpointRef dest, void *destRefCon1, void *destRefCon2)
{
	return GetMIDIDriver(self)->Flush(dest, destRefCon1, destRefCon2);
}

OSStatus	MIDIDriverMonitor(MIDIDriverRef self, MIDIEndpointRef dest, const MIDIPacketList *pktlist)
{
	return GetMIDIDriver(self)->Monitor(dest, pktlist);
}

// The MIDIDriverInterface function table.
static MIDIDriverInterface MIDIDriverInterfaceFtbl = {
	NULL, // Required padding for COM
	//
	// These are the required COM functions
	MIDIDriverQueryInterface,
	MIDIDriverAddRef,
	MIDIDriverRelease,
	//
	// These are the MIDIDriver methods
	MIDIDriverFindDevices,
	MIDIDriverStart,
	MIDIDriverStop,
	MIDIDriverConfigure,
	MIDIDriverSend,
	MIDIDriverEnableSource,
	MIDIDriverFlush,
	MIDIDriverMonitor
};

MIDIDriver::MIDIDriver(CFUUIDRef factoryID)
{
	// Point to the function table
	mInterface = &MIDIDriverInterfaceFtbl;

	// Retain and keep an open instance refcount for each factory.
	mFactoryID = factoryID;
	CFPlugInAddInstanceForFactory(factoryID);

	mRefCount = 1;
	mVersion = 0;
}

MIDIDriver::~MIDIDriver()
{
	if (mFactoryID) {
		CFPlugInRemoveInstanceForFactory(mFactoryID);
		// CFRelease(mFactoryID); this came from CFUUIDGetConstantUUIDWithBytes which
		// says that it is immortal and should never be released
	}
}
<|endoftext|>


<commit_before>#include "pch.h"
#include "VendingMachine.h"
#include "GameManager.h"
#include "SoundManager.h"
#include "SpriteComponent.h"
#include "AnimationComponent.h"
#include "InputManager.h"
#include "ComponentManager.h"
#include "StageManager.h"
#include "HPKit.h"
#include "SpriteComponent.h"

#define KITNUM 2
#define VENDING_WIDTH 50
#define VENDING_HEIGHT 90

bool VendingMachine::init()
{
	if (!NPC::init())
	{
		return false;
	}

	//Ÿ vendingMachine ٲ Ѵ.
	m_Type = OT_VENDING_MACHINE;
	m_Info.m_Size = cocos2d::Size(VENDING_WIDTH, VENDING_HEIGHT);

	//kitnum ʱȭ
	m_KitNum = KITNUM;

	//ڽ
	auto meterial = cocos2d::PhysicsMaterial(0, 0, 0);
	m_Body = cocos2d::PhysicsBody::createBox(m_Info.m_Size, meterial, cocos2d::Point(0, 0));
	m_Body->setContactTestBitmask(PHYC_PLAYER);
	m_Body->setCategoryBitmask(PHYC_NPC);
	m_Body->setCollisionBitmask(PHYC_PLAYER | PHYC_BLOCK);
	m_Body->setMass(10);
	m_Body->setRotationEnable(false);
	m_Body->setVelocityLimit(1000);
	setPhysicsBody(m_Body);
	m_Body->retain();

	//Ʈ ʱȭ
	m_FirstSprite = GET_COMPONENT_MANAGER()->createComponent<SpriteComponent>();
	m_FirstSprite->initSprite(ST_VENDING_MACHINE, this);
	m_FirstSprite->retain();
	m_FirstSprite->enter();

	//ִϸ̼ ʱȭ
	m_ContactAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();
	m_ContactAni->setAnimation(AT_VENDING_MACHINE_CONTACT, this, 1, false);
	m_ContactAni->retain();
	m_SeperateAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();
	m_SeperateAni->setAnimation(AT_VENDING_MACHINE_SEPERATE, this, 1, false);
	m_SeperateAni->retain();

	return true;
}

void VendingMachine::update(float dTime)
{
	Creature::update(dTime);
	if (m_OnContact)
	{

		if (GET_INPUT_MANAGER()->getKeyState(KC_INTERACT) == KS_PRESS)
		{
			if (m_KitNum > 0)
			{
				--m_KitNum;
				//⼭ ÷̾  ٿ Ǵµ

				//⼭ ŰƮ
				int roomNum = GET_STAGE_MANAGER()->getRoomNum();
				auto hpKit = HPKit::create();
				GET_STAGE_MANAGER()->addObject(hpKit, roomNum, getPosition(), GAME_OBJECT);

				if (m_KitNum <= 0)
				{
					m_IsDead = true;
				}
			}
		}
	}
}

void VendingMachine::enter()
{
	resume();
	m_FirstSprite->enter();
}

void VendingMachine::exit()
{
	removeFromParent();
}

void VendingMachine::dead()
{
	exit();
}

bool VendingMachine::onContactBegin(cocos2d::PhysicsContact& contact)
{
	auto bodyA = contact.getShapeA()->getBody();
	auto bodyB = contact.getShapeB()->getBody();
	auto componentA = (BaseComponent*)bodyA->getNode();
	auto componentB = (BaseComponent*)bodyB->getNode();
	BaseComponent* enemyComponent;
	BaseComponent* myComponent;

	bool isComponentA = true;

	if (componentA->getType() == getType())
	{
		enemyComponent = componentB;
		myComponent = componentA;
		isComponentA = true;
	}
	else
	{
		enemyComponent = componentA;
		myComponent = componentB;
		isComponentA = false;
	}

	if ((m_LockOwner == nullptr || m_LockOwner == myComponent)
		&& enemyComponent->getPhysicsBody()->getCategoryBitmask() == PHYC_PLAYER)
	{
		m_LockOwner = myComponent;
		m_OnContact = true;
		m_MessageBox->enter();
	}

	m_SeperateAni->exit();
	m_FirstSprite->exit();
	m_ContactAni->enter();

	return true;
}

void VendingMachine::onContactSeparate(cocos2d::PhysicsContact& contact)
{
	m_ContactAni->exit();
	m_FirstSprite->exit();
	m_SeperateAni->enter();
	m_OnContact = false;
	m_MessageBox->exit();
}

<commit_msg>벤딩머신 속도 빠르게<commit_after>#include "pch.h"
#include "VendingMachine.h"
#include "GameManager.h"
#include "SoundManager.h"
#include "SpriteComponent.h"
#include "AnimationComponent.h"
#include "InputManager.h"
#include "ComponentManager.h"
#include "StageManager.h"
#include "HPKit.h"
#include "SpriteComponent.h"

#define KITNUM 2
#define VENDING_WIDTH 50
#define VENDING_HEIGHT 90

bool VendingMachine::init()
{
	if (!NPC::init())
	{
		return false;
	}

	//Ÿ vendingMachine ٲ Ѵ.
	m_Type = OT_VENDING_MACHINE;
	m_Info.m_Size = cocos2d::Size(VENDING_WIDTH, VENDING_HEIGHT);

	//kitnum ʱȭ
	m_KitNum = KITNUM;

	//ڽ
	auto meterial = cocos2d::PhysicsMaterial(0, 0, 0);
	m_Body = cocos2d::PhysicsBody::createBox(m_Info.m_Size, meterial, cocos2d::Point(0, 0));
	m_Body->setContactTestBitmask(PHYC_PLAYER);
	m_Body->setCategoryBitmask(PHYC_NPC);
	m_Body->setCollisionBitmask(PHYC_PLAYER | PHYC_BLOCK);
	m_Body->setMass(10);
	m_Body->setRotationEnable(false);
	m_Body->setVelocityLimit(1000);
	setPhysicsBody(m_Body);
	m_Body->retain();

	//Ʈ ʱȭ
	m_FirstSprite = GET_COMPONENT_MANAGER()->createComponent<SpriteComponent>();
	m_FirstSprite->initSprite(ST_VENDING_MACHINE, this);
	m_FirstSprite->retain();
	m_FirstSprite->enter();

	//ִϸ̼ ʱȭ
	m_ContactAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();
	m_ContactAni->setAnimation(AT_VENDING_MACHINE_CONTACT, this, 1, false);
	m_ContactAni->retain();
	m_ContactAni->exit();
	m_SeperateAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();
	m_SeperateAni->setAnimation(AT_VENDING_MACHINE_SEPERATE, this, 1, false);
	m_SeperateAni->retain();
	m_SeperateAni->exit();

	return true;
}

void VendingMachine::update(float dTime)
{
	Creature::update(dTime);
	if (m_OnContact)
	{

		if (GET_INPUT_MANAGER()->getKeyState(KC_INTERACT) == KS_PRESS)
		{
			if (m_KitNum > 0)
			{
				--m_KitNum;
				//⼭ ÷̾  ٿ Ǵµ

				//⼭ ŰƮ
				int roomNum = GET_STAGE_MANAGER()->getRoomNum();
				auto hpKit = HPKit::create();
				GET_STAGE_MANAGER()->addObject(hpKit, roomNum, getPosition(), GAME_OBJECT);

				if (m_KitNum <= 0)
				{
					m_IsDead = true;
				}
			}
		}
	}
}

void VendingMachine::enter()
{
	resume();
	m_FirstSprite->enter();
}

void VendingMachine::exit()
{
	removeFromParent();
}

void VendingMachine::dead()
{
	exit();
}

bool VendingMachine::onContactBegin(cocos2d::PhysicsContact& contact)
{
	auto bodyA = contact.getShapeA()->getBody();
	auto bodyB = contact.getShapeB()->getBody();
	auto componentA = (BaseComponent*)bodyA->getNode();
	auto componentB = (BaseComponent*)bodyB->getNode();
	BaseComponent* enemyComponent;
	BaseComponent* myComponent;

	bool isComponentA = true;

	if (componentA->getType() == getType())
	{
		enemyComponent = componentB;
		myComponent = componentA;
		isComponentA = true;
	}
	else
	{
		enemyComponent = componentA;
		myComponent = componentB;
		isComponentA = false;
	}

	if ((m_LockOwner == nullptr || m_LockOwner == myComponent)
		&& enemyComponent->getPhysicsBody()->getCategoryBitmask() == PHYC_PLAYER)
	{
		m_LockOwner = myComponent;
		m_OnContact = true;
		m_MessageBox->enter();
		m_SeperateAni->exit();
		m_FirstSprite->exit();
		m_ContactAni->enter();

	}

	return true;
}

void VendingMachine::onContactSeparate(cocos2d::PhysicsContact& contact)
{
	m_ContactAni->exit();
	m_FirstSprite->exit();
	m_SeperateAni->enter();
	m_OnContact = false;
	m_MessageBox->exit();
}

<|endoftext|>