<commit_before>// Copyright (c) 2012 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 <jni.h>

#include "chrome/browser/android/chrome_startup_flags.h"

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/android/sys_utils.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/common/content_switches.h"
#include "media/base/media_switches.h"

namespace {

void SetCommandLineSwitch(const std::string& switch_string) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switch_string))
    command_line->AppendSwitch(switch_string);
}

void SetCommandLineSwitchASCII(const std::string& switch_string,
                               const std::string& value) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switch_string))
    command_line->AppendSwitchASCII(switch_string, value);
}

}  // namespace

void SetChromeSpecificCommandLineFlags() {
  // Turn on autologin.
  SetCommandLineSwitch(switches::kEnableAutologin);

  // Enable prerender for the omnibox.
  SetCommandLineSwitchASCII(
      switches::kPrerenderMode, switches::kPrerenderModeSwitchValueEnabled);
  SetCommandLineSwitchASCII(
      switches::kPrerenderFromOmnibox,
      switches::kPrerenderFromOmniboxSwitchValueEnabled);
  if (base::android::SysUtils::IsLowEndDevice())
    SetCommandLineSwitch(switches::kDisableSyncFavicons);
}
<commit_msg>[android] Enable DOM distiller by default on development channels.<commit_after>// Copyright (c) 2012 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 <jni.h>

#include "chrome/browser/android/chrome_startup_flags.h"

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/android/sys_utils.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/public/common/content_switches.h"
#include "media/base/media_switches.h"

namespace {

void SetCommandLineSwitch(const std::string& switch_string) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switch_string))
    command_line->AppendSwitch(switch_string);
}

void SetCommandLineSwitchASCII(const std::string& switch_string,
                               const std::string& value) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switch_string))
    command_line->AppendSwitchASCII(switch_string, value);
}

}  // namespace

void SetChromeSpecificCommandLineFlags() {
  // Turn on autologin.
  SetCommandLineSwitch(switches::kEnableAutologin);

  // Enable prerender for the omnibox.
  SetCommandLineSwitchASCII(switches::kPrerenderMode,
                            switches::kPrerenderModeSwitchValueEnabled);
  SetCommandLineSwitchASCII(switches::kPrerenderFromOmnibox,
                            switches::kPrerenderFromOmniboxSwitchValueEnabled);

  // Disable syncing favicons on low end devices.
  if (base::android::SysUtils::IsLowEndDevice())
    SetCommandLineSwitch(switches::kDisableSyncFavicons);

  // Enable DOM Distiller on local builds, canary and dev-channel.
  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel == chrome::VersionInfo::CHANNEL_UNKNOWN ||
      channel == chrome::VersionInfo::CHANNEL_CANARY ||
      channel == chrome::VersionInfo::CHANNEL_DEV) {
    SetCommandLineSwitch(switches::kEnableDomDistiller);
  }
}
<|endoftext|>


<commit_before>#include "core/mat4.h"
#include "core/random.h"
#include "core/mat4.h"
#include "core/axisangle.h"
#include "core/aabb.h"
#include "core/texturetypes.h"
#include "core/vfs.h"
#include "core/vfs_imagegenerator.h"
#include "core/vfs_path.h"
#include "core/os.h"
#include "core/range.h"
#include "core/camera.h"
#include "core/stringutils.h"
#include "core/stdutils.h"
#include "core/proto.h"
#include "core/log.h"
#include "core/rgb.h"
#include "core/colors.h"
#include "core/palette_lospec.h"
#include "core/palette.h"

#include "render/init.h"
#include "render/debuggl.h"
#include "render/materialshader.h"
#include "render/compiledmesh.h"
#include "render/texturecache.h"
#include "render/shaderattribute3d.h"
#include "render/texture.h"
#include "render/world.h"
#include "render/viewport.h"
#include "render/materialshadercache.h"
#include "render/defaultfiles.h"

#include "window/imguilibrary.h"
#include "window/timer.h"
#include "window/imgui_ext.h"
#include "window/imgui_extra.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"
#include "window/filesystem.h"
#include "window/engine.h"
#include "window/canvas.h"

#include "imgui/imgui.h"
#include "SDL.h"
#include <iostream>
#include <memory>

#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui/imgui_internal.h"
#include "window/imgui_ext.h"

using namespace euphoria::core;
using namespace euphoria::render;
using namespace euphoria::window;

ImU32
C(const Rgbai& c)
{
    return IM_COL32(c.r, c.g, c.b, c.a);
}

bool IsOver(const ImVec2& min, const ImVec2& max, const ImVec2& mouse)
{
    const auto over_min = min.x <= mouse.x && min.y <= mouse.y;
    const auto over_max = max.x >= mouse.x && max.y >= mouse.y;
    return over_min && over_max;
}

int
main(int argc, char** argv)
{
    Engine engine;

    if (const auto r = engine.Setup(argparse::Arguments::Extract(argc, argv)); r != 0)
    {
        return r;
    }

    int window_width  = 1280;
    int window_height = 720;

    if(!engine.CreateWindow("Painter", window_width, window_height, true))
    {
        return -1;
    }

    // ViewportHandler viewport_handler;
    // viewport_handler.SetSize(window_width, window_height);

    bool running = true;

    //////////////////////////////////////////////////////////////////////////////
    // main loop
    CanvasConfig cc;
    Canvas canvas;
    Image image;
    Random random;
    auto palette = palette::EDG64();
    auto foreground = 0;
    auto background = 1;

    image.SetupNoAlphaSupport(64, 64);
    image.SetAllTopBottom([&](int x, int y)
    {
        return Rgbai{palette.colors[background]};
    });

    while(running)
    {
        SDL_Event e;
        while(SDL_PollEvent(&e) != 0)
        {
            engine.imgui->ProcessEvents(&e);

            if(engine.HandleResize(e, &window_width, &window_height))
            {
                // viewport_handler.SetSize(window_width, window_height);
            }

            switch(e.type)
            {
            case SDL_QUIT: running = false; break;
            default:
                // ignore other events
                break;
            }
        }

        engine.imgui->StartNewFrame();

        if(ImGui::BeginMainMenuBar())
        {
            if(ImGui::BeginMenu("File"))
            {
                if(ImGui::MenuItem("Exit", "Ctrl+Q"))
                {
                    running = false;
                }
                ImGui::EndMenu();
            }
        }
        ImGui::EndMainMenuBar();

        if(ImGui::Begin("palette"))
        {
            const auto tile_size = 20;
            const auto spacing = 3;

            auto x = 0.0f;
            auto y = 0.0f;

            if(imgui::CanvasBegin(ImVec4(0.3, 0.3, 0.3, 1.0f), "palette"))
            {
                const auto p = ImGui::GetCursorScreenPos();
                const auto size = ImGui::GetContentRegionAvail();

                const auto hovering = ImGui::IsAnyItemHovered();
                const auto left_clicked = ImGui::IsMouseClicked(0);
                const auto right_clicked = ImGui::IsMouseClicked(1);

                ImDrawList* draw_list = ImGui::GetWindowDrawList();
                for(int palette_index=0; palette_index<palette.colors.size(); palette_index+=1)
                {
                    if(x + tile_size > size.x)
                    {
                        x = 0;
                        y += tile_size + spacing;
                    }

                    const auto min = p + ImVec2(x, y);
                    const auto max = min + ImVec2(tile_size, tile_size);
                    const auto mouse = ImGui::GetMousePos();

                    draw_list->AddRectFilled(min, max, C(palette.colors[palette_index]));
                    x += tile_size + spacing;

                    if(!hovering && (left_clicked || right_clicked))
                    {
                        if(IsOver(min, max, mouse))
                        {
                            if(left_clicked)
                            {
                                foreground = palette_index;
                            }
                            else
                            {
                                background = palette_index;
                            }

                        }
                    }
                }
                imgui::CanvasEnd();
            }
        }
        ImGui::End();

        ImGui::SetNextWindowSize(ImVec2 {300, 300}, ImGuiCond_FirstUseEver);
        if(ImGui::Begin("pixel"))
        {
            if(image.IsValid())
            {
                const auto hovering = ImGui::IsAnyItemHovered();
                const auto left_down = ImGui::IsMouseDown(0);
                const auto right_down = ImGui::IsMouseDown(1);

                canvas.Begin(cc);
                canvas.ShowGrid(cc);

                // draw image
                ImDrawList* draw_list = ImGui::GetWindowDrawList();
                image.ForAllTopBottom([&](int x, int y, const Rgbai& c)
                {
                    const auto pixel_size = 5;
                    const auto p = ImVec2(x * pixel_size, y*pixel_size);
                    const auto s = ImVec2(pixel_size, pixel_size);
                    const auto ps = canvas.WorldToScreen(p);
                    const auto pss = canvas.WorldToScreen(p+s);
                    const auto m = ImGui::GetMousePos();
                    if(ps.x <= m.x && ps.y <= m.y && pss.x >= m.x && pss.y >= m.y)
                    {
                        // hovering over pixel
                        if(!hovering && left_down)
                        {
                            image.SetPixel(x, y, palette.colors[foreground]);
                        }

                        // hovering over pixel
                        if(!hovering && right_down)
                        {
                            image.SetPixel(x, y, palette.colors[background]);
                        }
                    }
                    draw_list->AddRectFilled(ps, pss, C(c));
                });

                canvas.ShowRuler(cc);
                canvas.End(cc);
            }
        }
        ImGui::End();

        // ImGui::ShowMetricsWindow();

        engine.init->ClearScreen(Color::LightGray);
        engine.imgui->Render();

        SDL_GL_SwapWindow(engine.window->window);
    }

    return 0;
}
<commit_msg>draw currently selected palette<commit_after>#include "core/mat4.h"
#include "core/random.h"
#include "core/mat4.h"
#include "core/axisangle.h"
#include "core/aabb.h"
#include "core/texturetypes.h"
#include "core/vfs.h"
#include "core/vfs_imagegenerator.h"
#include "core/vfs_path.h"
#include "core/os.h"
#include "core/range.h"
#include "core/camera.h"
#include "core/stringutils.h"
#include "core/stdutils.h"
#include "core/proto.h"
#include "core/log.h"
#include "core/rgb.h"
#include "core/colors.h"
#include "core/palette_lospec.h"
#include "core/palette.h"

