<commit_before>/*  This file is part of the KDE project.

Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

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 or 3 of the License.

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, see <http://www.gnu.org/licenses/>.
*/

#include "videowidget.h"

#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include <QtCore/QTimer>
#include <QtCore/QSettings>

#include "mediaobject.h"

#include "videorenderer_vmr9.h"
#include "videorenderer_soft.h"

QT_BEGIN_NAMESPACE

#ifndef QT_NO_PHONON_VIDEO

namespace Phonon
{
    namespace DS9
    {
        //class used internally to return the widget where the video is shown on
        class VideoWindow : public QWidget
        {
        public:
            explicit VideoWindow(QWidget *parent, VideoWidget *vw)
                : QWidget(parent), m_node(vw), m_currentRenderer(0)
            {
                //default background color
                setPalette(QPalette(Qt::black));
                setAttribute(Qt::WA_OpaquePaintEvent, true);
                setAttribute(Qt::WA_NoSystemBackground, true);
                setAttribute(Qt::WA_PaintOnScreen, true);
                setAutoFillBackground(false);
            }

            QPaintEngine* paintEngine() const
            {
                return 0;
            }

            bool isEmbedded() const
            {
#if QT_VERSION >= 0x040400
                return window()->testAttribute(Qt::WA_DontShowOnScreen);
#else
                return false;
#endif
            }

            bool needsSoftRendering() const
            {
                QPaintDevice *dev = QPainter::redirected(this, 0);
                return (dev && dev != this);
            }

            void resizeEvent(QResizeEvent *e)
            {
                m_node->updateVideoSize();
                QWidget::resizeEvent(e);
            }

            AbstractVideoRenderer *currentRenderer() const
            {
                return m_currentRenderer;
            }

            void setCurrentRenderer(AbstractVideoRenderer *renderer)
            {
                m_currentRenderer = renderer;
                //we disallow repaint on that widget for just a fraction of second
                //this allows better transition between videos
                setUpdatesEnabled(false);
                m_flickerFreeTimer.start(20, this);
            }

            void timerEvent(QTimerEvent *e)
            {
                if (e->timerId() == m_flickerFreeTimer.timerId()) {
                    m_flickerFreeTimer.stop();
                    setUpdatesEnabled(true);
                }
                QWidget::timerEvent(e);
            }

            QSize sizeHint() const
            {
                return m_currentRenderer->sizeHint().expandedTo(QWidget::sizeHint());
            }

            void changeEvent(QEvent *e)
            {
                checkCurrentRenderingMode();
                QWidget::changeEvent(e);
            }

            void setVisible(bool visible)
            {
                checkCurrentRenderingMode();
                QWidget::setVisible(visible);
            }

            void paintEvent(QPaintEvent *e)
            {
                if (!updatesEnabled())
                    return; //this avoids repaint from native events
                checkCurrentRenderingMode();
                m_currentRenderer->repaintCurrentFrame(this, e->rect());
            }

            //this code manages the activation/deactivation of the screensaver
            /*bool event(QEvent *e)
            {
                if (e->type() == QEvent::Resize) {
                    //we disable the screensaver if the video is in fullscreen mode
                    disableScreenSaver(window()->windowState() & Qt::WindowFullScreen);
                }
                return QWidget::event(e);
            }*/

        private:
            //for fullscreen mode
            void disableScreenSaver(bool b)
            {
                const QLatin1String screenSaverActive("ScreenSaveActive");
                QSettings settings( QLatin1String("HKEY_CURRENT_USER\\Control Panel\\Desktop"), QSettings::NativeFormat);
                if (b) {
                    if (m_restoreScreenSaverActive.isNull()) {
                        //we store the value to be able to restore it later
                        m_restoreScreenSaverActive = settings.value(screenSaverActive);
                        settings.setValue(screenSaverActive, QString::number(!b));
                    }
                } else if (!m_restoreScreenSaverActive.isNull()) {
                    //we restore the previous value
                    settings.setValue(screenSaverActive, m_restoreScreenSaverActive);
                }
            }

            void checkCurrentRenderingMode()
            {
                if (!m_currentRenderer)
                    return;

                if (m_currentRenderer->isNative()) {
                    if (isEmbedded()) {
                        //we need to switch to software renderer
                        m_currentRenderer = m_node->switchRendering(m_currentRenderer);
                        setAttribute(Qt::WA_PaintOnScreen, false);
                    } else if (needsSoftRendering()) {
                        m_node->performSoftRendering(m_currentRenderer->snapshot());
                    }
                } else if (!isEmbedded()) {
                    m_currentRenderer = m_node->switchRendering(m_currentRenderer);
                    setAttribute(Qt::WA_PaintOnScreen, true);
                }
            }

            VideoWidget *m_node;
            AbstractVideoRenderer *m_currentRenderer;
            QVariant m_restoreScreenSaverActive;
            QBasicTimer m_flickerFreeTimer;
        };

        VideoWidget::VideoWidget(QWidget *parent)
            : BackendNode(parent), m_aspectRatio(Phonon::VideoWidget::AspectRatioAuto),
              m_scaleMode(Phonon::VideoWidget::FitInView),
              m_brightness(0.), m_contrast(0.), m_hue(0.), m_saturation(0.), m_noNativeRendererSupported(false)

        {
            //initialisation of the widget
            m_widget = new VideoWindow(parent, this);

            //initialization of the renderers
            qMemSet(m_renderers, 0, sizeof(m_renderers));

            for(int i = 0; i< FILTER_COUNT ;++i) {
                //This might return a non native (ie Qt) renderer in case native is not supported
                AbstractVideoRenderer *renderer = getRenderer(i, Native, true);
                m_filters[i] = renderer->getFilter();
            }

            //by default, we take the first VideoWindow object
            setCurrentGraph(0);
        }

        VideoWidget::~VideoWidget()
        {
            for (int i = 0; i < 4; ++i) {
                delete m_renderers[i];
            }
        }

        void VideoWidget::notifyVideoLoaded()
        {
            updateVideoSize();
            m_widget->updateGeometry();
        }

        AbstractVideoRenderer *VideoWidget::switchRendering(AbstractVideoRenderer *current)
        {
            const bool toNative = !current->isNative();
            if (toNative && m_noNativeRendererSupported)
                return current; //no switch here

            if (!mediaObject())
                return current;

            //firt we delete the renderer
            //initialization of the widgets
            for(int i = 0; i < FILTER_COUNT; ++i) {
                Filter oldFilter = m_filters[i];

                //Let's create a software renderer
                AbstractVideoRenderer *renderer = getRenderer(i, toNative ? Native : NonNative, true);

                if (m_mediaObject) {
                    m_mediaObject->switchFilters(i, oldFilter, renderer->getFilter());
                }

                m_filters[i] = renderer->getFilter();
            }

            return getRenderer(mediaObject()->currentGraph()->index(), toNative ? Native: NonNative);
        }

        void VideoWidget::performSoftRendering(const QImage &currentImage)
        {
            const int graphIndex = mediaObject()->currentGraph()->index();
            VideoRendererSoft *r = static_cast<VideoRendererSoft*>(getRenderer(graphIndex, NonNative, true /*autocreation*/));
            r->setSnapshot(currentImage);
            r->notifyResize(m_widget->size(), m_aspectRatio, m_scaleMode);
            r->repaintCurrentFrame(m_widget, m_widget->rect());

        }

        void VideoWidget::setCurrentGraph(int index)
        {
            for(int i = 0; i < 2; ++i) {
                if (AbstractVideoRenderer *renderer = getRenderer(i, Native))
                    renderer->setActive(index == i);
            }

            //be sure to update all the things that needs an update
            applyMixerSettings();
            updateVideoSize();

            AbstractVideoRenderer *r = m_widget->currentRenderer();

            //we determine dynamically if it is native or non native
            r = getRenderer(index, !r || r->isNative() ? Native : NonNative);
			if (!r)
				r = getRenderer(index, NonNative);
            m_widget->setCurrentRenderer(r);
        }

        Phonon::VideoWidget::AspectRatio VideoWidget::aspectRatio() const
        {
            return m_aspectRatio;
        }

        void VideoWidget::setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio)
        {
            m_aspectRatio = aspectRatio;
            updateVideoSize();
            m_widget->update();
        }

        Phonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const
        {
            return m_scaleMode;
        }

        QWidget *VideoWidget::widget()
        {
            return m_widget;
        }

