<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/torrent_info.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

    std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i)
    {
        return i.trackers().begin();
    }

    std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i)
    {
        return i.trackers().end();
    }

    void add_node(torrent_info& ti, char const* hostname, int port)
    {
        ti.add_node(std::make_pair(hostname, port));
    }

    list nodes(torrent_info const& ti)
    {
        list result;

        typedef std::vector<std::pair<std::string, int> > list_type;

        for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i)
        {
            result.append(make_tuple(i->first, i->second));
        }

        return result;
    }

    file_storage::iterator begin_files(torrent_info& i)
    {
        return i.begin_files();
    }

    file_storage::iterator end_files(torrent_info& i)
    {
        return i.end_files();
    }

    //list files(torrent_info const& ti, bool storage) {
    list files(torrent_info const& ti, bool storage) {
        list result;

        typedef torrent_info::file_iterator iter;

        for (iter i = ti.begin_files(); i != ti.end_files(); ++i)
            result.append(ti.files().at(i));

        return result;
    }

    std::string metadata(torrent_info const& ti) {
        std::string result(ti.metadata().get(), ti.metadata_size());
        return result;
    }

    torrent_info construct0(std::string path) {
        return torrent_info(path);
    }

    list map_block(torrent_info& ti, int piece, size_type offset, int size)
    {
       std::vector<file_slice> p = ti.map_block(piece, offset, size);
       list result;

       for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i)
          result.append(*i);

       return result;
    }

    bool get_tier(announce_entry const& ae) { return ae.tier; }
    void set_tier(announce_entry& ae, bool v) { ae.tier = v; }
    bool get_fail_limit(announce_entry const& ae) { return ae.fail_limit; }
    void set_fail_limit(announce_entry& ae, int l) { ae.fail_limit = l; }
    bool get_fails(announce_entry const& ae) { return ae.fails; }
    bool get_source(announce_entry const& ae) { return ae.source; }
    bool get_verified(announce_entry const& ae) { return ae.verified; }
    bool get_updating(announce_entry const& ae) { return ae.updating; }
    bool get_start_sent(announce_entry const& ae) { return ae.start_sent; }
    bool get_complete_sent(announce_entry const& ae) { return ae.complete_sent; }
    bool get_send_stats(announce_entry const& ae) { return ae.send_stats; }

    size_type get_size(file_entry const& fe) { return fe.size; }
    size_type get_offset(file_entry const& fe) { return fe.offset; }
    bool get_pad_file(file_entry const& fe) { return fe.pad_file; }
    bool get_executable_attribute(file_entry const& fe) { return fe.executable_attribute; }
    bool get_hidden_attribute(file_entry const& fe) { return fe.hidden_attribute; }
    bool get_symlink_attribute(file_entry const& fe) { return fe.symlink_attribute; }

} // namespace unnamed

void bind_torrent_info()
{
    return_value_policy<copy_const_reference> copy;

    void (torrent_info::*rename_file0)(int, std::string const&) = &torrent_info::rename_file;
#if TORRENT_USE_WSTRING
    void (torrent_info::*rename_file1)(int, std::wstring const&) = &torrent_info::rename_file;
#endif

    class_<file_slice>("file_slice")
        .def_readwrite("file_index", &file_slice::file_index)
        .def_readwrite("offset", &file_slice::offset)
        .def_readwrite("size", &file_slice::size)
        ;

    class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init)
#ifndef TORRENT_NO_DEPRECATE
        .def(init<entry const&>(arg("e")))
#endif
        .def(init<sha1_hash const&, int>((arg("info_hash"), arg("flags") = 0)))
        .def(init<char const*, int, int>((arg("buffer"), arg("length"), arg("flags") = 0)))
        .def(init<std::string, int>((arg("file"), arg("flags") = 0)))
        .def(init<torrent_info const&, int>((arg("ti"), arg("flags") = 0)))
#if TORRENT_USE_WSTRING
        .def(init<std::wstring, int>((arg("file"), arg("flags") = 0)))
#endif

        .def("add_tracker", &torrent_info::add_tracker, arg("url"))
        .def("add_url_seed", &torrent_info::add_url_seed)

        .def("name", &torrent_info::name, copy)
        .def("comment", &torrent_info::comment, copy)
        .def("creator", &torrent_info::creator, copy)
        .def("total_size", &torrent_info::total_size)
        .def("piece_length", &torrent_info::piece_length)
        .def("num_pieces", &torrent_info::num_pieces)
#ifndef TORRENT_NO_DEPRECATE
        .def("info_hash", &torrent_info::info_hash, copy)
#endif
        .def("hash_for_piece", &torrent_info::hash_for_piece)
        .def("piece_size", &torrent_info::piece_size)

        .def("num_files", &torrent_info::num_files, (arg("storage")=false))
        .def("file_at", &torrent_info::file_at)
        .def("file_at_offset", &torrent_info::file_at_offset)
        .def("files", &files, (arg("storage")=false))
        .def("rename_file", rename_file0)
#if TORRENT_USE_WSTRING
        .def("rename_file", rename_file1)
#endif

        .def("priv", &torrent_info::priv)
        .def("trackers", range(begin_trackers, end_trackers))

        .def("creation_date", &torrent_info::creation_date)

        .def("add_node", &add_node)
        .def("nodes", &nodes)
        .def("metadata", &metadata)
        .def("metadata_size", &torrent_info::metadata_size)
        .def("map_block", map_block)
        .def("map_file", &torrent_info::map_file)
        ;

    class_<file_entry>("file_entry")
        .def_readwrite("path", &file_entry::path)
        .def_readwrite("symlink_path", &file_entry::symlink_path)
        .def_readwrite("filehash", &file_entry::filehash)
        .def_readwrite("mtime", &file_entry::mtime)
        .add_property("pad_file", &get_pad_file)
        .add_property("executable_attribute", &get_executable_attribute)
        .add_property("hidden_attribute", &get_hidden_attribute)
        .add_property("symlink_attribute", &get_symlink_attribute)
        .add_property("offset", &get_offset)
        .add_property("size", &get_size)
        ;

    class_<announce_entry>("announce_entry", init<std::string const&>())
        .def_readwrite("url", &announce_entry::url)
        .add_property("tier", &get_tier, &set_tier)
        .add_property("fail_limit", &get_fail_limit, &set_fail_limit)
        .add_property("fails", &get_fails)
        .add_property("source", &get_source)
        .add_property("verified", &get_verified)
        .add_property("updating", &get_updating)
        .add_property("start_sent", &get_start_sent)
        .add_property("complete_sent", &get_complete_sent)
        .add_property("send_stats", &get_send_stats)

        .def("reset", &announce_entry::reset)
        .def("failed", &announce_entry::failed, arg("retry_interval") = 0)
        .def("can_announce", &announce_entry::can_announce)
        .def("is_working", &announce_entry::is_working)
        .def("trim", &announce_entry::trim)
        ;

    enum_<announce_entry::tracker_source>("tracker_source")
        .value("source_torrent", announce_entry::source_torrent)
        .value("source_client", announce_entry::source_client)
        .value("source_magnet_link", announce_entry::source_magnet_link)
        .value("source_tex", announce_entry::source_tex)
    ;
}

<commit_msg>fix python bindings for hash_for_piece<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/torrent_info.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

    std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i)
    {
        return i.trackers().begin();
    }

    std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i)
    {
        return i.trackers().end();
    }

    void add_node(torrent_info& ti, char const* hostname, int port)
    {
        ti.add_node(std::make_pair(hostname, port));
    }

    list nodes(torrent_info const& ti)
    {
        list result;

        typedef std::vector<std::pair<std::string, int> > list_type;

        for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i)
        {
            result.append(make_tuple(i->first, i->second));
        }

        return result;
    }

    file_storage::iterator begin_files(torrent_info& i)
    {
        return i.begin_files();
    }

    file_storage::iterator end_files(torrent_info& i)
    {
        return i.end_files();
    }

    //list files(torrent_info const& ti, bool storage) {
    list files(torrent_info const& ti, bool storage) {
        list result;

        typedef torrent_info::file_iterator iter;

        for (iter i = ti.begin_files(); i != ti.end_files(); ++i)
            result.append(ti.files().at(i));

        return result;
    }

    std::string hash_for_piece(torrent_info const& ti, int i)
    {
        return ti.hash_for_piece(i).to_string();
    }

    std::string metadata(torrent_info const& ti) {
        std::string result(ti.metadata().get(), ti.metadata_size());
        return result;
    }

    torrent_info construct0(std::string path) {
        return torrent_info(path);
    }

    list map_block(torrent_info& ti, int piece, size_type offset, int size)
    {
       std::vector<file_slice> p = ti.map_block(piece, offset, size);
       list result;

       for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i)
          result.append(*i);

       return result;
    }

    bool get_tier(announce_entry const& ae) { return ae.tier; }
    void set_tier(announce_entry& ae, bool v) { ae.tier = v; }
    bool get_fail_limit(announce_entry const& ae) { return ae.fail_limit; }
    void set_fail_limit(announce_entry& ae, int l) { ae.fail_limit = l; }
    bool get_fails(announce_entry const& ae) { return ae.fails; }
    bool get_source(announce_entry const& ae) { return ae.source; }
    bool get_verified(announce_entry const& ae) { return ae.verified; }
    bool get_updating(announce_entry const& ae) { return ae.updating; }
    bool get_start_sent(announce_entry const& ae) { return ae.start_sent; }
    bool get_complete_sent(announce_entry const& ae) { return ae.complete_sent; }
    bool get_send_stats(announce_entry const& ae) { return ae.send_stats; }

    size_type get_size(file_entry const& fe) { return fe.size; }
    size_type get_offset(file_entry const& fe) { return fe.offset; }
    bool get_pad_file(file_entry const& fe) { return fe.pad_file; }
    bool get_executable_attribute(file_entry const& fe) { return fe.executable_attribute; }
    bool get_hidden_attribute(file_entry const& fe) { return fe.hidden_attribute; }
    bool get_symlink_attribute(file_entry const& fe) { return fe.symlink_attribute; }

} // namespace unnamed

