<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;
            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;
}
<commit_msg>added todo<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;

/*
PixLE todo
different paint tools: brush, fill
brushes / sizes
brush preview/hover
transparency
tool: eraser
layers
undo/redo
save/load via terminal
fast draw
aa lines
tile x/y mode
clone/pattern brush
*/

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("PixLE", 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("Image"))
        {
            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>#include "headers/mainwindow.h"
#include "headers/cryptogame.h"
#include "headers/primefactorization.h"
#include "headers/generateprimes.h"
#include "ui_mainwindow.h"
#include "QPushButton"

#include "iostream" //for debugging

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_GPUCheckBox_clicked()
{

}

void MainWindow::on_pushButton_clicked()
{
    std::cout<<"Start the game."<<std::endl;
//    cryptogame agame = cryptogame();
//    std::cout<<agame.getEncryptedMessage()<<std::endl;

}

void MainWindow::on_factorPrimesButton_clicked()
{
	using std::cout;
	using std::endl;

	cout<< "'Factor Primes' button pressed" <<endl;
	mpz_class composite, p, q;
	GeneratePrimes gp = GeneratePrimes();
	p = gp.readRandomPrime("primes.txt");
	q = gp.readRandomPrime("primes.txt");
	composite = p * q;

	cout << p.get_str(10) << " * " << q.get_str(10) << " = " << composite.get_str(10) << endl;

	cout << "Number to factor: " << composite.get_str(10) << endl;

	PrimeFactorization pf = PrimeFactorization();
	pf.bruteForceFactor(composite);

	cout << "factor 1: " << pf.p1.get_str(10) << endl;
	cout << "factor 2: " << pf.p2.get_str(10) << endl;
}
<commit_msg>removed comment<commit_after>#include "headers/mainwindow.h"
#include "headers/cryptogame.h"
#include "headers/primefactorization.h"
#include "headers/generateprimes.h"
#include "ui_mainwindow.h"
#include "QPushButton"

#include "iostream" //for debugging

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_GPUCheckBox_clicked()
{

}

void MainWindow::on_pushButton_clicked()
{
    std::cout<<"Start the game."<<std::endl;
    cryptogame agame = cryptogame();
    std::cout<<agame.getEncryptedMessage()<<std::endl;

}

void MainWindow::on_factorPrimesButton_clicked()
{
	using std::cout;
	using std::endl;

	cout<< "'Factor Primes' button pressed" <<endl;
	mpz_class composite, p, q;
	GeneratePrimes gp = GeneratePrimes();
	p = gp.readRandomPrime("primes.txt");
	q = gp.readRandomPrime("primes.txt");
	composite = p * q;

	cout << p.get_str(10) << " * " << q.get_str(10) << " = " << composite.get_str(10) << endl;

	cout << "Number to factor: " << composite.get_str(10) << endl;

	PrimeFactorization pf = PrimeFactorization();
	pf.bruteForceFactor(composite);

	cout << "factor 1: " << pf.p1.get_str(10) << endl;
	cout << "factor 2: " << pf.p2.get_str(10) << endl;
}
<|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/extensions/test_extension_system.h"

#include "chrome/browser/extensions/api/alarms/alarm_manager.h"
#include "chrome/browser/extensions/extension_devtools_manager.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/extensions/extension_pref_value_map.h"
#include "chrome/browser/extensions/extension_pref_value_map_factory.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/value_store/testing_value_store.h"
#include "chrome/common/chrome_switches.h"

TestExtensionSystem::TestExtensionSystem(Profile* profile)
    : profile_(profile),
      info_map_(new ExtensionInfoMap()) {
}

TestExtensionSystem::~TestExtensionSystem() {
}

void TestExtensionSystem::Shutdown() {
  extension_process_manager_.reset();
}

void TestExtensionSystem::CreateExtensionProcessManager() {
  extension_process_manager_.reset(ExtensionProcessManager::Create(profile_));
}

void TestExtensionSystem::CreateAlarmManager(
    extensions::AlarmManager::TimeProvider now) {
  alarm_manager_.reset(new extensions::AlarmManager(profile_, now));
}

ExtensionService* TestExtensionSystem::CreateExtensionService(
    const CommandLine* command_line,
    const FilePath& install_directory,
    bool autoupdate_enabled) {
  bool extensions_disabled =
      command_line && command_line->HasSwitch(switches::kDisableExtensions);

  // Note that the GetPrefs() creates a TestingPrefService, therefore
  // the extension controlled pref values set in extension_prefs_
  // are not reflected in the pref service. One would need to
  // inject a new ExtensionPrefStore(extension_pref_value_map, false).

  extension_prefs_.reset(new extensions::ExtensionPrefs(
      profile_->GetPrefs(),
      install_directory,
      ExtensionPrefValueMapFactory::GetForProfile(profile_)));
  state_store_.reset(new extensions::StateStore(
      profile_,
      new TestingValueStore()));
  extension_prefs_->Init(extensions_disabled);
  extension_service_.reset(new ExtensionService(profile_,
                                                command_line,
                                                install_directory,
                                                extension_prefs_.get(),
                                                autoupdate_enabled,
                                                true));
  return extension_service_.get();
}

extensions::ManagementPolicy* TestExtensionSystem::CreateManagementPolicy() {
  management_policy_.reset(new extensions::ManagementPolicy());
  DCHECK(extension_prefs_.get());
  management_policy_->RegisterProvider(extension_prefs_.get());

  return management_policy();
}

ExtensionService* TestExtensionSystem::extension_service() {
  return extension_service_.get();
}

extensions::ManagementPolicy* TestExtensionSystem::management_policy() {
  return management_policy_.get();
}

void TestExtensionSystem::SetExtensionService(ExtensionService* service) {
  extension_service_.reset(service);
}

UserScriptMaster* TestExtensionSystem::user_script_master() {
  return NULL;
}

ExtensionDevToolsManager* TestExtensionSystem::devtools_manager() {
  return NULL;
}

ExtensionProcessManager* TestExtensionSystem::process_manager() {
  return extension_process_manager_.get();
}

extensions::AlarmManager* TestExtensionSystem::alarm_manager() {
  return alarm_manager_.get();
}

extensions::StateStore* TestExtensionSystem::state_store() {
  return state_store_.get();
}

ExtensionInfoMap* TestExtensionSystem::info_map() {
  return info_map_.get();
}

extensions::LazyBackgroundTaskQueue*
TestExtensionSystem::lazy_background_task_queue() {
  return NULL;
}

ExtensionMessageService* TestExtensionSystem::message_service() {
  return NULL;
}

ExtensionEventRouter* TestExtensionSystem::event_router() {
  return NULL;
}

extensions::RulesRegistryService*
TestExtensionSystem::rules_registry_service() {
  return NULL;
}

// static
ProfileKeyedService* TestExtensionSystem::Build(Profile* profile) {
  return new TestExtensionSystem(profile);
}
<commit_msg>Don't create external extension providers for a TestExtensionSystem.<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/extensions/test_extension_system.h"

#include "chrome/browser/extensions/api/alarms/alarm_manager.h"
#include "chrome/browser/extensions/extension_devtools_manager.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/extensions/extension_pref_value_map.h"
#include "chrome/browser/extensions/extension_pref_value_map_factory.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/value_store/testing_value_store.h"
#include "chrome/common/chrome_switches.h"

TestExtensionSystem::TestExtensionSystem(Profile* profile)
    : profile_(profile),
      info_map_(new ExtensionInfoMap()) {
}

TestExtensionSystem::~TestExtensionSystem() {
}

void TestExtensionSystem::Shutdown() {
  extension_process_manager_.reset();
}

void TestExtensionSystem::CreateExtensionProcessManager() {
  extension_process_manager_.reset(ExtensionProcessManager::Create(profile_));
}

void TestExtensionSystem::CreateAlarmManager(
    extensions::AlarmManager::TimeProvider now) {
  alarm_manager_.reset(new extensions::AlarmManager(profile_, now));
}

ExtensionService* TestExtensionSystem::CreateExtensionService(
    const CommandLine* command_line,
    const FilePath& install_directory,
    bool autoupdate_enabled) {
  bool extensions_disabled =
      command_line && command_line->HasSwitch(switches::kDisableExtensions);

  // Note that the GetPrefs() creates a TestingPrefService, therefore
  // the extension controlled pref values set in extension_prefs_
  // are not reflected in the pref service. One would need to
  // inject a new ExtensionPrefStore(extension_pref_value_map, false).

  extension_prefs_.reset(new extensions::ExtensionPrefs(
      profile_->GetPrefs(),
      install_directory,
      ExtensionPrefValueMapFactory::GetForProfile(profile_)));
  state_store_.reset(new extensions::StateStore(
      profile_,
      new TestingValueStore()));
  extension_prefs_->Init(extensions_disabled);
  extension_service_.reset(new ExtensionService(profile_,
                                                command_line,
                                                install_directory,
                                                extension_prefs_.get(),
                                                autoupdate_enabled,
                                                true));
  extension_service_->ClearProvidersForTesting();
  return extension_service_.get();
}

extensions::ManagementPolicy* TestExtensionSystem::CreateManagementPolicy() {
  management_policy_.reset(new extensions::ManagementPolicy());
  DCHECK(extension_prefs_.get());
  management_policy_->RegisterProvider(extension_prefs_.get());

  return management_policy();
}

ExtensionService* TestExtensionSystem::extension_service() {
  return extension_service_.get();
}

extensions::ManagementPolicy* TestExtensionSystem::management_policy() {
  return management_policy_.get();
}

void TestExtensionSystem::SetExtensionService(ExtensionService* service) {
  extension_service_.reset(service);
}

UserScriptMaster* TestExtensionSystem::user_script_master() {
  return NULL;
}

ExtensionDevToolsManager* TestExtensionSystem::devtools_manager() {
  return NULL;
}

ExtensionProcessManager* TestExtensionSystem::process_manager() {
  return extension_process_manager_.get();
}

extensions::AlarmManager* TestExtensionSystem::alarm_manager() {
  return alarm_manager_.get();
}

extensions::StateStore* TestExtensionSystem::state_store() {
  return state_store_.get();
}

ExtensionInfoMap* TestExtensionSystem::info_map() {
  return info_map_.get();
}

extensions::LazyBackgroundTaskQueue*
TestExtensionSystem::lazy_background_task_queue() {
  return NULL;
}

ExtensionMessageService* TestExtensionSystem::message_service() {
  return NULL;
}

ExtensionEventRouter* TestExtensionSystem::event_router() {
  return NULL;
}

extensions::RulesRegistryService*
TestExtensionSystem::rules_registry_service() {
  return NULL;
}

// static
ProfileKeyedService* TestExtensionSystem::Build(Profile* profile) {
  return new TestExtensionSystem(profile);
}
<|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/speech/speech_input_bubble.h"

#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/ui/views/info_bubble.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "views/controls/button/native_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/layout/layout_constants.h"
#include "views/view.h"

namespace {

const int kBubbleHorizMargin = 6;
const int kBubbleVertMargin = 0;

// This is the content view which is placed inside a SpeechInputBubble.
class ContentView
    : public views::View,
      public views::ButtonListener {
 public:
  explicit ContentView(SpeechInputBubbleDelegate* delegate);

  void UpdateLayout(SpeechInputBubbleBase::DisplayMode mode,
                    const string16& message_text);
  void SetImage(const SkBitmap& image);

  // views::ButtonListener methods.
  virtual void ButtonPressed(views::Button* source, const views::Event& event);

  // views::View overrides.
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();

 private:
  SpeechInputBubbleDelegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* message_;
  views::NativeButton* try_again_;
  views::NativeButton* cancel_;

  DISALLOW_COPY_AND_ASSIGN(ContentView);
};

ContentView::ContentView(SpeechInputBubbleDelegate* delegate)
     : delegate_(delegate) {
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  const gfx::Font& font = rb.GetFont(ResourceBundle::MediumFont);

  heading_ = new views::Label(
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_BUBBLE_HEADING)));
  heading_->SetFont(font);
  heading_->SetHorizontalAlignment(views::Label::ALIGN_CENTER);
  AddChildView(heading_);

  message_ = new views::Label();
  message_->SetFont(font);
  message_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  message_->SetMultiLine(true);
  AddChildView(message_);

  icon_ = new views::ImageView();
  icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_SPEECH_INPUT_MIC_EMPTY));
  icon_->SetHorizontalAlignment(views::ImageView::CENTER);
  AddChildView(icon_);

  cancel_ = new views::NativeButton(
      this,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_CANCEL)));
  AddChildView(cancel_);

  try_again_ = new views::NativeButton(
      this,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_TRY_AGAIN)));
  AddChildView(try_again_);
}