        void VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode)
        {
            m_scaleMode = scaleMode;
            updateVideoSize();
            m_widget->update();
        }

        void VideoWidget::setBrightness(qreal b)
        {
            m_brightness = b;
            applyMixerSettings();
        }

        void VideoWidget::setContrast(qreal c)
        {
            m_contrast = c;
            applyMixerSettings();
        }

        void VideoWidget::setHue(qreal h)
        {
            m_hue = h;
            applyMixerSettings();
        }

        void VideoWidget::setSaturation(qreal s)
        {
            m_saturation = s;
            applyMixerSettings();
        }

        qreal VideoWidget::brightness() const
        {
            return m_brightness;
        }

        qreal VideoWidget::contrast() const
        {
            return m_contrast;
        }

        qreal VideoWidget::hue() const
        {
            return m_hue;
        }

        qreal VideoWidget::saturation() const
        {
            return m_saturation;
        }

        AbstractVideoRenderer *VideoWidget::getRenderer(int graphIndex, RendererType type, bool autoCreate)
        {
            int index = graphIndex * 2 + type;
            if (m_renderers[index] == 0 && autoCreate) {
                AbstractVideoRenderer *renderer = 0;
				if (type == Native) {
                    renderer = new VideoRendererVMR9(m_widget);
                    if (renderer->getFilter() == 0) {
                        //instanciating the renderer might fail with error VFW_E_DDRAW_CAPS_NOT_SUITABLE (0x80040273)
                        m_noNativeRendererSupported = true;
                        delete renderer;
                        renderer = 0;
                    }
                }

                if (renderer == 0) {
                    type = NonNative;
                    index = graphIndex * 2 + type;
                    if (m_renderers[index] == 0)
                        renderer = new VideoRendererSoft(m_widget); //this always succeeds
                    else
                        renderer = m_renderers[index];
                }

                m_renderers[index] = renderer;

                //be sure to update all the things that needs an update
                applyMixerSettings();
                updateVideoSize();

            }
            return m_renderers[index];
        }

        //this must be called whe nthe node is actually connected
        void  VideoWidget::applyMixerSettings() const
        {
            for (int i = 0; i < 4; ++i) {
                if (AbstractVideoRenderer *renderer = m_renderers[i])
                    renderer->applyMixerSettings(m_brightness, m_contrast, m_hue, m_saturation);
            }
        }

        void VideoWidget::connected(BackendNode *, const InputPin&)
        {
            //in case of a connection, we simply reapply the mixer settings
            applyMixerSettings();
            updateVideoSize();
        }

        void VideoWidget::updateVideoSize() const
        {
            for (int i = 0; i < 4; ++i) {
                if (AbstractVideoRenderer *renderer = m_renderers[i])
                    renderer->notifyResize(m_widget->size(), m_aspectRatio, m_scaleMode);
            }
        }

    }
}

#endif //QT_NO_PHONON_VIDEO

QT_END_NAMESPACE

#include "moc_videowidget.cpp"
<commit_msg>Phonon videos on windows would not show with video acceleration disabled<commit_after>/*  This file is part of the KDE project.

Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

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 or 3 of the License.

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, see <http://www.gnu.org/licenses/>.
*/

#include "videowidget.h"

#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include <QtCore/QTimer>
#include <QtCore/QSettings>

#include "mediaobject.h"

#include "videorenderer_vmr9.h"
#include "videorenderer_soft.h"

QT_BEGIN_NAMESPACE

#ifndef QT_NO_PHONON_VIDEO

namespace Phonon
{
    namespace DS9
    {
        //class used internally to return the widget where the video is shown on
        class VideoWindow : public QWidget
        {
        public:
            explicit VideoWindow(QWidget *parent, VideoWidget *vw)
                : QWidget(parent), m_node(vw), m_currentRenderer(0)
            {
                //default background color
                setPalette(QPalette(Qt::black));
                setAttribute(Qt::WA_OpaquePaintEvent, true);
                setAttribute(Qt::WA_NoSystemBackground, true);
                setAttribute(Qt::WA_PaintOnScreen, true);
                setAutoFillBackground(false);
            }

            QPaintEngine* paintEngine() const
            {
                return 0;
            }

            bool isEmbedded() const
            {
#if QT_VERSION >= 0x040400
                return window()->testAttribute(Qt::WA_DontShowOnScreen);
#else
                return false;
#endif
            }

            bool needsSoftRendering() const
            {
                QPaintDevice *dev = QPainter::redirected(this, 0);
                return (dev && dev != this);
            }

            void resizeEvent(QResizeEvent *e)
            {
                m_node->updateVideoSize();
                QWidget::resizeEvent(e);
            }

            AbstractVideoRenderer *currentRenderer() const
            {
                return m_currentRenderer;
            }

            void setCurrentRenderer(AbstractVideoRenderer *renderer)
            {
                m_currentRenderer = renderer;
                //we disallow repaint on that widget for just a fraction of second
                //this allows better transition between videos
                setUpdatesEnabled(false);
                m_flickerFreeTimer.start(20, this);
            }

            void timerEvent(QTimerEvent *e)
            {
                if (e->timerId() == m_flickerFreeTimer.timerId()) {
                    m_flickerFreeTimer.stop();
                    setUpdatesEnabled(true);
                }
                QWidget::timerEvent(e);
            }

            QSize sizeHint() const
            {
                return m_currentRenderer->sizeHint().expandedTo(QWidget::sizeHint());
            }

            void changeEvent(QEvent *e)
            {
                checkCurrentRenderingMode();
                QWidget::changeEvent(e);
            }

            void setVisible(bool visible)
            {
                checkCurrentRenderingMode();
                QWidget::setVisible(visible);
            }

            void paintEvent(QPaintEvent *e)
            {
                if (!updatesEnabled())
                    return; //this avoids repaint from native events
                checkCurrentRenderingMode();
                m_currentRenderer->repaintCurrentFrame(this, e->rect());
            }

            //this code manages the activation/deactivation of the screensaver
            /*bool event(QEvent *e)
            {
                if (e->type() == QEvent::Resize) {
                    //we disable the screensaver if the video is in fullscreen mode
                    disableScreenSaver(window()->windowState() & Qt::WindowFullScreen);
                }
                return QWidget::event(e);
            }*/

        private:
            //for fullscreen mode
            void disableScreenSaver(bool b)
            {
                const QLatin1String screenSaverActive("ScreenSaveActive");
                QSettings settings( QLatin1String("HKEY_CURRENT_USER\\Control Panel\\Desktop"), QSettings::NativeFormat);
                if (b) {
                    if (m_restoreScreenSaverActive.isNull()) {
                        //we store the value to be able to restore it later
                        m_restoreScreenSaverActive = settings.value(screenSaverActive);
                        settings.setValue(screenSaverActive, QString::number(!b));
                    }
                } else if (!m_restoreScreenSaverActive.isNull()) {
                    //we restore the previous value
                    settings.setValue(screenSaverActive, m_restoreScreenSaverActive);
                }
            }

            void checkCurrentRenderingMode()
            {
                if (!m_currentRenderer)
                    return;

                if (m_currentRenderer->isNative()) {
                    if (isEmbedded()) {
                        //we need to switch to software renderer
                        m_currentRenderer = m_node->switchRendering(m_currentRenderer);
                        setAttribute(Qt::WA_PaintOnScreen, false);
                    } else if (needsSoftRendering()) {
                        m_node->performSoftRendering(m_currentRenderer->snapshot());
                    }
                } else if (!isEmbedded()) {
                    m_currentRenderer = m_node->switchRendering(m_currentRenderer);
                    setAttribute(Qt::WA_PaintOnScreen, false);
                }
            }

            VideoWidget *m_node;
            AbstractVideoRenderer *m_currentRenderer;
            QVariant m_restoreScreenSaverActive;
            QBasicTimer m_flickerFreeTimer;
        };

        VideoWidget::VideoWidget(QWidget *parent)
            : BackendNode(parent), m_aspectRatio(Phonon::VideoWidget::AspectRatioAuto),
              m_scaleMode(Phonon::VideoWidget::FitInView),
              m_brightness(0.), m_contrast(0.), m_hue(0.), m_saturation(0.), m_noNativeRendererSupported(false)

        {
            //initialisation of the widget
            m_widget = new VideoWindow(parent, this);

            //initialization of the renderers
            qMemSet(m_renderers, 0, sizeof(m_renderers));

            for(int i = 0; i< FILTER_COUNT ;++i) {
                //This might return a non native (ie Qt) renderer in case native is not supported
                AbstractVideoRenderer *renderer = getRenderer(i, Native, true);
                m_filters[i] = renderer->getFilter();
            }

            //by default, we take the first VideoWindow object
            setCurrentGraph(0);
        }

        VideoWidget::~VideoWidget()
        {
            for (int i = 0; i < 4; ++i) {
                delete m_renderers[i];
            }
        }

        void VideoWidget::notifyVideoLoaded()
        {
            updateVideoSize();
            m_widget->updateGeometry();
        }

        AbstractVideoRenderer *VideoWidget::switchRendering(AbstractVideoRenderer *current)
        {
            const bool toNative = !current->isNative();
            if (toNative && m_noNativeRendererSupported)
                return current; //no switch here

            if (!mediaObject())
                return current;

            //firt we delete the renderer
            //initialization of the widgets
            for(int i = 0; i < FILTER_COUNT; ++i) {
                Filter oldFilter = m_filters[i];

                //Let's create a software renderer
                AbstractVideoRenderer *renderer = getRenderer(i, toNative ? Native : NonNative, true);

                if (m_mediaObject) {
                    m_mediaObject->switchFilters(i, oldFilter, renderer->getFilter());
                }

                m_filters[i] = renderer->getFilter();
            }

            return getRenderer(mediaObject()->currentGraph()->index(), toNative ? Native: NonNative);
        }

        void VideoWidget::performSoftRendering(const QImage &currentImage)
        {
            const int graphIndex = mediaObject()->currentGraph()->index();
            VideoRendererSoft *r = static_cast<VideoRendererSoft*>(getRenderer(graphIndex, NonNative, true /*autocreation*/));
            r->setSnapshot(currentImage);
            r->notifyResize(m_widget->size(), m_aspectRatio, m_scaleMode);
            r->repaintCurrentFrame(m_widget, m_widget->rect());

        }

