<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 <cmath>
#include <set>
#include <vector>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "base/threading/thread.h"
#include "chrome/browser/device_orientation/orientation.h"
#include "chrome/browser/device_orientation/provider_impl.h"

namespace device_orientation {

ProviderImpl::ProviderImpl(const DataFetcherFactory factories[])
    : creator_loop_(MessageLoop::current()),
      ALLOW_THIS_IN_INITIALIZER_LIST(do_poll_method_factory_(this)) {
  for (const DataFetcherFactory* fp = factories; *fp; ++fp)
    factories_.push_back(*fp);
}

ProviderImpl::~ProviderImpl() {
}

void ProviderImpl::AddObserver(Observer* observer) {
  DCHECK(MessageLoop::current() == creator_loop_);

  observers_.insert(observer);
  if (observers_.size() == 1)
    Start();
  else
    observer->OnOrientationUpdate(last_notification_);
}

void ProviderImpl::RemoveObserver(Observer* observer) {
  DCHECK(MessageLoop::current() == creator_loop_);

  observers_.erase(observer);
  if (observers_.empty())
    Stop();
}

void ProviderImpl::Start() {
  DCHECK(MessageLoop::current() == creator_loop_);
  DCHECK(!polling_thread_.get());

  polling_thread_.reset(new base::Thread("Device orientation polling thread"));
  if (!polling_thread_->Start()) {
    LOG(ERROR) << "Failed to start device orientation polling thread";
    polling_thread_.reset();
    return;
  }
  ScheduleInitializePollingThread();
}

void ProviderImpl::Stop() {
  DCHECK(MessageLoop::current() == creator_loop_);
  polling_thread_.reset();
  data_fetcher_.reset();
}

void ProviderImpl::DoInitializePollingThread(
    std::vector<DataFetcherFactory> factories) {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  typedef std::vector<DataFetcherFactory>::const_iterator Iterator;
  for (Iterator i = factories_.begin(), e = factories_.end(); i != e; ++i) {
    DataFetcherFactory factory = *i;
    scoped_ptr<DataFetcher> fetcher(factory());
    Orientation orientation;

    if (fetcher.get() && fetcher->GetOrientation(&orientation)) {
      // Pass ownership of fetcher to provider_.
      data_fetcher_.swap(fetcher);
      last_orientation_ = orientation;

      // Notify observers.
      ScheduleDoNotify(orientation);

      // Start polling.
      ScheduleDoPoll();
      return;
    }
  }

  // When no orientation data can be provided.
  ScheduleDoNotify(Orientation::Empty());
}

void ProviderImpl::ScheduleInitializePollingThread() {
  DCHECK(MessageLoop::current() == creator_loop_);

  Task* task = NewRunnableMethod(this,
                                 &ProviderImpl::DoInitializePollingThread,
                                 factories_);
  MessageLoop* polling_loop = polling_thread_->message_loop();
  polling_loop->PostTask(FROM_HERE, task);
}

void ProviderImpl::DoNotify(const Orientation& orientation) {
  DCHECK(MessageLoop::current() == creator_loop_);

  last_notification_ = orientation;

  typedef std::set<Observer*>::const_iterator Iterator;
  for (Iterator i = observers_.begin(), e = observers_.end(); i != e; ++i)
    (*i)->OnOrientationUpdate(orientation);

  if (orientation.IsEmpty()) {
    // Notify observers about failure to provide data exactly once.
    observers_.clear();
    Stop();
  }
}

void ProviderImpl::ScheduleDoNotify(const Orientation& orientation) {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  Task* task = NewRunnableMethod(this, &ProviderImpl::DoNotify, orientation);
  creator_loop_->PostTask(FROM_HERE, task);
}

void ProviderImpl::DoPoll() {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  Orientation orientation;
  if (!data_fetcher_->GetOrientation(&orientation)) {
    LOG(ERROR) << "Failed to poll device orientation data fetcher.";

    ScheduleDoNotify(Orientation::Empty());
    return;
  }

  if (SignificantlyDifferent(orientation, last_orientation_)) {
    last_orientation_ = orientation;
    ScheduleDoNotify(orientation);
  }

  ScheduleDoPoll();
}

void ProviderImpl::ScheduleDoPoll() {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  Task* task = do_poll_method_factory_.NewRunnableMethod(&ProviderImpl::DoPoll);
  MessageLoop* polling_loop = polling_thread_->message_loop();
  polling_loop->PostDelayedTask(FROM_HERE, task, SamplingIntervalMs());
}

namespace {

bool IsElementSignificantlyDifferent(bool can_provide_element1,
                                     bool can_provide_element2,
                                     double element1,
                                     double element2) {
  const double kThreshold = 0.1;

  if (can_provide_element1 != can_provide_element2)
    return true;
  if (can_provide_element1 &&
      std::fabs(element1 - element2) >= kThreshold)
    return true;
  return false;
}
}  // namespace

// Returns true if two orientations are considered different enough that
// observers should be notified of the new orientation.
bool ProviderImpl::SignificantlyDifferent(const Orientation& o1,
                                          const Orientation& o2) {
  return IsElementSignificantlyDifferent(o1.can_provide_alpha_,
                                         o2.can_provide_alpha_,
                                         o1.alpha_,
                                         o2.alpha_) ||
      IsElementSignificantlyDifferent(o1.can_provide_beta_,
                                         o2.can_provide_beta_,
                                         o1.beta_,
                                         o2.beta_) ||
      IsElementSignificantlyDifferent(o1.can_provide_gamma_,
                                         o2.can_provide_gamma_,
                                         o1.gamma_,
                                         o2.gamma_);
}

int ProviderImpl::SamplingIntervalMs() const {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());
  DCHECK(data_fetcher_.get());

  // TODO(erg): There used to be unused code here, that called a default
  // implementation on the DataFetcherInterface that was never defined. I'm
  // removing unused methods from headers.
  return kDesiredSamplingIntervalMs;
}

}  // namespace device_orientation
<commit_msg>Device Orientation: suppress assert about thread join from IO thread.<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 <cmath>
#include <set>
#include <vector>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/device_orientation/orientation.h"
#include "chrome/browser/device_orientation/provider_impl.h"

namespace device_orientation {

ProviderImpl::ProviderImpl(const DataFetcherFactory factories[])
    : creator_loop_(MessageLoop::current()),
      ALLOW_THIS_IN_INITIALIZER_LIST(do_poll_method_factory_(this)) {
  for (const DataFetcherFactory* fp = factories; *fp; ++fp)
    factories_.push_back(*fp);
}

ProviderImpl::~ProviderImpl() {
}

void ProviderImpl::AddObserver(Observer* observer) {
  DCHECK(MessageLoop::current() == creator_loop_);

  observers_.insert(observer);
  if (observers_.size() == 1)
    Start();
  else
    observer->OnOrientationUpdate(last_notification_);
}

void ProviderImpl::RemoveObserver(Observer* observer) {
  DCHECK(MessageLoop::current() == creator_loop_);

  observers_.erase(observer);
  if (observers_.empty())
    Stop();
}

void ProviderImpl::Start() {
  DCHECK(MessageLoop::current() == creator_loop_);
  DCHECK(!polling_thread_.get());

  polling_thread_.reset(new base::Thread("Device orientation polling thread"));
  if (!polling_thread_->Start()) {
    LOG(ERROR) << "Failed to start device orientation polling thread";
    polling_thread_.reset();
    return;
  }
  ScheduleInitializePollingThread();
}

void ProviderImpl::Stop() {
  DCHECK(MessageLoop::current() == creator_loop_);

  // TODO(hans): Don't join the thread. See crbug.com/72286.
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  polling_thread_.reset();
  data_fetcher_.reset();
}

void ProviderImpl::DoInitializePollingThread(
    std::vector<DataFetcherFactory> factories) {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  typedef std::vector<DataFetcherFactory>::const_iterator Iterator;
  for (Iterator i = factories_.begin(), e = factories_.end(); i != e; ++i) {
    DataFetcherFactory factory = *i;
    scoped_ptr<DataFetcher> fetcher(factory());
    Orientation orientation;

    if (fetcher.get() && fetcher->GetOrientation(&orientation)) {
      // Pass ownership of fetcher to provider_.
      data_fetcher_.swap(fetcher);
      last_orientation_ = orientation;

      // Notify observers.
      ScheduleDoNotify(orientation);

      // Start polling.
      ScheduleDoPoll();
      return;
    }
  }

  // When no orientation data can be provided.
  ScheduleDoNotify(Orientation::Empty());
}

void ProviderImpl::ScheduleInitializePollingThread() {
  DCHECK(MessageLoop::current() == creator_loop_);

  Task* task = NewRunnableMethod(this,
                                 &ProviderImpl::DoInitializePollingThread,
                                 factories_);
  MessageLoop* polling_loop = polling_thread_->message_loop();
  polling_loop->PostTask(FROM_HERE, task);
}

void ProviderImpl::DoNotify(const Orientation& orientation) {
  DCHECK(MessageLoop::current() == creator_loop_);

  last_notification_ = orientation;

  typedef std::set<Observer*>::const_iterator Iterator;
  for (Iterator i = observers_.begin(), e = observers_.end(); i != e; ++i)
    (*i)->OnOrientationUpdate(orientation);

  if (orientation.IsEmpty()) {
    // Notify observers about failure to provide data exactly once.
    observers_.clear();
    Stop();
  }
}

void ProviderImpl::ScheduleDoNotify(const Orientation& orientation) {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  Task* task = NewRunnableMethod(this, &ProviderImpl::DoNotify, orientation);
  creator_loop_->PostTask(FROM_HERE, task);
}

void ProviderImpl::DoPoll() {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  Orientation orientation;
  if (!data_fetcher_->GetOrientation(&orientation)) {
    LOG(ERROR) << "Failed to poll device orientation data fetcher.";

    ScheduleDoNotify(Orientation::Empty());
    return;
  }

  if (SignificantlyDifferent(orientation, last_orientation_)) {
    last_orientation_ = orientation;
    ScheduleDoNotify(orientation);
  }

  ScheduleDoPoll();
}

void ProviderImpl::ScheduleDoPoll() {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());