#include "render/init.h"
#include "render/debuggl.h"
#include "render/materialshader.h"
#include "render/compiledmesh.h"
#include "render/texturecache.h"
#include "render/shaderattribute3d.h"
#include "render/texture.h"
#include "render/world.h"
#include "render/viewport.h"
#include "render/materialshadercache.h"
#include "render/defaultfiles.h"

#include "window/imguilibrary.h"
#include "window/timer.h"
#include "window/imgui_ext.h"
#include "window/imgui_extra.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"
#include "window/filesystem.h"
#include "window/engine.h"
#include "window/canvas.h"

#include "imgui/imgui.h"
#include "SDL.h"
#include <iostream>
#include <memory>

#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui/imgui_internal.h"
#include "window/imgui_ext.h"

using namespace euphoria::core;
using namespace euphoria::render;
using namespace euphoria::window;

ImU32
C(const Rgbai& c)
{
    return IM_COL32(c.r, c.g, c.b, c.a);
}

bool IsOver(const ImVec2& min, const ImVec2& max, const ImVec2& mouse)
{
    const auto over_min = min.x <= mouse.x && min.y <= mouse.y;
    const auto over_max = max.x >= mouse.x && max.y >= mouse.y;
    return over_min && over_max;
}

int
main(int argc, char** argv)
{
    Engine engine;

    if (const auto r = engine.Setup(argparse::Arguments::Extract(argc, argv)); r != 0)
    {
        return r;
    }

    int window_width  = 1280;
    int window_height = 720;

    if(!engine.CreateWindow("Painter", window_width, window_height, true))
    {
        return -1;
    }

    // ViewportHandler viewport_handler;
    // viewport_handler.SetSize(window_width, window_height);

    bool running = true;

    //////////////////////////////////////////////////////////////////////////////
    // main loop
    CanvasConfig cc;
    Canvas canvas;
    Image image;
    Random random;
    auto palette = palette::EDG64();
    auto foreground = 0;
    auto background = 1;

    image.SetupNoAlphaSupport(64, 64);
    image.SetAllTopBottom([&](int x, int y)
    {
        return Rgbai{palette.colors[background]};
    });

    while(running)
    {
        SDL_Event e;
        while(SDL_PollEvent(&e) != 0)
        {
            engine.imgui->ProcessEvents(&e);

            if(engine.HandleResize(e, &window_width, &window_height))
            {
                // viewport_handler.SetSize(window_width, window_height);
            }

            switch(e.type)
            {
            case SDL_QUIT: running = false; break;
            default:
                // ignore other events
                break;
            }
        }

        engine.imgui->StartNewFrame();

        if(ImGui::BeginMainMenuBar())
        {
            if(ImGui::BeginMenu("File"))
            {
                if(ImGui::MenuItem("Exit", "Ctrl+Q"))
                {
                    running = false;
                }
                ImGui::EndMenu();
            }
        }
        ImGui::EndMainMenuBar();

        if(ImGui::Begin("palette"))
        {

            const auto tile_size = 20;
            const auto spacing = 3;
            const auto big_spacing = 10;
            const auto big_offset = 0.20f;
            const auto max_pal_size = tile_size * 5;

            if(imgui::CanvasBegin(ImVec4(0.3, 0.3, 0.3, 1.0f), "palette"))
            {
                const auto p = ImGui::GetCursorScreenPos();
                const auto size = ImGui::GetContentRegionAvail();

                const auto hovering = ImGui::IsAnyItemHovered();
                const auto left_clicked = ImGui::IsMouseClicked(0);
                const auto right_clicked = ImGui::IsMouseClicked(1);
                const auto mouse = ImGui::GetMousePos();

                ImDrawList* draw_list = ImGui::GetWindowDrawList();

                auto x = 0.0f;
                auto y = 0.0f;

                for(int palette_index=0; palette_index<palette.colors.size(); palette_index+=1)
                {
                    if(x + tile_size > size.x)
                    {
                        x = 0;
                        y += tile_size + spacing;
                    }

                    const auto min = p + ImVec2(x, y);
                    const auto max = min + ImVec2(tile_size, tile_size);

                    draw_list->AddRectFilled(min, max, C(palette.colors[palette_index]));
                    x += tile_size + spacing;

                    if(!hovering && (left_clicked || right_clicked))
                    {
                        if(IsOver(min, max, mouse))
                        {
                            if(left_clicked)
                            {
                                foreground = palette_index;
                            }
                            else
                            {
                                background = palette_index;
                            }

                        }
                    }
                }

                y += tile_size;

                const auto big_size = std::min(size.x, size.y - y) - big_spacing * 2;

                if(big_size > 0)
                {
                    const auto bsf = std::min<float>(max_pal_size, big_size / (1+big_offset));
                    const auto bs = ImVec2(bsf, bsf);
                    const auto foreground_pos = ImVec2
                    (
                        size.x/2 - (bsf * (1+big_offset))/2,
                        y+big_spacing
                    );

                    const auto background_pos = foreground_pos + bs * big_offset;
                    draw_list->AddRectFilled(p + background_pos, p + background_pos + bs, C(palette.GetSafeIndex(background)));
                    draw_list->AddRectFilled(p + foreground_pos, p + foreground_pos + bs, C(palette.GetSafeIndex(foreground)));
                }

                imgui::CanvasEnd();
            }
        }
        ImGui::End();

        ImGui::SetNextWindowSize(ImVec2 {300, 300}, ImGuiCond_FirstUseEver);
        if(ImGui::Begin("pixel"))
        {
            if(image.IsValid())
            {
                const auto hovering = ImGui::IsAnyItemHovered();
                const auto left_down = ImGui::IsMouseDown(0);
                const auto right_down = ImGui::IsMouseDown(1);

                canvas.Begin(cc);
                canvas.ShowGrid(cc);

                // draw image
                ImDrawList* draw_list = ImGui::GetWindowDrawList();
                image.ForAllTopBottom([&](int x, int y, const Rgbai& c)
                {
                    const auto pixel_size = 5;
                    const auto p = ImVec2(x * pixel_size, y*pixel_size);
                    const auto s = ImVec2(pixel_size, pixel_size);
                    const auto ps = canvas.WorldToScreen(p);
                    const auto pss = canvas.WorldToScreen(p+s);
                    const auto m = ImGui::GetMousePos();
                    if(ps.x <= m.x && ps.y <= m.y && pss.x >= m.x && pss.y >= m.y)
                    {
                        // hovering over pixel
                        if(!hovering && left_down)
                        {
                            image.SetPixel(x, y, palette.colors[foreground]);
                        }

                        // hovering over pixel
                        if(!hovering && right_down)
                        {
                            image.SetPixel(x, y, palette.colors[background]);
                        }
                    }
                    draw_list->AddRectFilled(ps, pss, C(c));
                });

                canvas.ShowRuler(cc);
                canvas.End(cc);
            }
        }
        ImGui::End();

        // ImGui::ShowMetricsWindow();

        engine.init->ClearScreen(Color::LightGray);
        engine.imgui->Render();

        SDL_GL_SwapWindow(engine.window->window);
    }

    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtQml/qqmlextensionplugin.h>
#include <QtQml/qqml.h>
#include <QtQml/qjsvalue.h>
#include <QtQml/qjsengine.h>
#include "QtQuickTest/private/quicktestresult_p.h"
#include "QtQuickTest/private/quicktestevent_p.h"
#include "private/qtestoptions_p.h"
#include "QtQuick/qquickitem.h"
#include <QtQml/private/qqmlengine_p.h>
#include <QtGui/QGuiApplication>
#include <QtGui/qstylehints.h>

QML_DECLARE_TYPE(QuickTestResult)
QML_DECLARE_TYPE(QuickTestEvent)

#include <QtDebug>

QT_BEGIN_NAMESPACE

class QuickTestUtil : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool printAvailableFunctions READ printAvailableFunctions NOTIFY printAvailableFunctionsChanged)
    Q_PROPERTY(int dragThreshold READ dragThreshold NOTIFY dragThresholdChanged)
