<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "shell.h"

#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/renderer_preferences.h"
#include "shell_browser_context.h"
#include "shell_content_browser_client.h"
#include "shell_switches.h"
#include "third_party/skia/include/core/SkColor.h"

namespace content {

namespace {

// Callback for Debug > Show web inspector... menu item.
gboolean ShowWebInspectorActivated(GtkWidget* widget, Shell* shell) {
  shell->ShowDevTools();
  return FALSE;  // Don't stop this message.
}

GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text,
                        GCallback callback, Shell* shell) {
  GtkWidget* entry = gtk_menu_item_new_with_mnemonic(text);
  g_signal_connect(entry, "activate", callback, shell);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), entry);
  return entry;
}

GtkWidget* CreateMenu(GtkWidget* menu_bar, const char* text) {
  GtkWidget* menu_widget = gtk_menu_new();
  GtkWidget* menu_header = gtk_menu_item_new_with_label(text);
  gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_header), menu_widget);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), menu_header);
  return menu_widget;
}

GtkWidget* CreateMenuBar(Shell* shell) {
  GtkWidget* menu_bar = gtk_menu_bar_new();
  GtkWidget* debug_menu = CreateMenu(menu_bar, "Debug");
  AddMenuEntry(debug_menu, "_Show Developer Tools...",
               G_CALLBACK(ShowWebInspectorActivated), shell);
  return menu_bar;
}

}  // namespace

void Shell::PlatformInitialize() {
}

void Shell::PlatformCleanUp() {
  // Nothing to clean up; GTK will clean up the widgets shortly after.
}

void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
  GtkToolItem* item = NULL;
  switch (control) {
    case BACK_BUTTON:
      item = back_button_;
      break;
    case FORWARD_BUTTON:
      item = forward_button_;
      break;
    case STOP_BUTTON:
      item = stop_button_;
      break;
    default:
      NOTREACHED() << "Unknown UI control";
      return;
  }
  gtk_widget_set_sensitive(GTK_WIDGET(item), is_enabled);
}

void Shell::PlatformSetAddressBarURL(const GURL& url) {
  gtk_entry_set_text(GTK_ENTRY(url_edit_view_), url.spec().c_str());
}

void Shell::PlatformSetIsLoading(bool loading) {
  if (loading)
    gtk_spinner_start(GTK_SPINNER(spinner_));
  else
    gtk_spinner_stop(GTK_SPINNER(spinner_));
}

void Shell::PlatformCreateWindow(int width, int height) {
  window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
  gtk_window_set_title(window_, "node-webkit");
  gtk_window_set_default_size(window_, width, height);
  g_signal_connect(G_OBJECT(window_), "destroy",
                   G_CALLBACK(OnWindowDestroyedThunk), this);

  if (window_manifest_) {
    // window.x and window.y
    int x, y;
    if (window_manifest_->GetInteger(switches::kmX, &x) &&
        window_manifest_->GetInteger(switches::kmY, &y)) {
      gtk_window_move(window_, x, y);
    } else {
      // window.postion
      std::string desription;
      if (window_manifest_->GetString(switches::kmPosition, &desription)) {
        if (desription == "center")
          gtk_window_set_position(window_, GTK_WIN_POS_CENTER);
        else if (desription == "mouse")
          gtk_window_set_position(window_, GTK_WIN_POS_MOUSE);
      }
    }

    GdkGeometry geometry = { 0 };
    int hints = GDK_HINT_POS;
    int tmp = -1;
    if (window_manifest_->GetInteger(switches::kmMinWidth, &tmp)) {
      hints |= GDK_HINT_MIN_SIZE;
      geometry.min_width = tmp;
    }
    if (window_manifest_->GetInteger(switches::kmMinHeight, &tmp)) {
      hints |= GDK_HINT_MIN_SIZE;
      geometry.min_height = tmp;
    }
    if (window_manifest_->GetInteger(switches::kmMaxWidth, &tmp)) {
      hints |= GDK_HINT_MAX_SIZE;
      geometry.max_width = tmp;
    }
    if (window_manifest_->GetInteger(switches::kmMaxHeight, &tmp)) {
      hints |= GDK_HINT_MAX_SIZE;
      geometry.max_height = tmp;
    }
    if (hints != GDK_HINT_POS) {
      gtk_window_set_geometry_hints(
          window_, GTK_WIDGET(window_), &geometry, (GdkWindowHints)hints);
    }
  }

  vbox_ = gtk_vbox_new(FALSE, 0);

  // Create the menu bar.
  GtkWidget* menu_bar = CreateMenuBar(this);
  if (is_show_devtools_) {
    gtk_box_pack_start(GTK_BOX(vbox_), menu_bar, FALSE, FALSE, 0);
  }

  // Create the object that mediates accelerators.
  GtkAccelGroup* accel_group = gtk_accel_group_new();
  gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group);

  // Set global window handling accelerators:
  gtk_accel_group_connect(
      accel_group, GDK_w, GDK_CONTROL_MASK,
      GTK_ACCEL_VISIBLE,
      g_cclosure_new(G_CALLBACK(OnCloseWindowKeyPressedThunk),
                     this, NULL));

  gtk_accel_group_connect(
      accel_group, GDK_n, GDK_CONTROL_MASK,
      GTK_ACCEL_VISIBLE,
      g_cclosure_new(G_CALLBACK(OnNewWindowKeyPressedThunk),
                    this, NULL));

  GtkWidget* toolbar = gtk_toolbar_new();
  // Turn off the labels on the toolbar buttons.
  gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);

  back_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_GO_BACK);
  g_signal_connect(back_button_, "clicked",
                   G_CALLBACK(&OnBackButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), back_button_, -1 /* append */);
  gtk_widget_add_accelerator(GTK_WIDGET(back_button_), "clicked", accel_group,
                             GDK_Left, GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

  forward_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_GO_FORWARD);
  g_signal_connect(forward_button_, "clicked",
                   G_CALLBACK(&OnForwardButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), forward_button_, -1 /* append */);
  gtk_widget_add_accelerator(GTK_WIDGET(forward_button_), "clicked",
                             accel_group,
                             GDK_Right, GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

  reload_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_REFRESH);
  g_signal_connect(reload_button_, "clicked",
                   G_CALLBACK(&OnReloadButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), reload_button_, -1 /* append */);
  gtk_widget_add_accelerator(GTK_WIDGET(reload_button_), "clicked",
                             accel_group,
                             GDK_r, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

  stop_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_STOP);
  g_signal_connect(stop_button_, "clicked",
                   G_CALLBACK(&OnStopButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), stop_button_, -1 /* append */);

  url_edit_view_ = gtk_entry_new();
  g_signal_connect(G_OBJECT(url_edit_view_), "activate",
                   G_CALLBACK(&OnURLEntryActivateThunk), this);

  gtk_accel_group_connect(
      accel_group, GDK_l, GDK_CONTROL_MASK,
      GTK_ACCEL_VISIBLE,
      g_cclosure_new(G_CALLBACK(OnHighlightURLViewThunk),
                     this, NULL));

  GtkToolItem* tool_item = gtk_tool_item_new();
  gtk_container_add(GTK_CONTAINER(tool_item), url_edit_view_);
  gtk_tool_item_set_expand(tool_item, TRUE);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool_item, -1 /* append */);

  // Center a 20x20 spinner in a 26x24 area.
  GtkWidget* spinner_alignment = gtk_alignment_new(0.5, 0.5, 0, 0);
  gtk_alignment_set_padding(GTK_ALIGNMENT(spinner_alignment), 2, 2, 4, 4);
  spinner_ = gtk_spinner_new();
  gtk_widget_set_size_request(spinner_, 20, 20);
  gtk_container_add(GTK_CONTAINER(spinner_alignment), spinner_);

  spinner_item_ = gtk_tool_item_new();
  gtk_container_add(GTK_CONTAINER(spinner_item_), spinner_alignment);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), spinner_item_, -1 /* append */);

  if (is_toolbar_open_)
    gtk_box_pack_start(GTK_BOX(vbox_), toolbar, FALSE, FALSE, 0);

  gtk_container_add(GTK_CONTAINER(window_), vbox_);
  gtk_widget_show_all(GTK_WIDGET(window_));

  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree))
    gtk_widget_set_uposition(GTK_WIDGET(window_), 10000, 10000);

  SizeTo(width, height);
}

void Shell::PlatformSetContents() {
  WebContentsView* content_view = web_contents_->GetView();
  gtk_container_add(GTK_CONTAINER(vbox_), content_view->GetNativeView());

  // As an additional requirement on Linux, we must set the colors for the
  // render widgets in webkit.
  content::RendererPreferences* prefs =
      web_contents_->GetMutableRendererPrefs();
  prefs->focus_ring_color = SkColorSetARGB(255, 229, 151, 0);
  prefs->thumb_active_color = SkColorSetRGB(244, 244, 244);
  prefs->thumb_inactive_color = SkColorSetRGB(234, 234, 234);
  prefs->track_color = SkColorSetRGB(211, 211, 211);

  prefs->active_selection_bg_color = SkColorSetRGB(30, 144, 255);
  prefs->active_selection_fg_color = SK_ColorWHITE;
  prefs->inactive_selection_bg_color = SkColorSetRGB(200, 200, 200);
  prefs->inactive_selection_fg_color = SkColorSetRGB(50, 50, 50);
}

void Shell::SizeTo(int width, int height) {
  content_width_ = width;
  content_height_ = height;
  if (web_contents_.get()) {
    gtk_widget_set_size_request(web_contents_->GetNativeView(), width, height);
  }
}

void Shell::PlatformResizeSubViews() {
  SizeTo(content_width_, content_height_);
}