  Task* task = do_poll_method_factory_.NewRunnableMethod(&ProviderImpl::DoPoll);
  MessageLoop* polling_loop = polling_thread_->message_loop();
  polling_loop->PostDelayedTask(FROM_HERE, task, SamplingIntervalMs());
}

namespace {

bool IsElementSignificantlyDifferent(bool can_provide_element1,
                                     bool can_provide_element2,
                                     double element1,
                                     double element2) {
  const double kThreshold = 0.1;

  if (can_provide_element1 != can_provide_element2)
    return true;
  if (can_provide_element1 &&
      std::fabs(element1 - element2) >= kThreshold)
    return true;
  return false;
}
}  // namespace

// Returns true if two orientations are considered different enough that
// observers should be notified of the new orientation.
bool ProviderImpl::SignificantlyDifferent(const Orientation& o1,
                                          const Orientation& o2) {
  return IsElementSignificantlyDifferent(o1.can_provide_alpha_,
                                         o2.can_provide_alpha_,
                                         o1.alpha_,
                                         o2.alpha_) ||
      IsElementSignificantlyDifferent(o1.can_provide_beta_,
                                         o2.can_provide_beta_,
                                         o1.beta_,
                                         o2.beta_) ||
      IsElementSignificantlyDifferent(o1.can_provide_gamma_,
                                         o2.can_provide_gamma_,
                                         o1.gamma_,
                                         o2.gamma_);
}

int ProviderImpl::SamplingIntervalMs() const {
  DCHECK(MessageLoop::current() == polling_thread_->message_loop());
  DCHECK(data_fetcher_.get());

  // TODO(erg): There used to be unused code here, that called a default
  // implementation on the DataFetcherInterface that was never defined. I'm
  // removing unused methods from headers.
  return kDesiredSamplingIntervalMs;
}

}  // namespace device_orientation
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/profile.h"

// Flaky, http://crbug.com/42314.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Notifications) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_;
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest"))
      << message_;
  browser()->profile()->GetDesktopNotificationService()
      ->GrantPermission(GURL(
          "chrome-extension://peoadpeiejnhkmpaakpnompolbglelel"));
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs"))
      << message_;
#endif
}

<commit_msg>Disable a flaky test that seems to completely blow up with some frequency on the mac bots and seems to cause a ripple in hosing the bot in general. BUG=42314,50060 TEST=Mac test bots stay greener Review URL: http://codereview.chromium.org/2834069<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/profile.h"

// Fails and hoses bot, http://crbug.com/50060.
// Flaky, http://crbug.com/42314.
#if defined(OS_MACOSX)
#define MAYBE_Notifications DISABLED_Notifications
#else
#define MAYBE_Notifications FLAKY_Notifications
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Notifications) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_;
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest"))
      << message_;
  browser()->profile()->GetDesktopNotificationService()
      ->GrantPermission(GURL(
          "chrome-extension://peoadpeiejnhkmpaakpnompolbglelel"));
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs"))
      << message_;
#endif
}

<|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/printing/printing_message_filter.h"

#include "base/process_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"

#if defined(OS_CHROMEOS)
#include <fcntl.h>

#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#else
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#endif

namespace {

#if defined(OS_CHROMEOS)
typedef std::map<int, FilePath> SequenceToPathMap;

struct PrintingSequencePathMap {
  SequenceToPathMap map;
  int sequence;
};

// No locking, only access on the FILE thread.
static base::LazyInstance<PrintingSequencePathMap>
    g_printing_file_descriptor_map(base::LINKER_INITIALIZED);
#endif

void RenderParamsFromPrintSettings(const printing::PrintSettings& settings,
                                   ViewMsg_Print_Params* params) {
  params->page_size = settings.page_setup_device_units().physical_size();
  params->printable_size.SetSize(
      settings.page_setup_device_units().content_area().width(),
      settings.page_setup_device_units().content_area().height());
  params->margin_top = settings.page_setup_device_units().content_area().x();
  params->margin_left = settings.page_setup_device_units().content_area().y();
  params->dpi = settings.dpi();
  // Currently hardcoded at 1.25. See PrintSettings' constructor.
  params->min_shrink = settings.min_shrink;
  // Currently hardcoded at 2.0. See PrintSettings' constructor.
  params->max_shrink = settings.max_shrink;
  // Currently hardcoded at 72dpi. See PrintSettings' constructor.
  params->desired_dpi = settings.desired_dpi;
  // Always use an invalid cookie.
  params->document_cookie = 0;
  params->selection_only = settings.selection_only;
  params->supports_alpha_blend = settings.supports_alpha_blend();
}

}  // namespace

PrintingMessageFilter::PrintingMessageFilter()
    : print_job_manager_(g_browser_process->print_job_manager()) {
#if defined(OS_CHROMEOS)
  cloud_print_enabled_ = true;
#else
  cloud_print_enabled_ = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableCloudPrint);
#endif
}

PrintingMessageFilter::~PrintingMessageFilter() {
}

void PrintingMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_CHROMEOS)
  if (message.type() == ViewHostMsg_AllocateTempFileForPrinting::ID ||
      message.type() == ViewHostMsg_TempFileForPrintingWritten::ID) {
    *thread = BrowserThread::FILE;
  }
#endif
}

bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message,
                                              bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(PrintingMessageFilter, message, *message_was_ok)
#if defined(OS_WIN)
    IPC_MESSAGE_HANDLER(ViewHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS)
    IPC_MESSAGE_HANDLER(ViewHostMsg_AllocateTempFileForPrinting,
                        OnAllocateTempFileForPrinting)
    IPC_MESSAGE_HANDLER(ViewHostMsg_TempFileForPrintingWritten,
                        OnTempFileForPrintingWritten)
#endif
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetDefaultPrintSettings,
                                    OnGetDefaultPrintSettings)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_ScriptedPrint, OnScriptedPrint)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_UpdatePrintSettings,
                                    OnUpdatePrintSettings)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
    base::SharedMemoryHandle renderer_handle,
    base::SharedMemoryHandle* browser_handle) {
  // Duplicate the handle in this process right now so the memory is kept alive
  // (even if it is not mapped)
  base::SharedMemory shared_buf(renderer_handle, true, peer_handle());
  shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif

#if defined(OS_CHROMEOS)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
    base::FileDescriptor* temp_file_fd, int* sequence_number) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  temp_file_fd->fd = *sequence_number = -1;
  temp_file_fd->auto_close = false;

  SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
  *sequence_number = g_printing_file_descriptor_map.Get().sequence++;

  FilePath path;
  if (file_util::CreateTemporaryFile(&path)) {
    int fd = open(path.value().c_str(), O_WRONLY);
    if (fd >= 0) {
      SequenceToPathMap::iterator it = map->find(*sequence_number);
      if (it != map->end()) {
        NOTREACHED() << "Sequence number already in use. seq=" <<
            *sequence_number;
      } else {
        (*map)[*sequence_number] = path;
        temp_file_fd->fd = fd;
        temp_file_fd->auto_close = true;
      }
    }
  }
}

void PrintingMessageFilter::OnTempFileForPrintingWritten(int sequence_number) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
  SequenceToPathMap::iterator it = map->find(sequence_number);
  if (it == map->end()) {
    NOTREACHED() << "Got a sequence that we didn't pass to the "
                    "renderer: " << sequence_number;
    return;
  }

  if (cloud_print_enabled_)
    PrintDialogCloud::CreatePrintDialogForPdf(it->second, string16(), true);
  else
    NOTIMPLEMENTED();

  // Erase the entry in the map.
  map->erase(it);
}
#endif  // defined(OS_CHROMEOS)

void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
  scoped_refptr<printing::PrinterQuery> printer_query;
  if (!print_job_manager_->printing_enabled()) {
    // Reply with NULL query.
    OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
    return;
  }

  print_job_manager_->PopPrinterQuery(0, &printer_query);
  if (!printer_query.get()) {
    printer_query = new printing::PrinterQuery;
  }

  CancelableTask* task = NewRunnableMethod(
      this,
      &PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
      printer_query,
      reply_msg);
  // Loads default settings. This is asynchronous, only the IPC message sender
  // will hang until the settings are retrieved.
  printer_query->GetSettings(printing::PrinterQuery::DEFAULTS,
                             NULL,
                             0,
                             false,
                             true,
                             task);
}

