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

#include "content/shell/browser/shell.h"

#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/events/event.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/screen.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/test/desktop_test_views_delegate.h"
#include "ui/views/view.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

#if defined(OS_CHROMEOS)
#include "chromeos/dbus/dbus_thread_manager.h"
#include "content/shell/browser/minimal_shell.h"
#include "ui/aura/test/test_screen.h"
#endif

#if defined(OS_WIN)
#include <fcntl.h>
#include <io.h>
#endif

namespace content {

namespace {
// ViewDelegate implementation for aura content shell
class ShellViewsDelegateAura : public views::DesktopTestViewsDelegate {
 public:
  ShellViewsDelegateAura() : use_transparent_windows_(false) {
  }

  virtual ~ShellViewsDelegateAura() {
  }

  void SetUseTransparentWindows(bool transparent) {
    use_transparent_windows_ = transparent;
  }

  // Overridden from views::TestViewsDelegate:
  virtual bool UseTransparentWindows() const OVERRIDE {
    return use_transparent_windows_;
  }

 private:
  bool use_transparent_windows_;

  DISALLOW_COPY_AND_ASSIGN(ShellViewsDelegateAura);
};

// Maintain the UI controls and web view for content shell
class ShellWindowDelegateView : public views::WidgetDelegateView,
                                public views::TextfieldController,
                                public views::ButtonListener {
 public:
  enum UIControl {
    BACK_BUTTON,
    FORWARD_BUTTON,
    STOP_BUTTON
  };

  ShellWindowDelegateView(Shell* shell)
    : shell_(shell),
      toolbar_view_(new View),
      contents_view_(new View) {
  }
  virtual ~ShellWindowDelegateView() {}

  // Update the state of UI controls
  void SetAddressBarURL(const GURL& url) {
    url_entry_->SetText(ASCIIToUTF16(url.spec()));
  }
  void SetWebContents(WebContents* web_contents) {
    contents_view_->SetLayoutManager(new views::FillLayout());
    web_view_ = new views::WebView(web_contents->GetBrowserContext());
    web_view_->SetWebContents(web_contents);
    web_contents->GetView()->Focus();
    contents_view_->AddChildView(web_view_);
    Layout();
  }
  void SetWindowTitle(const string16& title) { title_ = title; }
  void EnableUIControl(UIControl control, bool is_enabled) {
    if (control == BACK_BUTTON) {
      back_button_->SetState(is_enabled ? views::CustomButton::STATE_NORMAL
          : views::CustomButton::STATE_DISABLED);
    } else if (control == FORWARD_BUTTON) {
      forward_button_->SetState(is_enabled ? views::CustomButton::STATE_NORMAL
          : views::CustomButton::STATE_DISABLED);
    } else if (control == STOP_BUTTON) {
      stop_button_->SetState(is_enabled ? views::CustomButton::STATE_NORMAL
          : views::CustomButton::STATE_DISABLED);
    }
  }

 private:
  // Initialize the UI control contained in shell window
  void InitShellWindow() {
    set_background(views::Background::CreateStandardPanelBackground());

    views::GridLayout* layout = new views::GridLayout(this);
    SetLayoutManager(layout);

    views::ColumnSet* column_set = layout->AddColumnSet(0);
    column_set->AddPaddingColumn(0, 2);
    column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                          views::GridLayout::USE_PREF, 0, 0);
    column_set->AddPaddingColumn(0, 2);

    layout->AddPaddingRow(0, 2);

    // Add toolbar buttons and URL text field
    {
      layout->StartRow(0, 0);
      views::GridLayout* toolbar_layout = new views::GridLayout(toolbar_view_);
      toolbar_view_->SetLayoutManager(toolbar_layout);

      views::ColumnSet* toolbar_column_set =
          toolbar_layout->AddColumnSet(0);
      // Back button
      back_button_ = new views::LabelButton(this, ASCIIToUTF16("Back"));
      back_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size back_button_size = back_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    back_button_size.width(),
                                    back_button_size.width() / 2);
      // Forward button
      forward_button_ = new views::LabelButton(this, ASCIIToUTF16("Forward"));
      forward_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size forward_button_size = forward_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    forward_button_size.width(),
                                    forward_button_size.width() / 2);
      // Refresh button
      refresh_button_ = new views::LabelButton(this, ASCIIToUTF16("Refresh"));
      refresh_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size refresh_button_size = refresh_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    refresh_button_size.width(),
                                    refresh_button_size.width() / 2);
      // Stop button
      stop_button_ = new views::LabelButton(this, ASCIIToUTF16("Stop"));
      stop_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size stop_button_size = stop_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    stop_button_size.width(),
                                    stop_button_size.width() / 2);
      toolbar_column_set->AddPaddingColumn(0, 2);
      // URL entry
      url_entry_ = new views::Textfield();
      url_entry_->SetController(this);
      toolbar_column_set->AddColumn(views::GridLayout::FILL,
                                    views::GridLayout::FILL, 1,
                                    views::GridLayout::USE_PREF, 0, 0);

      // Fill up the first row
      toolbar_layout->StartRow(0, 0);
      toolbar_layout->AddView(back_button_);
      toolbar_layout->AddView(forward_button_);
      toolbar_layout->AddView(refresh_button_);
      toolbar_layout->AddView(stop_button_);
      toolbar_layout->AddView(url_entry_);

      layout->AddView(toolbar_view_);
    }

    layout->AddPaddingRow(0, 5);

    // Add web contents view as the second row
    {
      layout->StartRow(1, 0);
      layout->AddView(contents_view_);
    }

    layout->AddPaddingRow(0, 5);
  }
  // Overridden from TextfieldController
  virtual void ContentsChanged(views::Textfield* sender,
                               const string16& new_contents) OVERRIDE {
  }
  virtual bool HandleKeyEvent(views::Textfield* sender,
                              const ui::KeyEvent& key_event) OVERRIDE {
   if (sender == url_entry_ && key_event.key_code() == ui::VKEY_RETURN) {
     std::string text = UTF16ToUTF8(url_entry_->text());
     GURL url(text);
     if (!url.has_scheme()) {
       url = GURL(std::string("http://") + std::string(text));
       url_entry_->SetText(ASCIIToUTF16(url.spec()));
     }
     shell_->LoadURL(url);
     return true;
   }
   return false;
  }

  // Overridden from ButtonListener
  virtual void ButtonPressed(views::Button* sender,
                             const ui::Event& event) OVERRIDE {
    if (sender == back_button_)
      shell_->GoBackOrForward(-1);
    else if (sender == forward_button_)
      shell_->GoBackOrForward(1);
    else if (sender == refresh_button_)
      shell_->Reload();
    else if (sender == stop_button_)
      shell_->Stop();
  }

  // Overridden from WidgetDelegateView
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return true; }
  virtual string16 GetWindowTitle() const OVERRIDE {
    return title_;
  }
  virtual void WindowClosing() OVERRIDE {
    if (shell_) {
      delete shell_;
      shell_ = NULL;
    }
  }
  virtual View* GetContentsView() OVERRIDE { return this; }

  // Overridden from View
  virtual void ViewHierarchyChanged(
      const ViewHierarchyChangedDetails& details) OVERRIDE {
    if (details.is_add && details.child == this) {
      InitShellWindow();
    }
  }

 private:
  // Hold a reference of Shell for deleting it when the window is closing
  Shell* shell_;

  // Window title
  string16 title_;

  // Toolbar view contains forward/backward/reload button and URL entry
  View* toolbar_view_;
  views::LabelButton* back_button_;
  views::LabelButton* forward_button_;
  views::LabelButton* refresh_button_;
  views::LabelButton* stop_button_;
  views::Textfield* url_entry_;

  // Contents view contains the web contents view
  View* contents_view_;
  views::WebView* web_view_;

  DISALLOW_COPY_AND_ASSIGN(ShellWindowDelegateView);
};

}  // namespace

#if defined(OS_CHROMEOS)
MinimalShell* Shell::minimal_shell_ = NULL;
#endif
views::ViewsDelegate* Shell::views_delegate_ = NULL;

// static
void Shell::PlatformInitialize(const gfx::Size& default_window_size) {
#if defined(OS_WIN)
  _setmode(_fileno(stdout), _O_BINARY);
  _setmode(_fileno(stderr), _O_BINARY);
#endif
#if defined(OS_CHROMEOS)
  chromeos::DBusThreadManager::Initialize();
  gfx::Screen::SetScreenInstance(
      gfx::SCREEN_TYPE_NATIVE, aura::TestScreen::Create());
  minimal_shell_ = new content::MinimalShell(default_window_size);
#else
  gfx::Screen::SetScreenInstance(
      gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
  views_delegate_ = new ShellViewsDelegateAura();
}

void Shell::PlatformExit() {
  std::vector<Shell*> windows = windows_;
  for (std::vector<Shell*>::iterator it = windows.begin();
       it != windows.end(); ++it) {
    (*it)->window_widget_->Close();
  }
#if defined(OS_CHROMEOS)
  if (minimal_shell_)
    delete minimal_shell_;
#endif
  if (views_delegate_)
    delete views_delegate_;
#if defined(OS_CHROMEOS)
  chromeos::DBusThreadManager::Shutdown();
#endif
  aura::Env::DeleteInstance();
}

void Shell::PlatformCleanUp() {
}

void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  if (control == BACK_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::BACK_BUTTON,
        is_enabled);
  } else if (control == FORWARD_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::FORWARD_BUTTON,
        is_enabled);
  } else if (control == STOP_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::STOP_BUTTON,
        is_enabled);
  }
}

void Shell::PlatformSetAddressBarURL(const GURL& url) {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetAddressBarURL(url);
}

void Shell::PlatformSetIsLoading(bool loading) {
}

void Shell::PlatformCreateWindow(int width, int height) {
#if defined(OS_CHROMEOS)
  window_widget_ =
      views::Widget::CreateWindowWithContextAndBounds(
          new ShellWindowDelegateView(this),
          minimal_shell_->GetDefaultParent(NULL, NULL, gfx::Rect()),
          gfx::Rect(0, 0, width, height));
#else
  window_widget_ =
      views::Widget::CreateWindowWithBounds(new ShellWindowDelegateView(this),
               gfx::Rect(0, 0, width, height));
#endif

  window_ = window_widget_->GetNativeWindow();
  // Call ShowRootWindow on RootWindow created by MinimalShell without
  // which XWindow owned by RootWindow doesn't get mapped.
  window_->GetRootWindow()->ShowRootWindow();
  window_widget_->Show();
}

void Shell::PlatformSetContents() {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetWebContents(web_contents_.get());
}

void Shell::PlatformResizeSubViews() {
}

void Shell::Close() {
  window_widget_->CloseNow();
}

void Shell::PlatformSetTitle(const string16& title) {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetWindowTitle(title);
  window_widget_->UpdateWindowTitle();
}

}  // namespace content
<commit_msg>Attempt headless on win aura content_shell<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/shell/browser/shell.h"

#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/events/event.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/screen.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/test/desktop_test_views_delegate.h"
#include "ui/views/view.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

#if defined(OS_CHROMEOS)
#include "chromeos/dbus/dbus_thread_manager.h"
#include "content/shell/browser/minimal_shell.h"
#include "ui/aura/test/test_screen.h"
#endif

#if defined(OS_WIN)
#include <fcntl.h>
#include <io.h>
#endif

namespace content {

namespace {
// ViewDelegate implementation for aura content shell
class ShellViewsDelegateAura : public views::DesktopTestViewsDelegate {
 public:
  ShellViewsDelegateAura() : use_transparent_windows_(false) {
  }

