<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/panels/panel_manager.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/panels/detached_panel_strip.h"
#include "chrome/browser/ui/panels/docked_panel_strip.h"
#include "chrome/browser/ui/panels/panel_drag_controller.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher.h"
#include "chrome/browser/ui/panels/panel_resize_controller.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"

#if defined(TOOLKIT_GTK)
#include "ui/base/x/x11_util.h"
#endif

namespace {
// Width of spacing around panel strip and the left/right edges of the screen.
const int kPanelStripLeftMargin = 6;
const int kPanelStripRightMargin = 24;

// Maxmium width of a panel is based on a factor of the working area.
#if defined(OS_CHROMEOS)
// ChromeOS device screens are relatively small and limiting the width
// interferes with some apps (e.g. http://crbug.com/111121).
const double kPanelMaxWidthFactor = 0.80;
#else
const double kPanelMaxWidthFactor = 0.35;
#endif

// Maxmium height of a panel is based on a factor of the working area.
const double kPanelMaxHeightFactor = 0.5;
}  // namespace

// static
bool PanelManager::shorten_time_intervals_ = false;

// static
PanelManager* PanelManager::GetInstance() {
  static base::LazyInstance<PanelManager> instance = LAZY_INSTANCE_INITIALIZER;
  return instance.Pointer();
}

// static
bool PanelManager::ShouldUsePanels(const std::string& extension_id) {
#if defined(TOOLKIT_GTK)
  // Panels are only supported on a white list of window managers for Linux.
  ui::WindowManagerName wm_type = ui::GuessWindowManager();
  if (wm_type != ui::WM_COMPIZ &&
      wm_type != ui::WM_ICE_WM &&
      wm_type != ui::WM_KWIN &&
      wm_type != ui::WM_METACITY &&
      wm_type != ui::WM_MUTTER) {
    return false;
  }
#endif  // TOOLKIT_GTK

  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
      channel == chrome::VersionInfo::CHANNEL_BETA) {
    return CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kEnablePanels) ||
        extension_id == std::string("nckgahadagoaajjgafhacjanaoiihapd") ||
        extension_id == std::string("ljclpkphhpbpinifbeabbhlfddcpfdde") ||
        extension_id == std::string("ppleadejekpmccmnpjdimmlfljlkdfej") ||
        extension_id == std::string("eggnbpckecmjlblplehfpjjdhhidfdoj");
  }

  return true;
}

PanelManager::PanelManager()
    : panel_mouse_watcher_(PanelMouseWatcher::Create()),
      auto_sizing_enabled_(true) {
  // DisplaySettingsProvider should be created before the creation of strips
  // since some strip might depend on it.
  display_settings_provider_.reset(DisplaySettingsProvider::Create());
  display_settings_provider_->AddDisplayAreaObserver(this);

  detached_strip_.reset(new DetachedPanelStrip(this));
  docked_strip_.reset(new DockedPanelStrip(this));
  drag_controller_.reset(new PanelDragController(this));
  resize_controller_.reset(new PanelResizeController(this));
}

PanelManager::~PanelManager() {
  display_settings_provider_->RemoveDisplayAreaObserver(this);

  // Docked strip should be disposed explicitly before DisplaySettingsProvider
  // is gone since docked strip needs to remove the observer from
  // DisplaySettingsProvider.
  docked_strip_.reset();
}

void PanelManager::OnDisplayAreaChanged(const gfx::Rect& display_area) {
  if (display_area == display_area_)
    return;
  display_area_ = display_area;

  gfx::Rect docked_strip_bounds = display_area;
  docked_strip_bounds.set_x(display_area.x() + kPanelStripLeftMargin);
  docked_strip_bounds.set_width(display_area.width() -
                                kPanelStripLeftMargin - kPanelStripRightMargin);
  docked_strip_->SetDisplayArea(docked_strip_bounds);

  detached_strip_->SetDisplayArea(display_area);
}

void PanelManager::OnFullScreenModeChanged(bool is_full_screen) {
  docked_strip_->OnFullScreenModeChanged(is_full_screen);
}

int PanelManager::GetMaxPanelWidth() const {
  return static_cast<int>(display_area_.width() * kPanelMaxWidthFactor);
}

int PanelManager::GetMaxPanelHeight() const {
  return display_area_.height() * kPanelMaxHeightFactor;
}

Panel* PanelManager::CreatePanel(Browser* browser) {
  // Need to sync the display area if no panel is present. This is because:
  // 1) Display area is not initialized until first panel is created.
  // 2) On windows, display settings notification is tied to a window. When
  //    display settings are changed at the time that no panel exists, we do
  //    not receive any notification.
  if (num_panels() == 0)
    display_settings_provider_->OnDisplaySettingsChanged();

  int width = browser->override_bounds().width();
  int height = browser->override_bounds().height();
  Panel* panel = new Panel(browser, gfx::Size(width, height));
  docked_strip_->AddPanel(panel, PanelStrip::DEFAULT_POSITION);
  docked_strip_->UpdatePanelOnStripChange(panel);

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PANEL_ADDED,
      content::Source<Panel>(panel),
      content::NotificationService::NoDetails());

  if (num_panels() == 1) {
    display_settings_provider_->AddFullScreenObserver(this);
  }

  return panel;
}

void PanelManager::OnPanelClosed(Panel* panel) {
  if (num_panels() == 1) {
    display_settings_provider_->RemoveFullScreenObserver(this);
  }

  drag_controller_->OnPanelClosed(panel);
  resize_controller_->OnPanelClosed(panel);
  panel->panel_strip()->RemovePanel(panel);

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PANEL_CLOSED,
      content::Source<Panel>(panel),
      content::NotificationService::NoDetails());
}

void PanelManager::StartDragging(Panel* panel,
                                 const gfx::Point& mouse_location) {
  drag_controller_->StartDragging(panel, mouse_location);
}

void PanelManager::Drag(const gfx::Point& mouse_location) {
  drag_controller_->Drag(mouse_location);
}

void PanelManager::EndDragging(bool cancelled) {
  drag_controller_->EndDragging(cancelled);
}

void PanelManager::StartResizingByMouse(Panel* panel,
    const gfx::Point& mouse_location,
    panel::ResizingSides sides) {
  if (panel->CanResizeByMouse() != panel::NOT_RESIZABLE &&
      sides != panel::RESIZE_NONE)
    resize_controller_->StartResizing(panel, mouse_location, sides);
}

void PanelManager::ResizeByMouse(const gfx::Point& mouse_location) {
  if (resize_controller_->IsResizing())
    resize_controller_->Resize(mouse_location);
}

void PanelManager::EndResizingByMouse(bool cancelled) {
  if (resize_controller_->IsResizing()) {
    Panel* resized_panel = resize_controller_->EndResizing(cancelled);
    if (!cancelled && resized_panel->panel_strip())
      resized_panel->panel_strip()->RefreshLayout();
  }
}

void PanelManager::OnPanelExpansionStateChanged(Panel* panel) {
  // For panels outside of the docked strip changing state is a no-op.
  // But since this method may be called for panels in other strips
  // we need to check this condition.
  if (panel->panel_strip() == docked_strip_.get())
    docked_strip_->OnPanelExpansionStateChanged(panel);

}

void PanelManager::OnWindowAutoResized(Panel* panel,
                                       const gfx::Size& preferred_window_size) {
  DCHECK(auto_sizing_enabled_);
  panel->panel_strip()->ResizePanelWindow(panel, preferred_window_size);
}

void PanelManager::ResizePanel(Panel* panel, const gfx::Size& new_size) {
  PanelStrip* panel_strip = panel->panel_strip();
  if (!panel_strip)
    return;
  panel_strip->ResizePanelWindow(panel, new_size);
  panel->SetAutoResizable(false);
}

void PanelManager::OnPanelResizedByMouse(Panel* panel,
                                         const gfx::Rect& new_bounds) {
  panel->panel_strip()->OnPanelResizedByMouse(panel, new_bounds);
}

void PanelManager::MovePanelToStrip(
    Panel* panel,
    PanelStrip::Type new_layout,
    PanelStrip::PositioningMask positioning_mask) {
  DCHECK(panel);
  PanelStrip* current_strip = panel->panel_strip();
  DCHECK(current_strip);
  DCHECK_NE(current_strip->type(), new_layout);
  current_strip->RemovePanel(panel);

  PanelStrip* target_strip = NULL;
  switch (new_layout) {
    case PanelStrip::DETACHED:
      target_strip = detached_strip_.get();
      break;
    case PanelStrip::DOCKED:
      target_strip = docked_strip_.get();
      break;
    default:
      NOTREACHED();
  }

  target_strip->AddPanel(panel, positioning_mask);
  target_strip->UpdatePanelOnStripChange(panel);
}

bool PanelManager::ShouldBringUpTitlebars(int mouse_x, int mouse_y) const {
  return docked_strip_->ShouldBringUpTitlebars(mouse_x, mouse_y);
}

void PanelManager::BringUpOrDownTitlebars(bool bring_up) {
  docked_strip_->BringUpOrDownTitlebars(bring_up);
}

BrowserWindow* PanelManager::GetNextBrowserWindowToActivate(
    Panel* panel) const {
  // Find the last active browser window that is not minimized.
  BrowserList::const_reverse_iterator iter = BrowserList::begin_last_active();
  BrowserList::const_reverse_iterator end = BrowserList::end_last_active();
  for (; (iter != end); ++iter) {
    Browser* browser = *iter;
    if (panel->browser() != browser && !browser->window()->IsMinimized())
      return browser->window();
  }

  return NULL;
}

void PanelManager::CloseAll() {
  DCHECK(!drag_controller_->IsDragging());

  detached_strip_->CloseAll();
  docked_strip_->CloseAll();
}

int PanelManager::num_panels() const {
  return detached_strip_->num_panels() + docked_strip_->num_panels();
}

std::vector<Panel*> PanelManager::panels() const {
  std::vector<Panel*> panels;
  for (DetachedPanelStrip::Panels::const_iterator iter =
           detached_strip_->panels().begin();
       iter != detached_strip_->panels().end(); ++iter)
    panels.push_back(*iter);
  for (DockedPanelStrip::Panels::const_iterator iter =
           docked_strip_->panels().begin();
       iter != docked_strip_->panels().end(); ++iter)
    panels.push_back(*iter);
  return panels;
}

void PanelManager::SetMouseWatcher(PanelMouseWatcher* watcher) {
  panel_mouse_watcher_.reset(watcher);
}

void PanelManager::OnPanelAnimationEnded(Panel* panel) {
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PANEL_BOUNDS_ANIMATIONS_FINISHED,
      content::Source<Panel>(panel),
      content::NotificationService::NoDetails());
}