void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  ViewMsg_Print_Params params;
  if (!printer_query.get() ||
      printer_query->last_status() != printing::PrintingContext::OK) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params);
    params.document_cookie = printer_query->cookie();
  }
  ViewHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If printing was enabled.
  if (printer_query.get()) {
    // If user hasn't cancelled.
    if (printer_query->cookie() && printer_query->settings().dpi()) {
      print_job_manager_->QueuePrinterQuery(printer_query.get());
    } else {
      printer_query->StopWorker();
    }
  }
}

void PrintingMessageFilter::OnScriptedPrint(
    const ViewHostMsg_ScriptedPrint_Params& params,
    IPC::Message* reply_msg) {
  gfx::NativeView host_view =
      gfx::NativeViewFromIdInBrowser(params.host_window_id);

  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager_->PopPrinterQuery(params.cookie, &printer_query);
  if (!printer_query.get()) {
    printer_query = new printing::PrinterQuery;
  }

  CancelableTask* task = NewRunnableMethod(
      this,
      &PrintingMessageFilter::OnScriptedPrintReply,
      printer_query,
      params.routing_id,
      reply_msg);

  printer_query->GetSettings(printing::PrinterQuery::ASK_USER,
                             host_view,
                             params.expected_pages_count,
                             params.has_selection,
                             params.use_overlays,
                             task);
}

void PrintingMessageFilter::OnScriptedPrintReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    int routing_id,
    IPC::Message* reply_msg) {
  ViewMsg_PrintPages_Params params;
  if (printer_query->last_status() != printing::PrintingContext::OK ||
      !printer_query->settings().dpi()) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
    params.params.document_cookie = printer_query->cookie();
    params.pages =
        printing::PageRange::GetPages(printer_query->settings().ranges);
  }
  ViewHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  if (params.params.dpi && params.params.document_cookie) {
    print_job_manager_->QueuePrinterQuery(printer_query.get());
  } else {
    printer_query->StopWorker();
  }
}

void PrintingMessageFilter::OnUpdatePrintSettings(
    int document_cookie, const DictionaryValue& job_settings,
    IPC::Message* reply_msg) {
  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager_->PopPrinterQuery(document_cookie, &printer_query);
  if (printer_query.get()) {
    CancelableTask* task = NewRunnableMethod(
        this,
        &PrintingMessageFilter::OnUpdatePrintSettingsReply,
        printer_query,
        reply_msg);
    printer_query->SetSettings(job_settings, task);
  }
}

void PrintingMessageFilter::OnUpdatePrintSettingsReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  ViewMsg_Print_Params params;
  if (!printer_query.get() ||
      printer_query->last_status() != printing::PrintingContext::OK) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params);
    params.document_cookie = printer_query->cookie();
  }
  ViewHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If printing was enabled.
  if (printer_query.get()) {
    // If user hasn't cancelled.
    if (printer_query->cookie() && printer_query->settings().dpi()) {
      print_job_manager_->QueuePrinterQuery(printer_query.get());
    } else {
      printer_query->StopWorker();
    }
  }
}

<commit_msg>Printing: Remove a check for a condition that's always true.<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/printing/printing_message_filter.h"

#include "base/process_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"

#if defined(OS_CHROMEOS)
#include <fcntl.h>

#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#else
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#endif

namespace {

#if defined(OS_CHROMEOS)
typedef std::map<int, FilePath> SequenceToPathMap;

struct PrintingSequencePathMap {
  SequenceToPathMap map;
  int sequence;
};

// No locking, only access on the FILE thread.
static base::LazyInstance<PrintingSequencePathMap>
    g_printing_file_descriptor_map(base::LINKER_INITIALIZED);
#endif

void RenderParamsFromPrintSettings(const printing::PrintSettings& settings,
                                   ViewMsg_Print_Params* params) {
  params->page_size = settings.page_setup_device_units().physical_size();
  params->printable_size.SetSize(
      settings.page_setup_device_units().content_area().width(),
      settings.page_setup_device_units().content_area().height());
  params->margin_top = settings.page_setup_device_units().content_area().x();
  params->margin_left = settings.page_setup_device_units().content_area().y();
  params->dpi = settings.dpi();
  // Currently hardcoded at 1.25. See PrintSettings' constructor.
  params->min_shrink = settings.min_shrink;
  // Currently hardcoded at 2.0. See PrintSettings' constructor.
  params->max_shrink = settings.max_shrink;
  // Currently hardcoded at 72dpi. See PrintSettings' constructor.
  params->desired_dpi = settings.desired_dpi;
  // Always use an invalid cookie.
  params->document_cookie = 0;
  params->selection_only = settings.selection_only;
  params->supports_alpha_blend = settings.supports_alpha_blend();
}

}  // namespace

PrintingMessageFilter::PrintingMessageFilter()
    : print_job_manager_(g_browser_process->print_job_manager()) {
#if defined(OS_CHROMEOS)
  cloud_print_enabled_ = true;
#else
  cloud_print_enabled_ = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableCloudPrint);
#endif
}

PrintingMessageFilter::~PrintingMessageFilter() {
}

void PrintingMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_CHROMEOS)
  if (message.type() == ViewHostMsg_AllocateTempFileForPrinting::ID ||
      message.type() == ViewHostMsg_TempFileForPrintingWritten::ID) {
    *thread = BrowserThread::FILE;
  }
#endif
}

bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message,
                                              bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(PrintingMessageFilter, message, *message_was_ok)
#if defined(OS_WIN)
    IPC_MESSAGE_HANDLER(ViewHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS)
    IPC_MESSAGE_HANDLER(ViewHostMsg_AllocateTempFileForPrinting,
                        OnAllocateTempFileForPrinting)
    IPC_MESSAGE_HANDLER(ViewHostMsg_TempFileForPrintingWritten,
                        OnTempFileForPrintingWritten)
#endif
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetDefaultPrintSettings,
                                    OnGetDefaultPrintSettings)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_ScriptedPrint, OnScriptedPrint)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_UpdatePrintSettings,
                                    OnUpdatePrintSettings)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
    base::SharedMemoryHandle renderer_handle,
    base::SharedMemoryHandle* browser_handle) {
  // Duplicate the handle in this process right now so the memory is kept alive
  // (even if it is not mapped)
  base::SharedMemory shared_buf(renderer_handle, true, peer_handle());
  shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif

#if defined(OS_CHROMEOS)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
    base::FileDescriptor* temp_file_fd, int* sequence_number) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  temp_file_fd->fd = *sequence_number = -1;
  temp_file_fd->auto_close = false;

  SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
  *sequence_number = g_printing_file_descriptor_map.Get().sequence++;

  FilePath path;
  if (file_util::CreateTemporaryFile(&path)) {
    int fd = open(path.value().c_str(), O_WRONLY);
    if (fd >= 0) {
      SequenceToPathMap::iterator it = map->find(*sequence_number);
      if (it != map->end()) {
        NOTREACHED() << "Sequence number already in use. seq=" <<
            *sequence_number;
      } else {
        (*map)[*sequence_number] = path;
        temp_file_fd->fd = fd;
        temp_file_fd->auto_close = true;
      }
    }
  }
}

void PrintingMessageFilter::OnTempFileForPrintingWritten(int sequence_number) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
  SequenceToPathMap::iterator it = map->find(sequence_number);
  if (it == map->end()) {
    NOTREACHED() << "Got a sequence that we didn't pass to the "
                    "renderer: " << sequence_number;
    return;
  }

  if (cloud_print_enabled_)
    PrintDialogCloud::CreatePrintDialogForPdf(it->second, string16(), true);
  else
    NOTIMPLEMENTED();

  // Erase the entry in the map.
  map->erase(it);
}
#endif  // defined(OS_CHROMEOS)

void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
  scoped_refptr<printing::PrinterQuery> printer_query;
  if (!print_job_manager_->printing_enabled()) {
    // Reply with NULL query.
    OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
    return;
  }

  print_job_manager_->PopPrinterQuery(0, &printer_query);
  if (!printer_query.get()) {
    printer_query = new printing::PrinterQuery;
  }

  CancelableTask* task = NewRunnableMethod(
      this,
      &PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
      printer_query,
      reply_msg);
  // Loads default settings. This is asynchronous, only the IPC message sender
  // will hang until the settings are retrieved.
  printer_query->GetSettings(printing::PrinterQuery::DEFAULTS,
                             NULL,
                             0,
                             false,
                             true,
                             task);
}

void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  ViewMsg_Print_Params params;
  if (!printer_query.get() ||
      printer_query->last_status() != printing::PrintingContext::OK) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params);
    params.document_cookie = printer_query->cookie();
  }
  ViewHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If printing was enabled.
  if (printer_query.get()) {
    // If user hasn't cancelled.
    if (printer_query->cookie() && printer_query->settings().dpi()) {
      print_job_manager_->QueuePrinterQuery(printer_query.get());
    } else {
      printer_query->StopWorker();
    }
  }
}