  virtual ~ShellViewsDelegateAura() {
  }

  void SetUseTransparentWindows(bool transparent) {
    use_transparent_windows_ = transparent;
  }

  // Overridden from views::TestViewsDelegate:
  virtual bool UseTransparentWindows() const OVERRIDE {
    return use_transparent_windows_;
  }

 private:
  bool use_transparent_windows_;

  DISALLOW_COPY_AND_ASSIGN(ShellViewsDelegateAura);
};

// Maintain the UI controls and web view for content shell
class ShellWindowDelegateView : public views::WidgetDelegateView,
                                public views::TextfieldController,
                                public views::ButtonListener {
 public:
  enum UIControl {
    BACK_BUTTON,
    FORWARD_BUTTON,
    STOP_BUTTON
  };

  ShellWindowDelegateView(Shell* shell)
    : shell_(shell),
      toolbar_view_(new View),
      contents_view_(new View) {
  }
  virtual ~ShellWindowDelegateView() {}

  // Update the state of UI controls
  void SetAddressBarURL(const GURL& url) {
    url_entry_->SetText(ASCIIToUTF16(url.spec()));
  }
  void SetWebContents(WebContents* web_contents) {
    contents_view_->SetLayoutManager(new views::FillLayout());
    web_view_ = new views::WebView(web_contents->GetBrowserContext());
    web_view_->SetWebContents(web_contents);
    web_contents->GetView()->Focus();
    contents_view_->AddChildView(web_view_);
    Layout();
  }
  void SetWindowTitle(const string16& title) { title_ = title; }
  void EnableUIControl(UIControl control, bool is_enabled) {
    if (control == BACK_BUTTON) {
      back_button_->SetState(is_enabled ? views::CustomButton::STATE_NORMAL
          : views::CustomButton::STATE_DISABLED);
    } else if (control == FORWARD_BUTTON) {
      forward_button_->SetState(is_enabled ? views::CustomButton::STATE_NORMAL
          : views::CustomButton::STATE_DISABLED);
    } else if (control == STOP_BUTTON) {
      stop_button_->SetState(is_enabled ? views::CustomButton::STATE_NORMAL
          : views::CustomButton::STATE_DISABLED);
    }
  }

 private:
  // Initialize the UI control contained in shell window
  void InitShellWindow() {
    set_background(views::Background::CreateStandardPanelBackground());

    views::GridLayout* layout = new views::GridLayout(this);
    SetLayoutManager(layout);

    views::ColumnSet* column_set = layout->AddColumnSet(0);
    column_set->AddPaddingColumn(0, 2);
    column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                          views::GridLayout::USE_PREF, 0, 0);
    column_set->AddPaddingColumn(0, 2);

    layout->AddPaddingRow(0, 2);

    // Add toolbar buttons and URL text field
    {
      layout->StartRow(0, 0);
      views::GridLayout* toolbar_layout = new views::GridLayout(toolbar_view_);
      toolbar_view_->SetLayoutManager(toolbar_layout);

      views::ColumnSet* toolbar_column_set =
          toolbar_layout->AddColumnSet(0);
      // Back button
      back_button_ = new views::LabelButton(this, ASCIIToUTF16("Back"));
      back_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size back_button_size = back_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    back_button_size.width(),
                                    back_button_size.width() / 2);
      // Forward button
      forward_button_ = new views::LabelButton(this, ASCIIToUTF16("Forward"));
      forward_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size forward_button_size = forward_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    forward_button_size.width(),
                                    forward_button_size.width() / 2);
      // Refresh button
      refresh_button_ = new views::LabelButton(this, ASCIIToUTF16("Refresh"));
      refresh_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size refresh_button_size = refresh_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    refresh_button_size.width(),
                                    refresh_button_size.width() / 2);
      // Stop button
      stop_button_ = new views::LabelButton(this, ASCIIToUTF16("Stop"));
      stop_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
      gfx::Size stop_button_size = stop_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(views::GridLayout::CENTER,
                                    views::GridLayout::CENTER, 0,
                                    views::GridLayout::FIXED,
                                    stop_button_size.width(),
                                    stop_button_size.width() / 2);
      toolbar_column_set->AddPaddingColumn(0, 2);
      // URL entry
      url_entry_ = new views::Textfield();
      url_entry_->SetController(this);
      toolbar_column_set->AddColumn(views::GridLayout::FILL,
                                    views::GridLayout::FILL, 1,
                                    views::GridLayout::USE_PREF, 0, 0);

      // Fill up the first row
      toolbar_layout->StartRow(0, 0);
      toolbar_layout->AddView(back_button_);
      toolbar_layout->AddView(forward_button_);
      toolbar_layout->AddView(refresh_button_);
      toolbar_layout->AddView(stop_button_);
      toolbar_layout->AddView(url_entry_);

      layout->AddView(toolbar_view_);
    }

    layout->AddPaddingRow(0, 5);

    // Add web contents view as the second row
    {
      layout->StartRow(1, 0);
      layout->AddView(contents_view_);
    }

    layout->AddPaddingRow(0, 5);
  }
  // Overridden from TextfieldController
  virtual void ContentsChanged(views::Textfield* sender,
                               const string16& new_contents) OVERRIDE {
  }
  virtual bool HandleKeyEvent(views::Textfield* sender,
                              const ui::KeyEvent& key_event) OVERRIDE {
   if (sender == url_entry_ && key_event.key_code() == ui::VKEY_RETURN) {
     std::string text = UTF16ToUTF8(url_entry_->text());
     GURL url(text);
     if (!url.has_scheme()) {
       url = GURL(std::string("http://") + std::string(text));
       url_entry_->SetText(ASCIIToUTF16(url.spec()));
     }
     shell_->LoadURL(url);
     return true;
   }
   return false;
  }

  // Overridden from ButtonListener
  virtual void ButtonPressed(views::Button* sender,
                             const ui::Event& event) OVERRIDE {
    if (sender == back_button_)
      shell_->GoBackOrForward(-1);
    else if (sender == forward_button_)
      shell_->GoBackOrForward(1);
    else if (sender == refresh_button_)
      shell_->Reload();
    else if (sender == stop_button_)
      shell_->Stop();
  }

  // Overridden from WidgetDelegateView
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return true; }
  virtual string16 GetWindowTitle() const OVERRIDE {
    return title_;
  }
  virtual void WindowClosing() OVERRIDE {
    if (shell_) {
      delete shell_;
      shell_ = NULL;
    }
  }
  virtual View* GetContentsView() OVERRIDE { return this; }

  // Overridden from View
  virtual void ViewHierarchyChanged(
      const ViewHierarchyChangedDetails& details) OVERRIDE {
    if (details.is_add && details.child == this) {
      InitShellWindow();
    }
  }

 private:
  // Hold a reference of Shell for deleting it when the window is closing
  Shell* shell_;

  // Window title
  string16 title_;

  // Toolbar view contains forward/backward/reload button and URL entry
  View* toolbar_view_;
  views::LabelButton* back_button_;
  views::LabelButton* forward_button_;
  views::LabelButton* refresh_button_;
  views::LabelButton* stop_button_;
  views::Textfield* url_entry_;

  // Contents view contains the web contents view
  View* contents_view_;
  views::WebView* web_view_;

  DISALLOW_COPY_AND_ASSIGN(ShellWindowDelegateView);
};

}  // namespace

#if defined(OS_CHROMEOS)
MinimalShell* Shell::minimal_shell_ = NULL;
#endif
views::ViewsDelegate* Shell::views_delegate_ = NULL;

// static
void Shell::PlatformInitialize(const gfx::Size& default_window_size) {
#if defined(OS_WIN)
  _setmode(_fileno(stdout), _O_BINARY);
  _setmode(_fileno(stderr), _O_BINARY);
#endif
#if defined(OS_CHROMEOS)
  chromeos::DBusThreadManager::Initialize();
  gfx::Screen::SetScreenInstance(
      gfx::SCREEN_TYPE_NATIVE, aura::TestScreen::Create());
  minimal_shell_ = new content::MinimalShell(default_window_size);
#else
  gfx::Screen::SetScreenInstance(
      gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
  views_delegate_ = new ShellViewsDelegateAura();
}

void Shell::PlatformExit() {
  std::vector<Shell*> windows = windows_;
  for (std::vector<Shell*>::iterator it = windows.begin();
       it != windows.end(); ++it) {
    if (!(*it)->headless_)
      (*it)->window_widget_->Close();
  }
#if defined(OS_CHROMEOS)
  if (minimal_shell_)
    delete minimal_shell_;
#endif
  if (views_delegate_)
    delete views_delegate_;
#if defined(OS_CHROMEOS)
  chromeos::DBusThreadManager::Shutdown();
#endif
  aura::Env::DeleteInstance();
}

void Shell::PlatformCleanUp() {
}

void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
  if (headless_)
    return;
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  if (control == BACK_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::BACK_BUTTON,
        is_enabled);
  } else if (control == FORWARD_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::FORWARD_BUTTON,
        is_enabled);
  } else if (control == STOP_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::STOP_BUTTON,
        is_enabled);
  }
}

void Shell::PlatformSetAddressBarURL(const GURL& url) {
  if (headless_)
    return;
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetAddressBarURL(url);
}

void Shell::PlatformSetIsLoading(bool loading) {
}

void Shell::PlatformCreateWindow(int width, int height) {
  if (headless_)
    return;
#if defined(OS_CHROMEOS)
  window_widget_ =
      views::Widget::CreateWindowWithContextAndBounds(
          new ShellWindowDelegateView(this),
          minimal_shell_->GetDefaultParent(NULL, NULL, gfx::Rect()),
          gfx::Rect(0, 0, width, height));
#else
  window_widget_ =
      views::Widget::CreateWindowWithBounds(new ShellWindowDelegateView(this),
               gfx::Rect(0, 0, width, height));
#endif

  window_ = window_widget_->GetNativeWindow();
  // Call ShowRootWindow on RootWindow created by MinimalShell without
  // which XWindow owned by RootWindow doesn't get mapped.
  window_->GetRootWindow()->ShowRootWindow();
  window_widget_->Show();
}

void Shell::PlatformSetContents() {
  if (headless_)
    return;
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetWebContents(web_contents_.get());
}

void Shell::PlatformResizeSubViews() {
}

void Shell::Close() {
  if (headless_)
    return;
  window_widget_->CloseNow();
}

void Shell::PlatformSetTitle(const string16& title) {
  if (headless_)
    return;
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetWindowTitle(title);
  window_widget_->UpdateWindowTitle();
}

}  // namespace content
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNodeNumber.cpp,v $
//   $Revision: 1.22 $
//   $Name:  $
//   $Author: ssahle $
//   $Date: 2007/08/15 15:02:03 $
// End CVS Header

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

#include "copasi.h"
#include "CEvaluationNode.h"

#include "sbml/math/ASTNode.h"

#include <sstream>

CEvaluationNodeNumber::CEvaluationNodeNumber():
    CEvaluationNode(CEvaluationNode::INVALID, "")
{mPrecedence = PRECEDENCE_NUMBER;}

CEvaluationNodeNumber::CEvaluationNodeNumber(const SubType & subType,
    const Data & data):
    CEvaluationNode((Type) (CEvaluationNode::NUMBER | subType), data)
{
  char * end;
  const char * str = mData.c_str();

  switch (subType)
    {
    case DOUBLE:
    case INTEGER:
    case ENOTATION:
      mValue = strtod(str, NULL);
      break;

    case RATIONALE:
      str++; // Skip the '('
      mValue = strtod(str, &end);
      end++; // Skip the '/'
      mValue /= strtod(end, NULL);
      break;

    case INVALID:
      fatalError();
      break;
    }

  mPrecedence = PRECEDENCE_NUMBER;
}