void Shell::Close() {
  gtk_widget_destroy(GTK_WIDGET(window_));
}

void Shell::Move(const gfx::Rect& pos) {
  gint x = static_cast<gint>(bounds.x());
  gint y = static_cast<gint>(bounds.y());
  gint width = static_cast<gint>(bounds.width());
  gint height = static_cast<gint>(bounds.height());

  gtk_window_move(window_, x, y);
  SizeTo(width, height);
}

void Shell::OnBackButtonClicked(GtkWidget* widget) {
  GoBackOrForward(-1);
}

void Shell::OnForwardButtonClicked(GtkWidget* widget) {
  GoBackOrForward(1);
}

void Shell::OnReloadButtonClicked(GtkWidget* widget) {
  Reload();
}

void Shell::OnStopButtonClicked(GtkWidget* widget) {
  Stop();
}

void Shell::OnURLEntryActivate(GtkWidget* entry) {
  const gchar* str = gtk_entry_get_text(GTK_ENTRY(entry));
  GURL url(str);
  if (!url.has_scheme())
    url = GURL(std::string("http://") + std::string(str));
  LoadURL(GURL(url));
}

// Callback for when the main window is destroyed.
gboolean Shell::OnWindowDestroyed(GtkWidget* window) {
  delete this;
  return FALSE;  // Don't stop this message.
}

gboolean Shell::OnCloseWindowKeyPressed(GtkAccelGroup* accel_group,
                                        GObject* acceleratable,
                                        guint keyval,
                                        GdkModifierType modifier) {
  gtk_widget_destroy(GTK_WIDGET(window_));
  return TRUE;
}

gboolean Shell::OnNewWindowKeyPressed(GtkAccelGroup* accel_group,
                                      GObject* acceleratable,
                                      guint keyval,
                                      GdkModifierType modifier) {
  ShellBrowserContext* browser_context =
      static_cast<ShellContentBrowserClient*>(
        GetContentClient()->browser())->browser_context();
  Shell::CreateNewWindow(browser_context,
                         GURL(),
                         NULL,
                         MSG_ROUTING_NONE,
                         NULL);
  return TRUE;
}

gboolean Shell::OnHighlightURLView(GtkAccelGroup* accel_group,
                                   GObject* acceleratable,
                                   guint keyval,
                                   GdkModifierType modifier) {
  gtk_widget_grab_focus(GTK_WIDGET(url_edit_view_));
  return TRUE;
}

void Shell::PlatformSetTitle(const string16& title) {
  std::string title_utf8 = UTF16ToUTF8(title);
  gtk_window_set_title(GTK_WINDOW(window_), title_utf8.c_str());
}

}  // namespace content
<commit_msg>[GTK] Fix resizing issues on GTK<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "shell.h"

#include <gdk/gdkkeysyms.h>
#include <gtk/gtk.h>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/renderer_preferences.h"
#include "shell_browser_context.h"
#include "shell_content_browser_client.h"
#include "shell_switches.h"
#include "third_party/skia/include/core/SkColor.h"

namespace content {

namespace {

// Callback for Debug > Show web inspector... menu item.
gboolean ShowWebInspectorActivated(GtkWidget* widget, Shell* shell) {
  shell->ShowDevTools();
  return FALSE;  // Don't stop this message.
}

GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text,
                        GCallback callback, Shell* shell) {
  GtkWidget* entry = gtk_menu_item_new_with_mnemonic(text);
  g_signal_connect(entry, "activate", callback, shell);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), entry);
  return entry;
}

GtkWidget* CreateMenu(GtkWidget* menu_bar, const char* text) {
  GtkWidget* menu_widget = gtk_menu_new();
  GtkWidget* menu_header = gtk_menu_item_new_with_label(text);
  gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_header), menu_widget);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), menu_header);
  return menu_widget;
}

GtkWidget* CreateMenuBar(Shell* shell) {
  GtkWidget* menu_bar = gtk_menu_bar_new();
  GtkWidget* debug_menu = CreateMenu(menu_bar, "Debug");
  AddMenuEntry(debug_menu, "_Show Developer Tools...",
               G_CALLBACK(ShowWebInspectorActivated), shell);
  return menu_bar;
}

}  // namespace

void Shell::PlatformInitialize() {
}

void Shell::PlatformCleanUp() {
  // Nothing to clean up; GTK will clean up the widgets shortly after.
}

void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
  GtkToolItem* item = NULL;
  switch (control) {
    case BACK_BUTTON:
      item = back_button_;
      break;
    case FORWARD_BUTTON:
      item = forward_button_;
      break;
    case STOP_BUTTON:
      item = stop_button_;
      break;
    default:
      NOTREACHED() << "Unknown UI control";
      return;
  }
  gtk_widget_set_sensitive(GTK_WIDGET(item), is_enabled);
}

void Shell::PlatformSetAddressBarURL(const GURL& url) {
  gtk_entry_set_text(GTK_ENTRY(url_edit_view_), url.spec().c_str());
}

void Shell::PlatformSetIsLoading(bool loading) {
  if (loading)
    gtk_spinner_start(GTK_SPINNER(spinner_));
  else
    gtk_spinner_stop(GTK_SPINNER(spinner_));
}

void Shell::PlatformCreateWindow(int width, int height) {
  window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
  gtk_window_set_title(window_, "node-webkit");
  gtk_window_set_default_size(window_, width, height);
  g_signal_connect(G_OBJECT(window_), "destroy",
                   G_CALLBACK(OnWindowDestroyedThunk), this);

  if (window_manifest_) {
    // window.x and window.y
    int x, y;
    if (window_manifest_->GetInteger(switches::kmX, &x) &&
        window_manifest_->GetInteger(switches::kmY, &y)) {
      gtk_window_move(window_, x, y);
    } else {
      // window.postion
      std::string desription;
      if (window_manifest_->GetString(switches::kmPosition, &desription)) {
        if (desription == "center")
          gtk_window_set_position(window_, GTK_WIN_POS_CENTER);
        else if (desription == "mouse")
          gtk_window_set_position(window_, GTK_WIN_POS_MOUSE);
      }
    }

    GdkGeometry geometry = { 0 };
    int hints = GDK_HINT_POS;
    int tmp = -1;
    if (window_manifest_->GetInteger(switches::kmMinWidth, &tmp)) {
      hints |= GDK_HINT_MIN_SIZE;
      geometry.min_width = tmp;
    }
    if (window_manifest_->GetInteger(switches::kmMinHeight, &tmp)) {
      hints |= GDK_HINT_MIN_SIZE;
      geometry.min_height = tmp;
    }
    if (window_manifest_->GetInteger(switches::kmMaxWidth, &tmp)) {
      hints |= GDK_HINT_MAX_SIZE;
      geometry.max_width = tmp;
    }
    if (window_manifest_->GetInteger(switches::kmMaxHeight, &tmp)) {
      hints |= GDK_HINT_MAX_SIZE;
      geometry.max_height = tmp;
    }
    if (hints != GDK_HINT_POS) {
      gtk_window_set_geometry_hints(
          window_, GTK_WIDGET(window_), &geometry, (GdkWindowHints)hints);
    }
  }

  vbox_ = gtk_vbox_new(FALSE, 0);

  // Create the menu bar.
  GtkWidget* menu_bar = CreateMenuBar(this);
  if (is_show_devtools_) {
    gtk_box_pack_start(GTK_BOX(vbox_), menu_bar, FALSE, FALSE, 0);
  }

  // Create the object that mediates accelerators.
  GtkAccelGroup* accel_group = gtk_accel_group_new();
  gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group);

  // Set global window handling accelerators:
  gtk_accel_group_connect(
      accel_group, GDK_w, GDK_CONTROL_MASK,
      GTK_ACCEL_VISIBLE,
      g_cclosure_new(G_CALLBACK(OnCloseWindowKeyPressedThunk),
                     this, NULL));

  gtk_accel_group_connect(
      accel_group, GDK_n, GDK_CONTROL_MASK,
      GTK_ACCEL_VISIBLE,
      g_cclosure_new(G_CALLBACK(OnNewWindowKeyPressedThunk),
                    this, NULL));

  GtkWidget* toolbar = gtk_toolbar_new();
  // Turn off the labels on the toolbar buttons.
  gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);

  back_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_GO_BACK);
  g_signal_connect(back_button_, "clicked",
                   G_CALLBACK(&OnBackButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), back_button_, -1 /* append */);
  gtk_widget_add_accelerator(GTK_WIDGET(back_button_), "clicked", accel_group,
                             GDK_Left, GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

  forward_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_GO_FORWARD);
  g_signal_connect(forward_button_, "clicked",
                   G_CALLBACK(&OnForwardButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), forward_button_, -1 /* append */);
  gtk_widget_add_accelerator(GTK_WIDGET(forward_button_), "clicked",
                             accel_group,
                             GDK_Right, GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

  reload_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_REFRESH);
  g_signal_connect(reload_button_, "clicked",
                   G_CALLBACK(&OnReloadButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), reload_button_, -1 /* append */);
  gtk_widget_add_accelerator(GTK_WIDGET(reload_button_), "clicked",
                             accel_group,
                             GDK_r, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

  stop_button_ = gtk_tool_button_new_from_stock(GTK_STOCK_STOP);
  g_signal_connect(stop_button_, "clicked",
                   G_CALLBACK(&OnStopButtonClickedThunk), this);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), stop_button_, -1 /* append */);

  url_edit_view_ = gtk_entry_new();
  g_signal_connect(G_OBJECT(url_edit_view_), "activate",
                   G_CALLBACK(&OnURLEntryActivateThunk), this);

  gtk_accel_group_connect(
      accel_group, GDK_l, GDK_CONTROL_MASK,
      GTK_ACCEL_VISIBLE,
      g_cclosure_new(G_CALLBACK(OnHighlightURLViewThunk),
                     this, NULL));

  GtkToolItem* tool_item = gtk_tool_item_new();
  gtk_container_add(GTK_CONTAINER(tool_item), url_edit_view_);
  gtk_tool_item_set_expand(tool_item, TRUE);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool_item, -1 /* append */);

  // Center a 20x20 spinner in a 26x24 area.
  GtkWidget* spinner_alignment = gtk_alignment_new(0.5, 0.5, 0, 0);
  gtk_alignment_set_padding(GTK_ALIGNMENT(spinner_alignment), 2, 2, 4, 4);
  spinner_ = gtk_spinner_new();
  gtk_widget_set_size_request(spinner_, 20, 20);
  gtk_container_add(GTK_CONTAINER(spinner_alignment), spinner_);

  spinner_item_ = gtk_tool_item_new();
  gtk_container_add(GTK_CONTAINER(spinner_item_), spinner_alignment);
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), spinner_item_, -1 /* append */);

  if (is_toolbar_open_)
    gtk_box_pack_start(GTK_BOX(vbox_), toolbar, FALSE, FALSE, 0);

  gtk_container_add(GTK_CONTAINER(window_), vbox_);
  gtk_widget_show_all(GTK_WIDGET(window_));

  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree))
    gtk_widget_set_uposition(GTK_WIDGET(window_), 10000, 10000);

  SizeTo(width, height);
}