        void VideoWidget::setCurrentGraph(int index)
        {
            for(int i = 0; i < 2; ++i) {
                if (AbstractVideoRenderer *renderer = getRenderer(i, Native))
                    renderer->setActive(index == i);
            }

            //be sure to update all the things that needs an update
            applyMixerSettings();
            updateVideoSize();

            AbstractVideoRenderer *r = m_widget->currentRenderer();

            //we determine dynamically if it is native or non native
            r = getRenderer(index, !r || r->isNative() ? Native : NonNative);
			if (!r)
				r = getRenderer(index, NonNative);
            m_widget->setCurrentRenderer(r);
        }

        Phonon::VideoWidget::AspectRatio VideoWidget::aspectRatio() const
        {
            return m_aspectRatio;
        }

        void VideoWidget::setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio)
        {
            m_aspectRatio = aspectRatio;
            updateVideoSize();
            m_widget->update();
        }

        Phonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const
        {
            return m_scaleMode;
        }

        QWidget *VideoWidget::widget()
        {
            return m_widget;
        }

        void VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode)
        {
            m_scaleMode = scaleMode;
            updateVideoSize();
            m_widget->update();
        }

        void VideoWidget::setBrightness(qreal b)
        {
            m_brightness = b;
            applyMixerSettings();
        }

        void VideoWidget::setContrast(qreal c)
        {
            m_contrast = c;
            applyMixerSettings();
        }

        void VideoWidget::setHue(qreal h)
        {
            m_hue = h;
            applyMixerSettings();
        }

        void VideoWidget::setSaturation(qreal s)
        {
            m_saturation = s;
            applyMixerSettings();
        }

        qreal VideoWidget::brightness() const
        {
            return m_brightness;
        }

        qreal VideoWidget::contrast() const
        {
            return m_contrast;
        }

        qreal VideoWidget::hue() const
        {
            return m_hue;
        }

        qreal VideoWidget::saturation() const
        {
            return m_saturation;
        }

        AbstractVideoRenderer *VideoWidget::getRenderer(int graphIndex, RendererType type, bool autoCreate)
        {
            int index = graphIndex * 2 + type;
            if (m_renderers[index] == 0 && autoCreate) {
                AbstractVideoRenderer *renderer = 0;
				if (type == Native) {
                    renderer = new VideoRendererVMR9(m_widget);
                    if (renderer->getFilter() == 0) {
                        //instanciating the renderer might fail with error VFW_E_DDRAW_CAPS_NOT_SUITABLE (0x80040273)
                        m_noNativeRendererSupported = true;
                        delete renderer;
                        renderer = 0;
                    }
                }

                if (renderer == 0) {
                    type = NonNative;
                    index = graphIndex * 2 + type;
                    if (m_renderers[index] == 0)
                        renderer = new VideoRendererSoft(m_widget); //this always succeeds
                    else
                        renderer = m_renderers[index];
                }

                m_renderers[index] = renderer;

                //be sure to update all the things that needs an update
                applyMixerSettings();
                updateVideoSize();

            }
            return m_renderers[index];
        }

        //this must be called whe nthe node is actually connected
        void  VideoWidget::applyMixerSettings() const
        {
            for (int i = 0; i < 4; ++i) {
                if (AbstractVideoRenderer *renderer = m_renderers[i])
                    renderer->applyMixerSettings(m_brightness, m_contrast, m_hue, m_saturation);
            }
        }

        void VideoWidget::connected(BackendNode *, const InputPin&)
        {
            //in case of a connection, we simply reapply the mixer settings
            applyMixerSettings();
            updateVideoSize();
        }

        void VideoWidget::updateVideoSize() const
        {
            for (int i = 0; i < 4; ++i) {
                if (AbstractVideoRenderer *renderer = m_renderers[i])
                    renderer->notifyResize(m_widget->size(), m_aspectRatio, m_scaleMode);
            }
        }

    }
}

#endif //QT_NO_PHONON_VIDEO

QT_END_NAMESPACE

#include "moc_videowidget.cpp"
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/infobars/infobar.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/ui/ui_test.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/spawned_test_server/spawned_test_server.h"

// MediaStreamInfoBarTest -----------------------------------------------------

class MediaStreamInfoBarTest : public WebRtcTestBase {
 public:
  MediaStreamInfoBarTest() {}
  virtual ~MediaStreamInfoBarTest() {}

  // InProcessBrowserTest:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // This test expects to run with fake devices but real UI.
    command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);
    EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream))
        << "Since this test tests the UI we want the real UI!";
  }

 protected:
  content::WebContents* LoadTestPageInTab() {
    EXPECT_TRUE(test_server()->Start());

    const char kMainWebrtcTestHtmlPage[] =
        "files/webrtc/webrtc_jsep01_test.html";
    ui_test_utils::NavigateToURL(
        browser(), test_server()->GetURL(kMainWebrtcTestHtmlPage));
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaStreamInfoBarTest);
};

// Actual tests ---------------------------------------------------------------

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestAllowingUserMedia) {
  content::WebContents* tab_contents = LoadTestPageInTab();
  GetUserMediaAndAccept(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestDenyingUserMedia) {
  content::WebContents* tab_contents = LoadTestPageInTab();
  GetUserMediaAndDeny(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestDismissingInfobar) {
  content::WebContents* tab_contents = LoadTestPageInTab();
  GetUserMediaAndDismiss(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       TestAcceptThenDenyWhichShouldBeSticky) {
#if defined(OS_WIN) && defined(USE_ASH)
  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
    return;
#endif

  content::WebContents* tab_contents = LoadTestPageInTab();

  GetUserMediaAndAccept(tab_contents);
  GetUserMediaAndDeny(tab_contents);

  // Should fail with permission denied right away with no infobar popping up.
  GetUserMedia(tab_contents, kAudioVideoCallConstraints);
  EXPECT_TRUE(PollingWaitUntil("obtainGetUserMediaResult()",
                               kFailedWithErrorPermissionDenied,
                               tab_contents));
  InfoBarService* infobar_service =
      InfoBarService::FromWebContents(tab_contents);
  EXPECT_EQ(0u, infobar_service->infobar_count());
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestAcceptIsNotSticky) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If accept were sticky the second call would hang because it hangs if an
  // infobar does not pop up.
  GetUserMediaAndAccept(tab_contents);
  GetUserMediaAndAccept(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestDismissIsNotSticky) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If dismiss were sticky the second call would hang because it hangs if an
  // infobar does not pop up.
  GetUserMediaAndDismiss(tab_contents);
  GetUserMediaAndDismiss(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       TestDenyingThenClearingStickyException) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  GetUserMediaAndDeny(tab_contents);

  HostContentSettingsMap* settings_map =
      browser()->profile()->GetHostContentSettingsMap();

  settings_map->ClearSettingsForOneType(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
  settings_map->ClearSettingsForOneType(
      CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);

  // If an infobar is not launched now, this will hang.
  GetUserMediaAndDeny(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       DenyingMicDoesNotCauseStickyDenyForCameras) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If mic blocking also blocked cameras, the second call here would hang.
  GetUserMediaWithSpecificConstraintsAndDeny(tab_contents,
                                             kAudioOnlyCallConstraints);
  GetUserMediaWithSpecificConstraintsAndAccept(tab_contents,
                                               kVideoOnlyCallConstraints);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       DenyingCameraDoesNotCauseStickyDenyForMics) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If camera blocking also blocked mics, the second call here would hang.
  GetUserMediaWithSpecificConstraintsAndDeny(tab_contents,
                                             kVideoOnlyCallConstraints);
  GetUserMediaWithSpecificConstraintsAndAccept(tab_contents,
                                               kAudioOnlyCallConstraints);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       DenyingMicStillSucceedsWithCameraForAudioVideoCalls) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If microphone blocking also blocked a AV call, the second call here
  // would hang. The requester should only be granted access to the cam though.
  GetUserMediaWithSpecificConstraintsAndDeny(tab_contents,
                                             kAudioOnlyCallConstraints);
  GetUserMediaWithSpecificConstraintsAndAccept(tab_contents,
                                               kAudioVideoCallConstraints);

  // TODO(phoglund): verify the requester actually only gets video tracks.
}
<commit_msg>Disabling some MediaStreamInfoBarTests on ChromiumOS dbg<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/infobars/infobar.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/ui/ui_test.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/spawned_test_server/spawned_test_server.h"

// MediaStreamInfoBarTest -----------------------------------------------------

class MediaStreamInfoBarTest : public WebRtcTestBase {
 public:
  MediaStreamInfoBarTest() {}
  virtual ~MediaStreamInfoBarTest() {}

  // InProcessBrowserTest:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // This test expects to run with fake devices but real UI.
    command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);
    EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream))
        << "Since this test tests the UI we want the real UI!";
  }

 protected:
  content::WebContents* LoadTestPageInTab() {
    EXPECT_TRUE(test_server()->Start());

    const char kMainWebrtcTestHtmlPage[] =
        "files/webrtc/webrtc_jsep01_test.html";
    ui_test_utils::NavigateToURL(
        browser(), test_server()->GetURL(kMainWebrtcTestHtmlPage));
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaStreamInfoBarTest);
};