CEvaluationNodeNumber::CEvaluationNodeNumber(const CEvaluationNodeNumber & src):
    CEvaluationNode(src)
{}

CEvaluationNodeNumber::~CEvaluationNodeNumber() {}

#ifdef WIN32
// warning C4056: overflow in floating-point constant arithmetic
// warning C4756: overflow in constant arithmetic
# pragma warning (disable: 4056 4756)
#endif

CEvaluationNode* CEvaluationNodeNumber::createNodeFromASTTree(const ASTNode& node)
{
  ASTNodeType_t type = node.getType();
  std::stringstream ss;
  SubType subType;
  std::string data = "";
  CEvaluationNode* pNode = NULL;
  switch (type)
    {
    case AST_INTEGER:
      subType = INTEGER;
      ss << node.getInteger();
      data = ss.str();

      //if (node.getInteger() < 0)
      //  data = "(" + data + ")";

      pNode = new CEvaluationNodeNumber(subType, data);
      break;
    case AST_REAL:
      subType = DOUBLE;
      if (node.getReal() == (2*DBL_MAX))
        {
          pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::_INFINITY, "INFINITY");
        }
      else if (node.getReal() == (-2*DBL_MAX))
        {
          pNode = new CEvaluationNodeOperator(CEvaluationNodeOperator::MINUS, "-");
          pNode->addChild(new CEvaluationNodeConstant(CEvaluationNodeConstant::_INFINITY, "INFINITY"));
        }
      else if (isnan(node.getReal()))
        {
          pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::_NaN, "NAN");
        }
      else
        {
          ss << node.getReal();
          data = ss.str();

          //if (node.getReal() < 0)
          //  data = "(" + data + ")";

          pNode = new CEvaluationNodeNumber(subType, data);
        }
      break;
    case AST_REAL_E:
      subType = ENOTATION;
      ss << node.getReal();
      data = ss.str();

      //if (node.getReal() < 0)
      //  data = "(" + data + ")";

      pNode = new CEvaluationNodeNumber(subType, data);
      break;
    case AST_RATIONAL:
      subType = RATIONALE;
      ss << "(" << node.getNumerator() << "/" << node.getDenominator() << ")";
      data = ss.str();
      pNode = new CEvaluationNodeNumber(subType, data);
      break;
    default:
      subType = INVALID;
      break;
    }
  return pNode;
}

#ifdef WIN32
# pragma warning (default: 4056 4756)
#endif

ASTNode* CEvaluationNodeNumber::toAST() const
  {
    SubType subType = (SubType)CEvaluationNode::subType(this->getType());
    ASTNode* node = new ASTNode();
    double num1;
    double num2;
    char* end;
    const char * str = mData.c_str();

    switch (subType)
      {
      case DOUBLE:
        node->setType(AST_REAL);
        node->setValue(this->value());
        break;
      case INTEGER:
        node->setType(AST_INTEGER);
        node->setValue((long)this->value());
        break;
      case ENOTATION:
        node->setType(AST_REAL_E);
        num2 = floor(log10(this->value()));
        num1 = pow(10, log10(this->value()) - num2);
        node->setValue(num1, (long)num2);
        break;
      case RATIONALE:
        node->setType(AST_RATIONAL);
        str++; // Skip the '('
        num1 = strtod(str, &end);
        end++; // Skip the '/'
        num2 = strtod(end, NULL);
        node->setValue((long)num1, (long)num2);
        break;
      case INVALID:
        break;
      }
    return node;
  }

#include "utilities/copasimathml.h"

void CEvaluationNodeNumber::writeMathML(std::ostream & out,
                                        const std::vector<std::vector<std::string> > & /* env */,
                                        bool /* expand */,
                                        unsigned C_INT32 l) const
  {
    out << SPC(l) << "<mn>" << mData << "</mn>" << std::endl;
    //or use mValue instead?
  }
<commit_msg>Fixed ambiguous pow function.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNodeNumber.cpp,v $
//   $Revision: 1.23 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2007/09/19 14:08:56 $
// End CVS Header

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

#include "copasi.h"
#include "CEvaluationNode.h"

#include "sbml/math/ASTNode.h"

#include <sstream>

CEvaluationNodeNumber::CEvaluationNodeNumber():
    CEvaluationNode(CEvaluationNode::INVALID, "")
{mPrecedence = PRECEDENCE_NUMBER;}

CEvaluationNodeNumber::CEvaluationNodeNumber(const SubType & subType,
    const Data & data):
    CEvaluationNode((Type) (CEvaluationNode::NUMBER | subType), data)
{
  char * end;
  const char * str = mData.c_str();

  switch (subType)
    {
    case DOUBLE:
    case INTEGER:
    case ENOTATION:
      mValue = strtod(str, NULL);
      break;

    case RATIONALE:
      str++; // Skip the '('
      mValue = strtod(str, &end);
      end++; // Skip the '/'
      mValue /= strtod(end, NULL);
      break;

    case INVALID:
      fatalError();
      break;
    }

  mPrecedence = PRECEDENCE_NUMBER;
}

CEvaluationNodeNumber::CEvaluationNodeNumber(const CEvaluationNodeNumber & src):
    CEvaluationNode(src)
{}

CEvaluationNodeNumber::~CEvaluationNodeNumber() {}

#ifdef WIN32
// warning C4056: overflow in floating-point constant arithmetic
// warning C4756: overflow in constant arithmetic
# pragma warning (disable: 4056 4756)
#endif

CEvaluationNode* CEvaluationNodeNumber::createNodeFromASTTree(const ASTNode& node)
{
  ASTNodeType_t type = node.getType();
  std::stringstream ss;
  SubType subType;
  std::string data = "";
  CEvaluationNode* pNode = NULL;
  switch (type)
    {
    case AST_INTEGER:
      subType = INTEGER;
      ss << node.getInteger();
      data = ss.str();

      //if (node.getInteger() < 0)
      //  data = "(" + data + ")";

      pNode = new CEvaluationNodeNumber(subType, data);
      break;
    case AST_REAL:
      subType = DOUBLE;
      if (node.getReal() == (2*DBL_MAX))
        {
          pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::_INFINITY, "INFINITY");
        }
      else if (node.getReal() == (-2*DBL_MAX))
        {
          pNode = new CEvaluationNodeOperator(CEvaluationNodeOperator::MINUS, "-");
          pNode->addChild(new CEvaluationNodeConstant(CEvaluationNodeConstant::_INFINITY, "INFINITY"));
        }
      else if (isnan(node.getReal()))
        {
          pNode = new CEvaluationNodeConstant(CEvaluationNodeConstant::_NaN, "NAN");
        }
      else
        {
          ss << node.getReal();
          data = ss.str();

          //if (node.getReal() < 0)
          //  data = "(" + data + ")";

          pNode = new CEvaluationNodeNumber(subType, data);
        }
      break;
    case AST_REAL_E:
      subType = ENOTATION;
      ss << node.getReal();
      data = ss.str();

      //if (node.getReal() < 0)
      //  data = "(" + data + ")";

      pNode = new CEvaluationNodeNumber(subType, data);
      break;
    case AST_RATIONAL:
      subType = RATIONALE;
      ss << "(" << node.getNumerator() << "/" << node.getDenominator() << ")";
      data = ss.str();
      pNode = new CEvaluationNodeNumber(subType, data);
      break;
    default:
      subType = INVALID;
      break;
    }
  return pNode;
}

#ifdef WIN32
# pragma warning (default: 4056 4756)
#endif

ASTNode* CEvaluationNodeNumber::toAST() const
  {
    SubType subType = (SubType)CEvaluationNode::subType(this->getType());
    ASTNode* node = new ASTNode();
    double num1;
    double num2;
    char* end;
    const char * str = mData.c_str();

    switch (subType)
      {
      case DOUBLE:
        node->setType(AST_REAL);
        node->setValue(this->value());
        break;
      case INTEGER:
        node->setType(AST_INTEGER);
        node->setValue((long)this->value());
        break;
      case ENOTATION:
        node->setType(AST_REAL_E);
        num2 = floor(log10(this->value()));
        num1 = pow(10.0, log10(this->value()) - num2);
        node->setValue(num1, (long)num2);
        break;
      case RATIONALE:
        node->setType(AST_RATIONAL);
        str++; // Skip the '('
        num1 = strtod(str, &end);
        end++; // Skip the '/'
        num2 = strtod(end, NULL);
        node->setValue((long)num1, (long)num2);
        break;
      case INVALID:
        break;
      }
    return node;
  }

#include "utilities/copasimathml.h"

void CEvaluationNodeNumber::writeMathML(std::ostream & out,
                                        const std::vector<std::vector<std::string> > & /* env */,
                                        bool /* expand */,
                                        unsigned C_INT32 l) const
  {
    out << SPC(l) << "<mn>" << mData << "</mn>" << std::endl;
    //or use mValue instead?
  }
<|endoftext|>


<commit_before>#include "Command.h"
#include <KrisLibrary/math/angle.h>
#include <KrisLibrary/errors.h>

ActuatorCommand::ActuatorCommand()
  :mode(OFF),measureAngleAbsolute(true),
   kP(0),kI(0),kD(0),qdes(0),dqdes(0),iterm(0),
  torque(0),desiredVelocity(0)
{}

void ActuatorCommand::SetOff()
{
  mode=OFF;
}

void ActuatorCommand::SetPID(Real _qdes,Real _dqdes,Real _iterm)
{
  mode=PID;
  qdes=_qdes;
  dqdes=_dqdes;
  iterm=_iterm;
  torque=0;
}

void ActuatorCommand::SetTorque(Real t)
{
  mode=TORQUE;
  torque=t;
}

void ActuatorCommand::SetLockedVelocity(Real vel,Real torqueMax)
{
  mode=LOCKED_VELOCITY;
  desiredVelocity=vel;
  torque=torqueMax;
}

Real ActuatorCommand::GetPIDTorque(Real q,Real dq) const
{
  Real deltaq,deltadq;
  if(measureAngleAbsolute) {
    deltaq=qdes-q;
    if(Abs(AngleDiff(qdes,q)) < Abs(deltaq*0.5)) {
      printf("PID loop has a possible angle encoder error, using AngleDiff\n");
      printf("  qdes = %g, q = %g\n",qdes,q);
      printf("  AngleDiff %g, sub %g\n",AngleDiff(qdes,q),deltaq);
      //getchar();
      deltaq = AngleDiff(qdes,q);
    }
  }
  else
    deltaq=AngleDiff(qdes,q);
  deltadq=dqdes-dq;
  //printf("P torque: %g, D torque: %g, I torque %g, FF torque %g\n",kP*deltaq,kD*deltadq,kI*iterm,torque);
  return kP*deltaq+kD*deltadq+kI*iterm+torque;
}

void ActuatorCommand::IntegratePID(Real q,Real dt)
{
  if(measureAngleAbsolute) {
    if(Abs(AngleDiff(qdes,q)) < Abs((qdes-q)*0.5))
      iterm += AngleDiff(qdes,q)*dt;
    else
      iterm += (qdes-q)*dt;
  }
  else
    iterm += AngleDiff(qdes,q)*dt;

  //integrate qdes
  qdes += dqdes*dt;
}

void RobotMotorCommand::SetTorque(const Vector& torques)
{
  Assert(torques.n == (int)actuators.size());
  for(size_t i=0;i<actuators.size();i++)
    actuators[i].SetTorque(torques(i));
}

