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

#include "chrome/browser/chromeos/dom_ui/menu_ui.h"

#include "app/menus/menu_model.h"
#include "app/resource_bundle.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/singleton.h"
#include "base/string_number_conversions.h"
#include "base/string_piece.h"
#include "base/values.h"
#include "base/weak_ptr.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/views/domui_menu_widget.h"
#include "chrome/browser/chromeos/views/native_menu_domui.h"
#include "chrome/browser/dom_ui/dom_ui_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fetcher.h"
#include "gfx/canvas_skia.h"
#include "grit/app_resources.h"
#include "grit/browser_resources.h"
#include "views/controls/menu/menu_config.h"
#include "views/controls/menu/radio_button_image_gtk.h"
#include "views/widget/widget_gtk.h"

namespace {

// Creates scroll button's up image when |up| is true or
// down image if |up| is false.
SkBitmap CreateMenuScrollArrowImage(bool up) {
  const views::MenuConfig& config = views::MenuConfig::instance();

  int height = config.scroll_arrow_height;
  gfx::CanvasSkia canvas(height * 2, height, false);

  if (!up) {
    // flip the direction.
    canvas.scale(1.0, -1.0);
    canvas.translate(0, -height);
  }
  // Draw triangle.
  SkPath path;
  path.moveTo(height, 0);
  path.lineTo(0, height);
  path.lineTo(height * 2, height);
  SkPaint paint;
  paint.setColor(SK_ColorBLACK);
  paint.setStyle(SkPaint::kFill_Style);
  paint.setAntiAlias(true);
  canvas.drawPath(path, paint);
  return canvas.ExtractBitmap();
}

// Returns the scroll button's up image if |up| is true, or
// "down" image otherwise.
const std::string& GetImageDataUrlForMenuScrollArrow(bool up) {
  static const std::string upImage =
      dom_ui_util::GetImageDataUrl(CreateMenuScrollArrowImage(true));
  static const std::string downImage =
      dom_ui_util::GetImageDataUrl(CreateMenuScrollArrowImage(false));
  return up ? upImage : downImage;
}

// Returns the radio button's "on" image if |on| is true, or
// "off" image otherwise.
const std::string& GetImageDataUrlForRadio(bool on) {
  static const std::string onImage =
      dom_ui_util::GetImageDataUrl(*views::GetRadioButtonImage(true));
  static const std::string offImage =
       dom_ui_util::GetImageDataUrl(*views::GetRadioButtonImage(false));
  return on ? onImage : offImage;
}

std::string GetMenuUIHTMLSourceFromString(const std::string& menu_html) {
#define SET_INTEGER_PROPERTY(prop) \
  value_config.SetInteger(#prop, menu_config.prop)

  const views::MenuConfig& menu_config = views::MenuConfig::instance();

  DictionaryValue value_config;
  value_config.SetString("radioOnUrl", GetImageDataUrlForRadio(true));
  value_config.SetString("radioOffUrl", GetImageDataUrlForRadio(false));
  value_config.SetString(
      "arrowUrl", dom_ui_util::GetImageDataUrlFromResource(IDR_MENU_ARROW));
  value_config.SetString(
      "checkUrl", dom_ui_util::GetImageDataUrlFromResource(IDR_MENU_CHECK));

  value_config.SetString(
      "scrollUpUrl", GetImageDataUrlForMenuScrollArrow(true));
  value_config.SetString(
      "scrollDownUrl", GetImageDataUrlForMenuScrollArrow(false));

  SET_INTEGER_PROPERTY(item_top_margin);
  SET_INTEGER_PROPERTY(item_bottom_margin);
  SET_INTEGER_PROPERTY(item_no_icon_top_margin);
  SET_INTEGER_PROPERTY(item_no_icon_bottom_margin);
  SET_INTEGER_PROPERTY(item_left_margin);
  SET_INTEGER_PROPERTY(label_to_arrow_padding);
  SET_INTEGER_PROPERTY(arrow_to_edge_padding);
  SET_INTEGER_PROPERTY(icon_to_label_padding);
  SET_INTEGER_PROPERTY(gutter_to_label);
  SET_INTEGER_PROPERTY(check_width);
  SET_INTEGER_PROPERTY(check_height);
  SET_INTEGER_PROPERTY(radio_width);
  SET_INTEGER_PROPERTY(radio_height);
  SET_INTEGER_PROPERTY(arrow_height);
  SET_INTEGER_PROPERTY(arrow_width);
  SET_INTEGER_PROPERTY(gutter_width);
  SET_INTEGER_PROPERTY(separator_height);
  SET_INTEGER_PROPERTY(render_gutter);
  SET_INTEGER_PROPERTY(show_mnemonics);
  SET_INTEGER_PROPERTY(scroll_arrow_height);
  SET_INTEGER_PROPERTY(label_to_accelerator_padding);

  std::string json_config;
  base::JSONWriter::Write(&value_config, false, &json_config);
  return menu_html + "<script>init(" + json_config + ");</script>";
}

// Returns the menu's html code given by the resource id with the code
// to intialization the menu. The resource string should be pure code
// and should not contain i18n string.
std::string GetMenuUIHTMLSourceFromResource(int res) {
  const base::StringPiece menu_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(res));
  return GetMenuUIHTMLSourceFromString(menu_html.as_string());
}

class MenuUIHTMLSource : public ChromeURLDataManager::DataSource,
                         public URLFetcher::Delegate {
 public:
  explicit MenuUIHTMLSource(Profile* profile);

  // Called when the network layer has requested a resource underneath
  // the path we registered.
  virtual void StartDataRequest(const std::string& path,
                                bool is_off_the_record,
                                int request_id);
  virtual std::string GetMimeType(const std::string&) const {
    return "text/html";
  }

  // URLFetcher::Delegate implements:
  virtual void OnURLFetchComplete(const URLFetcher* source,
                                  const GURL& url,
                                  const URLRequestStatus& status,
                                  int response_code,
                                  const ResponseCookies& cookies,
                                  const std::string& data);

 private:
  virtual ~MenuUIHTMLSource() {}
#ifndef NDEBUG
  int request_id_;
  Profile* profile_;
#endif
  DISALLOW_COPY_AND_ASSIGN(MenuUIHTMLSource);
};

// The handler for Javascript messages related to the "system" view.
class MenuHandler : public chromeos::MenuHandlerBase,
                    public base::SupportsWeakPtr<MenuHandler>,
                    public TabContentsDelegate {
 public:
  MenuHandler();
  virtual ~MenuHandler();

  // DOMMessageHandler implementation.
  virtual DOMMessageHandler* Attach(DOMUI* dom_ui);
  virtual void RegisterMessages();

 private:
  void HandleClick(const ListValue* values);
  void HandleOpenSubmenu(const ListValue* values);
  void HandleCloseSubmenu(const ListValue* values);
  void HandleMoveInputToSubmenu(const ListValue* values);
  void HandleMoveInputToParent(const ListValue* values);

  // TabContentsDelegate implements:
  virtual void UpdatePreferredSize(const gfx::Size& new_size);
  virtual void LoadingStateChanged(TabContents* contents);

  virtual void OpenURLFromTab(TabContents* source,
                              const GURL& url, const GURL& referrer,
                              WindowOpenDisposition disposition,
                              PageTransition::Type transition) {}
  virtual void NavigationStateChanged(const TabContents* source,
                                      unsigned changed_flags) {}
  virtual void AddNewContents(TabContents* source,
                              TabContents* new_contents,
                              WindowOpenDisposition disposition,
                              const gfx::Rect& initial_pos,
                              bool user_gesture) {}

  // TODO(oshima): Handle crash
  virtual void ActivateContents(TabContents* contents) {}
  virtual void DeactivateContents(TabContents* contents) {}
  virtual void CloseContents(TabContents* source) {}
  virtual void MoveContents(TabContents* source, const gfx::Rect& pos) {}
  virtual bool IsPopup(const TabContents* source) { return false; }
  virtual void ToolbarSizeChanged(TabContents* source, bool is_animating) {}
  virtual void URLStarredChanged(TabContents* source, bool starred) {}
  virtual void UpdateTargetURL(TabContents* source, const GURL& url) {}
  virtual bool CanDownload(int request_id) { return false; }
  virtual bool infobars_enabled() { return false; }
  virtual bool ShouldEnablePreferredSizeNotifications() { return true; }
  virtual bool CanReloadContents(TabContents* source) const { return false; }

  // True if the page is loaded.
  bool loaded_;

  DISALLOW_COPY_AND_ASSIGN(MenuHandler);
};

////////////////////////////////////////////////////////////////////////////////
//
// MenuUIHTMLSource
//
////////////////////////////////////////////////////////////////////////////////

MenuUIHTMLSource::MenuUIHTMLSource(Profile* profile)
    : DataSource(chrome::kChromeUIMenu, MessageLoop::current())
#ifndef NDEBUG
    , request_id_(-1),
      profile_(profile)
#endif
     {
}

void MenuUIHTMLSource::StartDataRequest(const std::string& path,
                                        bool is_off_the_record,
                                        int request_id) {
#ifndef NDEBUG
  std::string url = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
      switches::kDOMUIMenuUrl);
  if (!url.empty()) {
    request_id_ = request_id;
    URLFetcher* fetcher = new URLFetcher(GURL(url), URLFetcher::GET, this);
    fetcher->set_request_context(profile_->GetRequestContext());
    fetcher->Start();
    return;
  }
#endif

  static const std::string menu_html =
      GetMenuUIHTMLSourceFromResource(IDR_MENU_HTML);

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);

  // TODO(oshima): Eliminate boilerplate code. See http://crbug.com/57583 .
  html_bytes->data.resize(menu_html.size());
  std::copy(menu_html.begin(), menu_html.end(),
            html_bytes->data.begin());
  SendResponse(request_id, html_bytes);
}

void MenuUIHTMLSource::OnURLFetchComplete(const URLFetcher* source,
                                          const GURL& url,
                                          const URLRequestStatus& status,
                                          int response_code,
                                          const ResponseCookies& cookies,
                                          const std::string& data) {
  const std::string menu_html =
      GetMenuUIHTMLSourceFromString(data);

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);

  // TODO(oshima): Eliminate boilerplate code. See http://crbug.com/57583 .
  html_bytes->data.resize(menu_html.size());
  std::copy(menu_html.begin(), menu_html.end(),
            html_bytes->data.begin());
  SendResponse(request_id_, html_bytes);

  delete source;
}

////////////////////////////////////////////////////////////////////////////////
//
// MenuHandler
//
////////////////////////////////////////////////////////////////////////////////
MenuHandler::MenuHandler() : loaded_(false) {
}

MenuHandler::~MenuHandler() {
}

DOMMessageHandler* MenuHandler::Attach(DOMUI* dom_ui) {
  DOMMessageHandler* handler = DOMMessageHandler::Attach(dom_ui);
  dom_ui->tab_contents()->set_delegate(this);
  return handler;
}

void MenuHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback(
      "click",
      NewCallback(this,
                  &MenuHandler::HandleClick));
  dom_ui_->RegisterMessageCallback(
      "open_submenu",
      NewCallback(this,
                  &MenuHandler::HandleOpenSubmenu));
  dom_ui_->RegisterMessageCallback(
      "close_submenu",
      NewCallback(this,
                  &MenuHandler::HandleCloseSubmenu));
  dom_ui_->RegisterMessageCallback(
      "move_to_submenu",
      NewCallback(this,
                  &MenuHandler::HandleMoveInputToSubmenu));
  dom_ui_->RegisterMessageCallback(
      "move_to_parent",
      NewCallback(this,
                  &MenuHandler::HandleMoveInputToParent));
}

void MenuHandler::HandleClick(const ListValue* values) {
  CHECK_EQ(1U, values->GetSize());
  std::string index_str;
  bool success = values->GetString(0, &index_str);
  DCHECK(success);
  int index;
  success = base::StringToInt(index_str, &index);
  DCHECK(success);
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control) {
    menus::MenuModel* model = GetMenuModel();
    DCHECK(model);
    if (index < 0) {
      control->CloseAll();
    } else if (model->IsEnabledAt(index)) {
      control->Activate(model, index);
    }
  }
}

void MenuHandler::HandleOpenSubmenu(const ListValue* values) {
  CHECK_EQ(2U, values->GetSize());
  std::string index_str;
  bool success = values->GetString(0, &index_str);
  DCHECK(success);
  std::string y_str;
  success = values->GetString(1, &y_str);
  DCHECK(success);
  int index;
  success = base::StringToInt(index_str, &index);
  DCHECK(success);
  int y;
  success = base::StringToInt(y_str, &y);
  DCHECK(success);
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->OpenSubmenu(index, y);
}

void MenuHandler::HandleCloseSubmenu(const ListValue* values) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->CloseSubmenu();
}

void MenuHandler::HandleMoveInputToSubmenu(const ListValue* values) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->MoveInputToSubmenu();
}

void MenuHandler::HandleMoveInputToParent(const ListValue* values) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->MoveInputToParent();
}

void MenuHandler::UpdatePreferredSize(const gfx::Size& new_size) {
  if (!loaded_)
    return;
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->SetSize(new_size);
}

void MenuHandler::LoadingStateChanged(TabContents* contents) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control && !contents->is_loading()) {
    loaded_ = true;
    control->OnLoad();
  }
}

}  // namespace

namespace chromeos {

////////////////////////////////////////////////////////////////////////////////
//
// MenuHandlerBase
//
////////////////////////////////////////////////////////////////////////////////

chromeos::DOMUIMenuControl* MenuHandlerBase::GetMenuControl() {
  DOMUIMenuWidget* widget =
      chromeos::DOMUIMenuWidget::FindDOMUIMenuWidget(
          dom_ui_->tab_contents()->GetNativeView());
  if (widget)
    return widget->domui_menu();  // NativeMenuDOMUI implements DOMUIMenuControl
  else
    return NULL;
}

menus::MenuModel* MenuHandlerBase::GetMenuModel() {
  DOMUIMenuControl* control = GetMenuControl();
  if (control)
    return control->GetMenuModel();
  else
    return NULL;
}

////////////////////////////////////////////////////////////////////////////////
//
// MenuUI
//
////////////////////////////////////////////////////////////////////////////////

MenuUI::MenuUI(TabContents* contents) : DOMUI(contents) {
  MenuHandler* handler = new MenuHandler();
  AddMessageHandler((handler)->Attach(this));

  ChromeThread::PostTask(
      ChromeThread::IO, FROM_HERE,
      NewRunnableMethod(
          Singleton<ChromeURLDataManager>::get(),
          &ChromeURLDataManager::AddDataSource,
          make_scoped_refptr(CreateDataSource())));
}

ChromeURLDataManager::DataSource* MenuUI::CreateDataSource() {
  return new MenuUIHTMLSource(GetProfile());
}

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

#include "chrome/browser/chromeos/dom_ui/menu_ui.h"

#include "app/menus/menu_model.h"
#include "app/resource_bundle.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/singleton.h"
#include "base/string_number_conversions.h"
#include "base/string_piece.h"
#include "base/values.h"
#include "base/weak_ptr.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/views/domui_menu_widget.h"
#include "chrome/browser/chromeos/views/native_menu_domui.h"
#include "chrome/browser/dom_ui/dom_ui_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fetcher.h"
#include "gfx/canvas_skia.h"
#include "grit/app_resources.h"
#include "grit/browser_resources.h"
#include "views/controls/menu/menu_config.h"
#include "views/controls/menu/radio_button_image_gtk.h"
#include "views/widget/widget_gtk.h"

namespace {

// Creates scroll button's up image when |up| is true or
// down image if |up| is false.
SkBitmap CreateMenuScrollArrowImage(bool up) {
  const views::MenuConfig& config = views::MenuConfig::instance();

  int height = config.scroll_arrow_height;
  gfx::CanvasSkia canvas(height * 2, height, false);

  if (!up) {
    // flip the direction.
    canvas.scale(1.0, -1.0);
    canvas.translate(0, -height);
  }
  // Draw triangle.
  SkPath path;
  path.moveTo(height, 0);
  path.lineTo(0, height);
  path.lineTo(height * 2, height);
  SkPaint paint;
  paint.setColor(SK_ColorBLACK);
  paint.setStyle(SkPaint::kFill_Style);
  paint.setAntiAlias(true);
  canvas.drawPath(path, paint);
  return canvas.ExtractBitmap();
}

// Returns the scroll button's up image if |up| is true, or
// "down" image otherwise.
const std::string& GetImageDataUrlForMenuScrollArrow(bool up) {
  static const std::string upImage =
      dom_ui_util::GetImageDataUrl(CreateMenuScrollArrowImage(true));
  static const std::string downImage =
      dom_ui_util::GetImageDataUrl(CreateMenuScrollArrowImage(false));
  return up ? upImage : downImage;
}

// Returns the radio button's "on" image if |on| is true, or
// "off" image otherwise.
const std::string& GetImageDataUrlForRadio(bool on) {
  static const std::string onImage =
      dom_ui_util::GetImageDataUrl(*views::GetRadioButtonImage(true));
  static const std::string offImage =
       dom_ui_util::GetImageDataUrl(*views::GetRadioButtonImage(false));
  return on ? onImage : offImage;
}

std::string GetMenuUIHTMLSourceFromString(const std::string& menu_html) {
#define SET_INTEGER_PROPERTY(prop) \
  value_config.SetInteger(#prop, menu_config.prop)

  const views::MenuConfig& menu_config = views::MenuConfig::instance();

  DictionaryValue value_config;
  value_config.SetString("radioOnUrl", GetImageDataUrlForRadio(true));
  value_config.SetString("radioOffUrl", GetImageDataUrlForRadio(false));
  value_config.SetString(
      "arrowUrl", dom_ui_util::GetImageDataUrlFromResource(IDR_MENU_ARROW));
  value_config.SetString(
      "checkUrl", dom_ui_util::GetImageDataUrlFromResource(IDR_MENU_CHECK));

  value_config.SetString(
      "scrollUpUrl", GetImageDataUrlForMenuScrollArrow(true));
  value_config.SetString(
      "scrollDownUrl", GetImageDataUrlForMenuScrollArrow(false));

  SET_INTEGER_PROPERTY(item_top_margin);
  SET_INTEGER_PROPERTY(item_bottom_margin);
  SET_INTEGER_PROPERTY(item_no_icon_top_margin);
  SET_INTEGER_PROPERTY(item_no_icon_bottom_margin);
  SET_INTEGER_PROPERTY(item_left_margin);
  SET_INTEGER_PROPERTY(label_to_arrow_padding);
  SET_INTEGER_PROPERTY(arrow_to_edge_padding);
  SET_INTEGER_PROPERTY(icon_to_label_padding);
  SET_INTEGER_PROPERTY(gutter_to_label);
  SET_INTEGER_PROPERTY(check_width);
  SET_INTEGER_PROPERTY(check_height);
  SET_INTEGER_PROPERTY(radio_width);
  SET_INTEGER_PROPERTY(radio_height);
  SET_INTEGER_PROPERTY(arrow_height);
  SET_INTEGER_PROPERTY(arrow_width);
  SET_INTEGER_PROPERTY(gutter_width);
  SET_INTEGER_PROPERTY(separator_height);
  SET_INTEGER_PROPERTY(render_gutter);
  SET_INTEGER_PROPERTY(show_mnemonics);
  SET_INTEGER_PROPERTY(scroll_arrow_height);
  SET_INTEGER_PROPERTY(label_to_accelerator_padding);

  std::string json_config;
  base::JSONWriter::Write(&value_config, false, &json_config);
  return menu_html + "<script>init(" + json_config + ");</script>";
}

// Returns the menu's html code given by the resource id with the code
// to intialization the menu. The resource string should be pure code
// and should not contain i18n string.
std::string GetMenuUIHTMLSourceFromResource(int res) {
  const base::StringPiece menu_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(res));
  return GetMenuUIHTMLSourceFromString(menu_html.as_string());
}

class MenuUIHTMLSource : public ChromeURLDataManager::DataSource,
                         public URLFetcher::Delegate {
 public:
  explicit MenuUIHTMLSource(Profile* profile);

  // Called when the network layer has requested a resource underneath
  // the path we registered.
  virtual void StartDataRequest(const std::string& path,
                                bool is_off_the_record,
                                int request_id);
  virtual std::string GetMimeType(const std::string&) const {
    return "text/html";
  }

  // URLFetcher::Delegate implements:
  virtual void OnURLFetchComplete(const URLFetcher* source,
                                  const GURL& url,
                                  const URLRequestStatus& status,
                                  int response_code,
                                  const ResponseCookies& cookies,
                                  const std::string& data);

 private:
  virtual ~MenuUIHTMLSource() {}
#ifndef NDEBUG
  int request_id_;
  Profile* profile_;
#endif
  DISALLOW_COPY_AND_ASSIGN(MenuUIHTMLSource);
};

// The handler for Javascript messages related to the "system" view.
class MenuHandler : public chromeos::MenuHandlerBase,
                    public base::SupportsWeakPtr<MenuHandler>,
                    public TabContentsDelegate {
 public:
  MenuHandler();
  virtual ~MenuHandler();

  // DOMMessageHandler implementation.
  virtual DOMMessageHandler* Attach(DOMUI* dom_ui);
  virtual void RegisterMessages();

 private:
  void HandleClick(const ListValue* values);
  void HandleOpenSubmenu(const ListValue* values);
  void HandleCloseSubmenu(const ListValue* values);
  void HandleMoveInputToSubmenu(const ListValue* values);
  void HandleMoveInputToParent(const ListValue* values);

  // TabContentsDelegate implements:
  virtual void UpdatePreferredSize(const gfx::Size& new_size);
  virtual void LoadingStateChanged(TabContents* contents);

  virtual void OpenURLFromTab(TabContents* source,
                              const GURL& url, const GURL& referrer,
                              WindowOpenDisposition disposition,
                              PageTransition::Type transition) {}
  virtual void NavigationStateChanged(const TabContents* source,
                                      unsigned changed_flags) {}
  virtual void AddNewContents(TabContents* source,
                              TabContents* new_contents,
                              WindowOpenDisposition disposition,
                              const gfx::Rect& initial_pos,
                              bool user_gesture) {}

  // TODO(oshima): Handle crash
  virtual void ActivateContents(TabContents* contents) {}
  virtual void DeactivateContents(TabContents* contents) {}
  virtual void CloseContents(TabContents* source) {}
  virtual void MoveContents(TabContents* source, const gfx::Rect& pos) {}
  virtual bool IsPopup(const TabContents* source) { return false; }
  virtual void ToolbarSizeChanged(TabContents* source, bool is_animating) {}
  virtual void URLStarredChanged(TabContents* source, bool starred) {}
  virtual void UpdateTargetURL(TabContents* source, const GURL& url) {}
  virtual bool CanDownload(int request_id) { return false; }
  virtual bool infobars_enabled() { return false; }
  virtual bool ShouldEnablePreferredSizeNotifications() { return true; }
  virtual bool CanReloadContents(TabContents* source) const { return false; }

  // True if the page is loaded.
  bool loaded_;

  DISALLOW_COPY_AND_ASSIGN(MenuHandler);
};

////////////////////////////////////////////////////////////////////////////////
//
// MenuUIHTMLSource
//
////////////////////////////////////////////////////////////////////////////////

MenuUIHTMLSource::MenuUIHTMLSource(Profile* profile)
    : DataSource(chrome::kChromeUIMenu, MessageLoop::current())
#ifndef NDEBUG
    , request_id_(-1),
      profile_(profile)
#endif
     {
}

void MenuUIHTMLSource::StartDataRequest(const std::string& path,
                                        bool is_off_the_record,
                                        int request_id) {
#ifndef NDEBUG
  std::string url = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
      switches::kDOMUIMenuUrl);
  if (!url.empty()) {
    request_id_ = request_id;
    URLFetcher* fetcher = new URLFetcher(GURL(url), URLFetcher::GET, this);
    fetcher->set_request_context(profile_->GetRequestContext());
    fetcher->Start();
    return;
  }
#endif