void PrintingMessageFilter::OnScriptedPrint(
    const ViewHostMsg_ScriptedPrint_Params& params,
    IPC::Message* reply_msg) {
  gfx::NativeView host_view =
      gfx::NativeViewFromIdInBrowser(params.host_window_id);

  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager_->PopPrinterQuery(params.cookie, &printer_query);
  if (!printer_query.get()) {
    printer_query = new printing::PrinterQuery;
  }

  CancelableTask* task = NewRunnableMethod(
      this,
      &PrintingMessageFilter::OnScriptedPrintReply,
      printer_query,
      params.routing_id,
      reply_msg);

  printer_query->GetSettings(printing::PrinterQuery::ASK_USER,
                             host_view,
                             params.expected_pages_count,
                             params.has_selection,
                             params.use_overlays,
                             task);
}

void PrintingMessageFilter::OnScriptedPrintReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    int routing_id,
    IPC::Message* reply_msg) {
  ViewMsg_PrintPages_Params params;
  if (printer_query->last_status() != printing::PrintingContext::OK ||
      !printer_query->settings().dpi()) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
    params.params.document_cookie = printer_query->cookie();
    params.pages =
        printing::PageRange::GetPages(printer_query->settings().ranges);
  }
  ViewHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  if (params.params.dpi && params.params.document_cookie) {
    print_job_manager_->QueuePrinterQuery(printer_query.get());
  } else {
    printer_query->StopWorker();
  }
}

void PrintingMessageFilter::OnUpdatePrintSettings(
    int document_cookie, const DictionaryValue& job_settings,
    IPC::Message* reply_msg) {
  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager_->PopPrinterQuery(document_cookie, &printer_query);
  if (printer_query.get()) {
    CancelableTask* task = NewRunnableMethod(
        this,
        &PrintingMessageFilter::OnUpdatePrintSettingsReply,
        printer_query,
        reply_msg);
    printer_query->SetSettings(job_settings, task);
  }
}

void PrintingMessageFilter::OnUpdatePrintSettingsReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  ViewMsg_Print_Params params;
  if (printer_query->last_status() != printing::PrintingContext::OK) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params);
    params.document_cookie = printer_query->cookie();
  }
  ViewHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If user hasn't cancelled.
  if (printer_query->cookie() && printer_query->settings().dpi())
    print_job_manager_->QueuePrinterQuery(printer_query.get());
  else
    printer_query->StopWorker();
}
<|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/webui/hung_renderer_dialog_ui.h"

#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "chrome/browser/profiles/profile.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"

HungRendererDialogUI::HungRendererDialogUI(TabContents* contents)
    : HtmlDialogUI(contents) {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIHungRendererDialogHost);

  source->AddLocalizedString("title", IDS_BROWSER_HANGMONITOR_RENDERER_TITLE);
  source->AddLocalizedString("explanation", IDS_BROWSER_HANGMONITOR_RENDERER);
  source->AddLocalizedString("kill", IDS_BROWSER_HANGMONITOR_RENDERER_END);
  source->AddLocalizedString("wait", IDS_BROWSER_HANGMONITOR_RENDERER_WAIT);

  // Set the json path.
  source->set_json_path("strings.js");

  // Add required resources.
  source->add_resource_path("hung_renderer_dialog.js",
                            IDR_HUNG_RENDERER_DIALOG_JS);
  source->add_resource_path("hung_renderer_dialog.css",
                            IDR_HUNG_RENDERER_DIALOG_CSS);

  // Set default resource.
  source->set_default_resource(IDR_HUNG_RENDERER_DIALOG_HTML);

  Profile* profile = Profile::FromBrowserContext(contents->browser_context());
  profile->GetChromeURLDataManager()->AddDataSource(source);
}

HungRendererDialogUI::~HungRendererDialogUI() {
}
<commit_msg>Add a theme source for the WebUI hung renderer dialog.<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/webui/hung_renderer_dialog_ui.h"

#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "chrome/browser/profiles/profile.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"

HungRendererDialogUI::HungRendererDialogUI(TabContents* contents)
    : HtmlDialogUI(contents) {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIHungRendererDialogHost);

  source->AddLocalizedString("title", IDS_BROWSER_HANGMONITOR_RENDERER_TITLE);
  source->AddLocalizedString("explanation", IDS_BROWSER_HANGMONITOR_RENDERER);
  source->AddLocalizedString("kill", IDS_BROWSER_HANGMONITOR_RENDERER_END);
  source->AddLocalizedString("wait", IDS_BROWSER_HANGMONITOR_RENDERER_WAIT);

  // Set the json path.
  source->set_json_path("strings.js");

  // Add required resources.
  source->add_resource_path("hung_renderer_dialog.js",
                            IDR_HUNG_RENDERER_DIALOG_JS);
  source->add_resource_path("hung_renderer_dialog.css",
                            IDR_HUNG_RENDERER_DIALOG_CSS);

  // Set default resource.
  source->set_default_resource(IDR_HUNG_RENDERER_DIALOG_HTML);

  Profile* profile = Profile::FromBrowserContext(contents->browser_context());
  profile->GetChromeURLDataManager()->AddDataSource(source);

  // Set up the chrome://theme/ source.
  ThemeSource* theme = new ThemeSource(profile);
  profile->GetChromeURLDataManager()->AddDataSource(theme);
}