void RobotMotorCommand::Clear()
{
  for(size_t i=0;i<actuators.size();i++)
    actuators[i].SetOff();
}

void RobotMotorCommand::ResetPIDIntegrals()
{
  for(size_t i=0;i<actuators.size();i++)
    actuators[i].iterm=0;
}

Real RobotMotorCommand::GetTorque(int i,double q,double dq)
{
  switch(actuators[i].mode) {
  case ActuatorCommand::OFF: return 0;
  case ActuatorCommand::TORQUE: return actuators[i].torque;
  case ActuatorCommand::PID: return actuators[i].GetPIDTorque(q,dq);
  case ActuatorCommand::LOCKED_VELOCITY: return actuators[i].torque;
  }
  return 0;
}

bool RobotMotorCommand::Read(File& f)
{
  int n;
  if(!ReadFile(f,n)) return false;
  if(n < 0) return false;
  actuators.resize(n);
  for(int i=0;i<n;i++)
    if(!f.ReadData(&actuators[i],sizeof(actuators[i]))) return false;
  return true;
}

bool RobotMotorCommand::Write(File& f) const
{
  int n=(int)actuators.size();
  if(!WriteFile(f,n)) return false;
  for(int i=0;i<n;i++)
    if(!f.WriteData(&actuators[i],sizeof(actuators[i]))) return false;
  return true;
}
<commit_msg>Added myfile include<commit_after>#include "Command.h"
#include <KrisLibrary/math/angle.h>
#include <KrisLibrary/myfile.h>
#include <KrisLibrary/errors.h>

ActuatorCommand::ActuatorCommand()
  :mode(OFF),measureAngleAbsolute(true),
   kP(0),kI(0),kD(0),qdes(0),dqdes(0),iterm(0),
  torque(0),desiredVelocity(0)
{}

void ActuatorCommand::SetOff()
{
  mode=OFF;
}

void ActuatorCommand::SetPID(Real _qdes,Real _dqdes,Real _iterm)
{
  mode=PID;
  qdes=_qdes;
  dqdes=_dqdes;
  iterm=_iterm;
  torque=0;
}

void ActuatorCommand::SetTorque(Real t)
{
  mode=TORQUE;
  torque=t;
}

void ActuatorCommand::SetLockedVelocity(Real vel,Real torqueMax)
{
  mode=LOCKED_VELOCITY;
  desiredVelocity=vel;
  torque=torqueMax;
}

Real ActuatorCommand::GetPIDTorque(Real q,Real dq) const
{
  Real deltaq,deltadq;
  if(measureAngleAbsolute) {
    deltaq=qdes-q;
    if(Abs(AngleDiff(qdes,q)) < Abs(deltaq*0.5)) {
      printf("PID loop has a possible angle encoder error, using AngleDiff\n");
      printf("  qdes = %g, q = %g\n",qdes,q);
      printf("  AngleDiff %g, sub %g\n",AngleDiff(qdes,q),deltaq);
      //getchar();
      deltaq = AngleDiff(qdes,q);
    }
  }
  else
    deltaq=AngleDiff(qdes,q);
  deltadq=dqdes-dq;
  //printf("P torque: %g, D torque: %g, I torque %g, FF torque %g\n",kP*deltaq,kD*deltadq,kI*iterm,torque);
  return kP*deltaq+kD*deltadq+kI*iterm+torque;
}

void ActuatorCommand::IntegratePID(Real q,Real dt)
{
  if(measureAngleAbsolute) {
    if(Abs(AngleDiff(qdes,q)) < Abs((qdes-q)*0.5))
      iterm += AngleDiff(qdes,q)*dt;
    else
      iterm += (qdes-q)*dt;
  }
  else
    iterm += AngleDiff(qdes,q)*dt;

  //integrate qdes
  qdes += dqdes*dt;
}

void RobotMotorCommand::SetTorque(const Vector& torques)
{
  Assert(torques.n == (int)actuators.size());
  for(size_t i=0;i<actuators.size();i++)
    actuators[i].SetTorque(torques(i));
}

void RobotMotorCommand::Clear()
{
  for(size_t i=0;i<actuators.size();i++)
    actuators[i].SetOff();
}

void RobotMotorCommand::ResetPIDIntegrals()
{
  for(size_t i=0;i<actuators.size();i++)
    actuators[i].iterm=0;
}

Real RobotMotorCommand::GetTorque(int i,double q,double dq)
{
  switch(actuators[i].mode) {
  case ActuatorCommand::OFF: return 0;
  case ActuatorCommand::TORQUE: return actuators[i].torque;
  case ActuatorCommand::PID: return actuators[i].GetPIDTorque(q,dq);
  case ActuatorCommand::LOCKED_VELOCITY: return actuators[i].torque;
  }
  return 0;
}

bool RobotMotorCommand::Read(File& f)
{
  int n;
  if(!ReadFile(f,n)) return false;
  if(n < 0) return false;
  actuators.resize(n);
  for(int i=0;i<n;i++)
    if(!f.ReadData(&actuators[i],sizeof(actuators[i]))) return false;
  return true;
}

bool RobotMotorCommand::Write(File& f) const
{
  int n=(int)actuators.size();
  if(!WriteFile(f,n)) return false;
  for(int i=0;i<n;i++)
    if(!f.WriteData(&actuators[i],sizeof(actuators[i]))) return false;
  return true;
}
<|endoftext|>


<commit_before>/**
 * @file Cosa/OWI/Driver.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * @section Description
 * 1-Wire device driver support class.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/OWI.h"
#include <util/delay_basic.h>

#define DELAY(us) _delay_loop_2((us) << 2)

int8_t
OWI::Driver::search_rom(int8_t last)
{
  if (!_pin->reset()) return (ERROR);
  _pin->write(OWI::SEARCH_ROM);
  uint8_t pos = 0;
  int8_t next = LAST;
  for (uint8_t i = 0; i < 8; i++) {
    uint8_t data = 0;
    for (uint8_t j = 0; j < 8; j++) {
      data >>= 1;
      switch (_pin->read(2)) {
      case 0b00: // Discrepency between device roms
	if (pos == last) {
	  _pin->write(1, 1);
	  data |= 0x80;
	  last = FIRST;
	}
	else if (pos > last) {
	  _pin->write(0, 1);
	  next = pos;
	} else if (_rom[i] & (1 << j)) {
	  _pin->write(1, 1);
	  data |= 0x80;
	}
	else {
	  _pin->write(0, 1);
	}
	break;
      case 0b01: // Only one's at this position
	_pin->write(1, 1);
	data |= 0x80;
	break;
      case 0b10: // Only zero's at this position
	_pin->write(0, 1);
	break;
      case 0b11: // No device detected
	goto error;
      }
      pos += 1;
    }
    _rom[i] = data;
  }
  return (next);
 error:
  return (ERROR);
}

bool
OWI::Driver::read_rom()
{
  if (!_pin->reset()) return (0);
  _pin->write(OWI::READ_ROM);
  _pin->begin();
  for (uint8_t i = 0; i < ROM_MAX; i++) {
    _rom[i] = _pin->read();
  }
  return (_pin->end() == 0);
}

bool
OWI::Driver::match_rom()
{
  if (!_pin->reset()) return (0);
  _pin->write(OWI::MATCH_ROM);
  for (uint8_t i = 0; i < ROM_MAX; i++) {
    _pin->write(_rom[i]);
  }
  return (1);
}

bool
OWI::Driver::skip_rom()
{
  if (!_pin->reset()) return (0);
  _pin->write(OWI::SKIP_ROM);
  return (1);
}

void
OWI::Driver::print_rom(IOStream& stream)
{
  uint8_t i;
  stream.printf_P(PSTR("OWI::rom(family = %hd, id = "), _rom[0]);
  for (i = 1; i < ROM_MAX - 1; i++)
    stream.printf_P(PSTR("%hd, "), _rom[i]);
  stream.printf_P(PSTR("crc = %hd)\n"), _rom[i]);
}

bool
OWI::Driver::connect(uint8_t family, uint8_t index)
{
  int8_t last = FIRST;
  do {
    last = search_rom(last);
    if (last == ERROR) return (0);
    if (_rom[0] == family) {
      if (index == 0) return (1);
      index -= 1;
    }
  } while (last != LAST);
  for (uint8_t i = 1; i < ROM_MAX; i++) _rom[i] = 0;
  return (0);
}
<commit_msg>Removing dead code.<commit_after>/**
 * @file Cosa/OWI/Driver.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * @section Description
 * 1-Wire device driver support class.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/OWI.h"

int8_t
OWI::Driver::search_rom(int8_t last)
{
  if (!_pin->reset()) return (ERROR);
  _pin->write(OWI::SEARCH_ROM);
  uint8_t pos = 0;
  int8_t next = LAST;
  for (uint8_t i = 0; i < 8; i++) {
    uint8_t data = 0;
    for (uint8_t j = 0; j < 8; j++) {
      data >>= 1;
      switch (_pin->read(2)) {
      case 0b00: // Discrepency between device roms
	if (pos == last) {
	  _pin->write(1, 1);
	  data |= 0x80;
	  last = FIRST;
	}
	else if (pos > last) {
	  _pin->write(0, 1);
	  next = pos;
	} else if (_rom[i] & (1 << j)) {
	  _pin->write(1, 1);
	  data |= 0x80;
	}
	else {
	  _pin->write(0, 1);
	}
	break;
      case 0b01: // Only one's at this position
	_pin->write(1, 1);
	data |= 0x80;
	break;
      case 0b10: // Only zero's at this position
	_pin->write(0, 1);
	break;
      case 0b11: // No device detected
	goto error;
      }
      pos += 1;
    }
    _rom[i] = data;
  }
  return (next);
 error:
  return (ERROR);
}

bool
OWI::Driver::read_rom()
{
  if (!_pin->reset()) return (0);
  _pin->write(OWI::READ_ROM);
  _pin->begin();
  for (uint8_t i = 0; i < ROM_MAX; i++) {
    _rom[i] = _pin->read();
  }
  return (_pin->end() == 0);
}

bool
OWI::Driver::match_rom()
{
  if (!_pin->reset()) return (0);
  _pin->write(OWI::MATCH_ROM);
  for (uint8_t i = 0; i < ROM_MAX; i++) {
    _pin->write(_rom[i]);
  }
  return (1);
}

bool
OWI::Driver::skip_rom()
{
  if (!_pin->reset()) return (0);
  _pin->write(OWI::SKIP_ROM);
  return (1);
}

void
OWI::Driver::print_rom(IOStream& stream)
{
  uint8_t i;
  stream.printf_P(PSTR("OWI::rom(family = %hd, id = "), _rom[0]);
  for (i = 1; i < ROM_MAX - 1; i++)
    stream.printf_P(PSTR("%hd, "), _rom[i]);
  stream.printf_P(PSTR("crc = %hd)\n"), _rom[i]);
}

bool
OWI::Driver::connect(uint8_t family, uint8_t index)
{
  int8_t last = FIRST;
  do {
    last = search_rom(last);
    if (last == ERROR) return (0);
    if (_rom[0] == family) {
      if (index == 0) return (1);
      index -= 1;
    }
  } while (last != LAST);
  for (uint8_t i = 1; i < ROM_MAX; i++) _rom[i] = 0;
  return (0);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

bool nearHundred(int n);

int main() {
   bool go = true;
   int n;
   cout << "Please enter an integer: ";
   cin >> n;

   if (nearHundred(n))
      printf("%d is within 10 of 100 or 200", n);
   else
      printf("%d isn't within 10 of 100 or 200", n);
	return 0;
}

bool nearHundred(int n) {
   if (abs(n) >= 90 && abs(n) <= 110)
      return true;
   else if (abs(n) >= 190 && abs(n) <= 210)
      return true;
   else
      return false;
}
<commit_msg>Update NearHundred.cpp<commit_after>/*
   Programmer: Kristoffer Larson

   Description: State if input values are within 10
   	of 100 or 200.
*/

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