void ContentView::UpdateLayout(SpeechInputBubbleBase::DisplayMode mode,
                               const string16& message_text) {
  bool is_message = (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE);
  heading_->SetVisible(!is_message);
  icon_->SetVisible(!is_message);
  message_->SetVisible(is_message);
  try_again_->SetVisible(is_message);

  if (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE) {
    message_->SetText(UTF16ToWideHack(message_text));
  } else if (mode == SpeechInputBubbleBase::DISPLAY_MODE_RECORDING) {
    heading_->SetText(UTF16ToWide(
        l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_BUBBLE_HEADING)));
    icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed(
        IDR_SPEECH_INPUT_MIC_EMPTY));
  } else {
    heading_->SetText(UTF16ToWide(
        l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_BUBBLE_WORKING)));
  }
}

void ContentView::SetImage(const SkBitmap& image) {
  icon_->SetImage(image);
}

void ContentView::ButtonPressed(views::Button* source,
                                const views::Event& event) {
  if (source == cancel_) {
    delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL);
  } else if (source == try_again_) {
    delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_TRY_AGAIN);
  } else {
    NOTREACHED() << "Unknown button";
  }
}

gfx::Size ContentView::GetPreferredSize() {
  int width = heading_->GetPreferredSize().width();
  int control_width = cancel_->GetPreferredSize().width() +
                      try_again_->GetPreferredSize().width() +
                      views::kRelatedButtonHSpacing;
  if (control_width > width)
    width = control_width;
  control_width = icon_->GetPreferredSize().width();
  if (control_width > width)
    width = control_width;

  int height = cancel_->GetPreferredSize().height();
  if (message_->IsVisible()) {
    height += message_->GetHeightForWidth(width) +
              views::kLabelToControlVerticalSpacing;
  } else {
    height += heading_->GetPreferredSize().height() +
              icon_->GetImage().height();
  }
  width += kBubbleHorizMargin * 2;
  height += kBubbleVertMargin * 2;

  return gfx::Size(width, height);
}

void ContentView::Layout() {
  int x = kBubbleHorizMargin;
  int y = kBubbleVertMargin;
  int available_width = width() - kBubbleHorizMargin * 2;
  int available_height = height() - kBubbleVertMargin * 2;

  if (message_->IsVisible()) {
    DCHECK(try_again_->IsVisible());

    int height = try_again_->GetPreferredSize().height();
    int try_again_width = try_again_->GetPreferredSize().width();
    int cancel_width = cancel_->GetPreferredSize().width();
    y += available_height - height;
    x += (available_width - cancel_width - try_again_width -
          views::kRelatedButtonHSpacing) / 2;
    try_again_->SetBounds(x, y, try_again_width, height);
    cancel_->SetBounds(x + try_again_width + views::kRelatedButtonHSpacing, y,
                       cancel_width, height);

    height = message_->GetHeightForWidth(available_width);
    if (height > y - kBubbleVertMargin)
      height = y - kBubbleVertMargin;
    message_->SetBounds(kBubbleHorizMargin, kBubbleVertMargin,
                        available_width, height);
  } else {
    DCHECK(heading_->IsVisible());
    DCHECK(icon_->IsVisible());

    int height = heading_->GetPreferredSize().height();
    heading_->SetBounds(x, y, available_width, height);
    y += height;

    height = icon_->GetImage().height();
    icon_->SetBounds(x, y, available_width, height);
    y += height;

    height = cancel_->GetPreferredSize().height();
    int width = cancel_->GetPreferredSize().width();
    cancel_->SetBounds(x + (available_width - width) / 2, y, width, height);
  }
}

