<commit_before>#include "ampfrm.h"
#include <qwt_knob.h>
#include <qwt_thermo.h>
#include <qwt_round_scale_draw.h>
#include <qwt_math.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qfont.h>
#include <qpen.h>
#include <qevent.h>

#if QT_VERSION < 0x040600
#define qFastSin(x) ::sin(x)
#define qFastCos(x) ::cos(x)
#endif

class Knob: public QWidget
{
public:
    Knob( const QString &title, double min, double max, QWidget *parent ):
        QWidget( parent )
    {
        d_knob = new QwtKnob( this );
        d_knob->setScale( min, max );
        d_knob->setTotalSteps( 0 ); // disable
        d_knob->setScaleMaxMajor( 10 );

        d_knob->setKnobStyle( QwtKnob::Raised );
        d_knob->setKnobWidth( 50 );
        d_knob->setBorderWidth( 2 );
        d_knob->setMarkerStyle( QwtKnob::Notch );
        d_knob->setMarkerSize( 8 );

        d_knob->scaleDraw()->setTickLength( QwtScaleDiv::MinorTick, 4 );
        d_knob->scaleDraw()->setTickLength( QwtScaleDiv::MediumTick, 4 );
        d_knob->scaleDraw()->setTickLength( QwtScaleDiv::MajorTick, 6 );

        d_label = new QLabel( title, this );
        d_label->setAlignment( Qt::AlignTop | Qt::AlignHCenter );

        setSizePolicy( QSizePolicy::MinimumExpanding,
            QSizePolicy::MinimumExpanding );
    }

    virtual QSize sizeHint() const
    {
        QSize sz1 = d_knob->sizeHint();
        QSize sz2 = d_label->sizeHint();

        const int w = qMax( sz1.width(), sz2.width() );
        const int h = sz1.height() + sz2.height();

        int off = qCeil( d_knob->scaleDraw()->extent( d_knob->font() ) );
        off -= 10; // spacing

        return QSize( w, h - off );
    }

    void setValue( double value )
    {
        d_knob->setValue( value );
    }

    double value() const
    {
        return d_knob->value();
    }

protected:
    virtual void resizeEvent( QResizeEvent *e )
    {
        const QSize sz = e->size();

        int h = d_label->sizeHint().height();

        d_label->setGeometry( 0, sz.height() - h, sz.width(), h );

        h = d_knob->sizeHint().height();
        int off = qCeil( d_knob->scaleDraw()->extent( d_knob->font() ) );
        off -= 10; // spacing

        d_knob->setGeometry( 0, d_label->pos().y() - h + off,
            sz.width(), h );
    }

private:
    QwtKnob *d_knob;
    QLabel *d_label;
};

class Thermo: public QWidget
{
public:
    Thermo( const QString &title, QWidget *parent ):
        QWidget( parent )
    {
        d_thermo = new QwtThermo( this );
        d_thermo->setPipeWidth( 6 );
        d_thermo->setScale( -40, 10 );
        d_thermo->setFillBrush( Qt::green );
        d_thermo->setAlarmBrush( Qt::red );
        d_thermo->setAlarmLevel( 0.0 );
        d_thermo->setAlarmEnabled( true );

        QLabel *label = new QLabel( title, this );
        label->setAlignment( Qt::AlignTop | Qt::AlignLeft );

        QVBoxLayout *layout = new QVBoxLayout( this );
        layout->setMargin( 0 );
        layout->setSpacing( 0 );
        layout->addWidget( d_thermo, 10 );
        layout->addWidget( label );
    }

    void setValue( double value )
    {
        d_thermo->setValue( value );
    }

private:
    QwtThermo *d_thermo;
};

AmpFrame::AmpFrame( QWidget *p ):
    QFrame( p )
{
    d_knbVolume = new Knob( "Volume", 0.0, 10.0, this );
    d_knbBalance = new Knob( "Balance", -10.0, 10.0, this );
    d_knbTreble = new Knob( "Treble", -10.0, 10.0, this );
    d_knbBass = new Knob( "Bass", -10.0, 10.0, this );

    d_thmLeft = new Thermo( "Left [dB]", this );
    d_thmRight = new Thermo( "Right [dB]", this );

    QHBoxLayout *layout = new QHBoxLayout( this );
    layout->setSpacing( 0 );
    layout->setMargin( 10 );
    layout->addWidget( d_knbVolume );
    layout->addWidget( d_knbBalance );
    layout->addWidget( d_knbTreble );
    layout->addWidget( d_knbBass );
    layout->addSpacing( 20 );
    layout->addStretch( 10 );
    layout->addWidget( d_thmLeft );
    layout->addSpacing( 10 );
    layout->addWidget( d_thmRight );

    d_knbVolume->setValue( 7.0 );
    ( void )startTimer( 50 );
}

void AmpFrame::timerEvent( QTimerEvent * )
{
    static double phs = 0;

    //
    //  This amplifier generates its own input signal...
    //

    const double sig_bass = ( 1.0 + 0.1 * d_knbBass->value() )
        * qFastSin( 13.0 * phs );
    const double sig_mid_l = qFastSin( 17.0 * phs );
    const double sig_mid_r = qFastCos( 17.5 * phs );
    const double sig_trbl_l = 0.5 * ( 1.0 + 0.1 * d_knbTreble->value() )
        * qFastSin( 35.0 * phs );
    const double sig_trbl_r = 0.5 * ( 1.0 + 0.1 * d_knbTreble->value() )
        * qFastSin( 34.0 * phs );

    double sig_l = 0.05 * d_master * d_knbVolume->value()
        * qwtSqr( sig_bass + sig_mid_l + sig_trbl_l );
    double sig_r = 0.05 * d_master * d_knbVolume->value()
        * qwtSqr( sig_bass + sig_mid_r + sig_trbl_r );

    double balance = 0.1 * d_knbBalance->value();
    if ( balance > 0 )
        sig_l *= ( 1.0 - balance );
    else
        sig_r *= ( 1.0 + balance );

    if ( sig_l > 0.01 )
        sig_l = 20.0 * log10( sig_l );
    else
        sig_l = -40.0;

    if ( sig_r > 0.01 )
        sig_r = 20.0 * log10( sig_r );
    else
        sig_r = - 40.0;

    d_thmLeft->setValue( sig_l );
    d_thmRight->setValue( sig_r );

    phs += M_PI / 100;
    if ( phs > M_PI )
        phs = 0;
}

void AmpFrame::setMaster( double v )
{
    d_master = v;
}
<commit_msg>knob alignemnt fixed<commit_after>#include "ampfrm.h"
#include <qwt_knob.h>
#include <qwt_thermo.h>
#include <qwt_round_scale_draw.h>
#include <qwt_math.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qfont.h>
#include <qpen.h>
#include <qevent.h>

#if QT_VERSION < 0x040600
#define qFastSin(x) ::sin(x)
#define qFastCos(x) ::cos(x)
#endif

class Knob: public QWidget
{
public:
    Knob( const QString &title, double min, double max, QWidget *parent ):
        QWidget( parent )
    {
        d_knob = new QwtKnob( this );
        d_knob->setScale( min, max );
        d_knob->setTotalSteps( 0 ); // disable
        d_knob->setScaleMaxMajor( 10 );

        d_knob->setKnobStyle( QwtKnob::Raised );
        d_knob->setKnobWidth( 50 );
        d_knob->setBorderWidth( 2 );
        d_knob->setMarkerStyle( QwtKnob::Notch );
        d_knob->setMarkerSize( 8 );

        d_knob->scaleDraw()->setTickLength( QwtScaleDiv::MinorTick, 4 );
        d_knob->scaleDraw()->setTickLength( QwtScaleDiv::MediumTick, 4 );
        d_knob->scaleDraw()->setTickLength( QwtScaleDiv::MajorTick, 6 );

        d_label = new QLabel( title, this );
        d_label->setAlignment( Qt::AlignTop | Qt::AlignHCenter );

        setSizePolicy( QSizePolicy::MinimumExpanding,
            QSizePolicy::MinimumExpanding );
    }

    virtual QSize sizeHint() const
    {
        QSize sz1 = d_knob->sizeHint();
        QSize sz2 = d_label->sizeHint();

        const int w = qMax( sz1.width(), sz2.width() );
        const int h = sz1.height() + sz2.height();

        int off = qCeil( d_knob->scaleDraw()->extent( d_knob->font() ) );
        off -= 10; // spacing

        return QSize( w, h - off );
    }

    void setValue( double value )
    {
        d_knob->setValue( value );
    }

    double value() const
    {
        return d_knob->value();
    }

protected:
    virtual void resizeEvent( QResizeEvent *e )
    {
        const QSize sz = e->size();

        int h = d_label->sizeHint().height();

        d_label->setGeometry( 0, sz.height() - h, sz.width(), h );

        h = d_knob->sizeHint().height();
        int off = qCeil( d_knob->scaleDraw()->extent( d_knob->font() ) );
        off -= 10; // spacing

        d_knob->setGeometry( 0, d_label->pos().y() - h + off,
            sz.width(), h );
    }

private:
    QwtKnob *d_knob;
    QLabel *d_label;
};