public:
    QuickTestUtil(QObject *parent = 0)
        :QObject(parent)
    {}

    ~QuickTestUtil()
    {}
    bool printAvailableFunctions() const
    {
        return QTest::printAvailableFunctions;
    }
    int dragThreshold() const { return qApp->styleHints()->startDragDistance(); }

Q_SIGNALS:
    void printAvailableFunctionsChanged();
    void dragThresholdChanged();

public Q_SLOTS:

    QQmlV4Handle typeName(const QVariant& v) const
    {
        QString name(v.typeName());
        if (v.canConvert<QObject*>()) {
            QQmlType *type = 0;
            const QMetaObject *mo = v.value<QObject*>()->metaObject();
            while (!type && mo) {
                type = QQmlMetaType::qmlType(mo);
                mo = mo->superClass();
            }
            if (type) {
                name = type->qmlTypeName();
            }
        }

        return QQmlV4Handle(v8::String::New(name.toUtf8())->v4Value());
    }

    bool compare(const QVariant& act, const QVariant& exp) const {
        return act == exp;
    }

    QQmlV4Handle callerFile(int frameIndex = 0) const
    {
        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());

        QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1);
        if (stack.size() > frameIndex)
            return QQmlV4Handle(QV4::Value::fromString(v4->newString(stack.at(frameIndex).source)));
        return QQmlV4Handle();
    }
    int callerLine(int frameIndex = 0) const
    {
        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());

        QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1);
        if (stack.size() > frameIndex)
            return stack.at(frameIndex).line;
        return -1;
    }
};

QT_END_NAMESPACE

QML_DECLARE_TYPE(QuickTestUtil)

QT_BEGIN_NAMESPACE

class QTestQmlModule : public QQmlExtensionPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")

public:
    virtual void registerTypes(const char *uri)
    {
        Q_ASSERT(QLatin1String(uri) == QLatin1String("QtTest"));
        qmlRegisterType<QuickTestResult>(uri,1,0,"TestResult");
        qmlRegisterType<QuickTestEvent>(uri,1,0,"TestEvent");
        qmlRegisterType<QuickTestUtil>(uri,1,0,"TestUtil");
    }

    void initializeEngine(QQmlEngine *, const char *)
    {
    }
};

QT_END_NAMESPACE

#include "main.moc"
<commit_msg>Remove last v8 dependency in the testlib<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtQml/qqmlextensionplugin.h>
#include <QtQml/qqml.h>
#include <QtQml/qjsvalue.h>
#include <QtQml/qjsengine.h>
#include "QtQuickTest/private/quicktestresult_p.h"
#include "QtQuickTest/private/quicktestevent_p.h"
#include "private/qtestoptions_p.h"
#include "QtQuick/qquickitem.h"
#include <QtQml/private/qqmlengine_p.h>
#include <QtGui/QGuiApplication>
#include <QtGui/qstylehints.h>

QML_DECLARE_TYPE(QuickTestResult)
QML_DECLARE_TYPE(QuickTestEvent)

#include <QtDebug>

QT_BEGIN_NAMESPACE

class QuickTestUtil : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool printAvailableFunctions READ printAvailableFunctions NOTIFY printAvailableFunctionsChanged)
    Q_PROPERTY(int dragThreshold READ dragThreshold NOTIFY dragThresholdChanged)
public:
    QuickTestUtil(QObject *parent = 0)
        :QObject(parent)
    {}

    ~QuickTestUtil()
    {}
    bool printAvailableFunctions() const
    {
        return QTest::printAvailableFunctions;
    }
    int dragThreshold() const { return qApp->styleHints()->startDragDistance(); }

Q_SIGNALS:
    void printAvailableFunctionsChanged();
    void dragThresholdChanged();

public Q_SLOTS:

    QQmlV4Handle typeName(const QVariant& v) const
    {
        QString name(v.typeName());
        if (v.canConvert<QObject*>()) {
            QQmlType *type = 0;
            const QMetaObject *mo = v.value<QObject*>()->metaObject();
            while (!type && mo) {
                type = QQmlMetaType::qmlType(mo);
                mo = mo->superClass();
            }
            if (type) {
                name = type->qmlTypeName();
            }
        }

        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());
        return QQmlV4Handle(QV4::Value::fromString(v4->newString(name)));
    }

    bool compare(const QVariant& act, const QVariant& exp) const {
        return act == exp;
    }

    QQmlV4Handle callerFile(int frameIndex = 0) const
    {
        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());

        QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1);
        if (stack.size() > frameIndex)
            return QQmlV4Handle(QV4::Value::fromString(v4->newString(stack.at(frameIndex).source)));
        return QQmlV4Handle();
    }
    int callerLine(int frameIndex = 0) const
    {
        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());

        QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1);
        if (stack.size() > frameIndex)
            return stack.at(frameIndex).line;
        return -1;
    }
};

QT_END_NAMESPACE

QML_DECLARE_TYPE(QuickTestUtil)

QT_BEGIN_NAMESPACE

class QTestQmlModule : public QQmlExtensionPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")

public:
    virtual void registerTypes(const char *uri)
    {
        Q_ASSERT(QLatin1String(uri) == QLatin1String("QtTest"));
        qmlRegisterType<QuickTestResult>(uri,1,0,"TestResult");
        qmlRegisterType<QuickTestEvent>(uri,1,0,"TestEvent");
        qmlRegisterType<QuickTestUtil>(uri,1,0,"TestUtil");
    }

    void initializeEngine(QQmlEngine *, const char *)
    {
    }
};

QT_END_NAMESPACE

#include "main.moc"
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/profiles/profile.h"

#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/platform_file.h"
#include "base/version.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/chrome_version_service.h"
#include "chrome/browser/profiles/profile_impl.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

class MockProfileDelegate : public Profile::Delegate {
 public:
  MOCK_METHOD3(OnProfileCreated, void(Profile*, bool, bool));
};

// Creates a prefs file in the given directory.
void CreatePrefsFileInDirectory(const FilePath& directory_path) {
  FilePath pref_path(directory_path.Append(chrome::kPreferencesFilename));
  base::PlatformFile file = base::CreatePlatformFile(pref_path,
      base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_WRITE, NULL, NULL);
  ASSERT_TRUE(file != base::kInvalidPlatformFileValue);
  ASSERT_TRUE(base::ClosePlatformFile(file));
  std::string data("{}");
  ASSERT_TRUE(file_util::WriteFile(pref_path, data.c_str(), data.size()));
}

void CheckChromeVersion(Profile *profile, bool is_new) {
  std::string created_by_version;
  if (is_new) {
    chrome::VersionInfo version_info;
    created_by_version = version_info.Version();
  } else {
    created_by_version = "1.0.0.0";
  }
  std::string pref_version =
      ChromeVersionService::GetVersion(profile->GetPrefs());
  // Assert that created_by_version pref gets set to current version.
  EXPECT_EQ(created_by_version, pref_version);
}

}  // namespace

typedef InProcessBrowserTest ProfileBrowserTest;

// Test OnProfileCreate is called with is_new_profile set to true when
// creating a new profile synchronously.
//
// Flaky (sometimes timeout): http://crbug.com/141141
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateNewProfileSynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());
  CheckChromeVersion(profile.get(), true);
}

// Test OnProfileCreate is called with is_new_profile set to false when
// creating a profile synchronously with an existing prefs file.
// Flaky: http://crbug.com/141517
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateOldProfileSynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  CreatePrefsFileInDirectory(temp_dir.path());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());
  CheckChromeVersion(profile.get(), false);
}

// Test OnProfileCreate is called with is_new_profile set to true when
// creating a new profile asynchronously.
// This test is flaky on Linux, Win and Mac.  See crbug.com/142787
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateNewProfileAsynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Wait for the profile to be created.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_PROFILE_CREATED,
      content::Source<Profile>(profile.get()));
  observer.Wait();
  CheckChromeVersion(profile.get(), true);
}