void bind_torrent_info()
{
    return_value_policy<copy_const_reference> copy;

    void (torrent_info::*rename_file0)(int, std::string const&) = &torrent_info::rename_file;
#if TORRENT_USE_WSTRING
    void (torrent_info::*rename_file1)(int, std::wstring const&) = &torrent_info::rename_file;
#endif

    class_<file_slice>("file_slice")
        .def_readwrite("file_index", &file_slice::file_index)
        .def_readwrite("offset", &file_slice::offset)
        .def_readwrite("size", &file_slice::size)
        ;

    class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init)
#ifndef TORRENT_NO_DEPRECATE
        .def(init<entry const&>(arg("e")))
#endif
        .def(init<sha1_hash const&, int>((arg("info_hash"), arg("flags") = 0)))
        .def(init<char const*, int, int>((arg("buffer"), arg("length"), arg("flags") = 0)))
        .def(init<std::string, int>((arg("file"), arg("flags") = 0)))
        .def(init<torrent_info const&, int>((arg("ti"), arg("flags") = 0)))
#if TORRENT_USE_WSTRING
        .def(init<std::wstring, int>((arg("file"), arg("flags") = 0)))
#endif

        .def("add_tracker", &torrent_info::add_tracker, arg("url"))
        .def("add_url_seed", &torrent_info::add_url_seed)

        .def("name", &torrent_info::name, copy)
        .def("comment", &torrent_info::comment, copy)
        .def("creator", &torrent_info::creator, copy)
        .def("total_size", &torrent_info::total_size)
        .def("piece_length", &torrent_info::piece_length)
        .def("num_pieces", &torrent_info::num_pieces)
#ifndef TORRENT_NO_DEPRECATE
        .def("info_hash", &torrent_info::info_hash, copy)
#endif
        .def("hash_for_piece", &hash_for_piece)
        .def("piece_size", &torrent_info::piece_size)

        .def("num_files", &torrent_info::num_files, (arg("storage")=false))
        .def("file_at", &torrent_info::file_at)
        .def("file_at_offset", &torrent_info::file_at_offset)
        .def("files", &files, (arg("storage")=false))
        .def("rename_file", rename_file0)
#if TORRENT_USE_WSTRING
        .def("rename_file", rename_file1)
#endif

        .def("priv", &torrent_info::priv)
        .def("trackers", range(begin_trackers, end_trackers))

        .def("creation_date", &torrent_info::creation_date)

        .def("add_node", &add_node)
        .def("nodes", &nodes)
        .def("metadata", &metadata)
        .def("metadata_size", &torrent_info::metadata_size)
        .def("map_block", map_block)
        .def("map_file", &torrent_info::map_file)
        ;

    class_<file_entry>("file_entry")
        .def_readwrite("path", &file_entry::path)
        .def_readwrite("symlink_path", &file_entry::symlink_path)
        .def_readwrite("filehash", &file_entry::filehash)
        .def_readwrite("mtime", &file_entry::mtime)
        .add_property("pad_file", &get_pad_file)
        .add_property("executable_attribute", &get_executable_attribute)
        .add_property("hidden_attribute", &get_hidden_attribute)
        .add_property("symlink_attribute", &get_symlink_attribute)
        .add_property("offset", &get_offset)
        .add_property("size", &get_size)
        ;

    class_<announce_entry>("announce_entry", init<std::string const&>())
        .def_readwrite("url", &announce_entry::url)
        .add_property("tier", &get_tier, &set_tier)
        .add_property("fail_limit", &get_fail_limit, &set_fail_limit)
        .add_property("fails", &get_fails)
        .add_property("source", &get_source)
        .add_property("verified", &get_verified)
        .add_property("updating", &get_updating)
        .add_property("start_sent", &get_start_sent)
        .add_property("complete_sent", &get_complete_sent)
        .add_property("send_stats", &get_send_stats)

        .def("reset", &announce_entry::reset)
        .def("failed", &announce_entry::failed, arg("retry_interval") = 0)
        .def("can_announce", &announce_entry::can_announce)
        .def("is_working", &announce_entry::is_working)
        .def("trim", &announce_entry::trim)
        ;

    enum_<announce_entry::tracker_source>("tracker_source")
        .value("source_torrent", announce_entry::source_torrent)
        .value("source_client", announce_entry::source_client)
        .value("source_magnet_link", announce_entry::source_magnet_link)
        .value("source_tex", announce_entry::source_tex)
    ;
}

<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/exception.h>
#include <vespa/vespalib/util/slaveproc.h>

using namespace vespalib;

TEST("that uncaught exception causes negative exitcode.") {
    SlaveProc proc("exec ./vespalib_caught_uncaught_app uncaught");
    proc.wait();
    EXPECT_LESS(proc.getExitCode(), 0);
}

TEST("that uncaught silenced exception causes exitcode 66") {
    SlaveProc proc("exec ./vespalib_caught_uncaught_app silenced_and_uncaught");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 66);
}

TEST("that caught silenced exception followed by an uncaught causes negative exitcode.") {
    SlaveProc proc("exec ./vespalib_caught_uncaught_app uncaught_after_silenced_and_caught");
    proc.wait();
    EXPECT_LESS(proc.getExitCode(), 0);
}

TEST("that caught silenced exception causes exitcode 0") {
    SlaveProc proc("exec ./vespalib_caught_uncaught_app silenced_and_caught");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 0);
}

TEST("that mmap within limits are fine cause exitcode 0") {
    SlaveProc proc("exec ./vespalib_mmap_app 100000000 10485760 1");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 0);
}

TEST("that mmap beyond limits cause negative exitcode.") {
    SlaveProc proc("exec ./vespalib_mmap_app 100000000 10485760 10");
    proc.wait();
    EXPECT_LESS(proc.getExitCode(), 0);
}

TEST("that mmap beyond limits with set VESPA_SILENCE_CORE_ON_OOM cause exitcode 66.") {
    SlaveProc proc("VESPA_SILENCE_CORE_ON_OOM=1 exec ./vespalib_mmap_app 100000000 10485760 10");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 66);
}

TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); }
<commit_msg>Add 'ulimit -c 0 && ' in front of crashing exec-s<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/exception.h>
#include <vespa/vespalib/util/slaveproc.h>

using namespace vespalib;

TEST("that uncaught exception causes negative exitcode.") {
    SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app uncaught");
    proc.wait();
    EXPECT_LESS(proc.getExitCode(), 0);
}

TEST("that uncaught silenced exception causes exitcode 66") {
    SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app silenced_and_uncaught");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 66);
}

TEST("that caught silenced exception followed by an uncaught causes negative exitcode.") {
    SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app uncaught_after_silenced_and_caught");
    proc.wait();
    EXPECT_LESS(proc.getExitCode(), 0);
}

TEST("that caught silenced exception causes exitcode 0") {
    SlaveProc proc("ulimit -c 0 && exec ./vespalib_caught_uncaught_app silenced_and_caught");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 0);
}

TEST("that mmap within limits are fine cause exitcode 0") {
    SlaveProc proc("ulimit -c 0 && exec ./vespalib_mmap_app 100000000 10485760 1");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 0);
}

TEST("that mmap beyond limits cause negative exitcode.") {
    SlaveProc proc("ulimit -c 0 && exec ./vespalib_mmap_app 100000000 10485760 10");
    proc.wait();
    EXPECT_LESS(proc.getExitCode(), 0);
}

TEST("that mmap beyond limits with set VESPA_SILENCE_CORE_ON_OOM cause exitcode 66.") {
    SlaveProc proc("ulimit -c 0 && VESPA_SILENCE_CORE_ON_OOM=1 exec ./vespalib_mmap_app 100000000 10485760 10");
    proc.wait();
    EXPECT_EQUAL(proc.getExitCode(), 66);
}

TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/win/screen_capturer_win_gdi.h"

#include <assert.h>

#include <utility>

#include "webrtc/base/checks.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/desktop_frame_win.h"
#include "webrtc/modules/desktop_capture/desktop_region.h"
#include "webrtc/modules/desktop_capture/mouse_cursor.h"
#include "webrtc/modules/desktop_capture/win/cursor.h"
#include "webrtc/modules/desktop_capture/win/desktop.h"
#include "webrtc/modules/desktop_capture/win/screen_capture_utils.h"
#include "webrtc/system_wrappers/include/logging.h"

namespace webrtc {

namespace {

// Constants from dwmapi.h.
const UINT DWM_EC_DISABLECOMPOSITION = 0;
const UINT DWM_EC_ENABLECOMPOSITION = 1;

const wchar_t kDwmapiLibraryName[] = L"dwmapi.dll";

}  // namespace

ScreenCapturerWinGdi::ScreenCapturerWinGdi(
    const DesktopCaptureOptions& options) {
  if (options.disable_effects()) {
    // Load dwmapi.dll dynamically since it is not available on XP.
    if (!dwmapi_library_)
      dwmapi_library_ = LoadLibrary(kDwmapiLibraryName);

    if (dwmapi_library_) {
      composition_func_ = reinterpret_cast<DwmEnableCompositionFunc>(
          GetProcAddress(dwmapi_library_, "DwmEnableComposition"));
    }
  }
}

ScreenCapturerWinGdi::~ScreenCapturerWinGdi() {
  if (desktop_dc_)
    ReleaseDC(NULL, desktop_dc_);
  if (memory_dc_)
    DeleteDC(memory_dc_);

  // Restore Aero.
  if (composition_func_)
    (*composition_func_)(DWM_EC_ENABLECOMPOSITION);

  if (dwmapi_library_)
    FreeLibrary(dwmapi_library_);
}

void ScreenCapturerWinGdi::SetSharedMemoryFactory(
    std::unique_ptr<SharedMemoryFactory> shared_memory_factory) {
  shared_memory_factory_ = std::move(shared_memory_factory);
}

void ScreenCapturerWinGdi::CaptureFrame() {
  int64_t capture_start_time_nanos = rtc::TimeNanos();

  queue_.MoveToNextFrame();
  RTC_DCHECK(!queue_.current_frame() || !queue_.current_frame()->IsShared());

  // Make sure the GDI capture resources are up-to-date.
  PrepareCaptureResources();

  if (!CaptureImage()) {
    callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr);
    return;
  }

