<commit_before>/*************************************************************************
 *
 *  $RCSfile: DrawViewWrapper.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: bm $ $Date: 2003-10-06 09:58:27 $
 *
 *  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: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CHART2_DRAW_VIEW_WRAPPER_HXX
#define _CHART2_DRAW_VIEW_WRAPPER_HXX

#ifndef _E3D_VIEW3D_HXX
#include <svx/view3d.hxx>
#endif

class SdrModel;

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/** The DrawViewWrapper should help us to reduce effort if the underlying DrawingLayer changes.
Another task is to hide functionality we do not need, for example more than one page.
*/

class MarkHandleProvider
{
public:
    virtual bool getMarkHandles( SdrHdlList& rHdlList ) =0;
    virtual bool getFrameDragSingles() =0;
};

class DrawViewWrapper : public E3dView
{
public:
    DrawViewWrapper(SdrModel* pModel, OutputDevice* pOut);
    virtual ~DrawViewWrapper();

    //fill list of selection handles 'aHdl'
    virtual void SetMarkHandles();

    //SdrPageView*    GetPageView() { return m_pWrappedDLPageView; };

    SdrObject* getHitObject( const Point& rPnt ) const;
    //BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions, SdrObject** ppRootObj, ULONG* pnMarkNum=NULL, USHORT* pnPassNum=NULL) const;
    //BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const;
    //BOOL PickObj(const Point& rPnt, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const { return PickObj(rPnt,nHitTolLog,rpObj,rpPV,nOptions); }

    //void MarkObj(SdrObject* pObj, SdrPageView* pPV, BOOL bUnmark=FALSE, BOOL bImpNoSetMarkHdl=FALSE);
    void MarkObject( SdrObject* pObj );

    //----------------------
    //pMarkHandleProvider can be NULL; ownership is not taken
    void setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider );

    void InitRedraw( OutputDevice* pOut, const Region& rReg );

private:
    mutable SdrPageView*            m_pWrappedDLPageView;
    mutable MarkHandleProvider*     m_pMarkHandleProvider;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif

<commit_msg>added text-edit-outliner support<commit_after>/*************************************************************************
 *
 *  $RCSfile: DrawViewWrapper.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: iha $ $Date: 2003-10-28 16:24:35 $
 *
 *  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: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CHART2_DRAW_VIEW_WRAPPER_HXX
#define _CHART2_DRAW_VIEW_WRAPPER_HXX

#ifndef _E3D_VIEW3D_HXX
#include <svx/view3d.hxx>
#endif

class SdrModel;

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/** The DrawViewWrapper should help us to reduce effort if the underlying DrawingLayer changes.
Another task is to hide functionality we do not need, for example more than one page.
*/

class MarkHandleProvider
{
public:
    virtual bool getMarkHandles( SdrHdlList& rHdlList ) =0;
    virtual bool getFrameDragSingles() =0;
};

class DrawViewWrapper : public E3dView
{
public:
    DrawViewWrapper(SdrModel* pModel, OutputDevice* pOut);
    virtual ~DrawViewWrapper();

    //fill list of selection handles 'aHdl'
    virtual void SetMarkHandles();

    SdrPageView*    GetPageView() { return m_pWrappedDLPageView; };

    SdrObject* getHitObject( const Point& rPnt ) const;
    //BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions, SdrObject** ppRootObj, ULONG* pnMarkNum=NULL, USHORT* pnPassNum=NULL) const;
    //BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const;
    //BOOL PickObj(const Point& rPnt, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const { return PickObj(rPnt,nHitTolLog,rpObj,rpPV,nOptions); }

    //void MarkObj(SdrObject* pObj, SdrPageView* pPV, BOOL bUnmark=FALSE, BOOL bImpNoSetMarkHdl=FALSE);
    void MarkObject( SdrObject* pObj );

    //----------------------
    //pMarkHandleProvider can be NULL; ownership is not taken
    void setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider );

    void InitRedraw( OutputDevice* pOut, const Region& rReg );

    SdrObject*   getTextEditObject() const;
    SdrOutliner* getOutliner() const;

private:
    mutable SdrPageView*            m_pWrappedDLPageView;
    mutable MarkHandleProvider*     m_pMarkHandleProvider;

    ::std::auto_ptr< SdrOutliner >  m_apOutliner;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif

<|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/chromeos/login/background_view.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/feedback_menu_button.h"
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"

// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>

using views::WidgetGtk;

namespace chromeos {

BackgroundView::BackgroundView() : status_area_(NULL),
                                   os_version_label_(NULL),
                                   boot_times_label_(NULL),
                                   did_paint_(false) {
  views::Painter* painter = chromeos::CreateWizardPainter(
      &chromeos::BorderDefinition::kWizardBorder);
  set_background(views::Background::CreateBackgroundPainter(true, painter));
  InitStatusArea();
  InitInfoLabels();
}

static void ResetXCursor() {
  // TODO(sky): nuke this once new window manager is in place.
  // This gets rid of the ugly X default cursor.
  Display* display = x11_util::GetXDisplay();
  Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
  XID root_window = x11_util::GetX11RootWindow();
  XSetWindowAttributes attr;
  attr.cursor = cursor;
  XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}

// static
views::Widget* BackgroundView::CreateWindowContainingView(
    const gfx::Rect& bounds,
    BackgroundView** view) {
  ResetXCursor();

  WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
  window->Init(NULL, bounds);
  *view = new BackgroundView();
  window->SetContentsView(*view);

  (*view)->UpdateWindowType();

  // This keeps the window from flashing at startup.
  GdkWindow* gdk_window = window->GetNativeView()->window;
  gdk_window_set_back_pixmap(gdk_window, NULL, false);

  return window;
}

void BackgroundView::SetStatusAreaVisible(bool visible) {
  status_area_->SetVisible(visible);
}

void BackgroundView::Paint(gfx::Canvas* canvas) {
  views::View::Paint(canvas);
  if (!did_paint_) {
    did_paint_ = true;
    UpdateWindowType();
  }
}

void BackgroundView::Layout() {
  int corner_padding =
      chromeos::BorderDefinition::kWizardBorder.padding +
      chromeos::BorderDefinition::kWizardBorder.corner_radius / 2;
  int kInfoLeftPadding = 60;
  int kInfoBottomPadding = 40;
  int kInfoBetweenLinesPadding = 4;
  gfx::Size status_area_size = status_area_->GetPreferredSize();
  status_area_->SetBounds(
      width() - status_area_size.width() - corner_padding,
      corner_padding,
      status_area_size.width(),
      status_area_size.height());
  gfx::Size version_size = os_version_label_->GetPreferredSize();
  os_version_label_->SetBounds(
      kInfoLeftPadding,
      height() -
          ((2 * version_size.height()) +
          kInfoBottomPadding +
          kInfoBetweenLinesPadding),
      width() - 2 * kInfoLeftPadding,
      version_size.height());
  boot_times_label_->SetBounds(
      kInfoLeftPadding,
      height() - (version_size.height() + kInfoBottomPadding),
      width() - 2 * corner_padding,
      version_size.height());
}

void BackgroundView::ChildPreferredSizeChanged(View* child) {
  Layout();
  SchedulePaint();
}

gfx::NativeWindow BackgroundView::GetNativeWindow() const {
  return
      GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}

bool BackgroundView::ShouldOpenButtonOptions(
    const views::View* button_view) const {
  if (button_view == status_area_->clock_view() ||
      button_view == status_area_->feedback_view() ||
      button_view == status_area_->language_view() ||
      button_view == status_area_->network_view()) {
    return false;
  }
  return true;
}

void BackgroundView::OpenButtonOptions(const views::View* button_view) const {
  // TODO(avayvod): Add some dialog for options or remove them completely.
}

bool BackgroundView::IsButtonVisible(const views::View* button_view) const {
  return true;
}

bool BackgroundView::IsBrowserMode() const {
  return false;
}

void BackgroundView::LocaleChanged() {
  Layout();
  SchedulePaint();
}

void BackgroundView::InitStatusArea() {
  DCHECK(status_area_ == NULL);
  status_area_ = new StatusAreaView(this);
  status_area_->Init();
  AddChildView(status_area_);
}

void BackgroundView::InitInfoLabels() {
  const SkColor kVersionColor = 0xff8eb1f4;
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();

  os_version_label_ = new views::Label();
  os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  os_version_label_->SetColor(kVersionColor);
  os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
  AddChildView(os_version_label_);
  boot_times_label_ = new views::Label();
  boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  boot_times_label_->SetColor(kVersionColor);
  boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
  AddChildView(boot_times_label_);

  if (CrosLibrary::Get()->EnsureLoaded()) {
    version_loader_.GetVersion(
        &version_consumer_, NewCallback(this, &BackgroundView::OnVersion));
    boot_times_loader_.GetBootTimes(
        &boot_times_consumer_, NewCallback(this, &BackgroundView::OnBootTimes));
  } else {
    os_version_label_->SetText(
        ASCIIToWide(CrosLibrary::Get()->load_error_string()));
  }
}

void BackgroundView::UpdateWindowType() {
  std::vector<int> params;
  params.push_back(did_paint_ ? 1 : 0);
  WmIpc::instance()->SetWindowType(
      GTK_WIDGET(GetNativeWindow()),
      WM_IPC_WINDOW_LOGIN_BACKGROUND,
      &params);
}

void BackgroundView::OnVersion(
    VersionLoader::Handle handle, std::string version) {
  std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
  version_text += ' ';
  version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
  version_text += ' ';
  version_text += version;
  os_version_label_->SetText(ASCIIToWide(version_text));
}

void BackgroundView::OnBootTimes(
    BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
  // TODO(davemoore) if we decide to keep these times visible we will need
  // to localize the strings.
  const char* kBootTimesNoChromeExec =
      "Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
  const char* kBootTimesChromeExec =
      "Boot took %.2f seconds "
      "(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
  std::string boot_times_text;

  if (boot_times.chrome_exec > 0) {
    boot_times_text =
        StringPrintf(
            kBootTimesChromeExec,
            boot_times.firmware + boot_times.login_prompt_ready,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.chrome_exec - boot_times.pre_startup,
            boot_times.login_prompt_ready - boot_times.chrome_exec);
  } else {
    boot_times_text =
        StringPrintf(
            kBootTimesNoChromeExec,
            boot_times.firmware + boot_times.login_prompt_ready,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.login_prompt_ready - boot_times.pre_startup);
  }
  boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}

}  // namespace chromeos
<commit_msg>Made feedback icon hidden on login screen.<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/chromeos/login/background_view.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/feedback_menu_button.h"
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"

// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>

using views::WidgetGtk;

namespace chromeos {

BackgroundView::BackgroundView() : status_area_(NULL),
                                   os_version_label_(NULL),
                                   boot_times_label_(NULL),
                                   did_paint_(false) {
  views::Painter* painter = chromeos::CreateWizardPainter(
      &chromeos::BorderDefinition::kWizardBorder);
  set_background(views::Background::CreateBackgroundPainter(true, painter));
  InitStatusArea();
  InitInfoLabels();
}

static void ResetXCursor() {
  // TODO(sky): nuke this once new window manager is in place.
  // This gets rid of the ugly X default cursor.
  Display* display = x11_util::GetXDisplay();
  Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
  XID root_window = x11_util::GetX11RootWindow();
  XSetWindowAttributes attr;
  attr.cursor = cursor;
  XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}

// static
views::Widget* BackgroundView::CreateWindowContainingView(
    const gfx::Rect& bounds,
    BackgroundView** view) {
  ResetXCursor();

  WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
  window->Init(NULL, bounds);
  *view = new BackgroundView();
  window->SetContentsView(*view);

  (*view)->UpdateWindowType();

  // This keeps the window from flashing at startup.
  GdkWindow* gdk_window = window->GetNativeView()->window;
  gdk_window_set_back_pixmap(gdk_window, NULL, false);

  return window;
}

void BackgroundView::SetStatusAreaVisible(bool visible) {
  status_area_->SetVisible(visible);
}

void BackgroundView::Paint(gfx::Canvas* canvas) {
  views::View::Paint(canvas);
  if (!did_paint_) {
    did_paint_ = true;
    UpdateWindowType();
  }
}

void BackgroundView::Layout() {
  int corner_padding =
      chromeos::BorderDefinition::kWizardBorder.padding +
      chromeos::BorderDefinition::kWizardBorder.corner_radius / 2;
  int kInfoLeftPadding = 60;
  int kInfoBottomPadding = 40;
  int kInfoBetweenLinesPadding = 4;
  gfx::Size status_area_size = status_area_->GetPreferredSize();
  status_area_->SetBounds(
      width() - status_area_size.width() - corner_padding,
      corner_padding,
      status_area_size.width(),
      status_area_size.height());
  gfx::Size version_size = os_version_label_->GetPreferredSize();
  os_version_label_->SetBounds(
      kInfoLeftPadding,
      height() -
          ((2 * version_size.height()) +
          kInfoBottomPadding +
          kInfoBetweenLinesPadding),
      width() - 2 * kInfoLeftPadding,
      version_size.height());
  boot_times_label_->SetBounds(
      kInfoLeftPadding,
      height() - (version_size.height() + kInfoBottomPadding),
      width() - 2 * corner_padding,
      version_size.height());
}

void BackgroundView::ChildPreferredSizeChanged(View* child) {
  Layout();
  SchedulePaint();
}

gfx::NativeWindow BackgroundView::GetNativeWindow() const {
  return
      GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}

bool BackgroundView::ShouldOpenButtonOptions(
    const views::View* button_view) const {
  if (button_view == status_area_->clock_view() ||
      button_view == status_area_->feedback_view() ||
      button_view == status_area_->language_view() ||
      button_view == status_area_->network_view()) {
    return false;
  }
  return true;
}

void BackgroundView::OpenButtonOptions(const views::View* button_view) const {
  // TODO(avayvod): Add some dialog for options or remove them completely.
}

bool BackgroundView::IsButtonVisible(const views::View* button_view) const {
  if (button_view == status_area_->feedback_view())
    return false;
  return true;
}

bool BackgroundView::IsBrowserMode() const {
  return false;
}

void BackgroundView::LocaleChanged() {
  Layout();
  SchedulePaint();
}

void BackgroundView::InitStatusArea() {
  DCHECK(status_area_ == NULL);
  status_area_ = new StatusAreaView(this);
  status_area_->Init();
  status_area_->Update();
  AddChildView(status_area_);
}

void BackgroundView::InitInfoLabels() {
  const SkColor kVersionColor = 0xff8eb1f4;
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();

  os_version_label_ = new views::Label();
  os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  os_version_label_->SetColor(kVersionColor);
  os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
  AddChildView(os_version_label_);
  boot_times_label_ = new views::Label();
  boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  boot_times_label_->SetColor(kVersionColor);
  boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
  AddChildView(boot_times_label_);

  if (CrosLibrary::Get()->EnsureLoaded()) {
    version_loader_.GetVersion(
        &version_consumer_, NewCallback(this, &BackgroundView::OnVersion));
    boot_times_loader_.GetBootTimes(
        &boot_times_consumer_, NewCallback(this, &BackgroundView::OnBootTimes));
  } else {
    os_version_label_->SetText(
        ASCIIToWide(CrosLibrary::Get()->load_error_string()));
  }
}

void BackgroundView::UpdateWindowType() {
  std::vector<int> params;
  params.push_back(did_paint_ ? 1 : 0);
  WmIpc::instance()->SetWindowType(
      GTK_WIDGET(GetNativeWindow()),
      WM_IPC_WINDOW_LOGIN_BACKGROUND,
      &params);
}

void BackgroundView::OnVersion(
    VersionLoader::Handle handle, std::string version) {
  std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
  version_text += ' ';
  version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
  version_text += ' ';
  version_text += version;
  os_version_label_->SetText(ASCIIToWide(version_text));
}

void BackgroundView::OnBootTimes(
    BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
  // TODO(davemoore) if we decide to keep these times visible we will need
  // to localize the strings.
  const char* kBootTimesNoChromeExec =
      "Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
  const char* kBootTimesChromeExec =
      "Boot took %.2f seconds "
      "(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
  std::string boot_times_text;

  if (boot_times.chrome_exec > 0) {
    boot_times_text =
        StringPrintf(
            kBootTimesChromeExec,
            boot_times.firmware + boot_times.login_prompt_ready,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.chrome_exec - boot_times.pre_startup,
            boot_times.login_prompt_ready - boot_times.chrome_exec);
  } else {
    boot_times_text =
        StringPrintf(
            kBootTimesNoChromeExec,
            boot_times.firmware + boot_times.login_prompt_ready,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.login_prompt_ready - boot_times.pre_startup);
  }
  boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}

}  // namespace chromeos
<|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/dom_ui/chrome_url_data_manager.h"

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/i18n/rtl.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/values.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif
#include "chrome/browser/appcache/view_appcache_internals_job_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/shared_resources_data_source.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/net/view_http_cache_job_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/url_util.h"
#include "grit/platform_locale_settings.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_job.h"