// Test OnProfileCreate is called with is_new_profile set to false when
// creating a profile asynchronously with an existing prefs file.
// Flaky: http://crbug.com/141517
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateOldProfileAsynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  CreatePrefsFileInDirectory(temp_dir.path());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false));
  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Wait for the profile to be created.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_PROFILE_CREATED,
      content::Source<Profile>(profile.get()));
  observer.Wait();
  CheckChromeVersion(profile.get(), false);
}

// Test that a README file is created for profiles that didn't have it.
// Flaky: http://crbug.com/140882
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_ProfileReadmeCreated) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  // No delay before README creation.
  ProfileImpl::create_readme_delay_ms = 0;

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Wait for the profile to be created.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_PROFILE_CREATED,
      content::Source<Profile>(profile.get()));
  observer.Wait();

  content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);

  // Verify that README exists.
  EXPECT_TRUE(file_util::PathExists(
      temp_dir.path().Append(chrome::kReadmeFilename)));
}

// Test that Profile can be deleted before README file is created.
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ProfileDeletedBeforeReadmeCreated) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  // No delay before README creation.
  ProfileImpl::create_readme_delay_ms = 0;

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Delete the Profile instance and run pending tasks (this includes the task
  // for README creation).
  profile.reset();
  content::RunAllPendingInMessageLoop();
  content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
}

// Test that repeated setting of exit type is handled correctly.
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ExitType) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  PrefService* prefs = profile->GetPrefs();
  // The initial state is crashed; store for later reference.
  std::string crash_value(prefs->GetString(prefs::kSessionExitType));

  // The first call to a type other than crashed should change the value.
  profile->SetExitType(Profile::EXIT_SESSION_ENDED);
  std::string first_call_value(prefs->GetString(prefs::kSessionExitType));
  EXPECT_NE(crash_value, first_call_value);

  // Subsequent calls to a non-crash value should be ignored.
  profile->SetExitType(Profile::EXIT_NORMAL);
  std::string second_call_value(prefs->GetString(prefs::kSessionExitType));
  EXPECT_EQ(first_call_value, second_call_value);

  // Setting back to a crashed value should work.
  profile->SetExitType(Profile::EXIT_CRASHED);
  std::string final_value(prefs->GetString(prefs::kSessionExitType));
  EXPECT_EQ(crash_value, final_value);
}
<commit_msg>Disable ProfileBrowserTest.ExitType on Windows where it times out sometimes.<commit_after>// Copyright (c) 2012 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/profiles/profile.h"

#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/platform_file.h"
#include "base/version.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/chrome_version_service.h"
#include "chrome/browser/profiles/profile_impl.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

class MockProfileDelegate : public Profile::Delegate {
 public:
  MOCK_METHOD3(OnProfileCreated, void(Profile*, bool, bool));
};

// Creates a prefs file in the given directory.
void CreatePrefsFileInDirectory(const FilePath& directory_path) {
  FilePath pref_path(directory_path.Append(chrome::kPreferencesFilename));
  base::PlatformFile file = base::CreatePlatformFile(pref_path,
      base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_WRITE, NULL, NULL);
  ASSERT_TRUE(file != base::kInvalidPlatformFileValue);
  ASSERT_TRUE(base::ClosePlatformFile(file));
  std::string data("{}");
  ASSERT_TRUE(file_util::WriteFile(pref_path, data.c_str(), data.size()));
}

void CheckChromeVersion(Profile *profile, bool is_new) {
  std::string created_by_version;
  if (is_new) {
    chrome::VersionInfo version_info;
    created_by_version = version_info.Version();
  } else {
    created_by_version = "1.0.0.0";
  }
  std::string pref_version =
      ChromeVersionService::GetVersion(profile->GetPrefs());
  // Assert that created_by_version pref gets set to current version.
  EXPECT_EQ(created_by_version, pref_version);
}

}  // namespace

typedef InProcessBrowserTest ProfileBrowserTest;

// Test OnProfileCreate is called with is_new_profile set to true when
// creating a new profile synchronously.
//
// Flaky (sometimes timeout): http://crbug.com/141141
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateNewProfileSynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());
  CheckChromeVersion(profile.get(), true);
}

// Test OnProfileCreate is called with is_new_profile set to false when
// creating a profile synchronously with an existing prefs file.
// Flaky: http://crbug.com/141517
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateOldProfileSynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  CreatePrefsFileInDirectory(temp_dir.path());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());
  CheckChromeVersion(profile.get(), false);
}

// Test OnProfileCreate is called with is_new_profile set to true when
// creating a new profile asynchronously.
// This test is flaky on Linux, Win and Mac.  See crbug.com/142787
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateNewProfileAsynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Wait for the profile to be created.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_PROFILE_CREATED,
      content::Source<Profile>(profile.get()));
  observer.Wait();
  CheckChromeVersion(profile.get(), true);
}

// Test OnProfileCreate is called with is_new_profile set to false when
// creating a profile asynchronously with an existing prefs file.
// Flaky: http://crbug.com/141517
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest,
                       DISABLED_CreateOldProfileAsynchronous) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  CreatePrefsFileInDirectory(temp_dir.path());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false));
  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Wait for the profile to be created.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_PROFILE_CREATED,
      content::Source<Profile>(profile.get()));
  observer.Wait();
  CheckChromeVersion(profile.get(), false);
}

// Test that a README file is created for profiles that didn't have it.
// Flaky: http://crbug.com/140882
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_ProfileReadmeCreated) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  // No delay before README creation.
  ProfileImpl::create_readme_delay_ms = 0;

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Wait for the profile to be created.
  content::WindowedNotificationObserver observer(
      chrome::NOTIFICATION_PROFILE_CREATED,
      content::Source<Profile>(profile.get()));
  observer.Wait();

  content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);

  // Verify that README exists.
  EXPECT_TRUE(file_util::PathExists(
      temp_dir.path().Append(chrome::kReadmeFilename)));
}

// Test that Profile can be deleted before README file is created.
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ProfileDeletedBeforeReadmeCreated) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  // No delay before README creation.
  ProfileImpl::create_readme_delay_ms = 0;

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  // Delete the Profile instance and run pending tasks (this includes the task
  // for README creation).
  profile.reset();
  content::RunAllPendingInMessageLoop();
  content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
}

// Test that repeated setting of exit type is handled correctly.
#if defined(OS_WIN)
// Flaky on Windows: http://crbug.com/163713
#define MAYBE_ExitType DISABLED_ExitType
#else
#define MAYBE_ExitType ExitType
#endif
IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, MAYBE_ExitType) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  MockProfileDelegate delegate;
  EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true));

  scoped_ptr<Profile> profile(Profile::CreateProfile(
      temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS));
  ASSERT_TRUE(profile.get());

  PrefService* prefs = profile->GetPrefs();
  // The initial state is crashed; store for later reference.
  std::string crash_value(prefs->GetString(prefs::kSessionExitType));

  // The first call to a type other than crashed should change the value.
  profile->SetExitType(Profile::EXIT_SESSION_ENDED);
  std::string first_call_value(prefs->GetString(prefs::kSessionExitType));
  EXPECT_NE(crash_value, first_call_value);

  // Subsequent calls to a non-crash value should be ignored.
  profile->SetExitType(Profile::EXIT_NORMAL);
  std::string second_call_value(prefs->GetString(prefs::kSessionExitType));
  EXPECT_EQ(first_call_value, second_call_value);

  // Setting back to a crashed value should work.
  profile->SetExitType(Profile::EXIT_CRASHED);
  std::string final_value(prefs->GetString(prefs::kSessionExitType));
  EXPECT_EQ(crash_value, final_value);
}
<|endoftext|>


<commit_before><commit_msg>user c-array instead of vector<> in hot loop<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 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/sync/signin_manager.h"

#include "chrome/browser/net/gaia/token_service.h"
#include "chrome/browser/net/gaia/token_service_unittest.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/sync/util/oauth.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/test/base/signaling_task.h"
#include "chrome/test/base/testing_profile.h"
#include "content/test/test_url_fetcher_factory.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_status.h"

#include "testing/gtest/include/gtest/gtest.h"