bool nearHundred(int n);

int main() {
   bool go = true;
   int n;
   cout << "Please enter an integer: ";
   cin >> n;

   if (nearHundred(n))
      printf("%d is within 10 of 100 or 200", n);
   else
      printf("%d isn't within 10 of 100 or 200", n);
	return 0;
}

bool nearHundred(int n) {
   if (abs(n) >= 90 && abs(n) <= 110)
      return true;
   else if (abs(n) >= 190 && abs(n) <= 210)
      return true;
   else
      return false;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgl2pexvertexarray_p.h"

#include <private/qbezier_p.h>

QT_BEGIN_NAMESPACE

void QGL2PEXVertexArray::clear()
{
    vertexArray.reset();
    vertexArrayStops.clear();
    boundingRectDirty = true;
}

QGLRect QGL2PEXVertexArray::boundingRect() const
{
    if (boundingRectDirty)
        return QGLRect(0.0, 0.0, 0.0, 0.0);
    else
        return QGLRect(minX, minY, maxX, maxY);
}

void QGL2PEXVertexArray::addRect(const QRectF &rect)
{
    vertexArray << rect.topLeft() << rect.topRight() << rect.bottomRight()
                << rect.bottomRight() << rect.bottomLeft() << rect.topLeft();
}

void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseScale)
{
    const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
    const QPainterPath::ElementType* const elements = path.elements();

    if (boundingRectDirty) {
        minX = maxX = points[0].x();
        minY = maxY = points[0].y();
        boundingRectDirty = false;
    }

    vertexArray.add(points[0]); // The first element is always a moveTo

    do {
        if (!elements) {
//             qDebug("QVectorPath has no elements");
            // If the path has a null elements pointer, the elements implicitly
            // start with a moveTo (already added) and continue with lineTos:
            for (int i=1; i<path.elementCount(); ++i)
                lineToArray(points[i].x(), points[i].y());

            break;
        }
//         qDebug("QVectorPath has element types");

        for (int i=1; i<path.elementCount(); ++i) {
            const QPainterPath::ElementType elementType = elements[i];
            switch (elementType) {
            case QPainterPath::MoveToElement:
//                qDebug("element[%d] is a MoveToElement", i);
                vertexArrayStops.append(vertexArray.size());
                vertexArray.add(points[i]); // Add the moveTo as a new vertex
                break;
            case QPainterPath::LineToElement:
//                qDebug("element[%d] is a LineToElement", i);
                lineToArray(points[i].x(), points[i].y());
                break;
            case QPainterPath::CurveToElement:
//                qDebug("element[%d] is a CurveToElement", i);
                curveToArray(points[i], points[i+1], points[i+2], curveInverseScale);
                i+=2;
                break;
            default:
                break;
            }
        }
    } while (0);

    vertexArrayStops.append(vertexArray.size());
}

void QGL2PEXVertexArray::lineToArray(const GLfloat x, const GLfloat y)
{
    vertexArray.add(QGLPoint(x, y));

    if (x > maxX)
        maxX = x;
    else if (x < minX)
        minX = x;
    if (y > maxY)
        maxY = y;
    else if (y < minY)
        minY = y;
}

void QGL2PEXVertexArray::curveToArray(const QGLPoint &cp1, const QGLPoint &cp2, const QGLPoint &ep, GLfloat inverseScale)
{
    qreal inverseScaleHalf = inverseScale / 2;

    QBezier beziers[32];
    beziers[0] = QBezier::fromPoints(vertexArray.last(), cp1, cp2, ep);
    QBezier *b = beziers;
    while (b >= beziers) {
        // check if we can pop the top bezier curve from the stack
        qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
        qreal d;
        if (l > inverseScale) {
            d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2) - (b->y4 - b->y1)*(b->x1 - b->x2) )
                + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3) - (b->y4 - b->y1)*(b->x1 - b->x3) );
            d /= l;
        } else {
            d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
                qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
        }
        if (d < inverseScaleHalf || b == beziers + 31) {
            // good enough, we pop it off and add the endpoint
            lineToArray(b->x4, b->y4);
            --b;
        } else {
            // split, second half of the polygon goes lower into the stack
            b->split(b+1, b);
           ++b;
        }
    }
}

QT_END_NAMESPACE
<commit_msg>Fixed path filling in the GL2 paint engine.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgl2pexvertexarray_p.h"

#include <private/qbezier_p.h>

QT_BEGIN_NAMESPACE

void QGL2PEXVertexArray::clear()
{
    vertexArray.reset();
    vertexArrayStops.clear();
    boundingRectDirty = true;
}

QGLRect QGL2PEXVertexArray::boundingRect() const
{
    if (boundingRectDirty)
        return QGLRect(0.0, 0.0, 0.0, 0.0);
    else
        return QGLRect(minX, minY, maxX, maxY);
}

void QGL2PEXVertexArray::addRect(const QRectF &rect)
{
    vertexArray << rect.topLeft() << rect.topRight() << rect.bottomRight()
                << rect.bottomRight() << rect.bottomLeft() << rect.topLeft();
}

void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseScale)
{
    const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
    const QPainterPath::ElementType* const elements = path.elements();

    if (boundingRectDirty) {
        minX = maxX = points[0].x();
        minY = maxY = points[0].y();
        boundingRectDirty = false;
    }

    vertexArray.add(points[0]); // The first element is always a moveTo

    do {
        if (!elements) {
//             qDebug("QVectorPath has no elements");
            // If the path has a null elements pointer, the elements implicitly
            // start with a moveTo (already added) and continue with lineTos:
            for (int i=1; i<path.elementCount(); ++i)
                lineToArray(points[i].x(), points[i].y());

            break;
        }
//         qDebug("QVectorPath has element types");

        for (int i=1; i<path.elementCount(); ++i) {
            const QPainterPath::ElementType elementType = elements[i];
            switch (elementType) {
            case QPainterPath::MoveToElement:
//                qDebug("element[%d] is a MoveToElement", i);
                vertexArrayStops.append(vertexArray.size());
                lineToArray(points[i].x(), points[i].y()); // Add the moveTo as a new vertex
                break;
            case QPainterPath::LineToElement:
//                qDebug("element[%d] is a LineToElement", i);
                lineToArray(points[i].x(), points[i].y());
                break;
            case QPainterPath::CurveToElement:
//                qDebug("element[%d] is a CurveToElement", i);
                curveToArray(points[i], points[i+1], points[i+2], curveInverseScale);
                i+=2;
                break;
            default:
                break;
            }
        }
    } while (0);

    vertexArrayStops.append(vertexArray.size());
}

void QGL2PEXVertexArray::lineToArray(const GLfloat x, const GLfloat y)
{
    vertexArray.add(QGLPoint(x, y));

    if (x > maxX)
        maxX = x;
    else if (x < minX)
        minX = x;
    if (y > maxY)
        maxY = y;
    else if (y < minY)
        minY = y;
}

void QGL2PEXVertexArray::curveToArray(const QGLPoint &cp1, const QGLPoint &cp2, const QGLPoint &ep, GLfloat inverseScale)
{
    qreal inverseScaleHalf = inverseScale / 2;

    QBezier beziers[32];
    beziers[0] = QBezier::fromPoints(vertexArray.last(), cp1, cp2, ep);
    QBezier *b = beziers;
    while (b >= beziers) {
        // check if we can pop the top bezier curve from the stack
        qreal l = qAbs(b->x4 - b->x1) + qAbs(b->y4 - b->y1);
        qreal d;
        if (l > inverseScale) {
            d = qAbs( (b->x4 - b->x1)*(b->y1 - b->y2) - (b->y4 - b->y1)*(b->x1 - b->x2) )
                + qAbs( (b->x4 - b->x1)*(b->y1 - b->y3) - (b->y4 - b->y1)*(b->x1 - b->x3) );
            d /= l;
        } else {
            d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
                qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
        }
        if (d < inverseScaleHalf || b == beziers + 31) {
            // good enough, we pop it off and add the endpoint
            lineToArray(b->x4, b->y4);
            --b;
        } else {
            // split, second half of the polygon goes lower into the stack
            b->split(b+1, b);
           ++b;
        }
    }
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "sensor_msgs/point_cloud_conversion.h"

#include <boost/make_shared.hpp>
#include "pcl/io/pcd_io.h"
#include <pcl/features/fpfh_omp.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d_omp.h>
#include "pcl/filters/voxel_grid.h"

//#include "feature_extractor_fpfh/AddTwoInts.h"
#include "feature_extractor_fpfh/FPFHCalc.h"

using namespace pcl;
using namespace std;
typedef KdTree<PointXYZ>::Ptr KdTreePtr;

bool fpfh_cb(feature_extractor_fpfh::FPFHCalc::Request &req,
             feature_extractor_fpfh::FPFHCalc::Response &res)
{
    float leaf_size = .01;
    pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
    sensor_msgs::PointCloud2::Ptr input_cloud(new sensor_msgs::PointCloud2());
    sensor_msgs::convertPointCloudToPointCloud2(req.input, *input_cloud);
    //sensor_msgs::PointCloud2::Ptr input_cloud(&req.input);

    sensor_msgs::PointCloud2::Ptr cloud_filtered(new sensor_msgs::PointCloud2());
    sor.setInputCloud(input_cloud);
    sor.setLeafSize (leaf_size, leaf_size, leaf_size);
    sor.filter(*cloud_filtered);
    ROS_INFO("after filtering: %d points", cloud_filtered->width * cloud_filtered->height);

    PointCloud<PointXYZ> cloud;
    fromROSMsg(*cloud_filtered, cloud);
    std::vector<int> indices;
    indices.resize (cloud.points.size());
    for (size_t i = 0; i < indices.size (); ++i) { indices[i] = i; }

    // make tree
    KdTreePtr tree;
    tree.reset(new KdTreeFLANN<PointXYZ> (false));
    tree->setInputCloud(cloud.makeShared());

    PointCloud<Normal>::Ptr normals(new PointCloud<Normal>());
    boost::shared_ptr< vector<int> > indicesptr(new vector<int> (indices));
    NormalEstimation<PointXYZ, Normal> normal_estimator;

    // set normal estimation parameters
    normal_estimator.setIndices(indicesptr);
    normal_estimator.setSearchMethod(tree);
    normal_estimator.setKSearch(10); // Use 10 nearest neighbors to estimate the normals

    // estimate
    ROS_INFO("Calculating normals...\n");
    normal_estimator.setInputCloud(cloud.makeShared());
    normal_estimator.compute(*normals);

    // calculate FPFH
    //FPFHEstimation<PointXYZ, Normal, FPFHSignature33> fpfh;
    FPFHEstimationOMP<PointXYZ, Normal, FPFHSignature33> fpfh(4);    // instantiate 4 threads

    // object
    PointCloud<FPFHSignature33>::Ptr fphists (new PointCloud<FPFHSignature33>());

    // set parameters
    int d1, d2, d3;
    d1 = d2 = d3 = 11;
    fpfh.setNrSubdivisions(d1, d2, d3);
    fpfh.setIndices(indicesptr);
    fpfh.setSearchMethod(tree);
    fpfh.setKSearch(indices.size());

    // estimate
    ROS_INFO("Calculating fpfh...\n");
    fpfh.setInputNormals(normals);
    fpfh.setInputCloud(cloud.makeShared());
    fpfh.compute(*fphists);

    res.hist.dim[0] = d1;
    res.hist.dim[1] = d2;
    res.hist.dim[2] = d3;
    unsigned int total_size = d1+d2+d3;
    res.hist.histograms.resize(total_size * cloud.points.size());
    res.hist.points3d.resize(3*cloud.points.size());

    ROS_INFO("copying into message...\n");
    for (unsigned int i = 0; i < cloud.points.size(); i++)
    {
        for (unsigned int j = 0; j < total_size; j++)
        {
            res.hist.histograms[i*total_size + j] = fphists->points[i].histogram[j];
            //if (i == 0)
            //{
            //    printf(">> %.2f \n", fphists->points[i].histogram[j]);
            //}

            //if (i == 4)
            //{
            //    printf("X %.2f \n", fphists->points[i].histogram[j]);
            //}
        }

        res.hist.points3d[3*i]   = cloud.points[i].x;
        res.hist.points3d[3*i+1] = cloud.points[i].y;
        res.hist.points3d[3*i+2] = cloud.points[i].z;
        //if (i == 0)
        //    printf(">> 0  %.4f %.4f %.4f \n", cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);
        //if (i == 4)
        //    printf(">> 4  %.4f %.4f %.4f \n", cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);
    }

    res.hist.npoints = cloud.points.size();
    ROS_INFO("done.\n");
    //printf("%d\n", );
    // sensor_msgs::PointCloud2 req
    // new feature_extractor::FPFHist()
    return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "fpfh_feature_extractor");
  ros::NodeHandle n;
  //ros::ServiceServer service = n.advertiseService("fpfh", fpfh);
  //ros::ServiceServer service = n.advertiseService("add", add);
  ros::ServiceServer fpfh_service = n.advertiseService("fpfh", fpfh_cb);

  //ros::ServiceServer service = n.advertiseService("fpfh", boost::bind(&fpfh, _1, _2));
  ROS_INFO("ready.\n");
  ros::spin();
  return 0;
}