<commit_msg>Use panels instead of popups on XFCE.<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/panels/panel_manager.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/panels/detached_panel_strip.h"
#include "chrome/browser/ui/panels/docked_panel_strip.h"
#include "chrome/browser/ui/panels/panel_drag_controller.h"
#include "chrome/browser/ui/panels/panel_mouse_watcher.h"
#include "chrome/browser/ui/panels/panel_resize_controller.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"

#if defined(TOOLKIT_GTK)
#include "ui/base/x/x11_util.h"
#endif

namespace {
// Width of spacing around panel strip and the left/right edges of the screen.
const int kPanelStripLeftMargin = 6;
const int kPanelStripRightMargin = 24;

// Maxmium width of a panel is based on a factor of the working area.
#if defined(OS_CHROMEOS)
// ChromeOS device screens are relatively small and limiting the width
// interferes with some apps (e.g. http://crbug.com/111121).
const double kPanelMaxWidthFactor = 0.80;
#else
const double kPanelMaxWidthFactor = 0.35;
#endif

// Maxmium height of a panel is based on a factor of the working area.
const double kPanelMaxHeightFactor = 0.5;
}  // namespace

// static
bool PanelManager::shorten_time_intervals_ = false;

// static
PanelManager* PanelManager::GetInstance() {
  static base::LazyInstance<PanelManager> instance = LAZY_INSTANCE_INITIALIZER;
  return instance.Pointer();
}

// static
bool PanelManager::ShouldUsePanels(const std::string& extension_id) {
#if defined(TOOLKIT_GTK)
  // Panels are only supported on a white list of window managers for Linux.
  ui::WindowManagerName wm_type = ui::GuessWindowManager();
  if (wm_type != ui::WM_COMPIZ &&
      wm_type != ui::WM_ICE_WM &&
      wm_type != ui::WM_KWIN &&
      wm_type != ui::WM_METACITY &&
      wm_type != ui::WM_MUTTER &&
      wm_type != ui::WM_XFWM4) {
    return false;
  }
#endif  // TOOLKIT_GTK

  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
      channel == chrome::VersionInfo::CHANNEL_BETA) {
    return CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kEnablePanels) ||
        extension_id == std::string("nckgahadagoaajjgafhacjanaoiihapd") ||
        extension_id == std::string("ljclpkphhpbpinifbeabbhlfddcpfdde") ||
        extension_id == std::string("ppleadejekpmccmnpjdimmlfljlkdfej") ||
        extension_id == std::string("eggnbpckecmjlblplehfpjjdhhidfdoj");
  }

  return true;
}

PanelManager::PanelManager()
    : panel_mouse_watcher_(PanelMouseWatcher::Create()),
      auto_sizing_enabled_(true) {
  // DisplaySettingsProvider should be created before the creation of strips
  // since some strip might depend on it.
  display_settings_provider_.reset(DisplaySettingsProvider::Create());
  display_settings_provider_->AddDisplayAreaObserver(this);

  detached_strip_.reset(new DetachedPanelStrip(this));
  docked_strip_.reset(new DockedPanelStrip(this));
  drag_controller_.reset(new PanelDragController(this));
  resize_controller_.reset(new PanelResizeController(this));
}

PanelManager::~PanelManager() {
  display_settings_provider_->RemoveDisplayAreaObserver(this);

  // Docked strip should be disposed explicitly before DisplaySettingsProvider
  // is gone since docked strip needs to remove the observer from
  // DisplaySettingsProvider.
  docked_strip_.reset();
}

void PanelManager::OnDisplayAreaChanged(const gfx::Rect& display_area) {
  if (display_area == display_area_)
    return;
  display_area_ = display_area;

  gfx::Rect docked_strip_bounds = display_area;
  docked_strip_bounds.set_x(display_area.x() + kPanelStripLeftMargin);
  docked_strip_bounds.set_width(display_area.width() -
                                kPanelStripLeftMargin - kPanelStripRightMargin);
  docked_strip_->SetDisplayArea(docked_strip_bounds);

  detached_strip_->SetDisplayArea(display_area);
}

void PanelManager::OnFullScreenModeChanged(bool is_full_screen) {
  docked_strip_->OnFullScreenModeChanged(is_full_screen);
}

int PanelManager::GetMaxPanelWidth() const {
  return static_cast<int>(display_area_.width() * kPanelMaxWidthFactor);
}

int PanelManager::GetMaxPanelHeight() const {
  return display_area_.height() * kPanelMaxHeightFactor;
}

Panel* PanelManager::CreatePanel(Browser* browser) {
  // Need to sync the display area if no panel is present. This is because:
  // 1) Display area is not initialized until first panel is created.
  // 2) On windows, display settings notification is tied to a window. When
  //    display settings are changed at the time that no panel exists, we do
  //    not receive any notification.
  if (num_panels() == 0)
    display_settings_provider_->OnDisplaySettingsChanged();

  int width = browser->override_bounds().width();
  int height = browser->override_bounds().height();
  Panel* panel = new Panel(browser, gfx::Size(width, height));
  docked_strip_->AddPanel(panel, PanelStrip::DEFAULT_POSITION);
  docked_strip_->UpdatePanelOnStripChange(panel);

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PANEL_ADDED,
      content::Source<Panel>(panel),
      content::NotificationService::NoDetails());

  if (num_panels() == 1) {
    display_settings_provider_->AddFullScreenObserver(this);
  }

  return panel;
}

void PanelManager::OnPanelClosed(Panel* panel) {
  if (num_panels() == 1) {
    display_settings_provider_->RemoveFullScreenObserver(this);
  }

  drag_controller_->OnPanelClosed(panel);
  resize_controller_->OnPanelClosed(panel);
  panel->panel_strip()->RemovePanel(panel);

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PANEL_CLOSED,
      content::Source<Panel>(panel),
      content::NotificationService::NoDetails());
}

void PanelManager::StartDragging(Panel* panel,
                                 const gfx::Point& mouse_location) {
  drag_controller_->StartDragging(panel, mouse_location);
}

void PanelManager::Drag(const gfx::Point& mouse_location) {
  drag_controller_->Drag(mouse_location);
}

void PanelManager::EndDragging(bool cancelled) {
  drag_controller_->EndDragging(cancelled);
}

void PanelManager::StartResizingByMouse(Panel* panel,
    const gfx::Point& mouse_location,
    panel::ResizingSides sides) {
  if (panel->CanResizeByMouse() != panel::NOT_RESIZABLE &&
      sides != panel::RESIZE_NONE)
    resize_controller_->StartResizing(panel, mouse_location, sides);
}

void PanelManager::ResizeByMouse(const gfx::Point& mouse_location) {
  if (resize_controller_->IsResizing())
    resize_controller_->Resize(mouse_location);
}

void PanelManager::EndResizingByMouse(bool cancelled) {
  if (resize_controller_->IsResizing()) {
    Panel* resized_panel = resize_controller_->EndResizing(cancelled);
    if (!cancelled && resized_panel->panel_strip())
      resized_panel->panel_strip()->RefreshLayout();
  }
}

void PanelManager::OnPanelExpansionStateChanged(Panel* panel) {
  // For panels outside of the docked strip changing state is a no-op.
  // But since this method may be called for panels in other strips
  // we need to check this condition.
  if (panel->panel_strip() == docked_strip_.get())
    docked_strip_->OnPanelExpansionStateChanged(panel);

}

void PanelManager::OnWindowAutoResized(Panel* panel,
                                       const gfx::Size& preferred_window_size) {
  DCHECK(auto_sizing_enabled_);
  panel->panel_strip()->ResizePanelWindow(panel, preferred_window_size);
}

void PanelManager::ResizePanel(Panel* panel, const gfx::Size& new_size) {
  PanelStrip* panel_strip = panel->panel_strip();
  if (!panel_strip)
    return;
  panel_strip->ResizePanelWindow(panel, new_size);
  panel->SetAutoResizable(false);
}

void PanelManager::OnPanelResizedByMouse(Panel* panel,
                                         const gfx::Rect& new_bounds) {
  panel->panel_strip()->OnPanelResizedByMouse(panel, new_bounds);
}

void PanelManager::MovePanelToStrip(
    Panel* panel,
    PanelStrip::Type new_layout,
    PanelStrip::PositioningMask positioning_mask) {
  DCHECK(panel);
  PanelStrip* current_strip = panel->panel_strip();
  DCHECK(current_strip);
  DCHECK_NE(current_strip->type(), new_layout);
  current_strip->RemovePanel(panel);

  PanelStrip* target_strip = NULL;
  switch (new_layout) {
    case PanelStrip::DETACHED:
      target_strip = detached_strip_.get();
      break;
    case PanelStrip::DOCKED:
      target_strip = docked_strip_.get();
      break;
    default:
      NOTREACHED();
  }

  target_strip->AddPanel(panel, positioning_mask);
  target_strip->UpdatePanelOnStripChange(panel);
}

bool PanelManager::ShouldBringUpTitlebars(int mouse_x, int mouse_y) const {
  return docked_strip_->ShouldBringUpTitlebars(mouse_x, mouse_y);
}

void PanelManager::BringUpOrDownTitlebars(bool bring_up) {
  docked_strip_->BringUpOrDownTitlebars(bring_up);
}

BrowserWindow* PanelManager::GetNextBrowserWindowToActivate(
    Panel* panel) const {
  // Find the last active browser window that is not minimized.
  BrowserList::const_reverse_iterator iter = BrowserList::begin_last_active();
  BrowserList::const_reverse_iterator end = BrowserList::end_last_active();
  for (; (iter != end); ++iter) {
    Browser* browser = *iter;
    if (panel->browser() != browser && !browser->window()->IsMinimized())
      return browser->window();
  }

  return NULL;
}

void PanelManager::CloseAll() {
  DCHECK(!drag_controller_->IsDragging());

  detached_strip_->CloseAll();
  docked_strip_->CloseAll();
}

int PanelManager::num_panels() const {
  return detached_strip_->num_panels() + docked_strip_->num_panels();
}

std::vector<Panel*> PanelManager::panels() const {
  std::vector<Panel*> panels;
  for (DetachedPanelStrip::Panels::const_iterator iter =
           detached_strip_->panels().begin();
       iter != detached_strip_->panels().end(); ++iter)
    panels.push_back(*iter);
  for (DockedPanelStrip::Panels::const_iterator iter =
           docked_strip_->panels().begin();
       iter != docked_strip_->panels().end(); ++iter)
    panels.push_back(*iter);
  return panels;
}

void PanelManager::SetMouseWatcher(PanelMouseWatcher* watcher) {
  panel_mouse_watcher_.reset(watcher);
}