// Implementation of SpeechInputBubble.
class SpeechInputBubbleImpl
    : public SpeechInputBubbleBase,
      public InfoBubbleDelegate {
 public:
  SpeechInputBubbleImpl(TabContents* tab_contents,
                        Delegate* delegate,
                        const gfx::Rect& element_rect);
  virtual ~SpeechInputBubbleImpl();

  // SpeechInputBubble methods.
  virtual void Show();
  virtual void Hide();

  // SpeechInputBubbleBase methods.
  virtual void UpdateLayout();
  virtual void SetImage(const SkBitmap& image);

  // Returns the screen rectangle to use as the info bubble's target.
  // |element_rect| is the html element's bounds in page coordinates.
  gfx::Rect GetInfoBubbleTarget(const gfx::Rect& element_rect);

  // InfoBubbleDelegate
  virtual void InfoBubbleClosing(InfoBubble* info_bubble,
                                 bool closed_by_escape);
  virtual bool CloseOnEscape();
  virtual bool FadeInOnShow();

 private:
  Delegate* delegate_;
  InfoBubble* info_bubble_;
  ContentView* bubble_content_;
  gfx::Rect element_rect_;

  // Set to true if the object is being destroyed normally instead of the
  // user clicking outside the window causing it to close automatically.
  bool did_invoke_close_;

  DISALLOW_COPY_AND_ASSIGN(SpeechInputBubbleImpl);
};

SpeechInputBubbleImpl::SpeechInputBubbleImpl(TabContents* tab_contents,
                                             Delegate* delegate,
                                             const gfx::Rect& element_rect)
    : SpeechInputBubbleBase(tab_contents),
      delegate_(delegate),
      info_bubble_(NULL),
      bubble_content_(NULL),
      element_rect_(element_rect),
      did_invoke_close_(false) {
}

SpeechInputBubbleImpl::~SpeechInputBubbleImpl() {
  did_invoke_close_ = true;
  Hide();
}

gfx::Rect SpeechInputBubbleImpl::GetInfoBubbleTarget(
    const gfx::Rect& element_rect) {
  gfx::Rect container_rect;
  tab_contents()->GetContainerBounds(&container_rect);
  return gfx::Rect(
      container_rect.x() + element_rect.x() + kBubbleTargetOffsetX,
      container_rect.y() + element_rect.y() + element_rect.height(), 1, 1);
}

void SpeechInputBubbleImpl::InfoBubbleClosing(InfoBubble* info_bubble,
                                              bool closed_by_escape) {
  info_bubble_ = NULL;
  bubble_content_ = NULL;
  if (!did_invoke_close_)
    delegate_->InfoBubbleFocusChanged();
}

bool SpeechInputBubbleImpl::CloseOnEscape() {
  return false;
}

bool SpeechInputBubbleImpl::FadeInOnShow() {
  return false;
}

void SpeechInputBubbleImpl::Show() {
  if (info_bubble_)
    return;  // nothing to do, already visible.

  bubble_content_ = new ContentView(delegate_);
  UpdateLayout();

  views::Widget* tab = views::Widget::GetWidgetFromNativeView(
      tab_contents()->view()->GetNativeView());
  views::Widget* parent = tab ? tab->GetRootWidget() : NULL;

  if (parent) {
    info_bubble_ = InfoBubble::Show(parent,
                                    GetInfoBubbleTarget(element_rect_),
                                    BubbleBorder::TOP_LEFT, bubble_content_,
                                    this);

    // We don't want fade outs when closing because it makes speech recognition
    // appear slower than it is. Also setting it to false allows |Close| to
    // destroy the bubble immediately instead of waiting for the fade animation
    // to end so the caller can manage this object's life cycle like a normal
    // stack based or member variable object.
    info_bubble_->set_fade_away_on_close(false);
  }
}

void SpeechInputBubbleImpl::Hide() {
  if (info_bubble_)
    info_bubble_->Close();
}

void SpeechInputBubbleImpl::UpdateLayout() {
  if (bubble_content_)
    bubble_content_->UpdateLayout(display_mode(), message_text());
  if (info_bubble_)  // Will be null on first call.
    info_bubble_->SizeToContents();
}

void SpeechInputBubbleImpl::SetImage(const SkBitmap& image) {
  if (bubble_content_)
    bubble_content_->SetImage(image);
}

}  // namespace

SpeechInputBubble* SpeechInputBubble::CreateNativeBubble(
    TabContents* tab_contents,
    SpeechInputBubble::Delegate* delegate,
    const gfx::Rect& element_rect) {
  return new SpeechInputBubbleImpl(tab_contents, delegate, element_rect);
}
<commit_msg>Redo the speech bubble layout on windows.<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/speech/speech_input_bubble.h"

#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/ui/views/info_bubble.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "media/audio/audio_manager.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "views/border.h"
#include "views/controls/button/native_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/layout/layout_constants.h"
#include "views/view.h"

namespace {

const int kBubbleHorizMargin = 6;
const int kBubbleVertMargin = 4;
const int kBubbleHeadingVertMargin = 6;

// This is the content view which is placed inside a SpeechInputBubble.
class ContentView
    : public views::View,
      public views::ButtonListener,
      public views::LinkController {
 public:
  explicit ContentView(SpeechInputBubbleDelegate* delegate);

  void UpdateLayout(SpeechInputBubbleBase::DisplayMode mode,
                    const string16& message_text);
  void SetImage(const SkBitmap& image);

  // views::ButtonListener methods.
  virtual void ButtonPressed(views::Button* source, const views::Event& event);

  // views::LinkController methods.
  virtual void LinkActivated(views::Link* source, int event_flags);

  // views::View overrides.
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();

 private:
  SpeechInputBubbleDelegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* message_;
  views::NativeButton* try_again_;
  views::NativeButton* cancel_;
  views::Link* mic_settings_;

  DISALLOW_COPY_AND_ASSIGN(ContentView);
};

ContentView::ContentView(SpeechInputBubbleDelegate* delegate)
     : delegate_(delegate) {
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  const gfx::Font& font = rb.GetFont(ResourceBundle::MediumFont);

  heading_ = new views::Label(
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_BUBBLE_HEADING)));
  heading_->set_border(views::Border::CreateEmptyBorder(
      kBubbleHeadingVertMargin, 0, kBubbleHeadingVertMargin, 0));
  heading_->SetFont(font);
  heading_->SetHorizontalAlignment(views::Label::ALIGN_CENTER);
  heading_->SetText(UTF16ToWide(
      l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_BUBBLE_HEADING)));
  AddChildView(heading_);

  message_ = new views::Label();
  message_->SetFont(font);
  message_->SetHorizontalAlignment(views::Label::ALIGN_CENTER);
  message_->SetMultiLine(true);
  AddChildView(message_);

  icon_ = new views::ImageView();
  icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_SPEECH_INPUT_MIC_EMPTY));
  icon_->SetHorizontalAlignment(views::ImageView::CENTER);
  AddChildView(icon_);

  cancel_ = new views::NativeButton(
      this,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_CANCEL)));
  AddChildView(cancel_);

  try_again_ = new views::NativeButton(
      this,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_TRY_AGAIN)));
  AddChildView(try_again_);

  mic_settings_ = new views::Link(
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_MIC_SETTINGS)));
  mic_settings_->SetController(this);
  AddChildView(mic_settings_);
}

void ContentView::UpdateLayout(SpeechInputBubbleBase::DisplayMode mode,
                               const string16& message_text) {
  bool is_message = (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE);
  icon_->SetVisible(!is_message);
  message_->SetVisible(is_message);
  mic_settings_->SetVisible(is_message);
  try_again_->SetVisible(is_message);
  heading_->SetVisible(mode == SpeechInputBubbleBase::DISPLAY_MODE_RECORDING);

  if (mode == SpeechInputBubbleBase::DISPLAY_MODE_MESSAGE) {
    message_->SetText(UTF16ToWideHack(message_text));
  } else if (mode == SpeechInputBubbleBase::DISPLAY_MODE_RECORDING) {
    icon_->SetImage(*ResourceBundle::GetSharedInstance().GetBitmapNamed(
        IDR_SPEECH_INPUT_MIC_EMPTY));
  }

  if (icon_->IsVisible())
    icon_->ResetImageSize();
}