class Thermo: public QWidget
{
public:
    Thermo( const QString &title, QWidget *parent ):
        QWidget( parent )
    {
        d_thermo = new QwtThermo( this );
        d_thermo->setPipeWidth( 6 );
        d_thermo->setScale( -40, 10 );
        d_thermo->setFillBrush( Qt::green );
        d_thermo->setAlarmBrush( Qt::red );
        d_thermo->setAlarmLevel( 0.0 );
        d_thermo->setAlarmEnabled( true );

        QLabel *label = new QLabel( title, this );
        label->setAlignment( Qt::AlignTop | Qt::AlignLeft );

        QVBoxLayout *layout = new QVBoxLayout( this );
        layout->setMargin( 0 );
        layout->setSpacing( 0 );
        layout->addWidget( d_thermo, 10 );
        layout->addWidget( label );
    }

    void setValue( double value )
    {
        d_thermo->setValue( value );
    }

private:
    QwtThermo *d_thermo;
};

AmpFrame::AmpFrame( QWidget *p ):
    QFrame( p )
{
    d_knbVolume = new Knob( "Volume", 0.0, 10.0, this );
    d_knbBalance = new Knob( "Balance", -10.0, 10.0, this );
    d_knbTreble = new Knob( "Treble", -10.0, 10.0, this );
    d_knbBass = new Knob( "Bass", -10.0, 10.0, this );

    d_thmLeft = new Thermo( "Left [dB]", this );
    d_thmRight = new Thermo( "Right [dB]", this );

    QHBoxLayout *layout = new QHBoxLayout( this );
    layout->setSpacing( 0 );
    layout->setMargin( 10 );
    layout->addWidget( d_knbVolume, 0, Qt::AlignHCenter | Qt::AlignTop );
    layout->addWidget( d_knbBalance, 0, Qt::AlignHCenter | Qt::AlignTop );
    layout->addWidget( d_knbTreble, 0, Qt::AlignHCenter | Qt::AlignTop );
    layout->addWidget( d_knbBass, 0, Qt::AlignHCenter | Qt::AlignTop );
    layout->addSpacing( 20 );
    layout->addStretch( 10 );
    layout->addWidget( d_thmLeft );
    layout->addSpacing( 10 );
    layout->addWidget( d_thmRight );

    d_knbVolume->setValue( 7.0 );
    ( void )startTimer( 50 );
}

void AmpFrame::timerEvent( QTimerEvent * )
{
    static double phs = 0;

    //
    //  This amplifier generates its own input signal...
    //

    const double sig_bass = ( 1.0 + 0.1 * d_knbBass->value() )
        * qFastSin( 13.0 * phs );
    const double sig_mid_l = qFastSin( 17.0 * phs );
    const double sig_mid_r = qFastCos( 17.5 * phs );
    const double sig_trbl_l = 0.5 * ( 1.0 + 0.1 * d_knbTreble->value() )
        * qFastSin( 35.0 * phs );
    const double sig_trbl_r = 0.5 * ( 1.0 + 0.1 * d_knbTreble->value() )
        * qFastSin( 34.0 * phs );

    double sig_l = 0.05 * d_master * d_knbVolume->value()
        * qwtSqr( sig_bass + sig_mid_l + sig_trbl_l );
    double sig_r = 0.05 * d_master * d_knbVolume->value()
        * qwtSqr( sig_bass + sig_mid_r + sig_trbl_r );

    double balance = 0.1 * d_knbBalance->value();
    if ( balance > 0 )
        sig_l *= ( 1.0 - balance );
    else
        sig_r *= ( 1.0 + balance );

    if ( sig_l > 0.01 )
        sig_l = 20.0 * log10( sig_l );
    else
        sig_l = -40.0;

    if ( sig_r > 0.01 )
        sig_r = 20.0 * log10( sig_r );
    else
        sig_r = - 40.0;

    d_thmLeft->setValue( sig_l );
    d_thmRight->setValue( sig_r );

    phs += M_PI / 100;
    if ( phs > M_PI )
        phs = 0;
}

void AmpFrame::setMaster( double v )
{
    d_master = v;
}
<|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/views/info_bubble.h"

#include "base/keyboard_codes.h"
#include "chrome/browser/window_sizer.h"
#include "chrome/common/notification_service.h"
#include "gfx/canvas.h"
#include "gfx/color_utils.h"
#include "gfx/path.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "views/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/client_view.h"
#include "views/window/window.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#endif

// Background color of the bubble.
#if defined(OS_WIN)
const SkColor InfoBubble::kBackgroundColor =
    color_utils::GetSysSkColor(COLOR_WINDOW);
#else
// TODO(beng): source from theme provider.
const SkColor InfoBubble::kBackgroundColor = SK_ColorWHITE;
#endif

void BorderContents::Init() {
  DCHECK(!bubble_border_);
  bubble_border_ = new BubbleBorder(BubbleBorder::TOP_LEFT);
  set_border(bubble_border_);
  bubble_border_->set_background_color(InfoBubble::kBackgroundColor);
}

void BorderContents::SizeAndGetBounds(
    const gfx::Rect& position_relative_to,
    BubbleBorder::ArrowLocation arrow_location,
    bool allow_bubble_offscreen,
    const gfx::Size& contents_size,
    gfx::Rect* contents_bounds,
    gfx::Rect* window_bounds) {
  if (base::i18n::IsRTL())
    arrow_location = BubbleBorder::rtl_mirror(arrow_location);
  bubble_border_->set_arrow_location(arrow_location);
  // Set the border.
  set_border(bubble_border_);
  bubble_border_->set_background_color(InfoBubble::kBackgroundColor);

  // Give the contents a margin.
  gfx::Size local_contents_size(contents_size);
  local_contents_size.Enlarge(kLeftMargin + kRightMargin,
                              kTopMargin + kBottomMargin);

  // Try putting the arrow in its initial location, and calculating the bounds.
  *window_bounds =
      bubble_border_->GetBounds(position_relative_to, local_contents_size);

  if (!allow_bubble_offscreen) {
    // See if those bounds will fit on the monitor.
    scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider(
        WindowSizer::CreateDefaultMonitorInfoProvider());
    gfx::Rect monitor_bounds(
        monitor_provider->GetMonitorWorkAreaMatching(position_relative_to));
    if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) {
      // The bounds don't fit.  Move the arrow to try and improve things.
      if (window_bounds->bottom() > monitor_bounds.bottom())
        arrow_location = BubbleBorder::horizontal_mirror(arrow_location);
      else if (BubbleBorder::is_arrow_on_left(arrow_location) ?
               (window_bounds->right() > monitor_bounds.right()) :
               (window_bounds->x() < monitor_bounds.x())) {
        arrow_location = BubbleBorder::rtl_mirror(arrow_location);
      }

      bubble_border_->set_arrow_location(arrow_location);

      // Now get the recalculated bounds.
      *window_bounds = bubble_border_->GetBounds(position_relative_to,
                                                 local_contents_size);
    }
  }

  // Calculate the bounds of the contained contents (in window coordinates) by
  // subtracting the border dimensions and margin amounts.
  *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size());
  gfx::Insets insets;
  bubble_border_->GetInsets(&insets);
  contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin,
      insets.right() + kRightMargin, insets.bottom() + kBottomMargin);
}

void BorderContents::Paint(gfx::Canvas* canvas) {
  // The border of this view creates an anti-aliased round-rect region for the
  // contents, which we need to fill with the background color.
  // NOTE: This doesn't handle an arrow location of "NONE", which has square top
  // corners.
  SkPaint paint;
  paint.setAntiAlias(true);
  paint.setStyle(SkPaint::kFill_Style);
  paint.setColor(InfoBubble::kBackgroundColor);
  gfx::Path path;
  gfx::Rect bounds(GetLocalBounds(false));
  SkRect rect;
  rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()),
           SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom()));
  SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius());
  path.addRoundRect(rect, radius, radius);
  canvas->drawPath(path, paint);

  // Now we paint the border, so it will be alpha-blended atop the contents.
  // This looks slightly better in the corners than drawing the contents atop
  // the border.
  PaintBorder(canvas);
}

#if defined(OS_WIN)
// BorderWidget ---------------------------------------------------------------

BorderWidget::BorderWidget() : border_contents_(NULL) {
  set_delete_on_destroy(false);  // Our owner will free us manually.
  set_window_style(WS_POPUP);
  set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED);
}

void BorderWidget::Init(HWND owner) {
  DCHECK(!border_contents_);
  border_contents_ = CreateBorderContents();
  border_contents_->Init();
  WidgetWin::Init(GetAncestor(owner, GA_ROOT), gfx::Rect());
  SetContentsView(border_contents_);
  SetWindowPos(owner, 0, 0, 0, 0,
               SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW);
}

