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

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

class Profile;

namespace {

const int kRightColumnWidth = 210;
const int kIconSize = 69;

// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
 public:
  InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
      Extension* extension, SkBitmap* icon, ExtensionInstallUI::PromptType type)
          : delegate_(delegate), icon_(NULL), type_(type) {
    // Scale down to icon size, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > kIconSize || size.height() > kIconSize)
      size = gfx::Size(kIconSize, kIconSize);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(ExtensionInstallUI::kHeadingIds[type_],
                              UTF8ToWide(extension->name())));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);
  }

 private:
  // DialogDelegate
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const {
    switch (button) {
      case MessageBoxFlags::DIALOGBUTTON_OK:
        return l10n_util::GetString(ExtensionInstallUI::kButtonIds[type_]);
      case MessageBoxFlags::DIALOGBUTTON_CANCEL:
        return l10n_util::GetString(IDS_CANCEL);
      default:
        NOTREACHED();
        return L"";
    }
  }

  virtual int GetDefaultDialogButton() const {
    return MessageBoxFlags::DIALOGBUTTON_CANCEL;
  }

  virtual bool Accept() {
    delegate_->InstallUIProceed();
    return true;
  }

  virtual bool Cancel() {
    delegate_->InstallUIAbort();
    return true;
  }

  // WindowDelegate
  virtual bool IsModal() const { return true; }
  virtual std::wstring GetWindowTitle() const {
    return l10n_util::GetString(ExtensionInstallUI::kTitleIds[type_]);
  }
  virtual views::View* GetContentsView() { return this; }

  // View
  virtual gfx::Size GetPreferredSize() {
    int width = kRightColumnWidth;
    width += kIconSize;
    width += kPanelHorizMargin * 3;

    int height = kPanelVertMargin * 2;
    height += heading_->GetHeightForWidth(kRightColumnWidth);

    return gfx::Size(width,
                     std::max(height, kIconSize + kPanelVertMargin * 2));
  }

  virtual void Layout() {
    int x = kPanelHorizMargin;
    int y = kPanelVertMargin;

    heading_->SizeToFit(kRightColumnWidth);

    if (heading_->height() <= kIconSize) {
      icon_->SetBounds(x, y, kIconSize, kIconSize);
      x += kIconSize;
      x += kPanelHorizMargin;

      heading_->SetX(x);
      heading_->SetY(y + (kIconSize - heading_->height()) / 2);
    } else {
      icon_->SetBounds(x,
                       y + (heading_->height() - kIconSize) / 2,
                       kIconSize,
                       kIconSize);
      x += kIconSize;
      x += kPanelHorizMargin;

      heading_->SetX(x);
      heading_->SetY(y);
    }
  }

  ExtensionInstallUI::Delegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  ExtensionInstallUI::PromptType type_;

  DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};

}  // namespace

// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    PromptType type) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindow* window = browser->window();
  if (!window) {
    delegate->InstallUIAbort();
    return;
  }

  views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
      new InstallDialogContent(delegate, extension, icon,
                               type))->Show();
}
<commit_msg>Use browser::CreateViewsWindow for ExtensionInstallUI.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/views/window.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

class Profile;

namespace {

const int kRightColumnWidth = 210;
const int kIconSize = 69;

// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
 public:
  InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
      Extension* extension, SkBitmap* icon, ExtensionInstallUI::PromptType type)
          : delegate_(delegate), icon_(NULL), type_(type) {
    // Scale down to icon size, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > kIconSize || size.height() > kIconSize)
      size = gfx::Size(kIconSize, kIconSize);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(ExtensionInstallUI::kHeadingIds[type_],
                              UTF8ToWide(extension->name())));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);
  }

 private:
  // DialogDelegate
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const {
    switch (button) {
      case MessageBoxFlags::DIALOGBUTTON_OK:
        return l10n_util::GetString(ExtensionInstallUI::kButtonIds[type_]);
      case MessageBoxFlags::DIALOGBUTTON_CANCEL:
        return l10n_util::GetString(IDS_CANCEL);
      default:
        NOTREACHED();
        return L"";
    }
  }

  virtual int GetDefaultDialogButton() const {
    return MessageBoxFlags::DIALOGBUTTON_CANCEL;
  }

  virtual bool Accept() {
    delegate_->InstallUIProceed();
    return true;
  }

  virtual bool Cancel() {
    delegate_->InstallUIAbort();
    return true;
  }

  // WindowDelegate
  virtual bool IsModal() const { return true; }
  virtual std::wstring GetWindowTitle() const {
    return l10n_util::GetString(ExtensionInstallUI::kTitleIds[type_]);
  }
  virtual views::View* GetContentsView() { return this; }

  // View
  virtual gfx::Size GetPreferredSize() {
    int width = kRightColumnWidth;
    width += kIconSize;
    width += kPanelHorizMargin * 3;

    int height = kPanelVertMargin * 2;
    height += heading_->GetHeightForWidth(kRightColumnWidth);

    return gfx::Size(width,
                     std::max(height, kIconSize + kPanelVertMargin * 2));
  }

  virtual void Layout() {
    int x = kPanelHorizMargin;
    int y = kPanelVertMargin;

    heading_->SizeToFit(kRightColumnWidth);

    if (heading_->height() <= kIconSize) {
      icon_->SetBounds(x, y, kIconSize, kIconSize);
      x += kIconSize;
      x += kPanelHorizMargin;

      heading_->SetX(x);
      heading_->SetY(y + (kIconSize - heading_->height()) / 2);
    } else {
      icon_->SetBounds(x,
                       y + (heading_->height() - kIconSize) / 2,
                       kIconSize,
                       kIconSize);
      x += kIconSize;
      x += kPanelHorizMargin;

      heading_->SetX(x);
      heading_->SetY(y);
    }
  }

  ExtensionInstallUI::Delegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  ExtensionInstallUI::PromptType type_;

  DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};

}  // namespace

// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    PromptType type) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindow* window = browser->window();
  if (!window) {
    delegate->InstallUIAbort();
    return;
  }

  browser::CreateViewsWindow(window->GetNativeHandle(), gfx::Rect(),
      new InstallDialogContent(delegate, extension, icon,
                               type))->Show();
}
<|endoftext|>


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

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

class Profile;

namespace {

// Since apps don't (currently) have any privilege disclosure text, the dialog
// looks a bit empty if it is sized the same as extensions. So we scale
// everything down a bit for apps for the time being.
const int kRightColumnWidthApp = 210;
const int kRightColumnWidthExtension = 270;
const int kIconSizeApp = 69;
const int kIconSizeExtension = 85;

// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
 public:
  InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
      Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
      bool is_uninstall)
          : delegate_(delegate), icon_(NULL), warning_(NULL),
            is_uninstall_(NULL), create_shortcut_(NULL) {
    if (extension->IsApp()) {
      icon_size_ = kIconSizeApp;
      right_column_width_ = kRightColumnWidthApp;
    } else {
      icon_size_ = kIconSizeExtension;
      right_column_width_ = kRightColumnWidthExtension;
    }

    // Scale down to icon size, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > icon_size_ || size.height() > icon_size_)
      size = gfx::Size(icon_size_, icon_size_);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(is_uninstall ?
                                  IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
                                  IDS_EXTENSION_INSTALL_PROMPT_HEADING,
                              UTF8ToWide(extension->name())));
    heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);

    if (!is_uninstall && extension->IsApp()) {
      create_shortcut_ = new views::Checkbox(
          l10n_util::GetString(IDS_EXTENSION_PROMPT_CREATE_SHORTCUT));
      create_shortcut_->SetChecked(true);
      create_shortcut_->SetMultiLine(true);
      AddChildView(create_shortcut_);
    } else {
      warning_ = new views::Label(warning_text);
      warning_->SetMultiLine(true);
      warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
      AddChildView(warning_);
    }
  }

 private:
  // DialogDelegate
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const {
    switch (button) {
      case MessageBoxFlags::DIALOGBUTTON_OK:
        if (is_uninstall_)
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
        else
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
      case MessageBoxFlags::DIALOGBUTTON_CANCEL:
        return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
      default:
        NOTREACHED();
        return L"";
    }
  }

  virtual int GetDefaultDialogButton() const {
    return MessageBoxFlags::DIALOGBUTTON_CANCEL;
  }

  virtual bool Accept() {
    delegate_->InstallUIProceed(
        create_shortcut_ && create_shortcut_->checked());
    return true;
  }

  virtual bool Cancel() {
    delegate_->InstallUIAbort();
    return true;
  }

  // WindowDelegate
  virtual bool IsModal() const { return true; }
  virtual std::wstring GetWindowTitle() const {
    if (is_uninstall_)
      return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
    else
      return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
  }
  virtual views::View* GetContentsView() { return this; }

  // View
  virtual gfx::Size GetPreferredSize() {
    int width = right_column_width_ + kPanelHorizMargin + kPanelHorizMargin;
    width += icon_size_;
    width += kPanelHorizMargin;

    int height = kPanelVertMargin * 2;
    height += heading_->GetHeightForWidth(right_column_width_);
    height += kPanelVertMargin;

    if (warning_)
      height += warning_->GetHeightForWidth(right_column_width_);
    else
      height += create_shortcut_->GetPreferredSize().height();

    height += kPanelVertMargin;

    return gfx::Size(width, std::max(height, icon_size_ + kPanelVertMargin * 2));
  }

  virtual void Layout() {
    int x = kPanelHorizMargin;
    int y = kPanelVertMargin;

    icon_->SetBounds(x, y, icon_size_, icon_size_);
    x += icon_size_;
    x += kPanelHorizMargin;

    heading_->SizeToFit(right_column_width_);
    heading_->SetX(x);
    heading_->SetY(y);
    y += heading_->height();

    y += kPanelVertMargin;

    if (create_shortcut_) {
      create_shortcut_->SetBounds(x, y, right_column_width_, 0);
      create_shortcut_->SetBounds(x, y, right_column_width_,
          create_shortcut_->GetPreferredSize().height());

      int bottom_aligned = icon_->y() + icon_->height() -
          create_shortcut_->height();
      if (bottom_aligned > y) {
        create_shortcut_->SetY(bottom_aligned);
        y = bottom_aligned;
      }
      y += create_shortcut_->height();
    } else {
      warning_->SizeToFit(right_column_width_);
      warning_->SetX(x);
      warning_->SetY(y);
      y += warning_->height();
    }

    y += kPanelVertMargin;
  }

  ExtensionInstallUI::Delegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* warning_;
  views::Checkbox* create_shortcut_;
  bool is_uninstall_;
  int right_column_width_;
  int icon_size_;

  DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};

}  // namespace

// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    const string16& warning_text, bool is_uninstall) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindow* window = browser->window();
  if (!window) {
    delegate->InstallUIAbort();
    return;
  }

  views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
      new InstallDialogContent(delegate, extension, icon,
                               UTF16ToWideHack(warning_text),
                               is_uninstall))->Show();
}
<commit_msg>Fix compile error from 36513.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

class Profile;

namespace {

// Since apps don't (currently) have any privilege disclosure text, the dialog
// looks a bit empty if it is sized the same as extensions. So we scale
// everything down a bit for apps for the time being.
const int kRightColumnWidthApp = 210;
const int kRightColumnWidthExtension = 270;
const int kIconSizeApp = 69;
const int kIconSizeExtension = 85;

// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
 public:
  InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
      Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
      bool is_uninstall)
          : delegate_(delegate), icon_(NULL), warning_(NULL),
            create_shortcut_(NULL), is_uninstall_(false) {
    if (extension->IsApp()) {
      icon_size_ = kIconSizeApp;
      right_column_width_ = kRightColumnWidthApp;
    } else {
      icon_size_ = kIconSizeExtension;
      right_column_width_ = kRightColumnWidthExtension;
    }

    // Scale down to icon size, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > icon_size_ || size.height() > icon_size_)
      size = gfx::Size(icon_size_, icon_size_);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(is_uninstall ?
                                  IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
                                  IDS_EXTENSION_INSTALL_PROMPT_HEADING,
                              UTF8ToWide(extension->name())));
    heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);

    if (!is_uninstall && extension->IsApp()) {
      create_shortcut_ = new views::Checkbox(
          l10n_util::GetString(IDS_EXTENSION_PROMPT_CREATE_SHORTCUT));
      create_shortcut_->SetChecked(true);
      create_shortcut_->SetMultiLine(true);
      AddChildView(create_shortcut_);
    } else {
      warning_ = new views::Label(warning_text);
      warning_->SetMultiLine(true);
      warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
      AddChildView(warning_);
    }
  }

 private:
  // DialogDelegate
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const {
    switch (button) {
      case MessageBoxFlags::DIALOGBUTTON_OK:
        if (is_uninstall_)
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
        else
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
      case MessageBoxFlags::DIALOGBUTTON_CANCEL:
        return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
      default:
        NOTREACHED();
        return L"";
    }
  }

  virtual int GetDefaultDialogButton() const {
    return MessageBoxFlags::DIALOGBUTTON_CANCEL;
  }

  virtual bool Accept() {
    delegate_->InstallUIProceed(
        create_shortcut_ && create_shortcut_->checked());
    return true;
  }

  virtual bool Cancel() {
    delegate_->InstallUIAbort();
    return true;
  }

  // WindowDelegate
  virtual bool IsModal() const { return true; }
  virtual std::wstring GetWindowTitle() const {
    if (is_uninstall_)
      return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
    else
      return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
  }
  virtual views::View* GetContentsView() { return this; }

  // View
  virtual gfx::Size GetPreferredSize() {
    int width = right_column_width_ + kPanelHorizMargin + kPanelHorizMargin;
    width += icon_size_;
    width += kPanelHorizMargin;

    int height = kPanelVertMargin * 2;
    height += heading_->GetHeightForWidth(right_column_width_);
    height += kPanelVertMargin;

    if (warning_)
      height += warning_->GetHeightForWidth(right_column_width_);
    else
      height += create_shortcut_->GetPreferredSize().height();

    height += kPanelVertMargin;

    return gfx::Size(width, std::max(height, icon_size_ + kPanelVertMargin * 2));
  }

  virtual void Layout() {
    int x = kPanelHorizMargin;
    int y = kPanelVertMargin;

    icon_->SetBounds(x, y, icon_size_, icon_size_);
    x += icon_size_;
    x += kPanelHorizMargin;

    heading_->SizeToFit(right_column_width_);
    heading_->SetX(x);
    heading_->SetY(y);
    y += heading_->height();

    y += kPanelVertMargin;

    if (create_shortcut_) {
      create_shortcut_->SetBounds(x, y, right_column_width_, 0);
      create_shortcut_->SetBounds(x, y, right_column_width_,
          create_shortcut_->GetPreferredSize().height());

      int bottom_aligned = icon_->y() + icon_->height() -
          create_shortcut_->height();
      if (bottom_aligned > y) {
        create_shortcut_->SetY(bottom_aligned);
        y = bottom_aligned;
      }
      y += create_shortcut_->height();
    } else {
      warning_->SizeToFit(right_column_width_);
      warning_->SetX(x);
      warning_->SetY(y);
      y += warning_->height();
    }

    y += kPanelVertMargin;
  }

  ExtensionInstallUI::Delegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* warning_;
  views::Checkbox* create_shortcut_;
  bool is_uninstall_;
  int right_column_width_;
  int icon_size_;

  DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};

}  // namespace

// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    const string16& warning_text, bool is_uninstall) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindow* window = browser->window();
  if (!window) {
    delegate->InstallUIAbort();
    return;
  }

  views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
      new InstallDialogContent(delegate, extension, icon,
                               UTF16ToWideHack(warning_text),
                               is_uninstall))->Show();
}
<|endoftext|>


<commit_before>#include "WindowDX.h"

vector<bool> WindowDX::keys;
int	WindowDX::mouseDeltaX;
int	WindowDX::mouseDeltaY;
HWND WindowDX::hWnd;

WindowDX::WindowDX(HINSTANCE hInstance, int cmdShow)
{
	this->hInstance = hInstance;
	this->cmdShow = cmdShow;

	this->active = true;

	keys.resize(NUM_KEYS, false);

	SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}

WindowDX::~WindowDX()
{
	ReleaseCapture();
	ShowCursor(true);
}

LRESULT CALLBACK WindowDX::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_DESTROY:
		{
			PostQuitMessage(0);
			return 0;
		}break;

	case WM_KEYDOWN:
		{
			if(wParam == VK_ESCAPE)
			{
				DestroyWindow(hWnd);
			}

			keys[wParam] = true;

			return 0;
		}break;

	case WM_KEYUP:
		{
			keys[wParam] = false;

			return 0;
		}break;

	case WM_MOUSEMOVE:
		{
			//mouseDeltaMove(lParam);
			return 0;
		}break;

	}

	return DefWindowProc(hWnd, message, wParam, lParam);
}

void WindowDX::createWindow()
{
	WNDCLASSEX wc;

	ZeroMemory(&wc, sizeof(WNDCLASSEX));

	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WindowProc;
	wc.hInstance = hInstance;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.lpszClassName = "WindowClass";

	RegisterClassEx(&wc);

	hWnd = CreateWindowEx(NULL,
		"WindowClass",
		"PACMANIA",
		WS_OVERLAPPEDWINDOW,
		100,
		100,
		SCREEN_WIDTH,
		SCREEN_HEIGHT,
		NULL,
		NULL,
		hInstance,
		NULL);

	ShowWindow(hWnd, cmdShow);
}

void WindowDX::initCursor()
{
	SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
	SetCapture(hWnd);
	ShowCursor(false);
}

void WindowDX::init()
{
	createWindow();
	initCursor();

	MsgDXWindowHandle* msg = new MsgDXWindowHandle(&hWnd);
	Singleton<ObserverDirector>::get().push(msg);
}

void WindowDX::update(double delta)
{
	//Returns true if the applications is to be destroyed

	//bool quit = false;

	MSG msg = {0};

	if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);

		if(msg.message == WM_QUIT)
			active = false;
	}

	//return quit;
}

HWND WindowDX::getWindowHandle()
{
	return hWnd;
}

bool WindowDX::isActive()
{
	return active;
}<commit_msg>Added a function mouseDeltaMove that records mouse movement<commit_after>#include "WindowDX.h"

vector<bool> WindowDX::keys;
int	WindowDX::mouseDeltaX;
int	WindowDX::mouseDeltaY;
HWND WindowDX::hWnd;

WindowDX::WindowDX(HINSTANCE hInstance, int cmdShow)
{
	this->hInstance = hInstance;
	this->cmdShow = cmdShow;

	this->active = true;

	keys.resize(NUM_KEYS, false);

	SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}

WindowDX::~WindowDX()
{
	ReleaseCapture();
	ShowCursor(true);
}

void WindowDX::mouseDeltaMove(LPARAM lParam)
{
	//Find the upper left corner of the window's client area in screen coordinates
	POINT point;
	point.x = 0;
	point.y = 0;
	MapWindowPoints(hWnd, NULL, &point, 1);

	//Get current mouse position
	int mouseX = GET_X_LPARAM(lParam)+point.x;
	int mouseY = GET_Y_LPARAM(lParam)+point.y;

	//Calculate relative mouse movement
	mouseDeltaX = mouseX - SCREEN_WIDTH/2;
	mouseDeltaY = mouseY - SCREEN_HEIGHT/2;

	//Return cursor to screen center
	SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}

LRESULT CALLBACK WindowDX::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_DESTROY:
		{
			PostQuitMessage(0);
			return 0;
		}break;

	case WM_KEYDOWN:
		{
			if(wParam == VK_ESCAPE)
			{
				DestroyWindow(hWnd);
			}

			keys[wParam] = true;

			return 0;
		}break;

	case WM_KEYUP:
		{
			keys[wParam] = false;

			return 0;
		}break;

	case WM_MOUSEMOVE:
		{
			mouseDeltaMove(lParam);
			return 0;
		}break;

	}

	return DefWindowProc(hWnd, message, wParam, lParam);
}

void WindowDX::createWindow()
{
	WNDCLASSEX wc;

	ZeroMemory(&wc, sizeof(WNDCLASSEX));

	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WindowProc;
	wc.hInstance = hInstance;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.lpszClassName = "WindowClass";

	RegisterClassEx(&wc);

	hWnd = CreateWindowEx(NULL,
		"WindowClass",
		"PACMANIA",
		WS_OVERLAPPEDWINDOW,
		100,
		100,
		SCREEN_WIDTH,
		SCREEN_HEIGHT,
		NULL,
		NULL,
		hInstance,
		NULL);

	ShowWindow(hWnd, cmdShow);
}