  // Emit the current frame.
  std::unique_ptr<DesktopFrame> frame = queue_.current_frame()->Share();
  frame->set_dpi(DesktopVector(
      GetDeviceCaps(desktop_dc_, LOGPIXELSX),
      GetDeviceCaps(desktop_dc_, LOGPIXELSY)));
  frame->mutable_updated_region()->SetRect(
      DesktopRect::MakeSize(frame->size()));
  frame->set_capture_time_ms(
      (rtc::TimeNanos() - capture_start_time_nanos) /
      rtc::kNumNanosecsPerMillisec);
  callback_->OnCaptureResult(Result::SUCCESS, std::move(frame));
}

bool ScreenCapturerWinGdi::GetSourceList(SourceList* sources) {
  return webrtc::GetScreenList(sources);
}

bool ScreenCapturerWinGdi::SelectSource(SourceId id) {
  bool valid = IsScreenValid(id, &current_device_key_);
  if (valid)
    current_screen_id_ = id;
  return valid;
}

void ScreenCapturerWinGdi::Start(Callback* callback) {
  assert(!callback_);
  assert(callback);

  callback_ = callback;

  // Vote to disable Aero composited desktop effects while capturing. Windows
  // will restore Aero automatically if the process exits. This has no effect
  // under Windows 8 or higher.  See crbug.com/124018.
  if (composition_func_)
    (*composition_func_)(DWM_EC_DISABLECOMPOSITION);
}

void ScreenCapturerWinGdi::PrepareCaptureResources() {
  // Switch to the desktop receiving user input if different from the current
  // one.
  std::unique_ptr<Desktop> input_desktop(Desktop::GetInputDesktop());
  if (input_desktop && !desktop_.IsSame(*input_desktop)) {
    // Release GDI resources otherwise SetThreadDesktop will fail.
    if (desktop_dc_) {
      ReleaseDC(NULL, desktop_dc_);
      desktop_dc_ = nullptr;
    }

    if (memory_dc_) {
      DeleteDC(memory_dc_);
      memory_dc_ = nullptr;
    }

    // If SetThreadDesktop() fails, the thread is still assigned a desktop.
    // So we can continue capture screen bits, just from the wrong desktop.
    desktop_.SetThreadDesktop(input_desktop.release());

    // Re-assert our vote to disable Aero.
    // See crbug.com/124018 and crbug.com/129906.
    if (composition_func_) {
      (*composition_func_)(DWM_EC_DISABLECOMPOSITION);
    }
  }

  // If the display bounds have changed then recreate GDI resources.
  // TODO(wez): Also check for pixel format changes.
  DesktopRect screen_rect(DesktopRect::MakeXYWH(
      GetSystemMetrics(SM_XVIRTUALSCREEN),
      GetSystemMetrics(SM_YVIRTUALSCREEN),
      GetSystemMetrics(SM_CXVIRTUALSCREEN),
      GetSystemMetrics(SM_CYVIRTUALSCREEN)));
  if (!screen_rect.equals(desktop_dc_rect_)) {
    if (desktop_dc_) {
      ReleaseDC(NULL, desktop_dc_);
      desktop_dc_ = nullptr;
    }
    if (memory_dc_) {
      DeleteDC(memory_dc_);
      memory_dc_ = nullptr;
    }
    desktop_dc_rect_ = DesktopRect();
  }

  if (!desktop_dc_) {
    assert(!memory_dc_);

    // Create GDI device contexts to capture from the desktop into memory.
    desktop_dc_ = GetDC(nullptr);
    if (!desktop_dc_)
      abort();
    memory_dc_ = CreateCompatibleDC(desktop_dc_);
    if (!memory_dc_)
      abort();

    desktop_dc_rect_ = screen_rect;

    // Make sure the frame buffers will be reallocated.
    queue_.Reset();
  }
}

bool ScreenCapturerWinGdi::CaptureImage() {
  DesktopRect screen_rect =
      GetScreenRect(current_screen_id_, current_device_key_);
  if (screen_rect.is_empty())
    return false;

  DesktopSize size = screen_rect.size();
  // If the current buffer is from an older generation then allocate a new one.
  // Note that we can't reallocate other buffers at this point, since the caller
  // may still be reading from them.
  if (!queue_.current_frame() ||
      !queue_.current_frame()->size().equals(screen_rect.size())) {
    assert(desktop_dc_);
    assert(memory_dc_);

    std::unique_ptr<DesktopFrame> buffer = DesktopFrameWin::Create(
        size, shared_memory_factory_.get(), desktop_dc_);
    if (!buffer)
      return false;
    queue_.ReplaceCurrentFrame(SharedDesktopFrame::Wrap(std::move(buffer)));
  }

  // Select the target bitmap into the memory dc and copy the rect from desktop
  // to memory.
  DesktopFrameWin* current = static_cast<DesktopFrameWin*>(
      queue_.current_frame()->GetUnderlyingFrame());
  HGDIOBJ previous_object = SelectObject(memory_dc_, current->bitmap());
  if (previous_object) {
    BitBlt(memory_dc_, 0, 0, screen_rect.width(), screen_rect.height(),
           desktop_dc_, screen_rect.left(), screen_rect.top(),
           SRCCOPY | CAPTUREBLT);

    // Select back the previously selected object to that the device contect
    // could be destroyed independently of the bitmap if needed.
    SelectObject(memory_dc_, previous_object);
  }
  return true;
}

}  // namespace webrtc
<commit_msg>Log BitBlt failure<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/win/screen_capturer_win_gdi.h"

#include <utility>

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/desktop_frame_win.h"
#include "webrtc/modules/desktop_capture/desktop_region.h"
#include "webrtc/modules/desktop_capture/mouse_cursor.h"
#include "webrtc/modules/desktop_capture/win/cursor.h"
#include "webrtc/modules/desktop_capture/win/desktop.h"
#include "webrtc/modules/desktop_capture/win/screen_capture_utils.h"
#include "webrtc/system_wrappers/include/logging.h"

namespace webrtc {

namespace {

// Constants from dwmapi.h.
const UINT DWM_EC_DISABLECOMPOSITION = 0;
const UINT DWM_EC_ENABLECOMPOSITION = 1;

const wchar_t kDwmapiLibraryName[] = L"dwmapi.dll";

}  // namespace

ScreenCapturerWinGdi::ScreenCapturerWinGdi(
    const DesktopCaptureOptions& options) {
  if (options.disable_effects()) {
    // Load dwmapi.dll dynamically since it is not available on XP.
    if (!dwmapi_library_)
      dwmapi_library_ = LoadLibrary(kDwmapiLibraryName);

    if (dwmapi_library_) {
      composition_func_ = reinterpret_cast<DwmEnableCompositionFunc>(
          GetProcAddress(dwmapi_library_, "DwmEnableComposition"));
    }
  }
}

ScreenCapturerWinGdi::~ScreenCapturerWinGdi() {
  if (desktop_dc_)
    ReleaseDC(NULL, desktop_dc_);
  if (memory_dc_)
    DeleteDC(memory_dc_);

  // Restore Aero.
  if (composition_func_)
    (*composition_func_)(DWM_EC_ENABLECOMPOSITION);

  if (dwmapi_library_)
    FreeLibrary(dwmapi_library_);
}

void ScreenCapturerWinGdi::SetSharedMemoryFactory(
    std::unique_ptr<SharedMemoryFactory> shared_memory_factory) {
  shared_memory_factory_ = std::move(shared_memory_factory);
}

void ScreenCapturerWinGdi::CaptureFrame() {
  int64_t capture_start_time_nanos = rtc::TimeNanos();

  queue_.MoveToNextFrame();
  RTC_DCHECK(!queue_.current_frame() || !queue_.current_frame()->IsShared());

  // Make sure the GDI capture resources are up-to-date.
  PrepareCaptureResources();

  if (!CaptureImage()) {
    callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr);
    return;
  }

  // Emit the current frame.
  std::unique_ptr<DesktopFrame> frame = queue_.current_frame()->Share();
  frame->set_dpi(DesktopVector(
      GetDeviceCaps(desktop_dc_, LOGPIXELSX),
      GetDeviceCaps(desktop_dc_, LOGPIXELSY)));
  frame->mutable_updated_region()->SetRect(
      DesktopRect::MakeSize(frame->size()));
  frame->set_capture_time_ms(
      (rtc::TimeNanos() - capture_start_time_nanos) /
      rtc::kNumNanosecsPerMillisec);
  callback_->OnCaptureResult(Result::SUCCESS, std::move(frame));
}

bool ScreenCapturerWinGdi::GetSourceList(SourceList* sources) {
  return webrtc::GetScreenList(sources);
}

bool ScreenCapturerWinGdi::SelectSource(SourceId id) {
  bool valid = IsScreenValid(id, &current_device_key_);
  if (valid)
    current_screen_id_ = id;
  return valid;
}

void ScreenCapturerWinGdi::Start(Callback* callback) {
  RTC_DCHECK(!callback_);
  RTC_DCHECK(callback);

  callback_ = callback;

  // Vote to disable Aero composited desktop effects while capturing. Windows
  // will restore Aero automatically if the process exits. This has no effect
  // under Windows 8 or higher.  See crbug.com/124018.
  if (composition_func_)
    (*composition_func_)(DWM_EC_DISABLECOMPOSITION);
}