// URLRequestChromeJob is a URLRequestJob that manages running chrome-internal
// resource requests asynchronously.
// It hands off URL requests to ChromeURLDataManager, which asynchronously
// calls back once the data is available.
class URLRequestChromeJob : public URLRequestJob {
 public:
  explicit URLRequestChromeJob(URLRequest* request);

  // URLRequestJob implementation.
  virtual void Start();
  virtual void Kill();
  virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
  virtual bool GetMimeType(std::string* mime_type) const;

  // Called by ChromeURLDataManager to notify us that the data blob is ready
  // for us.
  void DataAvailable(RefCountedMemory* bytes);

  void SetMimeType(const std::string& mime_type) {
    mime_type_ = mime_type;
  }

 private:
  virtual ~URLRequestChromeJob();

  // Helper for Start(), to let us start asynchronously.
  // (This pattern is shared by most URLRequestJob implementations.)
  void StartAsync();

  // Do the actual copy from data_ (the data we're serving) into |buf|.
  // Separate from ReadRawData so we can handle async I/O.
  void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);

  // The actual data we're serving.  NULL until it's been fetched.
  scoped_refptr<RefCountedMemory> data_;
  // The current offset into the data that we're handing off to our
  // callers via the Read interfaces.
  int data_offset_;

  // For async reads, we keep around a pointer to the buffer that
  // we're reading into.
  scoped_refptr<net::IOBuffer> pending_buf_;
  int pending_buf_size_;
  std::string mime_type_;

  DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob);
};

// URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL
class URLRequestChromeFileJob : public URLRequestFileJob {
 public:
  URLRequestChromeFileJob(URLRequest* request, const FilePath& path);

 private:
  virtual ~URLRequestChromeFileJob();

  DISALLOW_COPY_AND_ASSIGN(URLRequestChromeFileJob);
};

void RegisterURLRequestChromeJob() {
  FilePath inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
    Singleton<ChromeURLDataManager>()->AddFileSource(
        chrome::kChromeUIDevToolsHost, inspector_dir);
  }

  SharedResourcesDataSource::Register();
  URLRequest::RegisterProtocolFactory(chrome::kChromeUIScheme,
                                      &ChromeURLDataManager::Factory);
}

void UnregisterURLRequestChromeJob() {
  FilePath inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
    Singleton<ChromeURLDataManager>()->RemoveFileSource(
        chrome::kChromeUIDevToolsHost);
  }
}

// static
void ChromeURLDataManager::URLToRequest(const GURL& url,
                                        std::string* source_name,
                                        std::string* path) {
  DCHECK(url.SchemeIs(chrome::kChromeUIScheme));

  if (!url.is_valid()) {
    NOTREACHED();
    return;
  }

  // Our input looks like: chrome://source_name/extra_bits?foo .
  // So the url's "host" is our source, and everything after the host is
  // the path.
  source_name->assign(url.host());

  const std::string& spec = url.possibly_invalid_spec();
  const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
  // + 1 to skip the slash at the beginning of the path.
  int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false) + 1;

  if (offset < static_cast<int>(spec.size()))
    path->assign(spec.substr(offset));
}

// static
bool ChromeURLDataManager::URLToFilePath(const GURL& url,
                                         FilePath* file_path) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string relative_path;

  // Remove Query and Ref from URL.
  GURL stripped_url;
  GURL::Replacements replacements;
  replacements.ClearQuery();
  replacements.ClearRef();
  stripped_url = url.ReplaceComponents(replacements);

  URLToRequest(stripped_url, &source_name, &relative_path);

  FileSourceMap::const_iterator i(
      Singleton<ChromeURLDataManager>()->file_sources_.find(source_name));
  if (i == Singleton<ChromeURLDataManager>()->file_sources_.end())
    return false;

  *file_path = i->second.AppendASCII(relative_path);

  return true;
}

ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { }

ChromeURLDataManager::~ChromeURLDataManager() { }

void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) {
  // TODO(jackson): A new data source with same name should not clobber the
  // existing one.
  data_sources_[source->source_name()] = source;
}

void ChromeURLDataManager::AddFileSource(const std::string& source_name,
                                         const FilePath& file_path) {
  DCHECK(file_sources_.count(source_name) == 0);
  file_sources_[source_name] = file_path;
}

void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) {
  DCHECK(file_sources_.count(source_name) == 1);
  file_sources_.erase(source_name);
}

bool ChromeURLDataManager::HasPendingJob(URLRequestChromeJob* job) const {
  for (PendingRequestMap::const_iterator i = pending_requests_.begin();
       i != pending_requests_.end(); ++i) {
    if (i->second == job)
      return true;
  }

  return false;
}

bool ChromeURLDataManager::StartRequest(const GURL& url,
                                        URLRequestChromeJob* job) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string path;
  URLToRequest(url, &source_name, &path);

  // Look up the data source for the request.
  DataSourceMap::iterator i = data_sources_.find(source_name);
  if (i == data_sources_.end())
    return false;
  DataSource* source = i->second;

  // Save this request so we know where to send the data.
  RequestID request_id = next_request_id_++;
  pending_requests_.insert(std::make_pair(request_id, job));

  // TODO(eroman): would be nicer if the mimetype were set at the same time
  // as the data blob. For now do it here, since NotifyHeadersComplete() is
  // going to get called once we return.
  job->SetMimeType(source->GetMimeType(path));

  ChromeURLRequestContext* context = static_cast<ChromeURLRequestContext*>(
      job->request()->context());

  // Forward along the request to the data source.
  MessageLoop* target_message_loop = source->MessageLoopForRequestPath(path);
  if (!target_message_loop) {
    // The DataSource is agnostic to which thread StartDataRequest is called
    // on for this path.  Call directly into it from this thread, the IO
    // thread.
    source->StartDataRequest(path, context->is_off_the_record(), request_id);
  } else {
    // The DataSource wants StartDataRequest to be called on a specific thread,
    // usually the UI thread, for this path.
    target_message_loop->PostTask(FROM_HERE,
        NewRunnableMethod(source, &DataSource::StartDataRequest,
                          path, context->is_off_the_record(), request_id));
  }
  return true;
}

void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) {
  // Remove the request from our list of pending requests.
  // If/when the source sends the data that was requested, the data will just
  // be thrown away.
  for (PendingRequestMap::iterator i = pending_requests_.begin();
       i != pending_requests_.end(); ++i) {
    if (i->second == job) {
      pending_requests_.erase(i);
      return;
    }
  }
}