void WindowDX::initCursor()
{
	SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
	SetCapture(hWnd);
	ShowCursor(false);
}

void WindowDX::init()
{
	createWindow();
	initCursor();

	MsgDXWindowHandle* msg = new MsgDXWindowHandle(&hWnd);
	Singleton<ObserverDirector>::get().push(msg);
}

void WindowDX::update(double delta)
{
	//Returns true if the applications is to be destroyed

	//bool quit = false;

	MSG msg = {0};

	if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);

		if(msg.message == WM_QUIT)
			active = false;
	}

	//return quit;
}

HWND WindowDX::getWindowHandle()
{
	return hWnd;
}

bool WindowDX::isActive()
{
	return active;
}<|endoftext|>


<commit_before>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

HadesMem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

HadesMem 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with HadesMem.  If not, see <http://www.gnu.org/licenses/>.
*/

// Hades
#include "Loader.hpp"
#include "HadesCommon/Logger.hpp"

namespace Hades
{
  namespace Kernel
  {
    Kernel* Loader::m_pKernel = nullptr;
    std::shared_ptr<Hades::Memory::PatchDetour> Loader::m_pCreateProcessInternalWHk;

    void Loader::Initialize(Kernel& MyKernel)
    {
      m_pKernel = &MyKernel;
    }

    void Loader::Hook()
    {
      HMODULE Kernel32Mod = GetModuleHandle(L"kernel32.dll");
      if (!Kernel32Mod)
      {
        std::error_code const LastError = GetLastErrorCode();
        BOOST_THROW_EXCEPTION(Error() <<
          ErrorFunction("Loader::Hook") <<
          ErrorString("Could not find Kernel32.dll") <<
          ErrorCode(LastError));
      }

      FARPROC const pCreateProcessInternalW = GetProcAddress(Kernel32Mod,
        "CreateProcessInternalW");
      if (!pCreateProcessInternalW)
      {
        std::error_code const LastError = GetLastErrorCode();
        BOOST_THROW_EXCEPTION(Error() <<
          ErrorFunction("Loader::Hook") <<
          ErrorString("Could not find Kernel32!CreateProcessInternalW") <<
          ErrorCode(LastError));
      }

      HADES_LOG_THREAD_SAFE(std::wcout << boost::wformat(L"Loader::"
        L"Hook: pCreateProcessInternalW = %p.") %pCreateProcessInternalW
        << std::endl);

      Memory::MemoryMgr const MyMemory(GetCurrentProcessId());
      m_pCreateProcessInternalWHk.reset(new Memory::PatchDetour(MyMemory,
        pCreateProcessInternalW, &CreateProcessInternalW_Hook));
      m_pCreateProcessInternalWHk->Apply();
    }

    void Loader::Unhook()
    {
      if (m_pCreateProcessInternalWHk)
      {
        m_pCreateProcessInternalWHk->Remove();
      }
    }

    BOOL WINAPI Loader::CreateProcessInternalW_Hook(
      HANDLE hToken,
      LPCWSTR lpApplicationName,
      LPWSTR lpCommandLine,
      LPSECURITY_ATTRIBUTES lpProcessAttributes,
      LPSECURITY_ATTRIBUTES lpThreadAttributes,
      BOOL bInheritHandles,
      DWORD dwCreationFlags,
      LPVOID lpEnvironment,
      LPCWSTR lpCurrentDirectory,
      LPSTARTUPINFOW lpStartupInfo,
      LPPROCESS_INFORMATION lpProcessInformation,
      PHANDLE hNewToken)
    {
      HADES_LOG_THREAD_SAFE(std::wcout <<
        "Loader::CreateProcessInternalW_Hook: Called." << std::endl);

      typedef BOOL (WINAPI* tCreateProcessInternalW)(
        HANDLE hToken,
        LPCWSTR lpApplicationName,
        LPWSTR lpCommandLine,
        LPSECURITY_ATTRIBUTES lpProcessAttributes,
        LPSECURITY_ATTRIBUTES lpThreadAttributes,
        BOOL bInheritHandles,
        DWORD dwCreationFlags,
        LPVOID lpEnvironment,
        LPCWSTR lpCurrentDirectory,
        LPSTARTUPINFOW lpStartupInfo,
        LPPROCESS_INFORMATION lpProcessInformation,
        PHANDLE hNewToken);
      auto pCreateProcessInternalW = reinterpret_cast<tCreateProcessInternalW>(
        m_pCreateProcessInternalWHk->GetTrampoline());

      return pCreateProcessInternalW(hToken, lpApplicationName, lpCommandLine,
        lpProcessAttributes, lpThreadAttributes, bInheritHandles,
        dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo,
        lpProcessInformation, hNewToken);
    }
  }
}
<commit_msg>* Note to self.<commit_after>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

HadesMem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

HadesMem 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with HadesMem.  If not, see <http://www.gnu.org/licenses/>.
*/

// Hades
#include "Loader.hpp"
#include "HadesCommon/Logger.hpp"

namespace Hades
{
  namespace Kernel
  {
    // Todo: Hook other process creation APIs such as ShellExecuteEx after
    // confirming they don't use already hooked APIs internally.

    Kernel* Loader::m_pKernel = nullptr;
    std::shared_ptr<Hades::Memory::PatchDetour> Loader::m_pCreateProcessInternalWHk;

    void Loader::Initialize(Kernel& MyKernel)
    {
      m_pKernel = &MyKernel;
    }

    void Loader::Hook()
    {
      HMODULE Kernel32Mod = GetModuleHandle(L"kernel32.dll");
      if (!Kernel32Mod)
      {
        std::error_code const LastError = GetLastErrorCode();
        BOOST_THROW_EXCEPTION(Error() <<
          ErrorFunction("Loader::Hook") <<
          ErrorString("Could not find Kernel32.dll") <<
          ErrorCode(LastError));
      }

      FARPROC const pCreateProcessInternalW = GetProcAddress(Kernel32Mod,
        "CreateProcessInternalW");
      if (!pCreateProcessInternalW)
      {
        std::error_code const LastError = GetLastErrorCode();
        BOOST_THROW_EXCEPTION(Error() <<
          ErrorFunction("Loader::Hook") <<
          ErrorString("Could not find Kernel32!CreateProcessInternalW") <<
          ErrorCode(LastError));
      }

      HADES_LOG_THREAD_SAFE(std::wcout << boost::wformat(L"Loader::"
        L"Hook: pCreateProcessInternalW = %p.") %pCreateProcessInternalW
        << std::endl);

      Memory::MemoryMgr const MyMemory(GetCurrentProcessId());
      m_pCreateProcessInternalWHk.reset(new Memory::PatchDetour(MyMemory,
        pCreateProcessInternalW, &CreateProcessInternalW_Hook));
      m_pCreateProcessInternalWHk->Apply();
    }

    void Loader::Unhook()
    {
      if (m_pCreateProcessInternalWHk)
      {
        m_pCreateProcessInternalWHk->Remove();
      }
    }

    BOOL WINAPI Loader::CreateProcessInternalW_Hook(
      HANDLE hToken,
      LPCWSTR lpApplicationName,
      LPWSTR lpCommandLine,
      LPSECURITY_ATTRIBUTES lpProcessAttributes,
      LPSECURITY_ATTRIBUTES lpThreadAttributes,
      BOOL bInheritHandles,
      DWORD dwCreationFlags,
      LPVOID lpEnvironment,
      LPCWSTR lpCurrentDirectory,
      LPSTARTUPINFOW lpStartupInfo,
      LPPROCESS_INFORMATION lpProcessInformation,
      PHANDLE hNewToken)
    {
      HADES_LOG_THREAD_SAFE(std::wcout <<
        "Loader::CreateProcessInternalW_Hook: Called." << std::endl);

      typedef BOOL (WINAPI* tCreateProcessInternalW)(
        HANDLE hToken,
        LPCWSTR lpApplicationName,
        LPWSTR lpCommandLine,
        LPSECURITY_ATTRIBUTES lpProcessAttributes,
        LPSECURITY_ATTRIBUTES lpThreadAttributes,
        BOOL bInheritHandles,
        DWORD dwCreationFlags,
        LPVOID lpEnvironment,
        LPCWSTR lpCurrentDirectory,
        LPSTARTUPINFOW lpStartupInfo,
        LPPROCESS_INFORMATION lpProcessInformation,
        PHANDLE hNewToken);
      auto pCreateProcessInternalW = reinterpret_cast<tCreateProcessInternalW>(
        m_pCreateProcessInternalWHk->GetTrampoline());

      return pCreateProcessInternalW(hToken, lpApplicationName, lpCommandLine,
        lpProcessAttributes, lpThreadAttributes, bInheritHandles,
        dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo,
        lpProcessInformation, hNewToken);
    }
  }
}
<|endoftext|>


<commit_before>//
// Created by Ulrich Eck on 20/07/16.
//

#ifdef WIN32
#include <utUtil/CleanWindows.h>
#endif

#include <utVision/TextureUpdate.h>

#include <utVision/OpenCLManager.h>
#include <utUtil/Exception.h>

#include <GL/glut.h>

#include <log4cpp/Category.hh>

// get a logger
static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.TextureUpdate" ) );