void Shell::PlatformSetContents() {
  WebContentsView* content_view = web_contents_->GetView();
  gtk_container_add(GTK_CONTAINER(vbox_), content_view->GetNativeView());

  // As an additional requirement on Linux, we must set the colors for the
  // render widgets in webkit.
  content::RendererPreferences* prefs =
      web_contents_->GetMutableRendererPrefs();
  prefs->focus_ring_color = SkColorSetARGB(255, 229, 151, 0);
  prefs->thumb_active_color = SkColorSetRGB(244, 244, 244);
  prefs->thumb_inactive_color = SkColorSetRGB(234, 234, 234);
  prefs->track_color = SkColorSetRGB(211, 211, 211);

  prefs->active_selection_bg_color = SkColorSetRGB(30, 144, 255);
  prefs->active_selection_fg_color = SK_ColorWHITE;
  prefs->inactive_selection_bg_color = SkColorSetRGB(200, 200, 200);
  prefs->inactive_selection_fg_color = SkColorSetRGB(50, 50, 50);
}

void Shell::SizeTo(int width, int height) {
  content_width_ = width;
  content_height_ = height;
  if (web_contents_.get()) {
    gtk_widget_set_size_request(web_contents_->GetNativeView(), width, height);
  }
}

void Shell::PlatformResizeSubViews() {
  SizeTo(content_width_, content_height_);
}

void Shell::Close() {
  gtk_widget_destroy(GTK_WIDGET(window_));
}

void Shell::Move(const gfx::Rect& bounds) {
  gint x = static_cast<gint>(bounds.x());
  gint y = static_cast<gint>(bounds.y());
  gint width = static_cast<gint>(bounds.width());
  gint height = static_cast<gint>(bounds.height());

  gtk_window_move(window_, x, y);
  gtk_window_resize(window_, width, height);
}

void Shell::OnBackButtonClicked(GtkWidget* widget) {
  GoBackOrForward(-1);
}

void Shell::OnForwardButtonClicked(GtkWidget* widget) {
  GoBackOrForward(1);
}

void Shell::OnReloadButtonClicked(GtkWidget* widget) {
  Reload();
}

void Shell::OnStopButtonClicked(GtkWidget* widget) {
  Stop();
}

void Shell::OnURLEntryActivate(GtkWidget* entry) {
  const gchar* str = gtk_entry_get_text(GTK_ENTRY(entry));
  GURL url(str);
  if (!url.has_scheme())
    url = GURL(std::string("http://") + std::string(str));
  LoadURL(GURL(url));
}

// Callback for when the main window is destroyed.
gboolean Shell::OnWindowDestroyed(GtkWidget* window) {
  delete this;
  return FALSE;  // Don't stop this message.
}

gboolean Shell::OnCloseWindowKeyPressed(GtkAccelGroup* accel_group,
                                        GObject* acceleratable,
                                        guint keyval,
                                        GdkModifierType modifier) {
  gtk_widget_destroy(GTK_WIDGET(window_));
  return TRUE;
}

gboolean Shell::OnNewWindowKeyPressed(GtkAccelGroup* accel_group,
                                      GObject* acceleratable,
                                      guint keyval,
                                      GdkModifierType modifier) {
  ShellBrowserContext* browser_context =
      static_cast<ShellContentBrowserClient*>(
        GetContentClient()->browser())->browser_context();
  Shell::CreateNewWindow(browser_context,
                         GURL(),
                         NULL,
                         MSG_ROUTING_NONE,
                         NULL);
  return TRUE;
}

gboolean Shell::OnHighlightURLView(GtkAccelGroup* accel_group,
                                   GObject* acceleratable,
                                   guint keyval,
                                   GdkModifierType modifier) {
  gtk_widget_grab_focus(GTK_WIDGET(url_edit_view_));
  return TRUE;
}

void Shell::PlatformSetTitle(const string16& title) {
  std::string title_utf8 = UTF16ToUTF8(title);
  gtk_window_set_title(GTK_WINDOW(window_), title_utf8.c_str());
}

}  // namespace content
<|endoftext|>


<commit_before><commit_msg>Remove '#define INLINE', inline in method definition is enough<commit_after><|endoftext|>


<commit_before><commit_msg>Called ck_abort after detecting a assertion failure in sanity<commit_after><|endoftext|>


<commit_before><commit_msg>consolidateStaticMemory: private memory stuct loads are safeExceptions<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Jesus Perez (a) Chuso <github at chuso dot net>
 * http://chuso.net
 *
 * Resitributable under the terms of the Artistic License
 * http://opensource.org/licenses/artistic-license.php
 */

#include "sugarcrmresource.h"
#include "sugarsoap.h"
#include "sugarconfig.h"
#include "moduleattribute.h"

#include "settings.h"
#include "settingsadaptor.h"

#include <QtDBus/QDBusConnection>

#include <KWindowSystem>
#include <KABC/Addressee>
#include <KCalCore/Todo>
#include <Akonadi/ItemFetchScope>
#include <Akonadi/ChangeRecorder>
#include <KLocalizedString>
#include <Akonadi/AttributeFactory>

using namespace Akonadi;

/*!
 * \class SugarSoap
 * \brief The SugarCrmResource class handles is the main class that is queried by Akonadi
*/

/*!
 * Constructs a new SugarCrmSource object.
 */
SugarCrmResource::SugarCrmResource( const QString &id )
  : ResourceBase( id )
{
  // Populate Map of valid modules and required fields for each module
  module *modinfo = new module;
  modinfo->fields << "id" << "first_name" << "last_name" << "email1";
  modinfo->mimes << "text/directory";
  modinfo->payload_function = &SugarCrmResource::contactPayload;
  modinfo->soap_function = &SugarCrmResource::contactSoap;
  SugarCrmResource::Modules["Contacts"] = SugarCrmResource::Modules["Leads"] = *modinfo;

  modinfo = new module;
  modinfo->fields << "id" << "name" << "description" << "date_due_flag" << "date_due" << "date_start_flag" << "date_start";
  modinfo->mimes << KCalCore::Todo::todoMimeType();
  modinfo->payload_function = &SugarCrmResource::taskPayload;
  modinfo->soap_function = &SugarCrmResource::taskSoap;
  SugarCrmResource::Modules["Tasks"] = *modinfo;

  modinfo = new module;
  modinfo->fields << "id" << "name" << "description" << "case_number" << "date_due" << "date_start_flag" << "date_start";
  modinfo->mimes << KCalCore::Todo::todoMimeType();
  // TODO: where status is active
  SugarCrmResource::Modules["Cases"] = *modinfo;

  new SettingsAdaptor( Settings::self() );
  QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ),
                            Settings::self(), QDBusConnection::ExportAdaptors );

  changeRecorder()->itemFetchScope().fetchFullPayload();
}

SugarCrmResource::~SugarCrmResource()
{
}

/*!
 * Called by Akonadi to know which collections we are going to provide
 */
void SugarCrmResource::retrieveCollections()
{
  // Build URL used for remoteIds
  KUrl url = KUrl(Settings::self()->url());
  if (!url.hasUser()) url.setUser(Settings::self()->username());

  AttributeFactory::registerAttribute<ModuleAttribute>();

  Collection root = Collection();
  root.setContentMimeTypes(QStringList() << Collection::mimeType());
  root.setRemoteId(url.url());
  root.setName(i18n("SugarCRM resource at %1").arg(url.url()));
  root.setParent(Collection::root());
  // TODO root.setRights()

  QMap<QString, Akonadi::Collection> m_collections;
  m_collections["RootCollection"] = root;

  // Add a collection for each module queried
  Collection c;
  c.setParent(root);
  c.setRemoteId("Contacts@" + url.url());
  c.setName(i18n("Contacts from SugarCRM resource at %1").arg(url.url()));
  c.setContentMimeTypes(QStringList("text/directory"));
  ModuleAttribute *attr = new ModuleAttribute(ModuleAttribute::Contacts);
  c.addAttribute(attr);
  m_collections[c.remoteId()] = c;

  Collection l;
  l.setParent(root);
  l.setRemoteId("Leads@" + url.url());
  attr = new ModuleAttribute(ModuleAttribute::Leads);
  l.addAttribute(attr);
  l.setName(i18n("Leads from SugarCRM resource at %1").arg(url.url()));
  l.setContentMimeTypes(QStringList("text/directory"));
  m_collections[l.remoteId()] = l;

  Collection t;
  t.setParent(root);
  t.setRemoteId("Tasks@" + url.url());
  attr = new ModuleAttribute(ModuleAttribute::Tasks);
  t.addAttribute(attr);
  t.setName(i18n("Tasks from SugarCRM resource at %1").arg(url.url()));
  t.setContentMimeTypes(QStringList(KCalCore::Todo::todoMimeType()));
  m_collections[t.remoteId()] = t;

  collectionsRetrieved(m_collections.values());
}