class SigninManagerTest : public TokenServiceTestHarness {
 public:
  virtual void SetUp() OVERRIDE {
    TokenServiceTestHarness::SetUp();
    manager_.reset(new SigninManager());
    google_login_success_.ListenFor(
        chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
        Source<Profile>(profile_.get()));
    google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED,
                                    Source<Profile>(profile_.get()));
    originally_using_oauth_ = browser_sync::IsUsingOAuth();
  }

  virtual void TearDown() OVERRIDE {
    browser_sync::SetIsUsingOAuthForTest(originally_using_oauth_);
  }

  void SimulateValidResponseClientLogin() {
    DCHECK(!browser_sync::IsUsingOAuth());
    // Simulate the correct ClientLogin response.
    TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
    DCHECK(fetcher);
    DCHECK(fetcher->delegate());
    fetcher->delegate()->OnURLFetchComplete(
        fetcher, GURL(GaiaUrls::GetInstance()->client_login_url()),
        net::URLRequestStatus(), 200, net::ResponseCookies(),
        "SID=sid\nLSID=lsid\nAuth=auth");

    // Then simulate the correct GetUserInfo response for the canonical email.
    // A new URL fetcher is used for each call.
    fetcher = factory_.GetFetcherByID(0);
    DCHECK(fetcher);
    DCHECK(fetcher->delegate());
    fetcher->delegate()->OnURLFetchComplete(
        fetcher, GURL(GaiaUrls::GetInstance()->get_user_info_url()),
        net::URLRequestStatus(), 200, net::ResponseCookies(),
        "email=user@gmail.com");
  }

  void SimulateSigninStartOAuth() {
    DCHECK(browser_sync::IsUsingOAuth());
    // Simulate a valid OAuth-based signin
    manager_->OnGetOAuthTokenSuccess("oauth_token-Ev1Vu1hv");
    manager_->OnOAuthGetAccessTokenSuccess("oauth1_access_token-qOAmlrSM",
                                           "secret-NKKn1DuR");
    manager_->OnOAuthWrapBridgeSuccess(browser_sync::SyncServiceName(),
                                       "oauth2_wrap_access_token-R0Z3nRtw",
                                       "3600");
  }

  void SimulateOAuthUserInfoSuccess() {
    manager_->OnUserInfoSuccess("user-xZIuqTKu@gmail.com");
  }

  void SimulateValidSigninOAuth() {
    SimulateSigninStartOAuth();
    SimulateOAuthUserInfoSuccess();
  }

  TestURLFetcherFactory factory_;
  scoped_ptr<SigninManager> manager_;
  TestNotificationTracker google_login_success_;
  TestNotificationTracker google_login_failure_;
  bool originally_using_oauth_;
};

// NOTE: ClientLogin's "StartSignin" is called after collecting credentials
//       from the user.  See also SigninManagerTest::SignInOAuth.
TEST_F(SigninManagerTest, SignInClientLogin) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());

  manager_->StartSignIn("username", "password", "", "");
  EXPECT_FALSE(manager_->GetUsername().empty());

  SimulateValidResponseClientLogin();

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  // Should persist across resets.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_EQ("user@gmail.com", manager_->GetUsername());
}

// NOTE: OAuth's "StartOAuthSignIn" is called before collecting credentials
//       from the user.  See also SigninManagerTest::SignInClientLogin.
TEST_F(SigninManagerTest, SignInOAuth) {
  browser_sync::SetIsUsingOAuthForTest(true);
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());

  SimulateValidSigninOAuth();
  EXPECT_FALSE(manager_->GetUsername().empty());

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  // Should persist across resets.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername());
}

TEST_F(SigninManagerTest, SignOutClientLogin) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  SimulateValidResponseClientLogin();
  manager_->OnClientLoginSuccess(credentials_);

  EXPECT_EQ("user@gmail.com", manager_->GetUsername());
  manager_->SignOut();
  EXPECT_TRUE(manager_->GetUsername().empty());
  // Should not be persisted anymore
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignOutOAuth) {
  browser_sync::SetIsUsingOAuthForTest(true);
  manager_->Initialize(profile_.get());

  SimulateValidSigninOAuth();
  EXPECT_FALSE(manager_->GetUsername().empty());

  EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername());
  manager_->SignOut();
  EXPECT_TRUE(manager_->GetUsername().empty());

  // Should not be persisted anymore
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignInFailureClientLogin) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED);
  manager_->OnClientLoginFailure(error);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetUsername().empty());

  // Should not be persisted
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR);
  manager_->OnClientLoginFailure(error);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_FALSE(manager_->GetUsername().empty());

  manager_->ProvideSecondFactorAccessCode("access");
  SimulateValidResponseClientLogin();

  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());
}

TEST_F(SigninManagerTest, ProvideSecondFactorFailure) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR);
  manager_->OnClientLoginFailure(error1);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_FALSE(manager_->GetUsername().empty());

  manager_->ProvideSecondFactorAccessCode("badaccess");
  GoogleServiceAuthError error2(
      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
  manager_->OnClientLoginFailure(error2);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(2U, google_login_failure_.size());
  EXPECT_FALSE(manager_->GetUsername().empty());

  manager_->ProvideSecondFactorAccessCode("badaccess");
  GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED);
  manager_->OnClientLoginFailure(error3);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(3U, google_login_failure_.size());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignOutMidConnect) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  manager_->SignOut();
  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignOutOnUserInfoSucessRaceTest) {
  browser_sync::SetIsUsingOAuthForTest(true);
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());

  SimulateSigninStartOAuth();
  manager_->SignOut();
  SimulateOAuthUserInfoSuccess();
  EXPECT_TRUE(manager_->GetUsername().empty());
}
<commit_msg>Sync/Valgrind: Fix a leak in SigninManagerTest.<commit_after>// Copyright (c) 2011 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/sync/signin_manager.h"

#include "chrome/browser/net/gaia/token_service.h"
#include "chrome/browser/net/gaia/token_service_unittest.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/sync/util/oauth.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/test/base/signaling_task.h"
#include "chrome/test/base/testing_profile.h"
#include "content/test/test_url_fetcher_factory.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_status.h"

#include "testing/gtest/include/gtest/gtest.h"

class SigninManagerTest : public TokenServiceTestHarness {
 public:
  virtual void SetUp() OVERRIDE {
    TokenServiceTestHarness::SetUp();
    manager_.reset(new SigninManager());
    google_login_success_.ListenFor(
        chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
        Source<Profile>(profile_.get()));
    google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED,
                                    Source<Profile>(profile_.get()));
    originally_using_oauth_ = browser_sync::IsUsingOAuth();
  }

  virtual void TearDown() OVERRIDE {
    TokenServiceTestHarness::TearDown();
    browser_sync::SetIsUsingOAuthForTest(originally_using_oauth_);
  }

  void SimulateValidResponseClientLogin() {
    DCHECK(!browser_sync::IsUsingOAuth());
    // Simulate the correct ClientLogin response.
    TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
    DCHECK(fetcher);
    DCHECK(fetcher->delegate());
    fetcher->delegate()->OnURLFetchComplete(
        fetcher, GURL(GaiaUrls::GetInstance()->client_login_url()),
        net::URLRequestStatus(), 200, net::ResponseCookies(),
        "SID=sid\nLSID=lsid\nAuth=auth");

    // Then simulate the correct GetUserInfo response for the canonical email.
    // A new URL fetcher is used for each call.
    fetcher = factory_.GetFetcherByID(0);
    DCHECK(fetcher);
    DCHECK(fetcher->delegate());
    fetcher->delegate()->OnURLFetchComplete(
        fetcher, GURL(GaiaUrls::GetInstance()->get_user_info_url()),
        net::URLRequestStatus(), 200, net::ResponseCookies(),
        "email=user@gmail.com");
  }

  void SimulateSigninStartOAuth() {
    DCHECK(browser_sync::IsUsingOAuth());
    // Simulate a valid OAuth-based signin
    manager_->OnGetOAuthTokenSuccess("oauth_token-Ev1Vu1hv");
    manager_->OnOAuthGetAccessTokenSuccess("oauth1_access_token-qOAmlrSM",
                                           "secret-NKKn1DuR");
    manager_->OnOAuthWrapBridgeSuccess(browser_sync::SyncServiceName(),
                                       "oauth2_wrap_access_token-R0Z3nRtw",
                                       "3600");
  }

  void SimulateOAuthUserInfoSuccess() {
    manager_->OnUserInfoSuccess("user-xZIuqTKu@gmail.com");
  }

  void SimulateValidSigninOAuth() {
    SimulateSigninStartOAuth();
    SimulateOAuthUserInfoSuccess();
  }

  TestURLFetcherFactory factory_;
  scoped_ptr<SigninManager> manager_;
  TestNotificationTracker google_login_success_;
  TestNotificationTracker google_login_failure_;
  bool originally_using_oauth_;
};

// NOTE: ClientLogin's "StartSignin" is called after collecting credentials
//       from the user.  See also SigninManagerTest::SignInOAuth.
TEST_F(SigninManagerTest, SignInClientLogin) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());

  manager_->StartSignIn("username", "password", "", "");
  EXPECT_FALSE(manager_->GetUsername().empty());

  SimulateValidResponseClientLogin();

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  // Should persist across resets.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_EQ("user@gmail.com", manager_->GetUsername());
}