namespace Ubitrack {
namespace Vision {

bool TextureUpdate::getImageFormat(const Measurement::ImageMeasurement& image, bool use_gpu, int& umatConvertCode,
        GLenum& imgFormat, int& numOfChannels)
{
    bool ret = true;
    switch (image->pixelFormat()) {
    case Image::LUMINANCE:
        imgFormat = GL_LUMINANCE;
        numOfChannels = 1;
        break;
    case Image::RGB:
        numOfChannels = use_gpu ? 4 : 3;
        imgFormat = use_gpu ? GL_RGBA : GL_RGB;
        umatConvertCode = cv::COLOR_RGB2RGBA;
        break;
#ifndef GL_BGR_EXT
    case Image::BGR:
        imgFormat = image_isOnGPU ? GL_RGBA : GL_RGB;
        numOfChannels = use_gpu ? 4 : 3;
        umatConvertCode = cv::COLOR_BGR2RGBA;
        break;
    case Image::BGRA:
        numOfChannels = 4;
        imgFormat = use_gpu ? GL_RGBA : GL_BGRA;
        umatConvertCode = cv::COLOR_BGRA2RGBA;
        break;
#else
        case Image::BGR:
        numOfChannels = use_gpu ? 4 : 3;
        imgFormat = use_gpu ? GL_RGBA : GL_BGR_EXT;
        umatConvertCode = cv::COLOR_BGR2RGBA;
        break;
    case Image::BGRA:
        numOfChannels = 4;
        imgFormat = use_gpu ? GL_RGBA : GL_BGRA_EXT;
        umatConvertCode = cv::COLOR_BGRA2RGBA;
        break;
#endif
    case Image::RGBA:
        numOfChannels = 4;
        imgFormat = GL_RGBA;
        break;
    default:
        // Log Error ?
        ret = false;
        break;
    }
    return ret;
}

void TextureUpdate::cleanupTexture() {
    if (m_bTextureInitialized ) {
        glBindTexture( GL_TEXTURE_2D, 0 );
        glDisable( GL_TEXTURE_2D );
        glDeleteTextures( 1, &(m_texture) );
    }
}

void TextureUpdate::initializeTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
   // access OCL Manager and initialize if needed
    Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();

    if (!image) {
        // LOG4CPP_WARN ??
        return;
    }

    // if OpenCL is enabled and image is on GPU, then use OCL codepath
    bool image_isOnGPU = oclManager.isEnabled() & image->isOnGPU();

    // find out texture format
    int umatConvertCode = -1;
    GLenum imgFormat = GL_LUMINANCE;
    int numOfChannels = 1;
    getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);

    if ( !m_bTextureInitialized )
    {

        // generate power-of-two sizes
        m_pow2Width = 1;
        while ( m_pow2Width < (unsigned)image->width() )
            m_pow2Width <<= 1;

        m_pow2Height = 1;
        while ( m_pow2Height < (unsigned)image->height() )
            m_pow2Height <<= 1;

        glGenTextures( 1, &(m_texture) );
        glBindTexture( GL_TEXTURE_2D, m_texture );

        // define texture parameters
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );

        // load empty texture image (defines texture size)
        glTexImage2D( GL_TEXTURE_2D, 0, numOfChannels, m_pow2Width, m_pow2Height, 0, imgFormat, GL_UNSIGNED_BYTE, 0 );
        LOG4CPP_DEBUG( logger, "glTexImage2D( width=" << m_pow2Width << ", height=" << m_pow2Height << " ): " << glGetError() );
        LOG4CPP_INFO( logger, "initalized texture ( " << imgFormat << " ) OnGPU: " << image_isOnGPU);

        if (oclManager.isInitialized()) {

#ifdef HAVE_OPENCL
            //Get an image Object from the OpenGL texture
            cl_int err;
// windows specific or opencl version specific ??
#ifdef WIN32
            m_clImage = clCreateFromGLTexture2D( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#else
            m_clImage = clCreateFromGLTexture( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#endif
            if (err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clCreateFromGLTexture2D:" << err );
            }
#endif
        }
        m_bTextureInitialized = true;
    }
#endif // HAVE_OPENCV
}

/*
 * Update Texture - requires valid OpenGL Context
 */
void TextureUpdate::updateTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
    // access OCL Manager and initialize if needed
    Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();

    if (!image) {
        // LOG4CPP_WARN ??
        return;
    }

    // if OpenCL is enabled and image is on GPU, then use OCL codepath
    bool image_isOnGPU = oclManager.isInitialized() & image->isOnGPU();

    if ( m_bTextureInitialized )
    {
        // check if received image fits into the allocated texture

        // find out texture format
        int umatConvertCode = -1;
        GLenum imgFormat = GL_LUMINANCE;
        int numOfChannels = 1;
        getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);

        if (image_isOnGPU) {
#ifdef HAVE_OPENCL

            glBindTexture( GL_TEXTURE_2D, m_texture );

            if (umatConvertCode != -1) {
                cv::cvtColor(image->uMat(), m_convertedImage, umatConvertCode );
            } else {
                m_convertedImage = image->uMat();
            }

            cv::ocl::finish();
            glFinish();

            cl_command_queue commandQueue = oclManager.getCommandQueue();
            cl_int err;

            clFinish(commandQueue);

            err = clEnqueueAcquireGLObjects(commandQueue, 1, &(m_clImage), 0, NULL, NULL);
            if(err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clEnqueueAcquireGLObjects:" << err );
            }

            cl_mem clBuffer = (cl_mem) m_convertedImage.handle(cv::ACCESS_READ);
            cl_command_queue cv_ocl_queue = (cl_command_queue)cv::ocl::Queue::getDefault().ptr();

            size_t offset = 0;
            size_t dst_origin[3] = {0, 0, 0};
            size_t region[3] = {static_cast<size_t>(m_convertedImage.cols), static_cast<size_t>(m_convertedImage.rows), 1};

            err = clEnqueueCopyBufferToImage(cv_ocl_queue, clBuffer, m_clImage, offset, dst_origin, region, 0, NULL, NULL);
            if (err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clEnqueueCopyBufferToImage:" << err );
            }

            err = clEnqueueReleaseGLObjects(commandQueue, 1, &m_clImage, 0, NULL, NULL);
            if(err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clEnqueueReleaseGLObjects:" << err );
            }
            cv::ocl::finish();

#else // HAVE_OPENCL
            LOG4CPP_ERROR( logger, "Image isOnGPU but OpenCL is disabled!!");
#endif // HAVE_OPENCL
        } else {
            // load image from CPU buffer into texture
            glBindTexture( GL_TEXTURE_2D, m_texture );
            glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, image->width(), image->height(),
                    imgFormat, GL_UNSIGNED_BYTE, image->Mat().data );

        }

    }
#endif // HAVE_OPENCV
}

}} // Ubitrack::Vision<commit_msg>remove glut dependency - was unused<commit_after>//
// Created by Ulrich Eck on 20/07/16.
//

#ifdef WIN32
#include <utUtil/CleanWindows.h>
#endif

#include <utVision/TextureUpdate.h>

#include <utVision/OpenCLManager.h>
#include <utUtil/Exception.h>

#include <log4cpp/Category.hh>

#ifdef _WIN32
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <utUtil/CleanWindows.h>
#elif __APPLE__
    #include <OpenGL/OpenGL.h>
    #include <OpenGL/glu.h>
#else
    #include <GL/gl.h>
    #include <GL/glu.h>
    #include <GL/glx.h>
#endif

// get a logger
static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.TextureUpdate" ) );

namespace Ubitrack {
namespace Vision {

bool TextureUpdate::getImageFormat(const Measurement::ImageMeasurement& image, bool use_gpu, int& umatConvertCode,
        GLenum& imgFormat, int& numOfChannels)
{
    bool ret = true;
    switch (image->pixelFormat()) {
    case Image::LUMINANCE:
        imgFormat = GL_LUMINANCE;
        numOfChannels = 1;
        break;
    case Image::RGB:
        numOfChannels = use_gpu ? 4 : 3;
        imgFormat = use_gpu ? GL_RGBA : GL_RGB;
        umatConvertCode = cv::COLOR_RGB2RGBA;
        break;
#ifndef GL_BGR_EXT
    case Image::BGR:
        imgFormat = image_isOnGPU ? GL_RGBA : GL_RGB;
        numOfChannels = use_gpu ? 4 : 3;
        umatConvertCode = cv::COLOR_BGR2RGBA;
        break;
    case Image::BGRA:
        numOfChannels = 4;
        imgFormat = use_gpu ? GL_RGBA : GL_BGRA;
        umatConvertCode = cv::COLOR_BGRA2RGBA;
        break;
#else
        case Image::BGR:
        numOfChannels = use_gpu ? 4 : 3;
        imgFormat = use_gpu ? GL_RGBA : GL_BGR_EXT;
        umatConvertCode = cv::COLOR_BGR2RGBA;
        break;
    case Image::BGRA:
        numOfChannels = 4;
        imgFormat = use_gpu ? GL_RGBA : GL_BGRA_EXT;
        umatConvertCode = cv::COLOR_BGRA2RGBA;
        break;
#endif
    case Image::RGBA:
        numOfChannels = 4;
        imgFormat = GL_RGBA;
        break;
    default:
        // Log Error ?
        ret = false;
        break;
    }
    return ret;
}

void TextureUpdate::cleanupTexture() {
    if (m_bTextureInitialized ) {
        glBindTexture( GL_TEXTURE_2D, 0 );
        glDisable( GL_TEXTURE_2D );
        glDeleteTextures( 1, &(m_texture) );
    }
}

void TextureUpdate::initializeTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
   // access OCL Manager and initialize if needed
    Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();

    if (!image) {
        // LOG4CPP_WARN ??
        return;
    }

    // if OpenCL is enabled and image is on GPU, then use OCL codepath
    bool image_isOnGPU = oclManager.isEnabled() & image->isOnGPU();

    // find out texture format
    int umatConvertCode = -1;
    GLenum imgFormat = GL_LUMINANCE;
    int numOfChannels = 1;
    getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);

    if ( !m_bTextureInitialized )
    {

        // generate power-of-two sizes
        m_pow2Width = 1;
        while ( m_pow2Width < (unsigned)image->width() )
            m_pow2Width <<= 1;

        m_pow2Height = 1;
        while ( m_pow2Height < (unsigned)image->height() )
            m_pow2Height <<= 1;

        glGenTextures( 1, &(m_texture) );
        glBindTexture( GL_TEXTURE_2D, m_texture );

        // define texture parameters
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );

        // load empty texture image (defines texture size)
        glTexImage2D( GL_TEXTURE_2D, 0, numOfChannels, m_pow2Width, m_pow2Height, 0, imgFormat, GL_UNSIGNED_BYTE, 0 );
        LOG4CPP_DEBUG( logger, "glTexImage2D( width=" << m_pow2Width << ", height=" << m_pow2Height << " ): " << glGetError() );
        LOG4CPP_INFO( logger, "initalized texture ( " << imgFormat << " ) OnGPU: " << image_isOnGPU);