//bool add(feature_extractor::AddTwoInts::Request  &req,
//         feature_extractor::AddTwoInts::Response &res )
//{
//  res.sum = req.a + req.b;
//  ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
//  ROS_INFO("sending back response: [%ld]", (long int)res.sum);
//  return true;
//}
<commit_msg><commit_after>#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "sensor_msgs/point_cloud_conversion.h"

#include <boost/make_shared.hpp>
#include "pcl/io/pcd_io.h"
#include <pcl/features/fpfh_omp.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d_omp.h>
#include "pcl/filters/voxel_grid.h"

//#include "feature_extractor_fpfh/AddTwoInts.h"
#include "feature_extractor_fpfh/FPFHCalc.h"

using namespace pcl;
using namespace std;
typedef KdTree<PointXYZ>::Ptr KdTreePtr;

bool fpfh_cb(feature_extractor_fpfh::FPFHCalc::Request &req,
             feature_extractor_fpfh::FPFHCalc::Response &res)
{
    float leaf_size = .01;
    pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
    sensor_msgs::PointCloud2::Ptr input_cloud(new sensor_msgs::PointCloud2());
    sensor_msgs::convertPointCloudToPointCloud2(req.input, *input_cloud);
    //sensor_msgs::PointCloud2::Ptr input_cloud(&req.input);

    sensor_msgs::PointCloud2::Ptr cloud_filtered(new sensor_msgs::PointCloud2());
    sor.setInputCloud(input_cloud);
    sor.setLeafSize (leaf_size, leaf_size, leaf_size);
    sor.filter(*cloud_filtered);
    ROS_INFO("after filtering: %d points", cloud_filtered->width * cloud_filtered->height);

    PointCloud<PointXYZ> cloud;
    fromROSMsg(*cloud_filtered, cloud);
    std::vector<int> indices;
    indices.resize (cloud.points.size());
    for (size_t i = 0; i < indices.size (); ++i) { indices[i] = i; }

    // make tree
    KdTreePtr tree;
    tree.reset(new KdTreeFLANN<PointXYZ> (false));
    tree->setInputCloud(cloud.makeShared());

    PointCloud<Normal>::Ptr normals(new PointCloud<Normal>());
    boost::shared_ptr< vector<int> > indicesptr(new vector<int> (indices));
    NormalEstimation<PointXYZ, Normal> normal_estimator;

    // set normal estimation parameters
    normal_estimator.setIndices(indicesptr);
    normal_estimator.setSearchMethod(tree);
    normal_estimator.setKSearch(10); // Use 10 nearest neighbors to estimate the normals

    // estimate
    ROS_INFO("Calculating normals...\n");
    normal_estimator.setInputCloud(cloud.makeShared());
    normal_estimator.compute(*normals);

    // calculate FPFH
    //FPFHEstimation<PointXYZ, Normal, FPFHSignature33> fpfh;
    FPFHEstimationOMP<PointXYZ, Normal, FPFHSignature33> fpfh(4);    // instantiate 4 threads

    // object
    PointCloud<FPFHSignature33>::Ptr fphists (new PointCloud<FPFHSignature33>());

    // set parameters
    int d1, d2, d3;
    d1 = d2 = d3 = 11;
    fpfh.setNrSubdivisions(d1, d2, d3);
    fpfh.setIndices(indicesptr);
    fpfh.setSearchMethod(tree);
    fpfh.setKSearch(50);

    // estimate
    ROS_INFO("Calculating fpfh...\n");
    fpfh.setInputNormals(normals);
    fpfh.setInputCloud(cloud.makeShared());
    fpfh.compute(*fphists);

    res.hist.dim[0] = d1;
    res.hist.dim[1] = d2;
    res.hist.dim[2] = d3;
    unsigned int total_size = d1+d2+d3;
    res.hist.histograms.resize(total_size * cloud.points.size());
    res.hist.points3d.resize(3*cloud.points.size());

    ROS_INFO("copying into message...\n");
    for (unsigned int i = 0; i < cloud.points.size(); i++)
    {
        for (unsigned int j = 0; j < total_size; j++)
        {
            res.hist.histograms[i*total_size + j] = fphists->points[i].histogram[j];
            //if (i == 0)
            //{
            //    printf(">> %.2f \n", fphists->points[i].histogram[j]);
            //}

            //if (i == 4)
            //{
            //    printf("X %.2f \n", fphists->points[i].histogram[j]);
            //}
        }

        res.hist.points3d[3*i]   = cloud.points[i].x;
        res.hist.points3d[3*i+1] = cloud.points[i].y;
        res.hist.points3d[3*i+2] = cloud.points[i].z;
        //if (i == 0)
        //    printf(">> 0  %.4f %.4f %.4f \n", cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);
        //if (i == 4)
        //    printf(">> 4  %.4f %.4f %.4f \n", cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);
    }

    res.hist.npoints = cloud.points.size();
    ROS_INFO("done.\n");
    //printf("%d\n", );
    // sensor_msgs::PointCloud2 req
    // new feature_extractor::FPFHist()
    return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "fpfh_feature_extractor");
  ros::NodeHandle n;
  //ros::ServiceServer service = n.advertiseService("fpfh", fpfh);
  //ros::ServiceServer service = n.advertiseService("add", add);
  ros::ServiceServer fpfh_service = n.advertiseService("fpfh", fpfh_cb);

  //ros::ServiceServer service = n.advertiseService("fpfh", boost::bind(&fpfh, _1, _2));
  ROS_INFO("ready.\n");
  ros::spin();
  return 0;
}

//bool add(feature_extractor::AddTwoInts::Request  &req,
//         feature_extractor::AddTwoInts::Response &res )
//{
//  res.sum = req.a + req.b;
//  ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
//  ROS_INFO("sending back response: [%ld]", (long int)res.sum);
//  return true;
//}
<|endoftext|>


<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_MEMORY_HH__
#define __BSE_MEMORY_HH__

#include <bse/bseenums.hh>