void ScreenCapturerWinGdi::PrepareCaptureResources() {
  // Switch to the desktop receiving user input if different from the current
  // one.
  std::unique_ptr<Desktop> input_desktop(Desktop::GetInputDesktop());
  if (input_desktop && !desktop_.IsSame(*input_desktop)) {
    // Release GDI resources otherwise SetThreadDesktop will fail.
    if (desktop_dc_) {
      ReleaseDC(NULL, desktop_dc_);
      desktop_dc_ = nullptr;
    }

    if (memory_dc_) {
      DeleteDC(memory_dc_);
      memory_dc_ = nullptr;
    }

    // If SetThreadDesktop() fails, the thread is still assigned a desktop.
    // So we can continue capture screen bits, just from the wrong desktop.
    desktop_.SetThreadDesktop(input_desktop.release());

    // Re-assert our vote to disable Aero.
    // See crbug.com/124018 and crbug.com/129906.
    if (composition_func_) {
      (*composition_func_)(DWM_EC_DISABLECOMPOSITION);
    }
  }

  // If the display bounds have changed then recreate GDI resources.
  // TODO(wez): Also check for pixel format changes.
  DesktopRect screen_rect(DesktopRect::MakeXYWH(
      GetSystemMetrics(SM_XVIRTUALSCREEN),
      GetSystemMetrics(SM_YVIRTUALSCREEN),
      GetSystemMetrics(SM_CXVIRTUALSCREEN),
      GetSystemMetrics(SM_CYVIRTUALSCREEN)));
  if (!screen_rect.equals(desktop_dc_rect_)) {
    if (desktop_dc_) {
      ReleaseDC(NULL, desktop_dc_);
      desktop_dc_ = nullptr;
    }
    if (memory_dc_) {
      DeleteDC(memory_dc_);
      memory_dc_ = nullptr;
    }
    desktop_dc_rect_ = DesktopRect();
  }

  if (!desktop_dc_) {
    RTC_DCHECK(!memory_dc_);

    // Create GDI device contexts to capture from the desktop into memory.
    desktop_dc_ = GetDC(nullptr);
    RTC_CHECK(desktop_dc_);
    memory_dc_ = CreateCompatibleDC(desktop_dc_);
    RTC_CHECK(memory_dc_);

    desktop_dc_rect_ = screen_rect;

    // Make sure the frame buffers will be reallocated.
    queue_.Reset();
  }
}