// NOTE: OAuth's "StartOAuthSignIn" is called before collecting credentials
//       from the user.  See also SigninManagerTest::SignInClientLogin.
TEST_F(SigninManagerTest, SignInOAuth) {
  browser_sync::SetIsUsingOAuthForTest(true);
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());

  SimulateValidSigninOAuth();
  EXPECT_FALSE(manager_->GetUsername().empty());

  // Should go into token service and stop.
  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  // Should persist across resets.
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername());
}

TEST_F(SigninManagerTest, SignOutClientLogin) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  SimulateValidResponseClientLogin();
  manager_->OnClientLoginSuccess(credentials_);

  EXPECT_EQ("user@gmail.com", manager_->GetUsername());
  manager_->SignOut();
  EXPECT_TRUE(manager_->GetUsername().empty());
  // Should not be persisted anymore
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignOutOAuth) {
  browser_sync::SetIsUsingOAuthForTest(true);
  manager_->Initialize(profile_.get());

  SimulateValidSigninOAuth();
  EXPECT_FALSE(manager_->GetUsername().empty());

  EXPECT_EQ("user-xZIuqTKu@gmail.com", manager_->GetUsername());
  manager_->SignOut();
  EXPECT_TRUE(manager_->GetUsername().empty());

  // Should not be persisted anymore
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignInFailureClientLogin) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED);
  manager_->OnClientLoginFailure(error);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetUsername().empty());

  // Should not be persisted
  manager_.reset(new SigninManager());
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR);
  manager_->OnClientLoginFailure(error);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_FALSE(manager_->GetUsername().empty());

  manager_->ProvideSecondFactorAccessCode("access");
  SimulateValidResponseClientLogin();

  EXPECT_EQ(1U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());
}

TEST_F(SigninManagerTest, ProvideSecondFactorFailure) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR);
  manager_->OnClientLoginFailure(error1);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(1U, google_login_failure_.size());

  EXPECT_FALSE(manager_->GetUsername().empty());

  manager_->ProvideSecondFactorAccessCode("badaccess");
  GoogleServiceAuthError error2(
      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
  manager_->OnClientLoginFailure(error2);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(2U, google_login_failure_.size());
  EXPECT_FALSE(manager_->GetUsername().empty());

  manager_->ProvideSecondFactorAccessCode("badaccess");
  GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED);
  manager_->OnClientLoginFailure(error3);

  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(3U, google_login_failure_.size());
  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignOutMidConnect) {
  browser_sync::SetIsUsingOAuthForTest(false);
  manager_->Initialize(profile_.get());
  manager_->StartSignIn("username", "password", "", "");
  manager_->SignOut();
  EXPECT_EQ(0U, google_login_success_.size());
  EXPECT_EQ(0U, google_login_failure_.size());

  EXPECT_TRUE(manager_->GetUsername().empty());
}

TEST_F(SigninManagerTest, SignOutOnUserInfoSucessRaceTest) {
  browser_sync::SetIsUsingOAuthForTest(true);
  manager_->Initialize(profile_.get());
  EXPECT_TRUE(manager_->GetUsername().empty());

  SimulateSigninStartOAuth();
  manager_->SignOut();
  SimulateOAuthUserInfoSuccess();
  EXPECT_TRUE(manager_->GetUsername().empty());
}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "session.h"
#include "domain.h"
#include "domainpart.h"
#include <vespa/fastlib/io/bufferedfile.h>
#include <cassert>

#include <vespa/log/log.h>
LOG_SETUP(".transactionlog.session");