namespace Bse {

/// Utilities for allocating cache line aligned memory from huge pages.
namespace FastMemory {

/// Minimum alignment >= cache line size, see getconf LEVEL1_DCACHE_LINESIZE.
inline constexpr size_t cache_line_size = 64;

} // FastMemory

// Allocate cache-line aligned memory block from fast memory pool, MT-Safe.
void*   fast_mem_alloc  (size_t size);
// Free a memory block allocated with aligned_malloc(), MT-Safe.
void    fast_mem_free   (void *mem);

/// Array with cache-line-alignment containing a fixed numer of PODs.
template<typename T, size_t ALIGNMENT = FastMemory::cache_line_size>
class FastMemArray {
  static_assert (std::is_trivially_copyable<T>::value);
  static_assert (ALIGNMENT <= FastMemory::cache_line_size);
  static_assert ((ALIGNMENT & (ALIGNMENT - 1)) == 0);
  static_assert (alignof (T) <= ALIGNMENT);
  const size_t n_elements_ = 0;
  T     *const data_ = nullptr;
  BSE_CLASS_NON_COPYABLE (FastMemArray);
protected:
  void     range_check (size_t n) const
  {
    if (n >= n_elements_)
      throw std::out_of_range (string_format ("FastMemArray::range_check: n >= size(): %u >= %u", n, size()));
  }
public:
  FastMemArray (size_t n_elements) :
    n_elements_ (n_elements),
    data_ ((T*) fast_mem_alloc (sizeof (T) * n_elements_))
  {
    std::fill (begin(), end(), T());
  }
  FastMemArray (const vector<T>& elements) :
    n_elements_ (elements.size()),
    data_ ((T*) fast_mem_alloc (sizeof (T) * n_elements_))
  {
    std::copy (elements.begin(), elements.end(), begin());
  }
  ~FastMemArray()
  {
    static_assert (std::is_trivially_destructible<T>::value);
    fast_mem_free (data_);
  }
  T*       begin      ()                { return &data_[0]; }
  T*       end        ()                { return &data_[n_elements_]; }
  size_t   size       () const          { return n_elements_; }
  T&       operator[] (size_t n)        { return data_[n]; }
  const T& operator[] (size_t n) const  { return data_[n]; }
  T&       at         (size_t n)        { range_check (n); return data_[n]; }
  const T& at         (size_t n) const  { range_check (n); return data_[n]; }
};

namespace FastMemory {

// == NewDeleteBase ==
class NewDeleteBase {
  static constexpr const std::align_val_t __cxxalignment = std::align_val_t (__STDCPP_DEFAULT_NEW_ALIGNMENT__);
  static void    delete_  (void *ptr, std::size_t sz, std::align_val_t al);
  static void*   new_     (std::size_t sz, std::align_val_t al);
public:
  // 'static' is implicit for operator new/delete
  void* operator new      (std::size_t sz)                            { return new_ (sz, __cxxalignment); }
  void* operator new[]    (std::size_t sz)                            { return new_ (sz, __cxxalignment); }
  void* operator new      (std::size_t sz, std::align_val_t al)       { return new_ (sz, al); }
  void* operator new[]    (std::size_t sz, std::align_val_t al)       { return new_ (sz, al); }
  // variants without size_t MUST NOT be defined for the following to be used
  void  operator delete   (void *ptr, std::size_t sz)                 { delete_ (ptr, sz, __cxxalignment); }
  void  operator delete[] (void *ptr, std::size_t sz)                 { delete_ (ptr, sz, __cxxalignment); }
  void  operator delete   (void *ptr, std::size_t sz, std::align_val_t al) { delete_ (ptr, sz, al); }
  void  operator delete[] (void *ptr, std::size_t sz, std::align_val_t al) { delete_ (ptr, sz, al); }
};

/// Internal allocator handle.
struct Allocator;
using AllocatorP = std::shared_ptr<Allocator>;

/// Reference for an allocated memory block.
struct Block {
  void  *const block_start = nullptr;
  const uint32 block_length = 0;
  Block& operator= (const Block &src) { this->~Block(); new (this) Block (src); return *this; }
  /*copy*/ Block   (const Block &src) = default;
  /*dflt*/ Block   () = default;
};

/// Memory area (over-)aligned to cache size and utilizing huge pages.
struct Arena {
  /// Create isolated memory area.
  explicit Arena     (uint32 mem_size, uint32 alignment = cache_line_size);
  /// Alignment for block addresses and length.
  size_t   alignment () const;
  /// Address of memory area.
  uint64   location  () const;
  /// Reserved memory area in bytes.
  uint64   reserved  () const;
  /// Create a memory block from cache-line aligned memory area, MT-Unsafe.
  Block    allocate  (uint32 length) const;
  Block    allocate  (uint32 length, std::nothrow_t) const;
  /// Realease a previously allocated block, MT-Unsafe.
  void     release   (Block allocatedblock) const;
protected:
  AllocatorP fma; ///< Identifier for the associated memory allocator.
  explicit Arena     (AllocatorP);
};

} // FastMemory

/// Compact, deduplicating string variant for constant strings that never need to be freed.
class CString {
  uint quark_ = 0;
public:
  using size_type = std::string::size_type;
  using const_iterator = std::string::const_iterator;
  using const_reference = std::string::const_reference;
  using const_reverse_iterator = std::string::const_reverse_iterator;
  /*ctor*/           CString     () noexcept                     = default;
  /*ctor*/           CString     (const char *c)                 { assign (c); }
  /*ctor*/           CString     (const char *c, size_type s)    { assign (c, s); }
  /*ctor*/           CString     (const std::string &s)          { assign (s); }
  /*copy*/           CString     (const CString&) noexcept       = default;
  /*move*/           CString     (CString&&) noexcept            = default;
  CString&           operator=   (const CString&) noexcept       = default;
  CString&           operator=   (CString&&) noexcept            = default;
  CString&           operator=   (const std::string &s)          { return assign (s); }
  CString&           operator=   (const char *c)                 { return assign (c); }
  CString&           operator=   (char ch)                       { return assign (std::addressof (ch), 1); }
  CString&           operator=   (std::initializer_list<char> l) { return assign (l.begin(), l.size()); }
  CString&           assign      (const CString &s)              { return this->operator= (s); }
  CString&           assign      (const std::string &s);
  CString&           assign      (const char *c, size_type s)   { return assign (std::string (c, s)); }
  CString&           assign      (const char *c)                { return assign (std::string (c)); }
  CString&           assign      (size_type count, char ch)     { return this->operator= (std::string (count, ch)); }
  const std::string& string      () const;
  const char*        c_str       () const noexcept      { return string().c_str(); }
  const char*        data        () const noexcept      { return string().data(); }
  const_reference    at          (size_type pos) const  { return string().at (pos); }
  const_reference    operator[]  (size_type pos) const  { return string().operator[] (pos); }
  size_type          capacity    () const noexcept      { return string().capacity(); }
  size_type          length      () const noexcept      { return string().length(); }
  bool               empty       () const noexcept      { return string().empty(); }
  size_type          size        () const noexcept      { return string().size(); }
  const_iterator     begin       () const noexcept      { return string().begin(); }
  const_iterator     cbegin      () const noexcept      { return string().cbegin(); }
  const_iterator     end         () const noexcept      { return string().end(); }
  const_iterator     cend        () const noexcept      { return string().cend(); }
  const_reverse_iterator rbegin  () const noexcept      { return string().rbegin(); }
  const_reverse_iterator crbegin () const noexcept      { return string().crbegin(); }
  const_reverse_iterator rend    () const noexcept      { return string().rend(); }
  const_reverse_iterator crend   () const noexcept      { return string().crend(); }
  /*conv*/  operator std::string () const noexcept      { return string(); }
  bool                 operator== (const CString &b) noexcept           { return quark_ == b.quark_; }
  bool                 operator== (const std::string &b) noexcept       { return string() == b; }
  bool                 operator== (const char *s) noexcept              { return string() == s; }
  bool                 operator!= (const CString &b) noexcept           { return quark_ != b.quark_; }
  bool                 operator!= (const std::string &b) noexcept       { return string() != b; }
  bool                 operator!= (const char *s) noexcept              { return string() != s; }
  bool                 operator<  (const CString &b) noexcept           { return string() < b.string(); }
  bool                 operator<  (const std::string &b) noexcept       { return string() < b; }
  bool                 operator<  (const char *s) noexcept              { return string() < s; }
  bool                 operator<= (const CString &b) noexcept           { return string() <= b.string(); }
  bool                 operator<= (const std::string &b) noexcept       { return string() <= b; }
  bool                 operator<= (const char *s) noexcept              { return string() <= s; }
  bool                 operator>  (const CString &b) noexcept           { return string() > b.string(); }
  bool                 operator>  (const std::string &b) noexcept       { return string() > b; }
  bool                 operator>  (const char *s) noexcept              { return string() > s; }
  bool                 operator>= (const CString &b) noexcept           { return string() >= b.string(); }
  bool                 operator>= (const std::string &b) noexcept       { return string() >= b; }
  bool                 operator>= (const char *s) noexcept              { return string() >= s; }
  friend std::ostream& operator<< (std::ostream &os, const CString &cs) { return os << cs.string(); }
  static CString     lookup      (const std::string &s);
  static const std::string::size_type npos = -1;
};

inline bool operator== (const std::string &s, const CString &c) { return s == c.string(); }
inline bool operator!= (const std::string &s, const CString &c) { return s != c.string(); }
inline bool operator<  (const std::string &s, const CString &c) { return s <  c.string(); }
inline bool operator<= (const std::string &s, const CString &c) { return s <= c.string(); }
inline bool operator>  (const std::string &s, const CString &c) { return s >  c.string(); }
inline bool operator>= (const std::string &s, const CString &c) { return s >= c.string(); }

inline bool operator== (const char *s, const CString &c) { return s == c.string(); }
inline bool operator!= (const char *s, const CString &c) { return s != c.string(); }
inline bool operator<  (const char *s, const CString &c) { return s <  c.string(); }
inline bool operator<= (const char *s, const CString &c) { return s <= c.string(); }
inline bool operator>  (const char *s, const CString &c) { return s >  c.string(); }
inline bool operator>= (const char *s, const CString &c) { return s >= c.string(); }

} // Bse

namespace std {
template<>
struct hash<::Bse::CString> {
  size_t operator() (const ::Bse::CString &cs) const
  {
    return ::std::hash<::std::string>{} (cs.string());
  }
};
} // std

#endif /* __BSE_MEMORY_HH__ */
<commit_msg>BSE: memory.hh: add friend operators to class declaration<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_MEMORY_HH__
#define __BSE_MEMORY_HH__

#include <bse/bseenums.hh>