/*!
 * Called by Akonadi to retrieve items from a collection
 * \param[in] collection Collection we want to retrieve items to
 */
void SugarCrmResource::retrieveItems( const Akonadi::Collection &collection )
{
  // FIXME Use collection attribute instead of item attribute
  AttributeFactory::registerAttribute<ModuleAttribute>();
  ModuleAttribute *attr = collection.attribute<ModuleAttribute>();
  QString mod = QString(attr->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;

  // Request items to SugarSoap
  soap = new SugarSoap(Settings::self()->url().url());
  QStringList *soapItems = soap->getEntries(mod);;

  // At this step, we only need their remoteIds.
  Item::List items;
  foreach (QString itemId, (*soapItems))
  {
    Item item(SugarCrmResource::Modules[mod].mimes[0]);
    item.setRemoteId(itemId);
    soap = new SugarSoap(Settings::self()->url().url());
    // TODO check returned value
    // Call function pointer to the function that returns the appropi
    QHash<QString, QString> *soapItem = soap->getEntry(mod, item.remoteId());
    item = (this->*SugarCrmResource::Modules[mod].payload_function)(*soapItem, item);
    item.setParentCollection(collection);
    ModuleAttribute::ModuleTypes m;
    if (mod == "Contacts")
      m = ModuleAttribute::Contacts;
    else if (mod == "Leads")
      m = ModuleAttribute::Leads;
    else if (mod == "Tasks")
      m = ModuleAttribute::Tasks;
    else
      return;
    ModuleAttribute *attr = new ModuleAttribute(m);
    item.addAttribute(attr);

    items << item;
  }

  itemsRetrieved( items );
}

/*!
 * Called by Akonadi when it wants to retrieve the whole data of a item
 * \param[in] item  the item
 * \param[in] parts item parts that need to be retrieved (not used)
 */
bool SugarCrmResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
  /* FIXME
  Q_UNUSED( parts );
  AttributeFactory::registerAttribute<ModuleAttribute>();
  // FIXME Use collection attribute instead of item attribute
  ModuleAttribute *attr = item.parentCollection().attribute<ModuleAttribute>();
  QString mod = QString(attr->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return false;

  // Request data to SugarSoap
  soap = new SugarSoap(Settings::self()->url().url());
  // TODO check returned value
  // Call function pointer to the function that returns the appropi
  QHash<QString, QString> *soapItem = soap->getEntry(mod, item.remoteId());

  itemRetrieved((this->*SugarCrmResource::Modules[mod].payload_function)(*soapItem, item));*/
  itemRetrieved(item);
  return true;
}

/*!
 * Receives an an Akonadi::Item and a SOAP assocative array that
 * contains an addreess book contact to be set as item's payload
 * \param[in] soapItem The associative array containing an address book contact
 * \param[in] item the item whom payload will be populated
 * \return A new Akonadi::Item with its payload
 */
Item SugarCrmResource::contactPayload(const QHash<QString, QString> &soapItem, const Akonadi::Item &item)
{
  // TODO: more fields
  KABC::Addressee addressee;
  addressee.setGivenName(soapItem["first_name"]);
  addressee.setFamilyName(soapItem["last_name"]);
  QStringList emails;
  emails << soapItem["email1"];
  addressee.setEmails(emails);
  Item newItem( item );
  newItem.setPayload<KABC::Addressee>( addressee );
  return newItem;
}

/*!
 * Receives an Akonadi::Item containing KABC::Addressee payload and
 * converts this payload to a SOAP assocative array that to be stored
 * in SugarCRM
 * \param[in] item the item whose payload that will be converted
 * \return A new QHash dictionary with item attributes
 */
QHash<QString, QString> SugarCrmResource::contactSoap(const Akonadi::Item &item)
{
  const KABC::Addressee &payload = item.payload<KABC::Addressee>();

  QHash<QString, QString> soapItem;

  soapItem["first_name"] = payload.givenName();
  soapItem["last_name"] = payload.familyName();
  if (payload.emails().length() >= 1)
    soapItem["email1"] = payload.emails().at(0);
  return soapItem;
}

/*!
 * Receives an Akonadi::Item and a SOAP assocative array that
 * contains a calendar task to be set as item's payload
 * \param[in] soapItem The associative array containing a calendar task
 * \param[in] item the item whom payload will be populated
 * \return A new Akonadi::Item with its payload
 */
Item SugarCrmResource::taskPayload(const QHash<QString, QString> &soapItem, const Akonadi::Item &item)
{
  KCalCore::Todo::Ptr event(new KCalCore::Todo);
  event->setUid(soapItem["id"]);
  /* ModuleAttribute *attr = new ModuleAttribute(ModuleAttribute::Tasks);
  item.addAttribute(attr); // FIXME */
  event->setSummary(soapItem["name"]);
  event->setDescription(soapItem["description"]);
  // FIXME: creation date
  if (!soapItem["date_start"].isEmpty())
    event->setDtStart(KDateTime::fromString(soapItem["date_start"], KDateTime::ISODate));
  if (!soapItem["date_due"].isEmpty())
    // FIXME: It seems that it only gets date but not time
    event->setDtDue(KDateTime::fromString(soapItem["date_due"], KDateTime::ISODate));
  Item newItem(item);
  newItem.setPayload<KCalCore::Todo::Ptr>(event);
  return newItem;
}

/*!
 * Receives an Akonadi::Item containing KABC::Addressee payload and
 * converts this payload to a SOAP assocative array that to be stored
 * in SugarCRM
 * \param[in] item the item whose payload that will be converted
 * \return A new QHash dictionary with item attributes
 */
QHash<QString, QString> SugarCrmResource::taskSoap(const Akonadi::Item &item)
{
  const KCalCore::Todo::Ptr &payload = item.payload<KCalCore::Todo::Ptr>();

  QHash<QString, QString> soapItem;

  soapItem["name"] = payload->summary();
  soapItem["description"] = payload->description();
  if (payload->hasStartDate())
  {
    soapItem["date_start"] = payload->dtStart().toString(KDateTime::ISODate);
    soapItem["date_start_flag"] = "1";
  }
  if (payload->hasDueDate())
  {
    soapItem["date_due"] = payload->dtDue().toString(KDateTime::ISODate);
    soapItem["date_due_flag"] = "1";
  }
  return soapItem;
}

void SugarCrmResource::aboutToQuit()
{
  // TODO: any cleanup you need to do while there is still an active
  // event loop. The resource will terminate after this method returns
}

/*!
 * Called by Akonadi to configure plugin.
 * Emits a configurationDialogAccepted() signal if it was successful,
 * configurationDialogRejected() otherwise.
 * \param[in] windowId Parent window
 */
void SugarCrmResource::configure(const WId windowId)
{
  Q_UNUSED( windowId );

  KWindowSystem::setMainWindow(&configDlg, windowId);
  configDlg.setUrl(Settings::self()->url().prettyUrl());
  configDlg.setUsername(Settings::self()->username());
  configDlg.setPassword(Settings::self()->password());

  // Check if user clicked OK or Cancel
  if (configDlg.exec() == QDialog::Rejected)
  {
    emit configurationDialogRejected();
    return;
  }

  // Test if supplied data is correct
  soap = new SugarSoap(configDlg.url());
  // TODO timeout
  Settings::self()->setSessionId(soap->login(configDlg.username(), configDlg.password()));
  if (Settings::self()->sessionId().isEmpty())
  {
    emit configurationDialogRejected();
    return;
  }

  // Sotre configuration values
  Settings::self()->setUrl(configDlg.url());
  Settings::self()->setUsername(configDlg.username());
  Settings::self()->setPassword(configDlg.password());

  // And write configuration file
  Settings::self()->writeConfig();

  emit configurationDialogAccepted();

  // Start synchronization
  synchronize();
}

// FIXME: Items appear as added in Akonadi even if adding to SugarCRM failed
void SugarCrmResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
  QString mod = QString(collection.attribute<ModuleAttribute>()->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;

  QString id = "";

  soap = new SugarSoap(Settings::self()->url().url());
  if (soap->editEntry(
    mod,
    (this->*SugarCrmResource::Modules[mod].soap_function)(item),
    id
  ))
  {
    Item newItem(item);
    newItem.setRemoteId(id);
    newItem.clearPayload(); // FIXME
    ModuleAttribute::ModuleTypes m;
    if (mod == "Contacts")
      m = ModuleAttribute::Contacts;
    else if (mod == "Leads")
      m = ModuleAttribute::Leads;
    else if (mod == "Tasks")
      m = ModuleAttribute::Tasks;
    else
      return;
    ModuleAttribute *attr = new ModuleAttribute(m);
    newItem.addAttribute(attr);
    changeCommitted(newItem);
  }
}

// FIXME: Items appear as changed in Akonadi even if update to SugarCRM failed
void SugarCrmResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
  Q_UNUSED(parts);

  // FIXME for now, we are storing in remoteID which module the item belongs to
  QString mod = QString(item.attribute<ModuleAttribute>()->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;

  soap = new SugarSoap(Settings::self()->url().url());

  if (soap->editEntry(
    mod,
    (this->*SugarCrmResource::Modules[mod].soap_function)(item),
    item.remoteId()
  ))
    changeCommitted(Item(item));
}