        if (oclManager.isInitialized()) {

#ifdef HAVE_OPENCL
            //Get an image Object from the OpenGL texture
            cl_int err;
// windows specific or opencl version specific ??
#ifdef WIN32
            m_clImage = clCreateFromGLTexture2D( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#else
            m_clImage = clCreateFromGLTexture( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#endif
            if (err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clCreateFromGLTexture2D:" << err );
            }
#endif
        }
        m_bTextureInitialized = true;
    }
#endif // HAVE_OPENCV
}

/*
 * Update Texture - requires valid OpenGL Context
 */
void TextureUpdate::updateTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
    // access OCL Manager and initialize if needed
    Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();

    if (!image) {
        // LOG4CPP_WARN ??
        return;
    }

    // if OpenCL is enabled and image is on GPU, then use OCL codepath
    bool image_isOnGPU = oclManager.isInitialized() & image->isOnGPU();

    if ( m_bTextureInitialized )
    {
        // check if received image fits into the allocated texture

        // find out texture format
        int umatConvertCode = -1;
        GLenum imgFormat = GL_LUMINANCE;
        int numOfChannels = 1;
        getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);

        if (image_isOnGPU) {
#ifdef HAVE_OPENCL

            glBindTexture( GL_TEXTURE_2D, m_texture );

            if (umatConvertCode != -1) {
                cv::cvtColor(image->uMat(), m_convertedImage, umatConvertCode );
            } else {
                m_convertedImage = image->uMat();
            }

            cv::ocl::finish();
            glFinish();

            cl_command_queue commandQueue = oclManager.getCommandQueue();
            cl_int err;

            clFinish(commandQueue);

            err = clEnqueueAcquireGLObjects(commandQueue, 1, &(m_clImage), 0, NULL, NULL);
            if(err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clEnqueueAcquireGLObjects:" << err );
            }

            cl_mem clBuffer = (cl_mem) m_convertedImage.handle(cv::ACCESS_READ);
            cl_command_queue cv_ocl_queue = (cl_command_queue)cv::ocl::Queue::getDefault().ptr();

            size_t offset = 0;
            size_t dst_origin[3] = {0, 0, 0};
            size_t region[3] = {static_cast<size_t>(m_convertedImage.cols), static_cast<size_t>(m_convertedImage.rows), 1};

            err = clEnqueueCopyBufferToImage(cv_ocl_queue, clBuffer, m_clImage, offset, dst_origin, region, 0, NULL, NULL);
            if (err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clEnqueueCopyBufferToImage:" << err );
            }

            err = clEnqueueReleaseGLObjects(commandQueue, 1, &m_clImage, 0, NULL, NULL);
            if(err != CL_SUCCESS)
            {
                LOG4CPP_ERROR( logger, "error at  clEnqueueReleaseGLObjects:" << err );
            }
            cv::ocl::finish();

#else // HAVE_OPENCL
            LOG4CPP_ERROR( logger, "Image isOnGPU but OpenCL is disabled!!");
#endif // HAVE_OPENCL
        } else {
            // load image from CPU buffer into texture
            glBindTexture( GL_TEXTURE_2D, m_texture );
            glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, image->width(), image->height(),
                    imgFormat, GL_UNSIGNED_BYTE, image->Mat().data );

        }

    }
#endif // HAVE_OPENCV
}

}} // Ubitrack::Vision<|endoftext|>


<commit_before>#include "vast/util/configuration.h"

#include <algorithm>
#include <cstring>
#include <iostream>
#include <fstream>

namespace vast {
namespace util {

// TODO: Implement this function.
void configuration::load(std::string const& filename)
{
  std::ifstream ifs(filename);
  if (! ifs)
    throw error::config("could not open configuration file");

  verify();
}

void configuration::load(int argc, char *argv[])
{
  for (int i = 1; i < argc; ++i)
  {
    std::string arg(argv[i]);
    if (arg.size() < 2)
    {
      throw error::config("ill-formed option specificiation", argv[i]);
    }
    else if (arg.size() == 2)
    {
      // Argument must be of the form '-*'.
      if (arg[0] != '-')
        throw error::config("ill-formed option specificiation", argv[i]);
      arg = arg[1];
      auto s = shortcuts_.find(arg);
      if (s == shortcuts_.end())
        throw error::config("unknown short option", arg[0]);
      arg = s->second;
    }
    else
    {
      // Argument must be of the form '--*'.
      if (! (arg[0] == '-' && arg[1] == '-'))
        throw error::config("ill-formed option specification", argv[i]);
      arg = arg.substr(2);
    }

    auto o = find_option(arg);
    if (! o)
      throw error::config("unknown option", arg);
    o->defaulted_ = false;

    std::vector<std::string> values;
    while (i + 1 < argc && std::strlen(argv[i + 1]) > 0 && argv[i + 1][0] != '-')
      values.emplace_back(argv[++i]);
    if (values.size() > o->max_vals_)
      throw error::config("too many values", arg);
    if (o->max_vals_ == 1 && values.size() != 1)
      throw error::config("option value required", arg);
    if (! values.empty())
      o->values_ = std::move(values);
  }
  verify();
}

bool configuration::check(std::string const& opt) const
{
  auto o = find_option(opt);
  return o && ! o->defaulted_;
}

std::string const& configuration::get(char const* opt) const
{
  auto o = find_option(opt);
  if (! o)
    throw error::config("invalid option cast", opt);
  if (o->values().empty())
    throw error::config("option has no value", opt);
  if (o->max_vals_ > 1)
    throw error::config("cannot get multi-value option", opt);
  return o->values_[0];
}

void configuration::usage(std::ostream& sink, bool show_all)
{
  sink << banner_ << "\n";
  for (auto& b : blocks_)
  {
    if (! show_all && ! b.visible_)
      continue;
    sink << "\n " << b.name_ << ":\n";
    auto has_shortcut = std::any_of(
        b.options_.begin(),
        b.options_.end(),
        [](option const& o) { return o.shortcut_ != '\0'; });
    auto max = std::max_element(
        b.options_.begin(),
        b.options_.end(),
        [](option const& o1, option const& o2)
        {
          return o1.name_.size() < o2.name_.size();
        });
    auto max_len = max->name_.size();
    for (auto& opt : b.options_)
    {
      sink << "   --" << opt.name_;
      sink << std::string(max_len - opt.name_.size(), ' ');
      if (has_shortcut)
        sink << (opt.shortcut_ ? std::string(" | -") + opt.shortcut_ : "     ");
      sink << "   " << opt.description_ << "\n";
    }
  }
  sink << std::endl;
}

configuration::option::option(std::string name,
                              std::string desc, char shortcut)
  : name_(std::move(name)),
    description_(std::move(desc)),
    shortcut_(shortcut)
{
}

configuration::option& configuration::option::multi(size_t n)
{
  max_vals_ = n;
  return *this;
}

configuration::option& configuration::option::single()
{
  return multi(1);
}

std::vector<std::string> const& configuration::option::values() const
{
  return values_;
}

configuration::block::block(block&& other)
  : visible_(other.visible_),
    name_(std::move(other.name_)),
    prefix_(std::move(other.prefix_)),
    options_(std::move(other.options_)),
    config_(other.config_)
{
  other.visible_ = true;
  other.config_ = nullptr;
}

configuration::option&
configuration::block::add(std::string name, std::string desc)
{
  std::string fqn = qualify(name);
  if (config_->find_option(fqn))
    throw error::config("option already exists", std::move(fqn));
  options_.emplace_back(std::move(fqn), std::move(desc));
  return options_.back();
}

configuration::option&
configuration::block::add(char shortcut, std::string name, std::string desc)
{
  if (config_->shortcuts_.count({shortcut}))
    throw error::config("option shortcut already exists", shortcut);
  config_->shortcuts_.insert({{shortcut}, std::move(qualify(name))});
  std::string fqn = qualify(name);
  if (config_->find_option(fqn))
    throw error::config("option already exists", std::move(fqn));
  options_.emplace_back(std::move(fqn), std::move(desc), shortcut);
  return options_.back();
}

configuration::block& configuration::create_block(std::string name,
                                                  std::string prefix)
{
  block b(std::move(name), std::move(prefix), this);
  blocks_.push_back(std::move(b));
  return blocks_.back();
}

bool configuration::block::visible() const
{
  return visible_;
}

void configuration::block::visible(bool flag)
{
  visible_ = flag;
}

configuration::block::block(std::string name,
                            std::string prefix,
                            configuration* config)
  : name_(std::move(name)),
    prefix_(std::move(prefix)),
    config_(config)
{
}

std::string configuration::block::qualify(std::string const& name) const
{
  return ! prefix_.empty() ? prefix_ + separator + name : name;
}

void configuration::conflicts(std::string const& opt1, std::string const& opt2) const
{
  if (check(opt1) && check(opt2))
    throw error::config("conflicting options", opt1, opt2);
}

void configuration::depends(std::string const& needy, std::string const& required) const
{
  if (check(needy) && ! check(required))
    throw error::config("missing option dependency", needy, required);
}

void configuration::banner(std::string banner)
{
  banner_ = std::move(banner);
}

void configuration::verify()
{
  // The default implementation doesn't do anything.
}

configuration::option*
configuration::find_option(std::string const& opt)
{
  for (auto& b : blocks_)
    for (size_t i = 0; i < b.options_.size(); ++i)
      if (b.options_[i].name_ == opt)
        return &b.options_[i];
  return nullptr;
}

configuration::option const*
configuration::find_option(std::string const& opt) const
{
  for (auto& b : blocks_)
    for (size_t i = 0; i < b.options_.size(); ++i)
      if (b.options_[i].name_ == opt)
        return &b.options_[i];
  return nullptr;
}

} // namespace util
} // namespace vast
<commit_msg>Allow omitting whitespace for short options.<commit_after>#include "vast/util/configuration.h"

#include <algorithm>
#include <cstring>
#include <iostream>
#include <fstream>