gfx::Rect BorderWidget::SizeAndGetBounds(
    const gfx::Rect& position_relative_to,
    BubbleBorder::ArrowLocation arrow_location,
    const gfx::Size& contents_size) {
  // Ask the border view to calculate our bounds (and our contents').
  gfx::Rect contents_bounds;
  gfx::Rect window_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to, arrow_location,
                                     false, contents_size, &contents_bounds,
                                     &window_bounds);
  SetBounds(window_bounds);

  // Chop a hole out of our region to show the contents through.
  // CreateRectRgn() expects (left, top, right, bottom) in window coordinates.
  HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(),
      contents_bounds.right(), contents_bounds.bottom());
  HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(),
                                     window_bounds.height());
  CombineRgn(window_region, window_region, contents_region, RGN_XOR);
  DeleteObject(contents_region);
  SetWindowRgn(window_region, true);

  // Return |contents_bounds| in screen coordinates.
  contents_bounds.Offset(window_bounds.origin());
  return contents_bounds;
}

BorderContents* BorderWidget::CreateBorderContents() {
  return new BorderContents();
}

LRESULT BorderWidget::OnMouseActivate(HWND window,
                                      UINT hit_test,
                                      UINT mouse_message) {
  // Never activate.
  return MA_NOACTIVATE;
}
#endif

// InfoBubble -----------------------------------------------------------------

// static
InfoBubble* InfoBubble::Show(views::Widget* parent,
                             const gfx::Rect& position_relative_to,
                             BubbleBorder::ArrowLocation arrow_location,
                             views::View* contents,
                             InfoBubbleDelegate* delegate) {
  InfoBubble* window = new InfoBubble;
  window->Init(parent, position_relative_to, arrow_location,
               contents, delegate);
  return window;
}

void InfoBubble::Close() {
  Close(false);
}

InfoBubble::InfoBubble()
    :
#if defined(OS_LINUX)
      WidgetGtk(TYPE_WINDOW),
      border_contents_(NULL),
#endif
      delegate_(NULL),
      closed_(false) {
}

void InfoBubble::Init(views::Widget* parent,
                      const gfx::Rect& position_relative_to,
                      BubbleBorder::ArrowLocation arrow_location,
                      views::View* contents,
                      InfoBubbleDelegate* delegate) {
  delegate_ = delegate;
  position_relative_to_ = position_relative_to;
  arrow_location_ = arrow_location;
  contents_ = contents;

  // Create the main window.
#if defined(OS_WIN)
  views::Window* parent_window = parent->GetWindow();
  if (parent_window)
    parent_window->DisableInactiveRendering();
  set_window_style(WS_POPUP | WS_CLIPCHILDREN);
  set_window_ex_style(WS_EX_TOOLWINDOW);
  WidgetWin::Init(parent->GetNativeView(), gfx::Rect());
#elif defined(OS_LINUX)
  MakeTransparent();
  make_transient_to_parent();
  WidgetGtk::Init(
      GTK_WIDGET(static_cast<WidgetGtk*>(parent)->GetNativeView()),
      gfx::Rect());
#if defined(OS_CHROMEOS)
  chromeos::WmIpc::instance()->SetWindowType(
      GetNativeView(),
      chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
      NULL);
#endif
#endif

  // Create a View to hold the contents of the main window.
  views::View* contents_view = new views::View;
  // We add |contents_view| to ourselves before the AddChildView() call below so
  // that when |contents| gets added, it will already have a widget, and thus
  // any NativeButtons it creates in ViewHierarchyChanged() will be functional
  // (e.g. calling SetChecked() on checkboxes is safe).
  SetContentsView(contents_view);
  // Adding |contents| as a child has to be done before we call
  // contents->GetPreferredSize() below, since some supplied views don't
  // actually initialize themselves until they're added to a hierarchy.
  contents_view->AddChildView(contents);

  // Calculate and set the bounds for all windows and views.
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  DCHECK(!border_.get());
  border_.reset(CreateBorderWidget());
  border_->Init(GetNativeView());

  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to,
                                            arrow_location,
                                            contents->GetPreferredSize());

  // Make |contents| take up the entire contents view.
  contents_view->SetLayoutManager(new views::FillLayout);

  // Paint the background color behind the contents.
  contents_view->set_background(
      views::Background::CreateSolidBackground(kBackgroundColor));
#else
  // Create a view to paint the border and background.
  border_contents_ = new BorderContents;
  border_contents_->Init();
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to,
      arrow_location, false, contents->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // This new view must be added before |contents| so it will paint under it.
  contents_view->AddChildView(0, border_contents_);

  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size()));
  contents->SetBounds(contents_bounds);
#endif
  SetBounds(window_bounds);

  // Register the Escape accelerator for closing.
  GetFocusManager()->RegisterAccelerator(
      views::Accelerator(base::VKEY_ESCAPE, false, false, false), this);

  // Done creating the bubble.
  NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED,
                                         Source<InfoBubble>(this),
                                         NotificationService::NoDetails());

  // Show the window.
#if defined(OS_WIN)
  border_->ShowWindow(SW_SHOW);
  ShowWindow(SW_SHOW);
#elif defined(OS_LINUX)
  views::WidgetGtk::Show();
#endif
}

#if defined(OS_WIN)
BorderWidget* InfoBubble::CreateBorderWidget() {
  return new BorderWidget;
}
#endif

void InfoBubble::SizeToContents() {
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to_,
                                            arrow_location_,
                                            contents_->GetPreferredSize());
#else
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to_,
      arrow_location_, false, contents_->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size()));
  contents_->SetBounds(contents_bounds);
#endif
  SetBounds(window_bounds);
}

#if defined(OS_WIN)
void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) {
  // The popup should close when it is deactivated.
  if (action == WA_INACTIVE && !closed_) {
    Close();
  } else if (action == WA_ACTIVE) {
    DCHECK(GetRootView()->GetChildViewCount() > 0);
    GetRootView()->GetChildViewAt(0)->RequestFocus();
  }
}
#elif defined(OS_LINUX)
void InfoBubble::IsActiveChanged() {
  if (!IsActive())
    Close();
}
#endif

void InfoBubble::Close(bool closed_by_escape) {
  if (closed_)
    return;

  if (delegate_)
    delegate_->InfoBubbleClosing(this, closed_by_escape);
  closed_ = true;
#if defined(OS_WIN)
  border_->Close();
  WidgetWin::Close();
#elif defined(OS_LINUX)
  WidgetGtk::Close();
#endif
}

bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) {
  if (!delegate_ || delegate_->CloseOnEscape()) {
    Close(true);
    return true;
  }
  return false;
}
<commit_msg>Fix default info_bubble arrow location for RTL.<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/views/info_bubble.h"

#include "base/keyboard_codes.h"
#include "chrome/browser/window_sizer.h"
#include "chrome/common/notification_service.h"
#include "gfx/canvas.h"
#include "gfx/color_utils.h"
#include "gfx/path.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "views/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/client_view.h"
#include "views/window/window.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#endif

// Background color of the bubble.
#if defined(OS_WIN)
const SkColor InfoBubble::kBackgroundColor =
    color_utils::GetSysSkColor(COLOR_WINDOW);
#else
// TODO(beng): source from theme provider.
const SkColor InfoBubble::kBackgroundColor = SK_ColorWHITE;
#endif

void BorderContents::Init() {
  // Default arrow location.
  BubbleBorder::ArrowLocation arrow_location = BubbleBorder::TOP_LEFT;
  if (base::i18n::IsRTL())
    arrow_location = BubbleBorder::rtl_mirror(arrow_location);
  DCHECK(!bubble_border_);
  bubble_border_ = new BubbleBorder(arrow_location);
  set_border(bubble_border_);
  bubble_border_->set_background_color(InfoBubble::kBackgroundColor);
}

void BorderContents::SizeAndGetBounds(
    const gfx::Rect& position_relative_to,
    BubbleBorder::ArrowLocation arrow_location,
    bool allow_bubble_offscreen,
    const gfx::Size& contents_size,
    gfx::Rect* contents_bounds,
    gfx::Rect* window_bounds) {
  if (base::i18n::IsRTL())
    arrow_location = BubbleBorder::rtl_mirror(arrow_location);
  bubble_border_->set_arrow_location(arrow_location);
  // Set the border.
  set_border(bubble_border_);
  bubble_border_->set_background_color(InfoBubble::kBackgroundColor);

  // Give the contents a margin.
  gfx::Size local_contents_size(contents_size);
  local_contents_size.Enlarge(kLeftMargin + kRightMargin,
                              kTopMargin + kBottomMargin);

  // Try putting the arrow in its initial location, and calculating the bounds.
  *window_bounds =
      bubble_border_->GetBounds(position_relative_to, local_contents_size);

  if (!allow_bubble_offscreen) {
    // See if those bounds will fit on the monitor.
    scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider(
        WindowSizer::CreateDefaultMonitorInfoProvider());
    gfx::Rect monitor_bounds(
        monitor_provider->GetMonitorWorkAreaMatching(position_relative_to));
    if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) {
      // The bounds don't fit.  Move the arrow to try and improve things.
      if (window_bounds->bottom() > monitor_bounds.bottom())
        arrow_location = BubbleBorder::horizontal_mirror(arrow_location);
      else if (BubbleBorder::is_arrow_on_left(arrow_location) ?
               (window_bounds->right() > monitor_bounds.right()) :
               (window_bounds->x() < monitor_bounds.x())) {
        arrow_location = BubbleBorder::rtl_mirror(arrow_location);
      }

      bubble_border_->set_arrow_location(arrow_location);

      // Now get the recalculated bounds.
      *window_bounds = bubble_border_->GetBounds(position_relative_to,
                                                 local_contents_size);
    }
  }

  // Calculate the bounds of the contained contents (in window coordinates) by
  // subtracting the border dimensions and margin amounts.
  *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size());
  gfx::Insets insets;
  bubble_border_->GetInsets(&insets);
  contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin,
      insets.right() + kRightMargin, insets.bottom() + kBottomMargin);
}