bool ScreenCapturerWinGdi::CaptureImage() {
  DesktopRect screen_rect =
      GetScreenRect(current_screen_id_, current_device_key_);
  if (screen_rect.is_empty())
    return false;

  DesktopSize size = screen_rect.size();
  // If the current buffer is from an older generation then allocate a new one.
  // Note that we can't reallocate other buffers at this point, since the caller
  // may still be reading from them.
  if (!queue_.current_frame() ||
      !queue_.current_frame()->size().equals(screen_rect.size())) {
    RTC_DCHECK(desktop_dc_);
    RTC_DCHECK(memory_dc_);

    std::unique_ptr<DesktopFrame> buffer = DesktopFrameWin::Create(
        size, shared_memory_factory_.get(), desktop_dc_);
    if (!buffer)
      return false;
    queue_.ReplaceCurrentFrame(SharedDesktopFrame::Wrap(std::move(buffer)));
  }

  // Select the target bitmap into the memory dc and copy the rect from desktop
  // to memory.
  DesktopFrameWin* current = static_cast<DesktopFrameWin*>(
      queue_.current_frame()->GetUnderlyingFrame());
  HGDIOBJ previous_object = SelectObject(memory_dc_, current->bitmap());
  if (!previous_object || previous_object == HGDI_ERROR) {
    return false;
  }

  bool result = (BitBlt(memory_dc_, 0, 0, screen_rect.width(),
      screen_rect.height(), desktop_dc_, screen_rect.left(), screen_rect.top(),
      SRCCOPY | CAPTUREBLT) != FALSE);
  if (!result) {
    LOG_GLE(LS_WARNING) << "BitBlt failed";
  }

  // Select back the previously selected object to that the device contect
  // could be destroyed independently of the bitmap if needed.
  SelectObject(memory_dc_, previous_object);

  return result;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: VIndexColumn.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: oj $ $Date: 2001-05-17 09:13:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_INDEXCOLUMN_HXX_
#include "connectivity/sdbcx/VIndexColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OIndexColumn::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndexColumnDescription");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndex");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OIndexColumn::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.IndexDescription");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Index");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OIndexColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -----------------------------------------------------------------------------
OIndexColumn::OIndexColumn(sal_Bool _bCase) : OColumn(_bCase),  m_IsAscending(sal_True)
{
    construct();
}

// -------------------------------------------------------------------------
OIndexColumn::OIndexColumn( sal_Bool _IsAscending,
                            const ::rtl::OUString&  _Name,
                            const ::rtl::OUString&  _TypeName,
                            const ::rtl::OUString&  _DefaultValue,
                            sal_Int32               _IsNullable,
                            sal_Int32               _Precision,
                            sal_Int32               _Scale,
                            sal_Int32               _Type,
                            sal_Bool                _IsAutoIncrement,
                            sal_Bool                _IsRowVersion,
                            sal_Bool                _IsCurrency,
                            sal_Bool                _bCase
                        ) : OColumn(_Name,
                            _TypeName,
                            _DefaultValue,
                            _IsNullable,
                            _Precision,
                            _Scale,
                            _Type,
                            _IsAutoIncrement,
                            _IsRowVersion,
                            _IsCurrency,
                            _bCase)
                        ,   m_IsAscending(_IsAscending)
{
    construct();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OIndexColumn::createArrayHelper( sal_Int32 _nId) const
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
    describeProperties(aProps);
    changePropertyAttributte(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OIndexColumn::getInfoHelper()
{
    return *OIndexColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
void OIndexColumn::construct()
{
    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING,    nAttrib,&m_IsAscending, ::getBooleanCppuType());
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.352); FILE MERGED 2005/09/05 17:25:55 rt 1.8.352.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VIndexColumn.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:43:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_INDEXCOLUMN_HXX_
#include "connectivity/sdbcx/VIndexColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OIndexColumn::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndexColumnDescription");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndex");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OIndexColumn::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.IndexDescription");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Index");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OIndexColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -----------------------------------------------------------------------------
OIndexColumn::OIndexColumn(sal_Bool _bCase) : OColumn(_bCase),  m_IsAscending(sal_True)
{
    construct();
}

// -------------------------------------------------------------------------
OIndexColumn::OIndexColumn( sal_Bool _IsAscending,
                            const ::rtl::OUString&  _Name,
                            const ::rtl::OUString&  _TypeName,
                            const ::rtl::OUString&  _DefaultValue,
                            sal_Int32               _IsNullable,
                            sal_Int32               _Precision,
                            sal_Int32               _Scale,
                            sal_Int32               _Type,
                            sal_Bool                _IsAutoIncrement,
                            sal_Bool                _IsRowVersion,
                            sal_Bool                _IsCurrency,
                            sal_Bool                _bCase
                        ) : OColumn(_Name,
                            _TypeName,
                            _DefaultValue,
                            _IsNullable,
                            _Precision,
                            _Scale,
                            _Type,
                            _IsAutoIncrement,
                            _IsRowVersion,
                            _IsCurrency,
                            _bCase)
                        ,   m_IsAscending(_IsAscending)
{
    construct();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OIndexColumn::createArrayHelper( sal_Int32 _nId) const
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
    describeProperties(aProps);
    changePropertyAttributte(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OIndexColumn::getInfoHelper()
{
    return *OIndexColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
void OIndexColumn::construct()
{
    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING,    nAttrib,&m_IsAscending, ::getBooleanCppuType());
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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 "test-platform-abstraction.h"
#include "dali-test-suite-utils.h"
#include <dali/integration-api/bitmap.h>

namespace Dali
{

TestPlatformAbstraction::TestPlatformAbstraction()
: mTrace(),
  mIsLoadingResult( false ),
  mGetDefaultFontSizeResult( 0 ),
  mLoadedResourcesQueue(),
  mFailedLoadQueue(),
  mResourceRequests(),
  mSize(),
  mClosestSize(),
  mLoadFileResult(),
  mSaveFileResult( false ),
  mSynchronouslyLoadedResource()
{
  Initialize();
}

TestPlatformAbstraction::~TestPlatformAbstraction()
{
}

void TestPlatformAbstraction::Suspend()
{
  mTrace.PushCall("Suspend", "");
}

void TestPlatformAbstraction::Resume()
{
  mTrace.PushCall("Resume", "");
}

ImageDimensions TestPlatformAbstraction::GetClosestImageSize( const std::string& filename,
                                                              ImageDimensions size,
                                                              FittingMode::Type fittingMode,
                                                              SamplingMode::Type samplingMode,
                                                              bool orientationCorrection )
{
  ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y );
  mTrace.PushCall("GetClosestImageSize", "");
  return closestSize;
}

ImageDimensions TestPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
                                                   ImageDimensions size,
                                                   FittingMode::Type fittingMode,
                                                   SamplingMode::Type samplingMode,
                                                   bool orientationCorrection )
{
  ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y );
  mTrace.PushCall("GetClosestImageSize", "");
  return closestSize;
}

void TestPlatformAbstraction::LoadResource(const Integration::ResourceRequest& request)
{
  std::ostringstream out;
  out << "Type:" << request.GetType()->id << ", Path: " << request.GetPath() << std::endl ;

  mTrace.PushCall("LoadResource", out.str());

  mResourceRequests.PushBack( new Integration::ResourceRequest(request) );
}

Integration::ResourcePointer TestPlatformAbstraction::LoadResourceSynchronously( const Integration::ResourceType& resourceType, const std::string& resourcePath )
{
  mTrace.PushCall("LoadResourceSynchronously", "");
  return mSynchronouslyLoadedResource;
}

Integration::BitmapPtr TestPlatformAbstraction::DecodeBuffer( const Integration::ResourceType& resourceType, uint8_t * buffer, size_t size )
{
  mTrace.PushCall("DecodeBuffer", "");
  return mDecodedBitmap;
}

void TestPlatformAbstraction::CancelLoad(Integration::ResourceId id, Integration::ResourceTypeId typeId)
{
  mTrace.PushCall("CancelLoad", "");
}

void TestPlatformAbstraction::GetResources(Integration::ResourceCache& cache)
{
  mTrace.PushCall("GetResources", "");

  while( !mLoadedResourcesQueue.empty() )
  {
    LoadedResource loaded( *mLoadedResourcesQueue.begin() );
    mLoadedResourcesQueue.erase( mLoadedResourcesQueue.begin() );
    cache.LoadResponse( loaded.id, loaded.type, loaded.resource, Integration::RESOURCE_COMPLETELY_LOADED );
  }

  // iterate through the resources which failed to load
  while( !mFailedLoadQueue.empty() )
  {
    FailedLoad failed( *mFailedLoadQueue.begin() );
    mFailedLoadQueue.erase( mFailedLoadQueue.begin() );
    cache.LoadFailed( failed.id, failed.failure );
  }
}

bool TestPlatformAbstraction::IsLoading()
{
  mTrace.PushCall("IsLoading", "");
  return mIsLoadingResult;
}

int TestPlatformAbstraction::GetDefaultFontSize() const
{
  mTrace.PushCall("GetDefaultFontSize", "");
  return mGetDefaultFontSizeResult;
}

void TestPlatformAbstraction::SetDpi (unsigned int dpiHorizontal, unsigned int dpiVertical)
{
  mTrace.PushCall("SetDpi", "");
}

bool TestPlatformAbstraction::LoadFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const
{
  mTrace.PushCall("LoadFile", "");
  if( mLoadFileResult.loadResult )
  {
    buffer = mLoadFileResult.buffer;
  }

  return mLoadFileResult.loadResult;
}

bool TestPlatformAbstraction::LoadShaderBinaryFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const
{
  mTrace.PushCall("LoadShaderBinaryFile", "");
  if( mLoadFileResult.loadResult )
  {
    buffer = mLoadFileResult.buffer;
  }

  return mLoadFileResult.loadResult;
}

bool TestPlatformAbstraction::SaveFile(const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) const
{
  mTrace.PushCall("SaveFile", "");
  return false;
}

void TestPlatformAbstraction::JoinLoaderThreads()
{
  mTrace.PushCall("JoinLoaderThreads", "");
}

/** Call this every test */
void TestPlatformAbstraction::Initialize()
{
  mTrace.Reset();
  mTrace.Enable(true);
  mLoadedResourcesQueue.clear();
  mFailedLoadQueue.clear();
  mResourceRequests.Clear();
  mIsLoadingResult=false;
  mSynchronouslyLoadedResource.Reset();
  mDecodedBitmap.Reset();
}

bool TestPlatformAbstraction::WasCalled(TestFuncEnum func)
{
  switch(func)
  {
    case SuspendFunc:                         return mTrace.FindMethod("Suspend");
    case ResumeFunc:                          return mTrace.FindMethod("Resume");
    case LoadResourceFunc:                    return mTrace.FindMethod("LoadResource");
    case LoadResourceSynchronouslyFunc:       return mTrace.FindMethod("LoadResourceSynchronously");
    case LoadFileFunc:                        return mTrace.FindMethod("LoadFile");
    case LoadShaderBinaryFileFunc:            return mTrace.FindMethod("LoadShaderBinaryFile");
    case SaveShaderBinaryFileFunc:            return mTrace.FindMethod("SaveShaderBinaryFile");
    case SaveFileFunc:                        return mTrace.FindMethod("SaveFile");
    case CancelLoadFunc:                      return mTrace.FindMethod("CancelLoad");
    case GetResourcesFunc:                    return mTrace.FindMethod("GetResources");
    case IsLoadingFunc:                       return mTrace.FindMethod("IsLoading");
    case SetDpiFunc:                          return mTrace.FindMethod("SetDpi");
    case JoinLoaderThreadsFunc:               return mTrace.FindMethod("JoinLoaderThreads");
  }
  return false;
}

void TestPlatformAbstraction::SetIsLoadingResult(bool result)
{
  mIsLoadingResult = result;
}

void TestPlatformAbstraction::ClearReadyResources()
{
  mLoadedResourcesQueue.clear();
  mFailedLoadQueue.clear();
  mSynchronouslyLoadedResource.Reset();
  mDecodedBitmap.Reset();
}

void TestPlatformAbstraction::SetResourceLoaded(Integration::ResourceId  loadedId,
                                                Integration::ResourceTypeId  loadedType,
                                                Integration::ResourcePointer loadedResource)
{
  LoadedResource loadedInfo;
  loadedInfo.id = loadedId;
  loadedInfo.type = loadedType;
  loadedInfo.resource = loadedResource;
  mLoadedResourcesQueue.push_back( loadedInfo );
}

void TestPlatformAbstraction::SetResourceLoadFailed(Integration::ResourceId  id,
                                                    Integration::ResourceFailure failure)
{
  FailedLoad failedInfo;
  failedInfo.id = id;
  failedInfo.failure = failure;
  mFailedLoadQueue.push_back( failedInfo );
}

Integration::ResourceRequest* TestPlatformAbstraction::GetRequest()
{
  Integration::ResourceRequest* request = NULL;

  // Return last request
  if( ! mResourceRequests.Empty() )
  {
    request = *( mResourceRequests.End() - 1 );
  }

  return request;
}

const TestPlatformAbstraction::ResourceRequestContainer& TestPlatformAbstraction::GetAllRequests() const
{
  return mResourceRequests;
}

void TestPlatformAbstraction::SetAllResourceRequestsAsLoaded()
{
  for( ResourceRequestContainer::Iterator iter = mResourceRequests.Begin(), endIter = mResourceRequests.End();
       iter != endIter; ++iter )
  {
    Integration::ResourceRequest* request = *iter;
    Integration::Bitmap* bitmap = Integration::Bitmap::New( Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD );
    Integration::ResourcePointer resource(bitmap);
    bitmap->GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGBA8888, 80, 80, 80, 80);
    SetResourceLoaded( request->GetId(), request->GetType()->id, resource );
  }
  mResourceRequests.Clear();
}

void TestPlatformAbstraction::SetAllResourceRequestsAsFailed( Integration::ResourceFailure failure )
{
  for( ResourceRequestContainer::Iterator iter = mResourceRequests.Begin(), endIter = mResourceRequests.End();
       iter != endIter; ++iter )
  {
    SetResourceLoadFailed( (*iter)->GetId(), failure);
  }
  mResourceRequests.Clear();
}

void TestPlatformAbstraction::DiscardRequest()
{
  mResourceRequests.Clear();
}

void TestPlatformAbstraction::SetClosestImageSize(const Vector2& size)
{
  mClosestSize = size;
}

void TestPlatformAbstraction::SetLoadFileResult( bool result, Dali::Vector< unsigned char >& buffer )
{
  mLoadFileResult.loadResult = result;
  if( result )
  {
    mLoadFileResult.buffer = buffer;
  }
}

void TestPlatformAbstraction::SetSaveFileResult( bool result )
{
  mSaveFileResult = result;
}

void TestPlatformAbstraction::SetSynchronouslyLoadedResource( Integration::ResourcePointer resource )
{
  mSynchronouslyLoadedResource = resource;
}

void TestPlatformAbstraction::SetDecodedBitmap( Integration::BitmapPtr bitmap )
{
  mDecodedBitmap = bitmap;
}

} // namespace Dali
<commit_msg>Fix SVACE issue - memory leak<commit_after>/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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 "test-platform-abstraction.h"
#include "dali-test-suite-utils.h"
#include <dali/integration-api/bitmap.h>

namespace Dali
{

TestPlatformAbstraction::TestPlatformAbstraction()
: mTrace(),
  mIsLoadingResult( false ),
  mGetDefaultFontSizeResult( 0 ),
  mLoadedResourcesQueue(),
  mFailedLoadQueue(),
  mResourceRequests(),
  mSize(),
  mClosestSize(),
  mLoadFileResult(),
  mSaveFileResult( false ),
  mSynchronouslyLoadedResource()
{
  Initialize();
}

TestPlatformAbstraction::~TestPlatformAbstraction()
{
  DiscardRequest();
}

void TestPlatformAbstraction::Suspend()
{
  mTrace.PushCall("Suspend", "");
}

void TestPlatformAbstraction::Resume()
{
  mTrace.PushCall("Resume", "");
}

ImageDimensions TestPlatformAbstraction::GetClosestImageSize( const std::string& filename,
                                                              ImageDimensions size,
                                                              FittingMode::Type fittingMode,
                                                              SamplingMode::Type samplingMode,
                                                              bool orientationCorrection )
{
  ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y );
  mTrace.PushCall("GetClosestImageSize", "");
  return closestSize;
}

ImageDimensions TestPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
                                                   ImageDimensions size,
                                                   FittingMode::Type fittingMode,
                                                   SamplingMode::Type samplingMode,
                                                   bool orientationCorrection )
{
  ImageDimensions closestSize = ImageDimensions( mClosestSize.x, mClosestSize.y );
  mTrace.PushCall("GetClosestImageSize", "");
  return closestSize;
}

void TestPlatformAbstraction::LoadResource(const Integration::ResourceRequest& request)
{
  std::ostringstream out;
  out << "Type:" << request.GetType()->id << ", Path: " << request.GetPath() << std::endl ;

  mTrace.PushCall("LoadResource", out.str());

  mResourceRequests.PushBack( new Integration::ResourceRequest(request) );
}

Integration::ResourcePointer TestPlatformAbstraction::LoadResourceSynchronously( const Integration::ResourceType& resourceType, const std::string& resourcePath )
{
  mTrace.PushCall("LoadResourceSynchronously", "");
  return mSynchronouslyLoadedResource;
}

Integration::BitmapPtr TestPlatformAbstraction::DecodeBuffer( const Integration::ResourceType& resourceType, uint8_t * buffer, size_t size )
{
  mTrace.PushCall("DecodeBuffer", "");
  return mDecodedBitmap;
}

void TestPlatformAbstraction::CancelLoad(Integration::ResourceId id, Integration::ResourceTypeId typeId)
{
  mTrace.PushCall("CancelLoad", "");
}

void TestPlatformAbstraction::GetResources(Integration::ResourceCache& cache)
{
  mTrace.PushCall("GetResources", "");

  while( !mLoadedResourcesQueue.empty() )
  {
    LoadedResource loaded( *mLoadedResourcesQueue.begin() );
    mLoadedResourcesQueue.erase( mLoadedResourcesQueue.begin() );
    cache.LoadResponse( loaded.id, loaded.type, loaded.resource, Integration::RESOURCE_COMPLETELY_LOADED );
  }

  // iterate through the resources which failed to load
  while( !mFailedLoadQueue.empty() )
  {
    FailedLoad failed( *mFailedLoadQueue.begin() );
    mFailedLoadQueue.erase( mFailedLoadQueue.begin() );
    cache.LoadFailed( failed.id, failed.failure );
  }
}

bool TestPlatformAbstraction::IsLoading()
{
  mTrace.PushCall("IsLoading", "");
  return mIsLoadingResult;
}

int TestPlatformAbstraction::GetDefaultFontSize() const
{
  mTrace.PushCall("GetDefaultFontSize", "");
  return mGetDefaultFontSizeResult;
}

void TestPlatformAbstraction::SetDpi (unsigned int dpiHorizontal, unsigned int dpiVertical)
{
  mTrace.PushCall("SetDpi", "");
}

bool TestPlatformAbstraction::LoadFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const
{
  mTrace.PushCall("LoadFile", "");
  if( mLoadFileResult.loadResult )
  {
    buffer = mLoadFileResult.buffer;
  }

  return mLoadFileResult.loadResult;
}

bool TestPlatformAbstraction::LoadShaderBinaryFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const
{
  mTrace.PushCall("LoadShaderBinaryFile", "");
  if( mLoadFileResult.loadResult )
  {
    buffer = mLoadFileResult.buffer;
  }

  return mLoadFileResult.loadResult;
}

bool TestPlatformAbstraction::SaveFile(const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) const
{
  mTrace.PushCall("SaveFile", "");
  return false;
}

void TestPlatformAbstraction::JoinLoaderThreads()
{
  mTrace.PushCall("JoinLoaderThreads", "");
}

/** Call this every test */
void TestPlatformAbstraction::Initialize()
{
  mTrace.Reset();
  mTrace.Enable(true);
  mLoadedResourcesQueue.clear();
  mFailedLoadQueue.clear();
  mResourceRequests.Clear();
  mIsLoadingResult=false;
  mSynchronouslyLoadedResource.Reset();
  mDecodedBitmap.Reset();
}

bool TestPlatformAbstraction::WasCalled(TestFuncEnum func)
{
  switch(func)
  {
    case SuspendFunc:                         return mTrace.FindMethod("Suspend");
    case ResumeFunc:                          return mTrace.FindMethod("Resume");
    case LoadResourceFunc:                    return mTrace.FindMethod("LoadResource");
    case LoadResourceSynchronouslyFunc:       return mTrace.FindMethod("LoadResourceSynchronously");
    case LoadFileFunc:                        return mTrace.FindMethod("LoadFile");
    case LoadShaderBinaryFileFunc:            return mTrace.FindMethod("LoadShaderBinaryFile");
    case SaveShaderBinaryFileFunc:            return mTrace.FindMethod("SaveShaderBinaryFile");
    case SaveFileFunc:                        return mTrace.FindMethod("SaveFile");
    case CancelLoadFunc:                      return mTrace.FindMethod("CancelLoad");
    case GetResourcesFunc:                    return mTrace.FindMethod("GetResources");
    case IsLoadingFunc:                       return mTrace.FindMethod("IsLoading");
    case SetDpiFunc:                          return mTrace.FindMethod("SetDpi");
    case JoinLoaderThreadsFunc:               return mTrace.FindMethod("JoinLoaderThreads");
  }
  return false;
}

void TestPlatformAbstraction::SetIsLoadingResult(bool result)
{
  mIsLoadingResult = result;
}

void TestPlatformAbstraction::ClearReadyResources()
{
  mLoadedResourcesQueue.clear();
  mFailedLoadQueue.clear();
  mSynchronouslyLoadedResource.Reset();
  mDecodedBitmap.Reset();
}

void TestPlatformAbstraction::SetResourceLoaded(Integration::ResourceId  loadedId,
                                                Integration::ResourceTypeId  loadedType,
                                                Integration::ResourcePointer loadedResource)
{
  LoadedResource loadedInfo;
  loadedInfo.id = loadedId;
  loadedInfo.type = loadedType;
  loadedInfo.resource = loadedResource;
  mLoadedResourcesQueue.push_back( loadedInfo );
}

void TestPlatformAbstraction::SetResourceLoadFailed(Integration::ResourceId  id,
                                                    Integration::ResourceFailure failure)
{
  FailedLoad failedInfo;
  failedInfo.id = id;
  failedInfo.failure = failure;
  mFailedLoadQueue.push_back( failedInfo );
}

Integration::ResourceRequest* TestPlatformAbstraction::GetRequest()
{
  Integration::ResourceRequest* request = NULL;

  // Return last request
  if( ! mResourceRequests.Empty() )
  {
    request = *( mResourceRequests.End() - 1 );
  }

  return request;
}

const TestPlatformAbstraction::ResourceRequestContainer& TestPlatformAbstraction::GetAllRequests() const
{
  return mResourceRequests;
}

void TestPlatformAbstraction::SetAllResourceRequestsAsLoaded()
{
  for( ResourceRequestContainer::Iterator iter = mResourceRequests.Begin(), endIter = mResourceRequests.End();
       iter != endIter; ++iter )
  {
    Integration::ResourceRequest* request = *iter;
    Integration::Bitmap* bitmap = Integration::Bitmap::New( Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD );
    Integration::ResourcePointer resource(bitmap);
    bitmap->GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGBA8888, 80, 80, 80, 80);
    SetResourceLoaded( request->GetId(), request->GetType()->id, resource );
    delete request;
  }
  mResourceRequests.Clear();
}