namespace vast {
namespace util {

// TODO: Implement this function.
void configuration::load(std::string const& filename)
{
  std::ifstream ifs(filename);
  if (! ifs)
    throw error::config("could not open configuration file");

  verify();
}

void configuration::load(int argc, char *argv[])
{
  for (int i = 1; i < argc; ++i)
  {
    std::vector<std::string> values;
    std::string arg(argv[i]);
    if (arg.size() < 2)
    {
      throw error::config("ill-formed option specificiation", argv[i]);
    }
    else if (arg[0] == '-' && arg[1] == '-')
    {
      // Argument must begin with '--'.
      if (arg.size() == 2)
        throw error::config("ill-formed option specification", argv[i]);
      arg = arg.substr(2);
    }
    else if (arg[0] == '-')
    {
      if (arg.size() > 2)
        // The short option comes with a value.
        values.push_back(arg.substr(2));
      arg = arg[1];
      auto s = shortcuts_.find(arg);
      if (s == shortcuts_.end())
        throw error::config("unknown short option", arg[0]);
      arg = s->second;
    }

    auto o = find_option(arg);
    if (! o)
      throw error::config("unknown option", arg);
    o->defaulted_ = false;

    while (i + 1 < argc && std::strlen(argv[i + 1]) > 0 && argv[i + 1][0] != '-')
      values.emplace_back(argv[++i]);
    if (values.size() > o->max_vals_)
      throw error::config("too many values", arg);
    if (o->max_vals_ == 1 && values.size() != 1)
      throw error::config("option value required", arg);
    if (! values.empty())
      o->values_ = std::move(values);
  }
  verify();
}

bool configuration::check(std::string const& opt) const
{
  auto o = find_option(opt);
  return o && ! o->defaulted_;
}

std::string const& configuration::get(char const* opt) const
{
  auto o = find_option(opt);
  if (! o)
    throw error::config("invalid option cast", opt);
  if (o->values().empty())
    throw error::config("option has no value", opt);
  if (o->max_vals_ > 1)
    throw error::config("cannot get multi-value option", opt);
  return o->values_[0];
}

void configuration::usage(std::ostream& sink, bool show_all)
{
  sink << banner_ << "\n";
  for (auto& b : blocks_)
  {
    if (! show_all && ! b.visible_)
      continue;
    sink << "\n " << b.name_ << ":\n";
    auto has_shortcut = std::any_of(
        b.options_.begin(),
        b.options_.end(),
        [](option const& o) { return o.shortcut_ != '\0'; });
    auto max = std::max_element(
        b.options_.begin(),
        b.options_.end(),
        [](option const& o1, option const& o2)
        {
          return o1.name_.size() < o2.name_.size();
        });
    auto max_len = max->name_.size();
    for (auto& opt : b.options_)
    {
      sink << "   --" << opt.name_;
      sink << std::string(max_len - opt.name_.size(), ' ');
      if (has_shortcut)
        sink << (opt.shortcut_ ? std::string(" | -") + opt.shortcut_ : "     ");
      sink << "   " << opt.description_ << "\n";
    }
  }
  sink << std::endl;
}

configuration::option::option(std::string name,
                              std::string desc, char shortcut)
  : name_(std::move(name)),
    description_(std::move(desc)),
    shortcut_(shortcut)
{
}

configuration::option& configuration::option::multi(size_t n)
{
  max_vals_ = n;
  return *this;
}

configuration::option& configuration::option::single()
{
  return multi(1);
}

std::vector<std::string> const& configuration::option::values() const
{
  return values_;
}

configuration::block::block(block&& other)
  : visible_(other.visible_),
    name_(std::move(other.name_)),
    prefix_(std::move(other.prefix_)),
    options_(std::move(other.options_)),
    config_(other.config_)
{
  other.visible_ = true;
  other.config_ = nullptr;
}

configuration::option&
configuration::block::add(std::string name, std::string desc)
{
  std::string fqn = qualify(name);
  if (config_->find_option(fqn))
    throw error::config("option already exists", std::move(fqn));
  options_.emplace_back(std::move(fqn), std::move(desc));
  return options_.back();
}

configuration::option&
configuration::block::add(char shortcut, std::string name, std::string desc)
{
  if (config_->shortcuts_.count({shortcut}))
    throw error::config("option shortcut already exists", shortcut);
  config_->shortcuts_.insert({{shortcut}, std::move(qualify(name))});
  std::string fqn = qualify(name);
  if (config_->find_option(fqn))
    throw error::config("option already exists", std::move(fqn));
  options_.emplace_back(std::move(fqn), std::move(desc), shortcut);
  return options_.back();
}

configuration::block& configuration::create_block(std::string name,
                                                  std::string prefix)
{
  block b(std::move(name), std::move(prefix), this);
  blocks_.push_back(std::move(b));
  return blocks_.back();
}

bool configuration::block::visible() const
{
  return visible_;
}

void configuration::block::visible(bool flag)
{
  visible_ = flag;
}

configuration::block::block(std::string name,
                            std::string prefix,
                            configuration* config)
  : name_(std::move(name)),
    prefix_(std::move(prefix)),
    config_(config)
{
}

std::string configuration::block::qualify(std::string const& name) const
{
  return ! prefix_.empty() ? prefix_ + separator + name : name;
}

void configuration::conflicts(std::string const& opt1, std::string const& opt2) const
{
  if (check(opt1) && check(opt2))
    throw error::config("conflicting options", opt1, opt2);
}

void configuration::depends(std::string const& needy, std::string const& required) const
{
  if (check(needy) && ! check(required))
    throw error::config("missing option dependency", needy, required);
}

void configuration::banner(std::string banner)
{
  banner_ = std::move(banner);
}

void configuration::verify()
{
  // The default implementation doesn't do anything.
}

configuration::option*
configuration::find_option(std::string const& opt)
{
  for (auto& b : blocks_)
    for (size_t i = 0; i < b.options_.size(); ++i)
      if (b.options_[i].name_ == opt)
        return &b.options_[i];
  return nullptr;
}

configuration::option const*
configuration::find_option(std::string const& opt) const
{
  for (auto& b : blocks_)
    for (size_t i = 0; i < b.options_.size(); ++i)
      if (b.options_[i].name_ == opt)
        return &b.options_[i];
  return nullptr;
}

} // namespace util
} // namespace vast
<|endoftext|>


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

#include <vlGraphics/FontManager.hpp>
#include <vlCore/Log.hpp>
#include <algorithm>

#include "ft2build.h"
#include FT_FREETYPE_H

using namespace vl;

//-----------------------------------------------------------------------------
FontManager::FontManager(void* free_type_library)
{
  mFreeTypeLibrary = free_type_library;
  if (!free_type_library)
  {
    FT_Library freetype = NULL;
    FT_Error error = FT_Init_FreeType( &freetype );
    mFreeTypeLibrary = freetype;
    if ( error )
    {
      Log::error("FontManager::FontManager(): an error occurred during FreeType library initialization!\n");
      VL_TRAP()
    }
  }
}
//-----------------------------------------------------------------------------
FontManager::~FontManager()
{
  releaseAllFonts();
  if (mFreeTypeLibrary)
  {
    FT_Done_FreeType( (FT_Library)mFreeTypeLibrary );
    mFreeTypeLibrary = NULL;
  }
}
//-----------------------------------------------------------------------------
Font* FontManager::acquireFont(const String& path, int size, bool smooth)
{
  ref<Font> font;
  for(unsigned i=0; !font && i<mFonts.size(); ++i)
    if (fonts()[i]->filePath() == path && fonts()[i]->size() == size && fonts()[i]->smooth() == smooth)
      font = fonts()[0];

  if (!font)
  {
    font = new Font(this);
    font->loadFont(path);
    font->setSize(size);
    font->setSmooth(smooth);
    mFonts.push_back( font );
  }

  return font.get();
}
//-----------------------------------------------------------------------------
void FontManager::releaseFont(Font* font)
{
  std::vector< ref<Font> >::iterator it = std::find(mFonts.begin(), mFonts.end(), font);
  if (it != mFonts.end())
    mFonts.erase(it);
}
//-----------------------------------------------------------------------------
void FontManager::releaseAllFonts()
{
  for(unsigned i=0; i<mFonts.size(); ++i)
    mFonts[i]->releaseFreeTypeData();
}
//-----------------------------------------------------------------------------
<commit_msg>BUG: fixed FontManager::acquireFont().<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.org                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#include <vlGraphics/FontManager.hpp>
#include <vlCore/Log.hpp>
#include <algorithm>

#include "ft2build.h"
#include FT_FREETYPE_H

using namespace vl;

//-----------------------------------------------------------------------------
FontManager::FontManager(void* free_type_library)
{
  mFreeTypeLibrary = free_type_library;
  if (!free_type_library)
  {
    FT_Library freetype = NULL;
    FT_Error error = FT_Init_FreeType( &freetype );
    mFreeTypeLibrary = freetype;
    if ( error )
    {
      Log::error("FontManager::FontManager(): an error occurred during FreeType library initialization!\n");
      VL_TRAP()
    }
  }
}
//-----------------------------------------------------------------------------
FontManager::~FontManager()
{
  releaseAllFonts();
  if (mFreeTypeLibrary)
  {
    FT_Done_FreeType( (FT_Library)mFreeTypeLibrary );
    mFreeTypeLibrary = NULL;
  }
}
//-----------------------------------------------------------------------------
Font* FontManager::acquireFont(const String& path, int size, bool smooth)
{
  ref<Font> font;
  for(unsigned i=0; !font && i<mFonts.size(); ++i)
    if (fonts()[i]->filePath() == path && fonts()[i]->size() == size && fonts()[i]->smooth() == smooth)
      font = fonts()[i];

  if (!font)
  {
    font = new Font(this);
    font->loadFont(path);
    font->setSize(size);
    font->setSmooth(smooth);
    mFonts.push_back( font );
  }

  return font.get();
}
//-----------------------------------------------------------------------------
void FontManager::releaseFont(Font* font)
{
  std::vector< ref<Font> >::iterator it = std::find(mFonts.begin(), mFonts.end(), font);
  if (it != mFonts.end())
    mFonts.erase(it);
}
//-----------------------------------------------------------------------------
void FontManager::releaseAllFonts()
{
  for(unsigned i=0; i<mFonts.size(); ++i)
    mFonts[i]->releaseFreeTypeData();
}
//-----------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "inc.h"
#include <functional>
#include <algorithm>
#include <iterator>
#include <type_traits>

NS_BEGIN(elloop);

using namespace std;
using namespace std::placeholders;

void print(int n1, int n2, int n3)
{
    p(n1); p(" "); p(n2); p(" "); p(n3); cr;
}