void BorderContents::Paint(gfx::Canvas* canvas) {
  // The border of this view creates an anti-aliased round-rect region for the
  // contents, which we need to fill with the background color.
  // NOTE: This doesn't handle an arrow location of "NONE", which has square top
  // corners.
  SkPaint paint;
  paint.setAntiAlias(true);
  paint.setStyle(SkPaint::kFill_Style);
  paint.setColor(InfoBubble::kBackgroundColor);
  gfx::Path path;
  gfx::Rect bounds(GetLocalBounds(false));
  SkRect rect;
  rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()),
           SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom()));
  SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius());
  path.addRoundRect(rect, radius, radius);
  canvas->drawPath(path, paint);

  // Now we paint the border, so it will be alpha-blended atop the contents.
  // This looks slightly better in the corners than drawing the contents atop
  // the border.
  PaintBorder(canvas);
}

#if defined(OS_WIN)
// BorderWidget ---------------------------------------------------------------

BorderWidget::BorderWidget() : border_contents_(NULL) {
  set_delete_on_destroy(false);  // Our owner will free us manually.
  set_window_style(WS_POPUP);
  set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED);
}

void BorderWidget::Init(HWND owner) {
  DCHECK(!border_contents_);
  border_contents_ = CreateBorderContents();
  border_contents_->Init();
  WidgetWin::Init(GetAncestor(owner, GA_ROOT), gfx::Rect());
  SetContentsView(border_contents_);
  SetWindowPos(owner, 0, 0, 0, 0,
               SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW);
}

gfx::Rect BorderWidget::SizeAndGetBounds(
    const gfx::Rect& position_relative_to,
    BubbleBorder::ArrowLocation arrow_location,
    const gfx::Size& contents_size) {
  // Ask the border view to calculate our bounds (and our contents').
  gfx::Rect contents_bounds;
  gfx::Rect window_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to, arrow_location,
                                     false, contents_size, &contents_bounds,
                                     &window_bounds);
  SetBounds(window_bounds);

  // Chop a hole out of our region to show the contents through.
  // CreateRectRgn() expects (left, top, right, bottom) in window coordinates.
  HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(),
      contents_bounds.right(), contents_bounds.bottom());
  HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(),
                                     window_bounds.height());
  CombineRgn(window_region, window_region, contents_region, RGN_XOR);
  DeleteObject(contents_region);
  SetWindowRgn(window_region, true);

  // Return |contents_bounds| in screen coordinates.
  contents_bounds.Offset(window_bounds.origin());
  return contents_bounds;
}

BorderContents* BorderWidget::CreateBorderContents() {
  return new BorderContents();
}

LRESULT BorderWidget::OnMouseActivate(HWND window,
                                      UINT hit_test,
                                      UINT mouse_message) {
  // Never activate.
  return MA_NOACTIVATE;
}
#endif

// InfoBubble -----------------------------------------------------------------

// static
InfoBubble* InfoBubble::Show(views::Widget* parent,
                             const gfx::Rect& position_relative_to,
                             BubbleBorder::ArrowLocation arrow_location,
                             views::View* contents,
                             InfoBubbleDelegate* delegate) {
  InfoBubble* window = new InfoBubble;
  window->Init(parent, position_relative_to, arrow_location,
               contents, delegate);
  return window;
}

void InfoBubble::Close() {
  Close(false);
}

InfoBubble::InfoBubble()
    :
#if defined(OS_LINUX)
      WidgetGtk(TYPE_WINDOW),
      border_contents_(NULL),
#endif
      delegate_(NULL),
      closed_(false) {
}

void InfoBubble::Init(views::Widget* parent,
                      const gfx::Rect& position_relative_to,
                      BubbleBorder::ArrowLocation arrow_location,
                      views::View* contents,
                      InfoBubbleDelegate* delegate) {
  delegate_ = delegate;
  position_relative_to_ = position_relative_to;
  arrow_location_ = arrow_location;
  contents_ = contents;

  // Create the main window.
#if defined(OS_WIN)
  views::Window* parent_window = parent->GetWindow();
  if (parent_window)
    parent_window->DisableInactiveRendering();
  set_window_style(WS_POPUP | WS_CLIPCHILDREN);
  set_window_ex_style(WS_EX_TOOLWINDOW);
  WidgetWin::Init(parent->GetNativeView(), gfx::Rect());
#elif defined(OS_LINUX)
  MakeTransparent();
  make_transient_to_parent();
  WidgetGtk::Init(
      GTK_WIDGET(static_cast<WidgetGtk*>(parent)->GetNativeView()),
      gfx::Rect());
#if defined(OS_CHROMEOS)
  chromeos::WmIpc::instance()->SetWindowType(
      GetNativeView(),
      chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
      NULL);
#endif
#endif

  // Create a View to hold the contents of the main window.
  views::View* contents_view = new views::View;
  // We add |contents_view| to ourselves before the AddChildView() call below so
  // that when |contents| gets added, it will already have a widget, and thus
  // any NativeButtons it creates in ViewHierarchyChanged() will be functional
  // (e.g. calling SetChecked() on checkboxes is safe).
  SetContentsView(contents_view);
  // Adding |contents| as a child has to be done before we call
  // contents->GetPreferredSize() below, since some supplied views don't
  // actually initialize themselves until they're added to a hierarchy.
  contents_view->AddChildView(contents);

  // Calculate and set the bounds for all windows and views.
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  DCHECK(!border_.get());
  border_.reset(CreateBorderWidget());
  border_->Init(GetNativeView());

  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to,
                                            arrow_location,
                                            contents->GetPreferredSize());

  // Make |contents| take up the entire contents view.
  contents_view->SetLayoutManager(new views::FillLayout);

  // Paint the background color behind the contents.
  contents_view->set_background(
      views::Background::CreateSolidBackground(kBackgroundColor));
#else
  // Create a view to paint the border and background.
  border_contents_ = new BorderContents;
  border_contents_->Init();
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to,
      arrow_location, false, contents->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // This new view must be added before |contents| so it will paint under it.
  contents_view->AddChildView(0, border_contents_);

  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size()));
  contents->SetBounds(contents_bounds);
#endif
  SetBounds(window_bounds);

  // Register the Escape accelerator for closing.
  GetFocusManager()->RegisterAccelerator(
      views::Accelerator(base::VKEY_ESCAPE, false, false, false), this);

  // Done creating the bubble.
  NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED,
                                         Source<InfoBubble>(this),
                                         NotificationService::NoDetails());

  // Show the window.
#if defined(OS_WIN)
  border_->ShowWindow(SW_SHOW);
  ShowWindow(SW_SHOW);
#elif defined(OS_LINUX)
  views::WidgetGtk::Show();
#endif
}

#if defined(OS_WIN)
BorderWidget* InfoBubble::CreateBorderWidget() {
  return new BorderWidget;
}
#endif

void InfoBubble::SizeToContents() {
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to_,
                                            arrow_location_,
                                            contents_->GetPreferredSize());
#else
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to_,
      arrow_location_, false, contents_->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size()));
  contents_->SetBounds(contents_bounds);
#endif
  SetBounds(window_bounds);
}

#if defined(OS_WIN)
void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) {
  // The popup should close when it is deactivated.
  if (action == WA_INACTIVE && !closed_) {
    Close();
  } else if (action == WA_ACTIVE) {
    DCHECK(GetRootView()->GetChildViewCount() > 0);
    GetRootView()->GetChildViewAt(0)->RequestFocus();
  }
}
#elif defined(OS_LINUX)
void InfoBubble::IsActiveChanged() {
  if (!IsActive())
    Close();
}
#endif

void InfoBubble::Close(bool closed_by_escape) {
  if (closed_)
    return;

  if (delegate_)
    delegate_->InfoBubbleClosing(this, closed_by_escape);
  closed_ = true;
#if defined(OS_WIN)
  border_->Close();
  WidgetWin::Close();
#elif defined(OS_LINUX)
  WidgetGtk::Close();
#endif
}

bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) {
  if (!delegate_ || delegate_->CloseOnEscape()) {
    Close(true);
    return true;
  }
  return false;
}
<|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 <unistd.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <sys/prctl.h>
#include <sys/wait.h>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/global_descriptors_posix.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/rand_util.h"
#include "base/sys_info.h"
#include "base/unix_domain_socket_posix.h"

#include "chrome/browser/zygote_host_linux.h"
#include "chrome/common/chrome_descriptors.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/sandbox_methods_linux.h"