void TestPlatformAbstraction::SetAllResourceRequestsAsFailed( Integration::ResourceFailure failure )
{
  for( ResourceRequestContainer::Iterator iter = mResourceRequests.Begin(), endIter = mResourceRequests.End();
       iter != endIter; ++iter )
  {
    Integration::ResourceRequest* request = *iter;
    SetResourceLoadFailed( (*iter)->GetId(), failure);
    delete request;
  }
  mResourceRequests.Clear();
}

void TestPlatformAbstraction::DiscardRequest()
{
  for( ResourceRequestContainer::Iterator iter = mResourceRequests.Begin(), endIter = mResourceRequests.End();
       iter != endIter; ++iter )
  {
    Integration::ResourceRequest* request = *iter;
    delete request;
  }
  mResourceRequests.Clear();
}

void TestPlatformAbstraction::SetClosestImageSize(const Vector2& size)
{
  mClosestSize = size;
}

void TestPlatformAbstraction::SetLoadFileResult( bool result, Dali::Vector< unsigned char >& buffer )
{
  mLoadFileResult.loadResult = result;
  if( result )
  {
    mLoadFileResult.buffer = buffer;
  }
}

void TestPlatformAbstraction::SetSaveFileResult( bool result )
{
  mSaveFileResult = result;
}

void TestPlatformAbstraction::SetSynchronouslyLoadedResource( Integration::ResourcePointer resource )
{
  mSynchronouslyLoadedResource = resource;
}

void TestPlatformAbstraction::SetDecodedBitmap( Integration::BitmapPtr bitmap )
{
  mDecodedBitmap = bitmap;
}

} // namespace Dali
<|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/api/declarative/rules_registry_storage_delegate.h"

#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/extensions/extension_info_map.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/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"

namespace extensions {

namespace {

scoped_ptr<base::Value> RulesToValue(
    const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) {
  scoped_ptr<base::ListValue> list(new base::ListValue());
  for (size_t i = 0; i < rules.size(); ++i)
    list->Append(rules[i]->ToValue().release());
  return list.PassAs<base::Value>();
}

std::vector<linked_ptr<RulesRegistry::Rule> > RulesFromValue(
    base::Value* value) {
  std::vector<linked_ptr<RulesRegistry::Rule> > rules;

  base::ListValue* list = NULL;
  if (!value || !value->GetAsList(&list))
    return rules;

  for (size_t i = 0; i < list->GetSize(); ++i) {
    base::DictionaryValue* dict = NULL;
    if (!list->GetDictionary(i, &dict))
      continue;
    linked_ptr<RulesRegistry::Rule> rule(new RulesRegistry::Rule());
    if (RulesRegistry::Rule::Populate(*dict, rule.get()))
      rules.push_back(rule);
  }

  return rules;
}

}  // namespace

// This class coordinates information between the UI and RulesRegistry threads.
// It may outlive the RulesRegistry, which owns the delegate. Methods/variables
// should be used on the UI thread unless otherwise noted.
class RulesRegistryStorageDelegate::Inner
    : public content::NotificationObserver,
      public base::RefCountedThreadSafe<Inner> {
 public:
  Inner(Profile* profile,
        RulesRegistryWithCache* rules_registry,
        const std::string& storage_key);

  // Run this once, just after Inner is constructed.
  void Init();

 private:
  friend class base::RefCountedThreadSafe<Inner>;
  friend class RulesRegistryStorageDelegate;

  virtual ~Inner();

  // Initialization of the storage delegate if it is used in the context of
  // an incognito profile.
  void InitForOTRProfile();

  // NotificationObserver
  virtual void Observe(
      int type,
      const content::NotificationSource& source,
      const content::NotificationDetails& details) OVERRIDE;

  // Read/write a list of rules serialized to Values.
  void ReadFromStorage(const std::string& extension_id);
  void ReadFromStorageCallback(const std::string& extension_id,
                       scoped_ptr<base::Value> value);
  void WriteToStorage(const std::string& extension_id,
                      scoped_ptr<base::Value> value);

  // Check if we are done reading all data from storage on startup, and notify
  // the RulesRegistry on its thread if so. The notification is delivered
  // exactly once.
  void CheckIfReady();

  // Deserialize the rules from the given Value object and add them to the
  // RulesRegistry.
  void ReadFromStorageOnRegistryThread(const std::string& extension_id,
                                       scoped_ptr<base::Value> value);

  // Notify the RulesRegistry that we are now ready.
  void NotifyReadyOnRegistryThread();

  scoped_ptr<content::NotificationRegistrar> registrar_;
  Profile* profile_;

  // The key under which rules are stored.
  const std::string storage_key_;

  // A set of extension IDs that have rules we are reading from storage.
  // TODO(vabr): Once the migration code of http://crbug.com/166474 is removed,
  // switch this back to just set. http://crbug.com/176926
  std::multiset<std::string> waiting_for_extensions_;

  // The thread that our RulesRegistry lives on.
  content::BrowserThread::ID rules_registry_thread_;

  // The following are only accessible on rules_registry_thread_.

  // The RulesRegistry whose delegate we are.
  RulesRegistryWithCache* rules_registry_;

  // True when we have finished reading from storage for all extensions that
  // are loaded on startup.
  bool ready_;

  // We measure the time spent on loading rules on init. The result is logged
  // with UMA once per the delegate instance, unless in Incognito.
  base::Time storage_init_time_;
  bool log_storage_init_delay_;
};

RulesRegistryStorageDelegate::RulesRegistryStorageDelegate() {
}

RulesRegistryStorageDelegate::~RulesRegistryStorageDelegate() {
  // RulesRegistry owns us, which means it has been deleted.
  inner_->rules_registry_ = NULL;
}

void RulesRegistryStorageDelegate::InitOnUIThread(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  extensions::StateStore* store = ExtensionSystem::Get(profile)->rules_store();
  if (store)
    store->RegisterKey(storage_key);
  inner_ = new Inner(profile, rules_registry, storage_key);
  inner_->Init();
}

void RulesRegistryStorageDelegate::CleanupOnUIThread() {
  // The registrar must be deleted on the UI thread.
  inner_->registrar_.reset();
  inner_->profile_ = NULL;  // no longer safe to use.
}

bool RulesRegistryStorageDelegate::IsReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  return inner_->ready_;
}