void ChromeURLDataManager::DataAvailable(
    RequestID request_id,
    scoped_refptr<RefCountedMemory> bytes) {
  // Forward this data on to the pending URLRequest, if it exists.
  PendingRequestMap::iterator i = pending_requests_.find(request_id);
  if (i != pending_requests_.end()) {
    // We acquire a reference to the job so that it doesn't disappear under the
    // feet of any method invoked here (we could trigger a callback).
    scoped_refptr<URLRequestChromeJob> job = i->second;
    pending_requests_.erase(i);
    job->DataAvailable(bytes);
  }
}

void ChromeURLDataManager::DataSource::SendResponse(
    RequestID request_id,
    RefCountedMemory* bytes) {
  ChromeThread::PostTask(
      ChromeThread::IO, FROM_HERE,
      NewRunnableMethod(Singleton<ChromeURLDataManager>::get(),
                        &ChromeURLDataManager::DataAvailable,
                        request_id, scoped_refptr<RefCountedMemory>(bytes)));
}

MessageLoop* ChromeURLDataManager::DataSource::MessageLoopForRequestPath(
    const std::string& path) const {
  return message_loop_;
}

// static
void ChromeURLDataManager::DataSource::SetFontAndTextDirection(
    DictionaryValue* localized_strings) {
  localized_strings->SetString(L"fontfamily",
      l10n_util::GetString(IDS_WEB_FONT_FAMILY));

  int web_font_size_id = IDS_WEB_FONT_SIZE;
#if defined(OS_WIN)
  // Some fonts used for some languages changed a lot in terms of the font
  // metric in Vista. So, we need to use different size before Vista.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    web_font_size_id = IDS_WEB_FONT_SIZE_XP;
#endif
  localized_strings->SetString(L"fontsize",
      l10n_util::GetString(web_font_size_id));

  localized_strings->SetString(L"textdirection",
      base::i18n::IsRTL() ? L"rtl" : L"ltr");
}

URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request,
                                             const std::string& scheme) {
  // Try first with a file handler
  FilePath path;
  if (ChromeURLDataManager::URLToFilePath(request->url(), &path))
    return new URLRequestChromeFileJob(request, path);

  // Next check for chrome://view-http-cache/*, which uses its own job type.
  if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
    return ViewHttpCacheJobFactory::CreateJobForRequest(request);

  // Next check for chrome://appcache-internals/, which uses its own job type.
  if (ViewAppCacheInternalsJobFactory::IsSupportedURL(request->url()))
    return ViewAppCacheInternalsJobFactory::CreateJobForRequest(request);

  // Fall back to using a custom handler
  return new URLRequestChromeJob(request);
}

URLRequestChromeJob::URLRequestChromeJob(URLRequest* request)
    : URLRequestJob(request),
      data_offset_(0),
      pending_buf_size_(0) {
}

URLRequestChromeJob::~URLRequestChromeJob() {
  CHECK(!Singleton<ChromeURLDataManager>()->HasPendingJob(this));
}

void URLRequestChromeJob::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
      this, &URLRequestChromeJob::StartAsync));
}

void URLRequestChromeJob::Kill() {
  Singleton<ChromeURLDataManager>()->RemoveRequest(this);
}

bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const {
  *mime_type = mime_type_;
  return !mime_type_.empty();
}

void URLRequestChromeJob::DataAvailable(RefCountedMemory* bytes) {
  if (bytes) {
    // The request completed, and we have all the data.
    // Clear any IO pending status.
    SetStatus(URLRequestStatus());

    data_ = bytes;
    int bytes_read;
    if (pending_buf_.get()) {
      CHECK(pending_buf_->data());
      CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
      pending_buf_ = NULL;
      NotifyReadComplete(bytes_read);
    }
  } else {
    // The request failed.
    NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_FAILED));
  }
}

bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
                                      int* bytes_read) {
  if (!data_.get()) {
    SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
    DCHECK(!pending_buf_.get());
    CHECK(buf->data());
    pending_buf_ = buf;
    pending_buf_size_ = buf_size;
    return false;  // Tell the caller we're still waiting for data.
  }

  // Otherwise, the data is available.
  CompleteRead(buf, buf_size, bytes_read);
  return true;
}

void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
                                       int* bytes_read) {
  int remaining = static_cast<int>(data_->size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), data_->front() + data_offset_, buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
}

void URLRequestChromeJob::StartAsync() {
  if (!request_)
    return;

  if (Singleton<ChromeURLDataManager>()->StartRequest(request_->url(), this)) {
    NotifyHeadersComplete();
  } else {
    NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
                                      net::ERR_INVALID_URL));
  }
}

URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request,
                                                 const FilePath& path)
    : URLRequestFileJob(request, path) {
}

URLRequestChromeFileJob::~URLRequestChromeFileJob() { }
<commit_msg>Prevent hitting DCHECK when multiple slashes are specified in chrome://devtools///.<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/dom_ui/chrome_url_data_manager.h"

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/i18n/rtl.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/values.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif
#include "chrome/browser/appcache/view_appcache_internals_job_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/shared_resources_data_source.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/net/view_http_cache_job_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/ref_counted_util.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/url_util.h"
#include "grit/platform_locale_settings.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_job.h"

// URLRequestChromeJob is a URLRequestJob that manages running chrome-internal
// resource requests asynchronously.
// It hands off URL requests to ChromeURLDataManager, which asynchronously
// calls back once the data is available.
class URLRequestChromeJob : public URLRequestJob {
 public:
  explicit URLRequestChromeJob(URLRequest* request);

  // URLRequestJob implementation.
  virtual void Start();
  virtual void Kill();
  virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
  virtual bool GetMimeType(std::string* mime_type) const;

  // Called by ChromeURLDataManager to notify us that the data blob is ready
  // for us.
  void DataAvailable(RefCountedMemory* bytes);

  void SetMimeType(const std::string& mime_type) {
    mime_type_ = mime_type;
  }

 private:
  virtual ~URLRequestChromeJob();

  // Helper for Start(), to let us start asynchronously.
  // (This pattern is shared by most URLRequestJob implementations.)
  void StartAsync();

  // Do the actual copy from data_ (the data we're serving) into |buf|.
  // Separate from ReadRawData so we can handle async I/O.
  void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);

  // The actual data we're serving.  NULL until it's been fetched.
  scoped_refptr<RefCountedMemory> data_;
  // The current offset into the data that we're handing off to our
  // callers via the Read interfaces.
  int data_offset_;

  // For async reads, we keep around a pointer to the buffer that
  // we're reading into.
  scoped_refptr<net::IOBuffer> pending_buf_;
  int pending_buf_size_;
  std::string mime_type_;

  DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob);
};

// URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL
class URLRequestChromeFileJob : public URLRequestFileJob {
 public:
  URLRequestChromeFileJob(URLRequest* request, const FilePath& path);

 private:
  virtual ~URLRequestChromeFileJob();

  DISALLOW_COPY_AND_ASSIGN(URLRequestChromeFileJob);
};

void RegisterURLRequestChromeJob() {
  FilePath inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
    Singleton<ChromeURLDataManager>()->AddFileSource(
        chrome::kChromeUIDevToolsHost, inspector_dir);
  }

  SharedResourcesDataSource::Register();
  URLRequest::RegisterProtocolFactory(chrome::kChromeUIScheme,
                                      &ChromeURLDataManager::Factory);
}

void UnregisterURLRequestChromeJob() {
  FilePath inspector_dir;
  if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) {
    Singleton<ChromeURLDataManager>()->RemoveFileSource(
        chrome::kChromeUIDevToolsHost);
  }
}

// static
void ChromeURLDataManager::URLToRequest(const GURL& url,
                                        std::string* source_name,
                                        std::string* path) {
  DCHECK(url.SchemeIs(chrome::kChromeUIScheme));

  if (!url.is_valid()) {
    NOTREACHED();
    return;
  }

  // Our input looks like: chrome://source_name/extra_bits?foo .
  // So the url's "host" is our source, and everything after the host is
  // the path.
  source_name->assign(url.host());

  const std::string& spec = url.possibly_invalid_spec();
  const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
  // + 1 to skip the slash at the beginning of the path.
  int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false) + 1;

  if (offset < static_cast<int>(spec.size()))
    path->assign(spec.substr(offset));
}