#include "media/base/media.h"

#include "skia/ext/SkFontHost_fontconfig_control.h"

// http://code.google.com/p/chromium/wiki/LinuxZygote

static const int kMagicSandboxIPCDescriptor = 5;

// This is the object which implements the zygote. The ZygoteMain function,
// which is called from ChromeMain, at the the bottom and simple constructs one
// of these objects and runs it.
class Zygote {
 public:
  bool ProcessRequests() {
    // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
    // browser on it.
    // A SOCK_DGRAM is installed in fd 4. This is the sandbox IPC channel.
    // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC

    // We need to accept SIGCHLD, even though our handler is a no-op because
    // otherwise we cannot wait on children. (According to POSIX 2001.)
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = SIGCHLDHandler;
    CHECK(sigaction(SIGCHLD, &action, NULL) == 0);

    for (;;) {
      if (HandleRequestFromBrowser(3))
        return true;
    }
  }

 private:
  // See comment below, where sigaction is called.
  static void SIGCHLDHandler(int signal) { }

  // ---------------------------------------------------------------------------
  // Requests from the browser...

  // Read and process a request from the browser. Returns true if we are in a
  // new process and thus need to unwind back into ChromeMain.
  bool HandleRequestFromBrowser(int fd) {
    std::vector<int> fds;
    static const unsigned kMaxMessageLength = 1024;
    char buf[kMaxMessageLength];
    const ssize_t len = base::RecvMsg(fd, buf, sizeof(buf), &fds);
    if (len == -1) {
      LOG(WARNING) << "Error reading message from browser: " << errno;
      return false;
    }

    if (len == 0) {
      // EOF from the browser. We should die.
      _exit(0);
      return false;
    }

    Pickle pickle(buf, len);
    void* iter = NULL;

    int kind;
    if (pickle.ReadInt(&iter, &kind)) {
      switch (kind) {
        case ZygoteHost::kCmdFork:
          return HandleForkRequest(fd, pickle, iter, fds);
        case ZygoteHost::kCmdReap:
          if (!fds.empty())
            break;
          return HandleReapRequest(fd, pickle, iter);
        case ZygoteHost::kCmdDidProcessCrash:
          if (!fds.empty())
            break;
          return HandleDidProcessCrash(fd, pickle, iter);
        default:
          NOTREACHED();
          break;
      }
    }

    LOG(WARNING) << "Error parsing message from browser";
    for (std::vector<int>::const_iterator
         i = fds.begin(); i != fds.end(); ++i)
      close(*i);
    return false;
  }

  bool HandleReapRequest(int fd, Pickle& pickle, void* iter) {
    pid_t child;

    if (!pickle.ReadInt(&iter, &child)) {
      LOG(WARNING) << "Error parsing reap request from browser";
      return false;
    }

    ProcessWatcher::EnsureProcessTerminated(child);

    return false;
  }

  bool HandleDidProcessCrash(int fd, Pickle& pickle, void* iter) {
    base::ProcessHandle child;

    if (!pickle.ReadInt(&iter, &child)) {
      LOG(WARNING) << "Error parsing DidProcessCrash request from browser";
      return false;
    }

    bool child_exited;
    bool did_crash = base::DidProcessCrash(&child_exited, child);

    Pickle write_pickle;
    write_pickle.WriteBool(did_crash);
    write_pickle.WriteBool(child_exited);
    HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));

    return false;
  }

  // Handle a 'fork' request from the browser: this means that the browser
  // wishes to start a new renderer.
  bool HandleForkRequest(int fd, Pickle& pickle, void* iter,
                         std::vector<int>& fds) {
    std::vector<std::string> args;
    int argc, numfds;
    base::GlobalDescriptors::Mapping mapping;
    pid_t child;

    if (!pickle.ReadInt(&iter, &argc))
      goto error;

    for (int i = 0; i < argc; ++i) {
      std::string arg;
      if (!pickle.ReadString(&iter, &arg))
        goto error;
      args.push_back(arg);
    }

    if (!pickle.ReadInt(&iter, &numfds))
      goto error;
    if (numfds != static_cast<int>(fds.size()))
      goto error;

    for (int i = 0; i < numfds; ++i) {
      base::GlobalDescriptors::Key key;
      if (!pickle.ReadUInt32(&iter, &key))
        goto error;
      mapping.push_back(std::make_pair(key, fds[i]));
    }

    mapping.push_back(std::make_pair(
        static_cast<uint32_t>(kSandboxIPCChannel), 5));

    child = fork();

    if (!child) {
      close(3);  // our socket from the browser is in fd 3
      Singleton<base::GlobalDescriptors>()->Reset(mapping);
      CommandLine::Reset();
      CommandLine::Init(args);
      return true;
    }

    for (std::vector<int>::const_iterator
         i = fds.begin(); i != fds.end(); ++i)
      close(*i);

    HANDLE_EINTR(write(fd, &child, sizeof(child)));
    return false;

   error:
    LOG(WARNING) << "Error parsing fork request from browser";
    for (std::vector<int>::const_iterator
         i = fds.begin(); i != fds.end(); ++i)
      close(*i);
    return false;
  }
};

// Patched dynamic symbol wrapper functions...
namespace sandbox_wrapper {

void do_localtime(time_t input, struct tm* output, char* timezone_out,
                  size_t timezone_out_len) {
  Pickle request;
  request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
  request.WriteString(
      std::string(reinterpret_cast<char*>(&input), sizeof(input)));

  uint8_t reply_buf[512];
  const ssize_t r = base::SendRecvMsg(
      kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL, request);
  if (r == -1) {
    memset(output, 0, sizeof(struct tm));
    return;
  }

  Pickle reply(reinterpret_cast<char*>(reply_buf), r);
  void* iter = NULL;
  std::string result, timezone;
  if (!reply.ReadString(&iter, &result) ||
      !reply.ReadString(&iter, &timezone) ||
      result.size() != sizeof(struct tm)) {
    memset(output, 0, sizeof(struct tm));
    return;
  }

  memcpy(output, result.data(), sizeof(struct tm));
  if (timezone_out_len) {
    const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
    memcpy(timezone_out, timezone.data(), copy_len);
    timezone_out[copy_len] = 0;
    output->tm_zone = timezone_out;
  } else {
    output->tm_zone = NULL;
  }
}

struct tm* localtime(const time_t* timep) {
  static struct tm time_struct;
  static char timezone_string[64];
  do_localtime(*timep, &time_struct, timezone_string, sizeof(timezone_string));
  return &time_struct;
}

struct tm* localtime_r(const time_t* timep, struct tm* result) {
  do_localtime(*timep, result, NULL, 0);
  return result;
}

}  // namespace sandbox_wrapper

/* On IA-32, function calls which need to be resolved by the dynamic linker are
 * directed to the producure linking table (PLT). Each PLT entry contains code
 * which jumps (indirectly) via the global offset table (GOT):
 *   Dump of assembler code for function f@plt:
 *   0x0804830c <f@plt+0>:   jmp    *0x804a004  # GOT indirect jump
 *   0x08048312 <f@plt+6>:   push   $0x8
 *   0x08048317 <f@plt+11>:  jmp    0x80482ec <_init+48>
 *
 * At the beginning of a process's lifetime, the GOT entry jumps back to
 * <f@plt+6> end then enters the dynamic linker. Once the symbol has been
 * resolved, the GOT entry is patched so that future calls go directly to the
 * resolved function.
 *
 * This macro finds the PLT entry for a given symbol, |symbol|, and reads the
 * GOT entry address from the first instruction. It then patches that address
 * with the address of a replacement function, |replacement|.
 */
#define PATCH_GLOBAL_OFFSET_TABLE(symbol, replacement) \
       /* First, get the current instruction pointer since the PLT address */ \
       /* is IP relative */ \
  asm ("call 0f\n" \
       "0: pop %%ecx\n" \
       /* Move the IP relative address of the PLT entry into EAX */ \
       "mov $" #symbol "@plt,%%eax\n" \
       /* Add EAX to ECX to get an absolute entry */ \
       "add %%eax,%%ecx\n" \
       /* The value in ECX was relative to the add instruction, however, */ \
       /* the IP value was that of the pop. The pop and mov take 6 */ \
       /* bytes, so adding 6 gets us the correct address for the PLT. The */ \
       /* first instruction at the PLT is FF 25 <abs address>, so we skip 2 */ \
       /* bytes to get to the address. 6 + 2 = 8: */ \
       "movl 8(%%ecx),%%ecx\n" \
       /* Now ECX contains the address of the GOT entry, we poke our */ \
       /* replacement function in there: */ \
       "movl %0,(%%ecx)\n" \
       :  /* no output */ \
       :  "r" (replacement) \
       : "memory", "%eax", "%ecx");