template <typename T1, typename T2>
auto add(const T1 & t1, const T2& t2) -> decltype(t1 + t2)
{
    return t1 + t2;
}

double multiply(double d1, double d2)
{
    return d1 * d2;
}

double divide(double d1, int n)
{
    assert(n != 0);
    return d1 / n;
}

int ret4()
{
    pln("ret4() called");
    return 4;
}

class Foo
{
public:
    void f(int n1, int n2, int n3)
    {
        p(n1); p(" "); p(n2); p(" "); p(n3); cr;
    }

    void print()
    {
        psln(a_);
    }

    int a_ { 100 };
};

class Movable
{
public:
    Movable(int size = 1000000) : size_(size)
    {
        hugeMem_ = new int[size_];
    }

    ~Movable()
    {
        if (hugeMem_)
        {
            delete hugeMem_;
        }
    }

    Movable(Movable&& moved) : hugeMem_(moved.hugeMem_)
    {
        pln("Movable move ctr called");
        moved.hugeMem_ = nullptr;
    }

    int     *hugeMem_;
    int     size_;
};

Movable returnMovable()
{
    Movable m;
    LOGD("in %s, m.hugeMem_ is : %x\n", __FUNCTION__, m.hugeMem_);
    return m;
}

void useMoveable(Movable m1, Movable m2)
{
    psln(m1.hugeMem_);
    psln(m2.hugeMem_);
}

// prototype of template function bind.
// template <class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);

// template <class Ret, class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindNormalFunction, @);

//----------------------------- extreme situation ------------------------------
auto emptyArg = bind(multiply, 1, 2);
EXPECT_EQ(2, emptyArg());

auto need2arg = bind(multiply, _1, _2);
EXPECT_EQ(2, need2arg(1, 2));
EXPECT_EQ(2, need2arg(1, 2, ret4()));

//--------------------- bind normal function -----------------------------------
auto same = bind(multiply, _1, _2);
EXPECT_EQ(200.0, same(2, 100));

auto doublize = bind(multiply, _1, 2.0);
EXPECT_EQ(200.0, doublize(100));

auto ret_20 = bind(multiply, 2, 10);
EXPECT_EQ(20.0, ret_20());

double d1 = divide(10, 2);
EXPECT_EQ(5, d1);
auto revertDivide = bind(divide, _2, _1);
double d2 = revertDivide(10, 2);
EXPECT_EQ(1 / 5.0, d2);

auto rounding = bind<int>(divide, _1, _2);
auto i1 = rounding(10, 3);
bool isSameType = is_same<int, decltype(i1)>::value;
EXPECT_TRUE(isSameType);
EXPECT_EQ(3, i1);

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, UsePlaceholders, @);
auto arg3 = bind(print, _3, _2, _1);
arg3(1, 2, 3);  // 3 2 1
auto arg2 = bind(print, _1, _1, _2);
arg2(1, 2);     // 1 1 2
auto arg1 = bind(print, _1, _1, _1);
arg1(1);        // 1 1 1
auto arg0 = bind(print, 1, 1, 1);
arg0();         // 1 1 1
arg0(2);        // 1 1 1, 2 is ignored.
arg0(2,2,2);    // 1 1 1, 2 2 2 is ignored.

// try to accept 4 args
auto arg4 = bind(print, _2, _3, _4);
//arg4(1, 2, 3);                // compile error, too few args.ɶ಻ in call
arg4(1, 2, 3, 4);               // 2 3 4; 1 is ignored.
arg4(1, 2, 3, 4, 5);            // ok, 5 is ignored.
arg4(1, 2, 3, 4, 5, 6, 7, 8);   // ok, 5~8 are ignored. ɶ಻ in call

// try to accept 5 args
auto arg5 = bind(print, _1, _3, _5);
arg5(1, 2, 3, 4, 5);    // 1 3 5; 2,4 is ingored.

/*
if fn() need N args, then the number of placeholders S, and the number of normal args
V, should satisfy N == S + V.
*/
// try to use more than 3 placeholders
auto hold4 = bind(print, _1, _2, _3, _4);   // һ in bind
// error, too many args, caused by too many placeholders in definition of hold4.
//hold4(1, 2, 3, 4);

// try to use fewer than 3 placeholders.
auto hold2 = bind(print, _1, _2);           // һ in definition
// error, too few args, caused by too few placeholders in definition of hold2.
//hold2(1, 2, 3);

//auto hold_100 = bind(print, _100, _1, _2);    // max placeholders is _20 (VC++)
END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindMemberFunction, @);
Foo foo;
Foo &foo_ref = foo;

auto mfarg4 = bind(&Foo::f, _1, _2, _3, _4);
// or use object directly.
mfarg4(foo, 10, 20, 30);    // 10 20 30;
// use object pointer.
mfarg4(&foo, 10, 20, 30);   // 10 20 30;
// use object ref.
mfarg4(foo_ref, 10, 20, 30);    // 10 20 30;

auto mfarg3 = bind(&Foo::f, _1, _2, _3, 30);
mfarg3(&foo, 10, 20);       // 10 20 30;

auto mfarg2 = bind(&Foo::f, _1, _2, 20, 30);
mfarg2(&foo, 10);           // 10 20 30;

auto mfarg1 = bind(&Foo::f, _1, 10, 20, 30);
mfarg1(foo);                // 10 20 30;

auto mfarg0 = bind(&Foo::f, foo, 10, 20, 30);
mfarg0();                   // 10 20 30

auto mfarg01 = bind(&Foo::f, &foo, 10, 20, 30);
mfarg01();                  // 10 20 30
auto mfarg02 = bind(&Foo::f, foo_ref, 10, 20, 30);
mfarg02();                      // 10 20 30

// assign a mem_func to std::function.
std::function<void(int, int, int)> normal_func;
normal_func = bind(&Foo::f, foo, _1, _2, _3);
normal_func(10, 20, 30);        // 10 20 30

//------------------------------ bind member var ----------------------------
auto bindMv = bind(&Foo::a_, _1);
psln(bindMv(foo));             // bindMv(foo) = 100
//psln(bindMv(&foo));          // bindMv(foo) = 100
psln(bindMv(foo_ref));         // bindMv(foo) = 100

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, SubexpressionOfBind, @);

//--------------------------------- nested bind--------------------------------
auto addby1 = [](int x) -> int
{
    cout << "addby1() called" << endl;
    return (x + 1);
};

auto nestedF = bind(print, _1, bind(addby1, _1), _2);
nestedF(1, 3);                 // addby1() called<cr> 1 2 3

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindTemplateFunction, @);

// work with template function.
auto addby2 = bind(add<double, double>, _1, 2.0);
psln(addby2(10.2));       // 12.2

// TODO : why bind can't work with template function?
//auto addBy2 = bind<double>(add, _1, 2.0);
// ANSWER: stupid!
// bind<T> means bind's return value f, will return a value of type T.
// for example:

auto addby2_int = bind<int>(add<double, double>, _1, 2.0);
psln(addby2_int(10.2));     // 12

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, ReferenceWrapperBind, @);

//--------------------------------- test ref ---------------------------------
int x(10);
auto bindRef = bind(print, 1, std::cref(x), x);
bindRef();                // 1 10 10;
x = 100;
bindRef();                // 1 100 10;

END_TEST;

//-------------------------------- bind movable obj --------------------------------
BEGIN_TEST(FunctorTest, BindMovable, @);

//Movable movable;
//psln(movable.hugeMem_);
//auto bindMoved = bind(useMoveable, _1, _2);
//bindMoved(returnMovable(), returnMovable());
//psln(movable.hugeMem_);

END_TEST;

//----------------------------- Bind Predefined Functors -----------------------------
RUN_GTEST(FunctorTest, BindPredefinedFunctors, @);

// all predefined functors:
// negate, plus, minus, multiplies, divides, modulus, equal_to,
// not_equal_to, less, greater, less_equal, greater_equal,
// logical_not, logical_and, logical_or, bit_and, bit_or, bit_xor

auto tenTimes = bind(multiplies<int>(), _1, 10);
EXPECT_EQ(100, tenTimes(10));
EXPECT_EQ(200, tenTimes(20));
EXPECT_EQ(300, tenTimes(30));

// nested bind.
vector<int> v {1, 2, 3, 4, 5, 6, 7, 8};
// output v[i] if 10*v[i] > 50.
copy_if(v.begin(), v.end(),
    ostream_iterator<int>(cout, ", "),
    bind(greater<int>(),
        bind(multiplies<int>(), _1, 10),
        50));                               // 6,7,8,
cr;

END_TEST;

//----------------------------- Bind container Ref  -----------------------------
RUN_GTEST(FunctorTest, BindContainerElemByRef, @);

END_TEST;

//----------------------- c++98 mem_fun and c++11 mem_fn -----------------------
BEGIN_TEST(FunctorTest, Mem_FunTest, @);

using std::for_each;
using std::mem_fun;

// 1. mem_fun is for a pointer to an obj.
vector<Foo*> fpv;
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());

for_each(fpv.begin(), fpv.end(), mem_fun(&Foo::print));

for_each(fpv.begin(), fpv.end(), [&](Foo* foo)
{
    delete foo;
    foo = nullptr;
});

// 2. mem_fun_ref is for obj.
vector<Foo> fv;
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());

for_each(fv.begin(), fv.end(), mem_fun_ref(&Foo::print));

// 3. mem_fn work for obj, ref to obj and ptr to obj.
Foo foo;
Foo &foo_ref = foo;
Foo *fp = &foo;

auto callMemFn = mem_fn(&Foo::f);
callMemFn(foo, 1, 2, 3);
callMemFn(foo_ref, 1, 2, 3);
callMemFn(fp, 1, 2, 3);

END_TEST;

NS_END(elloop);<commit_msg>bind vs mem_fn<commit_after>#include "gtest/gtest.h"
#include "inc.h"
#include <functional>
#include <algorithm>
#include <iterator>
#include <type_traits>

NS_BEGIN(elloop);

using namespace std;
using namespace std::placeholders;

void print(int n1, int n2, int n3)
{
    p(n1); p(" "); p(n2); p(" "); p(n3); cr;
}

template <typename T1, typename T2>
auto add(const T1 & t1, const T2& t2) -> decltype(t1 + t2)
{
    return t1 + t2;
}

double multiply(double d1, double d2)
{
    return d1 * d2;
}