// static
bool ChromeURLDataManager::URLToFilePath(const GURL& url,
                                         FilePath* file_path) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string relative_path;

  // Remove Query and Ref from URL.
  GURL stripped_url;
  GURL::Replacements replacements;
  replacements.ClearQuery();
  replacements.ClearRef();
  stripped_url = url.ReplaceComponents(replacements);

  URLToRequest(stripped_url, &source_name, &relative_path);

  FileSourceMap::const_iterator i(
      Singleton<ChromeURLDataManager>()->file_sources_.find(source_name));
  if (i == Singleton<ChromeURLDataManager>()->file_sources_.end())
    return false;

  // Check that |relative_path| is not an absolute path (otherwise AppendASCII()
  // will DCHECK). The awkward use of StringType is because on some systems
  // FilePath expects a std::string, but on others a std::wstring.
  FilePath p(FilePath::StringType(relative_path.begin(), relative_path.end()));
  if (p.IsAbsolute())
    return false;

  *file_path = i->second.AppendASCII(relative_path);

  return true;
}

ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { }

ChromeURLDataManager::~ChromeURLDataManager() { }

void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) {
  // TODO(jackson): A new data source with same name should not clobber the
  // existing one.
  data_sources_[source->source_name()] = source;
}

void ChromeURLDataManager::AddFileSource(const std::string& source_name,
                                         const FilePath& file_path) {
  DCHECK(file_sources_.count(source_name) == 0);
  file_sources_[source_name] = file_path;
}

void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) {
  DCHECK(file_sources_.count(source_name) == 1);
  file_sources_.erase(source_name);
}

bool ChromeURLDataManager::HasPendingJob(URLRequestChromeJob* job) const {
  for (PendingRequestMap::const_iterator i = pending_requests_.begin();
       i != pending_requests_.end(); ++i) {
    if (i->second == job)
      return true;
  }

  return false;
}

bool ChromeURLDataManager::StartRequest(const GURL& url,
                                        URLRequestChromeJob* job) {
  // Parse the URL into a request for a source and path.
  std::string source_name;
  std::string path;
  URLToRequest(url, &source_name, &path);

  // Look up the data source for the request.
  DataSourceMap::iterator i = data_sources_.find(source_name);
  if (i == data_sources_.end())
    return false;
  DataSource* source = i->second;

  // Save this request so we know where to send the data.
  RequestID request_id = next_request_id_++;
  pending_requests_.insert(std::make_pair(request_id, job));

  // TODO(eroman): would be nicer if the mimetype were set at the same time
  // as the data blob. For now do it here, since NotifyHeadersComplete() is
  // going to get called once we return.
  job->SetMimeType(source->GetMimeType(path));

  ChromeURLRequestContext* context = static_cast<ChromeURLRequestContext*>(
      job->request()->context());

  // Forward along the request to the data source.
  MessageLoop* target_message_loop = source->MessageLoopForRequestPath(path);
  if (!target_message_loop) {
    // The DataSource is agnostic to which thread StartDataRequest is called
    // on for this path.  Call directly into it from this thread, the IO
    // thread.
    source->StartDataRequest(path, context->is_off_the_record(), request_id);
  } else {
    // The DataSource wants StartDataRequest to be called on a specific thread,
    // usually the UI thread, for this path.
    target_message_loop->PostTask(FROM_HERE,
        NewRunnableMethod(source, &DataSource::StartDataRequest,
                          path, context->is_off_the_record(), request_id));
  }
  return true;
}

void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) {
  // Remove the request from our list of pending requests.
  // If/when the source sends the data that was requested, the data will just
  // be thrown away.
  for (PendingRequestMap::iterator i = pending_requests_.begin();
       i != pending_requests_.end(); ++i) {
    if (i->second == job) {
      pending_requests_.erase(i);
      return;
    }
  }
}

void ChromeURLDataManager::DataAvailable(
    RequestID request_id,
    scoped_refptr<RefCountedMemory> bytes) {
  // Forward this data on to the pending URLRequest, if it exists.
  PendingRequestMap::iterator i = pending_requests_.find(request_id);
  if (i != pending_requests_.end()) {
    // We acquire a reference to the job so that it doesn't disappear under the
    // feet of any method invoked here (we could trigger a callback).
    scoped_refptr<URLRequestChromeJob> job = i->second;
    pending_requests_.erase(i);
    job->DataAvailable(bytes);
  }
}

void ChromeURLDataManager::DataSource::SendResponse(
    RequestID request_id,
    RefCountedMemory* bytes) {
  ChromeThread::PostTask(
      ChromeThread::IO, FROM_HERE,
      NewRunnableMethod(Singleton<ChromeURLDataManager>::get(),
                        &ChromeURLDataManager::DataAvailable,
                        request_id, scoped_refptr<RefCountedMemory>(bytes)));
}

MessageLoop* ChromeURLDataManager::DataSource::MessageLoopForRequestPath(
    const std::string& path) const {
  return message_loop_;
}

// static
void ChromeURLDataManager::DataSource::SetFontAndTextDirection(
    DictionaryValue* localized_strings) {
  localized_strings->SetString(L"fontfamily",
      l10n_util::GetString(IDS_WEB_FONT_FAMILY));

  int web_font_size_id = IDS_WEB_FONT_SIZE;
#if defined(OS_WIN)
  // Some fonts used for some languages changed a lot in terms of the font
  // metric in Vista. So, we need to use different size before Vista.
  if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
    web_font_size_id = IDS_WEB_FONT_SIZE_XP;
#endif
  localized_strings->SetString(L"fontsize",
      l10n_util::GetString(web_font_size_id));

  localized_strings->SetString(L"textdirection",
      base::i18n::IsRTL() ? L"rtl" : L"ltr");
}

URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request,
                                             const std::string& scheme) {
  // Try first with a file handler
  FilePath path;
  if (ChromeURLDataManager::URLToFilePath(request->url(), &path))
    return new URLRequestChromeFileJob(request, path);

  // Next check for chrome://view-http-cache/*, which uses its own job type.
  if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
    return ViewHttpCacheJobFactory::CreateJobForRequest(request);

  // Next check for chrome://appcache-internals/, which uses its own job type.
  if (ViewAppCacheInternalsJobFactory::IsSupportedURL(request->url()))
    return ViewAppCacheInternalsJobFactory::CreateJobForRequest(request);

  // Fall back to using a custom handler
  return new URLRequestChromeJob(request);
}

URLRequestChromeJob::URLRequestChromeJob(URLRequest* request)
    : URLRequestJob(request),
      data_offset_(0),
      pending_buf_size_(0) {
}

URLRequestChromeJob::~URLRequestChromeJob() {
  CHECK(!Singleton<ChromeURLDataManager>()->HasPendingJob(this));
}

void URLRequestChromeJob::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
      this, &URLRequestChromeJob::StartAsync));
}

void URLRequestChromeJob::Kill() {
  Singleton<ChromeURLDataManager>()->RemoveRequest(this);
}

bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const {
  *mime_type = mime_type_;
  return !mime_type_.empty();
}

void URLRequestChromeJob::DataAvailable(RefCountedMemory* bytes) {
  if (bytes) {
    // The request completed, and we have all the data.
    // Clear any IO pending status.
    SetStatus(URLRequestStatus());

    data_ = bytes;
    int bytes_read;
    if (pending_buf_.get()) {
      CHECK(pending_buf_->data());
      CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
      pending_buf_ = NULL;
      NotifyReadComplete(bytes_read);
    }
  } else {
    // The request failed.
    NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_FAILED));
  }
}

bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
                                      int* bytes_read) {
  if (!data_.get()) {
    SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
    DCHECK(!pending_buf_.get());
    CHECK(buf->data());
    pending_buf_ = buf;
    pending_buf_size_ = buf_size;
    return false;  // Tell the caller we're still waiting for data.
  }

  // Otherwise, the data is available.
  CompleteRead(buf, buf_size, bytes_read);
  return true;
}