// Actual tests ---------------------------------------------------------------

#if defined(OS_CHROMEOS) && !defined(NDEBUG)
#define MAYBE_TestAllowingUserMedia DISABLED_TestAllowingUserMedia
#else
#define MAYBE_TestAllowingUserMedia TestAllowingUserMedia
#endif
IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, MAYBE_TestAllowingUserMedia) {
  content::WebContents* tab_contents = LoadTestPageInTab();
  GetUserMediaAndAccept(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestDenyingUserMedia) {
  content::WebContents* tab_contents = LoadTestPageInTab();
  GetUserMediaAndDeny(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestDismissingInfobar) {
  content::WebContents* tab_contents = LoadTestPageInTab();
  GetUserMediaAndDismiss(tab_contents);
}

#if defined(OS_CHROMEOS) && !defined(NDEBUG)
#define MAYBE_TestAcceptThenDenyWhichShouldBeSticky \
  DISABLED_TestAcceptThenDenyWhichShouldBeSticky
#else
#define MAYBE_TestAcceptThenDenyWhichShouldBeSticky \
  TestAcceptThenDenyWhichShouldBeSticky
#endif
IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       TestAcceptThenDenyWhichShouldBeSticky) {
#if defined(OS_WIN) && defined(USE_ASH)
  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
    return;
#endif

  content::WebContents* tab_contents = LoadTestPageInTab();

  GetUserMediaAndAccept(tab_contents);
  GetUserMediaAndDeny(tab_contents);

  // Should fail with permission denied right away with no infobar popping up.
  GetUserMedia(tab_contents, kAudioVideoCallConstraints);
  EXPECT_TRUE(PollingWaitUntil("obtainGetUserMediaResult()",
                               kFailedWithErrorPermissionDenied,
                               tab_contents));
  InfoBarService* infobar_service =
      InfoBarService::FromWebContents(tab_contents);
  EXPECT_EQ(0u, infobar_service->infobar_count());
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestAcceptIsNotSticky) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If accept were sticky the second call would hang because it hangs if an
  // infobar does not pop up.
  GetUserMediaAndAccept(tab_contents);
  GetUserMediaAndAccept(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest, TestDismissIsNotSticky) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If dismiss were sticky the second call would hang because it hangs if an
  // infobar does not pop up.
  GetUserMediaAndDismiss(tab_contents);
  GetUserMediaAndDismiss(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       TestDenyingThenClearingStickyException) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  GetUserMediaAndDeny(tab_contents);

  HostContentSettingsMap* settings_map =
      browser()->profile()->GetHostContentSettingsMap();

  settings_map->ClearSettingsForOneType(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
  settings_map->ClearSettingsForOneType(
      CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);

  // If an infobar is not launched now, this will hang.
  GetUserMediaAndDeny(tab_contents);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       DenyingMicDoesNotCauseStickyDenyForCameras) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If mic blocking also blocked cameras, the second call here would hang.
  GetUserMediaWithSpecificConstraintsAndDeny(tab_contents,
                                             kAudioOnlyCallConstraints);
  GetUserMediaWithSpecificConstraintsAndAccept(tab_contents,
                                               kVideoOnlyCallConstraints);
}

#if defined(OS_CHROMEOS) && !defined(NDEBUG)
#define MAYBE_DenyingCameraDoesNotCauseStickyDenyForMics \
  DISABLED_DenyingCameraDoesNotCauseStickyDenyForMics
#else
#define MAYBE_DenyingCameraDoesNotCauseStickyDenyForMics \
  DenyingCameraDoesNotCauseStickyDenyForMics
#endif
IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       DenyingCameraDoesNotCauseStickyDenyForMics) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If camera blocking also blocked mics, the second call here would hang.
  GetUserMediaWithSpecificConstraintsAndDeny(tab_contents,
                                             kVideoOnlyCallConstraints);
  GetUserMediaWithSpecificConstraintsAndAccept(tab_contents,
                                               kAudioOnlyCallConstraints);
}

IN_PROC_BROWSER_TEST_F(MediaStreamInfoBarTest,
                       DenyingMicStillSucceedsWithCameraForAudioVideoCalls) {
  content::WebContents* tab_contents = LoadTestPageInTab();

  // If microphone blocking also blocked a AV call, the second call here
  // would hang. The requester should only be granted access to the cam though.
  GetUserMediaWithSpecificConstraintsAndDeny(tab_contents,
                                             kAudioOnlyCallConstraints);
  GetUserMediaWithSpecificConstraintsAndAccept(tab_contents,
                                               kAudioVideoCallConstraints);

  // TODO(phoglund): verify the requester actually only gets video tracks.
}
<|endoftext|>


<commit_before><commit_msg>RTF filter: import text box shapes as a Writer textframe<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/tab_contents/render_view_host_delegate_helper.h"

#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"

BackgroundContents*
RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(
    int route_id,
    Profile* profile,
    SiteInstance* site,
    GURL opener_url,
    const string16& frame_name) {
  ExtensionsService* extensions_service = profile->GetExtensionsService();

  if (!opener_url.is_valid() ||
      frame_name.empty() ||
      !extensions_service ||
      !extensions_service->is_ready())
    return NULL;

  Extension* extension = extensions_service->GetExtensionByURL(opener_url);
  if (!extension)
    extension = extensions_service->GetExtensionByWebExtent(opener_url);
  if (!extension ||
      !extension->HasApiPermission(Extension::kBackgroundPermission))
    return NULL;

  // Only allow a single background contents per app.
  if (!profile->GetBackgroundContentsService() ||
      profile->GetBackgroundContentsService()->GetAppBackgroundContents(
          ASCIIToUTF16(extension->id())))
    return NULL;

  // Ensure that we're trying to open this from the extension's process.
  ExtensionProcessManager* process_manager =
      profile->GetExtensionProcessManager();
  if (!site->GetProcess() || !process_manager ||
      site->GetProcess() != process_manager->GetExtensionProcess(opener_url))
    return NULL;

  // Passed all the checks, so this should be created as a BackgroundContents.
  BackgroundContents* contents = new BackgroundContents(site, route_id);
  string16 appid = ASCIIToUTF16(extension->id());
  BackgroundContentsOpenedDetails details = { contents, frame_name, appid };
  NotificationService::current()->Notify(
      NotificationType::BACKGROUND_CONTENTS_OPENED,
      Source<Profile>(profile),
      Details<BackgroundContentsOpenedDetails>(&details));

  return contents;
}

TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(
    int route_id,
    Profile* profile,
    SiteInstance* site,
    DOMUITypeID domui_type,
    RenderViewHostDelegate* opener,
    WindowContainerType window_container_type,
    const string16& frame_name) {
  if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
    BackgroundContents* contents = MaybeCreateBackgroundContents(
        route_id,
        profile,
        site,
        opener->GetURL(),
        frame_name);
    if (contents) {
      pending_contents_[route_id] = contents->render_view_host();
      return NULL;
    }
  }

  // Create the new web contents. This will automatically create the new
  // TabContentsView. In the future, we may want to create the view separately.
  TabContents* new_contents =
      new TabContents(profile,
                      site,
                      route_id,
                      opener->GetAsTabContents());
  new_contents->set_opener_dom_ui_type(domui_type);
  TabContentsView* new_view = new_contents->view();

  // TODO(brettw) it seems bogus that we have to call this function on the
  // newly created object and give it one of its own member variables.
  new_view->CreateViewForWidget(new_contents->render_view_host());

  // Save the created window associated with the route so we can show it later.
  pending_contents_[route_id] = new_contents->render_view_host();
  return new_contents;
}

RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(
    int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {
  RenderWidgetHost* widget_host =
      new RenderWidgetHost(process, route_id);
  RenderWidgetHostView* widget_view =
      RenderWidgetHostView::CreateViewForWidget(widget_host);
  // Popups should not get activated.
  widget_view->set_popup_type(popup_type);
  // Save the created widget associated with the route so we can show it later.
  pending_widget_views_[route_id] = widget_view;
  return widget_view;
}

TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {
  PendingContents::iterator iter = pending_contents_.find(route_id);
  if (iter == pending_contents_.end()) {
    DCHECK(false);
    return NULL;
  }

  RenderViewHost* new_rvh = iter->second;
  pending_contents_.erase(route_id);

  // The renderer crashed or it is a TabContents and has no view.
  if (!new_rvh->process()->HasConnection() ||
      (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))
    return NULL;

  // TODO(brettw) this seems bogus to reach into here and initialize the host.
  new_rvh->Init();
  return new_rvh->delegate()->GetAsTabContents();
}

RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(
    int route_id) {
  PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
  if (iter == pending_widget_views_.end()) {
    DCHECK(false);
    return NULL;
  }

  RenderWidgetHostView* widget_host_view = iter->second;
  pending_widget_views_.erase(route_id);

  RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
  if (!widget_host->process()->HasConnection()) {
    // The view has gone away or the renderer crashed. Nothing to do.
    return NULL;
  }

  return widget_host_view;
}

void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(
    RenderWidgetHost* host) {
  for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
       i != pending_widget_views_.end(); ++i) {
    if (host->view() == i->second) {
      pending_widget_views_.erase(i);
      return;
    }
  }
}