void ContentView::SetImage(const SkBitmap& image) {
  icon_->SetImage(image);
}

void ContentView::ButtonPressed(views::Button* source,
                                const views::Event& event) {
  if (source == cancel_) {
    delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL);
  } else if (source == try_again_) {
    delegate_->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_TRY_AGAIN);
  } else {
    NOTREACHED() << "Unknown button";
  }
}

void ContentView::LinkActivated(views::Link* source, int event_flags) {
  DCHECK_EQ(source, mic_settings_);
  AudioManager::GetAudioManager()->ShowAudioInputSettings();
}

gfx::Size ContentView::GetPreferredSize() {
  int width = heading_->GetPreferredSize().width();
  int control_width = cancel_->GetPreferredSize().width();
  if (try_again_->IsVisible()) {
    control_width += try_again_->GetPreferredSize().width() +
                     views::kRelatedButtonHSpacing;
  }
  if (control_width > width)
    width = control_width;
  control_width = icon_->GetPreferredSize().width();
  if (control_width > width)
    width = control_width;
  if (mic_settings_->IsVisible()) {
    control_width = mic_settings_->GetPreferredSize().width();
    if (control_width > width)
      width = control_width;
  }

  int height = cancel_->GetPreferredSize().height();
  if (message_->IsVisible()) {
    height += message_->GetHeightForWidth(width) +
              views::kLabelToControlVerticalSpacing;
  }
  if (heading_->IsVisible())
    height += heading_->GetPreferredSize().height();
  if (icon_->IsVisible())
    height += icon_->GetImage().height();
  if (mic_settings_->IsVisible())
    height += mic_settings_->GetPreferredSize().height();
  width += kBubbleHorizMargin * 2;
  height += kBubbleVertMargin * 2;

  return gfx::Size(width, height);
}

void ContentView::Layout() {
  int x = kBubbleHorizMargin;
  int y = kBubbleVertMargin;
  int available_width = width() - kBubbleHorizMargin * 2;
  int available_height = height() - kBubbleVertMargin * 2;

  if (message_->IsVisible()) {
    DCHECK(try_again_->IsVisible());

    int control_height = try_again_->GetPreferredSize().height();
    int try_again_width = try_again_->GetPreferredSize().width();
    int cancel_width = cancel_->GetPreferredSize().width();
    y += available_height - control_height;
    x += (available_width - cancel_width - try_again_width -
          views::kRelatedButtonHSpacing) / 2;
    try_again_->SetBounds(x, y, try_again_width, control_height);
    cancel_->SetBounds(x + try_again_width + views::kRelatedButtonHSpacing, y,
                       cancel_width, control_height);

    control_height = message_->GetHeightForWidth(available_width);
    message_->SetBounds(kBubbleHorizMargin, kBubbleVertMargin,
                        available_width, control_height);
    y = kBubbleVertMargin + control_height;

    control_height = mic_settings_->GetPreferredSize().height();
    mic_settings_->SetBounds(kBubbleHorizMargin, y, available_width,
                             control_height);
  } else {
    DCHECK(icon_->IsVisible());

    int control_height = icon_->GetImage().height();
    icon_->SetBounds(x, y, available_width, control_height);
    y += control_height;

    if (heading_->IsVisible()) {
      control_height = heading_->GetPreferredSize().height();
      heading_->SetBounds(x, y, available_width, control_height);
      y += control_height;
    }

    control_height = cancel_->GetPreferredSize().height();
    int width = cancel_->GetPreferredSize().width();
    cancel_->SetBounds(x + (available_width - width) / 2, y, width,
                       control_height);
  }
}

// Implementation of SpeechInputBubble.
class SpeechInputBubbleImpl
    : public SpeechInputBubbleBase,
      public InfoBubbleDelegate {
 public:
  SpeechInputBubbleImpl(TabContents* tab_contents,
                        Delegate* delegate,
                        const gfx::Rect& element_rect);
  virtual ~SpeechInputBubbleImpl();

  // SpeechInputBubble methods.
  virtual void Show();
  virtual void Hide();

  // SpeechInputBubbleBase methods.
  virtual void UpdateLayout();
  virtual void SetImage(const SkBitmap& image);

  // Returns the screen rectangle to use as the info bubble's target.
  // |element_rect| is the html element's bounds in page coordinates.
  gfx::Rect GetInfoBubbleTarget(const gfx::Rect& element_rect);

  // InfoBubbleDelegate
  virtual void InfoBubbleClosing(InfoBubble* info_bubble,
                                 bool closed_by_escape);
  virtual bool CloseOnEscape();
  virtual bool FadeInOnShow();

 private:
  Delegate* delegate_;
  InfoBubble* info_bubble_;
  ContentView* bubble_content_;
  gfx::Rect element_rect_;

  // Set to true if the object is being destroyed normally instead of the
  // user clicking outside the window causing it to close automatically.
  bool did_invoke_close_;

  DISALLOW_COPY_AND_ASSIGN(SpeechInputBubbleImpl);
};

SpeechInputBubbleImpl::SpeechInputBubbleImpl(TabContents* tab_contents,
                                             Delegate* delegate,
                                             const gfx::Rect& element_rect)
    : SpeechInputBubbleBase(tab_contents),
      delegate_(delegate),
      info_bubble_(NULL),
      bubble_content_(NULL),
      element_rect_(element_rect),
      did_invoke_close_(false) {
}

SpeechInputBubbleImpl::~SpeechInputBubbleImpl() {
  did_invoke_close_ = true;
  Hide();
}

gfx::Rect SpeechInputBubbleImpl::GetInfoBubbleTarget(
    const gfx::Rect& element_rect) {
  gfx::Rect container_rect;
  tab_contents()->GetContainerBounds(&container_rect);
  return gfx::Rect(
      container_rect.x() + element_rect.x() + element_rect.width() -
          kBubbleTargetOffsetX,
      container_rect.y() + element_rect.y() + element_rect.height(), 1, 1);
}

void SpeechInputBubbleImpl::InfoBubbleClosing(InfoBubble* info_bubble,
                                              bool closed_by_escape) {
  info_bubble_ = NULL;
  bubble_content_ = NULL;
  if (!did_invoke_close_)
    delegate_->InfoBubbleFocusChanged();
}

bool SpeechInputBubbleImpl::CloseOnEscape() {
  return false;
}

bool SpeechInputBubbleImpl::FadeInOnShow() {
  return false;
}

void SpeechInputBubbleImpl::Show() {
  if (info_bubble_)
    return;  // nothing to do, already visible.

  bubble_content_ = new ContentView(delegate_);
  UpdateLayout();

  views::Widget* tab = views::Widget::GetWidgetFromNativeView(
      tab_contents()->view()->GetNativeView());
  views::Widget* parent = tab ? tab->GetRootWidget() : NULL;

  if (parent) {
    info_bubble_ = InfoBubble::Show(parent,
                                    GetInfoBubbleTarget(element_rect_),
                                    BubbleBorder::TOP_LEFT, bubble_content_,
                                    this);

    // We don't want fade outs when closing because it makes speech recognition
    // appear slower than it is. Also setting it to false allows |Close| to
    // destroy the bubble immediately instead of waiting for the fade animation
    // to end so the caller can manage this object's life cycle like a normal
    // stack based or member variable object.
    info_bubble_->set_fade_away_on_close(false);
  }
}

void SpeechInputBubbleImpl::Hide() {
  if (info_bubble_)
    info_bubble_->Close();
}

void SpeechInputBubbleImpl::UpdateLayout() {
  if (bubble_content_)
    bubble_content_->UpdateLayout(display_mode(), message_text());
  if (info_bubble_)  // Will be null on first call.
    info_bubble_->SizeToContents();
}

void SpeechInputBubbleImpl::SetImage(const SkBitmap& image) {
  if (bubble_content_)
    bubble_content_->SetImage(image);
}

}  // namespace