void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
                                       int* bytes_read) {
  int remaining = static_cast<int>(data_->size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), data_->front() + data_offset_, buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
}

void URLRequestChromeJob::StartAsync() {
  if (!request_)
    return;

  if (Singleton<ChromeURLDataManager>()->StartRequest(request_->url(), this)) {
    NotifyHeadersComplete();
  } else {
    NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
                                      net::ERR_INVALID_URL));
  }
}

URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request,
                                                 const FilePath& path)
    : URLRequestFileJob(request, path) {
}

URLRequestChromeFileJob::~URLRequestChromeFileJob() { }
<|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/ref_counted.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

class MediaPlayerBrowserTest : public InProcessBrowserTest {
 public:
  MediaPlayerBrowserTest() {}

  GURL GetMusicTestURL() {
    return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3");
  }

  bool IsPlayerVisible() {
    for (BrowserList::const_iterator it = BrowserList::begin();
         it != BrowserList::end(); ++it) {
      if ((*it)->type() == Browser::TYPE_POPUP) {
        const GURL& url =
            (*it)->GetTabContentsAt((*it)->selected_index())->GetURL();

        if (url.SchemeIs(chrome::kChromeUIScheme) &&
            url.host() == chrome::kChromeUIMediaplayerHost) {
          return true;
        }
      }
    }
    return false;
  }

  bool IsPlaylistVisible() {
    for (BrowserList::const_iterator it = BrowserList::begin();
         it != BrowserList::end(); ++it) {
      if ((*it)->type() == Browser::TYPE_POPUP) {
        const GURL& url =
            (*it)->GetTabContentsAt((*it)->selected_index())->GetURL();

        if (url.SchemeIs(chrome::kChromeUIScheme) &&
            url.host() == chrome::kChromeUIMediaplayerHost &&
            url.ref() == "playlist") {
          return true;
        }
      }
    }
    return false;
  }
};

IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) {
  ASSERT_TRUE(StartHTTPServer());
  // Doing this so we have a valid profile.
  ui_test_utils::NavigateToURL(browser(),
                               GURL("chrome://downloads"));
  MediaPlayer* player = MediaPlayer::Get();
  // Check that its not currently visible
  ASSERT_FALSE(IsPlayerVisible());

  player->EnqueueMediaURL(GetMusicTestURL());

  ASSERT_TRUE(IsPlayerVisible());
}

IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) {
  ASSERT_TRUE(StartHTTPServer());
  // Doing this so we have a valid profile.
  ui_test_utils::NavigateToURL(browser(),
                               GURL("chrome://downloads"));
  MediaPlayer* player = MediaPlayer::Get();

  player->EnqueueMediaURL(GetMusicTestURL());

  EXPECT_FALSE(IsPlaylistVisible());

  player->TogglePlaylistWindowVisible();

  EXPECT_TRUE(IsPlaylistVisible());
}

}  // namespace
<commit_msg>Revert 47363 - Fix build on ChromeOS by adding required return value checks.<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/ref_counted.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

class MediaPlayerBrowserTest : public InProcessBrowserTest {
 public:
  MediaPlayerBrowserTest() {}

  GURL GetMusicTestURL() {
    return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3");
  }

  bool IsPlayerVisible() {
    for (BrowserList::const_iterator it = BrowserList::begin();
         it != BrowserList::end(); ++it) {
      if ((*it)->type() == Browser::TYPE_POPUP) {
        const GURL& url =
            (*it)->GetTabContentsAt((*it)->selected_index())->GetURL();

        if (url.SchemeIs(chrome::kChromeUIScheme) &&
            url.host() == chrome::kChromeUIMediaplayerHost) {
          return true;
        }
      }
    }
    return false;
  }

  bool IsPlaylistVisible() {
    for (BrowserList::const_iterator it = BrowserList::begin();
         it != BrowserList::end(); ++it) {
      if ((*it)->type() == Browser::TYPE_POPUP) {
        const GURL& url =
            (*it)->GetTabContentsAt((*it)->selected_index())->GetURL();

        if (url.SchemeIs(chrome::kChromeUIScheme) &&
            url.host() == chrome::kChromeUIMediaplayerHost &&
            url.ref() == "playlist") {
          return true;
        }
      }
    }
    return false;
  }
};

IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) {
  StartHTTPServer();
  // Doing this so we have a valid profile.
  ui_test_utils::NavigateToURL(browser(),
                               GURL("chrome://downloads"));
  MediaPlayer* player = MediaPlayer::Get();
  // Check that its not currently visible
  ASSERT_FALSE(IsPlayerVisible());

  player->EnqueueMediaURL(GetMusicTestURL());

  ASSERT_TRUE(IsPlayerVisible());
}

IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) {
  StartHTTPServer();
  // Doing this so we have a valid profile.
  ui_test_utils::NavigateToURL(browser(),
                               GURL("chrome://downloads"));
  MediaPlayer* player = MediaPlayer::Get();

  player->EnqueueMediaURL(GetMusicTestURL());

  EXPECT_FALSE(IsPlaylistVisible());

  player->TogglePlaylistWindowVisible();

  EXPECT_TRUE(IsPlaylistVisible());
}

}  // namespace
<|endoftext|>


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

#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/platform_app_browsertest_util.h"
#include "chrome/common/chrome_switches.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"

class AdViewTest : public extensions::PlatformAppBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableAdview);
    command_line->AppendSwitch(switches::kEnableAdviewSrcAttribute);
  }
};

// This test checks the "loadcommit" event is called when the page inside an
// <adview> is loaded.
#if defined(OS_MACOSX)
// Very flaky on MacOS 10.8.
#define MAYBE_LoadCommitEventIsCalled DISABLED_LoadCommitEventIsCalled
#else
#define MAYBE_LoadCommitEventIsCalled LoadCommitEventIsCalled
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_LoadCommitEventIsCalled) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/loadcommit_event")) << message_;
}

// This test checks the "loadabort" event is called when the "src" attribute
// of an <adview> is an invalid URL.
IN_PROC_BROWSER_TEST_F(AdViewTest, LoadAbortEventIsCalled) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/loadabort_event")) << message_;
}

// This test checks the page loaded inside an <adview> has the ability to
// 1) receive "message" events from the application, and 2) use
// "window.postMessage" to post back a message to the application.
#if defined(OS_WIN)
// Flaky, or takes too long time on Win7. (http://crbug.com/230271)
#define MAYBE_CommitMessageFromAdNetwork DISABLED_CommitMessageFromAdNetwork
#else
#define MAYBE_CommitMessageFromAdNetwork CommitMessageFromAdNetwork
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_CommitMessageFromAdNetwork) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/onloadcommit_ack")) << message_;
}

// This test checks the page running inside an <adview> has the ability to load
// and display an image inside an <iframe>.
// Note: Disabled for initial checkin because the test depends on a binary
//       file (image035.png) which the trybots don't process correctly when
//       first checked-in.
IN_PROC_BROWSER_TEST_F(AdViewTest, DISABLED_DisplayFirstAd) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/display_first_ad")) << message_;
}

// This test checks that <adview> attributes are also exposed as properties
// (with the same name and value).
IN_PROC_BROWSER_TEST_F(AdViewTest, PropertiesAreInSyncWithAttributes) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/properties_exposed")) << message_;
}

// This test checks an <adview> element has no behavior when the "adview"
// permission is missing from the application manifest.
IN_PROC_BROWSER_TEST_F(AdViewTest, AdViewPermissionIsRequired) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/permission_required")) << message_;
}

// This test checks that 1) it is possible change the value of the "ad-network"
// attribute of an <adview> element and 2) changing the value will reset the
// "src" attribute.
IN_PROC_BROWSER_TEST_F(AdViewTest, ChangeAdNetworkValue) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/change_ad_network")) << message_;
}