// static
WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(
    Profile* profile, bool is_dom_ui) {
  PrefService* prefs = profile->GetPrefs();
  WebPreferences web_prefs;

  web_prefs.fixed_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily));
  web_prefs.serif_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily));
  web_prefs.sans_serif_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily));
  if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))
    web_prefs.standard_font_family = web_prefs.serif_font_family;
  else
    web_prefs.standard_font_family = web_prefs.sans_serif_font_family;
  web_prefs.cursive_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily));
  web_prefs.fantasy_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily));

  web_prefs.default_font_size =
      prefs->GetInteger(prefs::kWebKitDefaultFontSize);
  web_prefs.default_fixed_font_size =
      prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
  web_prefs.minimum_font_size =
      prefs->GetInteger(prefs::kWebKitMinimumFontSize);
  web_prefs.minimum_logical_font_size =
      prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);

  web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);

  web_prefs.javascript_can_open_windows_automatically =
      prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
  web_prefs.dom_paste_enabled =
      prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
  web_prefs.shrinks_standalone_images_to_fit =
      prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
  const DictionaryValue* inspector_settings =
      prefs->GetDictionary(prefs::kWebKitInspectorSettings);
  if (inspector_settings) {
    for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());
         iter != inspector_settings->end_keys(); ++iter) {
      std::string value;
      if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))
          web_prefs.inspector_settings.push_back(
              std::make_pair(WideToUTF8(*iter), value));
    }
  }
  web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);

  {  // Command line switches are used for preferences with no user interface.
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    web_prefs.developer_extras_enabled =
        !command_line.HasSwitch(switches::kDisableDevTools);
    web_prefs.javascript_enabled =
        !command_line.HasSwitch(switches::kDisableJavaScript) &&
        prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);
    web_prefs.web_security_enabled =
        !command_line.HasSwitch(switches::kDisableWebSecurity) &&
        prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);
    web_prefs.plugins_enabled =
        !command_line.HasSwitch(switches::kDisablePlugins) &&
        prefs->GetBoolean(prefs::kWebKitPluginsEnabled);
    web_prefs.java_enabled =
        !command_line.HasSwitch(switches::kDisableJava) &&
        prefs->GetBoolean(prefs::kWebKitJavaEnabled);
    web_prefs.loads_images_automatically =
        prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
    web_prefs.uses_page_cache =
        command_line.HasSwitch(switches::kEnableFastback);
    web_prefs.remote_fonts_enabled =
        !command_line.HasSwitch(switches::kDisableRemoteFonts);
    web_prefs.xss_auditor_enabled =
        command_line.HasSwitch(switches::kEnableXSSAuditor);
    web_prefs.application_cache_enabled =
        !command_line.HasSwitch(switches::kDisableApplicationCache);

    web_prefs.local_storage_enabled =
        !command_line.HasSwitch(switches::kDisableLocalStorage);
    web_prefs.databases_enabled =
        !command_line.HasSwitch(switches::kDisableDatabases);
    web_prefs.experimental_webgl_enabled =
        command_line.HasSwitch(switches::kEnableExperimentalWebGL);
    web_prefs.site_specific_quirks_enabled =
        !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
    web_prefs.allow_file_access_from_file_urls =
        command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
    web_prefs.show_composited_layer_borders =
        command_line.HasSwitch(switches::kShowCompositedLayerBorders);
    web_prefs.accelerated_compositing_enabled =
        command_line.HasSwitch(switches::kEnableAcceleratedCompositing);
    web_prefs.accelerated_2d_canvas_enabled =
        command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);
    web_prefs.memory_info_enabled =
        command_line.HasSwitch(switches::kEnableMemoryInfo);
    // The user stylesheet watcher may not exist in a testing profile.
    if (profile->GetUserStyleSheetWatcher()) {
      web_prefs.user_style_sheet_enabled = true;
      web_prefs.user_style_sheet_location =
          profile->GetUserStyleSheetWatcher()->user_style_sheet();
    } else {
      web_prefs.user_style_sheet_enabled = false;
    }
  }

  web_prefs.uses_universal_detector =
      prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
  web_prefs.text_areas_are_resizable =
      prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);

  // Make sure we will set the default_encoding with canonical encoding name.
  web_prefs.default_encoding =
      CharacterEncoding::GetCanonicalEncodingNameByAliasName(
          web_prefs.default_encoding);
  if (web_prefs.default_encoding.empty()) {
    prefs->ClearPref(prefs::kDefaultCharset);
    web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
  }
  DCHECK(!web_prefs.default_encoding.empty());

  if (is_dom_ui) {
    web_prefs.loads_images_automatically = true;
    web_prefs.javascript_enabled = true;
  }

  return web_prefs;
}
<commit_msg>Remove unneeded browser.h include from RVHDelegateHelper.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/tab_contents/render_view_host_delegate_helper.h"

#include "base/command_line.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"

BackgroundContents*
RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(
    int route_id,
    Profile* profile,
    SiteInstance* site,
    GURL opener_url,
    const string16& frame_name) {
  ExtensionsService* extensions_service = profile->GetExtensionsService();

  if (!opener_url.is_valid() ||
      frame_name.empty() ||
      !extensions_service ||
      !extensions_service->is_ready())
    return NULL;

  Extension* extension = extensions_service->GetExtensionByURL(opener_url);
  if (!extension)
    extension = extensions_service->GetExtensionByWebExtent(opener_url);
  if (!extension ||
      !extension->HasApiPermission(Extension::kBackgroundPermission))
    return NULL;

  // Only allow a single background contents per app.
  if (!profile->GetBackgroundContentsService() ||
      profile->GetBackgroundContentsService()->GetAppBackgroundContents(
          ASCIIToUTF16(extension->id())))
    return NULL;

  // Ensure that we're trying to open this from the extension's process.
  ExtensionProcessManager* process_manager =
      profile->GetExtensionProcessManager();
  if (!site->GetProcess() || !process_manager ||
      site->GetProcess() != process_manager->GetExtensionProcess(opener_url))
    return NULL;

  // Passed all the checks, so this should be created as a BackgroundContents.
  BackgroundContents* contents = new BackgroundContents(site, route_id);
  string16 appid = ASCIIToUTF16(extension->id());
  BackgroundContentsOpenedDetails details = { contents, frame_name, appid };
  NotificationService::current()->Notify(
      NotificationType::BACKGROUND_CONTENTS_OPENED,
      Source<Profile>(profile),
      Details<BackgroundContentsOpenedDetails>(&details));

  return contents;
}

TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(
    int route_id,
    Profile* profile,
    SiteInstance* site,
    DOMUITypeID domui_type,
    RenderViewHostDelegate* opener,
    WindowContainerType window_container_type,
    const string16& frame_name) {
  if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
    BackgroundContents* contents = MaybeCreateBackgroundContents(
        route_id,
        profile,
        site,
        opener->GetURL(),
        frame_name);
    if (contents) {
      pending_contents_[route_id] = contents->render_view_host();
      return NULL;
    }
  }

  // Create the new web contents. This will automatically create the new
  // TabContentsView. In the future, we may want to create the view separately.
  TabContents* new_contents =
      new TabContents(profile,
                      site,
                      route_id,
                      opener->GetAsTabContents());
  new_contents->set_opener_dom_ui_type(domui_type);
  TabContentsView* new_view = new_contents->view();

  // TODO(brettw) it seems bogus that we have to call this function on the
  // newly created object and give it one of its own member variables.
  new_view->CreateViewForWidget(new_contents->render_view_host());

  // Save the created window associated with the route so we can show it later.
  pending_contents_[route_id] = new_contents->render_view_host();
  return new_contents;
}

RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(
    int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {
  RenderWidgetHost* widget_host =
      new RenderWidgetHost(process, route_id);
  RenderWidgetHostView* widget_view =
      RenderWidgetHostView::CreateViewForWidget(widget_host);
  // Popups should not get activated.
  widget_view->set_popup_type(popup_type);
  // Save the created widget associated with the route so we can show it later.
  pending_widget_views_[route_id] = widget_view;
  return widget_view;
}

TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {
  PendingContents::iterator iter = pending_contents_.find(route_id);
  if (iter == pending_contents_.end()) {
    DCHECK(false);
    return NULL;
  }

  RenderViewHost* new_rvh = iter->second;
  pending_contents_.erase(route_id);

  // The renderer crashed or it is a TabContents and has no view.
  if (!new_rvh->process()->HasConnection() ||
      (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))
    return NULL;

  // TODO(brettw) this seems bogus to reach into here and initialize the host.
  new_rvh->Init();
  return new_rvh->delegate()->GetAsTabContents();
}

RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(
    int route_id) {
  PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
  if (iter == pending_widget_views_.end()) {
    DCHECK(false);
    return NULL;
  }

  RenderWidgetHostView* widget_host_view = iter->second;
  pending_widget_views_.erase(route_id);

  RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
  if (!widget_host->process()->HasConnection()) {
    // The view has gone away or the renderer crashed. Nothing to do.
    return NULL;
  }

  return widget_host_view;
}

void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(
    RenderWidgetHost* host) {
  for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
       i != pending_widget_views_.end(); ++i) {
    if (host->view() == i->second) {
      pending_widget_views_.erase(i);
      return;
    }
  }
}