void SugarCrmResource::itemRemoved( const Akonadi::Item &item )
{
  // FIXME for now, we are storing in remoteID which module the item belongs to
  QString mod = QString(item.attribute<ModuleAttribute>()->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;
  soap = new SugarSoap(Settings::self()->url().url());

  QHash<QString, QString> soapItem;
  soapItem["deleted"] = "1";

  if (soap->editEntry(
    mod,
    soapItem,
    item.remoteId()
  ))
    changeCommitted(Item(item));
}

AKONADI_RESOURCE_MAIN( SugarCrmResource );
QHash<QString,module> SugarCrmResource::Modules;

#include "sugarcrmresource.moc"
<commit_msg>Clone Akonadi custom attribute instead of using nested if statements.<commit_after>/*
 * Copyright (C) 2013 Jesus Perez (a) Chuso <github at chuso dot net>
 * http://chuso.net
 *
 * Resitributable under the terms of the Artistic License
 * http://opensource.org/licenses/artistic-license.php
 */

#include "sugarcrmresource.h"
#include "sugarsoap.h"
#include "sugarconfig.h"
#include "moduleattribute.h"

#include "settings.h"
#include "settingsadaptor.h"

#include <QtDBus/QDBusConnection>

#include <KWindowSystem>
#include <KABC/Addressee>
#include <KCalCore/Todo>
#include <Akonadi/ItemFetchScope>
#include <Akonadi/ChangeRecorder>
#include <KLocalizedString>
#include <Akonadi/AttributeFactory>

using namespace Akonadi;

/*!
 * \class SugarSoap
 * \brief The SugarCrmResource class handles is the main class that is queried by Akonadi
*/

/*!
 * Constructs a new SugarCrmSource object.
 */
SugarCrmResource::SugarCrmResource( const QString &id )
  : ResourceBase( id )
{
  // Populate Map of valid modules and required fields for each module
  module *modinfo = new module;
  modinfo->fields << "id" << "first_name" << "last_name" << "email1";
  modinfo->mimes << "text/directory";
  modinfo->payload_function = &SugarCrmResource::contactPayload;
  modinfo->soap_function = &SugarCrmResource::contactSoap;
  SugarCrmResource::Modules["Contacts"] = SugarCrmResource::Modules["Leads"] = *modinfo;

  modinfo = new module;
  modinfo->fields << "id" << "name" << "description" << "date_due_flag" << "date_due" << "date_start_flag" << "date_start";
  modinfo->mimes << KCalCore::Todo::todoMimeType();
  modinfo->payload_function = &SugarCrmResource::taskPayload;
  modinfo->soap_function = &SugarCrmResource::taskSoap;
  SugarCrmResource::Modules["Tasks"] = *modinfo;

  modinfo = new module;
  modinfo->fields << "id" << "name" << "description" << "case_number" << "date_due" << "date_start_flag" << "date_start";
  modinfo->mimes << KCalCore::Todo::todoMimeType();
  // TODO: payload
  // TODO: where status is active
  SugarCrmResource::Modules["Cases"] = *modinfo;

  new SettingsAdaptor( Settings::self() );
  QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ),
                            Settings::self(), QDBusConnection::ExportAdaptors );

  changeRecorder()->itemFetchScope().fetchFullPayload();
}

SugarCrmResource::~SugarCrmResource()
{
}

/*!
 * Called by Akonadi to know which collections we are going to provide
 */
void SugarCrmResource::retrieveCollections()
{
  // Build URL used for remoteIds
  KUrl url = KUrl(Settings::self()->url());
  if (!url.hasUser()) url.setUser(Settings::self()->username());

  AttributeFactory::registerAttribute<ModuleAttribute>();

  Collection root = Collection();
  root.setContentMimeTypes(QStringList() << Collection::mimeType());
  root.setRemoteId(url.url());
  root.setName(i18n("SugarCRM resource at %1").arg(url.url()));
  root.setParent(Collection::root());
  // TODO root.setRights()

  QMap<QString, Akonadi::Collection> m_collections;
  m_collections["RootCollection"] = root;

  // Add a collection for each module queried
  Collection c;
  c.setParent(root);
  c.setRemoteId("Contacts@" + url.url());
  c.setName(i18n("Contacts from SugarCRM resource at %1").arg(url.url()));
  c.setContentMimeTypes(QStringList("text/directory"));
  ModuleAttribute *attr = new ModuleAttribute(ModuleAttribute::Contacts);
  c.addAttribute(attr);
  m_collections[c.remoteId()] = c;

  // TODO cases

  Collection l;
  l.setParent(root);
  l.setRemoteId("Leads@" + url.url());
  attr = new ModuleAttribute(ModuleAttribute::Leads);
  l.addAttribute(attr);
  l.setName(i18n("Leads from SugarCRM resource at %1").arg(url.url()));
  l.setContentMimeTypes(QStringList("text/directory"));
  m_collections[l.remoteId()] = l;

  Collection t;
  t.setParent(root);
  t.setRemoteId("Tasks@" + url.url());
  attr = new ModuleAttribute(ModuleAttribute::Tasks);
  t.addAttribute(attr);
  t.setName(i18n("Tasks from SugarCRM resource at %1").arg(url.url()));
  t.setContentMimeTypes(QStringList(KCalCore::Todo::todoMimeType()));
  m_collections[t.remoteId()] = t;

  collectionsRetrieved(m_collections.values());
}

/*!
 * Called by Akonadi to retrieve items from a collection
 * \param[in] collection Collection we want to retrieve items to
 */
void SugarCrmResource::retrieveItems( const Akonadi::Collection &collection )
{
  // FIXME Use collection attribute instead of item attribute
  AttributeFactory::registerAttribute<ModuleAttribute>();
  ModuleAttribute *attr = collection.attribute<ModuleAttribute>();
  QString mod = QString(attr->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;

  // Request items to SugarSoap
  soap = new SugarSoap(Settings::self()->url().url());
  QStringList *soapItems = soap->getEntries(mod);;

  // At this step, we only need their remoteIds.
  Item::List items;
  foreach (QString itemId, (*soapItems))
  {
    Item item(SugarCrmResource::Modules[mod].mimes[0]);
    item.setRemoteId(itemId);

    // TODO: move to retrieveItem()
    soap = new SugarSoap(Settings::self()->url().url());
    // TODO check returned value
    // Call function pointer to the function that returns the appropi
    QHash<QString, QString> *soapItem = soap->getEntry(mod, item.remoteId());
    item = (this->*SugarCrmResource::Modules[mod].payload_function)(*soapItem, item);
    item.setParentCollection(collection);
    // end of code to move to retrieveItem()

    item.addAttribute(attr->clone());

    items << item;
  }

  itemsRetrieved( items );
}

/*!
 * Called by Akonadi when it wants to retrieve the whole data of a item
 * \param[in] item  the item
 * \param[in] parts item parts that need to be retrieved (not used)
 */
bool SugarCrmResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
  Q_UNUSED( parts );
  itemRetrieved(item);
  return true;
}

/*!
 * Receives an an Akonadi::Item and a SOAP assocative array that
 * contains an addreess book contact to be set as item's payload
 * \param[in] soapItem The associative array containing an address book contact
 * \param[in] item the item whom payload will be populated
 * \return A new Akonadi::Item with its payload
 */
Item SugarCrmResource::contactPayload(const QHash<QString, QString> &soapItem, const Akonadi::Item &item)
{
  // TODO: more fields
  KABC::Addressee addressee;
  addressee.setGivenName(soapItem["first_name"]);
  addressee.setFamilyName(soapItem["last_name"]);
  QStringList emails;
  emails << soapItem["email1"];
  addressee.setEmails(emails);
  Item newItem( item );
  newItem.setPayload<KABC::Addressee>( addressee );
  return newItem;
}

/*!
 * Receives an Akonadi::Item containing KABC::Addressee payload and
 * converts this payload to a SOAP assocative array that to be stored
 * in SugarCRM
 * \param[in] item the item whose payload that will be converted
 * \return A new QHash dictionary with item attributes
 */
QHash<QString, QString> SugarCrmResource::contactSoap(const Akonadi::Item &item)
{
  const KABC::Addressee &payload = item.payload<KABC::Addressee>();

  QHash<QString, QString> soapItem;

  soapItem["first_name"] = payload.givenName();
  soapItem["last_name"] = payload.familyName();
  if (payload.emails().length() >= 1)
    soapItem["email1"] = payload.emails().at(0);
  return soapItem;
}

/*!
 * Receives an Akonadi::Item and a SOAP assocative array that
 * contains a calendar task to be set as item's payload
 * \param[in] soapItem The associative array containing a calendar task
 * \param[in] item the item whom payload will be populated
 * \return A new Akonadi::Item with its payload
 */
Item SugarCrmResource::taskPayload(const QHash<QString, QString> &soapItem, const Akonadi::Item &item)
{
  KCalCore::Todo::Ptr event(new KCalCore::Todo);
  event->setUid(soapItem["id"]);
  /* ModuleAttribute *attr = new ModuleAttribute(ModuleAttribute::Tasks);
  item.addAttribute(attr); // FIXME */
  event->setSummary(soapItem["name"]);
  event->setDescription(soapItem["description"]);
  // FIXME: creation date
  if (!soapItem["date_start"].isEmpty())
    event->setDtStart(KDateTime::fromString(soapItem["date_start"], KDateTime::ISODate));
  if (!soapItem["date_due"].isEmpty())
    // FIXME: It seems that it only gets date but not time
    event->setDtDue(KDateTime::fromString(soapItem["date_due"], KDateTime::ISODate));
  Item newItem(item);
  newItem.setPayload<KCalCore::Todo::Ptr>(event);
  return newItem;
}