static bool MaybeEnterChroot() {
  const char* const sandbox_fd_string = getenv("SBX_D");
  if (sandbox_fd_string) {
    // The SUID sandbox sets this environment variable to a file descriptor
    // over which we can signal that we have completed our startup and can be
    // chrooted.

    char* endptr;
    const long fd_long = strtol(sandbox_fd_string, &endptr, 10);
    if (!*sandbox_fd_string || *endptr || fd_long < 0 || fd_long > INT_MAX)
      return false;
    const int fd = fd_long;

    // Before entering the sandbox, "prime" any systems that need to open
    // files and cache the results or the descriptors.
    base::RandUint64();

    base::SysInfo::MaxSharedMemorySize();

    // To make wcstombs/mbstowcs work in a renderer, setlocale() has to be
    // called before the sandbox is triggered. It's possible to avoid calling
    // setlocale() by pulling out the conversion between FilePath and
    // WebCore String out of the renderer and using string16 in place of
    // FilePath for IPC.
    const char* locale = setlocale(LC_ALL, "");
    LOG_IF(WARNING, locale == NULL) << "setlocale failed.";

#if defined(ARCH_CPU_X86)
    PATCH_GLOBAL_OFFSET_TABLE(localtime, sandbox_wrapper::localtime);
    PATCH_GLOBAL_OFFSET_TABLE(localtime_r, sandbox_wrapper::localtime_r);
#endif

    FilePath module_path;
    if (PathService::Get(base::DIR_MODULE, &module_path))
      media::InitializeMediaLibrary(module_path);

    static const char kChrootMe = 'C';
    static const char kChrootMeSuccess = 'O';

    if (HANDLE_EINTR(write(fd, &kChrootMe, 1)) != 1) {
      LOG(ERROR) << "Failed to write to chroot pipe: " << errno;
      return false;
    }

    // We need to reap the chroot helper process in any event:
    wait(NULL);

    char reply;
    if (HANDLE_EINTR(read(fd, &reply, 1)) != 1) {
      LOG(ERROR) << "Failed to read from chroot pipe: " << errno;
      return false;
    }

    if (reply != kChrootMeSuccess) {
      LOG(ERROR) << "Error code reply from chroot helper";
      return false;
    }

    SkiaFontConfigUseIPCImplementation(kMagicSandboxIPCDescriptor);

    // Previously, we required that the binary be non-readable. This causes the
    // kernel to mark the process as non-dumpable at startup. The thinking was
    // that, although we were putting the renderers into a PID namespace (with
    // the SUID sandbox), they would nonetheless be in the /same/ PID
    // namespace. So they could ptrace each other unless they were non-dumpable.
    //
    // If the binary was readable, then there would be a window between process
    // startup and the point where we set the non-dumpable flag in which a
    // compromised renderer could ptrace attach.
    //
    // However, now that we have a zygote model, only the (trusted) zygote
    // exists at this point and we can set the non-dumpable flag which is
    // inherited by all our renderer children.
    //
    // Note: a non-dumpable process can't be debugged. To debug sandbox-related
    // issues, one can specify --allow-sandbox-debugging to let the process be
    // dumpable.
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
      prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
      if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
        LOG(ERROR) << "Failed to set non-dumpable flag";
        return false;
      }
    }
  } else {
    SkiaFontConfigUseDirectImplementation();
  }

  return true;
}

bool ZygoteMain(const MainFunctionParams& params) {
  if (!MaybeEnterChroot()) {
    LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
               << errno << ")";
    return false;
  }

  Zygote zygote;
  return zygote.ProcessRequests();
}
<commit_msg>Linux: don't use GOT patching to intercept localtime(_r)<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 <dlfcn.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <sys/prctl.h>
#include <sys/wait.h>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/global_descriptors_posix.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/rand_util.h"
#include "base/sys_info.h"
#include "base/unix_domain_socket_posix.h"

#include "chrome/browser/zygote_host_linux.h"
#include "chrome/common/chrome_descriptors.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/sandbox_methods_linux.h"

#include "media/base/media.h"

#include "skia/ext/SkFontHost_fontconfig_control.h"

// http://code.google.com/p/chromium/wiki/LinuxZygote

static const int kMagicSandboxIPCDescriptor = 5;

// This is the object which implements the zygote. The ZygoteMain function,
// which is called from ChromeMain, at the the bottom and simple constructs one
// of these objects and runs it.
class Zygote {
 public:
  bool ProcessRequests() {
    // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
    // browser on it.
    // A SOCK_DGRAM is installed in fd 4. This is the sandbox IPC channel.
    // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC

    // We need to accept SIGCHLD, even though our handler is a no-op because
    // otherwise we cannot wait on children. (According to POSIX 2001.)
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = SIGCHLDHandler;
    CHECK(sigaction(SIGCHLD, &action, NULL) == 0);

    for (;;) {
      if (HandleRequestFromBrowser(3))
        return true;
    }
  }

 private:
  // See comment below, where sigaction is called.
  static void SIGCHLDHandler(int signal) { }

  // ---------------------------------------------------------------------------
  // Requests from the browser...

  // Read and process a request from the browser. Returns true if we are in a
  // new process and thus need to unwind back into ChromeMain.
  bool HandleRequestFromBrowser(int fd) {
    std::vector<int> fds;
    static const unsigned kMaxMessageLength = 1024;
    char buf[kMaxMessageLength];
    const ssize_t len = base::RecvMsg(fd, buf, sizeof(buf), &fds);
    if (len == -1) {
      LOG(WARNING) << "Error reading message from browser: " << errno;
      return false;
    }

    if (len == 0) {
      // EOF from the browser. We should die.
      _exit(0);
      return false;
    }

    Pickle pickle(buf, len);
    void* iter = NULL;

    int kind;
    if (pickle.ReadInt(&iter, &kind)) {
      switch (kind) {
        case ZygoteHost::kCmdFork:
          return HandleForkRequest(fd, pickle, iter, fds);
        case ZygoteHost::kCmdReap:
          if (!fds.empty())
            break;
          return HandleReapRequest(fd, pickle, iter);
        case ZygoteHost::kCmdDidProcessCrash:
          if (!fds.empty())
            break;
          return HandleDidProcessCrash(fd, pickle, iter);
        default:
          NOTREACHED();
          break;
      }
    }

    LOG(WARNING) << "Error parsing message from browser";
    for (std::vector<int>::const_iterator
         i = fds.begin(); i != fds.end(); ++i)
      close(*i);
    return false;
  }

  bool HandleReapRequest(int fd, Pickle& pickle, void* iter) {
    pid_t child;

    if (!pickle.ReadInt(&iter, &child)) {
      LOG(WARNING) << "Error parsing reap request from browser";
      return false;
    }

    ProcessWatcher::EnsureProcessTerminated(child);

    return false;
  }

  bool HandleDidProcessCrash(int fd, Pickle& pickle, void* iter) {
    base::ProcessHandle child;

    if (!pickle.ReadInt(&iter, &child)) {
      LOG(WARNING) << "Error parsing DidProcessCrash request from browser";
      return false;
    }

    bool child_exited;
    bool did_crash = base::DidProcessCrash(&child_exited, child);

    Pickle write_pickle;
    write_pickle.WriteBool(did_crash);
    write_pickle.WriteBool(child_exited);
    HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));

    return false;
  }

  // Handle a 'fork' request from the browser: this means that the browser
  // wishes to start a new renderer.
  bool HandleForkRequest(int fd, Pickle& pickle, void* iter,
                         std::vector<int>& fds) {
    std::vector<std::string> args;
    int argc, numfds;
    base::GlobalDescriptors::Mapping mapping;
    pid_t child;

    if (!pickle.ReadInt(&iter, &argc))
      goto error;

    for (int i = 0; i < argc; ++i) {
      std::string arg;
      if (!pickle.ReadString(&iter, &arg))
        goto error;
      args.push_back(arg);
    }

    if (!pickle.ReadInt(&iter, &numfds))
      goto error;
    if (numfds != static_cast<int>(fds.size()))
      goto error;

    for (int i = 0; i < numfds; ++i) {
      base::GlobalDescriptors::Key key;
      if (!pickle.ReadUInt32(&iter, &key))
        goto error;
      mapping.push_back(std::make_pair(key, fds[i]));
    }

    mapping.push_back(std::make_pair(
        static_cast<uint32_t>(kSandboxIPCChannel), 5));

    child = fork();

    if (!child) {
      close(3);  // our socket from the browser is in fd 3
      Singleton<base::GlobalDescriptors>()->Reset(mapping);
      CommandLine::Reset();
      CommandLine::Init(args);
      return true;
    }

    for (std::vector<int>::const_iterator
         i = fds.begin(); i != fds.end(); ++i)
      close(*i);

    HANDLE_EINTR(write(fd, &child, sizeof(child)));
    return false;

   error:
    LOG(WARNING) << "Error parsing fork request from browser";
    for (std::vector<int>::const_iterator
         i = fds.begin(); i != fds.end(); ++i)
      close(*i);
    return false;
  }
};