void PanelManager::OnPanelAnimationEnded(Panel* panel) {
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PANEL_BOUNDS_ANIMATIONS_FINISHED,
      content::Source<Panel>(panel),
      content::NotificationService::NoDetails());
}
<|endoftext|>


<commit_before>#include "profilecontainer.h"
#include "profilebuttons.h"
#include "profiletranslation.h"

#include <DuiButton>
#include <DuiSlider>
#include <DuiLabel>
#include <DuiLayout>
#include <DuiImage>
#include <DuiGridLayoutPolicy>
#include <DuiStylableWidget>
#include <QDebug>

namespace ProfileApplet{
    const int sliderMin = 0;
    const int sliderMax = 100;
}

ProfileContainer::ProfileContainer(int id, const QString &title, DuiWidget *parent) :
    DuiContainer(title, parent),
    slider(NULL),
    level(-2),
    profileId(id)
{
    qDebug() << "ProfileContainer::ProfileContainer()" << title;

    // TODO: hardcoded silent value!!
    if(profileId != 1) {
        slider = new DuiSlider(this, "continuous");
        slider->setOrientation(Qt::Horizontal);
        slider->setRange(ProfileApplet::sliderMin, ProfileApplet::sliderMax);
        slider->setThumbLabelVisible(false);
        connect(slider, SIGNAL(valueChanged(int)), this, SIGNAL(sliderValueChanged(int)));
    }

    button = new DuiButton(DcpProfile::VibrationText, this);
    button->setCheckable(true);
    button->setMaximumHeight(36);
    setVibration(true);
    connect(button, SIGNAL(toggled(bool)), this, SIGNAL(vibrationChanged(bool)));

    setLayout();
}

ProfileContainer::~ProfileContainer()
{
}

void ProfileContainer::setLayout()
{
    DuiLayout *layout = new DuiLayout();

    DuiGridLayoutPolicy *landscapePolicy = new DuiGridLayoutPolicy(layout);
    //landscapePolicy->setObjectName("profileContainerLayout.Landscape");
    layout->setLandscapePolicy(landscapePolicy); // ownership transferred

    DuiGridLayoutPolicy *portraitPolicy = new DuiGridLayoutPolicy(layout);
    //portraitPolicy->setObjectName("profileContainerLayout.Portrait");
    layout->setPortraitPolicy(portraitPolicy); // ownership transferred

    DuiImage* img = NULL;
    QGraphicsLayoutItem* item = NULL;

    if(slider)
    {
        img = new DuiImage("icon-m-volume-off", this);
        item = slider;
        qDebug() << "slider height" << slider->size().height();
        slider->setMaximumHeight(32);
    }
    else
    {
        img = new DuiImage("icon-m-volume", this);
        item = new DuiLabel(DcpProfile::NoRingingText, this);
    }
    img->setObjectName("speakerIcon");

    landscapePolicy->setColumnFixedWidth(0, img->imageSize().width());
    portraitPolicy->setColumnFixedWidth(0, img->imageSize().width());
    landscapePolicy->setRowFixedHeight(0, img->imageSize().height());
    portraitPolicy->setRowFixedHeight(0, img->imageSize().height());

    // set objects
    landscapePolicy->addItemAtPosition(img, 0, 0);
    portraitPolicy->addItemAtPosition(img, 0, 0);
    landscapePolicy->addItemAtPosition(item, 0, 1);
    portraitPolicy->addItemAtPosition(item, 0, 1);
    landscapePolicy->addItemAtPosition(button, 1, 0, 1, 2);
    portraitPolicy->addItemAtPosition(button, 1, 0, 1, 2);

    landscapePolicy->setSpacing(5);
    portraitPolicy->setSpacing(5);

    DuiStylableWidget *layoutWidget = new DuiStylableWidget();
    layoutWidget->setLayout(layout);
    layoutWidget->setObjectName("profileContainerLayout");

    setCentralWidget(layoutWidget);
}

void ProfileContainer::setLevel(int value)
{
    qDebug() << "ProfileContainer::setLevel for " << title() << ":" << value << "(old:" << level << ")";
    if(!slider || value == level)
        return;

    level = value;
    if(ProfileApplet::sliderMin < level && ProfileApplet::sliderMax >= level)
    {
        slider->setValue(level);
        qDebug() << "ProfileContainer::setLevel done:" << slider->value();
    }
    qDebug() << "ProfileContainer::setLevel done:" << slider->value();
}

void ProfileContainer::setVibration(bool enabled)
{
    qDebug() << "ProfileContainer::setVibration for " << title() << ":" << enabled;
    button->setChecked(enabled);
}

int ProfileContainer::id()
{
    return profileId;
}
<commit_msg>Icons switched to correct places<commit_after>#include "profilecontainer.h"
#include "profilebuttons.h"
#include "profiletranslation.h"

#include <DuiButton>
#include <DuiSlider>
#include <DuiLabel>
#include <DuiLayout>
#include <DuiImage>
#include <DuiGridLayoutPolicy>
#include <DuiStylableWidget>
#include <QDebug>

namespace ProfileApplet{
    const int sliderMin = 0;
    const int sliderMax = 100;
}

ProfileContainer::ProfileContainer(int id, const QString &title, DuiWidget *parent) :
    DuiContainer(title, parent),
    slider(NULL),
    level(-2),
    profileId(id)
{
    qDebug() << "ProfileContainer::ProfileContainer()" << title;

    // TODO: hardcoded silent value!!
    if(profileId != 1) {
        slider = new DuiSlider(this, "continuous");
        slider->setOrientation(Qt::Horizontal);
        slider->setRange(ProfileApplet::sliderMin, ProfileApplet::sliderMax);
        slider->setThumbLabelVisible(false);
        connect(slider, SIGNAL(valueChanged(int)), this, SIGNAL(sliderValueChanged(int)));
    }

    button = new DuiButton(DcpProfile::VibrationText, this);
    button->setCheckable(true);
    button->setMaximumHeight(36);
    setVibration(true);
    connect(button, SIGNAL(toggled(bool)), this, SIGNAL(vibrationChanged(bool)));

    setLayout();
}

ProfileContainer::~ProfileContainer()
{
}

void ProfileContainer::setLayout()
{
    DuiLayout *layout = new DuiLayout();

    DuiGridLayoutPolicy *landscapePolicy = new DuiGridLayoutPolicy(layout);
    //landscapePolicy->setObjectName("profileContainerLayout.Landscape");
    layout->setLandscapePolicy(landscapePolicy); // ownership transferred

    DuiGridLayoutPolicy *portraitPolicy = new DuiGridLayoutPolicy(layout);
    //portraitPolicy->setObjectName("profileContainerLayout.Portrait");
    layout->setPortraitPolicy(portraitPolicy); // ownership transferred

    DuiImage* img = NULL;
    QGraphicsLayoutItem* item = NULL;

    if(slider)
    {
        img = new DuiImage("icon-m-volume", this);
        item = slider;
        qDebug() << "slider height" << slider->size().height();
        slider->setMaximumHeight(32);
    }
    else
    {
        img = new DuiImage("icon-m-volume-off", this);
        item = new DuiLabel(DcpProfile::NoRingingText, this);
    }
    img->setObjectName("speakerIcon");

    landscapePolicy->setColumnFixedWidth(0, img->imageSize().width());
    portraitPolicy->setColumnFixedWidth(0, img->imageSize().width());
    landscapePolicy->setRowFixedHeight(0, img->imageSize().height());
    portraitPolicy->setRowFixedHeight(0, img->imageSize().height());

    // set objects
    landscapePolicy->addItemAtPosition(img, 0, 0);
    portraitPolicy->addItemAtPosition(img, 0, 0);
    landscapePolicy->addItemAtPosition(item, 0, 1);
    portraitPolicy->addItemAtPosition(item, 0, 1);
    landscapePolicy->addItemAtPosition(button, 1, 0, 1, 2);
    portraitPolicy->addItemAtPosition(button, 1, 0, 1, 2);

    landscapePolicy->setSpacing(5);
    portraitPolicy->setSpacing(5);

    DuiStylableWidget *layoutWidget = new DuiStylableWidget();
    layoutWidget->setLayout(layout);
    layoutWidget->setObjectName("profileContainerLayout");

    setCentralWidget(layoutWidget);
}

void ProfileContainer::setLevel(int value)
{
    qDebug() << "ProfileContainer::setLevel for " << title() << ":" << value << "(old:" << level << ")";
    if(!slider || value == level)
        return;

    level = value;
    if(ProfileApplet::sliderMin < level && ProfileApplet::sliderMax >= level)
    {
        slider->setValue(level);
        qDebug() << "ProfileContainer::setLevel done:" << slider->value();
    }
    qDebug() << "ProfileContainer::setLevel done:" << slider->value();
}

void ProfileContainer::setVibration(bool enabled)
{
    qDebug() << "ProfileContainer::setVibration for " << title() << ":" << enabled;
    button->setChecked(enabled);
}

int ProfileContainer::id()
{
    return profileId;
}
<|endoftext|>


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

#include "chrome/common/sandbox_init_wrapper.h"

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/sandbox_mac.h"

bool SandboxInitWrapper::InitializeSandbox(const CommandLine& command_line,
                                           const std::string& process_type) {
  if (command_line.HasSwitch(switches::kNoSandbox))
    return true;

  sandbox::SandboxProcessType sandbox_process_type;
  FilePath allowed_dir;  // Empty by default.

  if (process_type.empty()) {
    // Browser process isn't sandboxed.
    return true;
  } else if (process_type == switches::kRendererProcess) {
    // Renderer process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_RENDERER;
  } else if (process_type == switches::kExtensionProcess) {
    // Extension process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_RENDERER;
  } else if (process_type == switches::kUtilityProcess) {
    // Utility process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_UTILITY;
    allowed_dir = FilePath::FromWStringHack(
          command_line.GetSwitchValue(switches::kUtilityProcessAllowedDir));
  } else if (process_type == switches::kWorkerProcess) {
    // Worker process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_WORKER;
  } else if ((process_type == switches::kNaClProcess) ||
             (process_type == switches::kPluginProcess) ||
             (process_type == switches::kProfileImportProcess)) {
    return true;
  } else {
    // Failsafe: If you hit an unreached here, is your new process type in need
    // of sandboxing?
    NOTREACHED();
    return true;
  }

  // Warm up APIs before turning on the sandbox.
  sandbox::SandboxWarmup();

  // Actually sandbox the process.
  return sandbox::EnableSandbox(sandbox_process_type, allowed_dir);
}
<commit_msg>Small cleanup to Mac Sandbox code.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/sandbox_init_wrapper.h"

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/sandbox_mac.h"