/*!
 * Receives an Akonadi::Item containing KABC::Addressee payload and
 * converts this payload to a SOAP assocative array that to be stored
 * in SugarCRM
 * \param[in] item the item whose payload that will be converted
 * \return A new QHash dictionary with item attributes
 */
QHash<QString, QString> SugarCrmResource::taskSoap(const Akonadi::Item &item)
{
  const KCalCore::Todo::Ptr &payload = item.payload<KCalCore::Todo::Ptr>();

  QHash<QString, QString> soapItem;

  soapItem["name"] = payload->summary();
  soapItem["description"] = payload->description();
  if (payload->hasStartDate())
  {
    soapItem["date_start"] = payload->dtStart().toString(KDateTime::ISODate);
    soapItem["date_start_flag"] = "1";
  }
  if (payload->hasDueDate())
  {
    soapItem["date_due"] = payload->dtDue().toString(KDateTime::ISODate);
    soapItem["date_due_flag"] = "1";
  }
  return soapItem;
}

void SugarCrmResource::aboutToQuit()
{
  // TODO: any cleanup you need to do while there is still an active
  // event loop. The resource will terminate after this method returns
}

/*!
 * Called by Akonadi to configure plugin.
 * Emits a configurationDialogAccepted() signal if it was successful,
 * configurationDialogRejected() otherwise.
 * \param[in] windowId Parent window
 */
void SugarCrmResource::configure(const WId windowId)
{
  Q_UNUSED( windowId );

  KWindowSystem::setMainWindow(&configDlg, windowId);
  configDlg.setUrl(Settings::self()->url().prettyUrl());
  configDlg.setUsername(Settings::self()->username());
  configDlg.setPassword(Settings::self()->password());

  // Check if user clicked OK or Cancel
  if (configDlg.exec() == QDialog::Rejected)
  {
    emit configurationDialogRejected();
    return;
  }

  // Test if supplied data is correct
  soap = new SugarSoap(configDlg.url());
  // TODO timeout
  Settings::self()->setSessionId(soap->login(configDlg.username(), configDlg.password()));
  if (Settings::self()->sessionId().isEmpty())
  {
    emit configurationDialogRejected();
    return;
  }

  // Sotre configuration values
  Settings::self()->setUrl(configDlg.url());
  Settings::self()->setUsername(configDlg.username());
  Settings::self()->setPassword(configDlg.password());

  // And write configuration file
  Settings::self()->writeConfig();

  emit configurationDialogAccepted();

  // Start synchronization
  synchronize();
}

// FIXME: Items appear as added in Akonadi even if adding to SugarCRM failed
void SugarCrmResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )
{
  QString mod = QString(collection.attribute<ModuleAttribute>()->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;

  QString id = "";

  soap = new SugarSoap(Settings::self()->url().url());
  if (soap->editEntry(
    mod,
    (this->*SugarCrmResource::Modules[mod].soap_function)(item),
    id
  ))
  {
    Item newItem(item);
    newItem.setRemoteId(id);
    newItem.clearPayload(); // FIXME
    ModuleAttribute::ModuleTypes m;
    if (mod == "Contacts")
      m = ModuleAttribute::Contacts;
    else if (mod == "Leads")
      m = ModuleAttribute::Leads;
    else if (mod == "Tasks")
      m = ModuleAttribute::Tasks;
    else
      return;
    ModuleAttribute *attr = new ModuleAttribute(m);
    newItem.addAttribute(attr);
    changeCommitted(newItem);
  }
}

// FIXME: Items appear as changed in Akonadi even if update to SugarCRM failed
void SugarCrmResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )
{
  Q_UNUSED(parts);

  // FIXME for now, we are storing in remoteID which module the item belongs to
  QString mod = QString(item.attribute<ModuleAttribute>()->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;

  soap = new SugarSoap(Settings::self()->url().url());

  if (soap->editEntry(
    mod,
    (this->*SugarCrmResource::Modules[mod].soap_function)(item),
    item.remoteId()
  ))
    changeCommitted(Item(item));
}

void SugarCrmResource::itemRemoved( const Akonadi::Item &item )
{
  // FIXME for now, we are storing in remoteID which module the item belongs to
  QString mod = QString(item.attribute<ModuleAttribute>()->serialized());
  // Check if the module we got is valid
  if (!SugarCrmResource::Modules.contains(mod))
    return;
  soap = new SugarSoap(Settings::self()->url().url());

  QHash<QString, QString> soapItem;
  soapItem["deleted"] = "1";

  if (soap->editEntry(
    mod,
    soapItem,
    item.remoteId()
  ))
    changeCommitted(Item(item));
}

AKONADI_RESOURCE_MAIN( SugarCrmResource );
QHash<QString,module> SugarCrmResource::Modules;

#include "sugarcrmresource.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fwdtitem.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:47:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/
#ifndef _SVX_FWDTITEM_HXX
#define _SVX_FWDTITEM_HXX

// include ---------------------------------------------------------------

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef   ITEMID_FONTWIDTH
#define   ITEMID_FONTWIDTH 0
#endif

// class SvxFontWidthItem -----------------------------------------------

/*  [Beschreibung]

    Dieses Item beschreibt die Font-Breite.
*/

class SvxFontWidthItem : public SfxPoolItem
{
    UINT16  nWidth;         // 0 = default
    USHORT  nProp;          // default 100%
public:
    TYPEINFO();

    SvxFontWidthItem(   const USHORT nSz = 0,
                        const USHORT nPropWidth = 100,
                        const USHORT nId = ITEMID_FONTWIDTH );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int              operator==( const SfxPoolItem& ) const;
    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;

    virtual SfxPoolItem*     Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*     Create(SvStream &, USHORT) const;
    virtual SvStream&        Store(SvStream &, USHORT nItemVersion) const;
    virtual int              ScaleMetrics( long nMult, long nDiv );
    virtual int              HasMetrics() const;

    inline SvxFontWidthItem& operator=(const SvxFontWidthItem& rItem )
        {
            SetWidthValue( rItem.GetWidth() );
            SetProp( rItem.GetProp() );
            return *this;
        }

    void SetWidth( UINT16 nNewWidth, const USHORT nNewProp = 100 )
        {
            DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" );
            nWidth = UINT16(( (UINT32)nNewWidth * nNewProp ) / 100 );
            nProp = nNewProp;
        }

    UINT16 GetWidth() const { return nWidth; }

    void SetWidthValue( UINT16 nNewWidth )
        {
            DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" );
            nWidth = nNewWidth;
        }

    void SetProp( const USHORT nNewProp )
        {
            DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" );
            nProp = nNewProp;
        }

    USHORT GetProp() const { return nProp; }
};

#endif

<commit_msg>INTEGRATION: CWS pchfix04 (1.4.652); FILE MERGED 2007/02/05 12:13:42 os 1.4.652.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fwdtitem.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 14:19:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/
#ifndef _SVX_FWDTITEM_HXX
#define _SVX_FWDTITEM_HXX

// include ---------------------------------------------------------------

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

// class SvxFontWidthItem -----------------------------------------------

/*  [Beschreibung]

    Dieses Item beschreibt die Font-Breite.
*/

class SvxFontWidthItem : public SfxPoolItem
{
    UINT16  nWidth;         // 0 = default
    USHORT  nProp;          // default 100%
public:
    TYPEINFO();

    SvxFontWidthItem(   const USHORT nSz /*= 0*/,
                        const USHORT nPropWidth /*= 100*/,
                        const USHORT nId  );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int              operator==( const SfxPoolItem& ) const;
    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;

    virtual SfxPoolItem*     Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*     Create(SvStream &, USHORT) const;
    virtual SvStream&        Store(SvStream &, USHORT nItemVersion) const;
    virtual int              ScaleMetrics( long nMult, long nDiv );
    virtual int              HasMetrics() const;

    inline SvxFontWidthItem& operator=(const SvxFontWidthItem& rItem )
        {
            SetWidthValue( rItem.GetWidth() );
            SetProp( rItem.GetProp() );
            return *this;
        }

    void SetWidth( UINT16 nNewWidth, const USHORT nNewProp = 100 )
        {
            DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" );
            nWidth = UINT16(( (UINT32)nNewWidth * nNewProp ) / 100 );
            nProp = nNewProp;
        }

    UINT16 GetWidth() const { return nWidth; }

    void SetWidthValue( UINT16 nNewWidth )
        {
            DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" );
            nWidth = nNewWidth;
        }

    void SetProp( const USHORT nNewProp )
        {
            DBG_ASSERT( GetRefCount() == 0, "SetValue() with pooled item" );
            nProp = nNewProp;
        }

    USHORT GetProp() const { return nProp; }
};

#endif

<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "test_precomp.hpp"
#ifdef HAVE_OPENCL

//#define MAT_DEBUG
#ifdef MAT_DEBUG
#define MAT_DIFF(mat, mat2)\
{\
    for(int i = 0; i < mat.rows; i ++)\
    {\
        for(int j = 0; j < mat.cols; j ++)\
        {\
            cv::Vec4b s = mat.at<cv::Vec4b>(i, j);\
            cv::Vec4b s2 = mat2.at<cv::Vec4b>(i, j);\
            if(s != s2) printf("*");\
            else printf(".");\
        }\
        puts("\n");\
    }\
}
#else
#define MAT_DIFF(mat, mat2)
#endif

namespace
{

///////////////////////////////////////////////////////////////////////////////////////////////////////
// cvtColor
PARAM_TEST_CASE(CvtColor, cv::Size, MatDepth)
{
    cv::Size size;
    int depth;
    bool useRoi;

    cv::Mat img;

    virtual void SetUp()
    {
        size = GET_PARAM(0);
        depth = GET_PARAM(1);

        img = randomMat(size, CV_MAKE_TYPE(depth, 3), 0.0, depth == CV_32F ? 1.0 : 255.0);
    }
};

#define CVTCODE(name) cv::COLOR_ ## name
#define OCL_TEST_P_CVTCOLOR(name) OCL_TEST_P(CvtColor, name)\
{\
    cv::Mat src = img;\
    cv::ocl::oclMat ocl_img, dst;\
    ocl_img.upload(img);\
    cv::ocl::cvtColor(ocl_img, dst, CVTCODE(name));\
    cv::Mat dst_gold;\
    cv::cvtColor(src, dst_gold, CVTCODE(name));\
    cv::Mat dst_mat;\
    dst.download(dst_mat);\
    EXPECT_MAT_NEAR(dst_gold, dst_mat, 1e-5);\
}

//add new ones here using macro
OCL_TEST_P_CVTCOLOR(RGB2GRAY)
OCL_TEST_P_CVTCOLOR(BGR2GRAY)
OCL_TEST_P_CVTCOLOR(RGBA2GRAY)
OCL_TEST_P_CVTCOLOR(BGRA2GRAY)

OCL_TEST_P_CVTCOLOR(RGB2YUV)
OCL_TEST_P_CVTCOLOR(BGR2YUV)
OCL_TEST_P_CVTCOLOR(YUV2RGB)
OCL_TEST_P_CVTCOLOR(YUV2BGR)
OCL_TEST_P_CVTCOLOR(RGB2YCrCb)
OCL_TEST_P_CVTCOLOR(BGR2YCrCb)

PARAM_TEST_CASE(CvtColor_Gray2RGB, cv::Size, MatDepth, int)
{
    cv::Size size;
    int code;
    int depth;
    cv::Mat img;

    virtual void SetUp()
    {
        size  = GET_PARAM(0);
        depth = GET_PARAM(1);
        code  = GET_PARAM(2);
        img   = randomMat(size, CV_MAKETYPE(depth, 1), 0.0, depth == CV_32F ? 1.0 : 255.0);
    }
};
OCL_TEST_P(CvtColor_Gray2RGB, Accuracy)
{
    cv::Mat src = img;
    cv::ocl::oclMat ocl_img, dst;
    ocl_img.upload(src);
    cv::ocl::cvtColor(ocl_img, dst, code);
    cv::Mat dst_gold;
    cv::cvtColor(src, dst_gold, code);
    cv::Mat dst_mat;
    dst.download(dst_mat);
    EXPECT_MAT_NEAR(dst_gold, dst_mat, 1e-5);
}

PARAM_TEST_CASE(CvtColor_YUV420, cv::Size, int)
{
    cv::Size size;
    int code;

    cv::Mat img;

    virtual void SetUp()
    {
        size = GET_PARAM(0);
        code = GET_PARAM(1);
        img  = randomMat(size, CV_8UC1, 0.0, 255.0);
    }
};

OCL_TEST_P(CvtColor_YUV420, Accuracy)
{
    cv::Mat src = img;
    cv::ocl::oclMat ocl_img, dst;
    ocl_img.upload(src);
    cv::ocl::cvtColor(ocl_img, dst, code);
    cv::Mat dst_gold;
    cv::cvtColor(src, dst_gold, code);
    cv::Mat dst_mat;
    dst.download(dst_mat);
    MAT_DIFF(dst_mat, dst_gold);
    EXPECT_MAT_NEAR(dst_gold, dst_mat, 1e-5);
}

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, CvtColor, testing::Combine(
                            DIFFERENT_SIZES,
                            testing::Values(MatDepth(CV_8U), MatDepth(CV_16U), MatDepth(CV_32F))
                        ));

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, CvtColor_YUV420, testing::Combine(
                            testing::Values(cv::Size(128, 45), cv::Size(46, 132), cv::Size(1024, 1023)),
                            testing::Values((int)CV_YUV2RGBA_NV12, (int)CV_YUV2BGRA_NV12, (int)CV_YUV2RGB_NV12, (int)CV_YUV2BGR_NV12)
                        ));

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, CvtColor_Gray2RGB, testing::Combine(
                            DIFFERENT_SIZES,
                            testing::Values(MatDepth(CV_8U), MatDepth(CV_16U), MatDepth(CV_32F)),
                            testing::Values((int)CV_GRAY2BGR, (int)CV_GRAY2BGRA, (int)CV_GRAY2RGB, (int)CV_GRAY2RGBA)
                        ));
}
#endif
<commit_msg>ocl: rewrite CvtColor tests, added roi support<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "test_precomp.hpp"
#ifdef HAVE_OPENCL