// static
WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(
    Profile* profile, bool is_dom_ui) {
  PrefService* prefs = profile->GetPrefs();
  WebPreferences web_prefs;

  web_prefs.fixed_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily));
  web_prefs.serif_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily));
  web_prefs.sans_serif_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily));
  if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))
    web_prefs.standard_font_family = web_prefs.serif_font_family;
  else
    web_prefs.standard_font_family = web_prefs.sans_serif_font_family;
  web_prefs.cursive_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily));
  web_prefs.fantasy_font_family =
      UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily));

  web_prefs.default_font_size =
      prefs->GetInteger(prefs::kWebKitDefaultFontSize);
  web_prefs.default_fixed_font_size =
      prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
  web_prefs.minimum_font_size =
      prefs->GetInteger(prefs::kWebKitMinimumFontSize);
  web_prefs.minimum_logical_font_size =
      prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);

  web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);

  web_prefs.javascript_can_open_windows_automatically =
      prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
  web_prefs.dom_paste_enabled =
      prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
  web_prefs.shrinks_standalone_images_to_fit =
      prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
  const DictionaryValue* inspector_settings =
      prefs->GetDictionary(prefs::kWebKitInspectorSettings);
  if (inspector_settings) {
    for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());
         iter != inspector_settings->end_keys(); ++iter) {
      std::string value;
      if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))
          web_prefs.inspector_settings.push_back(
              std::make_pair(WideToUTF8(*iter), value));
    }
  }
  web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);

  {  // Command line switches are used for preferences with no user interface.
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    web_prefs.developer_extras_enabled =
        !command_line.HasSwitch(switches::kDisableDevTools);
    web_prefs.javascript_enabled =
        !command_line.HasSwitch(switches::kDisableJavaScript) &&
        prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);
    web_prefs.web_security_enabled =
        !command_line.HasSwitch(switches::kDisableWebSecurity) &&
        prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);
    web_prefs.plugins_enabled =
        !command_line.HasSwitch(switches::kDisablePlugins) &&
        prefs->GetBoolean(prefs::kWebKitPluginsEnabled);
    web_prefs.java_enabled =
        !command_line.HasSwitch(switches::kDisableJava) &&
        prefs->GetBoolean(prefs::kWebKitJavaEnabled);
    web_prefs.loads_images_automatically =
        prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
    web_prefs.uses_page_cache =
        command_line.HasSwitch(switches::kEnableFastback);
    web_prefs.remote_fonts_enabled =
        !command_line.HasSwitch(switches::kDisableRemoteFonts);
    web_prefs.xss_auditor_enabled =
        command_line.HasSwitch(switches::kEnableXSSAuditor);
    web_prefs.application_cache_enabled =
        !command_line.HasSwitch(switches::kDisableApplicationCache);

    web_prefs.local_storage_enabled =
        !command_line.HasSwitch(switches::kDisableLocalStorage);
    web_prefs.databases_enabled =
        !command_line.HasSwitch(switches::kDisableDatabases);
    web_prefs.experimental_webgl_enabled =
        command_line.HasSwitch(switches::kEnableExperimentalWebGL);
    web_prefs.site_specific_quirks_enabled =
        !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
    web_prefs.allow_file_access_from_file_urls =
        command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
    web_prefs.show_composited_layer_borders =
        command_line.HasSwitch(switches::kShowCompositedLayerBorders);
    web_prefs.accelerated_compositing_enabled =
        command_line.HasSwitch(switches::kEnableAcceleratedCompositing);
    web_prefs.accelerated_2d_canvas_enabled =
        command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);
    web_prefs.memory_info_enabled =
        command_line.HasSwitch(switches::kEnableMemoryInfo);
    // The user stylesheet watcher may not exist in a testing profile.
    if (profile->GetUserStyleSheetWatcher()) {
      web_prefs.user_style_sheet_enabled = true;
      web_prefs.user_style_sheet_location =
          profile->GetUserStyleSheetWatcher()->user_style_sheet();
    } else {
      web_prefs.user_style_sheet_enabled = false;
    }
  }

  web_prefs.uses_universal_detector =
      prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
  web_prefs.text_areas_are_resizable =
      prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);

  // Make sure we will set the default_encoding with canonical encoding name.
  web_prefs.default_encoding =
      CharacterEncoding::GetCanonicalEncodingNameByAliasName(
          web_prefs.default_encoding);
  if (web_prefs.default_encoding.empty()) {
    prefs->ClearPref(prefs::kDefaultCharset);
    web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
  }
  DCHECK(!web_prefs.default_encoding.empty());

  if (is_dom_ui) {
    web_prefs.loads_images_automatically = true;
    web_prefs.javascript_enabled = true;
  }

  return web_prefs;
}
<|endoftext|>


<commit_before>#include <itkThreadPool.h>

int itkThreadPoolTest(int /*i*/, char** /*argv*/)
{
  itk::ThreadPool::Pointer threadPool = itk::ThreadPool::New();

  return EXIT_SUCCESS;
}

<commit_msg>ADD: unit test for thread pool<commit_after>#include <itkDemoThreadPool.h>
#include <itkTPDemoTask.h>

namespace itk
{
class ExceptionTask : public TPTask
{
  public:
    typedef ExceptionTask Self;
    typedef TPTask Superclass;
    typedef SmartPointer<Self> Pointer;
    itkNewMacro(Self);

    void DoAction()
    {
      itkExceptionMacro("This is a test exception!");
    }
};
}

// first of all a simple thread pool with one task
int testSimpleTask()
{
  std::cout << " *** Testing a simple task ***\n";

  itk::TPDemoTask::Pointer demoTask = itk::TPDemoTask::New();
  demoTask->SetSleepTime(1);

  itk::ThreadPool::Pointer threadPool = itk::ThreadPool::New();
  threadPool->EnqueueTask(demoTask.GetPointer());
  threadPool->Run(1);

  std::cout << " *** [TEST PASSED] ***\n";

  return EXIT_SUCCESS;
}