double divide(double d1, int n)
{
    assert(n != 0);
    return d1 / n;
}

int ret4()
{
    pln("ret4() called");
    return 4;
}

class Foo
{
public:
    void f(int n1, int n2, int n3)
    {
        p(n1); p(" "); p(n2); p(" "); p(n3); cr;
    }

    void print()
    {
        psln(a_);
    }

    int a_ { 100 };
};

class Movable
{
public:
    Movable(int size = 1000000) : size_(size)
    {
        hugeMem_ = new int[size_];
    }

    ~Movable()
    {
        if (hugeMem_)
        {
            delete hugeMem_;
        }
    }

    Movable(Movable&& moved) : hugeMem_(moved.hugeMem_)
    {
        pln("Movable move ctr called");
        moved.hugeMem_ = nullptr;
    }

    int     *hugeMem_;
    int     size_;
};

Movable returnMovable()
{
    Movable m;
    LOGD("in %s, m.hugeMem_ is : %x\n", __FUNCTION__, m.hugeMem_);
    return m;
}

void useMoveable(Movable m1, Movable m2)
{
    psln(m1.hugeMem_);
    psln(m2.hugeMem_);
}

// prototype of template function bind.
// template <class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);

// template <class Ret, class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindNormalFunction, @);

//----------------------------- extreme situation ------------------------------
auto emptyArg = bind(multiply, 1, 2);
EXPECT_EQ(2, emptyArg());

auto need2arg = bind(multiply, _1, _2);
EXPECT_EQ(2, need2arg(1, 2));
EXPECT_EQ(2, need2arg(1, 2, ret4()));

//--------------------- bind normal function -----------------------------------
auto same = bind(multiply, _1, _2);
EXPECT_EQ(200.0, same(2, 100));

auto doublize = bind(multiply, _1, 2.0);
EXPECT_EQ(200.0, doublize(100));

auto ret_20 = bind(multiply, 2, 10);
EXPECT_EQ(20.0, ret_20());

double d1 = divide(10, 2);
EXPECT_EQ(5, d1);
auto revertDivide = bind(divide, _2, _1);
double d2 = revertDivide(10, 2);
EXPECT_EQ(1 / 5.0, d2);

auto rounding = bind<int>(divide, _1, _2);
auto i1 = rounding(10, 3);
bool isSameType = is_same<int, decltype(i1)>::value;
EXPECT_TRUE(isSameType);
EXPECT_EQ(3, i1);

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, UsePlaceholders, @);
auto arg3 = bind(print, _3, _2, _1);
arg3(1, 2, 3);  // 3 2 1
auto arg2 = bind(print, _1, _1, _2);
arg2(1, 2);     // 1 1 2
auto arg1 = bind(print, _1, _1, _1);
arg1(1);        // 1 1 1
auto arg0 = bind(print, 1, 1, 1);
arg0();         // 1 1 1
arg0(2);        // 1 1 1, 2 is ignored.
arg0(2,2,2);    // 1 1 1, 2 2 2 is ignored.

// try to accept 4 args
auto arg4 = bind(print, _2, _3, _4);
//arg4(1, 2, 3);                // compile error, too few args.ɶ಻ in call
arg4(1, 2, 3, 4);               // 2 3 4; 1 is ignored.
arg4(1, 2, 3, 4, 5);            // ok, 5 is ignored.
arg4(1, 2, 3, 4, 5, 6, 7, 8);   // ok, 5~8 are ignored. ɶ಻ in call

// try to accept 5 args
auto arg5 = bind(print, _1, _3, _5);
arg5(1, 2, 3, 4, 5);    // 1 3 5; 2,4 is ingored.

/*
if fn() need N args, then the number of placeholders S, and the number of normal args
V, should satisfy N == S + V.
*/
// try to use more than 3 placeholders
auto hold4 = bind(print, _1, _2, _3, _4);   // һ in bind
// error, too many args, caused by too many placeholders in definition of hold4.
//hold4(1, 2, 3, 4);

// try to use fewer than 3 placeholders.
auto hold2 = bind(print, _1, _2);           // һ in definition
// error, too few args, caused by too few placeholders in definition of hold2.
//hold2(1, 2, 3);

//auto hold_100 = bind(print, _100, _1, _2);    // max placeholders is _20 (VC++)
END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindMemberFunction, @);
Foo foo;
Foo &foo_ref = foo;

auto mfarg4 = bind(&Foo::f, _1, _2, _3, _4);
// or use object directly.
mfarg4(foo, 10, 20, 30);    // 10 20 30;
// use object pointer.
mfarg4(&foo, 10, 20, 30);   // 10 20 30;
// use object ref.
mfarg4(foo_ref, 10, 20, 30);    // 10 20 30;

auto mfarg3 = bind(&Foo::f, _1, _2, _3, 30);
mfarg3(&foo, 10, 20);       // 10 20 30;

auto mfarg2 = bind(&Foo::f, _1, _2, 20, 30);
mfarg2(&foo, 10);           // 10 20 30;

auto mfarg1 = bind(&Foo::f, _1, 10, 20, 30);
mfarg1(foo);                // 10 20 30;

auto mfarg0 = bind(&Foo::f, foo, 10, 20, 30);
mfarg0();                   // 10 20 30

auto mfarg01 = bind(&Foo::f, &foo, 10, 20, 30);
mfarg01();                  // 10 20 30
auto mfarg02 = bind(&Foo::f, foo_ref, 10, 20, 30);
mfarg02();                      // 10 20 30

// assign a mem_func to std::function.
std::function<void(int, int, int)> normal_func;
normal_func = bind(&Foo::f, foo, _1, _2, _3);
normal_func(10, 20, 30);        // 10 20 30

//------------------------------ bind member var ----------------------------
auto bindMv = bind(&Foo::a_, _1);
psln(bindMv(foo));             // bindMv(foo) = 100
//psln(bindMv(&foo));          // bindMv(foo) = 100
psln(bindMv(foo_ref));         // bindMv(foo) = 100

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, SubexpressionOfBind, @);

//--------------------------------- nested bind--------------------------------
auto addby1 = [](int x) -> int
{
    cout << "addby1() called" << endl;
    return (x + 1);
};

auto nestedF = bind(print, _1, bind(addby1, _1), _2);
nestedF(1, 3);                 // addby1() called<cr> 1 2 3

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindTemplateFunction, @);

// work with template function.
auto addby2 = bind(add<double, double>, _1, 2.0);
psln(addby2(10.2));       // 12.2

// TODO : why bind can't work with template function?
//auto addBy2 = bind<double>(add, _1, 2.0);
// ANSWER: stupid!
// bind<T> means bind's return value f, will return a value of type T.
// for example:

auto addby2_int = bind<int>(add<double, double>, _1, 2.0);
psln(addby2_int(10.2));     // 12

END_TEST;

//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, ReferenceWrapperBind, @);

//--------------------------------- test ref ---------------------------------
int x(10);
auto bindRef = bind(print, 1, std::cref(x), x);
bindRef();                // 1 10 10;
x = 100;
bindRef();                // 1 100 10;

END_TEST;

//-------------------------------- bind movable obj --------------------------------
BEGIN_TEST(FunctorTest, BindMovable, @);

//Movable movable;
//psln(movable.hugeMem_);
//auto bindMoved = bind(useMoveable, _1, _2);
//bindMoved(returnMovable(), returnMovable());
//psln(movable.hugeMem_);

END_TEST;

//----------------------------- Bind Predefined Functors -----------------------------
BEGIN_TEST(FunctorTest, BindPredefinedFunctors, @);

// all predefined functors:
// negate, plus, minus, multiplies, divides, modulus, equal_to,
// not_equal_to, less, greater, less_equal, greater_equal,
// logical_not, logical_and, logical_or, bit_and, bit_or, bit_xor

auto tenTimes = bind(multiplies<int>(), _1, 10);
EXPECT_EQ(100, tenTimes(10));
EXPECT_EQ(200, tenTimes(20));
EXPECT_EQ(300, tenTimes(30));

vector<int> v {1, 2, 3, 4, 5, 6, 7, 8};
// nested bind. output v[i] if 10*v[i] > 50.
copy_if(v.begin(), v.end(),
    ostream_iterator<int>(cout, ", "),
    bind(greater<int>(),
        bind(multiplies<int>(), _1, 10),
        50));                               // 6,7,8,
cr;

END_TEST;

//----------------------------- Bind container Ref  -----------------------------
BEGIN_TEST(FunctorTest, BindContainerElemByRef, @);

END_TEST;

//----------------------- c++98 mem_fun and c++11 mem_fn -----------------------
BEGIN_TEST(FunctorTest, Mem_FunTest, @);

using std::for_each;
using std::mem_fun;

// 1. mem_fun is for a pointer to an obj.
vector<Foo*> fpv;
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());

for_each(fpv.begin(), fpv.end(), mem_fun(&Foo::print));
cr;
for_each(fpv.begin(), fpv.end(), bind(&Foo::print, _1));    // also can use bind
cr;

for_each(fpv.begin(), fpv.end(), [&](Foo* foo)
{
    delete foo;
    foo = nullptr;
});

// 2. mem_fun_ref is for obj.
vector<Foo> fv;
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());

for_each(fv.begin(), fv.end(), mem_fun_ref(&Foo::print));
cr;
for_each(fv.begin(), fv.end(), bind(&Foo::print, _1));      // also can use bind
cr;

// 3. mem_fn work for obj, ref to obj and ptr to obj.
Foo foo;
Foo &foo_ref = foo;
Foo *fp = &foo;

auto callMemFn = mem_fn(&Foo::f);
callMemFn(foo, 1, 2, 3);
callMemFn(foo_ref, 1, 2, 3);
callMemFn(fp, 1, 2, 3);

END_TEST;

NS_END(elloop);<|endoftext|>


<commit_before>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#ifndef CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP
#define CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP

//
// typedefs for windows.h types to avoid pulling in entire system header for simple types
//

typedef void* HANDLE;

#endif
<commit_msg>crunch_base - Added DWORD to wintypes.hp<commit_after>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#ifndef CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP
#define CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP

//
// typedefs for windows.h types to avoid pulling in entire system header for simple types
//

typedef void* HANDLE;
typedef unsigned long DWORD;

#endif
<|endoftext|>