  static const std::string menu_html =
      GetMenuUIHTMLSourceFromResource(IDR_MENU_HTML);

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);

  // TODO(oshima): Eliminate boilerplate code. See http://crbug.com/57583 .
  html_bytes->data.resize(menu_html.size());
  std::copy(menu_html.begin(), menu_html.end(),
            html_bytes->data.begin());
  SendResponse(request_id, html_bytes);
}

void MenuUIHTMLSource::OnURLFetchComplete(const URLFetcher* source,
                                          const GURL& url,
                                          const URLRequestStatus& status,
                                          int response_code,
                                          const ResponseCookies& cookies,
                                          const std::string& data) {
#ifndef NDEBUG
  // This should not be called in release build.
  const std::string menu_html =
      GetMenuUIHTMLSourceFromString(data);

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);

  // TODO(oshima): Eliminate boilerplate code. See http://crbug.com/57583 .
  html_bytes->data.resize(menu_html.size());
  std::copy(menu_html.begin(), menu_html.end(),
            html_bytes->data.begin());
  SendResponse(request_id_, html_bytes);

  delete source;
#endif
}

////////////////////////////////////////////////////////////////////////////////
//
// MenuHandler
//
////////////////////////////////////////////////////////////////////////////////
MenuHandler::MenuHandler() : loaded_(false) {
}

MenuHandler::~MenuHandler() {
}

DOMMessageHandler* MenuHandler::Attach(DOMUI* dom_ui) {
  DOMMessageHandler* handler = DOMMessageHandler::Attach(dom_ui);
  dom_ui->tab_contents()->set_delegate(this);
  return handler;
}

void MenuHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback(
      "click",
      NewCallback(this,
                  &MenuHandler::HandleClick));
  dom_ui_->RegisterMessageCallback(
      "open_submenu",
      NewCallback(this,
                  &MenuHandler::HandleOpenSubmenu));
  dom_ui_->RegisterMessageCallback(
      "close_submenu",
      NewCallback(this,
                  &MenuHandler::HandleCloseSubmenu));
  dom_ui_->RegisterMessageCallback(
      "move_to_submenu",
      NewCallback(this,
                  &MenuHandler::HandleMoveInputToSubmenu));
  dom_ui_->RegisterMessageCallback(
      "move_to_parent",
      NewCallback(this,
                  &MenuHandler::HandleMoveInputToParent));
}

void MenuHandler::HandleClick(const ListValue* values) {
  CHECK_EQ(1U, values->GetSize());
  std::string index_str;
  bool success = values->GetString(0, &index_str);
  DCHECK(success);
  int index;
  success = base::StringToInt(index_str, &index);
  DCHECK(success);
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control) {
    menus::MenuModel* model = GetMenuModel();
    DCHECK(model);
    if (index < 0) {
      control->CloseAll();
    } else if (model->IsEnabledAt(index)) {
      control->Activate(model, index);
    }
  }
}

void MenuHandler::HandleOpenSubmenu(const ListValue* values) {
  CHECK_EQ(2U, values->GetSize());
  std::string index_str;
  bool success = values->GetString(0, &index_str);
  DCHECK(success);
  std::string y_str;
  success = values->GetString(1, &y_str);
  DCHECK(success);
  int index;
  success = base::StringToInt(index_str, &index);
  DCHECK(success);
  int y;
  success = base::StringToInt(y_str, &y);
  DCHECK(success);
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->OpenSubmenu(index, y);
}

void MenuHandler::HandleCloseSubmenu(const ListValue* values) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->CloseSubmenu();
}

void MenuHandler::HandleMoveInputToSubmenu(const ListValue* values) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->MoveInputToSubmenu();
}

void MenuHandler::HandleMoveInputToParent(const ListValue* values) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->MoveInputToParent();
}

void MenuHandler::UpdatePreferredSize(const gfx::Size& new_size) {
  if (!loaded_)
    return;
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control)
    control->SetSize(new_size);
}

void MenuHandler::LoadingStateChanged(TabContents* contents) {
  chromeos::DOMUIMenuControl* control = GetMenuControl();
  if (control && !contents->is_loading()) {
    loaded_ = true;
    control->OnLoad();
  }
}

}  // namespace