class AdViewNoSrcTest : public extensions::PlatformAppBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableAdview);
    //Note: The "kEnableAdviewSrcAttribute" flag is not here!
  }
};

// This test checks an invalid "ad-network" value (i.e. not whitelisted)
// is ignored.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, InvalidAdNetworkIsIgnored) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/invalid_ad_network")) << message_;
}

// This test checks the "src" attribute is ignored when the
// "kEnableAdviewSrcAttribute" is missing.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, EnableAdviewSrcAttributeFlagRequired) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/src_flag_required")) << message_;
}

// This test checks 1) an <adview> works end-to-end (i.e. page is loaded) when
// using a whitelisted ad-network, and 2) the "src" attribute is never exposed
// to the application.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, SrcNotExposed) {
  base::FilePath file_path = test_data_dir_
    .AppendASCII("platform_apps")
    .AppendASCII("ad_view/src_not_exposed")
    .AppendASCII("ad_network_fake_website.html");

  // Note: The following URL is identical to the whitelisted url
  //       for "admob" (see ad_view.js).
  GURL url = GURL("https://admob-sdk.doubleclick.net/chromeapps");
  std::string scheme = url.scheme();
  std::string hostname = url.host();

  content::URLRequestPrepackagedInterceptor interceptor(scheme, hostname);
  interceptor.SetResponse(url, file_path);

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/src_not_exposed")) << message_;
  ASSERT_EQ(1, interceptor.GetHitCount());
}

class AdViewNotEnabledTest : public extensions::PlatformAppBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
    //Note: The "kEnableAdview" flag is not here!
  }
};

// This test checks an <adview> element has no behavior when the "kEnableAdview"
// flag is missing.
IN_PROC_BROWSER_TEST_F(AdViewNotEnabledTest, EnableAdviewFlagRequired) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/flag_required")) << message_;
}
<commit_msg>Disable AdviewTest.ChangeAdNetworkValue browsertest (flaky on Mac10.8).<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/platform_app_browsertest_util.h"
#include "chrome/common/chrome_switches.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"

class AdViewTest : public extensions::PlatformAppBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableAdview);
    command_line->AppendSwitch(switches::kEnableAdviewSrcAttribute);
  }
};

// This test checks the "loadcommit" event is called when the page inside an
// <adview> is loaded.
#if defined(OS_MACOSX)
// Very flaky on MacOS 10.8.
#define MAYBE_LoadCommitEventIsCalled DISABLED_LoadCommitEventIsCalled
#else
#define MAYBE_LoadCommitEventIsCalled LoadCommitEventIsCalled
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_LoadCommitEventIsCalled) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/loadcommit_event")) << message_;
}

// This test checks the "loadabort" event is called when the "src" attribute
// of an <adview> is an invalid URL.
IN_PROC_BROWSER_TEST_F(AdViewTest, LoadAbortEventIsCalled) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/loadabort_event")) << message_;
}

// This test checks the page loaded inside an <adview> has the ability to
// 1) receive "message" events from the application, and 2) use
// "window.postMessage" to post back a message to the application.
#if defined(OS_WIN)
// Flaky, or takes too long time on Win7. (http://crbug.com/230271)
#define MAYBE_CommitMessageFromAdNetwork DISABLED_CommitMessageFromAdNetwork
#else
#define MAYBE_CommitMessageFromAdNetwork CommitMessageFromAdNetwork
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, MAYBE_CommitMessageFromAdNetwork) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/onloadcommit_ack")) << message_;
}

// This test checks the page running inside an <adview> has the ability to load
// and display an image inside an <iframe>.
// Note: Disabled for initial checkin because the test depends on a binary
//       file (image035.png) which the trybots don't process correctly when
//       first checked-in.
IN_PROC_BROWSER_TEST_F(AdViewTest, DISABLED_DisplayFirstAd) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/display_first_ad")) << message_;
}

// This test checks that <adview> attributes are also exposed as properties
// (with the same name and value).
IN_PROC_BROWSER_TEST_F(AdViewTest, PropertiesAreInSyncWithAttributes) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/properties_exposed")) << message_;
}

// This test checks an <adview> element has no behavior when the "adview"
// permission is missing from the application manifest.
IN_PROC_BROWSER_TEST_F(AdViewTest, AdViewPermissionIsRequired) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/permission_required")) << message_;
}

// This test checks that 1) it is possible change the value of the "ad-network"
// attribute of an <adview> element and 2) changing the value will reset the
// "src" attribute.
#if defined(OS_MACOSX)
// Very flaky on MacOS 10.8 - crbug.com/253644.
#define MAYBE_ChangeAdNetworkValue DISABLED_ChangeAdNetworkValue
#else
#define MAYBE_ChangeAdNetworkValue ChangeAdNetworkValue
#endif
IN_PROC_BROWSER_TEST_F(AdViewTest, ChangeAdNetworkValue) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/change_ad_network")) << message_;
}

class AdViewNoSrcTest : public extensions::PlatformAppBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableAdview);
    //Note: The "kEnableAdviewSrcAttribute" flag is not here!
  }
};

// This test checks an invalid "ad-network" value (i.e. not whitelisted)
// is ignored.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, InvalidAdNetworkIsIgnored) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/invalid_ad_network")) << message_;
}

// This test checks the "src" attribute is ignored when the
// "kEnableAdviewSrcAttribute" is missing.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, EnableAdviewSrcAttributeFlagRequired) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/src_flag_required")) << message_;
}

// This test checks 1) an <adview> works end-to-end (i.e. page is loaded) when
// using a whitelisted ad-network, and 2) the "src" attribute is never exposed
// to the application.
IN_PROC_BROWSER_TEST_F(AdViewNoSrcTest, SrcNotExposed) {
  base::FilePath file_path = test_data_dir_
    .AppendASCII("platform_apps")
    .AppendASCII("ad_view/src_not_exposed")
    .AppendASCII("ad_network_fake_website.html");

  // Note: The following URL is identical to the whitelisted url
  //       for "admob" (see ad_view.js).
  GURL url = GURL("https://admob-sdk.doubleclick.net/chromeapps");
  std::string scheme = url.scheme();
  std::string hostname = url.host();

  content::URLRequestPrepackagedInterceptor interceptor(scheme, hostname);
  interceptor.SetResponse(url, file_path);

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/src_not_exposed")) << message_;
  ASSERT_EQ(1, interceptor.GetHitCount());
}

class AdViewNotEnabledTest : public extensions::PlatformAppBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
    //Note: The "kEnableAdview" flag is not here!
  }
};

// This test checks an <adview> element has no behavior when the "kEnableAdview"
// flag is missing.
IN_PROC_BROWSER_TEST_F(AdViewNotEnabledTest, EnableAdviewFlagRequired) {
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunPlatformAppTest(
      "platform_apps/ad_view/flag_required")) << message_;
}
<|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/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class ExperimentalApiTest : public ExtensionApiTest {
public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // It's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}

// TODO(gregoryd): run the NaCl test on all systems once
// http://code.google.com/p/chromium/issues/detail?id=51335 is fixed.
// Meanwhile we run it on Mac OSX only, since we can be sure that an x86-32 NaCl
// module will work there.
// Mark as Flaky.  http://crbug.com/51861
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_NaClPermissionEnabled) {
  ASSERT_TRUE(RunExtensionTest("permissions/nacl_enabled")) << message_;
}
#endif
<commit_msg>Copyright change to kick off new build.<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/common/chrome_switches.h"

class ExperimentalApiTest : public ExtensionApiTest {
public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // It's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}

// TODO(gregoryd): run the NaCl test on all systems once
// http://code.google.com/p/chromium/issues/detail?id=51335 is fixed.
// Meanwhile we run it on Mac OSX only, since we can be sure that an x86-32 NaCl
// module will work there.
// Mark as Flaky.  http://crbug.com/51861
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_NaClPermissionEnabled) {
  ASSERT_TRUE(RunExtensionTest("permissions/nacl_enabled")) << message_;
}
#endif
<|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/ui/android/tab_model/tab_model.h"