void RulesRegistryStorageDelegate::OnRulesChanged(
    RulesRegistryWithCache* rules_registry,
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  std::vector<linked_ptr<RulesRegistry::Rule> > new_rules;
  std::string error = rules_registry->GetAllRules(extension_id, &new_rules);
  DCHECK_EQ("", error);
  content::BrowserThread::PostTask(
      content::BrowserThread::UI, FROM_HERE,
      base::Bind(&Inner::WriteToStorage, inner_, extension_id,
                 base::Passed(RulesToValue(new_rules))));
}

RulesRegistryStorageDelegate::Inner::Inner(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key)
    : registrar_(new content::NotificationRegistrar()),
      profile_(profile),
      storage_key_(storage_key),
      rules_registry_thread_(rules_registry->GetOwnerThread()),
      rules_registry_(rules_registry),
      ready_(false),
      log_storage_init_delay_(true) {}

void RulesRegistryStorageDelegate::Inner::Init() {
  if (!profile_->IsOffTheRecord()) {
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile_));
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
                    content::Source<Profile>(profile_));
  } else {
    log_storage_init_delay_ = false;
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile_->GetOriginalProfile()));
    InitForOTRProfile();
  }
}

RulesRegistryStorageDelegate::Inner::~Inner() {
  DCHECK(!registrar_.get());
}

void RulesRegistryStorageDelegate::Inner::InitForOTRProfile() {
  ExtensionService* extension_service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const ExtensionSet* extensions = extension_service->extensions();
  for (ExtensionSet::const_iterator i = extensions->begin();
       i != extensions->end(); ++i) {
    if (((*i)->HasAPIPermission(APIPermission::kDeclarativeContent) ||
         (*i)->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) &&
        extension_service->IsIncognitoEnabled((*i)->id()))
      ReadFromStorage((*i)->id());
  }
  CheckIfReady();
}

void RulesRegistryStorageDelegate::Inner::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
    const extensions::Extension* extension =
        content::Details<const extensions::Extension>(details).ptr();
    // TODO(mpcomplete): This API check should generalize to any use of
    // declarative rules, not just webRequest.
    if (extension->HasAPIPermission(APIPermission::kDeclarativeContent) ||
        extension->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) {
      ExtensionInfoMap* extension_info_map =
          ExtensionSystem::Get(profile_)->info_map();
      if (profile_->IsOffTheRecord() &&
          !extension_info_map->IsIncognitoEnabled(extension->id())) {
        // Ignore this extension.
      } else {
        ReadFromStorage(extension->id());
      }
    }
  } else if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
    CheckIfReady();
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorage(
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  if (storage_init_time_.is_null())
    storage_init_time_ = base::Time::Now();

  extensions::StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(extension_id,
                             storage_key_,
                             base::Bind(&Inner::ReadFromStorageCallback,
                                        make_scoped_refptr(this),
                                        extension_id));
  }

  // TODO(mpcomplete): Migration code. Remove when declarativeWebRequest goes
  // to stable.
  // http://crbug.com/166474
  store = ExtensionSystem::Get(profile_)->state_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(extension_id,
                             storage_key_,
                             base::Bind(&Inner::ReadFromStorageCallback,
                                        make_scoped_refptr(this),
                                        extension_id));
    store->RemoveExtensionValue(extension_id, storage_key_);
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageCallback(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  content::BrowserThread::PostTask(
      rules_registry_thread_,
      FROM_HERE,
      base::Bind(&Inner::ReadFromStorageOnRegistryThread,
                 make_scoped_refptr(this),
                 extension_id,
                 base::Passed(&value)));

  // TODO(vabr): Once the migration code of http://crbug.com/166474 is removed,
  // and |waiting_for_extensions_| is just a set again, switch this back to only
  // calling erase(extension_id). http://crbug.com/176926
  std::multiset<std::string>::iterator it =
      waiting_for_extensions_.find(extension_id);
  CHECK(it != waiting_for_extensions_.end());
  waiting_for_extensions_.erase(it);

  CheckIfReady();
  if (log_storage_init_delay_ && waiting_for_extensions_.empty()) {
    UMA_HISTOGRAM_TIMES("Extensions.DeclarativeRulesStorageInitialization",
                        base::Time::Now() - storage_init_time_);
    log_storage_init_delay_ = false;
  }
}

void RulesRegistryStorageDelegate::Inner::WriteToStorage(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store)
    store->SetExtensionValue(extension_id, storage_key_, value.Pass());
}

void RulesRegistryStorageDelegate::Inner::CheckIfReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!waiting_for_extensions_.empty())
    return;

  content::BrowserThread::PostTask(
      rules_registry_thread_,
      FROM_HERE,
      base::Bind(&Inner::NotifyReadyOnRegistryThread,
                 make_scoped_refptr(this)));
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageOnRegistryThread(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (!rules_registry_)
    return;  // registry went away

  rules_registry_->AddRules(extension_id, RulesFromValue(value.get()));
}

void RulesRegistryStorageDelegate::Inner::NotifyReadyOnRegistryThread() {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (ready_)
    return;  // we've already notified our readiness

  ready_ = true;

  if (!rules_registry_)
    return;  // registry went away
  rules_registry_->OnReady();
}

}  // namespace extensions
<commit_msg>Clean-up: remove unnecessary make_scoped_refptr<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/api/declarative/rules_registry_storage_delegate.h"

#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/extensions/extension_info_map.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/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"

namespace extensions {

namespace {

scoped_ptr<base::Value> RulesToValue(
    const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) {
  scoped_ptr<base::ListValue> list(new base::ListValue());
  for (size_t i = 0; i < rules.size(); ++i)
    list->Append(rules[i]->ToValue().release());
  return list.PassAs<base::Value>();
}

std::vector<linked_ptr<RulesRegistry::Rule> > RulesFromValue(
    base::Value* value) {
  std::vector<linked_ptr<RulesRegistry::Rule> > rules;

  base::ListValue* list = NULL;
  if (!value || !value->GetAsList(&list))
    return rules;

  for (size_t i = 0; i < list->GetSize(); ++i) {
    base::DictionaryValue* dict = NULL;
    if (!list->GetDictionary(i, &dict))
      continue;
    linked_ptr<RulesRegistry::Rule> rule(new RulesRegistry::Rule());
    if (RulesRegistry::Rule::Populate(*dict, rule.get()))
      rules.push_back(rule);
  }

  return rules;
}

}  // namespace

// This class coordinates information between the UI and RulesRegistry threads.
// It may outlive the RulesRegistry, which owns the delegate. Methods/variables
// should be used on the UI thread unless otherwise noted.
class RulesRegistryStorageDelegate::Inner
    : public content::NotificationObserver,
      public base::RefCountedThreadSafe<Inner> {
 public:
  Inner(Profile* profile,
        RulesRegistryWithCache* rules_registry,
        const std::string& storage_key);

  // Run this once, just after Inner is constructed.
  void Init();

 private:
  friend class base::RefCountedThreadSafe<Inner>;
  friend class RulesRegistryStorageDelegate;

  virtual ~Inner();

  // Initialization of the storage delegate if it is used in the context of
  // an incognito profile.
  void InitForOTRProfile();

  // NotificationObserver
  virtual void Observe(
      int type,
      const content::NotificationSource& source,
      const content::NotificationDetails& details) OVERRIDE;

  // Read/write a list of rules serialized to Values.
  void ReadFromStorage(const std::string& extension_id);
  void ReadFromStorageCallback(const std::string& extension_id,
                       scoped_ptr<base::Value> value);
  void WriteToStorage(const std::string& extension_id,
                      scoped_ptr<base::Value> value);

  // Check if we are done reading all data from storage on startup, and notify
  // the RulesRegistry on its thread if so. The notification is delivered
  // exactly once.
  void CheckIfReady();

  // Deserialize the rules from the given Value object and add them to the
  // RulesRegistry.
  void ReadFromStorageOnRegistryThread(const std::string& extension_id,
                                       scoped_ptr<base::Value> value);

  // Notify the RulesRegistry that we are now ready.
  void NotifyReadyOnRegistryThread();

  scoped_ptr<content::NotificationRegistrar> registrar_;
  Profile* profile_;

  // The key under which rules are stored.
  const std::string storage_key_;

  // A set of extension IDs that have rules we are reading from storage.
  // TODO(vabr): Once the migration code of http://crbug.com/166474 is removed,
  // switch this back to just set. http://crbug.com/176926
  std::multiset<std::string> waiting_for_extensions_;

  // The thread that our RulesRegistry lives on.
  content::BrowserThread::ID rules_registry_thread_;

  // The following are only accessible on rules_registry_thread_.

  // The RulesRegistry whose delegate we are.
  RulesRegistryWithCache* rules_registry_;

  // True when we have finished reading from storage for all extensions that
  // are loaded on startup.
  bool ready_;

  // We measure the time spent on loading rules on init. The result is logged
  // with UMA once per the delegate instance, unless in Incognito.
  base::Time storage_init_time_;
  bool log_storage_init_delay_;
};

RulesRegistryStorageDelegate::RulesRegistryStorageDelegate() {
}

RulesRegistryStorageDelegate::~RulesRegistryStorageDelegate() {
  // RulesRegistry owns us, which means it has been deleted.
  inner_->rules_registry_ = NULL;
}

void RulesRegistryStorageDelegate::InitOnUIThread(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  extensions::StateStore* store = ExtensionSystem::Get(profile)->rules_store();
  if (store)
    store->RegisterKey(storage_key);
  inner_ = new Inner(profile, rules_registry, storage_key);
  inner_->Init();
}

void RulesRegistryStorageDelegate::CleanupOnUIThread() {
  // The registrar must be deleted on the UI thread.
  inner_->registrar_.reset();
  inner_->profile_ = NULL;  // no longer safe to use.
}

bool RulesRegistryStorageDelegate::IsReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  return inner_->ready_;
}