bool SandboxInitWrapper::InitializeSandbox(const CommandLine& command_line,
                                           const std::string& process_type) {
  if (command_line.HasSwitch(switches::kNoSandbox))
    return true;

  sandbox::SandboxProcessType sandbox_process_type;
  FilePath allowed_dir;  // Empty by default.

  if (process_type.empty()) {
    // Browser process isn't sandboxed.
    return true;
  } else if (process_type == switches::kRendererProcess) {
    // Renderer process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_RENDERER;
  } else if (process_type == switches::kExtensionProcess) {
    // Extension processes are just renderers [they use RenderMain()] with a
    // different set of command line flags.
    // If we ever get here it means something has changed in regards
    // to the extension process mechanics and we should probably reexamine
    // how we sandbox extension processes since they are no longer identical
    // to renderers.
    NOTREACHED();
    return true;
  } else if (process_type == switches::kUtilityProcess) {
    // Utility process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_UTILITY;
    allowed_dir = FilePath::FromWStringHack(
          command_line.GetSwitchValue(switches::kUtilityProcessAllowedDir));
  } else if (process_type == switches::kWorkerProcess) {
    // Worker process sandbox.
    sandbox_process_type = sandbox::SANDBOX_TYPE_WORKER;
  } else if ((process_type == switches::kNaClProcess) ||
             (process_type == switches::kPluginProcess) ||
             (process_type == switches::kProfileImportProcess)) {
    return true;
  } else {
    // Failsafe: If you hit an unreached here, is your new process type in need
    // of sandboxing?
    NOTREACHED();
    return true;
  }

  // Warm up APIs before turning on the sandbox.
  sandbox::SandboxWarmup();

  // Actually sandbox the process.
  return sandbox::EnableSandbox(sandbox_process_type, allowed_dir);
}
<|endoftext|>


<commit_before><commit_msg>remove static OUStrings from static_initialization_and_destruction chain<commit_after><|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/message_loop.h"
#include "base/process_util.h"
#include "base/test/multiprocess_test.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

// TODO(port): Bring up this test this on other platforms.
#if defined(OS_POSIX)

using base::ProcessHandle;

const char kRendererTestChannelName[] = "test";

extern int RendererMain(const MainFunctionParams& parameters);

// TODO(port): The IPC Channel tests have a class with extremely similar
// functionality, we should combine them.
class RendererMainTest : public base::MultiProcessTest {
 protected:
  RendererMainTest() {}

  // Create a new MessageLoopForIO For each test.
  virtual void SetUp();
  virtual void TearDown();

  // Spawns a child process of the specified type
  base::ProcessHandle SpawnChild(const std::string& procname,
                                 IPC::Channel* channel);

  // Created around each test instantiation.
  MessageLoopForIO *message_loop_;
};

void RendererMainTest::SetUp() {
  MultiProcessTest::SetUp();

  // Construct a fresh IO Message loop for the duration of each test.
  message_loop_ = new MessageLoopForIO();
}

void RendererMainTest::TearDown() {
  delete message_loop_;
  message_loop_ = NULL;

  MultiProcessTest::TearDown();
}

ProcessHandle RendererMainTest::SpawnChild(const std::string& procname,
                                           IPC::Channel* channel) {
  base::file_handle_mapping_vector fds_to_map;
  const int ipcfd = channel->GetClientFileDescriptor();
  if (ipcfd > -1) {
    fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));
  }

  return MultiProcessTest::SpawnChild(procname, fds_to_map, false);
}

// Listener class that kills the message loop when it connects.
class SuicidalListener : public IPC::Channel::Listener {
 public:
  explicit SuicidalListener(bool* suicide_success)
      : suicide_success_(suicide_success) {}

  void OnChannelConnected(int32 peer_pid) {
    *suicide_success_ = true;
    MessageLoop::current()->Quit();
  }

  void OnMessageReceived(const IPC::Message& message) {
    // We shouldn't receive any messages
    ASSERT_TRUE(false);
  }

  // A flag that we set when we have successfully suicided.
  bool* suicide_success_;
};

MULTIPROCESS_TEST_MAIN(SimpleRenderer) {
  SandboxInitWrapper dummy_sandbox_init;
  CommandLine cl(*CommandLine::ForCurrentProcess());
  cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);

  MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);
  return RendererMain(dummy_params);
}

TEST_F(RendererMainTest, CreateDestroy) {
  bool suicide_success = false;
  SuicidalListener listener(&suicide_success);
  IPC::Channel control_channel(kRendererTestChannelName,
                               IPC::Channel::MODE_SERVER,
                               &listener);
  base::ProcessHandle renderer_pid = SpawnChild("SimpleRenderer",
                                                &control_channel);

  ASSERT_TRUE(control_channel.Connect());

  // The SuicidalListener *should* cause the following MessageLoop run
  // to quit, but just in case it doesn't, insert a QuitTask at the back
  // of the queue.
  MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
                                          TestTimeouts::action_timeout_ms());
  MessageLoop::current()->Run();
  ASSERT_TRUE(suicide_success);

  // The renderer should exit when we close the channel.
  control_channel.Close();

  EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,
                                         TestTimeouts::action_timeout_ms()));
}
#endif  // defined(OS_POSIX)
<commit_msg>Revert most of my recent changes to RendererMainTest.<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/message_loop.h"
#include "base/process_util.h"
#include "base/test/multiprocess_test.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

// TODO(port): Bring up this test this on other platforms.
#if defined(OS_POSIX)

using base::ProcessHandle;

const char kRendererTestChannelName[] = "test";

extern int RendererMain(const MainFunctionParams& parameters);

// TODO(port): The IPC Channel tests have a class with extremely similar
// functionality, we should combine them.
class RendererMainTest : public base::MultiProcessTest {
 protected:
  RendererMainTest() {}

  // Create a new MessageLoopForIO For each test.
  virtual void SetUp();
  virtual void TearDown();

  // Spawns a child process of the specified type
  base::ProcessHandle SpawnChild(const std::string& procname,
                                 IPC::Channel* channel);

  // Created around each test instantiation.
  MessageLoopForIO *message_loop_;
};

void RendererMainTest::SetUp() {
  MultiProcessTest::SetUp();

  // Construct a fresh IO Message loop for the duration of each test.
  message_loop_ = new MessageLoopForIO();
}

void RendererMainTest::TearDown() {
  delete message_loop_;
  message_loop_ = NULL;

  MultiProcessTest::TearDown();
}

ProcessHandle RendererMainTest::SpawnChild(const std::string& procname,
                                           IPC::Channel* channel) {
  base::file_handle_mapping_vector fds_to_map;
  const int ipcfd = channel->GetClientFileDescriptor();
  if (ipcfd > -1) {
    fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));
  }

  return MultiProcessTest::SpawnChild(procname, fds_to_map, false);
}

// Listener class that kills the message loop when it connects.
class SuicidalListener : public IPC::Channel::Listener {
 public:
  void OnChannelConnected(int32 peer_pid) {
    MessageLoop::current()->Quit();
  }

  void OnMessageReceived(const IPC::Message& message) {
    // We shouldn't receive any messages
    ASSERT_TRUE(false);
  }
};

MULTIPROCESS_TEST_MAIN(SimpleRenderer) {
  SandboxInitWrapper dummy_sandbox_init;
  CommandLine cl(*CommandLine::ForCurrentProcess());
  cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);

  MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);
  return RendererMain(dummy_params);
}

TEST_F(RendererMainTest, CreateDestroy) {
  SuicidalListener listener;
  IPC::Channel control_channel(kRendererTestChannelName,
                               IPC::Channel::MODE_SERVER,
                               &listener);
  base::ProcessHandle renderer_pid = SpawnChild("SimpleRenderer",
                                                &control_channel);

  ASSERT_TRUE(control_channel.Connect());

  MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
                                          TestTimeouts::action_timeout_ms());
  MessageLoop::current()->Run();

  // The renderer should exit when we close the channel.
  control_channel.Close();

  EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,
                                         TestTimeouts::action_timeout_ms()));
}
#endif  // defined(OS_POSIX)
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/CPlotItem.cpp,v $
//   $Revision: 1.17 $
//   $Name:  $
//   $Author: gauges $
//   $Date: 2007/02/12 20:54:09 $
// End CVS Header

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CPlotItem.h"
#include "report/CKeyFactory.h"

const std::string CPlotItem::TypeName[] =
  {
    "Unset",
    "2D Curve",
    "Histogram",

    "2D Plot",
    "SimWiz",
    ""
  };

const char* CPlotItem::XMLType[] =
  {
    "Unset",
    "Curve2D",
    "Histogram1DItem",

    "Plot2D",
    "SimWiz",
    NULL
  };

const std::string CPlotItem::RecordingActivityName[] =
  {
    "",
    "Before",
    "During",
    "",
    "After"
  };

const char* CPlotItem::XMLRecordingActivity[] =
  {
    "NotSet",
    "before",
    "during",
    "before&during",
    "after",
    "before&after",
    "during&after",
    "before&during&after",
    NULL
  };

CPlotItem::Type CPlotItem::TypeNameToEnum(const std::string & typeName) //static
{
  unsigned C_INT32 i = 0;
  while (TypeName[i] != typeName && TypeName[i] != "") i++;

  if (CPlotItem::TypeName[i] != "") return (CPlotItem::Type) i;
  else return CPlotItem::unset;
}

CPlotItem::CPlotItem(const std::string & name,
                     const CCopasiContainer * pParent,
                     const CPlotItem::Type & type):
    CCopasiParameterGroup(TypeName[type], pParent, "PlotItem"),
    mType(unset),
    mActivity(),
    mpXMLActivity(NULL)
{
  //setObjectName(TypeName[mType]); //TODO
  setObjectName(name);
  setType(type); //to create the parameters
}

CPlotItem::CPlotItem(const CPlotItem & src,
                     const CCopasiContainer * pParent):
    CCopasiParameterGroup(src, pParent),
    mType(unset),
    mActivity(),
    mpXMLActivity(NULL),
    channels(src.getChannels())
{
  /*
  std::cout << "Creating new PlotItem from Template: " << this << std::endl;
  for(unsigned int counter=0; counter < src.getChannels().size(); counter++)
  {
     std::cout << "Channel " << counter << ": " << src.getChannels()[counter] << std::endl;
  }
  for(unsigned int counter=0; counter < this->getChannels().size(); counter++)
  {
     std::cout << "New Channel " << counter << ": " << this->getChannels()[counter] << std::endl;
  }
  */
  setType(src.mType);
}