namespace
{
using namespace testing;

///////////////////////////////////////////////////////////////////////////////////////////////////////
// cvtColor

PARAM_TEST_CASE(CvtColor, MatDepth, bool)
{
    int depth;
    bool use_roi;

    // src mat
    cv::Mat src1;
    cv::Mat dst1;

    // src mat with roi
    cv::Mat src1_roi;
    cv::Mat dst1_roi;

    // ocl dst mat for testing
    cv::ocl::oclMat gsrc1_whole;
    cv::ocl::oclMat gdst1_whole;

    // ocl mat with roi
    cv::ocl::oclMat gsrc1_roi;
    cv::ocl::oclMat gdst1_roi;

    virtual void SetUp()
    {
        depth = GET_PARAM(0);
        use_roi = GET_PARAM(1);
    }

    virtual void random_roi(int channelsIn, int channelsOut)
    {
        const int srcType = CV_MAKE_TYPE(depth, channelsIn);
        const int dstType = CV_MAKE_TYPE(depth, channelsOut);

        Size roiSize = randomSize(1, MAX_VALUE);
        Border srcBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(src1, src1_roi, roiSize, srcBorder, srcType, 2, 100);

        Border dst1Border = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(dst1, dst1_roi, roiSize, dst1Border, dstType, 5, 16);

        generateOclMat(gsrc1_whole, gsrc1_roi, src1, roiSize, srcBorder);
        generateOclMat(gdst1_whole, gdst1_roi, dst1, roiSize, dst1Border);
    }

    void Near(double threshold = 1e-3)
    {
        EXPECT_MAT_NEAR(dst1, gdst1_whole, threshold);
        EXPECT_MAT_NEAR(dst1_roi, gdst1_roi, threshold);
    }

    void doTest(int channelsIn, int channelsOut, int code)
    {
        for (int j = 0; j < LOOP_TIMES; j++)
        {
            random_roi(channelsIn, channelsOut);

            cv::cvtColor(src1_roi, dst1_roi, code);
            cv::ocl::cvtColor(gsrc1_roi, gdst1_roi, code);

            Near();
        }
    }
};

#define CVTCODE(name) cv::COLOR_ ## name

OCL_TEST_P(CvtColor, RGB2GRAY)
{
    doTest(3, 1, CVTCODE(RGB2GRAY));
}
OCL_TEST_P(CvtColor, GRAY2RGB)
{
    doTest(1, 3, CVTCODE(GRAY2RGB));
};

OCL_TEST_P(CvtColor, BGR2GRAY)
{
    doTest(3, 1, CVTCODE(BGR2GRAY));
}
OCL_TEST_P(CvtColor, GRAY2BGR)
{
    doTest(1, 3, CVTCODE(GRAY2BGR));
};

OCL_TEST_P(CvtColor, RGBA2GRAY)
{
    doTest(3, 1, CVTCODE(RGBA2GRAY));
}
OCL_TEST_P(CvtColor, GRAY2RGBA)
{
    doTest(1, 3, CVTCODE(GRAY2RGBA));
};

OCL_TEST_P(CvtColor, BGRA2GRAY)
{
    doTest(3, 1, CVTCODE(BGRA2GRAY));
}
OCL_TEST_P(CvtColor, GRAY2BGRA)
{
    doTest(1, 3, CVTCODE(GRAY2BGRA));
};

OCL_TEST_P(CvtColor, RGB2YUV)
{
    doTest(3, 3, CVTCODE(RGB2YUV));
}
OCL_TEST_P(CvtColor, BGR2YUV)
{
    doTest(3, 3, CVTCODE(BGR2YUV));
}
OCL_TEST_P(CvtColor, YUV2RGB)
{
    doTest(3, 3, CVTCODE(YUV2RGB));
}
OCL_TEST_P(CvtColor, YUV2BGR)
{
    doTest(3, 3, CVTCODE(YUV2BGR));
}
OCL_TEST_P(CvtColor, RGB2YCrCb)
{
    doTest(3, 3, CVTCODE(RGB2YCrCb));
}
OCL_TEST_P(CvtColor, BGR2YCrCb)
{
    doTest(3, 3, CVTCODE(BGR2YCrCb));
}

struct CvtColor_YUV420 : CvtColor
{
    void random_roi(int channelsIn, int channelsOut)
    {
        const int srcType = CV_MAKE_TYPE(depth, channelsIn);
        const int dstType = CV_MAKE_TYPE(depth, channelsOut);

        Size roiSize = randomSize(1, MAX_VALUE);
        roiSize.width *= 2;
        roiSize.height *= 3;
        Border srcBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(src1, src1_roi, roiSize, srcBorder, srcType, 2, 100);

        Border dst1Border = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(dst1, dst1_roi, roiSize, dst1Border, dstType, 5, 16);

        generateOclMat(gsrc1_whole, gsrc1_roi, src1, roiSize, srcBorder);
        generateOclMat(gdst1_whole, gdst1_roi, dst1, roiSize, dst1Border);
    }
};

OCL_TEST_P(CvtColor_YUV420, YUV2RGBA_NV12)
{
    doTest(1, 4, CV_YUV2RGBA_NV12);
};

OCL_TEST_P(CvtColor_YUV420, YUV2BGRA_NV12)
{
    doTest(1, 4, CV_YUV2BGRA_NV12);
};

OCL_TEST_P(CvtColor_YUV420, YUV2RGB_NV12)
{
    doTest(1, 3, CV_YUV2RGB_NV12);
};

OCL_TEST_P(CvtColor_YUV420, YUV2BGR_NV12)
{
    doTest(1, 3, CV_YUV2BGR_NV12);
};

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, CvtColor,
                            testing::Combine(
                                testing::Values(MatDepth(CV_8U), MatDepth(CV_16U), MatDepth(CV_32F)),
                                Bool()
                            )
                        );

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, CvtColor_YUV420,
                            testing::Combine(
                                testing::Values(MatDepth(CV_8U)),
                                Bool()
                            )
                        );

}
#endif
<|endoftext|>