SpeechInputBubble* SpeechInputBubble::CreateNativeBubble(
    TabContents* tab_contents,
    SpeechInputBubble::Delegate* delegate,
    const gfx::Rect& element_rect) {
  return new SpeechInputBubbleImpl(tab_contents, delegate, element_rect);
}
<|endoftext|>


<commit_before>//===--- UseDefaultMemberInitCheck.cpp - clang-tidy------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "UseDefaultMemberInitCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace modernize {

static StringRef getValueOfValueInit(const QualType InitType) {
  switch (InitType->getScalarTypeKind()) {
  case Type::STK_CPointer:
  case Type::STK_BlockPointer:
  case Type::STK_ObjCObjectPointer:
  case Type::STK_MemberPointer:
    return "nullptr";

  case Type::STK_Bool:
    return "false";

  case Type::STK_Integral:
    switch (InitType->getAs<BuiltinType>()->getKind()) {
    case BuiltinType::Char_U:
    case BuiltinType::UChar:
    case BuiltinType::Char_S:
    case BuiltinType::SChar:
      return "'\\0'";
    case BuiltinType::WChar_U:
    case BuiltinType::WChar_S:
      return "L'\\0'";
    case BuiltinType::Char16:
      return "u'\\0'";
    case BuiltinType::Char32:
      return "U'\\0'";
    default:
      return "0";
    }

  case Type::STK_Floating:
    switch (InitType->getAs<BuiltinType>()->getKind()) {
    case BuiltinType::Half:
    case BuiltinType::Float:
      return "0.0f";
    default:
      return "0.0";
    }

  case Type::STK_FloatingComplex:
  case Type::STK_IntegralComplex:
    return getValueOfValueInit(
        InitType->getAs<ComplexType>()->getElementType());
  case Type::STK_FixedPoint:
    switch (InitType->getAs<BuiltinType>()->getKind()) {
      case BuiltinType::ShortAccum:
      case BuiltinType::SatShortAccum:
        return "0.0hk";
      case BuiltinType::Accum:
      case BuiltinType::SatAccum:
        return "0.0k";
      case BuiltinType::LongAccum:
      case BuiltinType::SatLongAccum:
        return "0.0lk";
      case BuiltinType::UShortAccum:
      case BuiltinType::SatUShortAccum:
        return "0.0uhk";
      case BuiltinType::UAccum:
      case BuiltinType::SatUAccum:
        return "0.0uk";
      case BuiltinType::ULongAccum:
      case BuiltinType::SatULongAccum:
        return "0.0ulk";
      case BuiltinType::ShortFract:
      case BuiltinType::SatShortFract:
        return "0.0hr";
      case BuiltinType::Fract:
      case BuiltinType::SatFract:
        return "0.0r";
      case BuiltinType::LongFract:
      case BuiltinType::SatLongFract:
        return "0.0lr";
      case BuiltinType::UShortFract:
      case BuiltinType::SatUShortFract:
        return "0.0uhr";
      case BuiltinType::UFract:
      case BuiltinType::SatUFract:
        return "0.0ur";
      case BuiltinType::ULongFract:
      case BuiltinType::SatULongFract:
        return "0.0ulr";
      default:
        llvm_unreachable("Unhandled fixed point BuiltinType");
    }
  }
  llvm_unreachable("Invalid scalar type kind");
}

static bool isZero(const Expr *E) {
  switch (E->getStmtClass()) {
  case Stmt::CXXNullPtrLiteralExprClass:
  case Stmt::ImplicitValueInitExprClass:
    return true;
  case Stmt::InitListExprClass:
    return cast<InitListExpr>(E)->getNumInits() == 0;
  case Stmt::CharacterLiteralClass:
    return !cast<CharacterLiteral>(E)->getValue();
  case Stmt::CXXBoolLiteralExprClass:
    return !cast<CXXBoolLiteralExpr>(E)->getValue();
  case Stmt::IntegerLiteralClass:
    return !cast<IntegerLiteral>(E)->getValue();
  case Stmt::FloatingLiteralClass: {
    llvm::APFloat Value = cast<FloatingLiteral>(E)->getValue();
    return Value.isZero() && !Value.isNegative();
  }
  default:
    return false;
  }
}

static const Expr *ignoreUnaryPlus(const Expr *E) {
  auto *UnaryOp = dyn_cast<UnaryOperator>(E);
  if (UnaryOp && UnaryOp->getOpcode() == UO_Plus)
    return UnaryOp->getSubExpr();
  return E;
}

static const Expr *getInitializer(const Expr *E) {
  auto *InitList = dyn_cast<InitListExpr>(E);
  if (InitList && InitList->getNumInits() == 1)
    return InitList->getInit(0);
  return E;
}

static bool sameValue(const Expr *E1, const Expr *E2) {
  E1 = ignoreUnaryPlus(getInitializer(E1->IgnoreParenImpCasts()));
  E2 = ignoreUnaryPlus(getInitializer(E2->IgnoreParenImpCasts()));

  if (isZero(E1) && isZero(E2))
    return true;

  if (E1->getStmtClass() != E2->getStmtClass())
    return false;

  switch (E1->getStmtClass()) {
  case Stmt::UnaryOperatorClass:
    return sameValue(cast<UnaryOperator>(E1)->getSubExpr(),
                     cast<UnaryOperator>(E2)->getSubExpr());
  case Stmt::CharacterLiteralClass:
    return cast<CharacterLiteral>(E1)->getValue() ==
           cast<CharacterLiteral>(E2)->getValue();
  case Stmt::CXXBoolLiteralExprClass:
    return cast<CXXBoolLiteralExpr>(E1)->getValue() ==
           cast<CXXBoolLiteralExpr>(E2)->getValue();
  case Stmt::IntegerLiteralClass:
    return cast<IntegerLiteral>(E1)->getValue() ==
           cast<IntegerLiteral>(E2)->getValue();
  case Stmt::FloatingLiteralClass:
    return cast<FloatingLiteral>(E1)->getValue().bitwiseIsEqual(
        cast<FloatingLiteral>(E2)->getValue());
  case Stmt::StringLiteralClass:
    return cast<StringLiteral>(E1)->getString() ==
           cast<StringLiteral>(E2)->getString();
  case Stmt::DeclRefExprClass:
    return cast<DeclRefExpr>(E1)->getDecl() == cast<DeclRefExpr>(E2)->getDecl();
  default:
    return false;
  }
}

UseDefaultMemberInitCheck::UseDefaultMemberInitCheck(StringRef Name,
                                                     ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      UseAssignment(Options.get("UseAssignment", 0) != 0),
      IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true) != 0) {}

void UseDefaultMemberInitCheck::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "UseAssignment", UseAssignment);
  Options.store(Opts, "IgnoreMacros", IgnoreMacros);
}

void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus11)
    return;

  auto Init =
      anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
            unaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("-")),
                          hasUnaryOperand(integerLiteral())),
            floatLiteral(),
            unaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("-")),
                          hasUnaryOperand(floatLiteral())),
            cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
            declRefExpr(to(enumConstantDecl())));

  Finder->addMatcher(
      cxxConstructorDecl(
          isDefaultConstructor(), unless(isInstantiated()),
          forEachConstructorInitializer(
              cxxCtorInitializer(
                  forField(unless(anyOf(getLangOpts().CPlusPlus2a
                                            ? unless(anything())
                                            : isBitField(),
                                        hasInClassInitializer(anything()),
                                        hasParent(recordDecl(isUnion()))))),
                  isWritten(), withInitializer(ignoringImplicit(Init)))
                  .bind("default"))),
      this);

  Finder->addMatcher(
      cxxConstructorDecl(
          unless(ast_matchers::isTemplateInstantiation()),
          forEachConstructorInitializer(
              cxxCtorInitializer(forField(hasInClassInitializer(anything())),
                                 isWritten(),
                                 withInitializer(ignoringImplicit(Init)))
                  .bind("existing"))),
      this);
}