namespace search::transactionlog {

vespalib::Executor::Task::UP
Session::createTask(const Session::SP & session)
{
    return std::make_unique<VisitTask>(session);
}

Session::VisitTask::VisitTask(const Session::SP & session)
    : _session(session)
{
    _session->startVisit();
}
Session::VisitTask::~VisitTask() = default;

void
Session::VisitTask::run()
{
    _session->visitOnly();
}

bool
Session::visit(FastOS_FileInterface & file, DomainPart & dp) {
    Packet packet(size_t(-1));
    bool more(false);
    if (dp.isClosed()) {
        more = dp.visit(file, _range, packet);
    } else {
        more = dp.visit(_range, packet);
    }
    if ( ! packet.getHandle().empty()) {
        send(packet);
    }
    return more;
}

void
Session::visit()
{
    LOG(debug, "[%d] : Visiting %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to());
    for (DomainPart::SP dpSafe = _domain->findPart(_range.from()); dpSafe.get() && (_range.from() < _range.to()) && (dpSafe.get()->range().from() <= _range.to()); dpSafe = _domain->findPart(_range.from())) {
        // Must use findPart and iterate until no candidate parts found.
        DomainPart * dp(dpSafe.get());
        LOG(debug, "[%d] : Visiting the interval %" PRIu64 " - %" PRIu64 " in domain part [%" PRIu64 ", %" PRIu64 "]", _id, _range.from(), _range.to(), dp->range().from(), dp->range().to());
        Fast_BufferedFile file;
        file.EnableDirectIO();
        for(bool more(true); ok() && more && (_range.from() < _range.to()); ) {
            more = visit(file, *dp);
        }
        // Nothing more in this DomainPart, force switch to next one.
        if (_range.from() < dp->range().to()) {
            _range.from(std::min(dp->range().to(), _range.to()));
        }
    }

    LOG(debug, "[%d] : Done visiting, starting subscribe %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to());
}

void
Session::startVisit() {
    assert(!_visitRunning);
    _visitRunning = true;
}
void
Session::visitOnly()
{
    visit();
    sendDone();
    finalize();
    _visitRunning = false;
}

bool Session::finished() const {
    return _finished || ! _destination->connected();
}

void
Session::finalize()
{
    if (!ok()) {
        LOG(error, "[%d] : Error in %s(%" PRIu64 " - %" PRIu64 "), stopping since I have no idea on what to do.", _id, "visitor", _range.from(), _range.to());
    }
    LOG(debug, "[%d] : Stopped %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to());
    _finished = true;
}

Session::Session(int sId, const SerialNumRange & r, const Domain::SP & d,
                 std::unique_ptr<Destination> destination) :
    _destination(std::move(destination)),
    _domain(d),
    _range(r),
    _id(sId),
    _visitRunning(false),
    _inSync(false),
    _finished(false),
    _startTime()
{
}

Session::~Session() = default;

bool
Session::send(const Packet & packet)
{
    return _destination->send(_id, _domain->name(), packet);
}

bool
Session::sendDone()
{
    bool retval = _destination->sendDone(_id, _domain->name());
    _inSync = true;
    return retval;
}

}
<commit_msg>Only visit via file.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "session.h"
#include "domain.h"
#include "domainpart.h"
#include <vespa/fastlib/io/bufferedfile.h>
#include <cassert>

#include <vespa/log/log.h>
LOG_SETUP(".transactionlog.session");

namespace search::transactionlog {

vespalib::Executor::Task::UP
Session::createTask(const Session::SP & session)
{
    return std::make_unique<VisitTask>(session);
}

Session::VisitTask::VisitTask(const Session::SP & session)
    : _session(session)
{
    _session->startVisit();
}
Session::VisitTask::~VisitTask() = default;

void
Session::VisitTask::run()
{
    _session->visitOnly();
}

bool
Session::visit(FastOS_FileInterface & file, DomainPart & dp) {
    Packet packet(size_t(-1));
    bool more = dp.visit(file, _range, packet);

    if ( ! packet.getHandle().empty()) {
        send(packet);
    }
    return more;
}

void
Session::visit()
{
    LOG(debug, "[%d] : Visiting %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to());
    for (DomainPart::SP dpSafe = _domain->findPart(_range.from()); dpSafe.get() && (_range.from() < _range.to()) && (dpSafe.get()->range().from() <= _range.to()); dpSafe = _domain->findPart(_range.from())) {
        // Must use findPart and iterate until no candidate parts found.
        DomainPart * dp(dpSafe.get());
        LOG(debug, "[%d] : Visiting the interval %" PRIu64 " - %" PRIu64 " in domain part [%" PRIu64 ", %" PRIu64 "]", _id, _range.from(), _range.to(), dp->range().from(), dp->range().to());
        Fast_BufferedFile file;
        file.EnableDirectIO();
        for(bool more(true); ok() && more && (_range.from() < _range.to()); ) {
            more = visit(file, *dp);
        }
        // Nothing more in this DomainPart, force switch to next one.
        if (_range.from() < dp->range().to()) {
            _range.from(std::min(dp->range().to(), _range.to()));
        }
    }

    LOG(debug, "[%d] : Done visiting, starting subscribe %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to());
}

void
Session::startVisit() {
    assert(!_visitRunning);
    _visitRunning = true;
}
void
Session::visitOnly()
{
    visit();
    sendDone();
    finalize();
    _visitRunning = false;
}

bool Session::finished() const {
    return _finished || ! _destination->connected();
}

void
Session::finalize()
{
    if (!ok()) {
        LOG(error, "[%d] : Error in %s(%" PRIu64 " - %" PRIu64 "), stopping since I have no idea on what to do.", _id, "visitor", _range.from(), _range.to());
    }
    LOG(debug, "[%d] : Stopped %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to());
    _finished = true;
}

Session::Session(int sId, const SerialNumRange & r, const Domain::SP & d,
                 std::unique_ptr<Destination> destination) :
    _destination(std::move(destination)),
    _domain(d),
    _range(r),
    _id(sId),
    _visitRunning(false),
    _inSync(false),
    _finished(false),
    _startTime()
{
}

Session::~Session() = default;

bool
Session::send(const Packet & packet)
{
    return _destination->send(_id, _domain->name(), packet);
}

bool
Session::sendDone()
{
    bool retval = _destination->sendDone(_id, _domain->name());
    _inSync = true;
    return retval;
}

}
<|endoftext|>


<commit_before>// xiva (acronym for HTTP Extended EVent Automata) is a simple HTTP server.
// Copyright (C) 2009 Yandex <highpower@yandex.ru>

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#ifndef XIVA_DETAILS_FUNCTORS_HPP_INCLUDED
#define XIVA_DETAILS_FUNCTORS_HPP_INCLUDED

#include <functional>
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

#include "details/char_traits.hpp"

namespace xiva { namespace details {

template <typename Pred, typename T>
struct unary_predicate : public std::unary_function<T, bool> {
	bool operator () (T var) const;
};

template <typename Pred, typename T>
struct binary_predicate : public std::binary_function<T const&, T const&, bool> {
	bool operator () (T const &var, T const &target) const;
};

template <typename Char>
struct is_space : public unary_predicate<is_space<Char>, Char> {
	static bool check(Char value);
};

template <typename Char>
struct is_blank : public unary_predicate<is_blank<Char>, Char> {
	static bool check(Char value);
};

template <typename Char>
struct is_line_end : public unary_predicate<is_line_end<Char>, Char> {
	static bool check(Char value);
};

template <typename Char>
struct is_not_line_end : public unary_predicate<is_not_line_end<Char>, Char> {
	static bool check(Char value);
};

template <typename Range>
struct ci_less : public binary_predicate<ci_less<Range>, Range> {
	static bool check(Range const &var, Range const &target);
};

template <typename Range>
struct ci_equal : public binary_predicate<ci_equal<Range>, Range> {
	static bool check(Range const &var, Range const &target);
};

template <>
struct ci_less<char> : public std::binary_function<char, char, bool> {
	bool operator () (char var, char target) const;
};

template <>
struct ci_equal<char> : public std::binary_function<char, char, bool> {
	bool operator () (char var, char target) const;
};

template <typename R1, typename R2> inline bool
is_ci_less(R1 const &var, R2 const &target) {
	BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value));
	return std::lexicographical_compare(var.begin(), var.end(), target.begin(),
		target.end(), ci_less<typename R1::value_type>());
}

template <typename R1, typename R2> inline bool
is_ci_equal(R1 const &var, R2 const &target) {
	//BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value));
	BOOST_STATIC_ASSERT((sizeof(typename R1::value_type) == sizeof(typename R2::value_type)));
	if (var.size() == target.size()) {
		return std::equal(var.begin(), var.end(), target.begin(),
			ci_equal<typename R1::value_type>());
	}
	return false;
}

template <typename Pred, typename T> inline bool
unary_predicate<Pred, T>::operator () (T value) const {
	return Pred::check(value);
}

template <typename Pred, typename T> inline bool
binary_predicate<Pred, T>::operator () (T const &var, T const &target) const {
	return Pred::check(var, target);
}

template <typename Char> inline bool
is_space<Char>::check(Char value) {
	return char_traits<Char>::is_space(value);
}

template <typename Char> inline bool
is_blank<Char>::check(Char value) {
	return char_traits<Char>::is_blank(value);
}

template <typename Char> inline bool
is_line_end<Char>::check(Char value) {
	return (static_cast<Char>('\n') == value || static_cast<Char>('\r') == value);
}

template <typename Char> inline bool
is_not_line_end<Char>::check(Char value) {
	return !is_line_end<Char>::check(value);
}

template <typename Range> inline bool
ci_less<Range>::check(Range const &var, Range const &target) {
	return is_ci_less(var, target);
}

template <typename Range> inline bool
ci_equal<Range>::check(Range const &var, Range const &target) {
	return is_ci_equal(var, target);
}

inline bool
ci_less<char>::operator () (char var, char target) const {
	return char_traits<char>::to_lower(var) < char_traits<char>::to_lower(target);
}

inline bool
ci_equal<char>::operator () (char var, char target) const {
	return char_traits<char>::to_lower(var) == char_traits<char>::to_lower(target);
}

}} // namespaces

#endif // XIVA_DETAILS_FUNCTORS_HPP_INCLUDED
<commit_msg>probably fixed errors<commit_after>// xiva (acronym for HTTP Extended EVent Automata) is a simple HTTP server.
// Copyright (C) 2009 Yandex <highpower@yandex.ru>

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#ifndef XIVA_DETAILS_FUNCTORS_HPP_INCLUDED
#define XIVA_DETAILS_FUNCTORS_HPP_INCLUDED

#include <functional>
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

#include "details/char_traits.hpp"

namespace xiva { namespace details {

template <typename Pred, typename T>
struct unary_predicate : public std::unary_function<T, bool> {
	bool operator () (T var) const;
};

template <typename Pred, typename T>
struct binary_predicate : public std::binary_function<T const&, T const&, bool> {
	bool operator () (T const &var, T const &target) const;
};

template <typename Char>
struct is_space : public unary_predicate<is_space<Char>, Char> {
	static bool check(Char value);
};

template <typename Char>
struct is_blank : public unary_predicate<is_blank<Char>, Char> {
	static bool check(Char value);
};

template <typename Char>
struct is_line_end : public unary_predicate<is_line_end<Char>, Char> {
	static bool check(Char value);
};

template <typename Char>
struct is_not_line_end : public unary_predicate<is_not_line_end<Char>, Char> {
	static bool check(Char value);
};

template <typename Range>
struct ci_less : public binary_predicate<ci_less<Range>, Range> {
	static bool check(Range const &var, Range const &target);
};

template <typename Range>
struct ci_equal : public binary_predicate<ci_equal<Range>, Range> {
	static bool check(Range const &var, Range const &target);
};

template <>
struct ci_less<char> : public std::binary_function<char, char, bool> {
	bool operator () (char var, char target) const;
};

template <>
struct ci_less<const char> : public std::binary_function<const char, const char, bool> {
	bool operator () (const char var, const char target) const;
};

template <>
struct ci_equal<char> : public std::binary_function<char, char, bool> {
	bool operator () (char var, char target) const;
};

template <>
struct ci_equal<const char> : public std::binary_function<const char, const char, bool> {
	bool operator () (const char var, const char target) const;
};

template <typename R1, typename R2> inline bool
is_ci_less(R1 const &var, R2 const &target) {
	BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value));
	return std::lexicographical_compare(var.begin(), var.end(), target.begin(),
		target.end(), ci_less<typename R1::value_type>());
}

template <typename R1, typename R2> inline bool
is_ci_equal(R1 const &var, R2 const &target) {
	//BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value));
	BOOST_STATIC_ASSERT((sizeof(typename R1::value_type) == sizeof(typename R2::value_type)));
	if (var.size() == target.size()) {
		return std::equal(var.begin(), var.end(), target.begin(),
			ci_equal<typename R1::value_type>());
	}
	return false;
}

template <typename Pred, typename T> inline bool
unary_predicate<Pred, T>::operator () (T value) const {
	return Pred::check(value);
}

template <typename Pred, typename T> inline bool
binary_predicate<Pred, T>::operator () (T const &var, T const &target) const {
	return Pred::check(var, target);
}

template <typename Char> inline bool
is_space<Char>::check(Char value) {
	return char_traits<Char>::is_space(value);
}

template <typename Char> inline bool
is_blank<Char>::check(Char value) {
	return char_traits<Char>::is_blank(value);
}

template <typename Char> inline bool
is_line_end<Char>::check(Char value) {
	return (static_cast<Char>('\n') == value || static_cast<Char>('\r') == value);
}

template <typename Char> inline bool
is_not_line_end<Char>::check(Char value) {
	return !is_line_end<Char>::check(value);
}

template <typename Range> inline bool
ci_less<Range>::check(Range const &var, Range const &target) {
	return is_ci_less(var, target);
}

template <typename Range> inline bool
ci_equal<Range>::check(Range const &var, Range const &target) {
	return is_ci_equal(var, target);
}

inline bool
ci_less<char>::operator () (char var, char target) const {
	return char_traits<char>::to_lower(var) < char_traits<char>::to_lower(target);
}

inline bool
ci_less<const char>::operator () (const char var, const char target) const {
	return char_traits<const char>::to_lower(var) < char_traits<const char>::to_lower(target);
}

inline bool
ci_equal<char>::operator () (char var, char target) const {
	return char_traits<char>::to_lower(var) == char_traits<char>::to_lower(target);
}

inline bool
ci_equal<const char>::operator () (const char var, const char target) const {
	return char_traits<const char>::to_lower(var) == char_traits<const char>::to_lower(target);
}

}} // namespaces

#endif // XIVA_DETAILS_FUNCTORS_HPP_INCLUDED
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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

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

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

#ifndef FLUSSPFERD_CLASS_HPP
#define FLUSSPFERD_CLASS_HPP

#include "native_function_base.hpp"
#include "create.hpp"
#include "init.hpp"
#include "local_root_scope.hpp"
#include <boost/mpl/size_t.hpp>
#include <boost/ref.hpp>

namespace flusspferd {

namespace detail {

template<typename T>
struct class_constructor : native_function_base {
  class_constructor(unsigned arity, char const *name)
    : native_function_base(arity, name)
  {}

  void call(call_context &x) {
    x.result = create_native_object<T>(
        x.function.get_property("prototype").to_object(),
        boost::ref(x));
  }
};

}

struct class_info {
  typedef boost::mpl::size_t<0> constructor_arity;

  static void augment_constructor(object const &) {
  }

  static object create_prototype() {
    return create_object();
  }
};

template<typename T>
object load_class(object container = global()) {
  std::size_t const arity = T::class_info::constructor_arity::value;
  char const *name = T::class_info::constructor_name();

  local_root_scope scope;

  context ctx = get_current_context();

  value previous = container.get_property(name);

  if (previous.is_object())
    return previous.get_object();

  function constructor(
    create_native_function<detail::class_constructor<T> >(arity, name));

  ctx.add_constructor<T>(constructor);

  object prototype = T::class_info::create_prototype();

  ctx.add_prototype<T>(prototype);

  constructor.define_property(
    "prototype",
    prototype,
    object::dont_enumerate);

  T::class_info::augment_constructor(object(constructor));

  container.define_property(
    name,
    constructor,
    object::dont_enumerate);

  return constructor;
}

template<typename T>
bool load_internal_class() {
  local_root_scope scope;

  context ctx = get_current_context();

  object proto = ctx.get_prototype<T>();

  if (proto.is_valid())
    return false;

  proto = T::class_info::create_prototype();

  ctx.add_prototype<T>(proto);

  return true;
}

}

#endif
<commit_msg>Core: replace load_internal_class<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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

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

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

#ifndef FLUSSPFERD_CLASS_HPP
#define FLUSSPFERD_CLASS_HPP

#include "native_function_base.hpp"
#include "create.hpp"
#include "init.hpp"
#include "local_root_scope.hpp"
#include <boost/mpl/has_xxx.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/ref.hpp>

namespace flusspferd {

namespace detail {

BOOST_MPL_HAS_XXX_TRAIT_DEF(constructible)

template<typename T>
struct get_constructible {
  typedef typename T::constructible type;
};

template<typename T>
struct is_constructible :
  boost::mpl::or_<
    boost::mpl::not_<has_constructible<T> >,
    get_constructible<T>
  >::type
{};

template<typename T>
struct class_constructor : native_function_base {
  class_constructor(unsigned arity, char const *name)
    : native_function_base(arity, name)
  {}

  void call(call_context &x) {
    x.result = create_native_object<T>(
        x.function.get_property("prototype").to_object(),
        boost::ref(x));
  }
};

template<typename T>
object load_class(object &container, char const *name) {
  context ctx = get_current_context();

  object constructor(ctx.get_constructor<T>());

  object prototype = T::class_info::create_prototype();

  ctx.add_prototype<T>(prototype);

  constructor.define_property(
    "prototype",
    prototype,
    object::dont_enumerate);

  T::class_info::augment_constructor(object(constructor));

  container.define_property(name, constructor, object::dont_enumerate);

  return constructor;
}

}

struct class_info {
  typedef boost::mpl::size_t<0> constructor_arity;

  static void augment_constructor(object const &) {}

  static object create_prototype() {
    return create_object();
  }
};

template<typename T>
object load_class(
  object container = global(),
  typename boost::enable_if<
    detail::is_constructible<typename T::class_info>
  >::type * = 0)
{
  std::size_t const arity = T::class_info::constructor_arity::value;
  char const *name = T::class_info::constructor_name();

  local_root_scope scope;

  context ctx = get_current_context();

  value previous = container.get_property(name);

  if (previous.is_object())
    return previous.get_object();

  if (!ctx.get_constructor<T>().is_valid())
    ctx.add_constructor<T>(
      create_native_function<detail::class_constructor<T> >(arity, name));

  return detail::load_class<T>(container, name);
}

template<typename T>
bool load_class(
  object container = global(),
  typename boost::enable_if<
    boost::mpl::not_<detail::is_constructible<typename T::class_info> >
  >::type * = 0)
{
  char const *name = T::class_info::constructor_name();

  local_root_scope scope;

  context ctx = get_current_context();

  value previous = container.get_property(name);

  if (previous.is_object())
    return previous.get_object();

  if (!ctx.get_constructor<T>().is_valid())
    ctx.add_constructor<T>(create_object());

  return detail::load_class<T>(container, name);
}

}

#endif
<|endoftext|>


<commit_before>/*
The IF Contextual Media Group Kernel Version 3
Source Code

Written By Jeff Koftinoff <jeffk@contextualmediagroup.com>
Copyright (c) 1995-2005
By Contextual Media Group, Inc.
http://www.contextualmediagroup.com/

ALL RIGHTS RESERVED.

*/
#ifndef IFCMG_DB_NEEDLES_HPP
#define IFCMG_DB_NEEDLES_HPP

#include "ifcmg_world.hpp"

#include "ifcmg_string.hpp"
#include "ifcmg_db_util.hpp"

namespace ifcmg
{

  class db_needles_row_t
  {
  public:
    db_needles_row_t()
    :
    m_id(-1)
    {
    }

    db_needles_row_t( db_needles_row_t const &o )
    :
    m_id( o.m_id )
    {
    }

    db_needles_row_t( string_t const &line )
    {
    }

    ~db_needles_row_t()
    {
    }

    db_needles_row_t & operator = ( db_needles_row_t const &o )
    {
      return *this;
    }

    int64_t m_id;
    char m_needle[128];
    int64_t m_section;
    int64_t m_category1;
    int64_t m_category2;
    int64_t m_category3;
    int64_t m_category4;
    int32_t m_score;
    int32_t m_autogen;
  };

  typedef std::vector< db_needles_row_t > db_needles_table_t;

  void load( db_needles_table_t &t, filename_t file );

}

#endif

<commit_msg>more database needles implementation.<commit_after>/*
The IF Contextual Media Group Kernel Version 3
Source Code

Written By Jeff Koftinoff <jeffk@contextualmediagroup.com>
Copyright (c) 1995-2005
By Contextual Media Group, Inc.
http://www.contextualmediagroup.com/

ALL RIGHTS RESERVED.

*/
#ifndef IFCMG_DB_NEEDLES_HPP
#define IFCMG_DB_NEEDLES_HPP

#include "ifcmg_world.hpp"

#include "ifcmg_string.hpp"
#include "ifcmg_db_util.hpp"

namespace ifcmg
{

  class db_needles_row_t
  {
  public:
    db_needles_row_t()
    :
    m_id(-1)
    {
    }

    db_needles_row_t( db_needles_row_t const &o )
    :
    m_id( o.m_id )
    {
    }

    db_needles_row_t( string_t const &line )
    {
    }

    ~db_needles_row_t()
    {
    }

    db_needles_row_t & operator = ( db_needles_row_t const &o )
    {
      m_id = o.m_id;
      m_needle = o.m_needle;
      m_section = o.m_section;
      m_category1 = o.m_category1;
      m_category2 = o.m_category2;
      m_category3 = o.m_category3;
      m_category4 = o.m_category4;
      m_score = o.m_score;
      m_autogen = o.m_autogen;
      return *this;
    }

    int64_t m_id;
    std::string m_needle;
    int64_t m_section;
    int64_t m_category1;
    int64_t m_category2;
    int64_t m_category3;
    int64_t m_category4;
    int32_t m_score;
    int32_t m_autogen;
  };

  class db_needles_table_t
  {
  public:
  };

  void load( db_needles_table_t &t, filename_t file );
}

#endif

<|endoftext|>