namespace chromeos {

////////////////////////////////////////////////////////////////////////////////
//
// MenuHandlerBase
//
////////////////////////////////////////////////////////////////////////////////

chromeos::DOMUIMenuControl* MenuHandlerBase::GetMenuControl() {
  DOMUIMenuWidget* widget =
      chromeos::DOMUIMenuWidget::FindDOMUIMenuWidget(
          dom_ui_->tab_contents()->GetNativeView());
  if (widget)
    return widget->domui_menu();  // NativeMenuDOMUI implements DOMUIMenuControl
  else
    return NULL;
}

menus::MenuModel* MenuHandlerBase::GetMenuModel() {
  DOMUIMenuControl* control = GetMenuControl();
  if (control)
    return control->GetMenuModel();
  else
    return NULL;
}

////////////////////////////////////////////////////////////////////////////////
//
// MenuUI
//
////////////////////////////////////////////////////////////////////////////////

MenuUI::MenuUI(TabContents* contents) : DOMUI(contents) {
  MenuHandler* handler = new MenuHandler();
  AddMessageHandler((handler)->Attach(this));

  ChromeThread::PostTask(
      ChromeThread::IO, FROM_HERE,
      NewRunnableMethod(
          Singleton<ChromeURLDataManager>::get(),
          &ChromeURLDataManager::AddDataSource,
          make_scoped_refptr(CreateDataSource())));
}

ChromeURLDataManager::DataSource* MenuUI::CreateDataSource() {
  return new MenuUIHTMLSource(GetProfile());
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.

    Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>

    This program 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 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qwidgetstack.h>

#include <kconfig.h>
#include <kglobal.h>

#include "calendarview.h"
#include "datenavigator.h"
#include "kotodoview.h"
#include "koagendaview.h"
#include "komonthview.h"
#include "kolistview.h"
#include "kowhatsnextview.h"
#include "kojournalview.h"
#include "koprefs.h"
#include "koglobals.h"
#include "navigatorbar.h"

#include "koviewmanager.h"
#include "koviewmanager.moc"

KOViewManager::KOViewManager( CalendarView *mainView ) :
  QObject(), mMainView( mainView )
{
  mCurrentView = 0;

  mLastEventView = 0;

  mWhatsNextView = 0;
  mTodoView = 0;
  mAgendaView = 0;
  mMonthView = 0;
  mListView = 0;
  mJournalView = 0;
}

KOViewManager::~KOViewManager()
{
}

KOrg::BaseView *KOViewManager::currentView()
{
  return mCurrentView;
}

void KOViewManager::readSettings(KConfig *config)
{
  config->setGroup("General");
  QString view = config->readEntry("Current View");

  if (view == "WhatsNext") showWhatsNextView();
  else if (view == "Month") showMonthView();
  else if (view == "List") showListView();
  else if (view == "Journal") showJournalView();
  else if (view == "Todo") showTodoView();
  else showAgendaView();
}

void KOViewManager::writeSettings(KConfig *config)
{
  config->setGroup("General");

  QString view;
  if (mCurrentView == mWhatsNextView) view = "WhatsNext";
  else if (mCurrentView == mMonthView) view = "Month";
  else if (mCurrentView == mListView) view = "List";
  else if (mCurrentView == mJournalView) view = "Journal";
  else if (mCurrentView == mTodoView) view = "Todo";
  else view = "Agenda";

  config->writeEntry("Current View",view);

  if (mAgendaView) {
    mAgendaView->writeSettings(config);
  }
  if (mListView) {
    mListView->writeSettings(config);
  }
  if (mTodoView) {
    mTodoView->saveLayout(config,"Todo View");
  }
}

void KOViewManager::showView(KOrg::BaseView *view)
{
  if( view == mCurrentView ) return;

  mCurrentView = view;

  if ( mCurrentView && mCurrentView->isEventView() ) {
    mLastEventView = mCurrentView;
  }

  if ( mAgendaView ) mAgendaView->deleteSelectedDateTime();

  raiseCurrentView();
  mMainView->processIncidenceSelection( 0 );

  mMainView->updateView();

  mMainView->adaptNavigationUnits();
}

void KOViewManager::raiseCurrentView()
{
  if ((mMonthView && KOPrefs::instance()->mFullViewMonth && mCurrentView == mMonthView) ||
      (mTodoView && KOPrefs::instance()->mFullViewTodo && mCurrentView == mTodoView)) {
    mMainView->showLeftFrame( false );
    if ( mCurrentView == mTodoView ) {
      mMainView->navigatorBar()->hide();
    } else {
      mMainView->navigatorBar()->show();
    }
  } else {
    mMainView->showLeftFrame( true );
    mMainView->navigatorBar()->hide();
  }
  mMainView->viewStack()->raiseWidget(mCurrentView);
}

void KOViewManager::updateView()
{
  if ( mCurrentView ) mCurrentView->updateView();
}

void KOViewManager::updateView(const QDate &start, const QDate &end)
{
//  kdDebug(5850) << "KOViewManager::updateView()" << endl;

  if (mCurrentView) mCurrentView->showDates(start, end);

  if (mTodoView) mTodoView->updateView();
}

void KOViewManager::connectView(KOrg::BaseView *view)
{
  if (!view) return;

  // selecting an incidence
  connect( view, SIGNAL( incidenceSelected( Incidence * ) ),
           mMainView, SLOT( processMainViewSelection( Incidence * ) ) );

  // showing/editing/deleting an incidence. The calendar view takes care of the action.
  connect(view, SIGNAL(showIncidenceSignal(Incidence *)),
          mMainView, SLOT(showIncidence(Incidence *)));
  connect(view, SIGNAL(editIncidenceSignal(Incidence *)),
          mMainView, SLOT(editIncidence(Incidence *)));
  connect(view, SIGNAL(deleteIncidenceSignal(Incidence *)),
          mMainView, SLOT(deleteIncidence(Incidence *)));
  connect(view, SIGNAL(toggleAlarmSignal(Incidence *)),
          mMainView, SLOT(toggleAlarm(Incidence *)));
  connect(view,SIGNAL(dissociateOccurrenceSignal( Incidence *, const QDate & )),
          mMainView, SLOT(dissociateOccurrence( Incidence *, const QDate & )));
  connect(view,SIGNAL(dissociateFutureOccurrenceSignal( Incidence *, const QDate & )),
          mMainView, SLOT(dissociateFutureOccurrence( Incidence *, const QDate & )));

  // signals to create new incidences
  connect( view, SIGNAL( newEventSignal() ),
           mMainView, SLOT( newEvent() ) );
  connect( view, SIGNAL( newEventSignal( QDateTime ) ),
           mMainView, SLOT( newEvent( QDateTime ) ) );
  connect( view, SIGNAL( newEventSignal( QDateTime, QDateTime ) ),
           mMainView, SLOT( newEvent( QDateTime, QDateTime ) ) );
  connect( view, SIGNAL( newEventSignal( QDate ) ),
           mMainView, SLOT( newEvent( QDate ) ) );
  connect( view, SIGNAL( newTodoSignal( QDate ) ),
           mMainView, SLOT( newTodo( QDate ) ) );
  connect( view, SIGNAL( newSubTodoSignal( Todo * ) ),
           mMainView, SLOT( newSubTodo( Todo *) ) );

  // reload settings
  connect(mMainView, SIGNAL(configChanged()), view, SLOT(updateConfig()));

  // Notifications about added, changed and deleted incidences
  connect( mMainView, SIGNAL( dayPassed( QDate ) ),
           view, SLOT( dayPassed( QDate ) ) );
  connect( view, SIGNAL( startMultiModify( const QString & ) ),
           mMainView, SLOT( startMultiModify( const QString & ) ) );
  connect( view, SIGNAL( endMultiModify() ),
           mMainView, SLOT( endMultiModify() ) );

  connect( mMainView, SIGNAL( newIncidenceChanger( IncidenceChangerBase* ) ),
           view, SLOT( setIncidenceChanger( IncidenceChangerBase * ) ) );
  view->setIncidenceChanger( mMainView->incidenceChanger() );
}

void KOViewManager::connectTodoView( KOTodoView* todoView )
{
  if (!todoView) return;

  // SIGNALS/SLOTS FOR TODO VIEW
  connect( todoView, SIGNAL( purgeCompletedSignal() ),
           mMainView, SLOT( purgeCompleted() ) );
  connect( todoView, SIGNAL( unSubTodoSignal() ),
           mMainView, SLOT( todo_unsub() ) );
}

void KOViewManager::zoomInHorizontally()
{
  // is better resend the signal?
  if( mAgendaView == mCurrentView ) mAgendaView->zoomInHorizontally();
}
void KOViewManager::zoomOutHorizontally()
{
  if( mAgendaView== mCurrentView ) mAgendaView->zoomOutHorizontally();
}
void KOViewManager::zoomInVertically()
{
  if( mAgendaView== mCurrentView ) mAgendaView->zoomInVertically();
}
void KOViewManager::zoomOutVertically()
{
  if( mAgendaView== mCurrentView ) mAgendaView->zoomOutVertically();
}

void KOViewManager::addView(KOrg::BaseView *view)
{
  connectView( view );
#if QT_VERSION >= 300
  mMainView->viewStack()->addWidget( view );
#else
  mMainView->viewStack()->addWidget( view, 1 );
#endif
}

void KOViewManager::showWhatsNextView()
{
  if (!mWhatsNextView) {
    mWhatsNextView = new KOWhatsNextView(mMainView->calendar(),mMainView->viewStack(),
                                         "KOViewManager::WhatsNextView");
    addView(mWhatsNextView);
  }
  showView(mWhatsNextView);
}

void KOViewManager::showListView()
{
  if (!mListView) {
    mListView = new KOListView(mMainView->calendar(), mMainView->viewStack(), "KOViewManager::ListView");
    addView(mListView);
  }
  showView(mListView);
}

void KOViewManager::showAgendaView()
{
  if (!mAgendaView) {
    mAgendaView = new KOAgendaView(mMainView->calendar(), mMainView->viewStack(), "KOViewManager::AgendaView");

    addView(mAgendaView);

    connect(mAgendaView, SIGNAL( toggleExpand() ),
            mMainView, SLOT( toggleExpand() ) );
    connect(mMainView, SIGNAL( calendarViewExpanded( bool ) ),
            mAgendaView, SLOT( setExpandedButton( bool ) ) );

    mAgendaView->readSettings();
  }

  showView(mAgendaView);
}

void KOViewManager::showDayView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectDates( 1 );
}

void KOViewManager::showWorkWeekView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectWorkWeek();
}

void KOViewManager::showWeekView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectWeek();
}

void KOViewManager::showNextXView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectDates( QDate::currentDate(),
                                           KOPrefs::instance()->mNextXDays );
}

void KOViewManager::showMonthView()
{
  if (!mMonthView) {
    mMonthView = new KOMonthView(mMainView->calendar(), mMainView->viewStack(), "KOViewManager::MonthView");
    addView(mMonthView);
  }

  showView(mMonthView);
}

void KOViewManager::showTodoView()
{
  if ( !mTodoView ) {
    mTodoView = new KOTodoView( mMainView->calendar(), mMainView->viewStack(),
                                "KOViewManager::TodoView" );
    mTodoView->setCalendar( mMainView->calendar() );
    addView( mTodoView );
    connectTodoView( mTodoView );

    KConfig *config = KOGlobals::self()->config();
    mTodoView->restoreLayout( config, "Todo View" );
  }

  showView( mTodoView );
}

void KOViewManager::showJournalView()
{
  if (!mJournalView) {
    mJournalView = new KOJournalView(mMainView->calendar(),mMainView->viewStack(),
                                     "KOViewManager::JournalView");
    addView(mJournalView);
  }

  showView(mJournalView);
}

void KOViewManager::showEventView()
{
  if ( mLastEventView ) showView( mLastEventView );
  else showWeekView();
}

Incidence *KOViewManager::currentSelection()
{
  if ( !mCurrentView ) return 0;
  Incidence::List incidenceList = mCurrentView->selectedIncidences();
  if ( incidenceList.isEmpty() ) return 0;

  return incidenceList.first();
}

QDate KOViewManager::currentSelectionDate()
{
  QDate qd;
  if (mCurrentView) {
    DateList qvl = mCurrentView->selectedDates();
    if (!qvl.isEmpty()) qd = qvl.first();
  }
  return qd;
}