void CPlotItem::setType(CPlotItem::Type type)
{
  if (type == mType) return;
  if (mType != unset) clear();

  mType = type;

  //create parameters
  if (type == curve2d)
    {
      assertParameter("Line type", CCopasiParameter::UINT, (unsigned C_INT32) 0);
    }

  if (type == histoItem1d)
    {
      assertParameter("increment", CCopasiParameter::DOUBLE, (C_FLOAT64) 0.1);
    }

  if (type == curve2d || type == histoItem1d)
    {
      mpXMLActivity =
        assertParameter("Recording Activity", CCopasiParameter::STRING, std::string("during"))->getValue().pSTRING;

      const char ** pActivity = XMLRecordingActivity;
      while (*pActivity && mpXMLActivity->compare(*pActivity))
        pActivity++;
      mActivity = (COutputInterface::Activity) (pActivity - XMLRecordingActivity);

      if (mActivity < COutputInterface::BEFORE ||
          (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < mActivity)
        {
          mActivity = COutputInterface:: DURING;
          * mpXMLActivity = XMLRecordingActivity[mActivity];
        }
    }

  if (type == plot2d)
    {
      assertParameter("log X", CCopasiParameter::BOOL, false);
      assertParameter("log Y", CCopasiParameter::BOOL, false);
      mpXMLActivity = NULL;
      mActivity = (COutputInterface::Activity) 0;
    }
}

CPlotItem::~CPlotItem()
{}

void CPlotItem::cleanup()
{
  //TODO: parametergroup cleanup
}

void CPlotItem::initObjects()
{}

const CPlotItem::Type & CPlotItem::getType() const
  {return mType;}

void CPlotItem::setActivity(const COutputInterface::Activity & activity)
{
  switch (mType)
    {
    case curve2d:
    case histoItem1d:
      mActivity = activity;
      assert (COutputInterface::BEFORE <= mActivity &&
              mActivity <= (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER));
      * mpXMLActivity = XMLRecordingActivity[mActivity];
      break;

    default:
      mActivity = (COutputInterface::Activity) 0;
      break;
    }
}

const COutputInterface::Activity & CPlotItem::getActivity() const
  {
    const char ** pActivity = XMLRecordingActivity;
    COutputInterface::Activity Activity;

    switch (mType)
      {
      case curve2d:
      case histoItem1d:
        if (!mpXMLActivity)
          const_cast<CPlotItem *>(this)->mpXMLActivity =
            getParameter("Recording Activity")->getValue().pSTRING;

        while (*pActivity && mpXMLActivity->compare(*pActivity)) pActivity++;

        Activity =
          (COutputInterface::Activity) (pActivity - XMLRecordingActivity);

        if (Activity < COutputInterface::BEFORE ||
            (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < Activity)
          {
            Activity = COutputInterface::DURING;
            * mpXMLActivity = XMLRecordingActivity[Activity];
          }

        const_cast<CPlotItem *>(this)->mActivity = Activity;

        break;

      default:
        break;
      }

    return mActivity;
  }

std::vector<CPlotDataChannelSpec> & CPlotItem::getChannels()
{return channels;}

const std::vector<CPlotDataChannelSpec> & CPlotItem::getChannels() const
  {return channels;}

unsigned C_INT32 CPlotItem::getNumChannels() const
  {return channels.size();}

void CPlotItem::addChannel(const CPlotDataChannelSpec & channel)
{
  channels.push_back(channel);
}

const std::string & CPlotItem::getTitle() const
  {
    return getObjectName();
  }

void CPlotItem::setTitle(const std::string & title)
{
  setObjectName(title);
}
<commit_msg>fixed #834. Default bin size for histogram is now 1.0<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/CPlotItem.cpp,v $
//   $Revision: 1.18 $
//   $Name:  $
//   $Author: ssahle $
//   $Date: 2007/07/10 08:54:07 $
// End CVS Header

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CPlotItem.h"
#include "report/CKeyFactory.h"

const std::string CPlotItem::TypeName[] =
  {
    "Unset",
    "2D Curve",
    "Histogram",

    "2D Plot",
    "SimWiz",
    ""
  };

const char* CPlotItem::XMLType[] =
  {
    "Unset",
    "Curve2D",
    "Histogram1DItem",

    "Plot2D",
    "SimWiz",
    NULL
  };

const std::string CPlotItem::RecordingActivityName[] =
  {
    "",
    "Before",
    "During",
    "",
    "After"
  };

const char* CPlotItem::XMLRecordingActivity[] =
  {
    "NotSet",
    "before",
    "during",
    "before&during",
    "after",
    "before&after",
    "during&after",
    "before&during&after",
    NULL
  };

CPlotItem::Type CPlotItem::TypeNameToEnum(const std::string & typeName) //static
{
  unsigned C_INT32 i = 0;
  while (TypeName[i] != typeName && TypeName[i] != "") i++;

  if (CPlotItem::TypeName[i] != "") return (CPlotItem::Type) i;
  else return CPlotItem::unset;
}

CPlotItem::CPlotItem(const std::string & name,
                     const CCopasiContainer * pParent,
                     const CPlotItem::Type & type):
    CCopasiParameterGroup(TypeName[type], pParent, "PlotItem"),
    mType(unset),
    mActivity(),
    mpXMLActivity(NULL)
{
  //setObjectName(TypeName[mType]); //TODO
  setObjectName(name);
  setType(type); //to create the parameters
}

CPlotItem::CPlotItem(const CPlotItem & src,
                     const CCopasiContainer * pParent):
    CCopasiParameterGroup(src, pParent),
    mType(unset),
    mActivity(),
    mpXMLActivity(NULL),
    channels(src.getChannels())
{
  /*
  std::cout << "Creating new PlotItem from Template: " << this << std::endl;
  for(unsigned int counter=0; counter < src.getChannels().size(); counter++)
  {
     std::cout << "Channel " << counter << ": " << src.getChannels()[counter] << std::endl;
  }
  for(unsigned int counter=0; counter < this->getChannels().size(); counter++)
  {
     std::cout << "New Channel " << counter << ": " << this->getChannels()[counter] << std::endl;
  }
  */
  setType(src.mType);
}

void CPlotItem::setType(CPlotItem::Type type)
{
  if (type == mType) return;
  if (mType != unset) clear();

  mType = type;

  //create parameters
  if (type == curve2d)
    {
      assertParameter("Line type", CCopasiParameter::UINT, (unsigned C_INT32) 0);
    }

  if (type == histoItem1d)
    {
      assertParameter("increment", CCopasiParameter::DOUBLE, (C_FLOAT64) 1.0);
    }

  if (type == curve2d || type == histoItem1d)
    {
      mpXMLActivity =
        assertParameter("Recording Activity", CCopasiParameter::STRING, std::string("during"))->getValue().pSTRING;

      const char ** pActivity = XMLRecordingActivity;
      while (*pActivity && mpXMLActivity->compare(*pActivity))
        pActivity++;
      mActivity = (COutputInterface::Activity) (pActivity - XMLRecordingActivity);

      if (mActivity < COutputInterface::BEFORE ||
          (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < mActivity)
        {
          mActivity = COutputInterface:: DURING;
          * mpXMLActivity = XMLRecordingActivity[mActivity];
        }
    }

  if (type == plot2d)
    {
      assertParameter("log X", CCopasiParameter::BOOL, false);
      assertParameter("log Y", CCopasiParameter::BOOL, false);
      mpXMLActivity = NULL;
      mActivity = (COutputInterface::Activity) 0;
    }
}

CPlotItem::~CPlotItem()
{}

void CPlotItem::cleanup()
{
  //TODO: parametergroup cleanup
}

void CPlotItem::initObjects()
{}

const CPlotItem::Type & CPlotItem::getType() const
  {return mType;}

void CPlotItem::setActivity(const COutputInterface::Activity & activity)
{
  switch (mType)
    {
    case curve2d:
    case histoItem1d:
      mActivity = activity;
      assert (COutputInterface::BEFORE <= mActivity &&
              mActivity <= (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER));
      * mpXMLActivity = XMLRecordingActivity[mActivity];
      break;

    default:
      mActivity = (COutputInterface::Activity) 0;
      break;
    }
}

const COutputInterface::Activity & CPlotItem::getActivity() const
  {
    const char ** pActivity = XMLRecordingActivity;
    COutputInterface::Activity Activity;

    switch (mType)
      {
      case curve2d:
      case histoItem1d:
        if (!mpXMLActivity)
          const_cast<CPlotItem *>(this)->mpXMLActivity =
            getParameter("Recording Activity")->getValue().pSTRING;

        while (*pActivity && mpXMLActivity->compare(*pActivity)) pActivity++;

        Activity =
          (COutputInterface::Activity) (pActivity - XMLRecordingActivity);

        if (Activity < COutputInterface::BEFORE ||
            (COutputInterface::BEFORE | COutputInterface::DURING | COutputInterface::AFTER) < Activity)
          {
            Activity = COutputInterface::DURING;
            * mpXMLActivity = XMLRecordingActivity[Activity];
          }

        const_cast<CPlotItem *>(this)->mActivity = Activity;

        break;

      default:
        break;
      }

    return mActivity;
  }

std::vector<CPlotDataChannelSpec> & CPlotItem::getChannels()
{return channels;}

const std::vector<CPlotDataChannelSpec> & CPlotItem::getChannels() const
  {return channels;}

unsigned C_INT32 CPlotItem::getNumChannels() const
  {return channels.size();}

void CPlotItem::addChannel(const CPlotDataChannelSpec & channel)
{
  channels.push_back(channel);
}

const std::string & CPlotItem::getTitle() const
  {
    return getObjectName();
  }

void CPlotItem::setTitle(const std::string & title)
{
  setObjectName(title);
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//-----------------------------------------------------------------------------

// Test Lagrange interpolation

#include "../tests.h"
#include <iostream>
#include <fstream>
#include <cmath>

#include <base/logstream.h>
#include <base/polynomial.h>
#include <base/quadrature_lib.h>

using namespace Polynomials;

void check_interpolation (const std::vector<Polynomial<double> >& p,
			  const std::vector<Point<1> >& x)
{
  for (unsigned int i=0;i<p.size();++i)
    {
      deallog << i;
      for (unsigned int k=0;k<x.size();++k)
	{
	  deallog << '.';
	  const double y = p[i].value(x[k](0));
	  if (i == k)
	    {
	      if (std::fabs(y-1.) > 2.e-10)
		deallog << "Error1  lg y=" << std::log10(std::fabs(y-1.))
			<< std::endl;
	    }
	  else
	    {
	      if (std::fabs(y) > 2.e-10)
		deallog << "Error0  lg y=" << std::log10(std::fabs(y))
			<< std::endl;
	    }
	}
      deallog << std::endl;
    }
}

void
check_poly (const Quadrature<1>& q)
{
  deallog << "Points: " << q.n_quadrature_points << std::endl;
  std::vector<Polynomial<double> > p = Lagrange::generate_complete_basis(q.get_points());
  check_interpolation(p, q.get_points());
}

void
check_lge (unsigned int n)
{
  deallog << "Points: " << n+1 << std::endl;
  std::vector<Polynomial<double> > p = LagrangeEquidistant::generate_complete_basis(n);
  std::vector<Point<1> > x(n+1);
  const double h = 1./n;
  for (unsigned int i=0;i<=n;++i)
    x[i](0) = h*i;
  check_interpolation(p, x);
}

int main()
{
  std::ofstream logfile("polynomial_lagrange.output");
  logfile.precision(3);
  deallog.attach(logfile);
  deallog.depth_console(0);
//  deallog.threshold_double(1.e-10);

  QTrapez<1> trapez;
  QSimpson<1> simpson;
  QIterated<1> equi7(trapez, 6);
  QIterated<1> equi10(trapez, 9);

  QGauss<1> g2(2);
  QGauss<1> g3(3);
  QGauss<1> g7(7);
  QGauss<1> g10(10);

  QGaussLobatto<1> gl2(2);
  QGaussLobatto<1> gl3(3);
  QGaussLobatto<1> gl4(4);
  QGaussLobatto<1> gl5(5);
  QGaussLobatto<1> gl6(6);
  QGaussLobatto<1> gl7(7);
  QGaussLobatto<1> gl10(10);

  deallog.push("LagrangeEquidistant");
  check_lge(6);
  check_lge(9);
  deallog.pop();
  deallog.push("Equidistant");
  check_poly(trapez);
  check_poly(simpson);
  check_poly(equi7);
  check_poly(equi10);
  deallog.pop();
  deallog.push("Gauss");
  check_poly(g2);
  check_poly(g3);
  check_poly(g7);
  check_poly(g10);
  deallog.pop();
  deallog.push("GaussLobatto");
  check_poly(gl2);
  check_poly(gl3);
  check_poly(gl4);
  check_poly(gl5);
  check_poly(gl6);
  check_poly(gl7);
  check_poly(gl10);
  deallog.pop();
}
<commit_msg>Slightly relax tol to avoid Error0 for gcc2.95.3<commit_after>//-----------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//-----------------------------------------------------------------------------

// Test Lagrange interpolation

#include "../tests.h"
#include <iostream>
#include <fstream>
#include <cmath>

#include <base/logstream.h>
#include <base/polynomial.h>
#include <base/quadrature_lib.h>

using namespace Polynomials;

void check_interpolation (const std::vector<Polynomial<double> >& p,
			  const std::vector<Point<1> >& x)
{
  for (unsigned int i=0;i<p.size();++i)
    {
      deallog << i;
      for (unsigned int k=0;k<x.size();++k)
	{
	  deallog << '.';
	  const double y = p[i].value(x[k](0));
	  if (i == k)
	    {
	      if (std::fabs(y-1.) > 2.e-10)
		deallog << "Error1  lg y=" << std::log10(std::fabs(y-1.))
			<< std::endl;
	    }
	  else
	    {
	      if (std::fabs(y) > 3.e-10)
		deallog << "Error0  lg y=" << std::log10(std::fabs(y))
			<< std::endl;
	    }
	}
      deallog << std::endl;
    }
}

void
check_poly (const Quadrature<1>& q)
{
  deallog << "Points: " << q.n_quadrature_points << std::endl;
  std::vector<Polynomial<double> > p = Lagrange::generate_complete_basis(q.get_points());
  check_interpolation(p, q.get_points());
}

void
check_lge (unsigned int n)
{
  deallog << "Points: " << n+1 << std::endl;
  std::vector<Polynomial<double> > p = LagrangeEquidistant::generate_complete_basis(n);
  std::vector<Point<1> > x(n+1);
  const double h = 1./n;
  for (unsigned int i=0;i<=n;++i)
    x[i](0) = h*i;
  check_interpolation(p, x);
}

int main()
{
  std::ofstream logfile("polynomial_lagrange.output");
  logfile.precision(3);
  deallog.attach(logfile);
  deallog.depth_console(0);
//  deallog.threshold_double(1.e-10);

  QTrapez<1> trapez;
  QSimpson<1> simpson;
  QIterated<1> equi7(trapez, 6);
  QIterated<1> equi10(trapez, 9);

  QGauss<1> g2(2);
  QGauss<1> g3(3);
  QGauss<1> g7(7);
  QGauss<1> g10(10);

  QGaussLobatto<1> gl2(2);
  QGaussLobatto<1> gl3(3);
  QGaussLobatto<1> gl4(4);
  QGaussLobatto<1> gl5(5);
  QGaussLobatto<1> gl6(6);
  QGaussLobatto<1> gl7(7);
  QGaussLobatto<1> gl10(10);

  deallog.push("LagrangeEquidistant");
  check_lge(6);
  check_lge(9);
  deallog.pop();
  deallog.push("Equidistant");
  check_poly(trapez);
  check_poly(simpson);
  check_poly(equi7);
  check_poly(equi10);
  deallog.pop();
  deallog.push("Gauss");
  check_poly(g2);
  check_poly(g3);
  check_poly(g7);
  check_poly(g10);
  deallog.pop();
  deallog.push("GaussLobatto");
  check_poly(gl2);
  check_poly(gl3);
  check_poly(gl4);
  check_poly(gl5);
  check_poly(gl6);
  check_poly(gl7);
  check_poly(gl10);
  deallog.pop();
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// hash_join_test.cpp
//
// Identification: tests/executor/hash_join_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/hash_join_executor.h"
#include "backend/executor/hash_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/expression_util.h"
#include "backend/planner/hash_join_plan.h"
#include "backend/planner/hash_plan.h"
#include "backend/storage/data_table.h"

#include "mock_executor.h"
#include "executor/executor_tests_util.h"
#include "executor/join_tests_util.h"
#include "harness.h"

using ::testing::NotNull;
using ::testing::Return;

namespace peloton {
namespace test {

// Basic Test
// Single join clause, multiple tiles with same tuples per tile,
// join on key (i.e. there will have at most one tuple for each different join key
TEST(HashJoinTests, BasicTest) {

  expression::AbstractExpression *right_table_attr_1 =
      new expression::TupleValueExpression(1, 1);

  std::vector<std::unique_ptr<const expression::AbstractExpression> > hashkeys;
  hashkeys.emplace_back(right_table_attr_1);

  // Create hash plan node
  planner::HashPlan hash_plan_node(hashkeys);

  // Create the hash hash_join_executor
  executor::HashExecutor hash_executor(&hash_plan_node, nullptr);

  // Create hash join plan node.
  auto projection = JoinTestsUtil::CreateProjection();
  planner::HashJoinPlan hash_join_plan_node(nullptr, projection);

  // Create the hash join hash_join_executor
  executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);

  MockExecutor left_executor;
  hash_join_executor.AddChild(&left_executor);
  hash_join_executor.AddChild(&hash_join_executor);

  EXPECT_CALL(left_executor, DInit()).WillOnce(Return(true));

  EXPECT_CALL(left_executor, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(true));

  // Create a table and wrap it in logical tile
  size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
  std::unique_ptr<storage::DataTable> left_table(
      ExecutorTestsUtil::CreateTable(tile_group_size));
  ExecutorTestsUtil::PopulateTable(left_table.get(), tile_group_size * 3, false,
                                   false, false);
  std::unique_ptr<storage::DataTable> right_table(
      ExecutorTestsUtil::CreateTable(tile_group_size));
  ExecutorTestsUtil::PopulateTable(right_table.get(), tile_group_size * 2,
                                   false, false, false);

  std::unique_ptr<executor::LogicalTile> left_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));
  std::unique_ptr<executor::LogicalTile> left_logical_tile2(
      executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));

  std::unique_ptr<executor::LogicalTile> right_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(
          right_table->GetTileGroup(0)));
  std::unique_ptr<executor::LogicalTile> right_logical_tile2(
      executor::LogicalTileFactory::WrapTileGroup(
          right_table->GetTileGroup(1)));

  EXPECT_CALL(left_executor, GetOutput())
      .WillOnce(Return(left_logical_tile1.release()))
      .WillOnce(Return(left_logical_tile2.release()));

  // Run the hash_join_executor
  EXPECT_TRUE(hash_join_executor.Init());

  for (size_t tile_itr = 0; tile_itr < 2; tile_itr++)
    EXPECT_TRUE(hash_join_executor.Execute());

  EXPECT_FALSE(hash_join_executor.Execute());
}

}  // namespace test
}  // namespace peloton
<commit_msg>Finished basic hash join test<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// hash_join_test.cpp
//
// Identification: tests/executor/hash_join_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/hash_join_executor.h"
#include "backend/executor/hash_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/expression_util.h"
#include "backend/planner/hash_join_plan.h"
#include "backend/planner/hash_plan.h"
#include "backend/storage/data_table.h"