HungRendererDialogUI::~HungRendererDialogUI() {
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/common/appcache/appcache_dispatcher_host.h"

#include "chrome/browser/renderer_host/browser_render_process_host.h"
// TODO(eroman): uh oh, depending on stuff outside of common/
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/common/appcache/chrome_appcache_service.h"
#include "chrome/common/render_messages.h"

AppCacheDispatcherHost::AppCacheDispatcherHost(
    URLRequestContextGetter* request_context_getter)
        : request_context_getter_(request_context_getter),
          process_handle_(0) {
  DCHECK(request_context_getter_.get());
}

void AppCacheDispatcherHost::Initialize(IPC::Message::Sender* sender,
    int process_id, base::ProcessHandle process_handle) {
  DCHECK(sender);
  DCHECK(process_handle && !process_handle_);
  process_handle_ = process_handle;

  // Get the AppCacheService (it can only be accessed from IO thread).
  if (request_context_getter_.get()) {
    URLRequestContext* context =
        request_context_getter_->GetURLRequestContext();
    appcache_service_ =
        static_cast<ChromeURLRequestContext*>(context)->appcache_service();
    request_context_getter_ = NULL;
  }

  frontend_proxy_.set_sender(sender);
  if (appcache_service_.get()) {
    backend_impl_.Initialize(
        appcache_service_.get(), &frontend_proxy_, process_id);
    get_status_callback_.reset(
        NewCallback(this, &AppCacheDispatcherHost::GetStatusCallback));
    start_update_callback_.reset(
        NewCallback(this, &AppCacheDispatcherHost::StartUpdateCallback));
    swap_cache_callback_.reset(
        NewCallback(this, &AppCacheDispatcherHost::SwapCacheCallback));
  }
}

bool AppCacheDispatcherHost::OnMessageReceived(const IPC::Message& msg,
                                               bool *msg_ok) {
  DCHECK(process_handle_);
  *msg_ok = true;
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(AppCacheDispatcherHost, msg, *msg_ok)
    IPC_MESSAGE_HANDLER(AppCacheMsg_RegisterHost, OnRegisterHost);
    IPC_MESSAGE_HANDLER(AppCacheMsg_UnregisterHost, OnUnregisterHost);
    IPC_MESSAGE_HANDLER(AppCacheMsg_SelectCache, OnSelectCache);
    IPC_MESSAGE_HANDLER(AppCacheMsg_MarkAsForeignEntry, OnMarkAsForeignEntry);
    IPC_MESSAGE_HANDLER_DELAY_REPLY(AppCacheMsg_GetStatus, OnGetStatus);
    IPC_MESSAGE_HANDLER_DELAY_REPLY(AppCacheMsg_StartUpdate, OnStartUpdate);
    IPC_MESSAGE_HANDLER_DELAY_REPLY(AppCacheMsg_SwapCache, OnSwapCache);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP_EX()
  return handled;
}

void AppCacheDispatcherHost::OnRegisterHost(int host_id) {
  if (appcache_service_.get()) {
    if (!backend_impl_.RegisterHost(host_id)) {
      ReceivedBadMessage(AppCacheMsg_RegisterHost::ID);
    }
  }
}

void AppCacheDispatcherHost::OnUnregisterHost(int host_id) {
  if (appcache_service_.get()) {
    if (!backend_impl_.UnregisterHost(host_id)) {
      ReceivedBadMessage(AppCacheMsg_UnregisterHost::ID);
    }
  }
}

void AppCacheDispatcherHost::OnSelectCache(
    int host_id, const GURL& document_url,
    int64 cache_document_was_loaded_from,
    const GURL& opt_manifest_url) {
  if (appcache_service_.get()) {
    if (!backend_impl_.SelectCache(host_id, document_url,
                                   cache_document_was_loaded_from,
                                   opt_manifest_url)) {
      ReceivedBadMessage(AppCacheMsg_SelectCache::ID);
    }
  } else {
    frontend_proxy_.OnCacheSelected(
        host_id, appcache::kNoCacheId, appcache::UNCACHED);
  }
}

void AppCacheDispatcherHost::OnMarkAsForeignEntry(
    int host_id, const GURL& document_url,
    int64 cache_document_was_loaded_from) {
  if (appcache_service_.get()) {
    if (!backend_impl_.MarkAsForeignEntry(host_id, document_url,
                                          cache_document_was_loaded_from)) {
      ReceivedBadMessage(AppCacheMsg_MarkAsForeignEntry::ID);
    }
  }
}

void AppCacheDispatcherHost::OnGetStatus(int host_id,
                                         IPC::Message* reply_msg) {
  if (pending_reply_msg_.get()) {
    ReceivedBadMessage(AppCacheMsg_GetStatus::ID);
    delete reply_msg;
    return;
  }

  pending_reply_msg_.reset(reply_msg);
  if (appcache_service_.get()) {
    if (!backend_impl_.GetStatusWithCallback(
            host_id, get_status_callback_.get(), reply_msg)) {
      ReceivedBadMessage(AppCacheMsg_GetStatus::ID);
    }
    return;
  }

  GetStatusCallback(appcache::UNCACHED, reply_msg);
}

void AppCacheDispatcherHost::OnStartUpdate(int host_id,
                                           IPC::Message* reply_msg) {
  if (pending_reply_msg_.get()) {
    ReceivedBadMessage(AppCacheMsg_StartUpdate::ID);
    delete reply_msg;
    return;
  }

  pending_reply_msg_.reset(reply_msg);
  if (appcache_service_.get()) {
    if (!backend_impl_.StartUpdateWithCallback(
            host_id, start_update_callback_.get(), reply_msg)) {
      ReceivedBadMessage(AppCacheMsg_StartUpdate::ID);
    }
    return;
  }

  StartUpdateCallback(false, reply_msg);
}

void AppCacheDispatcherHost::OnSwapCache(int host_id,
                                         IPC::Message* reply_msg) {
  if (pending_reply_msg_.get()) {
    ReceivedBadMessage(AppCacheMsg_SwapCache::ID);
    delete reply_msg;
    return;
  }

  pending_reply_msg_.reset(reply_msg);
  if (appcache_service_.get()) {
    if (!backend_impl_.SwapCacheWithCallback(
            host_id, swap_cache_callback_.get(), reply_msg)) {
      ReceivedBadMessage(AppCacheMsg_SwapCache::ID);
    }
    return;
  }

  SwapCacheCallback(false, reply_msg);
}

void AppCacheDispatcherHost::GetStatusCallback(
    appcache::Status status, void* param) {
  IPC::Message* reply_msg = reinterpret_cast<IPC::Message*>(param);
  DCHECK(reply_msg == pending_reply_msg_.get());
  AppCacheMsg_GetStatus::WriteReplyParams(reply_msg, status);
  frontend_proxy_.sender()->Send(pending_reply_msg_.release());
}

void AppCacheDispatcherHost::StartUpdateCallback(bool result, void* param) {
  IPC::Message* reply_msg = reinterpret_cast<IPC::Message*>(param);
  DCHECK(reply_msg == pending_reply_msg_.get());
  AppCacheMsg_StartUpdate::WriteReplyParams(reply_msg, result);
  frontend_proxy_.sender()->Send(pending_reply_msg_.release());
}

void AppCacheDispatcherHost::SwapCacheCallback(bool result, void* param) {
  IPC::Message* reply_msg = reinterpret_cast<IPC::Message*>(param);
  DCHECK(reply_msg == pending_reply_msg_.get());
  AppCacheMsg_SwapCache::WriteReplyParams(reply_msg, result);
  frontend_proxy_.sender()->Send(pending_reply_msg_.release());
}

void AppCacheDispatcherHost::ReceivedBadMessage(uint32 msg_type) {
  // TODO(michaeln): Consider gathering UMA stats
  // http://code.google.com/p/chromium/issues/detail?id=24634
  BrowserRenderProcessHost::BadMessageTerminateProcess(
      msg_type, process_handle_);
}
<commit_msg>Don't defend against Initialize being called twice, that should not happen. <commit_after>// Copyright (c) 2009 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/common/appcache/appcache_dispatcher_host.h"

#include "chrome/browser/renderer_host/browser_render_process_host.h"
// TODO(eroman): uh oh, depending on stuff outside of common/
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/common/appcache/chrome_appcache_service.h"
#include "chrome/common/render_messages.h"

AppCacheDispatcherHost::AppCacheDispatcherHost(
    URLRequestContextGetter* request_context_getter)
        : request_context_getter_(request_context_getter),
          process_handle_(0) {
  DCHECK(request_context_getter_.get());
}

void AppCacheDispatcherHost::Initialize(IPC::Message::Sender* sender,
    int process_id, base::ProcessHandle process_handle) {
  DCHECK(sender);
  DCHECK(process_handle && !process_handle_);
  DCHECK(request_context_getter_.get());

  process_handle_ = process_handle;

  // Get the AppCacheService (it can only be accessed from IO thread).
  URLRequestContext* context = request_context_getter_->GetURLRequestContext();
  appcache_service_ =
      static_cast<ChromeURLRequestContext*>(context)->appcache_service();
  request_context_getter_ = NULL;

  frontend_proxy_.set_sender(sender);
  if (appcache_service_.get()) {
    backend_impl_.Initialize(
        appcache_service_.get(), &frontend_proxy_, process_id);
    get_status_callback_.reset(
        NewCallback(this, &AppCacheDispatcherHost::GetStatusCallback));
    start_update_callback_.reset(
        NewCallback(this, &AppCacheDispatcherHost::StartUpdateCallback));
    swap_cache_callback_.reset(
        NewCallback(this, &AppCacheDispatcherHost::SwapCacheCallback));
  }
}

bool AppCacheDispatcherHost::OnMessageReceived(const IPC::Message& msg,
                                               bool *msg_ok) {
  DCHECK(process_handle_);
  *msg_ok = true;
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(AppCacheDispatcherHost, msg, *msg_ok)
    IPC_MESSAGE_HANDLER(AppCacheMsg_RegisterHost, OnRegisterHost);
    IPC_MESSAGE_HANDLER(AppCacheMsg_UnregisterHost, OnUnregisterHost);
    IPC_MESSAGE_HANDLER(AppCacheMsg_SelectCache, OnSelectCache);
    IPC_MESSAGE_HANDLER(AppCacheMsg_MarkAsForeignEntry, OnMarkAsForeignEntry);
    IPC_MESSAGE_HANDLER_DELAY_REPLY(AppCacheMsg_GetStatus, OnGetStatus);
    IPC_MESSAGE_HANDLER_DELAY_REPLY(AppCacheMsg_StartUpdate, OnStartUpdate);
    IPC_MESSAGE_HANDLER_DELAY_REPLY(AppCacheMsg_SwapCache, OnSwapCache);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP_EX()
  return handled;
}

void AppCacheDispatcherHost::OnRegisterHost(int host_id) {
  if (appcache_service_.get()) {
    if (!backend_impl_.RegisterHost(host_id)) {
      ReceivedBadMessage(AppCacheMsg_RegisterHost::ID);
    }
  }
}

void AppCacheDispatcherHost::OnUnregisterHost(int host_id) {
  if (appcache_service_.get()) {
    if (!backend_impl_.UnregisterHost(host_id)) {
      ReceivedBadMessage(AppCacheMsg_UnregisterHost::ID);
    }
  }
}

void AppCacheDispatcherHost::OnSelectCache(
    int host_id, const GURL& document_url,
    int64 cache_document_was_loaded_from,
    const GURL& opt_manifest_url) {
  if (appcache_service_.get()) {
    if (!backend_impl_.SelectCache(host_id, document_url,
                                   cache_document_was_loaded_from,
                                   opt_manifest_url)) {
      ReceivedBadMessage(AppCacheMsg_SelectCache::ID);
    }
  } else {
    frontend_proxy_.OnCacheSelected(
        host_id, appcache::kNoCacheId, appcache::UNCACHED);
  }
}

void AppCacheDispatcherHost::OnMarkAsForeignEntry(
    int host_id, const GURL& document_url,
    int64 cache_document_was_loaded_from) {
  if (appcache_service_.get()) {
    if (!backend_impl_.MarkAsForeignEntry(host_id, document_url,
                                          cache_document_was_loaded_from)) {
      ReceivedBadMessage(AppCacheMsg_MarkAsForeignEntry::ID);
    }
  }
}

void AppCacheDispatcherHost::OnGetStatus(int host_id,
                                         IPC::Message* reply_msg) {
  if (pending_reply_msg_.get()) {
    ReceivedBadMessage(AppCacheMsg_GetStatus::ID);
    delete reply_msg;
    return;
  }

  pending_reply_msg_.reset(reply_msg);
  if (appcache_service_.get()) {
    if (!backend_impl_.GetStatusWithCallback(
            host_id, get_status_callback_.get(), reply_msg)) {
      ReceivedBadMessage(AppCacheMsg_GetStatus::ID);
    }
    return;
  }

  GetStatusCallback(appcache::UNCACHED, reply_msg);
}

void AppCacheDispatcherHost::OnStartUpdate(int host_id,
                                           IPC::Message* reply_msg) {
  if (pending_reply_msg_.get()) {
    ReceivedBadMessage(AppCacheMsg_StartUpdate::ID);
    delete reply_msg;
    return;
  }

  pending_reply_msg_.reset(reply_msg);
  if (appcache_service_.get()) {
    if (!backend_impl_.StartUpdateWithCallback(
            host_id, start_update_callback_.get(), reply_msg)) {
      ReceivedBadMessage(AppCacheMsg_StartUpdate::ID);
    }
    return;
  }

  StartUpdateCallback(false, reply_msg);
}

void AppCacheDispatcherHost::OnSwapCache(int host_id,
                                         IPC::Message* reply_msg) {
  if (pending_reply_msg_.get()) {
    ReceivedBadMessage(AppCacheMsg_SwapCache::ID);
    delete reply_msg;
    return;
  }

  pending_reply_msg_.reset(reply_msg);
  if (appcache_service_.get()) {
    if (!backend_impl_.SwapCacheWithCallback(
            host_id, swap_cache_callback_.get(), reply_msg)) {
      ReceivedBadMessage(AppCacheMsg_SwapCache::ID);
    }
    return;
  }

  SwapCacheCallback(false, reply_msg);
}

void AppCacheDispatcherHost::GetStatusCallback(
    appcache::Status status, void* param) {
  IPC::Message* reply_msg = reinterpret_cast<IPC::Message*>(param);
  DCHECK(reply_msg == pending_reply_msg_.get());
  AppCacheMsg_GetStatus::WriteReplyParams(reply_msg, status);
  frontend_proxy_.sender()->Send(pending_reply_msg_.release());
}

void AppCacheDispatcherHost::StartUpdateCallback(bool result, void* param) {
  IPC::Message* reply_msg = reinterpret_cast<IPC::Message*>(param);
  DCHECK(reply_msg == pending_reply_msg_.get());
  AppCacheMsg_StartUpdate::WriteReplyParams(reply_msg, result);
  frontend_proxy_.sender()->Send(pending_reply_msg_.release());
}

void AppCacheDispatcherHost::SwapCacheCallback(bool result, void* param) {
  IPC::Message* reply_msg = reinterpret_cast<IPC::Message*>(param);
  DCHECK(reply_msg == pending_reply_msg_.get());
  AppCacheMsg_SwapCache::WriteReplyParams(reply_msg, result);
  frontend_proxy_.sender()->Send(pending_reply_msg_.release());
}

void AppCacheDispatcherHost::ReceivedBadMessage(uint32 msg_type) {
  // TODO(michaeln): Consider gathering UMA stats
  // http://code.google.com/p/chromium/issues/detail?id=24634
  BrowserRenderProcessHost::BadMessageTerminateProcess(
      msg_type, process_handle_);
}
<|endoftext|>


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

#include "chrome/renderer/render_widget_fullscreen_pepper.h"

#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/fullscreen_container.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"

using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;

namespace {

// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
 public:
  PepperWidget(webkit::ppapi::PluginInstance* plugin,
               RenderWidgetFullscreenPepper* widget)
      : plugin_(plugin),
        widget_(widget),
        cursor_(WebCursorInfo::TypePointer) {
  }

  // WebWidget API
  virtual void close() {
    delete this;
  }

  virtual WebSize size() {
    return size_;
  }

  virtual void resize(const WebSize& size) {
    size_ = size;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    // TODO(piman): transparently scale the plugin instead of resizing it.
    plugin_->ViewChanged(plugin_rect, plugin_rect);
    widget_->GenerateFullRepaint();
  }

  virtual void layout() {
  }

  virtual void paint(WebCanvas* canvas, const WebRect& rect) {
    if (!plugin_)
      return;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    plugin_->Paint(canvas, plugin_rect, rect);
  }

  virtual void composite(bool finish) {
    NOTIMPLEMENTED();
  }

  virtual void themeChanged() {
    NOTIMPLEMENTED();
  }

  virtual bool handleInputEvent(const WebInputEvent& event) {
    if (!plugin_)
      return false;
    return plugin_->HandleInputEvent(event, &cursor_);
  }

  virtual void mouseCaptureLost() {
    NOTIMPLEMENTED();
  }

  virtual void setFocus(bool focus) {
    NOTIMPLEMENTED();
  }

  virtual bool setComposition(
      const WebString& text,
      const WebVector<WebCompositionUnderline>& underlines,
      int selectionStart,
      int selectionEnd) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition() {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition(const WebString& text) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual WebTextInputType textInputType() {
    NOTIMPLEMENTED();
    return WebKit::WebTextInputTypeNone;
  }

  virtual WebRect caretOrSelectionBounds() {
    NOTIMPLEMENTED();
    return WebRect();
  }

  virtual void setTextDirection(WebTextDirection) {
    NOTIMPLEMENTED();
  }

  virtual bool isAcceleratedCompositingActive() const {
    // TODO(piman): see if supporting accelerated compositing makes sense.
    return false;
  }

 private:
  webkit::ppapi::PluginInstance* plugin_;
  RenderWidgetFullscreenPepper* widget_;
  WebSize size_;
  WebCursorInfo cursor_;

  DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};

// A FullscreenContainer that forwards the API calls to the
// RenderWidgetFullscreenPepper.
class WidgetFullscreenContainer
    : public webkit::ppapi::FullscreenContainer {
 public:
  explicit WidgetFullscreenContainer(RenderWidgetFullscreenPepper* widget)
      : widget_(widget) {
  }
  virtual ~WidgetFullscreenContainer() { }

  virtual void Invalidate() {
    widget_->GenerateFullRepaint();
  }

  virtual void InvalidateRect(const WebKit::WebRect& rect) {
    widget_->didInvalidateRect(rect);
  }

  virtual void ScrollRect(int dx, int dy, const WebKit::WebRect& rect) {
    widget_->didScrollRect(dx, dy, rect);
  }

  virtual void Destroy() {
    widget_->SendClose();
  }

 private:
  RenderWidgetFullscreenPepper* widget_;

  DISALLOW_COPY_AND_ASSIGN(WidgetFullscreenContainer);
};

}  // anonymous namespace

// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
    int32 opener_id, RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin) {
  DCHECK_NE(MSG_ROUTING_NONE, opener_id);
  scoped_refptr<RenderWidgetFullscreenPepper> widget(
      new RenderWidgetFullscreenPepper(render_thread, plugin));
  widget->Init(opener_id);
  return widget.release();
}

RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
    RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin)
    : RenderWidgetFullscreen(render_thread, WebKit::WebPopupTypeSelect),
      plugin_(plugin),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          container_(new WidgetFullscreenContainer(this))) {
}

RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
}

WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
  return new PepperWidget(plugin_, this);
}

void RenderWidgetFullscreenPepper::Close() {
  // If the fullscreen window is closed (e.g. user pressed escape), reset to
  // normal mode.
  if (plugin_)
    plugin_->SetFullscreen(false);
}

void RenderWidgetFullscreenPepper::DidInitiatePaint() {
  if (plugin_)
    plugin_->ViewInitiatedPaint();
}

void RenderWidgetFullscreenPepper::DidFlushPaint() {
  if (plugin_)
    plugin_->ViewFlushedPaint();
}

void RenderWidgetFullscreenPepper::SendClose() {
  // This function is called by the plugin instance as it's going away, so reset
  // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
  plugin_ = NULL;
  Send(new ViewHostMsg_Close(routing_id_));
}

void RenderWidgetFullscreenPepper::GenerateFullRepaint() {
  didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
}

webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
    const gfx::Rect& paint_bounds,
    TransportDIB** dib,
    gfx::Rect* location,
    gfx::Rect* clip) {
  if (plugin_ &&
      plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
                                                location, clip))
    return plugin_;
  return NULL;
}
<commit_msg>Chromium support for webkitAnimationTime property<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/render_widget_fullscreen_pepper.h"

#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/fullscreen_container.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"

using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;

namespace {

// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
 public:
  PepperWidget(webkit::ppapi::PluginInstance* plugin,
               RenderWidgetFullscreenPepper* widget)
      : plugin_(plugin),
        widget_(widget),
        cursor_(WebCursorInfo::TypePointer) {
  }

  // WebWidget API
  virtual void close() {
    delete this;
  }

  virtual WebSize size() {
    return size_;
  }

  virtual void resize(const WebSize& size) {
    size_ = size;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    // TODO(piman): transparently scale the plugin instead of resizing it.
    plugin_->ViewChanged(plugin_rect, plugin_rect);
    widget_->GenerateFullRepaint();
  }

  virtual void clearCurrentAnimationTime() {
  }

  virtual void layout() {
  }

  virtual void paint(WebCanvas* canvas, const WebRect& rect) {
    if (!plugin_)
      return;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    plugin_->Paint(canvas, plugin_rect, rect);
  }

  virtual void composite(bool finish) {
    NOTIMPLEMENTED();
  }

  virtual void themeChanged() {
    NOTIMPLEMENTED();
  }

  virtual bool handleInputEvent(const WebInputEvent& event) {
    if (!plugin_)
      return false;
    return plugin_->HandleInputEvent(event, &cursor_);
  }

  virtual void mouseCaptureLost() {
    NOTIMPLEMENTED();
  }

  virtual void setFocus(bool focus) {
    NOTIMPLEMENTED();
  }