// now test with the demo task if new tasks can be created
int testTaskCreate()
{
  std::cout << " *** Testing the creation of new tasks ***\n";

  itk::TPDemoTask::Pointer demoTask = itk::TPDemoTask::New();
  demoTask->SetSleepTime(1);

  itk::DemoThreadPool::Pointer threadPool = itk::DemoThreadPool::New();
  threadPool->SetMaxSleepedSeconds(2);
  threadPool->EnqueueTask(demoTask.GetPointer());
  threadPool->Run(1);

  unsigned int runnedTasks = threadPool->GetRunnedTasks();

  if(runnedTasks < 2)
  {
    std::cout << "No tasks have been created!" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << " *** [TEST PASSED] ***\n";

  return EXIT_SUCCESS;
}

int testExceptionTask()
{
  std::cout << " *** Testing the exception handling ***\n";

  try
  {
    itk::ExceptionTask::Pointer exceptionTask = itk::ExceptionTask::New();

    itk::ThreadPool::Pointer threadPool = itk::ThreadPool::New();
    threadPool->EnqueueTask(exceptionTask.GetPointer());
    threadPool->Run(1);
  }
  catch (itk::ExceptionObject &e)
  {
    std::cout << " *** [TEST PASSED] ***\n";
    return EXIT_SUCCESS;
  }

  return EXIT_FAILURE;
}

int itkThreadPoolTest(int /*i*/, char* argv[])
{
  std::list<int> resultList;
  int failedCount = 0;
  int testCount;
  float failRatio;

  resultList.push_back(testSimpleTask());
  resultList.push_back(testTaskCreate());
  resultList.push_back(testExceptionTask());

  std::cout << " *** [ALL TESTS DONE] ***\n";

  testCount = resultList.size();
  bool allSuccess = true;

  while (resultList.size() > 0)
  {
    int value = resultList.front();
    if(value == EXIT_FAILURE)
    {
      failedCount++;
      allSuccess = false;
    }
    resultList.pop_front();
  }

  failRatio = 100 * (float) failedCount / (float) testCount;

  std::cout << "Result: " << failedCount << "/" << testCount << " Tests failed (" << failRatio << " %)" << std::endl;

  if(allSuccess)
  {
    return EXIT_SUCCESS;
  }
  else
  {
    return EXIT_FAILURE;
  }
}

<|endoftext|>


<commit_before>#include "ui_progressbar.h"

#include <util\container.h>
#include <util\math_base.h>

#include "util_sprite.h"

const std::string UIProgressbar::BOTTOM_ANIM_ = "_bottom";
const std::string UIProgressbar::MID_ANIM_ = "_mid";
const std::string UIProgressbar::TOP_ANIM_ = "_top";

UIProgressbar::UIProgressbar()
: hasMidAnim_()
, maxValue_(100.f)
, curValue_()
{

}

void UIProgressbar::Update(float delta)
{
    __super::Update(delta);

    UTIL_FOREACH(i, anims_, Anims)
        i->second.Update(delta);
}

void UIProgressbar::Render(RenderTarget& target) const
{
    UTIL_FOREACH(i, anims_, Anims)
        target.Draw(i->second);

    __super::Render(target);
}

void UIProgressbar::PostSetTopLeft()
{
    __super::PostSetTopLeft();
    if (hasMidAnim_)
        anims_[MID_ANIM_].SetX(GetLeft());
}

void UIProgressbar::PostSetWidthHeight()
{
    __super::PostSetWidthHeight();
    UpdateMidAnim();
}

void UIProgressbar::PostSetAnim(const std::string name, Animation& anim)
{
    __super::PostSetAnim(name, anim);

    if (name == MID_ANIM_)
    {
        hasMidAnim_ = true;
        UpdateMidAnim();
        SetCenter(anims_[MID_ANIM_], 0.f, 0.5f);
        anims_[MID_ANIM_].SetX(GetLeft());
    }
}

void UIProgressbar::UpdateMidAnim()
{
    if (!hasMidAnim_)
        return;

    Vector2f size = GetWidthHeight();
    size.x *= curValue_ / maxValue_;
    size.x = util::ClamUp(size.x, 1.f); //  1 أsize.x <= 0  SFML ڲ
    anims_[MID_ANIM_].Resize(size);
}

void UIProgressbar::SetMaxValue(float val)
{
    maxValue_ = val;
    UpdateMidAnim();
}

void UIProgressbar::SetCurValue(float val)
{
    curValue_ = val;
    UpdateMidAnim();
}
<commit_msg>Fixed UIProgressbar::SetVisibled(bool).<commit_after>#include "ui_progressbar.h"

#include <util\container.h>
#include <util\math_base.h>

#include "util_sprite.h"

const std::string UIProgressbar::BOTTOM_ANIM_ = "_bottom";
const std::string UIProgressbar::MID_ANIM_ = "_mid";
const std::string UIProgressbar::TOP_ANIM_ = "_top";

UIProgressbar::UIProgressbar()
: hasMidAnim_()
, maxValue_(100.f)
, curValue_()
{

}

void UIProgressbar::Update(float delta)
{
  if (!visibled_)
    return;

  __super::Update(delta);

  UTIL_FOREACH(i, anims_, Anims)
    i->second.Update(delta);
}

void UIProgressbar::Render(RenderTarget& target) const
{
  if (!visibled_)
    return;

  UTIL_FOREACH(i, anims_, Anims)
    target.Draw(i->second);

  __super::Render(target);
}

void UIProgressbar::PostSetTopLeft()
{
  __super::PostSetTopLeft();
  if (hasMidAnim_)
    anims_[MID_ANIM_].SetX(GetLeft());
}

void UIProgressbar::PostSetWidthHeight()
{
  __super::PostSetWidthHeight();
  UpdateMidAnim();
}

void UIProgressbar::PostSetAnim(const std::string name, Animation& anim)
{
  __super::PostSetAnim(name, anim);

  if (name == MID_ANIM_)
  {
    hasMidAnim_ = true;
    UpdateMidAnim();
    SetCenter(anims_[MID_ANIM_], 0.f, 0.5f);
    anims_[MID_ANIM_].SetX(GetLeft());
  }
}

void UIProgressbar::UpdateMidAnim()
{
  if (!hasMidAnim_)
    return;

  Vector2f size = GetWidthHeight();
  size.x *= curValue_ / maxValue_;
  size.x = util::ClamUp(size.x, 1.f); //  1 أsize.x <= 0  SFML ڲ
  anims_[MID_ANIM_].Resize(size);
}

void UIProgressbar::SetMaxValue(float val)
{
  maxValue_ = val;
  UpdateMidAnim();
}

void UIProgressbar::SetCurValue(float val)
{
  curValue_ = val;
  UpdateMidAnim();
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkConeSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkConeSource.h"

#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPolyData.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"

#include <math.h>

vtkCxxRevisionMacro(vtkConeSource, "1.76");
vtkStandardNewMacro(vtkConeSource);

//----------------------------------------------------------------------------
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkConeSource::vtkConeSource(int res)
{
  res = (res < 0 ? 0 : res);
  this->Resolution = res;
  this->Height = 1.0;
  this->Radius = 0.5;
  this->Capping = 1;

  this->Center[0] = 0.0;
  this->Center[1] = 0.0;
  this->Center[2] = 0.0;

  this->Direction[0] = 1.0;
  this->Direction[1] = 0.0;
  this->Direction[2] = 0.0;

  this->SetNumberOfInputPorts(0);
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  double angle;
  int numLines, numPolys, numPts;
  double x[3], xbot;
  int i;
  vtkIdType pts[VTK_CELL_SIZE];
  vtkPoints *newPoints;
  vtkCellArray *newLines=0;
  vtkCellArray *newPolys=0;
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));
  // for streaming
  int piece;
  int numPieces;
  int maxPieces;
  int start, end;
  int createBottom;

  piece = output->GetUpdatePiece();
  if (piece >= this->Resolution && !(piece == 0 && this->Resolution == 0))
    {
    return 1;
    }
  numPieces = output->GetUpdateNumberOfPieces();
  maxPieces = this->Resolution != 0 ? this->Resolution : 1;
  if (numPieces > maxPieces)
    {
    numPieces = maxPieces;
    }
  if (piece >= maxPieces)
    {
    // Super class should do this for us,
    // but I put this condition in any way.
    return 1;
    }
  start = maxPieces * piece / numPieces;
  end = (maxPieces * (piece+1) / numPieces) - 1;
  createBottom = (this->Capping && (start == 0));

  vtkDebugMacro("ConeSource Executing");

  if ( this->Resolution )
    {
    angle = 2.0*3.141592654/this->Resolution;
    }
  else
    {
    angle = 0.0;
    }

  // Set things up; allocate memory
  //
  switch ( this->Resolution )
  {
  case 0:
    numPts = 2;
    numLines =  1;
    newLines = vtkCellArray::New();
    newLines->Allocate(newLines->EstimateSize(numLines,numPts));
    break;

  case 1: case 2:
    numPts = 2*this->Resolution + 1;
    numPolys = this->Resolution;
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,3));
    break;

  default:
    if (createBottom)
      {
      // piece 0 has cap.
      numPts = this->Resolution + 1;
      numPolys = end - start + 2;
      }
    else
      {
      numPts = end - start + 3;
      numPolys = end - start + 2;
      }
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution));
    break;
  }
  newPoints = vtkPoints::New();
  newPoints->SetDataTypeToFloat(); //used later during transformation
  newPoints->Allocate(numPts);

  // Create cone
  //
  x[0] = this->Height / 2.0; // zero-centered
  x[1] = 0.0;
  x[2] = 0.0;
  pts[0] = newPoints->InsertNextPoint(x);

  xbot = -this->Height / 2.0;

  switch (this->Resolution)
  {
  case 0:
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    newLines->InsertNextCell(2,pts);
    break;

  case 2:  // fall through this case to use the code in case 1
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = -this->Radius;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = this->Radius;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);

  case 1:
    x[0] = xbot;
    x[1] = -this->Radius;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = this->Radius;
    x[2] = 0.0;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);
    break;

  default: // General case: create Resolution triangles and single cap
    // create the bottom.
    if ( createBottom )
      {
      for (i=0; i < this->Resolution; i++)
        {
        x[0] = xbot;
        x[1] = this->Radius * cos (i*angle);
        x[2] = this->Radius * sin (i*angle);
        // Reverse the order
        pts[this->Resolution - i - 1] = newPoints->InsertNextPoint(x);
        }
      newPolys->InsertNextCell(this->Resolution,pts);
      }

    pts[0] = 0;
    if ( ! createBottom)
      {
      // we need to create the points also
      x[0] = xbot;
      x[1] = this->Radius * cos (start*angle);
      x[2] = this->Radius * sin (start*angle);
      pts[1] = newPoints->InsertNextPoint(x);
      for (i = start; i <= end; ++i)
        {
        x[1] = this->Radius * cos ((i+1)*angle);
        x[2] = this->Radius * sin ((i+1)*angle);
        pts[2] = newPoints->InsertNextPoint(x);
        newPolys->InsertNextCell(3,pts);
        pts[1] = pts[2];
        }
      }
    else
      {
      // bottom and points have already been created.
      for (i=start; i <= end; i++)
        {
        pts[1] = i+1;
        pts[2] = i+2;
        if (pts[2] > this->Resolution)
          {
          pts[2] = 1;
          }
        newPolys->InsertNextCell(3,pts);
        }
      } // createBottom

  } //switch

  // A non-default origin and/or direction requires transformation
  //
  if ( this->Center[0] != 0.0 || this->Center[1] != 0.0 ||
       this->Center[2] != 0.0 || this->Direction[0] != 1.0 ||
       this->Direction[1] != 0.0 || this->Direction[2] != 0.0 )
    {
    vtkTransform *t = vtkTransform::New();
    t->Translate(this->Center[0], this->Center[1], this->Center[2]);
    double vMag = vtkMath::Norm(this->Direction);
    if ( this->Direction[0] < 0.0 )
      {
      // flip x -> -x to avoid instability
      t->RotateWXYZ(180.0, 0, 1, 0);
      t->RotateWXYZ(180.0, (this->Direction[0]-vMag)/2.0,
                    this->Direction[1]/2.0, this->Direction[2]/2.0);
      }
    else
      {
      t->RotateWXYZ(180.0, (this->Direction[0]+vMag)/2.0,
                    this->Direction[1]/2.0, this->Direction[2]/2.0);
      }
    float *ipts=
      static_cast<vtkFloatArray *>(newPoints->GetData())->GetPointer(0);
    for (i=0; i<numPts; i++, ipts+=3)
      {
      t->TransformPoint(ipts,ipts);
      }

    t->Delete();
    }

  // Update ourselves
  //
  output->SetPoints(newPoints);
  newPoints->Delete();

  if ( newPolys )
    {
    newPolys->Squeeze(); // we may have estimated size; reclaim some space
    output->SetPolys(newPolys);
    newPolys->Delete();
    }
  else
    {
    output->SetLines(newLines);
    newLines->Delete();
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestInformation(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
               -1);
  return 1;
}