void UseDefaultMemberInitCheck::check(const MatchFinder::MatchResult &Result) {
  if (const auto *Default =
          Result.Nodes.getNodeAs<CXXCtorInitializer>("default"))
    checkDefaultInit(Result, Default);
  else if (const auto *Existing =
               Result.Nodes.getNodeAs<CXXCtorInitializer>("existing"))
    checkExistingInit(Result, Existing);
  else
    llvm_unreachable("Bad Callback. No node provided.");
}

void UseDefaultMemberInitCheck::checkDefaultInit(
    const MatchFinder::MatchResult &Result, const CXXCtorInitializer *Init) {
  const FieldDecl *Field = Init->getAnyMember();

  SourceLocation StartLoc = Field->getBeginLoc();
  if (StartLoc.isMacroID() && IgnoreMacros)
    return;

  SourceLocation FieldEnd =
      Lexer::getLocForEndOfToken(Field->getSourceRange().getEnd(), 0,
                                 *Result.SourceManager, getLangOpts());
  SourceLocation LParenEnd = Lexer::getLocForEndOfToken(
      Init->getLParenLoc(), 0, *Result.SourceManager, getLangOpts());
  CharSourceRange InitRange =
      CharSourceRange::getCharRange(LParenEnd, Init->getRParenLoc());

  auto Diag =
      diag(Field->getLocation(), "use default member initializer for %0")
      << Field
      << FixItHint::CreateInsertion(FieldEnd, UseAssignment ? " = " : "{")
      << FixItHint::CreateInsertionFromRange(FieldEnd, InitRange);

  if (UseAssignment && isa<ImplicitValueInitExpr>(Init->getInit()))
    Diag << FixItHint::CreateInsertion(
        FieldEnd, getValueOfValueInit(Init->getInit()->getType()));

  if (!UseAssignment)
    Diag << FixItHint::CreateInsertion(FieldEnd, "}");

  Diag << FixItHint::CreateRemoval(Init->getSourceRange());
}

void UseDefaultMemberInitCheck::checkExistingInit(
    const MatchFinder::MatchResult &Result, const CXXCtorInitializer *Init) {
  const FieldDecl *Field = Init->getMember();

  if (!sameValue(Field->getInClassInitializer(), Init->getInit()))
    return;

  diag(Init->getSourceLocation(), "member initializer for %0 is redundant")
      << Field
      << FixItHint::CreateRemoval(Init->getSourceRange());
}

} // namespace modernize
} // namespace tidy
} // namespace clang
<commit_msg>[Fixed Point Arithmetic] Fix for clang-tools-extra warning<commit_after>//===--- UseDefaultMemberInitCheck.cpp - clang-tidy------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "UseDefaultMemberInitCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace modernize {

static StringRef getValueOfValueInit(const QualType InitType) {
  switch (InitType->getScalarTypeKind()) {
  case Type::STK_CPointer:
  case Type::STK_BlockPointer:
  case Type::STK_ObjCObjectPointer:
  case Type::STK_MemberPointer:
    return "nullptr";

  case Type::STK_Bool:
    return "false";

  case Type::STK_Integral:
    switch (InitType->getAs<BuiltinType>()->getKind()) {
    case BuiltinType::Char_U:
    case BuiltinType::UChar:
    case BuiltinType::Char_S:
    case BuiltinType::SChar:
      return "'\\0'";
    case BuiltinType::WChar_U:
    case BuiltinType::WChar_S:
      return "L'\\0'";
    case BuiltinType::Char16:
      return "u'\\0'";
    case BuiltinType::Char32:
      return "U'\\0'";
    default:
      return "0";
    }

  case Type::STK_Floating:
    switch (InitType->getAs<BuiltinType>()->getKind()) {
    case BuiltinType::Half:
    case BuiltinType::Float:
      return "0.0f";
    default:
      return "0.0";
    }

  case Type::STK_FloatingComplex:
  case Type::STK_IntegralComplex:
    return getValueOfValueInit(
        InitType->getAs<ComplexType>()->getElementType());

  case Type::STK_FixedPoint:
    switch (InitType->getAs<BuiltinType>()->getKind()) {
    case BuiltinType::ShortAccum:
    case BuiltinType::SatShortAccum:
      return "0.0hk";
    case BuiltinType::Accum:
    case BuiltinType::SatAccum:
      return "0.0k";
    case BuiltinType::LongAccum:
    case BuiltinType::SatLongAccum:
      return "0.0lk";
    case BuiltinType::UShortAccum:
    case BuiltinType::SatUShortAccum:
      return "0.0uhk";
    case BuiltinType::UAccum:
    case BuiltinType::SatUAccum:
      return "0.0uk";
    case BuiltinType::ULongAccum:
    case BuiltinType::SatULongAccum:
      return "0.0ulk";
    case BuiltinType::ShortFract:
    case BuiltinType::SatShortFract:
      return "0.0hr";
    case BuiltinType::Fract:
    case BuiltinType::SatFract:
      return "0.0r";
    case BuiltinType::LongFract:
    case BuiltinType::SatLongFract:
      return "0.0lr";
    case BuiltinType::UShortFract:
    case BuiltinType::SatUShortFract:
      return "0.0uhr";
    case BuiltinType::UFract:
    case BuiltinType::SatUFract:
      return "0.0ur";
    case BuiltinType::ULongFract:
    case BuiltinType::SatULongFract:
      return "0.0ulr";
    default:
      llvm_unreachable("Unhandled fixed point BuiltinType");
    }
  }
  llvm_unreachable("Invalid scalar type kind");
}

static bool isZero(const Expr *E) {
  switch (E->getStmtClass()) {
  case Stmt::CXXNullPtrLiteralExprClass:
  case Stmt::ImplicitValueInitExprClass:
    return true;
  case Stmt::InitListExprClass:
    return cast<InitListExpr>(E)->getNumInits() == 0;
  case Stmt::CharacterLiteralClass:
    return !cast<CharacterLiteral>(E)->getValue();
  case Stmt::CXXBoolLiteralExprClass:
    return !cast<CXXBoolLiteralExpr>(E)->getValue();
  case Stmt::IntegerLiteralClass:
    return !cast<IntegerLiteral>(E)->getValue();
  case Stmt::FloatingLiteralClass: {
    llvm::APFloat Value = cast<FloatingLiteral>(E)->getValue();
    return Value.isZero() && !Value.isNegative();
  }
  default:
    return false;
  }
}

static const Expr *ignoreUnaryPlus(const Expr *E) {
  auto *UnaryOp = dyn_cast<UnaryOperator>(E);
  if (UnaryOp && UnaryOp->getOpcode() == UO_Plus)
    return UnaryOp->getSubExpr();
  return E;
}

static const Expr *getInitializer(const Expr *E) {
  auto *InitList = dyn_cast<InitListExpr>(E);
  if (InitList && InitList->getNumInits() == 1)
    return InitList->getInit(0);
  return E;
}

static bool sameValue(const Expr *E1, const Expr *E2) {
  E1 = ignoreUnaryPlus(getInitializer(E1->IgnoreParenImpCasts()));
  E2 = ignoreUnaryPlus(getInitializer(E2->IgnoreParenImpCasts()));

  if (isZero(E1) && isZero(E2))
    return true;

  if (E1->getStmtClass() != E2->getStmtClass())
    return false;

  switch (E1->getStmtClass()) {
  case Stmt::UnaryOperatorClass:
    return sameValue(cast<UnaryOperator>(E1)->getSubExpr(),
                     cast<UnaryOperator>(E2)->getSubExpr());
  case Stmt::CharacterLiteralClass:
    return cast<CharacterLiteral>(E1)->getValue() ==
           cast<CharacterLiteral>(E2)->getValue();
  case Stmt::CXXBoolLiteralExprClass:
    return cast<CXXBoolLiteralExpr>(E1)->getValue() ==
           cast<CXXBoolLiteralExpr>(E2)->getValue();
  case Stmt::IntegerLiteralClass:
    return cast<IntegerLiteral>(E1)->getValue() ==
           cast<IntegerLiteral>(E2)->getValue();
  case Stmt::FloatingLiteralClass:
    return cast<FloatingLiteral>(E1)->getValue().bitwiseIsEqual(
        cast<FloatingLiteral>(E2)->getValue());
  case Stmt::StringLiteralClass:
    return cast<StringLiteral>(E1)->getString() ==
           cast<StringLiteral>(E2)->getString();
  case Stmt::DeclRefExprClass:
    return cast<DeclRefExpr>(E1)->getDecl() == cast<DeclRefExpr>(E2)->getDecl();
  default:
    return false;
  }
}