namespace Bse {

/// Utilities for allocating cache line aligned memory from huge pages.
namespace FastMemory {

/// Minimum alignment >= cache line size, see getconf LEVEL1_DCACHE_LINESIZE.
inline constexpr size_t cache_line_size = 64;

} // FastMemory

// Allocate cache-line aligned memory block from fast memory pool, MT-Safe.
void*   fast_mem_alloc  (size_t size);
// Free a memory block allocated with aligned_malloc(), MT-Safe.
void    fast_mem_free   (void *mem);

/// Array with cache-line-alignment containing a fixed numer of PODs.
template<typename T, size_t ALIGNMENT = FastMemory::cache_line_size>
class FastMemArray {
  static_assert (std::is_trivially_copyable<T>::value);
  static_assert (ALIGNMENT <= FastMemory::cache_line_size);
  static_assert ((ALIGNMENT & (ALIGNMENT - 1)) == 0);
  static_assert (alignof (T) <= ALIGNMENT);
  const size_t n_elements_ = 0;
  T     *const data_ = nullptr;
  BSE_CLASS_NON_COPYABLE (FastMemArray);
protected:
  void     range_check (size_t n) const
  {
    if (n >= n_elements_)
      throw std::out_of_range (string_format ("FastMemArray::range_check: n >= size(): %u >= %u", n, size()));
  }
public:
  FastMemArray (size_t n_elements) :
    n_elements_ (n_elements),
    data_ ((T*) fast_mem_alloc (sizeof (T) * n_elements_))
  {
    std::fill (begin(), end(), T());
  }
  FastMemArray (const vector<T>& elements) :
    n_elements_ (elements.size()),
    data_ ((T*) fast_mem_alloc (sizeof (T) * n_elements_))
  {
    std::copy (elements.begin(), elements.end(), begin());
  }
  ~FastMemArray()
  {
    static_assert (std::is_trivially_destructible<T>::value);
    fast_mem_free (data_);
  }
  T*       begin      ()                { return &data_[0]; }
  T*       end        ()                { return &data_[n_elements_]; }
  size_t   size       () const          { return n_elements_; }
  T&       operator[] (size_t n)        { return data_[n]; }
  const T& operator[] (size_t n) const  { return data_[n]; }
  T&       at         (size_t n)        { range_check (n); return data_[n]; }
  const T& at         (size_t n) const  { range_check (n); return data_[n]; }
};

namespace FastMemory {

// == NewDeleteBase ==
class NewDeleteBase {
  static constexpr const std::align_val_t __cxxalignment = std::align_val_t (__STDCPP_DEFAULT_NEW_ALIGNMENT__);
  static void    delete_  (void *ptr, std::size_t sz, std::align_val_t al);
  static void*   new_     (std::size_t sz, std::align_val_t al);
public:
  // 'static' is implicit for operator new/delete
  void* operator new      (std::size_t sz)                            { return new_ (sz, __cxxalignment); }
  void* operator new[]    (std::size_t sz)                            { return new_ (sz, __cxxalignment); }
  void* operator new      (std::size_t sz, std::align_val_t al)       { return new_ (sz, al); }
  void* operator new[]    (std::size_t sz, std::align_val_t al)       { return new_ (sz, al); }
  // variants without size_t MUST NOT be defined for the following to be used
  void  operator delete   (void *ptr, std::size_t sz)                 { delete_ (ptr, sz, __cxxalignment); }
  void  operator delete[] (void *ptr, std::size_t sz)                 { delete_ (ptr, sz, __cxxalignment); }
  void  operator delete   (void *ptr, std::size_t sz, std::align_val_t al) { delete_ (ptr, sz, al); }
  void  operator delete[] (void *ptr, std::size_t sz, std::align_val_t al) { delete_ (ptr, sz, al); }
};

/// Internal allocator handle.
struct Allocator;
using AllocatorP = std::shared_ptr<Allocator>;

/// Reference for an allocated memory block.
struct Block {
  void  *const block_start = nullptr;
  const uint32 block_length = 0;
  Block& operator= (const Block &src) { this->~Block(); new (this) Block (src); return *this; }
  /*copy*/ Block   (const Block &src) = default;
  /*dflt*/ Block   () = default;
};

/// Memory area (over-)aligned to cache size and utilizing huge pages.
struct Arena {
  /// Create isolated memory area.
  explicit Arena     (uint32 mem_size, uint32 alignment = cache_line_size);
  /// Alignment for block addresses and length.
  size_t   alignment () const;
  /// Address of memory area.
  uint64   location  () const;
  /// Reserved memory area in bytes.
  uint64   reserved  () const;
  /// Create a memory block from cache-line aligned memory area, MT-Unsafe.
  Block    allocate  (uint32 length) const;
  Block    allocate  (uint32 length, std::nothrow_t) const;
  /// Realease a previously allocated block, MT-Unsafe.
  void     release   (Block allocatedblock) const;
protected:
  AllocatorP fma; ///< Identifier for the associated memory allocator.
  explicit Arena     (AllocatorP);
};

} // FastMemory

/// Compact, deduplicating string variant for constant strings that never need to be freed.
class CString {
  uint quark_ = 0;
public:
  using size_type = std::string::size_type;
  using const_iterator = std::string::const_iterator;
  using const_reference = std::string::const_reference;
  using const_reverse_iterator = std::string::const_reverse_iterator;
  /*ctor*/           CString     () noexcept                     = default;
  /*ctor*/           CString     (const char *c)                 { assign (c); }
  /*ctor*/           CString     (const char *c, size_type s)    { assign (c, s); }
  /*ctor*/           CString     (const std::string &s)          { assign (s); }
  /*copy*/           CString     (const CString&) noexcept       = default;
  /*move*/           CString     (CString&&) noexcept            = default;
  CString&           operator=   (const CString&) noexcept       = default;
  CString&           operator=   (CString&&) noexcept            = default;
  CString&           operator=   (const std::string &s)          { return assign (s); }
  CString&           operator=   (const char *c)                 { return assign (c); }
  CString&           operator=   (char ch)                       { return assign (std::addressof (ch), 1); }
  CString&           operator=   (std::initializer_list<char> l) { return assign (l.begin(), l.size()); }
  CString&           assign      (const CString &s)              { return this->operator= (s); }
  CString&           assign      (const std::string &s);
  CString&           assign      (const char *c, size_type s)   { return assign (std::string (c, s)); }
  CString&           assign      (const char *c)                { return assign (std::string (c)); }
  CString&           assign      (size_type count, char ch)     { return this->operator= (std::string (count, ch)); }
  const std::string& string      () const;
  const char*        c_str       () const noexcept      { return string().c_str(); }
  const char*        data        () const noexcept      { return string().data(); }
  const_reference    at          (size_type pos) const  { return string().at (pos); }
  const_reference    operator[]  (size_type pos) const  { return string().operator[] (pos); }
  size_type          capacity    () const noexcept      { return string().capacity(); }
  size_type          length      () const noexcept      { return string().length(); }
  bool               empty       () const noexcept      { return string().empty(); }
  size_type          size        () const noexcept      { return string().size(); }
  const_iterator     begin       () const noexcept      { return string().begin(); }
  const_iterator     cbegin      () const noexcept      { return string().cbegin(); }
  const_iterator     end         () const noexcept      { return string().end(); }
  const_iterator     cend        () const noexcept      { return string().cend(); }
  const_reverse_iterator rbegin  () const noexcept      { return string().rbegin(); }
  const_reverse_iterator crbegin () const noexcept      { return string().crbegin(); }
  const_reverse_iterator rend    () const noexcept      { return string().rend(); }
  const_reverse_iterator crend   () const noexcept      { return string().crend(); }
  /*conv*/  operator std::string () const noexcept      { return string(); }
  bool                 operator== (const CString &b) noexcept           { return quark_ == b.quark_; }
  bool                 operator== (const std::string &b) noexcept       { return string() == b; }
  bool                 operator== (const char *s) noexcept              { return string() == s; }
  bool                 operator!= (const CString &b) noexcept           { return quark_ != b.quark_; }
  bool                 operator!= (const std::string &b) noexcept       { return string() != b; }
  bool                 operator!= (const char *s) noexcept              { return string() != s; }
  bool                 operator<  (const CString &b) noexcept           { return string() < b.string(); }
  bool                 operator<  (const std::string &b) noexcept       { return string() < b; }
  bool                 operator<  (const char *s) noexcept              { return string() < s; }
  bool                 operator<= (const CString &b) noexcept           { return string() <= b.string(); }
  bool                 operator<= (const std::string &b) noexcept       { return string() <= b; }
  bool                 operator<= (const char *s) noexcept              { return string() <= s; }
  bool                 operator>  (const CString &b) noexcept           { return string() > b.string(); }
  bool                 operator>  (const std::string &b) noexcept       { return string() > b; }
  bool                 operator>  (const char *s) noexcept              { return string() > s; }
  bool                 operator>= (const CString &b) noexcept           { return string() >= b.string(); }
  bool                 operator>= (const std::string &b) noexcept       { return string() >= b; }
  bool                 operator>= (const char *s) noexcept              { return string() >= s; }
  friend std::ostream& operator<< (std::ostream &os, const CString &cs) { return os << cs.string(); }
  friend bool          operator== (const char *s, const CString &c)     { return s == c.string(); }
  friend bool          operator!= (const char *s, const CString &c)     { return s != c.string(); }
  friend bool          operator<  (const char *s, const CString &c)     { return s <  c.string(); }
  friend bool          operator<= (const char *s, const CString &c)     { return s <= c.string(); }
  friend bool          operator>  (const char *s, const CString &c)     { return s >  c.string(); }
  friend bool          operator>= (const char *s, const CString &c)     { return s >= c.string(); }
  friend bool          operator== (const std::string &s, const CString &c) { return s == c.string(); }
  friend bool          operator!= (const std::string &s, const CString &c) { return s != c.string(); }
  friend bool          operator<  (const std::string &s, const CString &c) { return s <  c.string(); }
  friend bool          operator<= (const std::string &s, const CString &c) { return s <= c.string(); }
  friend bool          operator>  (const std::string &s, const CString &c) { return s >  c.string(); }
  friend bool          operator>= (const std::string &s, const CString &c) { return s >= c.string(); }
  static CString       lookup     (const std::string &s);
  static const std::string::size_type npos = -1;
};

} // Bse

namespace std {
template<>
struct hash<::Bse::CString> {
  size_t operator() (const ::Bse::CString &cs) const
  {
    return ::std::hash<::std::string>{} (cs.string());
  }
};
} // std

#endif /* __BSE_MEMORY_HH__ */
<|endoftext|>


<commit_before>#include "frameview.h"
#include <QWheelEvent>
#include <QMimeData>
#include "gitlivkcmdevt.h"
#include <QDebug>
FrameView::FrameView(QWidget *parent) :
    QGraphicsView(parent)
{
    m_dCurrScale = 1.0;
    m_cGraphicsPixmapItem.setTransformationMode(Qt::FastTransformation);
    m_cGraphicsScene.addItem(&m_cGraphicsPixmapItem);
    setScene(&m_cGraphicsScene);
    setAcceptDrops(false); //avoid blocking drop event to QMainWindow
}
void FrameView::wheelEvent ( QWheelEvent * event )
{
    //AnalyzerMsgSender::getInstance()->msgOut(QString("%1").arg(event->delta()));
    int iDelta = event->delta();
    double dIncrement = 0;
    if( iDelta < 0 )
    {
        dIncrement = -0.2;
    }
    else
    {
        dIncrement = 0.2;
    }

    double dNextScale = m_dCurrScale + dIncrement;
    if( dNextScale < 0.1 )
    {
        /// scale limit
    }
    else
    {

        //AnalyzerMsgSender::getInstance()->msgOut(QString("%1").arg(dNextScale));
        GitlIvkCmdEvt cEvt("zoom_frame");
        cEvt.setParameter("scale", dNextScale);
        cEvt.dispatch();

        int iImgX = m_cGraphicsPixmapItem.scenePos().x();
        int iImgY = m_cGraphicsPixmapItem.scenePos().y();

        int iMouseX = mapToScene(event->pos()).x();
        int iMouseY = mapToScene(event->pos()).y();

        //AnalyzerMsgSender::getInstance()->msgOut(QString("%1 %2 %3 %4").arg(iImgX).arg(iImgY).arg(iMouseX).arg(iMouseY));

        m_cGraphicsPixmapItem.moveBy((iImgX-iMouseX)*dIncrement/m_dCurrScale,
                                     (iImgY-iMouseY)*dIncrement/m_dCurrScale);

        m_dCurrScale = dNextScale;

    }
}

void FrameView::mousePressEvent ( QMouseEvent * event )
{
    m_iMousePressX = event->x();
    m_iMousePressY = event->y();
    m_iMousePressImageX = m_cGraphicsPixmapItem.x();
    m_iMousePressImageY = m_cGraphicsPixmapItem.y();
}

void FrameView::mouseMoveEvent ( QMouseEvent * event )
{
    int iTransX = event->x() - m_iMousePressX;
    int iTransY = event->y() - m_iMousePressY;
    m_cGraphicsPixmapItem.setPos(m_iMousePressImageX+iTransX,
                                 m_iMousePressImageY+iTransY);
}

<commit_msg>fix mouse move inaccuracy problem<commit_after>#include "frameview.h"
#include <QWheelEvent>
#include <QMimeData>
#include "gitlivkcmdevt.h"
#include <QDebug>
FrameView::FrameView(QWidget *parent) :
    QGraphicsView(parent)
{
    m_dCurrScale = 1.0;
    m_cGraphicsPixmapItem.setTransformationMode(Qt::FastTransformation);
    m_cGraphicsScene.addItem(&m_cGraphicsPixmapItem);
    setScene(&m_cGraphicsScene);
    setAcceptDrops(false); //avoid blocking drop event to QMainWindow
}
void FrameView::wheelEvent ( QWheelEvent * event )
{
    //AnalyzerMsgSender::getInstance()->msgOut(QString("%1").arg(event->delta()));
    int iDelta = event->delta();
    double dIncrement = 0;
    if( iDelta < 0 )
    {
        dIncrement = -0.2;
    }
    else
    {
        dIncrement = 0.2;
    }

    double dNextScale = m_dCurrScale + dIncrement;
    if( dNextScale < 0.1 )
    {
        /// scale limit
    }
    else
    {

        //AnalyzerMsgSender::getInstance()->msgOut(QString("%1").arg(dNextScale));
        GitlIvkCmdEvt cEvt("zoom_frame");
        cEvt.setParameter("scale", dNextScale);
        cEvt.dispatch();

        int iImgX = m_cGraphicsPixmapItem.scenePos().x();
        int iImgY = m_cGraphicsPixmapItem.scenePos().y();

        int iMouseX = mapToScene(event->pos()).x();
        int iMouseY = mapToScene(event->pos()).y();

        //AnalyzerMsgSender::getInstance()->msgOut(QString("%1 %2 %3 %4").arg(iImgX).arg(iImgY).arg(iMouseX).arg(iMouseY));

        m_cGraphicsPixmapItem.moveBy((iImgX-iMouseX)*dIncrement/m_dCurrScale,
                                     (iImgY-iMouseY)*dIncrement/m_dCurrScale);

        m_dCurrScale = dNextScale;

    }
}

void FrameView::mousePressEvent ( QMouseEvent * event )
{
    m_iMousePressX = mapToScene(event->pos()).x();
    m_iMousePressY = mapToScene(event->pos()).y();
    m_iMousePressImageX = m_cGraphicsPixmapItem.x();
    m_iMousePressImageY = m_cGraphicsPixmapItem.y();
}

void FrameView::mouseMoveEvent ( QMouseEvent * event )
{
    int iTransX = mapToScene(event->pos()).x() - m_iMousePressX;
    int iTransY = mapToScene(event->pos()).y() - m_iMousePressY;
    m_cGraphicsPixmapItem.setPos(m_iMousePressImageX+iTransX,
                                 m_iMousePressImageY+iTransY);
}

<|endoftext|>