static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
                                        char* timezone_out,
                                        size_t timezone_out_len) {
  Pickle request;
  request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
  request.WriteString(
      std::string(reinterpret_cast<char*>(&input), sizeof(input)));

  uint8_t reply_buf[512];
  const ssize_t r = base::SendRecvMsg(
      kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL, request);
  if (r == -1) {
    memset(output, 0, sizeof(struct tm));
    return;
  }

  Pickle reply(reinterpret_cast<char*>(reply_buf), r);
  void* iter = NULL;
  std::string result, timezone;
  if (!reply.ReadString(&iter, &result) ||
      !reply.ReadString(&iter, &timezone) ||
      result.size() != sizeof(struct tm)) {
    memset(output, 0, sizeof(struct tm));
    return;
  }

  memcpy(output, result.data(), sizeof(struct tm));
  if (timezone_out_len) {
    const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
    memcpy(timezone_out, timezone.data(), copy_len);
    timezone_out[copy_len] = 0;
    output->tm_zone = timezone_out;
  } else {
    output->tm_zone = NULL;
  }
}

static bool g_am_zygote_or_renderer = false;

// Sandbox interception of libc calls.
//
// Because we are running in a sandbox certain libc calls will fail (localtime
// being the motivating example - it needs to read /etc/localtime). We need to
// intercept these calls and proxy them to the browser. However, these calls
// may come from us or from our libraries. In some cases we can't just change
// our code.
//
// It's for these cases that we have the following setup:
//
// We define global functions for those functions which we wish to override.
// Since we will be first in the dynamic resolution order, the dynamic linker
// will point callers to our versions of these functions. However, we have the
// same binary for both the browser and the renderers, which means that our
// overrides will apply in the browser too.
//
// The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
// renderer process. It's set in ZygoteMain and inherited by the renderers when
// they fork. (This means that it'll be incorrect for global constructor
// functions and before ZygoteMain is called - beware).
//
// Our replacement functions can check this global and either proxy
// the call to the browser over the sandbox IPC
// (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
// dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
// current module.
//
// Other avenues:
//
// Our first attempt involved some assembly to patch the GOT of the current
// module. This worked, but was platform specific and doesn't catch the case
// where a library makes a call rather than current module.
//
// We also considered patching the function in place, but this would again by
// platform specific and the above technique seems to work well enough.

struct tm* localtime(const time_t* timep) {
  if (g_am_zygote_or_renderer) {
    static struct tm time_struct;
    static char timezone_string[64];
    ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
                                sizeof(timezone_string));
    return &time_struct;
  } else {
    typedef struct tm* (*LocaltimeFunction)(const time_t* timep);
    static LocaltimeFunction libc_localtime;
    if (!libc_localtime)
      libc_localtime = (LocaltimeFunction) dlsym(RTLD_NEXT, "localtime");

    return libc_localtime(timep);
  }
}

struct tm* localtime_r(const time_t* timep, struct tm* result) {
  if (g_am_zygote_or_renderer) {
    ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
    return result;
  } else {
    typedef struct tm* (*LocaltimeRFunction)(const time_t* timep,
                                             struct tm* result);
    static LocaltimeRFunction libc_localtime_r;
    if (!libc_localtime_r)
      libc_localtime_r = (LocaltimeRFunction) dlsym(RTLD_NEXT, "localtime_r");

    return libc_localtime_r(timep, result);
  }
}

static bool MaybeEnterChroot() {
  const char* const sandbox_fd_string = getenv("SBX_D");
  if (sandbox_fd_string) {
    // The SUID sandbox sets this environment variable to a file descriptor
    // over which we can signal that we have completed our startup and can be
    // chrooted.

    char* endptr;
    const long fd_long = strtol(sandbox_fd_string, &endptr, 10);
    if (!*sandbox_fd_string || *endptr || fd_long < 0 || fd_long > INT_MAX)
      return false;
    const int fd = fd_long;

    // Before entering the sandbox, "prime" any systems that need to open
    // files and cache the results or the descriptors.
    base::RandUint64();

    base::SysInfo::MaxSharedMemorySize();

    // To make wcstombs/mbstowcs work in a renderer, setlocale() has to be
    // called before the sandbox is triggered. It's possible to avoid calling
    // setlocale() by pulling out the conversion between FilePath and
    // WebCore String out of the renderer and using string16 in place of
    // FilePath for IPC.
    const char* locale = setlocale(LC_ALL, "");
    LOG_IF(WARNING, locale == NULL) << "setlocale failed.";

    FilePath module_path;
    if (PathService::Get(base::DIR_MODULE, &module_path))
      media::InitializeMediaLibrary(module_path);

    static const char kChrootMe = 'C';
    static const char kChrootMeSuccess = 'O';

    if (HANDLE_EINTR(write(fd, &kChrootMe, 1)) != 1) {
      LOG(ERROR) << "Failed to write to chroot pipe: " << errno;
      return false;
    }

    // We need to reap the chroot helper process in any event:
    wait(NULL);

    char reply;
    if (HANDLE_EINTR(read(fd, &reply, 1)) != 1) {
      LOG(ERROR) << "Failed to read from chroot pipe: " << errno;
      return false;
    }

    if (reply != kChrootMeSuccess) {
      LOG(ERROR) << "Error code reply from chroot helper";
      return false;
    }

    SkiaFontConfigUseIPCImplementation(kMagicSandboxIPCDescriptor);

    // Previously, we required that the binary be non-readable. This causes the
    // kernel to mark the process as non-dumpable at startup. The thinking was
    // that, although we were putting the renderers into a PID namespace (with
    // the SUID sandbox), they would nonetheless be in the /same/ PID
    // namespace. So they could ptrace each other unless they were non-dumpable.
    //
    // If the binary was readable, then there would be a window between process
    // startup and the point where we set the non-dumpable flag in which a
    // compromised renderer could ptrace attach.
    //
    // However, now that we have a zygote model, only the (trusted) zygote
    // exists at this point and we can set the non-dumpable flag which is
    // inherited by all our renderer children.
    //
    // Note: a non-dumpable process can't be debugged. To debug sandbox-related
    // issues, one can specify --allow-sandbox-debugging to let the process be
    // dumpable.
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
      prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
      if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
        LOG(ERROR) << "Failed to set non-dumpable flag";
        return false;
      }
    }
  } else {
    SkiaFontConfigUseDirectImplementation();
  }

  return true;
}

bool ZygoteMain(const MainFunctionParams& params) {
  g_am_zygote_or_renderer = true;

  if (!MaybeEnterChroot()) {
    LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
               << errno << ")";
    return false;
  }

  Zygote zygote;
  return zygote.ProcessRequests();
}
<|endoftext|>


<commit_before>#pragma once

#include <cstdint>
#include <functional>
#include <string>
#include <vector>

#include <lug/Graphics/Export.hpp>
#include <lug/Graphics/Render/Technique/Type.hpp>
#include <lug/Graphics/Resource.hpp>
#include <lug/Graphics/Vulkan/API/Pipeline.hpp>

namespace lug {
namespace Graphics {
namespace Vulkan {

class Renderer;

namespace Render {

/**
* @brief      Class for the Vulkan pipeline, Render side.
*/
class LUG_GRAPHICS_API Pipeline : public Resource {
public:
    /**
     * @brief      Id of the Pipeline.
     *             It's a concatenation of three parts: PrimitivePart, MaterialPart and PipelinePart
     *             It allows to uniquely identify a pipeline using these characteristics.
     */
    struct Id {
        /**
         * @brief      Describes the primitive.
         */
        struct PrimitivePart {
            union {
                struct {
                    uint32_t positionVertexData : 1;    ///< 0 if no attribute position.
                    uint32_t normalVertexData : 1;      ///< 0 if no attribute normal.
                    uint32_t tangentVertexData : 1;     ///< 0 if no attribute tangeant.
                    uint32_t countTexCoord : 2;         ///< The number of texcoord (maximum 3).
                    uint32_t primitiveMode : 3;         ///< The primitive mode. @see Mesh::PrimitiveSet::Mode.
                };

                uint32_t value;
            };

            explicit operator uint32_t() {
                return value;
            }
        };

        /**
         * @brief      Describes the material. How is the material composed,
         *             with textures, no textures, etc, to be used to construct unique
         *             pipelines.
         */
        struct MaterialPart {
            union {
                struct {
                    uint32_t baseColorInfo : 2;             ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t metallicRoughnessInfo : 2;     ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t normalInfo : 2;                ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t occlusionInfo : 2;             ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t emissiveInfo : 2;              ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                };

                uint32_t value;
            };

            explicit operator uint32_t() {
                return value;
            }
        };

        union {
            struct {
                uint32_t primitivePart : 8;
                uint32_t materialPart : 10;
            };

            uint32_t value;
        };

        explicit operator uint32_t() {
            return value;
        }

        bool operator==(const Id& other) const {
            return value == other.value;
        }

        PrimitivePart getPrimitivePart() {
            PrimitivePart tmp;
            tmp.value = primitivePart;
            return tmp;
        }

        MaterialPart getMaterialPart() {
            MaterialPart tmp;
            tmp.value = materialPart;
            return tmp;
        }

        /**
         * @brief      Create a pipeline id.
         *
         * @param[in]  primitivePart  The primitive part. It should be created manually beforehand.
         * @param[in]  materialPart   The material part. It should be created manually beforehand.
         *
         * @return     The created id.
         */
        static Id create(PrimitivePart primitivePart, MaterialPart materialPart) {
            Id id;

            id.primitivePart = static_cast<uint32_t>(primitivePart);
            id.materialPart = static_cast<uint32_t>(materialPart);

            return id;
        };
    };

public:
    class ShaderBuilder {
    public:
        enum class Type : uint8_t {
            Vertex,
            Fragment
        };