//----------------------------------------------------------------------------
void vtkConeSource::SetAngle(double angle)
{
  this->SetRadius( this->Height * tan( vtkMath::RadiansFromDegrees( angle ) ) );
}

//----------------------------------------------------------------------------
double vtkConeSource::GetAngle()
{
  return  vtkMath::DegreesFromRadians( atan2( this->Radius, this->Height ) );
}

//----------------------------------------------------------------------------
void vtkConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Height: " << this->Height << "\n";
  os << indent << "Radius: " << this->Radius << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Center: (" << this->Center[0] << ", "
     << this->Center[1] << ", " << this->Center[2] << ")\n";
  os << indent << "Direction: (" << this->Direction[0] << ", "
     << this->Direction[1] << ", " << this->Direction[2] << ")\n";
}
<commit_msg>BUG: Last commit was broken, I forgot that PreMultiply is the transform default.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkConeSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkConeSource.h"

#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPolyData.h"
#include "vtkTransform.h"
#include "vtkCellArray.h"

#include <math.h>

vtkCxxRevisionMacro(vtkConeSource, "1.77");
vtkStandardNewMacro(vtkConeSource);

//----------------------------------------------------------------------------
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkConeSource::vtkConeSource(int res)
{
  res = (res < 0 ? 0 : res);
  this->Resolution = res;
  this->Height = 1.0;
  this->Radius = 0.5;
  this->Capping = 1;

  this->Center[0] = 0.0;
  this->Center[1] = 0.0;
  this->Center[2] = 0.0;

  this->Direction[0] = 1.0;
  this->Direction[1] = 0.0;
  this->Direction[2] = 0.0;

  this->SetNumberOfInputPorts(0);
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  double angle;
  int numLines, numPolys, numPts;
  double x[3], xbot;
  int i;
  vtkIdType pts[VTK_CELL_SIZE];
  vtkPoints *newPoints;
  vtkCellArray *newLines=0;
  vtkCellArray *newPolys=0;
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));
  // for streaming
  int piece;
  int numPieces;
  int maxPieces;
  int start, end;
  int createBottom;

  piece = output->GetUpdatePiece();
  if (piece >= this->Resolution && !(piece == 0 && this->Resolution == 0))
    {
    return 1;
    }
  numPieces = output->GetUpdateNumberOfPieces();
  maxPieces = this->Resolution != 0 ? this->Resolution : 1;
  if (numPieces > maxPieces)
    {
    numPieces = maxPieces;
    }
  if (piece >= maxPieces)
    {
    // Super class should do this for us,
    // but I put this condition in any way.
    return 1;
    }
  start = maxPieces * piece / numPieces;
  end = (maxPieces * (piece+1) / numPieces) - 1;
  createBottom = (this->Capping && (start == 0));

  vtkDebugMacro("ConeSource Executing");

  if ( this->Resolution )
    {
    angle = 2.0*3.141592654/this->Resolution;
    }
  else
    {
    angle = 0.0;
    }

  // Set things up; allocate memory
  //
  switch ( this->Resolution )
  {
  case 0:
    numPts = 2;
    numLines =  1;
    newLines = vtkCellArray::New();
    newLines->Allocate(newLines->EstimateSize(numLines,numPts));
    break;

  case 1: case 2:
    numPts = 2*this->Resolution + 1;
    numPolys = this->Resolution;
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,3));
    break;

  default:
    if (createBottom)
      {
      // piece 0 has cap.
      numPts = this->Resolution + 1;
      numPolys = end - start + 2;
      }
    else
      {
      numPts = end - start + 3;
      numPolys = end - start + 2;
      }
    newPolys = vtkCellArray::New();
    newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution));
    break;
  }
  newPoints = vtkPoints::New();
  newPoints->SetDataTypeToFloat(); //used later during transformation
  newPoints->Allocate(numPts);

  // Create cone
  //
  x[0] = this->Height / 2.0; // zero-centered
  x[1] = 0.0;
  x[2] = 0.0;
  pts[0] = newPoints->InsertNextPoint(x);

  xbot = -this->Height / 2.0;

  switch (this->Resolution)
  {
  case 0:
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    newLines->InsertNextCell(2,pts);
    break;

  case 2:  // fall through this case to use the code in case 1
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = -this->Radius;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = this->Radius;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);

  case 1:
    x[0] = xbot;
    x[1] = -this->Radius;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = this->Radius;
    x[2] = 0.0;
    pts[2] = newPoints->InsertNextPoint(x);
    newPolys->InsertNextCell(3,pts);
    break;

  default: // General case: create Resolution triangles and single cap
    // create the bottom.
    if ( createBottom )
      {
      for (i=0; i < this->Resolution; i++)
        {
        x[0] = xbot;
        x[1] = this->Radius * cos (i*angle);
        x[2] = this->Radius * sin (i*angle);
        // Reverse the order
        pts[this->Resolution - i - 1] = newPoints->InsertNextPoint(x);
        }
      newPolys->InsertNextCell(this->Resolution,pts);
      }

    pts[0] = 0;
    if ( ! createBottom)
      {
      // we need to create the points also
      x[0] = xbot;
      x[1] = this->Radius * cos (start*angle);
      x[2] = this->Radius * sin (start*angle);
      pts[1] = newPoints->InsertNextPoint(x);
      for (i = start; i <= end; ++i)
        {
        x[1] = this->Radius * cos ((i+1)*angle);
        x[2] = this->Radius * sin ((i+1)*angle);
        pts[2] = newPoints->InsertNextPoint(x);
        newPolys->InsertNextCell(3,pts);
        pts[1] = pts[2];
        }
      }
    else
      {
      // bottom and points have already been created.
      for (i=start; i <= end; i++)
        {
        pts[1] = i+1;
        pts[2] = i+2;
        if (pts[2] > this->Resolution)
          {
          pts[2] = 1;
          }
        newPolys->InsertNextCell(3,pts);
        }
      } // createBottom

  } //switch

  // A non-default origin and/or direction requires transformation
  //
  if ( this->Center[0] != 0.0 || this->Center[1] != 0.0 ||
       this->Center[2] != 0.0 || this->Direction[0] != 1.0 ||
       this->Direction[1] != 0.0 || this->Direction[2] != 0.0 )
    {
    vtkTransform *t = vtkTransform::New();
    t->Translate(this->Center[0], this->Center[1], this->Center[2]);
    double vMag = vtkMath::Norm(this->Direction);
    if ( this->Direction[0] < 0.0 )
      {
      // flip x -> -x to avoid instability
      t->RotateWXYZ(180.0, (this->Direction[0]-vMag)/2.0,
                    this->Direction[1]/2.0, this->Direction[2]/2.0);
      t->RotateWXYZ(180.0, 0, 1, 0);
      }
    else
      {
      t->RotateWXYZ(180.0, (this->Direction[0]+vMag)/2.0,
                    this->Direction[1]/2.0, this->Direction[2]/2.0);
      }
    float *ipts=
      static_cast<vtkFloatArray *>(newPoints->GetData())->GetPointer(0);
    for (i=0; i<numPts; i++, ipts+=3)
      {
      t->TransformPoint(ipts,ipts);
      }

    t->Delete();
    }

  // Update ourselves
  //
  output->SetPoints(newPoints);
  newPoints->Delete();

  if ( newPolys )
    {
    newPolys->Squeeze(); // we may have estimated size; reclaim some space
    output->SetPolys(newPolys);
    newPolys->Delete();
    }
  else
    {
    output->SetLines(newLines);
    newLines->Delete();
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkConeSource::RequestInformation(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
               -1);
  return 1;
}

//----------------------------------------------------------------------------
void vtkConeSource::SetAngle(double angle)
{
  this->SetRadius( this->Height * tan( vtkMath::RadiansFromDegrees( angle ) ) );
}

//----------------------------------------------------------------------------
double vtkConeSource::GetAngle()
{
  return  vtkMath::DegreesFromRadians( atan2( this->Radius, this->Height ) );
}

//----------------------------------------------------------------------------
void vtkConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Height: " << this->Height << "\n";
  os << indent << "Radius: " << this->Radius << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
  os << indent << "Center: (" << this->Center[0] << ", "
     << this->Center[1] << ", " << this->Center[2] << ")\n";
  os << indent << "Direction: (" << this->Direction[0] << ", "
     << this->Direction[1] << ", " << this->Direction[2] << ")\n";
}
<|endoftext|>