#include "mock_executor.h"
#include "executor/executor_tests_util.h"
#include "executor/join_tests_util.h"
#include "harness.h"

using ::testing::NotNull;
using ::testing::Return;

namespace peloton {
namespace test {

// Basic Test
// Single join clause, multiple tiles with same tuples per tile,
// join on key (i.e. there will have at most one tuple for each different join key
TEST(HashJoinTests, BasicTest) {

  expression::AbstractExpression *right_table_attr_1 =
      new expression::TupleValueExpression(1, 1);

  std::vector<std::unique_ptr<const expression::AbstractExpression> > hashkeys;
  hashkeys.emplace_back(right_table_attr_1);

  // Create hash plan node
  planner::HashPlan hash_plan_node(hashkeys);

  // Create the hash hash_join_executor
  executor::HashExecutor hash_executor(&hash_plan_node, nullptr);

  // Create hash join plan node.
  auto projection = JoinTestsUtil::CreateProjection();
  planner::HashJoinPlan hash_join_plan_node(nullptr, projection);

  // Create the hash join hash_join_executor
  executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);

  MockExecutor left_executor, right_executor;
  hash_join_executor.AddChild(&left_executor);
  hash_join_executor.AddChild(&hash_executor);

  hash_executor.AddChild(&right_executor);

  EXPECT_CALL(left_executor, DInit())
      .WillOnce(Return(true));

  EXPECT_CALL(right_executor, DInit())
    .WillOnce(Return(true));