void KOViewManager::setDocumentId( const QString &id )
{
  if (mTodoView) mTodoView->setDocumentId( id );
}
<commit_msg>Update datenavigator when zooming. Patch by Mario.<commit_after>/*
    This file is part of KOrganizer.

    Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>

    This program 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 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qwidgetstack.h>

#include <kconfig.h>
#include <kglobal.h>

#include "calendarview.h"
#include "datenavigator.h"
#include "kotodoview.h"
#include "koagendaview.h"
#include "komonthview.h"
#include "kolistview.h"
#include "kowhatsnextview.h"
#include "kojournalview.h"
#include "koprefs.h"
#include "koglobals.h"
#include "navigatorbar.h"

#include "koviewmanager.h"
#include "koviewmanager.moc"

KOViewManager::KOViewManager( CalendarView *mainView ) :
  QObject(), mMainView( mainView )
{
  mCurrentView = 0;

  mLastEventView = 0;

  mWhatsNextView = 0;
  mTodoView = 0;
  mAgendaView = 0;
  mMonthView = 0;
  mListView = 0;
  mJournalView = 0;
}

KOViewManager::~KOViewManager()
{
}

KOrg::BaseView *KOViewManager::currentView()
{
  return mCurrentView;
}

void KOViewManager::readSettings(KConfig *config)
{
  config->setGroup("General");
  QString view = config->readEntry("Current View");

  if (view == "WhatsNext") showWhatsNextView();
  else if (view == "Month") showMonthView();
  else if (view == "List") showListView();
  else if (view == "Journal") showJournalView();
  else if (view == "Todo") showTodoView();
  else showAgendaView();
}

void KOViewManager::writeSettings(KConfig *config)
{
  config->setGroup("General");

  QString view;
  if (mCurrentView == mWhatsNextView) view = "WhatsNext";
  else if (mCurrentView == mMonthView) view = "Month";
  else if (mCurrentView == mListView) view = "List";
  else if (mCurrentView == mJournalView) view = "Journal";
  else if (mCurrentView == mTodoView) view = "Todo";
  else view = "Agenda";

  config->writeEntry("Current View",view);

  if (mAgendaView) {
    mAgendaView->writeSettings(config);
  }
  if (mListView) {
    mListView->writeSettings(config);
  }
  if (mTodoView) {
    mTodoView->saveLayout(config,"Todo View");
  }
}

void KOViewManager::showView(KOrg::BaseView *view)
{
  if( view == mCurrentView ) return;

  mCurrentView = view;

  if ( mCurrentView && mCurrentView->isEventView() ) {
    mLastEventView = mCurrentView;
  }

  if ( mAgendaView ) mAgendaView->deleteSelectedDateTime();

  raiseCurrentView();
  mMainView->processIncidenceSelection( 0 );

  mMainView->updateView();

  mMainView->adaptNavigationUnits();
}

void KOViewManager::raiseCurrentView()
{
  if ((mMonthView && KOPrefs::instance()->mFullViewMonth && mCurrentView == mMonthView) ||
      (mTodoView && KOPrefs::instance()->mFullViewTodo && mCurrentView == mTodoView)) {
    mMainView->showLeftFrame( false );
    if ( mCurrentView == mTodoView ) {
      mMainView->navigatorBar()->hide();
    } else {
      mMainView->navigatorBar()->show();
    }
  } else {
    mMainView->showLeftFrame( true );
    mMainView->navigatorBar()->hide();
  }
  mMainView->viewStack()->raiseWidget(mCurrentView);
}

void KOViewManager::updateView()
{
  if ( mCurrentView ) mCurrentView->updateView();
}

void KOViewManager::updateView(const QDate &start, const QDate &end)
{
//  kdDebug(5850) << "KOViewManager::updateView()" << endl;

  if (mCurrentView) mCurrentView->showDates(start, end);

  if (mTodoView) mTodoView->updateView();
}

void KOViewManager::connectView(KOrg::BaseView *view)
{
  if (!view) return;

  // selecting an incidence
  connect( view, SIGNAL( incidenceSelected( Incidence * ) ),
           mMainView, SLOT( processMainViewSelection( Incidence * ) ) );

  // showing/editing/deleting an incidence. The calendar view takes care of the action.
  connect(view, SIGNAL(showIncidenceSignal(Incidence *)),
          mMainView, SLOT(showIncidence(Incidence *)));
  connect(view, SIGNAL(editIncidenceSignal(Incidence *)),
          mMainView, SLOT(editIncidence(Incidence *)));
  connect(view, SIGNAL(deleteIncidenceSignal(Incidence *)),
          mMainView, SLOT(deleteIncidence(Incidence *)));
  connect(view, SIGNAL(toggleAlarmSignal(Incidence *)),
          mMainView, SLOT(toggleAlarm(Incidence *)));
  connect(view,SIGNAL(dissociateOccurrenceSignal( Incidence *, const QDate & )),
          mMainView, SLOT(dissociateOccurrence( Incidence *, const QDate & )));
  connect(view,SIGNAL(dissociateFutureOccurrenceSignal( Incidence *, const QDate & )),
          mMainView, SLOT(dissociateFutureOccurrence( Incidence *, const QDate & )));

  // signals to create new incidences
  connect( view, SIGNAL( newEventSignal() ),
           mMainView, SLOT( newEvent() ) );
  connect( view, SIGNAL( newEventSignal( QDateTime ) ),
           mMainView, SLOT( newEvent( QDateTime ) ) );
  connect( view, SIGNAL( newEventSignal( QDateTime, QDateTime ) ),
           mMainView, SLOT( newEvent( QDateTime, QDateTime ) ) );
  connect( view, SIGNAL( newEventSignal( QDate ) ),
           mMainView, SLOT( newEvent( QDate ) ) );
  connect( view, SIGNAL( newTodoSignal( QDate ) ),
           mMainView, SLOT( newTodo( QDate ) ) );
  connect( view, SIGNAL( newSubTodoSignal( Todo * ) ),
           mMainView, SLOT( newSubTodo( Todo *) ) );

  // reload settings
  connect(mMainView, SIGNAL(configChanged()), view, SLOT(updateConfig()));

  // Notifications about added, changed and deleted incidences
  connect( mMainView, SIGNAL( dayPassed( QDate ) ),
           view, SLOT( dayPassed( QDate ) ) );
  connect( view, SIGNAL( startMultiModify( const QString & ) ),
           mMainView, SLOT( startMultiModify( const QString & ) ) );
  connect( view, SIGNAL( endMultiModify() ),
           mMainView, SLOT( endMultiModify() ) );

  connect( mMainView, SIGNAL( newIncidenceChanger( IncidenceChangerBase* ) ),
           view, SLOT( setIncidenceChanger( IncidenceChangerBase * ) ) );
  view->setIncidenceChanger( mMainView->incidenceChanger() );
}

void KOViewManager::connectTodoView( KOTodoView* todoView )
{
  if (!todoView) return;

  // SIGNALS/SLOTS FOR TODO VIEW
  connect( todoView, SIGNAL( purgeCompletedSignal() ),
           mMainView, SLOT( purgeCompleted() ) );
  connect( todoView, SIGNAL( unSubTodoSignal() ),
           mMainView, SLOT( todo_unsub() ) );
}

void KOViewManager::zoomInHorizontally()
{
  if( mAgendaView == mCurrentView ) mAgendaView->zoomInHorizontally();
}
void KOViewManager::zoomOutHorizontally()
{
  if( mAgendaView== mCurrentView ) mAgendaView->zoomOutHorizontally();
}
void KOViewManager::zoomInVertically()
{
  if( mAgendaView== mCurrentView ) mAgendaView->zoomInVertically();
}
void KOViewManager::zoomOutVertically()
{
  if( mAgendaView== mCurrentView ) mAgendaView->zoomOutVertically();
}

void KOViewManager::addView(KOrg::BaseView *view)
{
  connectView( view );
#if QT_VERSION >= 300
  mMainView->viewStack()->addWidget( view );
#else
  mMainView->viewStack()->addWidget( view, 1 );
#endif
}

void KOViewManager::showWhatsNextView()
{
  if (!mWhatsNextView) {
    mWhatsNextView = new KOWhatsNextView(mMainView->calendar(),mMainView->viewStack(),
                                         "KOViewManager::WhatsNextView");
    addView(mWhatsNextView);
  }
  showView(mWhatsNextView);
}

void KOViewManager::showListView()
{
  if (!mListView) {
    mListView = new KOListView(mMainView->calendar(), mMainView->viewStack(), "KOViewManager::ListView");
    addView(mListView);
  }
  showView(mListView);
}

void KOViewManager::showAgendaView()
{
  if (!mAgendaView) {
    mAgendaView = new KOAgendaView(mMainView->calendar(), mMainView->viewStack(), "KOViewManager::AgendaView");

    addView(mAgendaView);

    connect(mAgendaView, SIGNAL( toggleExpand() ),
            mMainView, SLOT( toggleExpand() ) );
    connect(mMainView, SIGNAL( calendarViewExpanded( bool ) ),
            mAgendaView, SLOT( setExpandedButton( bool ) ) );

    connect( mAgendaView,SIGNAL( zoomViewHorizontally(const QDate &, int )),
      mMainView->dateNavigator(),SLOT( selectDates( const QDate &, int ) ) );
    mAgendaView->readSettings();
  }

  showView(mAgendaView);
}

void KOViewManager::showDayView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectDates( 1 );
}

void KOViewManager::showWorkWeekView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectWorkWeek();
}

void KOViewManager::showWeekView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectWeek();
}

void KOViewManager::showNextXView()
{
  showAgendaView();
  mMainView->dateNavigator()->selectDates( QDate::currentDate(),
                                           KOPrefs::instance()->mNextXDays );
}

void KOViewManager::showMonthView()
{
  if (!mMonthView) {
    mMonthView = new KOMonthView(mMainView->calendar(), mMainView->viewStack(), "KOViewManager::MonthView");
    addView(mMonthView);
  }

  showView(mMonthView);
}

void KOViewManager::showTodoView()
{
  if ( !mTodoView ) {
    mTodoView = new KOTodoView( mMainView->calendar(), mMainView->viewStack(),
                                "KOViewManager::TodoView" );
    mTodoView->setCalendar( mMainView->calendar() );
    addView( mTodoView );
    connectTodoView( mTodoView );

    KConfig *config = KOGlobals::self()->config();
    mTodoView->restoreLayout( config, "Todo View" );
  }

  showView( mTodoView );
}

void KOViewManager::showJournalView()
{
  if (!mJournalView) {
    mJournalView = new KOJournalView(mMainView->calendar(),mMainView->viewStack(),
                                     "KOViewManager::JournalView");
    addView(mJournalView);
  }

  showView(mJournalView);
}

void KOViewManager::showEventView()
{
  if ( mLastEventView ) showView( mLastEventView );
  else showWeekView();
}

Incidence *KOViewManager::currentSelection()
{
  if ( !mCurrentView ) return 0;
  Incidence::List incidenceList = mCurrentView->selectedIncidences();
  if ( incidenceList.isEmpty() ) return 0;

  return incidenceList.first();
}

QDate KOViewManager::currentSelectionDate()
{
  QDate qd;
  if (mCurrentView) {
    DateList qvl = mCurrentView->selectedDates();
    if (!qvl.isEmpty()) qd = qvl.first();
  }
  return qd;
}

void KOViewManager::setDocumentId( const QString &id )
{
  if (mTodoView) mTodoView->setDocumentId( id );
}
<|endoftext|>


<commit_before>/*
this test case shows how to execute CM kernel via OpenCL APIs.
the CM kernel source code is already compiled into file "cmrt_utest_genx.isa" with offline compiler.

I also copied the CM kernel source code and CM host source code here for your reference.

CM kernel source code:
#include <cm/cm.h>
extern "C" _GENX_MAIN_  void
simplemov(SurfaceIndex ibuf, SurfaceIndex obuf, uint d)
{
    matrix<uchar, 1, 4> in;
    matrix<uchar, 1, 4> out;

	uint h_pos = get_thread_origin_x();
	uint v_pos = get_thread_origin_y();

	read(ibuf, h_pos*4, v_pos, in);

	out = in / d;
	write(obuf, h_pos*4, v_pos, out);
}

CM host source code:
#include "cm_rt.h"

int main()
{
    FILE* pISA = fopen("cmrt_utest_genx.isa", "rb");
    if (pISA == NULL) {
        perror("cmrt_utest_genx.isa");
        return -1;
    }

    fseek (pISA, 0, SEEK_END);
    int codeSize = ftell (pISA);
    rewind(pISA);

    if(codeSize == 0)
    {
        perror("cmrt_utest_genx.isa");
        return -1;
    }

    void *pCommonISACode = (BYTE*) malloc(codeSize);
    if( !pCommonISACode )
    {
        return -1;
    }

    if (fread(pCommonISACode, 1, codeSize, pISA) != codeSize) {
        perror("cmrt_utest_genx.isa");
        return -1;
    }
    fclose(pISA);

    unsigned int  width = 256;
    unsigned int  height = 128;

    unsigned char *src;
    unsigned char *dst;
    src = (unsigned char*) malloc(width*height*4);
    dst = (unsigned char*) malloc(width*height*4);

    for (unsigned int i = 0; i < width*height*4; i++) {
        src[i] = i % 256;
        dst[i] = 0;
    }

    CmDevice* pCmDev = NULL;;
    UINT version = 0;

    int result = CreateCmDevice( pCmDev, version );
    if (result != CM_SUCCESS ) {
        printf("CmDevice creation error");
        return -1;
    }
    if( version < CM_1_0 ){
        printf(" The runtime API version is later than runtime DLL version");
        return -1;
    }

    CmProgram* program = NULL;
    result = pCmDev->LoadProgram(pCommonISACode, codeSize, program);
    if (result != CM_SUCCESS ) {
        perror("CM LoadProgram error");
        return -1;
    }

    CmKernel* kernel = NULL;
    result = pCmDev->CreateKernel(program, CM_KERNEL_FUNCTION(simplemov) , kernel);
    if (result != CM_SUCCESS ) {
        perror("CM CreateKernel error");
        return -1;
    }

    CmSurface2D*  pInputSurf = NULL;
    result = pCmDev->CreateSurface2D( width, height, CM_SURFACE_FORMAT_A8R8G8B8, pInputSurf );
    if (result != CM_SUCCESS ) {
        printf("CM CreateSurface2D error");
        return -1;
    }

    CmSurface2D*  pOutputSurf = NULL;
    result = pCmDev->CreateSurface2D( width, height, CM_SURFACE_FORMAT_A8R8G8B8, pOutputSurf );
    if (result != CM_SUCCESS ) {
        printf("CM CreateSurface2D error");
        return -1;
    }

    result = pInputSurf->WriteSurface( src, NULL );
    if (result != CM_SUCCESS ) {
        printf("CM WriteSurface error");
        return -1;
    }

    kernel->SetThreadCount( width * height );

    CmThreadSpace* pTS = NULL;
    result = pCmDev->CreateThreadSpace(width, height, pTS);
    if (result != CM_SUCCESS ) {
        printf("CM WriteSurface error");
        return -1;
    }

    SurfaceIndex * index0= NULL;
    pInputSurf->GetIndex(index0);
    kernel->SetKernelArg(0,sizeof(SurfaceIndex),index0);

    SurfaceIndex * index1= NULL;
    pOutputSurf->GetIndex(index1);
    kernel->SetKernelArg(1,sizeof(SurfaceIndex),index1);

	unsigned int  d = 3;
	kernel->SetKernelArg(2, sizeof(unsigned int), &d);

    CmQueue* pCmQueue = NULL;
    result = pCmDev->CreateQueue( pCmQueue );
    if (result != CM_SUCCESS ) {
        perror("CM CreateQueue error");
        return -1;
    }

    CmTask *pKernelArray = NULL;

    result = pCmDev->CreateTask(pKernelArray);
    if (result != CM_SUCCESS ) {
        printf("CmDevice CreateTask error");
        return -1;
    }

    result = pKernelArray-> AddKernel (kernel);
    if (result != CM_SUCCESS ) {
        printf("CmDevice AddKernel error");
        return -1;
    }

    CmEvent* e = NULL;
    result = pCmQueue->Enqueue(pKernelArray, e, pTS);
    if (result != CM_SUCCESS ) {
        printf("CmDevice enqueue error");
        return -1;
    }

    pCmDev->DestroyTask(pKernelArray);
    result = pOutputSurf->ReadSurface( dst, e );
    if (result != CM_SUCCESS ) {
        printf("CM ReadSurface error");
        return -1;
    }

	for (unsigned int i = 0; i < width*height*4; i++) {
        if (src[i] / d != dst[i]) {
			printf("test failed at %d, expected %d, got %d\n", i, src[i]/d, dst[i]);
			return -1;
		}
    }

	printf("test passed!\n");

    result = DestroyCmDevice( pCmDev );

    free(pCommonISACode);
    free(src);
    free(dst);

    return 0;
}

*/