UseDefaultMemberInitCheck::UseDefaultMemberInitCheck(StringRef Name,
                                                     ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      UseAssignment(Options.get("UseAssignment", 0) != 0),
      IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true) != 0) {}

void UseDefaultMemberInitCheck::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "UseAssignment", UseAssignment);
  Options.store(Opts, "IgnoreMacros", IgnoreMacros);
}

void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus11)
    return;

  auto Init =
      anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
            unaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("-")),
                          hasUnaryOperand(integerLiteral())),
            floatLiteral(),
            unaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("-")),
                          hasUnaryOperand(floatLiteral())),
            cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
            declRefExpr(to(enumConstantDecl())));

  Finder->addMatcher(
      cxxConstructorDecl(
          isDefaultConstructor(), unless(isInstantiated()),
          forEachConstructorInitializer(
              cxxCtorInitializer(
                  forField(unless(anyOf(getLangOpts().CPlusPlus2a
                                            ? unless(anything())
                                            : isBitField(),
                                        hasInClassInitializer(anything()),
                                        hasParent(recordDecl(isUnion()))))),
                  isWritten(), withInitializer(ignoringImplicit(Init)))
                  .bind("default"))),
      this);

  Finder->addMatcher(
      cxxConstructorDecl(
          unless(ast_matchers::isTemplateInstantiation()),
          forEachConstructorInitializer(
              cxxCtorInitializer(forField(hasInClassInitializer(anything())),
                                 isWritten(),
                                 withInitializer(ignoringImplicit(Init)))
                  .bind("existing"))),
      this);
}

void UseDefaultMemberInitCheck::check(const MatchFinder::MatchResult &Result) {
  if (const auto *Default =
          Result.Nodes.getNodeAs<CXXCtorInitializer>("default"))
    checkDefaultInit(Result, Default);
  else if (const auto *Existing =
               Result.Nodes.getNodeAs<CXXCtorInitializer>("existing"))
    checkExistingInit(Result, Existing);
  else
    llvm_unreachable("Bad Callback. No node provided.");
}

void UseDefaultMemberInitCheck::checkDefaultInit(
    const MatchFinder::MatchResult &Result, const CXXCtorInitializer *Init) {
  const FieldDecl *Field = Init->getAnyMember();

  SourceLocation StartLoc = Field->getBeginLoc();
  if (StartLoc.isMacroID() && IgnoreMacros)
    return;

  SourceLocation FieldEnd =
      Lexer::getLocForEndOfToken(Field->getSourceRange().getEnd(), 0,
                                 *Result.SourceManager, getLangOpts());
  SourceLocation LParenEnd = Lexer::getLocForEndOfToken(
      Init->getLParenLoc(), 0, *Result.SourceManager, getLangOpts());
  CharSourceRange InitRange =
      CharSourceRange::getCharRange(LParenEnd, Init->getRParenLoc());

  auto Diag =
      diag(Field->getLocation(), "use default member initializer for %0")
      << Field
      << FixItHint::CreateInsertion(FieldEnd, UseAssignment ? " = " : "{")
      << FixItHint::CreateInsertionFromRange(FieldEnd, InitRange);

  if (UseAssignment && isa<ImplicitValueInitExpr>(Init->getInit()))
    Diag << FixItHint::CreateInsertion(
        FieldEnd, getValueOfValueInit(Init->getInit()->getType()));

  if (!UseAssignment)
    Diag << FixItHint::CreateInsertion(FieldEnd, "}");

  Diag << FixItHint::CreateRemoval(Init->getSourceRange());
}

void UseDefaultMemberInitCheck::checkExistingInit(
    const MatchFinder::MatchResult &Result, const CXXCtorInitializer *Init) {
  const FieldDecl *Field = Init->getMember();

  if (!sameValue(Field->getInClassInitializer(), Init->getInit()))
    return;

  diag(Init->getSourceLocation(), "member initializer for %0 is redundant")
      << Field
      << FixItHint::CreateRemoval(Init->getSourceRange());
}

} // namespace modernize
} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>#ifndef GENERIC_CIFY_HPP
# define GENERIC_CIFY_HPP
# pragma once

#include <utility>

namespace generic
{

namespace
{

template <typename R, typename ...A> using return_type = R (*)(A...);

}

template <typename F, typename R, typename ...A>
return_type<R, A...> cify(R (*)(A...), F&& f)
{
  static F const f_(::std::forward<F>(f));

  struct S
  {
    static R f(A... args)
    {
      f_(::std::forward<A>(args)...);
    }
  };

  return &S::f;
}

}

#endif // GENERIC_CIFY_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_CIFY_HPP
# define GENERIC_CIFY_HPP
# pragma once

#include <utility>

namespace generic
{

namespace
{

template <typename R, typename ...A> using return_type = R (*)(A...);

}

template <typename F, int I = 0, typename R, typename ...A>
return_type<R, A...> cify(R (*)(A...), F&& f)
{
  static F const f_(::std::forward<F>(f));

  struct S
  {
    static R f(A... args)
    {
      f_(::std::forward<A>(args)...);
    }
  };

  return &S::f;
}

}

#endif // GENERIC_CIFY_HPP
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "database/src/desktop/core/operation.h"

#include <iostream>

#include "app/src/assert.h"
#include "app/src/path.h"
#include "database/src/desktop/util_desktop.h"