  EXPECT_CALL(left_executor, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  EXPECT_CALL(right_executor, DExecute())
      .WillOnce(Return(true))  // Itr 1
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  // Create a table and wrap it in logical tile
  size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
  std::unique_ptr<storage::DataTable> left_table(
      ExecutorTestsUtil::CreateTable(tile_group_size));
  ExecutorTestsUtil::PopulateTable(left_table.get(), tile_group_size * 3, false,
                                   false, false);
  std::unique_ptr<storage::DataTable> right_table(
      ExecutorTestsUtil::CreateTable(tile_group_size));
  ExecutorTestsUtil::PopulateTable(right_table.get(), tile_group_size * 2,
                                   false, false, false);

  std::unique_ptr<executor::LogicalTile> left_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));
  std::unique_ptr<executor::LogicalTile> left_logical_tile2(
      executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));

  std::unique_ptr<executor::LogicalTile> right_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(
          right_table->GetTileGroup(0)));
  std::unique_ptr<executor::LogicalTile> right_logical_tile2(
      executor::LogicalTileFactory::WrapTileGroup(
          right_table->GetTileGroup(1)));

  EXPECT_CALL(left_executor, GetOutput())
      .WillOnce(Return(left_logical_tile1.release()))
      .WillOnce(Return(left_logical_tile2.release()));

  EXPECT_CALL(right_executor, GetOutput())
      .WillOnce(Return(right_logical_tile1.release()))
      .WillOnce(Return(right_logical_tile2.release()));

  // Run the hash_join_executor
  EXPECT_TRUE(hash_join_executor.Init());

  for (size_t tile_itr = 0; tile_itr < 2; tile_itr++)
    EXPECT_TRUE(hash_join_executor.Execute());

  EXPECT_FALSE(hash_join_executor.Execute());
}

}  // namespace test
}  // namespace peloton
<|endoftext|>


<commit_before>#include "lunar_fiber.hpp"

#include <thread>

volatile int n = 0;

void
func1(void *arg)
{
    printf("func1\n");

    n++;
    while(n != 2); // barrier

    int cnt = 0;
    int s   = 0;
    timespec ts0;
    GETTIME(&ts0);
    for (;;) {
        void *data;
        if (lunar::pop_threadq_fiber(&data) == lunar::STRM_NO_MORE_DATA) {
            s++;
            lunar::select_fiber(nullptr, 0, nullptr, 0, true, 0);
            continue;
        }

        cnt++;
        if (cnt > 50000000) {
            timespec ts1;
            GETTIME(&ts1);
            TIMESPECSUB(&ts1, &ts0);
            printf("%lf [ops/s], select = %lf\n",
                   cnt / (ts1.tv_sec + ts1.tv_nsec * 1e-9),
                   s / (ts1.tv_sec + ts1.tv_nsec * 1e-9));

            cnt = 0;
            GETTIME(&ts0);
        }
    }
}

void
func2(void *arg)
{
    printf("func2\n");

    n++;
    while(n != 2); // barrier

    auto fb = lunar::get_fiber(1);
    printf("fiber = %p\n", fb);

    for (;;) lunar::push_threadq_fast_unsafe_fiber(fb, nullptr);
}

void
thread2()
{
    lunar::init_fiber(2);
    lunar::spawn_fiber(func2);
    lunar::run_fiber();
}

void
thread1()
{
    lunar::init_fiber(1);
    lunar::spawn_fiber(func1);
    lunar::run_fiber();
}

int
main(int argc, char *argv[])
{
    std::thread th1(thread1);
    std::thread th2(thread2);

    th1.join();
    th2.join();

    return 0;
}<commit_msg>minor fix<commit_after>#include "lunar_fiber.hpp"

#include <thread>

volatile int n = 0;

void
func1(void *arg)
{
    n++;
    while(n != 2); // barrier

    int cnt = 0;
    int s   = 0;
    timespec ts0;
    GETTIME(&ts0);
    for (;;) {
        void *data;
        if (lunar::pop_threadq_fiber(&data) == lunar::STRM_NO_MORE_DATA) {
            s++;
            lunar::select_fiber(nullptr, 0, nullptr, 0, true, 0);
            continue;
        }

        cnt++;
        if (cnt > 50000000) {
            timespec ts1;
            GETTIME(&ts1);
            TIMESPECSUB(&ts1, &ts0);
            auto sec = ts1.tv_sec + ts1.tv_nsec * 1e-9;

            printf("%lf [ops/s], select = %lf\n",
                   cnt / sec, s / sec);

            cnt = 0;
            s   = 0;
            GETTIME(&ts0);
        }
    }
}

void
func2(void *arg)
{
    n++;
    while(n != 2); // barrier

    auto fb = lunar::get_fiber(1);
    for (;;) lunar::push_threadq_fast_unsafe_fiber(fb, nullptr);
}

void
thread2()
{
    lunar::init_fiber(2);
    lunar::spawn_fiber(func2);
    lunar::run_fiber();
}

void
thread1()
{
    lunar::init_fiber(1);
    lunar::spawn_fiber(func1);
    lunar::run_fiber();
}

int
main(int argc, char *argv[])
{
    std::thread th1(thread1);
    std::thread th2(thread2);

    th1.join();
    th2.join();

    return 0;
}<|endoftext|>


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

#include "OneMulti.h"

OneMulti::~OneMulti()
{
}

unsigned int
OneMulti::run()
{
    if( disjCoresPreprocessing && !disjointCorePreprocessing() )
        return INCOHERENT;

    if( ub() == lb() )
        return OPTIMUM_FOUND;

    if( wasp::Options::stratification && solver.isWeighted( level() ) )
        return runWeighted();
    return runUnweighted();
}

unsigned int
OneMulti::runUnweighted()
{
    trace_msg( weakconstraints, 1, "Starting algorithm ONE" );
    computeAssumptions();

    initInUnsatCore();

    solver.setComputeUnsatCores( true );
    solver.turnOffSimplifications();
    while( solver.solve( assumptions ) == INCOHERENT )
    {
        if( !foundUnsat() )
            return INCOHERENT;
        assumptions.clear();
        computeAssumptions();
    }

    assert_msg( lb() == ub(), lb() << " != " << ub() );
    return OPTIMUM_FOUND;
}

unsigned int
OneMulti::runWeighted()
{
    trace_msg( weakconstraints, 1, "Starting algorithm ONE" );

    preprocessingWeights();
    changeWeight();
    computeAssumptionsStratified();

    initInUnsatCore();

    solver.setComputeUnsatCores( true );
    solver.turnOffSimplifications();

    while( true )
    {
        if( solver.solve( assumptions ) != INCOHERENT )
        {
            solver.unrollToZero();
            solver.clearConflictStatus();
            if( !changeWeight() )
                break;
        }
        else if( !foundUnsat() )
            return INCOHERENT;

        assumptions.clear();
        computeAssumptionsStratified();
        if( lb() == ub() )
            break;
    }

    assert_msg( lb() == ub(), lb() << " != " << ub() );

    return OPTIMUM_FOUND;
}

bool
OneMulti::processCoreOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    vector< Var >& newVars,
    uint64_t minWeight,
    unsigned int& n )
{
    trace_msg( weakconstraints, 2, "Processing core for algorithm One" );

    bool trivial = false;
    Clause* clause = new Clause();
    unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );
    for( unsigned int i = 0; i < originalSize; i++ )
    {
        OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i );
        if( optLitData.isRemoved() )
            continue;

        Literal lit = optLitData.lit;
        trace_msg( weakconstraints, 3, "Considering literal " << lit << " - weight " << optLitData.weight );
        Var v = lit.getVariable();
        if( visited( v ) )
        {
            trace_msg( weakconstraints, 4, "is in unsat core" );
            literals.push_back( lit.getOppositeLiteral() );
            weights.push_back( 1 );
            optLitData.remove();

            if( solver.isTrue( lit ) )
                trivial = true;

            if( !solver.isFalse( lit ) )
                clause->addLiteral( lit );

            if( optLitData.weight > minWeight )
                solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true );
        }
    }

    n = literals.size();
    for( unsigned int i = 0; i < n - 1; i++ )
    {
        Var auxVar = addAuxVariable();
        solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );
        newVars.push_back( auxVar );
    }

    for( int i = newVars.size() - 1; i >= 1; i-- )
    {
        Clause* c = new Clause();
        c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );
        c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );
        solver.addClauseRuntime( c );
    }

    if( trivial )
    {
        delete clause;
        return true;
    }

    return solver.addClauseRuntime( clause );
}

bool
OneMulti::addAggregateOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    vector< Var >& bounds )
{
    if( literals.size() == 1 )
    {
        trace_msg( weakconstraints, 2, "Literal " << literals[ 0 ] << " is removed from assumptions. Nothing more to do" );
        return true;
    }

    trace_msg( weakconstraints, 2, "Adding aggregate from unsat core" );
    MultiAggregate* multi = new MultiAggregate();
    assert(literals.size() == weights.size());
    for(unsigned int i = 0; i < literals.size(); i++)
        multi->addLiteral(literals[i], weights[i]);

    for(unsigned int i = 0; i < bounds.size(); i++)
        multi->addBound(Literal(bounds[i], POSITIVE),i+1);

    multi->finalizeNoBinaryClauses(solver);
    solver.attachMultiAggregate(*multi);
    solver.addMultiAggregate(multi);
    trace_msg( weakconstraints, 3, "Adding " << *multi );
    return true;
}

bool
OneMulti::processCoreOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    uint64_t minWeight,
    unsigned int& n )
{
    trace_msg( weakconstraints, 2, "Processing core for algorithm One" );

    bool trivial = false;
    Clause* clause = new Clause();
    unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );
    for( unsigned int i = 0; i < originalSize; i++ )
    {
        OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i );
        if( optLitData.isRemoved() )
            continue;

        Literal lit = optLitData.lit;
        trace_msg( weakconstraints, 3, "Considering literal " << lit << " - weight " << optLitData.weight );
        Var v = lit.getVariable();
        if( visited( v ) )
        {
            trace_msg( weakconstraints, 4, "is in unsat core" );
            literals.push_back( lit );
//            weights.push_back( optLitData.weight );
            weights.push_back( 1 );
            optLitData.remove();

            if( solver.isTrue( lit ) )
                trivial = true;

            if( !solver.isFalse( lit ) )
                clause->addLiteral( lit );

            if( optLitData.weight > minWeight )
                solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true );
        }
    }

    n = literals.size();
    vector< Var > newVars;
    for( unsigned int i = 0; i < n - 1; i++ )
    {
        Var auxVar = addAuxVariable();
        literals.push_back( Literal( auxVar, POSITIVE ) );
        weights.push_back( 1 );
        solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );
        newVars.push_back( auxVar );
    }

    for( int i = newVars.size() - 1; i >= 1; i-- )
    {
        Clause* c = new Clause();
        c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );
        c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );
        solver.addClauseRuntime( c );
    }

    if( trivial )
    {
        delete clause;
        return true;
    }

    return solver.addClauseRuntime( clause );
}