#include "utest_helper.hpp"
#include "utest_file_map.hpp"
#include <string.h>

void runtime_cmrt(void)
{
  uint32_t w = 256;
  uint32_t h = 128;
  cl_int status;
  cl_int binary_status;
  char *ker_path = NULL;

  cl_file_map_t *fm = cl_file_map_new();
  ker_path = cl_do_kiss_path("cmrt_utest_genx.isa", NULL);
  OCL_ASSERT (cl_file_map_open(fm, ker_path) == CL_FILE_MAP_SUCCESS);

  const unsigned char *kbin = (const unsigned char *)cl_file_map_begin(fm);
  const size_t sz = cl_file_map_size(fm);

  program = clCreateProgramWithBinary(ctx, 1,
            &device, &sz, &kbin, &binary_status, &status);

  OCL_ASSERT(program && status == CL_SUCCESS);

  /* OCL requires to build the program even if it is created from a binary */
  OCL_ASSERT(clBuildProgram(program, 1, &device, NULL, NULL, NULL) == CL_SUCCESS);

  kernel = clCreateKernel(program, "simplemov", &status);
  OCL_ASSERT(status == CL_SUCCESS);

  cl_image_format format;
  cl_image_desc desc;

  memset(&desc, 0x0, sizeof(cl_image_desc));
  memset(&format, 0x0, sizeof(cl_image_format));

  format.image_channel_order = CL_BGRA;
  format.image_channel_data_type = CL_UNORM_INT8;
  desc.image_type = CL_MEM_OBJECT_IMAGE2D;
  desc.image_width = w;
  desc.image_height = h;
  desc.image_row_pitch = 0;

  OCL_CREATE_IMAGE(buf[0], 0, &format, &desc, NULL);
  OCL_CREATE_IMAGE(buf[1], 0, &format, &desc, NULL);

  OCL_MAP_BUFFER(0);
  OCL_MAP_BUFFER(1);
  uint8_t* src = (uint8_t*)buf_data[0];
  uint8_t* dst = (uint8_t*)buf_data[1];
  for (uint32_t j = 0; j < h; ++j)
    for (uint32_t i = 0; i < w*4; i++) {
      src[j * w * 4 + i] = i;
      dst[j * w * 4 + i] = 0;
    }
  OCL_UNMAP_BUFFER(0);
  OCL_UNMAP_BUFFER(1);

  unsigned int d = 3;
  OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
  OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
  OCL_SET_ARG(2, sizeof(unsigned int), &d);
  globals[0] = w;
  globals[1] = h;

  //if kernel uses get_origin_thread_x/y, locals must be NULL to invoke pCmQueue->Enqueue
  //if kernel uses cm_linear_global_id, locals must be not NULL to invoke pCmQueue->EnqueueWithGroup
  OCL_CALL (clEnqueueNDRangeKernel, queue, kernel, 2, NULL, globals, NULL, 0, NULL, NULL);

  OCL_MAP_BUFFER(0);
  OCL_MAP_BUFFER(1);
  src = (uint8_t*)buf_data[0];
  dst = (uint8_t*)buf_data[1];
  for (uint32_t j = 0; j < h; ++j)
    for (uint32_t i = 0; i < w*4; i++) {
      OCL_ASSERT(src[j * w * 4 + i] / d == dst[j * w * 4 + i]);
    }
  OCL_UNMAP_BUFFER(0);
  OCL_UNMAP_BUFFER(1);
}

MAKE_UTEST_FROM_FUNCTION(runtime_cmrt);
<commit_msg>use OCL_MAP_BUFFER_GTT to map climage<commit_after>/*
this test case shows how to execute CM kernel via OpenCL APIs.
the CM kernel source code is already compiled into file "cmrt_utest_genx.isa" with offline compiler.

I also copied the CM kernel source code and CM host source code here for your reference.

CM kernel source code:
#include <cm/cm.h>
extern "C" _GENX_MAIN_  void
simplemov(SurfaceIndex ibuf, SurfaceIndex obuf, uint d)
{
    matrix<uchar, 1, 4> in;
    matrix<uchar, 1, 4> out;

	uint h_pos = get_thread_origin_x();
	uint v_pos = get_thread_origin_y();

	read(ibuf, h_pos*4, v_pos, in);

	out = in / d;
	write(obuf, h_pos*4, v_pos, out);
}

CM host source code:
#include "cm_rt.h"

int main()
{
    FILE* pISA = fopen("cmrt_utest_genx.isa", "rb");
    if (pISA == NULL) {
        perror("cmrt_utest_genx.isa");
        return -1;
    }

    fseek (pISA, 0, SEEK_END);
    int codeSize = ftell (pISA);
    rewind(pISA);

    if(codeSize == 0)
    {
        perror("cmrt_utest_genx.isa");
        return -1;
    }

    void *pCommonISACode = (BYTE*) malloc(codeSize);
    if( !pCommonISACode )
    {
        return -1;
    }

    if (fread(pCommonISACode, 1, codeSize, pISA) != codeSize) {
        perror("cmrt_utest_genx.isa");
        return -1;
    }
    fclose(pISA);

    unsigned int  width = 256;
    unsigned int  height = 128;

    unsigned char *src;
    unsigned char *dst;
    src = (unsigned char*) malloc(width*height*4);
    dst = (unsigned char*) malloc(width*height*4);

    for (unsigned int i = 0; i < width*height*4; i++) {
        src[i] = i % 256;
        dst[i] = 0;
    }

    CmDevice* pCmDev = NULL;;
    UINT version = 0;

    int result = CreateCmDevice( pCmDev, version );
    if (result != CM_SUCCESS ) {
        printf("CmDevice creation error");
        return -1;
    }
    if( version < CM_1_0 ){
        printf(" The runtime API version is later than runtime DLL version");
        return -1;
    }

    CmProgram* program = NULL;
    result = pCmDev->LoadProgram(pCommonISACode, codeSize, program);
    if (result != CM_SUCCESS ) {
        perror("CM LoadProgram error");
        return -1;
    }

    CmKernel* kernel = NULL;
    result = pCmDev->CreateKernel(program, CM_KERNEL_FUNCTION(simplemov) , kernel);
    if (result != CM_SUCCESS ) {
        perror("CM CreateKernel error");
        return -1;
    }

    CmSurface2D*  pInputSurf = NULL;
    result = pCmDev->CreateSurface2D( width, height, CM_SURFACE_FORMAT_A8R8G8B8, pInputSurf );
    if (result != CM_SUCCESS ) {
        printf("CM CreateSurface2D error");
        return -1;
    }

    CmSurface2D*  pOutputSurf = NULL;
    result = pCmDev->CreateSurface2D( width, height, CM_SURFACE_FORMAT_A8R8G8B8, pOutputSurf );
    if (result != CM_SUCCESS ) {
        printf("CM CreateSurface2D error");
        return -1;
    }

    result = pInputSurf->WriteSurface( src, NULL );
    if (result != CM_SUCCESS ) {
        printf("CM WriteSurface error");
        return -1;
    }

    kernel->SetThreadCount( width * height );

    CmThreadSpace* pTS = NULL;
    result = pCmDev->CreateThreadSpace(width, height, pTS);
    if (result != CM_SUCCESS ) {
        printf("CM WriteSurface error");
        return -1;
    }

    SurfaceIndex * index0= NULL;
    pInputSurf->GetIndex(index0);
    kernel->SetKernelArg(0,sizeof(SurfaceIndex),index0);

    SurfaceIndex * index1= NULL;
    pOutputSurf->GetIndex(index1);
    kernel->SetKernelArg(1,sizeof(SurfaceIndex),index1);

	unsigned int  d = 3;
	kernel->SetKernelArg(2, sizeof(unsigned int), &d);

    CmQueue* pCmQueue = NULL;
    result = pCmDev->CreateQueue( pCmQueue );
    if (result != CM_SUCCESS ) {
        perror("CM CreateQueue error");
        return -1;
    }

    CmTask *pKernelArray = NULL;

    result = pCmDev->CreateTask(pKernelArray);
    if (result != CM_SUCCESS ) {
        printf("CmDevice CreateTask error");
        return -1;
    }

    result = pKernelArray-> AddKernel (kernel);
    if (result != CM_SUCCESS ) {
        printf("CmDevice AddKernel error");
        return -1;
    }

    CmEvent* e = NULL;
    result = pCmQueue->Enqueue(pKernelArray, e, pTS);
    if (result != CM_SUCCESS ) {
        printf("CmDevice enqueue error");
        return -1;
    }

    pCmDev->DestroyTask(pKernelArray);
    result = pOutputSurf->ReadSurface( dst, e );
    if (result != CM_SUCCESS ) {
        printf("CM ReadSurface error");
        return -1;
    }

	for (unsigned int i = 0; i < width*height*4; i++) {
        if (src[i] / d != dst[i]) {
			printf("test failed at %d, expected %d, got %d\n", i, src[i]/d, dst[i]);
			return -1;
		}
    }

	printf("test passed!\n");

    result = DestroyCmDevice( pCmDev );

    free(pCommonISACode);
    free(src);
    free(dst);

    return 0;
}

*/

#include "utest_helper.hpp"
#include "utest_file_map.hpp"
#include <string.h>