void RulesRegistryStorageDelegate::OnRulesChanged(
    RulesRegistryWithCache* rules_registry,
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(inner_->rules_registry_thread_));
  std::vector<linked_ptr<RulesRegistry::Rule> > new_rules;
  std::string error = rules_registry->GetAllRules(extension_id, &new_rules);
  DCHECK_EQ("", error);
  content::BrowserThread::PostTask(
      content::BrowserThread::UI, FROM_HERE,
      base::Bind(&Inner::WriteToStorage, inner_, extension_id,
                 base::Passed(RulesToValue(new_rules))));
}

RulesRegistryStorageDelegate::Inner::Inner(
    Profile* profile,
    RulesRegistryWithCache* rules_registry,
    const std::string& storage_key)
    : registrar_(new content::NotificationRegistrar()),
      profile_(profile),
      storage_key_(storage_key),
      rules_registry_thread_(rules_registry->GetOwnerThread()),
      rules_registry_(rules_registry),
      ready_(false),
      log_storage_init_delay_(true) {}

void RulesRegistryStorageDelegate::Inner::Init() {
  if (!profile_->IsOffTheRecord()) {
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile_));
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
                    content::Source<Profile>(profile_));
  } else {
    log_storage_init_delay_ = false;
    registrar_->Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                    content::Source<Profile>(profile_->GetOriginalProfile()));
    InitForOTRProfile();
  }
}

RulesRegistryStorageDelegate::Inner::~Inner() {
  DCHECK(!registrar_.get());
}

void RulesRegistryStorageDelegate::Inner::InitForOTRProfile() {
  ExtensionService* extension_service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const ExtensionSet* extensions = extension_service->extensions();
  for (ExtensionSet::const_iterator i = extensions->begin();
       i != extensions->end(); ++i) {
    if (((*i)->HasAPIPermission(APIPermission::kDeclarativeContent) ||
         (*i)->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) &&
        extension_service->IsIncognitoEnabled((*i)->id()))
      ReadFromStorage((*i)->id());
  }
  CheckIfReady();
}

void RulesRegistryStorageDelegate::Inner::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
    const extensions::Extension* extension =
        content::Details<const extensions::Extension>(details).ptr();
    // TODO(mpcomplete): This API check should generalize to any use of
    // declarative rules, not just webRequest.
    if (extension->HasAPIPermission(APIPermission::kDeclarativeContent) ||
        extension->HasAPIPermission(APIPermission::kDeclarativeWebRequest)) {
      ExtensionInfoMap* extension_info_map =
          ExtensionSystem::Get(profile_)->info_map();
      if (profile_->IsOffTheRecord() &&
          !extension_info_map->IsIncognitoEnabled(extension->id())) {
        // Ignore this extension.
      } else {
        ReadFromStorage(extension->id());
      }
    }
  } else if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
    CheckIfReady();
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorage(
    const std::string& extension_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  if (storage_init_time_.is_null())
    storage_init_time_ = base::Time::Now();

  extensions::StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(
        extension_id, storage_key_,
        base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
  }

  // TODO(mpcomplete): Migration code. Remove when declarativeWebRequest goes
  // to stable.
  // http://crbug.com/166474
  store = ExtensionSystem::Get(profile_)->state_store();
  if (store) {
    waiting_for_extensions_.insert(extension_id);
    store->GetExtensionValue(
        extension_id, storage_key_,
        base::Bind(&Inner::ReadFromStorageCallback, this, extension_id));
    store->RemoveExtensionValue(extension_id, storage_key_);
  }
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageCallback(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  content::BrowserThread::PostTask(
      rules_registry_thread_,
      FROM_HERE,
      base::Bind(&Inner::ReadFromStorageOnRegistryThread, this, extension_id,
                 base::Passed(&value)));

  // TODO(vabr): Once the migration code of http://crbug.com/166474 is removed,
  // and |waiting_for_extensions_| is just a set again, switch this back to only
  // calling erase(extension_id). http://crbug.com/176926
  std::multiset<std::string>::iterator it =
      waiting_for_extensions_.find(extension_id);
  CHECK(it != waiting_for_extensions_.end());
  waiting_for_extensions_.erase(it);

  CheckIfReady();
  if (log_storage_init_delay_ && waiting_for_extensions_.empty()) {
    UMA_HISTOGRAM_TIMES("Extensions.DeclarativeRulesStorageInitialization",
                        base::Time::Now() - storage_init_time_);
    log_storage_init_delay_ = false;
  }
}

void RulesRegistryStorageDelegate::Inner::WriteToStorage(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!profile_)
    return;

  StateStore* store = ExtensionSystem::Get(profile_)->rules_store();
  if (store)
    store->SetExtensionValue(extension_id, storage_key_, value.Pass());
}

void RulesRegistryStorageDelegate::Inner::CheckIfReady() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (!waiting_for_extensions_.empty())
    return;

  content::BrowserThread::PostTask(
      rules_registry_thread_,
      FROM_HERE,
      base::Bind(&Inner::NotifyReadyOnRegistryThread, this));
}

void RulesRegistryStorageDelegate::Inner::ReadFromStorageOnRegistryThread(
    const std::string& extension_id, scoped_ptr<base::Value> value) {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (!rules_registry_)
    return;  // registry went away

  rules_registry_->AddRules(extension_id, RulesFromValue(value.get()));
}

void RulesRegistryStorageDelegate::Inner::NotifyReadyOnRegistryThread() {
  DCHECK(content::BrowserThread::CurrentlyOn(rules_registry_thread_));
  if (ready_)
    return;  // we've already notified our readiness

  ready_ = true;

  if (!rules_registry_)
    return;  // registry went away
  rules_registry_->OnReady();
}

}  // namespace extensions
<|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/ui/views/frame/browser_non_client_frame_view.h"

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"

namespace browser {

BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
    BrowserFrame* frame, BrowserView* browser_view) {
  if (browser_view->IsBrowserTypePopup() ||
      browser_view->IsBrowserTypePanel()) {
    // TODO(anicolao): implement popups for touch
    NOTIMPLEMENTED();
    return NULL;
  } else {
    return new TouchBrowserFrameView(frame, browser_view);
  }
}

}  // browser
<commit_msg>Use the non-touch popup frame instead of NULL.<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/ui/views/frame/browser_non_client_frame_view.h"

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h"

namespace browser {

BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
    BrowserFrame* frame, BrowserView* browser_view) {
  if (browser_view->IsBrowserTypePopup() ||
      browser_view->IsBrowserTypePanel()) {
    // TODO(anicolao): implement popups for touch
    NOTIMPLEMENTED();
    return new PopupNonClientFrameView(frame);
  } else {
    return new TouchBrowserFrameView(frame, browser_view);
  }
}

}  // browser
<|endoftext|>


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

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }
};

// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest, InstallAndUninstall) {
  host_resolver()->AddRule("www.example.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  std::string base_url = base::StringPrintf(
      "http://www.example.com:%u/files/extensions/",
      test_server()->host_port_pair().port());

  std::string testing_install_base_url = base_url;
  testing_install_base_url += "good.crx";
  InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());

  std::string page_url = base_url;
  page_url += "api_test/extension_gallery_install/test.html";
  ASSERT_TRUE(RunPageTest(page_url.c_str()));
}
<commit_msg>Re-disable ExtensionGalleryInstallApiTest.InstallAndUninstall that looks like it got accidentally re-enabled in r64517.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }
};

// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
                       MAYBE_InstallAndUninstall) {
  host_resolver()->AddRule("www.example.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  std::string base_url = base::StringPrintf(
      "http://www.example.com:%u/files/extensions/",
      test_server()->host_port_pair().port());

  std::string testing_install_base_url = base_url;
  testing_install_base_url += "good.crx";
  InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());

  std::string page_url = base_url;
  page_url += "api_test/extension_gallery_install/test.html";
  ASSERT_TRUE(RunPageTest(page_url.c_str()));
}
<|endoftext|>