bool
OneMulti::addAggregateOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    uint64_t bound )
{
    if( literals.size() == 1 )
    {
        trace_msg( weakconstraints, 2, "Literal " << literals[ 0 ] << " is removed from assumptions. Nothing more to do" );
        return true;
    }

    trace_msg( weakconstraints, 2, "Adding aggregate from unsat core" );
    Var aggrId = addAuxVariable();
    Aggregate* aggregate = createAggregate( aggrId, literals, weights );
    if( !processAndAddAggregate( aggregate, bound ) )
        return false;

    assert( !solver.isTrue( aggrId ) );
    solver.addClauseRuntime( Literal( aggrId, NEGATIVE ) );
    assert( solver.isFalse( aggrId ) );
    return true;
}

bool
OneMulti::foundUnsat()
{
    ++numberOfCalls;

    const Clause* core = solver.getUnsatCore();
    assert( core != NULL );
    const Clause& unsatCore = *( core );

    //The incoherence does not depend on weak constraints
    if( unsatCore.size() == 0 )
        return false;

    solver.clearConflictStatus();
    solver.unrollToZero();

    for( unsigned int i = 0; i < unsatCore.size(); i++ )
        visit( unsatCore[ i ].getVariable() );

    vector< Literal > literals;
    vector< uint64_t > weights;
    vector< Var > newVars;

    unsigned int n = 0;
    uint64_t minWeight = computeMinWeight();

    if( unsatCore.size() <= wasp::Options::multiThreshold )
    {
        if( !processCoreOne( literals, weights, minWeight, n ) || !addAggregateOne( literals, weights, n + 1 ) )
            return false;
    }
    else
    {
        if( !processCoreOne( literals, weights, newVars, minWeight, n ) || !addAggregateOne( literals, weights, newVars ) )
            return false;
    }
    incrementLb( minWeight );
    solver.foundLowerBound( lb() );

    return true;
}
<commit_msg>Fixed bug in one-multi.<commit_after>/*
 *
 *  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#include "OneMulti.h"

OneMulti::~OneMulti()
{
}

unsigned int
OneMulti::run()
{
    if( disjCoresPreprocessing && !disjointCorePreprocessing() )
        return INCOHERENT;

    if( ub() == lb() )
        return OPTIMUM_FOUND;

    if( wasp::Options::stratification && solver.isWeighted( level() ) )
        return runWeighted();
    return runUnweighted();
}

unsigned int
OneMulti::runUnweighted()
{
    trace_msg( weakconstraints, 1, "Starting algorithm ONE" );
    computeAssumptions();

    initInUnsatCore();

    solver.setComputeUnsatCores( true );
    solver.turnOffSimplifications();
    while( solver.solve( assumptions ) == INCOHERENT )
    {
        if( !foundUnsat() )
            return INCOHERENT;
        assumptions.clear();
        computeAssumptions();
    }

    assert_msg( lb() == ub(), lb() << " != " << ub() );
    return OPTIMUM_FOUND;
}

unsigned int
OneMulti::runWeighted()
{
    trace_msg( weakconstraints, 1, "Starting algorithm ONE" );

    preprocessingWeights();
    changeWeight();
    computeAssumptionsStratified();

    initInUnsatCore();

    solver.setComputeUnsatCores( true );
    solver.turnOffSimplifications();

    while( true )
    {
        if( solver.solve( assumptions ) != INCOHERENT )
        {
            solver.unrollToZero();
            solver.clearConflictStatus();
            if( !changeWeight() )
                break;
        }
        else if( !foundUnsat() )
            return INCOHERENT;

        assumptions.clear();
        computeAssumptionsStratified();
        if( lb() == ub() )
            break;
    }

    assert_msg( lb() == ub(), lb() << " != " << ub() );

    return OPTIMUM_FOUND;
}

bool
OneMulti::processCoreOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    vector< Var >& newVars,
    uint64_t minWeight,
    unsigned int& n )
{
    trace_msg( weakconstraints, 2, "Processing core for algorithm One" );

    bool trivial = false;
    Clause* clause = new Clause();
    unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );
    for( unsigned int i = 0; i < originalSize; i++ )
    {
        OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i );
        if( optLitData.isRemoved() )
            continue;

        Literal lit = optLitData.lit;
        trace_msg( weakconstraints, 3, "Considering literal " << lit << " - weight " << optLitData.weight );
        Var v = lit.getVariable();
        if( visited( v ) )
        {
            trace_msg( weakconstraints, 4, "is in unsat core" );
            literals.push_back( lit.getOppositeLiteral() );
            weights.push_back( 1 );
            optLitData.remove();

            if( solver.isTrue( lit ) )
                trivial = true;

            if( !solver.isFalse( lit ) )
                clause->addLiteral( lit );

            if( optLitData.weight > minWeight )
                solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true );
        }
    }

    n = literals.size();
    for( unsigned int i = 0; i < n - 1; i++ )
    {
        Var auxVar = addAuxVariable();
        solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );
        newVars.push_back( auxVar );
    }

    for( int i = newVars.size() - 1; i >= 1; i-- )
    {
        Clause* c = new Clause();
        c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );
        c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );
        solver.addClauseRuntime( c );
    }

    if( trivial )
    {
        delete clause;
        return true;
    }

    return solver.addClauseRuntime( clause );
}

bool
OneMulti::addAggregateOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    vector< Var >& bounds )
{
    if( literals.size() == 1 )
    {
        trace_msg( weakconstraints, 2, "Literal " << literals[ 0 ] << " is removed from assumptions. Nothing more to do" );
        return true;
    }

    trace_msg( weakconstraints, 2, "Adding aggregate from unsat core" );
    MultiAggregate* multi = new MultiAggregate();
    assert(literals.size() == weights.size());
    for(unsigned int i = 0; i < literals.size(); i++)
        multi->addLiteral(literals[i], weights[i]);

    for(unsigned int i = 0; i < bounds.size(); i++)
        multi->addBound(Literal(bounds[i], POSITIVE),i+1);

    multi->finalizeNoBinaryClauses(solver);
    solver.attachMultiAggregate(*multi);
    solver.addMultiAggregate(multi);
    trace_msg( weakconstraints, 3, "Adding " << *multi );
    return true;
}

bool
OneMulti::processCoreOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    uint64_t minWeight,
    unsigned int& n )
{
    trace_msg( weakconstraints, 2, "Processing core for algorithm One" );

    bool trivial = false;
    Clause* clause = new Clause();
    unsigned int originalSize = solver.numberOfOptimizationLiterals( level() );
    for( unsigned int i = 0; i < originalSize; i++ )
    {
        OptimizationLiteralData& optLitData = solver.getOptimizationLiteral( level(), i );
        if( optLitData.isRemoved() )
            continue;

        Literal lit = optLitData.lit;
        trace_msg( weakconstraints, 3, "Considering literal " << lit << " - weight " << optLitData.weight );
        Var v = lit.getVariable();
        if( visited( v ) )
        {
            trace_msg( weakconstraints, 4, "is in unsat core" );
            literals.push_back( lit );
//            weights.push_back( optLitData.weight );
            weights.push_back( 1 );
            optLitData.remove();

            if( solver.isTrue( lit ) )
                trivial = true;

            if( !solver.isFalse( lit ) )
                clause->addLiteral( lit );

            if( optLitData.weight > minWeight )
                solver.addOptimizationLiteral( lit, optLitData.weight - minWeight, level(), true );
        }
    }

    n = literals.size();
    vector< Var > newVars;
    for( unsigned int i = 0; i < n - 1; i++ )
    {
        Var auxVar = addAuxVariable();
        literals.push_back( Literal( auxVar, POSITIVE ) );
        weights.push_back( 1 );
        solver.addOptimizationLiteral( Literal( auxVar, NEGATIVE ), minWeight, level(), true );
        newVars.push_back( auxVar );
    }

    for( int i = newVars.size() - 1; i >= 1; i-- )
    {
        Clause* c = new Clause();
        c->addLiteral( Literal( newVars[ i ], NEGATIVE ) );
        c->addLiteral( Literal( newVars[ i - 1 ], POSITIVE ) );
        solver.addClauseRuntime( c );
    }

    if( trivial )
    {
        delete clause;
        return true;
    }

    return solver.addClauseRuntime( clause );
}

bool
OneMulti::addAggregateOne(
    vector< Literal >& literals,
    vector< uint64_t >& weights,
    uint64_t bound )
{
    if( literals.size() == 1 )
    {
        trace_msg( weakconstraints, 2, "Literal " << literals[ 0 ] << " is removed from assumptions. Nothing more to do" );
        return true;
    }

    trace_msg( weakconstraints, 2, "Adding aggregate from unsat core" );
    Var aggrId = addAuxVariable();
    Aggregate* aggregate = createAggregate( aggrId, literals, weights );
    if( !processAndAddAggregate( aggregate, bound ) )
        return false;

    assert( !solver.isTrue( aggrId ) );
    solver.addClauseRuntime( Literal( aggrId, NEGATIVE ) );
    assert( solver.isFalse( aggrId ) );
    return true;
}

bool
OneMulti::foundUnsat()
{
    ++numberOfCalls;

    const Clause* core = solver.getUnsatCore();
    assert( core != NULL );
    const Clause& unsatCore = *( core );

    //The incoherence does not depend on weak constraints
    if( unsatCore.size() == 0 )
        return false;

    solver.clearConflictStatus();
    solver.unrollToZero();

    bool found = false;
    for( unsigned int i = 0; i < unsatCore.size(); i++ ) {
        if( solver.isFalse( unsatCore[ i ] ) && solver.getDecisionLevel( unsatCore[ i ] ) == 0 )
        {
            visit( unsatCore[ i ].getVariable() );
            found = true;
        }
    }

    if( !found )
    {
        for( unsigned int i = 0; i < unsatCore.size(); i++ )
            visit( unsatCore[ i ].getVariable() );
    }

    vector< Literal > literals;
    vector< uint64_t > weights;
    vector< Var > newVars;

    unsigned int n = 0;
    uint64_t minWeight = computeMinWeight();

    if( unsatCore.size() <= wasp::Options::multiThreshold )
    {
        if( !processCoreOne( literals, weights, minWeight, n ) || !addAggregateOne( literals, weights, n + 1 ) )
            return false;
    }
    else
    {
        if( !processCoreOne( literals, weights, newVars, minWeight, n ) || !addAggregateOne( literals, weights, newVars ) )
            return false;
    }
    incrementLb( minWeight );
    solver.foundLowerBound( lb() );

    return true;
}
<|endoftext|>


<commit_before><commit_msg>Fix merge error from r1055<commit_after><|endoftext|>