<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2002 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#ifndef HAVE_UUID_GENERATE
#  include <uuid/sysdep.h>
#endif

#include <uuid/uuid.h>

#include <stdio.h>
#include <string.h>

#include <vpr/Util/GUID.h>

namespace vpr
{

 vpr::GUID::StdGUID null_guid_struct = { 0x00000000, 0x0000, 0x0000, 0x00, 0x00,
        { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
      };

 const vpr::GUID GUID::NullGUID( null_guid_struct );

 vpr::GUID::GenerateTag GUID::generateTag;
//

std::string GUID::toString () const
{
   std::string guid_str;
   char guid_c_str[37];

#ifdef HAVE_SNPRINTF
   snprintf(guid_c_str, 37,
#else
   sprintf(guid_c_str,
#endif
            "%08X-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X",
            mGuid.moz.m0, mGuid.moz.m1, mGuid.moz.m2, mGuid.moz.m3[0],
            (vpr::Uint32) mGuid.moz.m3[1], (vpr::Uint32) mGuid.moz.m3[2],
            (vpr::Uint32) mGuid.moz.m3[3], (vpr::Uint32) mGuid.moz.m3[4],
            (vpr::Uint32) mGuid.moz.m3[5], (vpr::Uint32) mGuid.moz.m3[6],
            (vpr::Uint32) mGuid.moz.m3[7]);
   guid_str = guid_c_str;

   return guid_str;
}

bool GUID::operator== (const GUID& guid) const
{
   /*
   bool ret_val0 = (mGuid.packed.l0 == guid.mGuid.packed.l0);
   bool ret_val1 = (mGuid.packed.l1 == guid.mGuid.packed.l1);
   bool ret_val2 = (mGuid.packed.l2 == guid.mGuid.packed.l2);
   bool ret_val3 = (mGuid.packed.l3 == guid.mGuid.packed.l3);
   return (ret_val0 && ret_val1 && ret_val2 && ret_val3);
   */

   return ( (mGuid.packed.l0 == guid.mGuid.packed.l0) &&
            (mGuid.packed.l1 == guid.mGuid.packed.l1) &&
            (mGuid.packed.l2 == guid.mGuid.packed.l2) &&
            (mGuid.packed.l3 == guid.mGuid.packed.l3) );
}

// ============================================================================
// Private methods.
// ============================================================================

GUID::GUID ()
   :  mGuid( GUID::NullGUID.mGuid )     // Assign a null guid
{
   ; /* Do nothing */
}

GUID::GUID (const struct vpr::GUID::StdGUID& guid)
{
   memcpy(&mGuid, &guid, sizeof(vpr::GUID::StdGUID));
}

GUID::GUID (const GUID& ns_guid, const std::string& name)
{
   generate(ns_guid,name);
}

void GUID::generate()
{
#ifdef HAVE_UUID_GENERATE
   uuid_t storage;
   uuid_generate(storage);
   memcpy((void*) &mGuid.standard, storage, sizeof(mGuid));
#else
   uuid_create( (uuid_t*)(&mGuid.standard));
#endif
}

void GUID::generate(const GUID& ns_guid, const std::string& name)
{
#ifdef HAVE_UUID_GENERATE
   vprASSERT(false && "Damn it!");
#else
   uuid_t temp_ns_id = *((uuid_t*)(&ns_guid.mGuid.standard));    // nasty, but works

   uuid_create_from_name((uuid_t*)(&mGuid.standard),
                         temp_ns_id,
                         (void*) name.c_str(), name.length());
#endif
}

void GUID::fromString (const std::string& guid_string)
{
   vpr::Uint32 m3[8];

   // The array of vpr::Uint32's is used to avoid alignment problems on
   // architectures such as MIPS.
   sscanf(guid_string.c_str(),
          "%08x-%04hx-%04hx-%02x%02x-%02x%02x%02x%02x%02x%02x",
          &mGuid.moz.m0, &mGuid.moz.m1, &mGuid.moz.m2,
          &m3[0], &m3[1], &m3[2], &m3[3], &m3[4], &m3[5], &m3[6], &m3[7]);

   // Fill the mGuid struct with the values read into m3[] above.
   for ( int i = 0; i < 8; i++ )
   {
      mGuid.moz.m3[i] = (vpr::Uint8) m3[i];
   }
}

} // End of vpr namespace
<commit_msg>Be a little less coarse when an assertion fails.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2002 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#ifndef HAVE_UUID_GENERATE
#  include <uuid/sysdep.h>
#endif

#include <uuid/uuid.h>

#include <stdio.h>
#include <string.h>

#include <vpr/Util/GUID.h>

namespace vpr
{

 vpr::GUID::StdGUID null_guid_struct = { 0x00000000, 0x0000, 0x0000, 0x00, 0x00,
        { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
      };

 const vpr::GUID GUID::NullGUID( null_guid_struct );

 vpr::GUID::GenerateTag GUID::generateTag;
//

std::string GUID::toString () const
{
   std::string guid_str;
   char guid_c_str[37];

#ifdef HAVE_SNPRINTF
   snprintf(guid_c_str, 37,
#else
   sprintf(guid_c_str,
#endif
            "%08X-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X",
            mGuid.moz.m0, mGuid.moz.m1, mGuid.moz.m2, mGuid.moz.m3[0],
            (vpr::Uint32) mGuid.moz.m3[1], (vpr::Uint32) mGuid.moz.m3[2],
            (vpr::Uint32) mGuid.moz.m3[3], (vpr::Uint32) mGuid.moz.m3[4],
            (vpr::Uint32) mGuid.moz.m3[5], (vpr::Uint32) mGuid.moz.m3[6],
            (vpr::Uint32) mGuid.moz.m3[7]);
   guid_str = guid_c_str;

   return guid_str;
}

bool GUID::operator== (const GUID& guid) const
{
   /*
   bool ret_val0 = (mGuid.packed.l0 == guid.mGuid.packed.l0);
   bool ret_val1 = (mGuid.packed.l1 == guid.mGuid.packed.l1);
   bool ret_val2 = (mGuid.packed.l2 == guid.mGuid.packed.l2);
   bool ret_val3 = (mGuid.packed.l3 == guid.mGuid.packed.l3);
   return (ret_val0 && ret_val1 && ret_val2 && ret_val3);
   */

   return ( (mGuid.packed.l0 == guid.mGuid.packed.l0) &&
            (mGuid.packed.l1 == guid.mGuid.packed.l1) &&
            (mGuid.packed.l2 == guid.mGuid.packed.l2) &&
            (mGuid.packed.l3 == guid.mGuid.packed.l3) );
}

// ============================================================================
// Private methods.
// ============================================================================

GUID::GUID ()
   :  mGuid( GUID::NullGUID.mGuid )     // Assign a null guid
{
   ; /* Do nothing */
}

GUID::GUID (const struct vpr::GUID::StdGUID& guid)
{
   memcpy(&mGuid, &guid, sizeof(vpr::GUID::StdGUID));
}

GUID::GUID (const GUID& ns_guid, const std::string& name)
{
   generate(ns_guid,name);
}

void GUID::generate()
{
#ifdef HAVE_UUID_GENERATE
   uuid_t storage;
   uuid_generate(storage);
   memcpy((void*) &mGuid.standard, storage, sizeof(mGuid));
#else
   uuid_create( (uuid_t*)(&mGuid.standard));
#endif
}

void GUID::generate(const GUID& ns_guid, const std::string& name)
{
#ifdef HAVE_UUID_GENERATE
   vprASSERT(false && "Unimplemented method!");
#else
   uuid_t temp_ns_id = *((uuid_t*)(&ns_guid.mGuid.standard));    // nasty, but works

   uuid_create_from_name((uuid_t*)(&mGuid.standard),
                         temp_ns_id,
                         (void*) name.c_str(), name.length());
#endif
}

void GUID::fromString (const std::string& guid_string)
{
   vpr::Uint32 m3[8];

   // The array of vpr::Uint32's is used to avoid alignment problems on
   // architectures such as MIPS.
   sscanf(guid_string.c_str(),
          "%08x-%04hx-%04hx-%02x%02x-%02x%02x%02x%02x%02x%02x",
          &mGuid.moz.m0, &mGuid.moz.m1, &mGuid.moz.m2,
          &m3[0], &m3[1], &m3[2], &m3[3], &m3[4], &m3[5], &m3[6], &m3[7]);

   // Fill the mGuid struct with the values read into m3[] above.
   for ( int i = 0; i < 8; i++ )
   {
      mGuid.moz.m3[i] = (vpr::Uint8) m3[i];
   }
}

} // End of vpr namespace
<|endoftext|>