void runtime_cmrt(void)
{
  uint32_t w = 256;
  uint32_t h = 128;
  cl_int status;
  cl_int binary_status;
  char *ker_path = NULL;

  cl_file_map_t *fm = cl_file_map_new();
  ker_path = cl_do_kiss_path("cmrt_utest_genx.isa", NULL);
  OCL_ASSERT (cl_file_map_open(fm, ker_path) == CL_FILE_MAP_SUCCESS);

  const unsigned char *kbin = (const unsigned char *)cl_file_map_begin(fm);
  const size_t sz = cl_file_map_size(fm);

  program = clCreateProgramWithBinary(ctx, 1,
            &device, &sz, &kbin, &binary_status, &status);

  OCL_ASSERT(program && status == CL_SUCCESS);

  /* OCL requires to build the program even if it is created from a binary */
  OCL_ASSERT(clBuildProgram(program, 1, &device, NULL, NULL, NULL) == CL_SUCCESS);

  kernel = clCreateKernel(program, "simplemov", &status);
  OCL_ASSERT(status == CL_SUCCESS);

  cl_image_format format;
  cl_image_desc desc;

  memset(&desc, 0x0, sizeof(cl_image_desc));
  memset(&format, 0x0, sizeof(cl_image_format));

  format.image_channel_order = CL_BGRA;
  format.image_channel_data_type = CL_UNORM_INT8;
  desc.image_type = CL_MEM_OBJECT_IMAGE2D;
  desc.image_width = w;
  desc.image_height = h;
  desc.image_row_pitch = 0;

  OCL_CREATE_IMAGE(buf[0], 0, &format, &desc, NULL);
  OCL_CREATE_IMAGE(buf[1], 0, &format, &desc, NULL);

  OCL_MAP_BUFFER_GTT(0);
  OCL_MAP_BUFFER_GTT(1);
  uint8_t* src = (uint8_t*)buf_data[0];
  uint8_t* dst = (uint8_t*)buf_data[1];
  for (uint32_t j = 0; j < h; ++j)
    for (uint32_t i = 0; i < w*4; i++) {
      src[j * w * 4 + i] = i;
      dst[j * w * 4 + i] = 0;
    }
  OCL_UNMAP_BUFFER_GTT(0);
  OCL_UNMAP_BUFFER_GTT(1);

  unsigned int d = 3;
  OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
  OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
  OCL_SET_ARG(2, sizeof(unsigned int), &d);
  globals[0] = w;
  globals[1] = h;

  //if kernel uses get_origin_thread_x/y, locals must be NULL to invoke pCmQueue->Enqueue
  //if kernel uses cm_linear_global_id, locals must be not NULL to invoke pCmQueue->EnqueueWithGroup
  OCL_CALL (clEnqueueNDRangeKernel, queue, kernel, 2, NULL, globals, NULL, 0, NULL, NULL);

  OCL_MAP_BUFFER_GTT(0);
  OCL_MAP_BUFFER_GTT(1);
  src = (uint8_t*)buf_data[0];
  dst = (uint8_t*)buf_data[1];
  for (uint32_t j = 0; j < h; ++j)
    for (uint32_t i = 0; i < w*4; i++) {
      OCL_ASSERT(src[j * w * 4 + i] / d == dst[j * w * 4 + i]);
    }
  OCL_UNMAP_BUFFER_GTT(0);
  OCL_UNMAP_BUFFER_GTT(1);
}

MAKE_UTEST_FROM_FUNCTION(runtime_cmrt);
<|endoftext|>


<commit_before><commit_msg>Handler now returns true or false<commit_after><|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "Exception.h"
#include "Backtrace.h"
#include "Logger.h"

#include <cstdlib>
#include <sstream>

using namespace std;

namespace avg {

Exception::Exception (int Code, const std::string& sErr)
    : m_Code (Code),
      m_sErr (sErr)
{
}

Exception::Exception (const Exception& ex)
    : m_Code (ex.GetCode ()),
      m_sErr (ex.GetStr ())
{
}

Exception::~Exception()
{
}

int Exception::GetCode () const
{
    return m_Code;
}

const string& Exception::GetStr () const
{
    return m_sErr;
}

void fatalError(const std::string& sMsg)
{
    AVG_TRACE(Logger::ERROR, "Internal error: "+sMsg+" Aborting.");
    exit(-1);
}

void debugBreak()
{
#ifdef _WIN32
    __asm int 3;
#else
    asm("int $3");
#endif
}

void avgAssert(bool b, const char * pszFile, int line)
{
    if (!b) {
        stringstream ss;
        ss << "Assertion failed in " << pszFile << ": " << line;
//        debugBreak();
        dumpBacktrace();
        throw(Exception(AVG_ERR_ASSERT_FAILED, ss.str()));
    }
}

}

<commit_msg>Added AVG_BREAK_ON_ASSERT support: If this env var is set, a failed AVG_ASSERT triggers a debug breakpoint.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "Exception.h"
#include "Backtrace.h"
#include "Logger.h"
#include "OSHelper.h"

#include <cstdlib>
#include <sstream>

using namespace std;

namespace avg {

Exception::Exception (int Code, const std::string& sErr)
    : m_Code (Code),
      m_sErr (sErr)
{
}

Exception::Exception (const Exception& ex)
    : m_Code (ex.GetCode ()),
      m_sErr (ex.GetStr ())
{
}

Exception::~Exception()
{
}

int Exception::GetCode () const
{
    return m_Code;
}

const string& Exception::GetStr () const
{
    return m_sErr;
}

void fatalError(const std::string& sMsg)
{
    AVG_TRACE(Logger::ERROR, "Internal error: "+sMsg+" Aborting.");
    exit(-1);
}

void debugBreak()
{
#ifdef _WIN32
    __asm int 3;
#else
    asm("int $3");
#endif
}

void avgAssert(bool b, const char * pszFile, int line)
{
    if (!b) {
        string sDummy;
        static bool bBreak = getEnv("AVG_BREAK_ON_ASSERT", sDummy);
        if (bBreak) {
            debugBreak();
        } else {
            stringstream ss;
            ss << "Assertion failed in " << pszFile << ": " << line;
            dumpBacktrace();
            throw(Exception(AVG_ERR_ASSERT_FAILED, ss.str()));
        }
    }
}

}
<|endoftext|>


<commit_before>#ifndef CCSR_HPP
#define CCSR_HPP

/**
 * \file   ccsr.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  Compressed CSR format composition.
 *
 * Lossy compression for CSR format. Stores unique matrix rows, where
 * uniqueness is determined approximately. If the precision loss is not
 * important (e.g. coefficients come from an experiment with incorporated
 * observation error), it may result in significant storage savings for large
 * matrices.
 */

#include <vector>
#include <deque>
#include <type_traits>
#include <memory>
#include <functional>
#include <exception>
#include <cassert>

#include <boost/unordered_set.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/zip_iterator.hpp>

namespace ccsr {

template <typename T>
struct hash_impl {
    static inline size_t get(T v) {
        return std::hash<T>()(v);
    }
};

template <>
struct hash_impl<double> {
    static inline size_t get(double v) {
        static const uint64_t mask = 0xffffffffff000000;
                                    // eeefffffffffffff;
        // Zero-out least significant bits and hash as uint64_t:
        return std::hash<uint64_t>()(*reinterpret_cast<const uint64_t*>(&v) & mask);
    }
};

template <>
struct hash_impl<float> {
    static inline size_t get(float v) {
        static const uint32_t mask = 0xfffffc00;
                                    // eeffffff;
        // Zero-out least significant bits and hash as uint64_t:
        return std::hash<uint32_t>()(*reinterpret_cast<const uint32_t*>(&v) & mask);
    }
};

template <class T>
inline size_t hash(const T &v) {
    return hash_impl<T>::get(v);
}

template <
    typename val_t = double,
    typename row_t = size_t,
    typename col_t = ptrdiff_t,
    typename idx_t = row_t
    >
class matrix {
    static_assert(std::is_signed<col_t>::value, "Column type should be signed!");

    private:
        size_t rows, cols;

        std::vector< idx_t > idx;
        std::vector< row_t > row;
        std::vector< col_t > col;
        std::vector< val_t > val;

        struct shift {
            template <class Sig>
            struct result {
                typedef col_t type;
            };

            col_t s;

            shift(col_t s) : s(s) {}

            col_t operator()(col_t v) const {
                return v + s;
            }
        };

        struct builder_t {
            std::deque< idx_t > idx;
            std::deque< row_t > row;
            std::deque< col_t > col;
            std::deque< val_t > val;

            struct row_hasher {
                val_t eps;

                row_hasher(val_t eps) : eps(eps) {}

                template <class Range>
                size_t operator()(const Range &r) const {
                    using boost::get;

                    auto begin = get<0>(r);
                    auto end   = get<1>(r);

                    size_t h = hash(end - begin);

                    for(auto i = begin; i != end; ++i)
                        h ^= hash(get<0>(*i)) ^ hash(get<1>(*i));

                    return h;
                }

                template <class Range1, class Range2>
                bool operator()(const Range1 &r1, const Range2 &r2) const {
                    using boost::get;

                    auto i1 = get<0>(r1);
                    auto e1 = get<1>(r1);
                    auto i2 = get<0>(r2);
                    auto e2 = get<1>(r2);

                    if (e1 - i1 != e2 - i2) return false;

                    for(; i1 != e1; ++i1, ++i2) {
                        if (get<0>(*i1) != get<0>(*i2))
                            return false;

                        if (fabs(get<1>(*i1) - get<1>(*i2)) > eps)
                            return false;
                    }

                    return true;
                }
            } hasher;

            typedef boost::zip_iterator<
                        boost::tuple<
                            typename std::deque< col_t >::const_iterator,
                            typename std::deque< val_t >::const_iterator
                        >
                    > row_iterator;

            typedef boost::tuple< row_iterator, row_iterator, size_t > row_range;

            boost::unordered_set<row_range, row_hasher, row_hasher> index;

            builder_t(val_t eps = 1e-5f)
                : hasher(eps), index(1979, hasher, hasher)
            {
                row.push_back(0);
            }

            void insert(col_t row_begin, col_t row_end,
                    const row_t *r, const col_t *c, const val_t *v)
            {
                for(col_t i = row_begin, j = 0; i < row_end; ++i, ++j) {
                    auto range = boost::make_tuple(
                            boost::make_zip_iterator(
                                boost::make_tuple(
                                    boost::make_transform_iterator(
                                        c + r[j], shift(-i)
                                        ),
                                    v + r[j])
                                ),
                            boost::make_zip_iterator(
                                boost::make_tuple(
                                    boost::make_transform_iterator(
                                        c + r[j + 1], shift(-i)
                                        ),
                                    v + r[j + 1])
                                )
                            );

                    auto pos = index.find(range, hasher, hasher);

                    if (pos == index.end()) {
                        idx.push_back(index.size());

                        size_t start = val.size();

                        for(size_t k = r[j]; k < r[j+1]; ++k) {
                            col.push_back( c[k] - i );
                            val.push_back( v[k] );
                        }

                        index.insert(
                                boost::make_tuple(
                                    boost::make_zip_iterator(
                                        boost::make_tuple(
                                            col.begin() + start,
                                            val.begin() + start)
                                        ),
                                    boost::make_zip_iterator(
                                        boost::make_tuple(
                                            col.end(),
                                            val.end()
                                            )
                                        ),
                                    index.size()
                                    )
                                );

                        row.push_back(val.size());
                    } else {
                        idx.push_back(boost::get<2>(*pos));
                    }
                }
            }
        };