    public:
        ShaderBuilder() = delete;

        ShaderBuilder(const ShaderBuilder&) = delete;
        ShaderBuilder(ShaderBuilder&&) = delete;

        ShaderBuilder& operator=(const ShaderBuilder&) = delete;
        ShaderBuilder& operator=(ShaderBuilder&&) = delete;

        ~ShaderBuilder() = delete;

    public:
        static std::vector<uint32_t> buildShader(std::string shaderRoot, ::lug::Graphics::Render::Technique::Type technique, Type type, Pipeline::Id id);
        static std::vector<uint32_t> buildShaderFromFile(std::string filename, Type type, Pipeline::Id id);
        static std::vector<uint32_t> buildShaderFromString(std::string filename, std::string content, Type type, Pipeline::Id id);
    };

public:
    Pipeline(Renderer& renderer, Id id);

    Pipeline(const Pipeline&) = delete;
    Pipeline(Pipeline&&) = delete;

    Pipeline& operator=(const Pipeline&) = delete;
    Pipeline& operator=(Pipeline&&) = delete;

    ~Pipeline() = default;

    /**
     * @brief      Returns the id of the Pipeline.
     *
     * @return     The id.
     */
    Id getId() const;

private:
    bool init();

private:
    static Resource::SharedPtr<Pipeline> create(Renderer& renderer, Id id);

private:
    Renderer& _renderer;
    Id _id;

    API::Pipeline _pipeline;
};

#include <lug/Graphics/Vulkan/Render/Pipeline.inl>

} // Render
} // Vulkan
} // Graphics
} // lug

// Make Pipeline Id hashable like a uint32_t
namespace std {
    template<> struct hash<lug::Graphics::Vulkan::Render::Pipeline::Id> {
        size_t operator()(const lug::Graphics::Vulkan::Render::Pipeline::Id& id) const {
            return hash<uint32_t>()(id.value);
        }
    };
}
<commit_msg>Export Pipeline::ShaderBuilder<commit_after>#pragma once

#include <cstdint>
#include <functional>
#include <string>
#include <vector>

#include <lug/Graphics/Export.hpp>
#include <lug/Graphics/Render/Technique/Type.hpp>
#include <lug/Graphics/Resource.hpp>
#include <lug/Graphics/Vulkan/API/Pipeline.hpp>

namespace lug {
namespace Graphics {
namespace Vulkan {

class Renderer;

namespace Render {

/**
* @brief      Class for the Vulkan pipeline, Render side.
*/
class LUG_GRAPHICS_API Pipeline : public Resource {
public:
    /**
     * @brief      Id of the Pipeline.
     *             It's a concatenation of three parts: PrimitivePart, MaterialPart and PipelinePart
     *             It allows to uniquely identify a pipeline using these characteristics.
     */
    struct Id {
        /**
         * @brief      Describes the primitive.
         */
        struct PrimitivePart {
            union {
                struct {
                    uint32_t positionVertexData : 1;    ///< 0 if no attribute position.
                    uint32_t normalVertexData : 1;      ///< 0 if no attribute normal.
                    uint32_t tangentVertexData : 1;     ///< 0 if no attribute tangeant.
                    uint32_t countTexCoord : 2;         ///< The number of texcoord (maximum 3).
                    uint32_t primitiveMode : 3;         ///< The primitive mode. @see Mesh::PrimitiveSet::Mode.
                };

                uint32_t value;
            };

            explicit operator uint32_t() {
                return value;
            }
        };

        /**
         * @brief      Describes the material. How is the material composed,
         *             with textures, no textures, etc, to be used to construct unique
         *             pipelines.
         */
        struct MaterialPart {
            union {
                struct {
                    uint32_t baseColorInfo : 2;             ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t metallicRoughnessInfo : 2;     ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t normalInfo : 2;                ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t occlusionInfo : 2;             ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                    uint32_t emissiveInfo : 2;              ///< 0b00 texture with UV0, 0b01 texture with UV1, 0b10 texture with UV2, 0b11 no texture.
                };

                uint32_t value;
            };

            explicit operator uint32_t() {
                return value;
            }
        };

        union {
            struct {
                uint32_t primitivePart : 8;
                uint32_t materialPart : 10;
            };

            uint32_t value;
        };

        explicit operator uint32_t() {
            return value;
        }

        bool operator==(const Id& other) const {
            return value == other.value;
        }

        PrimitivePart getPrimitivePart() {
            PrimitivePart tmp;
            tmp.value = primitivePart;
            return tmp;
        }

        MaterialPart getMaterialPart() {
            MaterialPart tmp;
            tmp.value = materialPart;
            return tmp;
        }

        /**
         * @brief      Create a pipeline id.
         *
         * @param[in]  primitivePart  The primitive part. It should be created manually beforehand.
         * @param[in]  materialPart   The material part. It should be created manually beforehand.
         *
         * @return     The created id.
         */
        static Id create(PrimitivePart primitivePart, MaterialPart materialPart) {
            Id id;

            id.primitivePart = static_cast<uint32_t>(primitivePart);
            id.materialPart = static_cast<uint32_t>(materialPart);

            return id;
        };
    };

public:
    class LUG_GRAPHICS_API ShaderBuilder {
    public:
        enum class Type : uint8_t {
            Vertex,
            Fragment
        };

    public:
        ShaderBuilder() = delete;

        ShaderBuilder(const ShaderBuilder&) = delete;
        ShaderBuilder(ShaderBuilder&&) = delete;

        ShaderBuilder& operator=(const ShaderBuilder&) = delete;
        ShaderBuilder& operator=(ShaderBuilder&&) = delete;

        ~ShaderBuilder() = delete;

    public:
        static std::vector<uint32_t> buildShader(std::string shaderRoot, ::lug::Graphics::Render::Technique::Type technique, Type type, Pipeline::Id id);
        static std::vector<uint32_t> buildShaderFromFile(std::string filename, Type type, Pipeline::Id id);
        static std::vector<uint32_t> buildShaderFromString(std::string filename, std::string content, Type type, Pipeline::Id id);
    };

public:
    Pipeline(Renderer& renderer, Id id);

    Pipeline(const Pipeline&) = delete;
    Pipeline(Pipeline&&) = delete;

    Pipeline& operator=(const Pipeline&) = delete;
    Pipeline& operator=(Pipeline&&) = delete;

    ~Pipeline() = default;

    /**
     * @brief      Returns the id of the Pipeline.
     *
     * @return     The id.
     */
    Id getId() const;

private:
    bool init();

private:
    static Resource::SharedPtr<Pipeline> create(Renderer& renderer, Id id);

private:
    Renderer& _renderer;
    Id _id;

    API::Pipeline _pipeline;
};

#include <lug/Graphics/Vulkan/Render/Pipeline.inl>

} // Render
} // Vulkan
} // Graphics
} // lug

// Make Pipeline Id hashable like a uint32_t
namespace std {
    template<> struct hash<lug::Graphics::Vulkan::Render::Pipeline::Id> {
        size_t operator()(const lug::Graphics::Vulkan::Render::Pipeline::Id& id) const {
            return hash<uint32_t>()(id.value);
        }
    };
}
<|endoftext|>


<commit_before>//============================================================================
// vSMC/cmake/FindOpenCL.cpp
//----------------------------------------------------------------------------
//                         vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013,2014, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================

#ifndef __has_attribute
#define __has_attribute(x) 0
#endif

#ifndef __has_builtin
#define __has_builtin(x) 0
#endif

#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif

#ifndef __has_extension
#define __has_extension(x) 0
#endif

#ifndef __has_feature
#define __has_feature(x) 0
#endif

#include <cl.hpp>
#include <vector>
#include <cassert>

int main ()
{
    std::vector<cl::Platform> plat;
    cl::Platform::get(&plat);
    std::vector<cl::Device> dev;
    plat[0].getDevices(CL_DEVICE_TYPE_ALL, &dev);
    assert(dev.size() != 0);

    return 0;
}
<commit_msg>new OpenCL test files<commit_after>//============================================================================
// vSMC/cmake/FindOpenCL.cpp
//----------------------------------------------------------------------------
//                         vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013,2014, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================

#ifndef __has_attribute
#define __has_attribute(x) 0
#endif

#ifndef __has_builtin
#define __has_builtin(x) 0
#endif

#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif

#ifndef __has_extension
#define __has_extension(x) 0
#endif

#ifndef __has_feature
#define __has_feature(x) 0
#endif

#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif

#include <cassert>

int main ()
{
    ::cl_platform_id platform;
    ::cl_device_id device;
    ::cl_uint num;
    ::cl_int status;
    status = clGetPlatformIDs(1, &platform, &num);
    assert(status == CL_SUCCESS && num != 0);
    status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, &num);
    assert(status == CL_SUCCESS && num != 0);

    return 0;
}
<|endoftext|>