#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/search_terms_data.h"
#include "chrome/browser/sync/glue/synced_window_delegate_android.h"
#include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"

using content::NotificationService;

TabModel::TabModel(Profile* profile)
  : profile_(profile),
    synced_window_delegate_(
        new browser_sync::SyncedWindowDelegateAndroid(this)),
    toolbar_model_(new ToolbarModelImpl(this)) {

  if (profile) {
    // A normal Profile creates an OTR profile if it does not exist when
    // GetOffTheRecordProfile() is called, so we guard it with
    // HasOffTheRecordProfile(). An OTR profile returns itself when you call
    // GetOffTheRecordProfile().
    is_off_the_record_ = (profile->HasOffTheRecordProfile() &&
        profile == profile->GetOffTheRecordProfile());

    // A profile can be destroyed, for example in the case of closing all
    // incognito tabs. We therefore must listen for when this happens, and
    // remove our pointer to the profile accordingly.
    registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
                   content::Source<Profile>(profile_));
    registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
                   content::NotificationService::AllSources());
  } else {
    is_off_the_record_ = false;
  }
}

TabModel::TabModel()
  : profile_(NULL),
    is_off_the_record_(false),
    synced_window_delegate_(
        new browser_sync::SyncedWindowDelegateAndroid(this)) {
}

TabModel::~TabModel() {
}

content::WebContents* TabModel::GetActiveWebContents() const {
  if (GetTabCount() == 0 || GetActiveIndex() < 0 ||
      GetActiveIndex() > GetTabCount())
    return NULL;
  return GetWebContentsAt(GetActiveIndex());
}

Profile* TabModel::GetProfile() const {
  return profile_;
}

bool TabModel::IsOffTheRecord() const {
  return is_off_the_record_;
}

browser_sync::SyncedWindowDelegate* TabModel::GetSyncedWindowDelegate() const {
  return synced_window_delegate_.get();
}

SessionID::id_type TabModel::GetSessionId() const {
  return session_id_.id();
}

void TabModel::BroadcastSessionRestoreComplete() {
  if (profile_) {
    NotificationService::current()->Notify(
        chrome::NOTIFICATION_SESSION_RESTORE_COMPLETE,
        content::Source<Profile>(profile_),
        NotificationService::NoDetails());
  } else {
    // TODO(nyquist): Uncomment this once downstream Android uses new
    // constructor that takes a Profile* argument. See crbug.com/159704.
    // NOTREACHED();
  }
}

ToolbarModel* TabModel::GetToolbarModel() {
  return toolbar_model_.get();
}

ToolbarModel::SecurityLevel TabModel::GetSecurityLevelForCurrentTab() {
  return toolbar_model_->GetSecurityLevel();
}

string16 TabModel::GetSearchTermsForCurrentTab() {
  return toolbar_model_->GetText(true);
}

std::string TabModel::GetQueryExtractionParam() {
  if (!profile_)
    return std::string();
  UIThreadSearchTermsData search_terms_data(profile_);
  return search_terms_data.InstantExtendedEnabledParam();
}

string16 TabModel::GetCorpusNameForCurrentTab() {
  return toolbar_model_->GetCorpusNameForMobile();
}

void TabModel::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_PROFILE_DESTROYED:
      // Our profile just got destroyed, so we delete our pointer to it.
      profile_ = NULL;
      break;
    case chrome::NOTIFICATION_PROFILE_CREATED:
      // Our incognito tab model out lives the profile, so we need to recapture
      // the pointer if ours was previously deleted.
      // NOTIFICATION_PROFILE_DESTROYED is not sent for every destruction, so
      // we overwrite the pointer regardless of whether it's NULL.
      if (is_off_the_record_) {
        Profile* profile = content::Source<Profile>(source).ptr();
        if (profile && profile->IsOffTheRecord())
          profile_ = profile;
      }
      break;
    default:
      NOTREACHED();
  }
}
<commit_msg>Set toolbar model to support extraction of url like search terms<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/ui/android/tab_model/tab_model.h"

#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/search_terms_data.h"
#include "chrome/browser/sync/glue/synced_window_delegate_android.h"
#include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"

using content::NotificationService;

TabModel::TabModel(Profile* profile)
  : profile_(profile),
    synced_window_delegate_(
        new browser_sync::SyncedWindowDelegateAndroid(this)),
    toolbar_model_(new ToolbarModelImpl(this)) {

  if (profile) {
    // A normal Profile creates an OTR profile if it does not exist when
    // GetOffTheRecordProfile() is called, so we guard it with
    // HasOffTheRecordProfile(). An OTR profile returns itself when you call
    // GetOffTheRecordProfile().
    is_off_the_record_ = (profile->HasOffTheRecordProfile() &&
        profile == profile->GetOffTheRecordProfile());

    // A profile can be destroyed, for example in the case of closing all
    // incognito tabs. We therefore must listen for when this happens, and
    // remove our pointer to the profile accordingly.
    registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
                   content::Source<Profile>(profile_));
    registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
                   content::NotificationService::AllSources());
  } else {
    is_off_the_record_ = false;
  }
  toolbar_model_->SetSupportsExtractionOfURLLikeSearchTerms(true);
}

TabModel::TabModel()
  : profile_(NULL),
    is_off_the_record_(false),
    synced_window_delegate_(
        new browser_sync::SyncedWindowDelegateAndroid(this)) {
}

TabModel::~TabModel() {
}

content::WebContents* TabModel::GetActiveWebContents() const {
  if (GetTabCount() == 0 || GetActiveIndex() < 0 ||
      GetActiveIndex() > GetTabCount())
    return NULL;
  return GetWebContentsAt(GetActiveIndex());
}

Profile* TabModel::GetProfile() const {
  return profile_;
}

bool TabModel::IsOffTheRecord() const {
  return is_off_the_record_;
}

browser_sync::SyncedWindowDelegate* TabModel::GetSyncedWindowDelegate() const {
  return synced_window_delegate_.get();
}

SessionID::id_type TabModel::GetSessionId() const {
  return session_id_.id();
}

void TabModel::BroadcastSessionRestoreComplete() {
  if (profile_) {
    NotificationService::current()->Notify(
        chrome::NOTIFICATION_SESSION_RESTORE_COMPLETE,
        content::Source<Profile>(profile_),
        NotificationService::NoDetails());
  } else {
    // TODO(nyquist): Uncomment this once downstream Android uses new
    // constructor that takes a Profile* argument. See crbug.com/159704.
    // NOTREACHED();
  }
}

ToolbarModel* TabModel::GetToolbarModel() {
  return toolbar_model_.get();
}

ToolbarModel::SecurityLevel TabModel::GetSecurityLevelForCurrentTab() {
  return toolbar_model_->GetSecurityLevel();
}

string16 TabModel::GetSearchTermsForCurrentTab() {
  return toolbar_model_->GetText(true);
}

std::string TabModel::GetQueryExtractionParam() {
  if (!profile_)
    return std::string();
  UIThreadSearchTermsData search_terms_data(profile_);
  return search_terms_data.InstantExtendedEnabledParam();
}

string16 TabModel::GetCorpusNameForCurrentTab() {
  return toolbar_model_->GetCorpusNameForMobile();
}

void TabModel::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_PROFILE_DESTROYED:
      // Our profile just got destroyed, so we delete our pointer to it.
      profile_ = NULL;
      break;
    case chrome::NOTIFICATION_PROFILE_CREATED:
      // Our incognito tab model out lives the profile, so we need to recapture
      // the pointer if ours was previously deleted.
      // NOTIFICATION_PROFILE_DESTROYED is not sent for every destruction, so
      // we overwrite the pointer regardless of whether it's NULL.
      if (is_off_the_record_) {
        Profile* profile = content::Source<Profile>(source).ptr();
        if (profile && profile->IsOffTheRecord())
          profile_ = profile;
      }
      break;
    default:
      NOTREACHED();
  }
}
<|endoftext|>