        std::unique_ptr<builder_t> builder;

    public:
        typedef boost::transform_iterator<
                    shift, typename std::vector<col_t>::const_iterator
                > column_iterator;

        typedef boost::tuple<
                    column_iterator, typename std::vector<val_t>::const_iterator
                > const_iterator_tuple;

        typedef boost::zip_iterator<const_iterator_tuple>
                const_row_iterator;

        /// Constructor.
        matrix(size_t rows, size_t cols, val_t eps = 1e-5)
            : rows(rows), cols(cols), builder(new builder_t(eps))
        {
        }

        void insert(col_t row_begin, col_t row_end,
                const row_t *r, const col_t *c, const val_t *v)
        {
            builder->insert(row_begin, row_end, r, c, v);
        }

        size_t finish() {
            if (builder->idx.size() != rows) throw std::logic_error(
                    "Matrix construction is incomplete "
                    "(some rows are left untouched)"
                    );

            idx.assign(builder->idx.begin(), builder->idx.end());
            row.assign(builder->row.begin(), builder->row.end());
            col.assign(builder->col.begin(), builder->col.end());
            val.assign(builder->val.begin(), builder->val.end());

            builder.reset();

            return row.size() - 1;
        }

        /// Begin boost::zip_iterator to columns/values for a given row.
        const_row_iterator begin(size_t i) const {
            assert(!builder && i < rows);

            return const_row_iterator(
                    const_iterator_tuple(
                        column_iterator(col.begin() + row[idx[i]], shift(i)),
                        val.begin() + row[idx[i]]
                        )
                    );
        }

        /// End boost::zip_iterator to columns/values for a given row.
        const_row_iterator end(size_t i) const {
            assert(!builder && i < rows);

            return const_row_iterator(
                    const_iterator_tuple(
                        column_iterator(col.begin() + row[idx[i] + 1], shift(i)),
                        val.begin() + row[idx[i] + 1]
                        )
                    );
        }
};

} // namespace ccsr

#endif
<commit_msg>Removed unnecessary typedefs<commit_after>#ifndef CCSR_HPP
#define CCSR_HPP

/**
 * \file   ccsr.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  Compressed CSR format composition.
 *
 * Lossy compression for CSR format. Stores unique matrix rows, where
 * uniqueness is determined approximately. If the precision loss is not
 * important (e.g. coefficients come from an experiment with incorporated
 * observation error), it may result in significant storage savings for large
 * matrices.
 */

#include <vector>
#include <deque>
#include <type_traits>
#include <memory>
#include <functional>
#include <exception>
#include <cassert>

#include <boost/unordered_set.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/zip_iterator.hpp>

namespace ccsr {

template <typename T>
struct hash_impl {
    static inline size_t get(T v) {
        return std::hash<T>()(v);
    }
};

template <>
struct hash_impl<double> {
    static inline size_t get(double v) {
        static const uint64_t mask = 0xffffffffff000000;
                                    // eeefffffffffffff;
        // Zero-out least significant bits and hash as uint64_t:
        return std::hash<uint64_t>()(*reinterpret_cast<const uint64_t*>(&v) & mask);
    }
};

template <>
struct hash_impl<float> {
    static inline size_t get(float v) {
        static const uint32_t mask = 0xfffffc00;
                                    // eeffffff;
        // Zero-out least significant bits and hash as uint64_t:
        return std::hash<uint32_t>()(*reinterpret_cast<const uint32_t*>(&v) & mask);
    }
};

template <class T>
inline size_t hash(const T &v) {
    return hash_impl<T>::get(v);
}

template <
    typename val_t = double,
    typename row_t = size_t,
    typename col_t = ptrdiff_t,
    typename idx_t = row_t
    >
class matrix {
    static_assert(std::is_signed<col_t>::value, "Column type should be signed!");

    private:
        size_t rows, cols;

        std::vector< idx_t > idx;
        std::vector< row_t > row;
        std::vector< col_t > col;
        std::vector< val_t > val;

        struct shift {
            typedef col_t result_type;

            col_t s;

            shift(col_t s) : s(s) {}

            col_t operator()(col_t v) const {
                return v + s;
            }
        };

        struct builder_t {
            std::deque< idx_t > idx;
            std::deque< row_t > row;
            std::deque< col_t > col;
            std::deque< val_t > val;

            struct row_hasher {
                val_t eps;

                row_hasher(val_t eps) : eps(eps) {}

                template <class Range>
                size_t operator()(const Range &r) const {
                    using boost::get;

                    auto begin = get<0>(r);
                    auto end   = get<1>(r);

                    size_t h = hash(end - begin);

                    for(auto i = begin; i != end; ++i)
                        h ^= hash(get<0>(*i)) ^ hash(get<1>(*i));

                    return h;
                }

                template <class Range1, class Range2>
                bool operator()(const Range1 &r1, const Range2 &r2) const {
                    using boost::get;

                    auto i1 = get<0>(r1);
                    auto e1 = get<1>(r1);
                    auto i2 = get<0>(r2);
                    auto e2 = get<1>(r2);

                    if (e1 - i1 != e2 - i2) return false;

                    for(; i1 != e1; ++i1, ++i2) {
                        if (get<0>(*i1) != get<0>(*i2))
                            return false;

                        if (fabs(get<1>(*i1) - get<1>(*i2)) > eps)
                            return false;
                    }

                    return true;
                }
            } hasher;

            typedef boost::zip_iterator<
                        boost::tuple<
                            typename std::deque< col_t >::const_iterator,
                            typename std::deque< val_t >::const_iterator
                        >
                    > row_iterator;

            typedef boost::tuple< row_iterator, row_iterator, size_t > row_range;

            boost::unordered_set<row_range, row_hasher, row_hasher> index;

            builder_t(val_t eps = 1e-5f)
                : hasher(eps), index(1979, hasher, hasher)
            {
                row.push_back(0);
            }

            void insert(col_t row_begin, col_t row_end,
                    const row_t *r, const col_t *c, const val_t *v)
            {
                for(col_t i = row_begin, j = 0; i < row_end; ++i, ++j) {
                    shift s(-i);

                    auto range = boost::make_tuple(
                            boost::make_zip_iterator(
                                boost::make_tuple(
                                    boost::make_transform_iterator(c + r[j], s),
                                    v + r[j])
                                ),
                            boost::make_zip_iterator(
                                boost::make_tuple(
                                    boost::make_transform_iterator(c + r[j+1], s),
                                    v + r[j+1])
                                )
                            );

                    auto pos = index.find(range, hasher, hasher);

                    if (pos == index.end()) {
                        idx.push_back(index.size());

                        size_t start = val.size();

                        for(size_t k = r[j]; k < r[j+1]; ++k) {
                            col.push_back( c[k] - i );
                            val.push_back( v[k] );
                        }

                        index.insert(
                                boost::make_tuple(
                                    boost::make_zip_iterator(
                                        boost::make_tuple(
                                            col.begin() + start,
                                            val.begin() + start)
                                        ),
                                    boost::make_zip_iterator(
                                        boost::make_tuple(
                                            col.end(),
                                            val.end()
                                            )
                                        ),
                                    index.size()
                                    )
                                );

                        row.push_back(val.size());
                    } else {
                        idx.push_back(boost::get<2>(*pos));
                    }
                }
            }
        };

        std::unique_ptr<builder_t> builder;

    public:
        typedef boost::zip_iterator<
                    boost::tuple<
                        boost::transform_iterator<
                            shift, typename std::vector<col_t>::const_iterator
                        >,
                        typename std::vector<val_t>::const_iterator
                    >
                > const_row_iterator;

        /// Constructor.
        matrix(size_t rows, size_t cols, val_t eps = 1e-5)
            : rows(rows), cols(cols), builder(new builder_t(eps))
        {
        }

        void insert(col_t row_begin, col_t row_end,
                const row_t *r, const col_t *c, const val_t *v)
        {
            builder->insert(row_begin, row_end, r, c, v);
        }

        size_t finish() {
            if (builder->idx.size() != rows) throw std::logic_error(
                    "Matrix construction is incomplete "
                    "(some rows are left untouched)"
                    );

            idx.assign(builder->idx.begin(), builder->idx.end());
            row.assign(builder->row.begin(), builder->row.end());
            col.assign(builder->col.begin(), builder->col.end());
            val.assign(builder->val.begin(), builder->val.end());

            builder.reset();

            return row.size() - 1;
        }

        /// Begin boost::zip_iterator to columns/values for a given row.
        const_row_iterator begin(size_t i) const {
            assert(!builder && i < rows);

            return boost::make_zip_iterator(
                    boost::make_tuple(
                        boost::make_transform_iterator(
                            col.begin() + row[idx[i]],
                            shift(i)
                            ),
                        val.begin() + row[idx[i]]
                        )
                    );
        }

        /// End boost::zip_iterator to columns/values for a given row.
        const_row_iterator end(size_t i) const {
            assert(!builder && i < rows);

            return boost::make_zip_iterator(
                    boost::make_tuple(
                        boost::make_transform_iterator(
                            col.begin() + row[idx[i] + 1],
                            shift(i)
                            ),
                        val.begin() + row[idx[i] + 1]
                        )
                    );
        }
};

} // namespace ccsr

#endif
<|endoftext|>


<commit_before>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
using namespace GiNaC;

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        cout << "Usage: " << argv[0] << " <graph-series-filename> <variable-name>\n";
        return 1;
    }

    // Reading in graph series:
    string graph_series_filename(argv[1]);
    ifstream graph_series_file(graph_series_filename);
    parser coefficient_reader;
    KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });

    ex variable = coefficient_reader(string(argv[2]));

    for (size_t n = 0; n <= graph_series.precision(); ++n)
        for (auto& term : graph_series[n])
            term.first = term.first.coeff(variable);

    graph_series.reduce();

    for (size_t n = 0; n <= graph_series.precision(); ++n)
    {
        if (graph_series[n] != 0 || n == graph_series.precision())
            cout << "h^" << n << ":\n";
        for (auto& term : graph_series[n])
            cout << term.second.encoding() << "    " << term.first << "\n";
    }
}
<commit_msg>Clarify usage of extract_coefficient<commit_after>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
using namespace GiNaC;

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        cout << "Usage: " << argv[0] << " <graph-series-filename> <expression>\n";
        return 1;
    }

    // Reading in graph series:
    string graph_series_filename(argv[1]);
    ifstream graph_series_file(graph_series_filename);
    parser coefficient_reader;
    KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });

    ex expression = coefficient_reader(string(argv[2]));

    for (size_t n = 0; n <= graph_series.precision(); ++n)
        for (auto& term : graph_series[n])
            term.first = term.first.coeff(expression);

    graph_series.reduce();

    for (size_t n = 0; n <= graph_series.precision(); ++n)
    {
        if (graph_series[n] != 0 || n == graph_series.precision())
            cout << "h^" << n << ":\n";
        for (auto& term : graph_series[n])
            cout << term.second.encoding() << "    " << term.first << "\n";
    }
}
<|endoftext|>