  virtual bool setComposition(
      const WebString& text,
      const WebVector<WebCompositionUnderline>& underlines,
      int selectionStart,
      int selectionEnd) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition() {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition(const WebString& text) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual WebTextInputType textInputType() {
    NOTIMPLEMENTED();
    return WebKit::WebTextInputTypeNone;
  }

  virtual WebRect caretOrSelectionBounds() {
    NOTIMPLEMENTED();
    return WebRect();
  }

  virtual void setTextDirection(WebTextDirection) {
    NOTIMPLEMENTED();
  }

  virtual bool isAcceleratedCompositingActive() const {
    // TODO(piman): see if supporting accelerated compositing makes sense.
    return false;
  }

 private:
  webkit::ppapi::PluginInstance* plugin_;
  RenderWidgetFullscreenPepper* widget_;
  WebSize size_;
  WebCursorInfo cursor_;

  DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};

// A FullscreenContainer that forwards the API calls to the
// RenderWidgetFullscreenPepper.
class WidgetFullscreenContainer
    : public webkit::ppapi::FullscreenContainer {
 public:
  explicit WidgetFullscreenContainer(RenderWidgetFullscreenPepper* widget)
      : widget_(widget) {
  }
  virtual ~WidgetFullscreenContainer() { }

  virtual void Invalidate() {
    widget_->GenerateFullRepaint();
  }

  virtual void InvalidateRect(const WebKit::WebRect& rect) {
    widget_->didInvalidateRect(rect);
  }

  virtual void ScrollRect(int dx, int dy, const WebKit::WebRect& rect) {
    widget_->didScrollRect(dx, dy, rect);
  }

  virtual void Destroy() {
    widget_->SendClose();
  }

 private:
  RenderWidgetFullscreenPepper* widget_;

  DISALLOW_COPY_AND_ASSIGN(WidgetFullscreenContainer);
};

}  // anonymous namespace

// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
    int32 opener_id, RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin) {
  DCHECK_NE(MSG_ROUTING_NONE, opener_id);
  scoped_refptr<RenderWidgetFullscreenPepper> widget(
      new RenderWidgetFullscreenPepper(render_thread, plugin));
  widget->Init(opener_id);
  return widget.release();
}

RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
    RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin)
    : RenderWidgetFullscreen(render_thread, WebKit::WebPopupTypeSelect),
      plugin_(plugin),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          container_(new WidgetFullscreenContainer(this))) {
}

RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
}

WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
  return new PepperWidget(plugin_, this);
}

void RenderWidgetFullscreenPepper::Close() {
  // If the fullscreen window is closed (e.g. user pressed escape), reset to
  // normal mode.
  if (plugin_)
    plugin_->SetFullscreen(false);
}

void RenderWidgetFullscreenPepper::DidInitiatePaint() {
  if (plugin_)
    plugin_->ViewInitiatedPaint();
}

void RenderWidgetFullscreenPepper::DidFlushPaint() {
  if (plugin_)
    plugin_->ViewFlushedPaint();
}

void RenderWidgetFullscreenPepper::SendClose() {
  // This function is called by the plugin instance as it's going away, so reset
  // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
  plugin_ = NULL;
  Send(new ViewHostMsg_Close(routing_id_));
}

void RenderWidgetFullscreenPepper::GenerateFullRepaint() {
  didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
}

webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
    const gfx::Rect& paint_bounds,
    TransportDIB** dib,
    gfx::Rect* location,
    gfx::Rect* clip) {
  if (plugin_ &&
      plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
                                                location, clip))
    return plugin_;
  return NULL;
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "CameraNode.h"
#include "DisplayEngine.h"
#include "Player.h"
#include "ISurface.h"

#include "../base/TimeSource.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"

#include "../imaging/FWCamera.h"
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

namespace avg {

CameraNode::CameraNode(const xmlNodePtr xmlNode, Player * pPlayer)
    : VideoBase(xmlNode, pPlayer),
      m_FrameNum(0)
{
    string sDevice = getDefaultedStringAttr (xmlNode, "device", "");
    double FrameRate = getDefaultedDoubleAttr (xmlNode, "framerate", 15);
    string sSource = getDefaultedStringAttr (xmlNode, "source", "firewire");
    int Width = getDefaultedIntAttr (xmlNode, "capturewidth", 640);
    int Height = getDefaultedIntAttr (xmlNode, "captureheight", 480);
    string sPF = getDefaultedStringAttr (xmlNode, "pixelformat", "RGB");

    if (sSource == "firewire") {
#if defined(AVG_ENABLE_1394)\
    || defined(AVG_ENABLE_1394_2)
    m_pCamera = CameraPtr(new FWCamera(sDevice, IntPoint(Width, Height), sPF,
            FrameRate, true));
#else
        AVG_TRACE(Logger::ERROR, "Firewire camera specified, but firewire "
                "support not compiled in.");
#endif
    } else if (sSource == "v4l") {
#if defined(AVG_ENABLE_V4L2)
        int Channel = getDefaultedIntAttr (xmlNode, "channel", 0);

        m_pCamera = CameraPtr(new V4LCamera(sDevice, Channel,
            IntPoint(Width, Height), sPF, true));
#else
        AVG_TRACE(Logger::ERROR, "Video4Linux camera specified, but "
                "Video4Linux support not compiled in.");
#endif
    } else {
        AVG_TRACE(Logger::ERROR,
            "Unable to set up camera. Camera source '"+sSource+"' unknown.");
    }

    if (m_pCamera) {
        m_pCamera->setFeature ("brightness",
            getDefaultedIntAttr(xmlNode, "brightness", -1));
        m_pCamera->setFeature ("exposure",
            getDefaultedIntAttr(xmlNode, "exposure", -1));
        m_pCamera->setFeature ("sharpness",
            getDefaultedIntAttr(xmlNode, "sharpness", -1));
        m_pCamera->setFeature ("saturation",
            getDefaultedIntAttr(xmlNode, "saturation", -1));
        m_pCamera->setFeature ("gamma",
            getDefaultedIntAttr(xmlNode, "gamma", -1));
        m_pCamera->setFeature ("shutter",
            getDefaultedIntAttr(xmlNode, "shutter", -1));
        m_pCamera->setFeature ("gain",
            getDefaultedIntAttr(xmlNode, "gain", -1));
        m_pCamera->setFeature ("whitebalance",
            getDefaultedIntAttr(xmlNode, "whitebalance", -1));
    }
}

CameraNode::~CameraNode()
{
    close();
}

void CameraNode::setDisplayEngine(DisplayEngine * pEngine)
{
    VideoBase::setDisplayEngine(pEngine);
}

string CameraNode::getTypeStr()
{
    return "Camera";
}

IntPoint CameraNode::getMediaSize()
{
    if (m_pCamera) {
        return m_pCamera->getImgSize();
    } else {
        return IntPoint(640,480);
    }
}

double CameraNode::getFPS()
{
    if (m_pCamera) {
        return m_pCamera->getFrameRate();
    } else {
        return 0;
    }
}

void CameraNode::open(YCbCrMode ycbcrMode)
{
    if (m_pCamera) {
        m_pCamera->open();
    }
}

void CameraNode::close()
{
    if (m_pCamera) {
        m_pCamera->close();
    }
}

unsigned int CameraNode::getFeature (const std::string& sFeature) const
{
    if (m_pCamera) {
        return m_pCamera->getFeature(sFeature);
    } else {
        return 0;
    }
}

void CameraNode::setFeature (const std::string& sFeature, int Value)
{
    if (m_pCamera) {
        m_pCamera->setFeature(sFeature, Value);
    }
}

int CameraNode::getFrameNum() const
{
    return m_FrameNum;
}

static ProfilingZone CameraProfilingZone("Camera::render");
static ProfilingZone CameraUploadProfilingZone("Camera tex download");

bool CameraNode::renderToSurface(ISurface * pSurface)
{
    if (m_pCamera) {
        ScopeTimer Timer(CameraProfilingZone);
        BitmapPtr pCurBmp = m_pCamera->getImage(false);
        if (pCurBmp) {
            BitmapPtr pTempBmp;
            while (pTempBmp = m_pCamera->getImage(false)) {
                pCurBmp = pTempBmp;
            }
            m_FrameNum++;
            BitmapPtr pBmp = pSurface->lockBmp();
            assert(pBmp->getPixelFormat() == pCurBmp->getPixelFormat());
            pBmp->copyPixels(*pCurBmp);
            pSurface->unlockBmps();
            {
                ScopeTimer Timer(CameraUploadProfilingZone);
                getEngine()->surfaceChanged(pSurface);
            }
        }
    }
    return true;
}

PixelFormat CameraNode::getPixelFormat()
{
    return B8G8R8X8;
}

}
<commit_msg>DS camera support.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "CameraNode.h"
#include "DisplayEngine.h"
#include "Player.h"
#include "ISurface.h"

#include "../base/TimeSource.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"

#include "../imaging/FWCamera.h"
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef _WIN32
#include "../imaging/DSCamera.h"
#endif

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