namespace firebase {
namespace database {
namespace internal {

const OperationSource OperationSource::kUser(OperationSource::kSourceUser,
                                             Optional<QueryParams>());
const OperationSource OperationSource::kServer(OperationSource::kSourceServer,
                                               Optional<QueryParams>());

Operation Operation::Overwrite(const OperationSource& source, const Path& path,
                               const Variant& snapshot) {
  return Operation(Operation::kTypeOverwrite, source, path, snapshot,
                   CompoundWrite(), Tree<bool>(), kAckConfirm);
}

Operation Operation::Merge(const OperationSource& source, const Path& path,
                           const CompoundWrite& children) {
  return Operation(Operation::kTypeMerge, source, path, Variant(), children,
                   Tree<bool>(), kAckConfirm);
}

Operation Operation::AckUserWrite(const Path& path,
                                  const Tree<bool>& affected_tree,
                                  AckStatus status) {
  return Operation(Operation::kTypeAckUserWrite, OperationSource::kUser, path,
                   Variant(), CompoundWrite(), affected_tree, status);
}

Operation Operation::ListenComplete(const OperationSource& source,
                                    const Path& path) {
  FIREBASE_DEV_ASSERT_MESSAGE(
      source.source != OperationSource::kSourceUser,
      "Can't have a listen complete from a user source");
  return Operation(Operation::kTypeListenComplete, source, path, Variant(),
                   CompoundWrite(), Tree<bool>(), kAckConfirm);
}

static Optional<Operation> OperationForChildOverwrite(
    const Operation& op, const std::string& child_key) {
  if (op.path.empty()) {
    return Optional<Operation>(Operation::Overwrite(
        op.source, Path(), VariantGetChild(&op.snapshot, child_key)));
  } else {
    std::vector<std::string> directories = op.path.GetDirectories();
    Path child_path(std::next(directories.begin()), directories.end());
    return Optional<Operation>(
        Operation::Overwrite(op.source, child_path, op.snapshot));
  }
}

static Optional<Operation> OperationForChildMerge(
    const Operation& op, const std::string& child_key) {
  if (op.path.empty()) {
    CompoundWrite child_tree = op.children.ChildCompoundWrite(Path(child_key));
    if (child_tree.IsEmpty()) {
      // This child is unaffected.
      return Optional<Operation>();
    } else if (child_tree.GetRootWrite().has_value()) {
      return Optional<Operation>(
          Operation::Overwrite(op.source, Path(), *child_tree.GetRootWrite()));
    } else {
      return Optional<Operation>(
          Operation::Merge(op.source, Path(), child_tree));
    }
  } else {
    std::vector<std::string> directories = op.path.GetDirectories();
    if (directories.front() == child_key) {
      auto start = directories.begin();
      auto finish = directories.end();
      return Optional<Operation>(Operation::Merge(
          op.source, Path(std::next(start), finish), op.children));
    } else {
      // Merge doesn't affect operation path.
      return Optional<Operation>();
    }
  }
}

static Optional<Operation> OperationForChildAckUserWrite(
    const Operation& op, const std::string& child_key) {
  if (!op.path.empty()) {
    FIREBASE_DEV_ASSERT_MESSAGE(
        op.path.GetDirectories().front() == child_key,
        "OperationForChild called for unrelated child.");
    std::vector<std::string> directories = op.path.GetDirectories();
    auto start = directories.begin();
    auto finish = directories.end();
    return Optional<Operation>(Operation::AckUserWrite(
        Path(std::next(start), finish), op.affected_tree,
        op.revert ? kAckRevert : kAckConfirm));
  } else if (op.affected_tree.value().has_value()) {
    FIREBASE_DEV_ASSERT_MESSAGE(
        op.affected_tree.children().empty(),
        "AffectedTree should not have overlapping affected paths.");
    // All child locations are affected as well; just return same operation.
    return Optional<Operation>(op);
  } else {
    const Tree<bool>* child_tree = op.affected_tree.GetChild(child_key);
    return Optional<Operation>(Operation::AckUserWrite(
        Path(), *child_tree, op.revert ? kAckRevert : kAckConfirm));
  }
}

static Optional<Operation> OperationForChildListenComplete(
    const Operation& op, const std::string& child_key) {
  if (op.path.empty()) {
    return Optional<Operation>(Operation::ListenComplete(op.source, Path()));
  } else {
    std::vector<std::string> directories = op.path.GetDirectories();
    auto start = directories.begin();
    auto finish = directories.end();
    return Optional<Operation>(
        Operation::ListenComplete(op.source, Path(std::next(start), finish)));
  }
}

Optional<Operation> OperationForChild(const Operation& op,
                                      const std::string& child_key) {
  switch (op.type) {
    case Operation::kTypeOverwrite: {
      return OperationForChildOverwrite(op, child_key);
    }
    case Operation::kTypeMerge: {
      return OperationForChildMerge(op, child_key);
    }
    case Operation::kTypeAckUserWrite: {
      return OperationForChildAckUserWrite(op, child_key);
    }
    case Operation::kTypeListenComplete: {
      return OperationForChildListenComplete(op, child_key);
    }
  }
}

}  // namespace internal
}  // namespace database
}  // namespace firebase
<commit_msg>Fixed a potential null deref and added a unit test to catch that edge case.<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "database/src/desktop/core/operation.h"

#include <iostream>

#include "app/src/assert.h"
#include "app/src/path.h"
#include "database/src/desktop/util_desktop.h"

namespace firebase {
namespace database {
namespace internal {

const OperationSource OperationSource::kUser(OperationSource::kSourceUser,
                                             Optional<QueryParams>());
const OperationSource OperationSource::kServer(OperationSource::kSourceServer,
                                               Optional<QueryParams>());

Operation Operation::Overwrite(const OperationSource& source, const Path& path,
                               const Variant& snapshot) {
  return Operation(Operation::kTypeOverwrite, source, path, snapshot,
                   CompoundWrite(), Tree<bool>(), kAckConfirm);
}

Operation Operation::Merge(const OperationSource& source, const Path& path,
                           const CompoundWrite& children) {
  return Operation(Operation::kTypeMerge, source, path, Variant(), children,
                   Tree<bool>(), kAckConfirm);
}

Operation Operation::AckUserWrite(const Path& path,
                                  const Tree<bool>& affected_tree,
                                  AckStatus status) {
  return Operation(Operation::kTypeAckUserWrite, OperationSource::kUser, path,
                   Variant(), CompoundWrite(), affected_tree, status);
}

Operation Operation::ListenComplete(const OperationSource& source,
                                    const Path& path) {
  FIREBASE_DEV_ASSERT_MESSAGE(
      source.source != OperationSource::kSourceUser,
      "Can't have a listen complete from a user source");
  return Operation(Operation::kTypeListenComplete, source, path, Variant(),
                   CompoundWrite(), Tree<bool>(), kAckConfirm);
}

static Optional<Operation> OperationForChildOverwrite(
    const Operation& op, const std::string& child_key) {
  if (op.path.empty()) {
    return Optional<Operation>(Operation::Overwrite(
        op.source, Path(), VariantGetChild(&op.snapshot, child_key)));
  } else {
    std::vector<std::string> directories = op.path.GetDirectories();
    Path child_path(std::next(directories.begin()), directories.end());
    return Optional<Operation>(
        Operation::Overwrite(op.source, child_path, op.snapshot));
  }
}

static Optional<Operation> OperationForChildMerge(
    const Operation& op, const std::string& child_key) {
  if (op.path.empty()) {
    CompoundWrite child_tree = op.children.ChildCompoundWrite(Path(child_key));
    if (child_tree.IsEmpty()) {
      // This child is unaffected.
      return Optional<Operation>();
    } else if (child_tree.GetRootWrite().has_value()) {
      return Optional<Operation>(
          Operation::Overwrite(op.source, Path(), *child_tree.GetRootWrite()));
    } else {
      return Optional<Operation>(
          Operation::Merge(op.source, Path(), child_tree));
    }
  } else {
    std::vector<std::string> directories = op.path.GetDirectories();
    if (directories.front() == child_key) {
      auto start = directories.begin();
      auto finish = directories.end();
      return Optional<Operation>(Operation::Merge(
          op.source, Path(std::next(start), finish), op.children));
    } else {
      // Merge doesn't affect operation path.
      return Optional<Operation>();
    }
  }
}

static Optional<Operation> OperationForChildAckUserWrite(
    const Operation& op, const std::string& child_key) {
  if (!op.path.empty()) {
    FIREBASE_DEV_ASSERT_MESSAGE(
        op.path.GetDirectories().front() == child_key,
        "OperationForChild called for unrelated child.");
    std::vector<std::string> directories = op.path.GetDirectories();
    auto start = directories.begin();
    auto finish = directories.end();
    return Optional<Operation>(Operation::AckUserWrite(
        Path(std::next(start), finish), op.affected_tree,
        op.revert ? kAckRevert : kAckConfirm));
  } else if (op.affected_tree.value().has_value()) {
    FIREBASE_DEV_ASSERT_MESSAGE(
        op.affected_tree.children().empty(),
        "AffectedTree should not have overlapping affected paths.");
    // All child locations are affected as well; just return same operation.
    return Optional<Operation>(op);
  } else {
    const Tree<bool>* child_tree = op.affected_tree.GetChild(child_key);
    return Optional<Operation>(
        Operation::AckUserWrite(Path(), child_tree ? *child_tree : Tree<bool>(),
                                op.revert ? kAckRevert : kAckConfirm));
  }
}

static Optional<Operation> OperationForChildListenComplete(
    const Operation& op, const std::string& child_key) {
  if (op.path.empty()) {
    return Optional<Operation>(Operation::ListenComplete(op.source, Path()));
  } else {
    std::vector<std::string> directories = op.path.GetDirectories();
    auto start = directories.begin();
    auto finish = directories.end();
    return Optional<Operation>(
        Operation::ListenComplete(op.source, Path(std::next(start), finish)));
  }
}

Optional<Operation> OperationForChild(const Operation& op,
                                      const std::string& child_key) {
  switch (op.type) {
    case Operation::kTypeOverwrite: {
      return OperationForChildOverwrite(op, child_key);
    }
    case Operation::kTypeMerge: {
      return OperationForChildMerge(op, child_key);
    }
    case Operation::kTypeAckUserWrite: {
      return OperationForChildAckUserWrite(op, child_key);
    }
    case Operation::kTypeListenComplete: {
      return OperationForChildListenComplete(op, child_key);
    }
  }
}

}  // namespace internal
}  // namespace database
}  // namespace firebase
<|endoftext|>