namespace avg {

CameraNode::CameraNode(const xmlNodePtr xmlNode, Player * pPlayer)
    : VideoBase(xmlNode, pPlayer),
      m_FrameNum(0)
{
    string sDevice = getDefaultedStringAttr (xmlNode, "device", "");
    double FrameRate = getDefaultedDoubleAttr (xmlNode, "framerate", 15);
    string sSource = getDefaultedStringAttr (xmlNode, "source", "firewire");
    int Width = getDefaultedIntAttr (xmlNode, "capturewidth", 640);
    int Height = getDefaultedIntAttr (xmlNode, "captureheight", 480);
    string sPF = getDefaultedStringAttr (xmlNode, "pixelformat", "RGB");

    if (sSource == "firewire") {
#if defined(AVG_ENABLE_1394)\
    || defined(AVG_ENABLE_1394_2)
    m_pCamera = CameraPtr(new FWCamera(sDevice, IntPoint(Width, Height), sPF,
            FrameRate, true));
#else
        AVG_TRACE(Logger::ERROR, "Firewire camera specified, but firewire "
                "support not compiled in.");
#endif
    } else if (sSource == "v4l") {
#if defined(AVG_ENABLE_V4L2)
        int Channel = getDefaultedIntAttr (xmlNode, "channel", 0);

        m_pCamera = CameraPtr(new V4LCamera(sDevice, Channel,
            IntPoint(Width, Height), sPF, true));
#else
        AVG_TRACE(Logger::ERROR, "Video4Linux camera specified, but "
                "Video4Linux support not compiled in.");
#endif
    } else if (sSource == "directshow") {
#if defined(_WIN32)
        m_pCamera = CameraPtr(new DSCamera(sDevice, IntPoint(Width, Height), sPF,
            FrameRate, true));
#else
        AVG_TRACE(Logger::ERROR, "DirectShow camera specified, but "
                "DirectShow is only available under windows.");
#endif
    } else {
        AVG_TRACE(Logger::ERROR,
            "Unable to set up camera. Camera source '"+sSource+"' unknown.");
    }

    if (m_pCamera) {
        m_pCamera->setFeature ("brightness",
            getDefaultedIntAttr(xmlNode, "brightness", -1));
        m_pCamera->setFeature ("exposure",
            getDefaultedIntAttr(xmlNode, "exposure", -1));
        m_pCamera->setFeature ("sharpness",
            getDefaultedIntAttr(xmlNode, "sharpness", -1));
        m_pCamera->setFeature ("saturation",
            getDefaultedIntAttr(xmlNode, "saturation", -1));
        m_pCamera->setFeature ("gamma",
            getDefaultedIntAttr(xmlNode, "gamma", -1));
        m_pCamera->setFeature ("shutter",
            getDefaultedIntAttr(xmlNode, "shutter", -1));
        m_pCamera->setFeature ("gain",
            getDefaultedIntAttr(xmlNode, "gain", -1));
        m_pCamera->setFeature ("whitebalance",
            getDefaultedIntAttr(xmlNode, "whitebalance", -1));
    }
}

CameraNode::~CameraNode()
{
    close();
}

void CameraNode::setDisplayEngine(DisplayEngine * pEngine)
{
    VideoBase::setDisplayEngine(pEngine);
}

string CameraNode::getTypeStr()
{
    return "Camera";
}

IntPoint CameraNode::getMediaSize()
{
    if (m_pCamera) {
        return m_pCamera->getImgSize();
    } else {
        return IntPoint(640,480);
    }
}

double CameraNode::getFPS()
{
    if (m_pCamera) {
        return m_pCamera->getFrameRate();
    } else {
        return 0;
    }
}

void CameraNode::open(YCbCrMode ycbcrMode)
{
    if (m_pCamera) {
        m_pCamera->open();
    }
}

void CameraNode::close()
{
    if (m_pCamera) {
        m_pCamera->close();
    }
}

unsigned int CameraNode::getFeature (const std::string& sFeature) const
{
    if (m_pCamera) {
        return m_pCamera->getFeature(sFeature);
    } else {
        return 0;
    }
}

void CameraNode::setFeature (const std::string& sFeature, int Value)
{
    if (m_pCamera) {
        m_pCamera->setFeature(sFeature, Value);
    }
}

int CameraNode::getFrameNum() const
{
    return m_FrameNum;
}

static ProfilingZone CameraProfilingZone("Camera::render");
static ProfilingZone CameraUploadProfilingZone("Camera tex download");

bool CameraNode::renderToSurface(ISurface * pSurface)
{
    if (m_pCamera) {
        ScopeTimer Timer(CameraProfilingZone);
        BitmapPtr pCurBmp = m_pCamera->getImage(false);
        if (pCurBmp) {
            BitmapPtr pTempBmp;
            while (pTempBmp = m_pCamera->getImage(false)) {
                pCurBmp = pTempBmp;
            }
            m_FrameNum++;
            BitmapPtr pBmp = pSurface->lockBmp();
            assert(pBmp->getPixelFormat() == pCurBmp->getPixelFormat());
            pBmp->copyPixels(*pCurBmp);
            pSurface->unlockBmps();
            {
                ScopeTimer Timer(CameraUploadProfilingZone);
                getEngine()->surfaceChanged(pSurface);
            }
        }
    }
    return true;
}

PixelFormat CameraNode::getPixelFormat()
{
    return B8G8R8X8;
}

}
<|endoftext|>


<commit_before>// Copyright (C) 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/*
 * insertReactionRowsCommand.cpp
 *
 *  Created on: 5 Aug 2014
 *      Author: dada
 */

#include <QUndoCommand>
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CChemEqInterface.h"
#include "model/CReaction.h"
#include "model/CReactionInterface.h"
#include "model/CModel.h"
#include "CQReactionDM.h"
#include "qtUtilities.h"

#include "UndoReactionData.h"
#include "insertReactionRowsCommand.h"

insertReactionRowsCommand::insertReactionRowsCommand(int position, int rows, CQReactionDM *pReactionDM, const QModelIndex&): CCopasiUndoCommand()
{
  mpReactionDM = pReactionDM;
  this->setText(insertRowsText());
  mRows = rows;
  mPosition = position;
  mType = REACTIONINSERT;
  setEntityType("Reaction");
}

insertReactionRowsCommand::~insertReactionRowsCommand()
{
  // TODO Auto-generated destructor stub
}

void insertReactionRowsCommand::redo()
{
  mpReactionDM->insertNewReactionRow(mPosition, mRows, QModelIndex());
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();
  assert(pModel != NULL);
  mpReaction = pModel->getReactions()[mPosition];
  std::string sName = mpReaction->getObjectName();
  mpReactionData->setName(sName);
  CReactionInterface* ri = new CReactionInterface((*CCopasiRootContainer::getDatamodelList())[0]->getModel());
  ri->initFromReaction(mpReaction);
  mpReactionData->setRi(ri);
  setUndoState(true);
  setAction("Add to list");
  setName(mpReactionData->getName());
}

void insertReactionRowsCommand::undo()
{
  mpReactionDM->deleteReactionRow(mpReaction);
  setUndoState(false);
  setAction("Remove from list");
}

QString insertReactionRowsCommand::insertRowsText() const
{
  return QObject::tr(": Inserted New Reaction");
}

UndoData *insertReactionRowsCommand::getUndoData() const
{
  return mpReactionData;
}
<commit_msg>- fix crash in undo framework due to un-initialized variable<commit_after>// Copyright (C) 2014 - 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/*
 * insertReactionRowsCommand.cpp
 *
 *  Created on: 5 Aug 2014
 *      Author: dada
 */

#include <QUndoCommand>
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CChemEqInterface.h"
#include "model/CReaction.h"
#include "model/CReactionInterface.h"
#include "model/CModel.h"
#include "CQReactionDM.h"
#include "qtUtilities.h"

#include "UndoReactionData.h"
#include "insertReactionRowsCommand.h"

insertReactionRowsCommand::insertReactionRowsCommand(int position, int rows, CQReactionDM *pReactionDM, const QModelIndex&)
  : CCopasiUndoCommand()
  , mpRi(NULL)
  , mpReactionData(NULL)

{
  mpReactionDM = pReactionDM;
  this->setText(insertRowsText());
  mRows = rows;
  mPosition = position;
  mType = REACTIONINSERT;
  setEntityType("Reaction");
}

insertReactionRowsCommand::~insertReactionRowsCommand()
{
  // TODO Auto-generated destructor stub
}

void insertReactionRowsCommand::redo()
{
  mpReactionDM->insertNewReactionRow(mPosition, mRows, QModelIndex());
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();
  assert(pModel != NULL);
  mpReaction = pModel->getReactions()[mPosition];
  std::string sName = mpReaction->getObjectName();

  if (mpReactionData != NULL)
    mpReactionData->setName(sName);

  CReactionInterface* ri = new CReactionInterface((*CCopasiRootContainer::getDatamodelList())[0]->getModel());
  ri->initFromReaction(mpReaction);

  if (mpReactionData != NULL)
    mpReactionData->setRi(ri);

  setUndoState(true);
  setAction("Add to list");

  if (mpReactionData != NULL)
    setName(mpReactionData->getName());
  else setName(sName);
}

void insertReactionRowsCommand::undo()
{
  mpReactionDM->deleteReactionRow(mpReaction);
  setUndoState(false);
  setAction("Remove from list");
}

QString insertReactionRowsCommand::insertRowsText() const
{
  return QObject::tr(": Inserted New Reaction");
}

UndoData *insertReactionRowsCommand::getUndoData() const
{
  return mpReactionData;
}
<|endoftext|>