<commit_before>// Copyright (c) 2011 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 "views/controls/native/native_view_host_gtk.h"

#include <gtk/gtk.h>
#include <algorithm>

#include "base/logging.h"
#include "views/controls/native/native_view_host.h"
#include "views/focus/focus_manager.h"
#include "views/widget/gtk_views_fixed.h"
#include "views/widget/native_widget_gtk.h"

namespace views {

namespace {
static bool signal_id_initialized_ = false;
static guint focus_in_event_signal_id_;
static guint focus_out_event_signal_id_;

////////////////////////////////////////////////////////////////////////////////
// Utility functions to block focus signals while re-creating
// Fixed widget.

void InitSignalIds() {
  if (!signal_id_initialized_) {
    signal_id_initialized_ = true;
    focus_in_event_signal_id_ =
        g_signal_lookup("focus-in-event", GTK_TYPE_WIDGET);
    focus_out_event_signal_id_ =
        g_signal_lookup("focus-out-event", GTK_TYPE_WIDGET);
  }
}

// Blocks a |signal_id| on the given |widget| if any.
void BlockSignal(GtkWidget* widget, guint signal_id) {
  gulong handler_id = g_signal_handler_find(G_OBJECT(widget),
                                            G_SIGNAL_MATCH_ID,
                                            signal_id,
                                            0, NULL, NULL, NULL);
  if (handler_id) {
    g_signal_handler_block(G_OBJECT(widget), handler_id);
  }
}

// Unblocks a |signal_id| on the given |widget| if any.
void UnblockSignal(GtkWidget* widget, guint signal_id) {
  gulong handler_id = g_signal_handler_find(G_OBJECT(widget),
                                            G_SIGNAL_MATCH_ID,
                                            signal_id,
                                            0, NULL, NULL, NULL);
  if (handler_id) {
    g_signal_handler_unblock(G_OBJECT(widget), handler_id);
  }
}

// Blocks focus in/out signals of the widget and its descendent
// children.
// Note: Due to the limiation of Gtk API, this only blocks the 1st
// handler found and won't block the rest if there is more than one handlers.
// See bug http://crbug.com/33236.
void BlockFocusSignals(GtkWidget* widget, gpointer data) {
  if (!widget)
    return;
  InitSignalIds();
  BlockSignal(widget, focus_in_event_signal_id_);
  BlockSignal(widget, focus_out_event_signal_id_);
  if (GTK_IS_CONTAINER(widget))
    gtk_container_foreach(GTK_CONTAINER(widget), BlockFocusSignals, data);
}

// Unlocks focus in/out signals of the widget and its descendent children.
void UnblockFocusSignals(GtkWidget* widget, gpointer data) {
  if (!widget)
    return;
  InitSignalIds();
  UnblockSignal(widget, focus_in_event_signal_id_);
  UnblockSignal(widget, focus_out_event_signal_id_);
  if (GTK_IS_CONTAINER(widget))
    gtk_container_foreach(GTK_CONTAINER(widget), UnblockFocusSignals, data);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostGtk, public:

NativeViewHostGtk::NativeViewHostGtk(NativeViewHost* host)
    : host_(host),
      installed_clip_(false),
      destroy_signal_id_(0),
      focus_signal_id_(0),
      fixed_(NULL) {
  CreateFixed(false);
}

NativeViewHostGtk::~NativeViewHostGtk() {
  if (fixed_)
    gtk_widget_destroy(fixed_);
}

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostGtk, NativeViewHostWrapper implementation:

void NativeViewHostGtk::NativeViewAttached() {
  DCHECK(host_->native_view());
  if (gtk_widget_get_parent(host_->native_view()))
    gtk_widget_reparent(host_->native_view(), fixed_);
  else
    gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());

  // Let the widget know that the native component has been painted.
  views::NativeWidgetGtk::RegisterChildExposeHandler(host_->native_view());

  if (!destroy_signal_id_) {
    destroy_signal_id_ = g_signal_connect(host_->native_view(),
                                          "destroy", G_CALLBACK(CallDestroy),
                                          this);
  }

  if (!focus_signal_id_) {
    focus_signal_id_ = g_signal_connect(host_->native_view(),
                                        "focus-in-event",
                                        G_CALLBACK(CallFocusIn), this);
  }

  // Always layout though.
  host_->Layout();

  // We own the native view as long as it's attached, so that we can safely
  // reparent it in multiple passes.
  gtk_widget_ref(host_->native_view());

  // TODO(port): figure out focus.
}

void NativeViewHostGtk::NativeViewDetaching(bool destroyed) {
  DCHECK(host_->native_view());

  g_signal_handler_disconnect(G_OBJECT(host_->native_view()),
                              destroy_signal_id_);
  destroy_signal_id_ = 0;

  g_signal_handler_disconnect(G_OBJECT(host_->native_view()),
                              focus_signal_id_);
  focus_signal_id_ = 0;

  installed_clip_ = false;

  if (fixed_ && !destroyed) {
    DCHECK_NE(static_cast<gfx::NativeView>(NULL),
              gtk_widget_get_parent(host_->native_view()));
    gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());
    DCHECK_EQ(
        0U, g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));
  }

  g_object_unref(G_OBJECT(host_->native_view()));
}

void NativeViewHostGtk::AddedToWidget() {
  if (!fixed_)
    CreateFixed(false);
  if (gtk_widget_get_parent(fixed_))
    GetHostWidget()->ReparentChild(fixed_);
  else
    GetHostWidget()->AddChild(fixed_);

  if (!host_->native_view())
    return;

  if (gtk_widget_get_parent(host_->native_view()))
    gtk_widget_reparent(host_->native_view(), fixed_);
  else
    gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());

  if (host_->IsVisibleInRootView())
    gtk_widget_show(fixed_);
  else
    gtk_widget_hide(fixed_);
  host_->Layout();
}

void NativeViewHostGtk::RemovedFromWidget() {
  if (!host_->native_view())
    return;
  DestroyFixed();
}

void NativeViewHostGtk::InstallClip(int x, int y, int w, int h) {
  DCHECK(w > 0 && h > 0);
  installed_clip_bounds_.SetRect(x, y, w, h);
  if (!installed_clip_) {
    installed_clip_ = true;

    // We only re-create the fixed with a window when a cliprect is installed.
    // Because the presence of a X Window will prevent transparency from working
    // properly, we only want it to be active for the duration of a clip
    // (typically during animations and scrolling.)
    CreateFixed(true);
  }
}

bool NativeViewHostGtk::HasInstalledClip() {
  return installed_clip_;
}

void NativeViewHostGtk::UninstallClip() {
  installed_clip_ = false;
  // We now re-create the fixed without a X Window so transparency works again.
  CreateFixed(false);
}

void NativeViewHostGtk::ShowWidget(int x, int y, int w, int h) {
  // x and y are the desired position of host_ in NativeWidgetGtk coordinates.
  int fixed_x = x;
  int fixed_y = y;
  int fixed_w = w;
  int fixed_h = h;
  int child_x = 0;
  int child_y = 0;
  int child_w = w;
  int child_h = h;
  if (installed_clip_) {
    child_x = -installed_clip_bounds_.x();
    child_y = -installed_clip_bounds_.y();
    fixed_x += -child_x;
    fixed_y += -child_y;
    fixed_w = std::min(installed_clip_bounds_.width(), w);
    fixed_h = std::min(installed_clip_bounds_.height(), h);
  }

  // Don't call gtk_widget_size_allocate now, as we're possibly in the
  // middle of a re-size, and it kicks off another re-size, and you
  // get flashing.  Instead, we'll set the desired size as properties
  // on the widget and queue the re-size.
  gtk_views_fixed_set_widget_size(host_->native_view(), child_w, child_h);
  gtk_fixed_move(GTK_FIXED(fixed_), host_->native_view(), child_x, child_y);

  // Size and place the fixed_.
  GetHostWidget()->PositionChild(fixed_, fixed_x, fixed_y, fixed_w, fixed_h);

  gtk_widget_show(fixed_);
  gtk_widget_show(host_->native_view());
}

void NativeViewHostGtk::HideWidget() {
  if (fixed_)
    gtk_widget_hide(fixed_);
}

void NativeViewHostGtk::SetFocus() {
  DCHECK(host_->native_view());
  gtk_widget_grab_focus(host_->native_view());
}

gfx::NativeViewAccessible NativeViewHostGtk::GetNativeViewAccessible() {
  return NULL;
}

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostGtk, private:

void NativeViewHostGtk::CreateFixed(bool needs_window) {
  GtkWidget* focused_widget = GetFocusedDescendant();

  bool focus_event_blocked = false;
  // We move focus around and do not want focus events to be emitted
  // during this process.
  if (fixed_) {
    BlockFocusSignals(GetHostWidget()->GetNativeView(), NULL);
    focus_event_blocked = true;
  }

  if (focused_widget) {
    // A descendant of our fixed has focus. When we destroy the fixed focus is
    // automatically moved. Temporarily move focus to our host widget, then
    // restore focus after we create the new fixed_. This way focus hasn't
    // really moved.
    gtk_widget_grab_focus(GetHostWidget()->GetNativeView());
  }

  DestroyFixed();

  fixed_ = gtk_views_fixed_new();
  gtk_widget_set_name(fixed_, "views-native-view-host-fixed");
  gtk_fixed_set_has_window(GTK_FIXED(fixed_), needs_window);
  // Defeat refcounting. We need to own the fixed.
  gtk_widget_ref(fixed_);

  NativeWidgetGtk* widget_gtk = GetHostWidget();
  if (widget_gtk)
    widget_gtk->AddChild(fixed_);

  if (host_->native_view())
    gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());

  if (widget_gtk && host_->native_view() && focused_widget) {
    gtk_widget_grab_focus(focused_widget);
  }
  if (focus_event_blocked) {
    // Unblocking a signal handler that is not blocked fails.
    // Unblock only when it's unblocked.
    UnblockFocusSignals(GetHostWidget()->GetNativeView(), NULL);
  }
}

void NativeViewHostGtk::DestroyFixed() {
  if (!fixed_)
    return;

  gtk_widget_hide(fixed_);
  GetHostWidget()->RemoveChild(fixed_);

  if (host_->native_view()) {
    // We can safely remove the widget from its container since we own the
    // widget from the moment it is attached.
    gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());
  }
  // fixed_ should not have any children this point.
  DCHECK_EQ(0U,
            g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));
  gtk_widget_destroy(fixed_);
  fixed_ = NULL;
}

NativeWidgetGtk* NativeViewHostGtk::GetHostWidget() const {
  return static_cast<NativeWidgetGtk*>(host_->GetWidget()->native_widget());
}

GtkWidget* NativeViewHostGtk::GetFocusedDescendant() {
  if (!fixed_)
    return NULL;
  NativeWidgetGtk* host = GetHostWidget();
  if (!host)
    return NULL;
  GtkWidget* top_level = gtk_widget_get_toplevel(host->GetNativeView());
  if (!top_level || !GTK_IS_WINDOW(top_level))
    return NULL;
  GtkWidget* focused = gtk_window_get_focus(GTK_WINDOW(top_level));
  if (!focused)
    return NULL;
  return (focused == fixed_ || gtk_widget_is_ancestor(focused, fixed_)) ?
      focused : NULL;
}

// static
void NativeViewHostGtk::CallDestroy(GtkObject* object,
                                    NativeViewHostGtk* host) {
  host->host_->NativeViewDestroyed();
}

// static
gboolean NativeViewHostGtk::CallFocusIn(GtkWidget* widget,
                                        GdkEventFocus* event,
                                        NativeViewHostGtk* host) {
  FocusManager* focus_manager =
      FocusManager::GetFocusManagerForNativeView(widget);
  if (!focus_manager) {
    // TODO(jcampan): http://crbug.com/21378 Reenable this NOTREACHED() when the
    // options page is only based on views.
    // NOTREACHED();
    NOTIMPLEMENTED();
    return false;
  }
  focus_manager->SetFocusedView(host->host_->focus_view());
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostWrapper, public:

// static
NativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper(
    NativeViewHost* host) {
  return new NativeViewHostGtk(host);
}

}  // namespace views
<commit_msg>Use NativeViewHostViews when using pure-views instead of NativeViewHostGtk.<commit_after>// Copyright (c) 2011 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 "views/controls/native/native_view_host_gtk.h"

#include <gtk/gtk.h>
#include <algorithm>

#include "base/logging.h"
#include "views/controls/native/native_view_host.h"
#include "views/controls/native/native_view_host_views.h"
#include "views/focus/focus_manager.h"
#include "views/widget/gtk_views_fixed.h"
#include "views/widget/native_widget_gtk.h"
#include "views/widget/widget.h"

namespace views {

namespace {
static bool signal_id_initialized_ = false;
static guint focus_in_event_signal_id_;
static guint focus_out_event_signal_id_;

////////////////////////////////////////////////////////////////////////////////
// Utility functions to block focus signals while re-creating
// Fixed widget.

void InitSignalIds() {
  if (!signal_id_initialized_) {
    signal_id_initialized_ = true;
    focus_in_event_signal_id_ =
        g_signal_lookup("focus-in-event", GTK_TYPE_WIDGET);
    focus_out_event_signal_id_ =
        g_signal_lookup("focus-out-event", GTK_TYPE_WIDGET);
  }
}

// Blocks a |signal_id| on the given |widget| if any.
void BlockSignal(GtkWidget* widget, guint signal_id) {
  gulong handler_id = g_signal_handler_find(G_OBJECT(widget),
                                            G_SIGNAL_MATCH_ID,
                                            signal_id,
                                            0, NULL, NULL, NULL);
  if (handler_id) {
    g_signal_handler_block(G_OBJECT(widget), handler_id);
  }
}

// Unblocks a |signal_id| on the given |widget| if any.
void UnblockSignal(GtkWidget* widget, guint signal_id) {
  gulong handler_id = g_signal_handler_find(G_OBJECT(widget),
                                            G_SIGNAL_MATCH_ID,
                                            signal_id,
                                            0, NULL, NULL, NULL);
  if (handler_id) {
    g_signal_handler_unblock(G_OBJECT(widget), handler_id);
  }
}

// Blocks focus in/out signals of the widget and its descendent
// children.
// Note: Due to the limiation of Gtk API, this only blocks the 1st
// handler found and won't block the rest if there is more than one handlers.
// See bug http://crbug.com/33236.
void BlockFocusSignals(GtkWidget* widget, gpointer data) {
  if (!widget)
    return;
  InitSignalIds();
  BlockSignal(widget, focus_in_event_signal_id_);
  BlockSignal(widget, focus_out_event_signal_id_);
  if (GTK_IS_CONTAINER(widget))
    gtk_container_foreach(GTK_CONTAINER(widget), BlockFocusSignals, data);
}

// Unlocks focus in/out signals of the widget and its descendent children.
void UnblockFocusSignals(GtkWidget* widget, gpointer data) {
  if (!widget)
    return;
  InitSignalIds();
  UnblockSignal(widget, focus_in_event_signal_id_);
  UnblockSignal(widget, focus_out_event_signal_id_);
  if (GTK_IS_CONTAINER(widget))
    gtk_container_foreach(GTK_CONTAINER(widget), UnblockFocusSignals, data);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostGtk, public:

NativeViewHostGtk::NativeViewHostGtk(NativeViewHost* host)
    : host_(host),
      installed_clip_(false),
      destroy_signal_id_(0),
      focus_signal_id_(0),
      fixed_(NULL) {
  CreateFixed(false);
}

NativeViewHostGtk::~NativeViewHostGtk() {
  if (fixed_)
    gtk_widget_destroy(fixed_);
}

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostGtk, NativeViewHostWrapper implementation:

void NativeViewHostGtk::NativeViewAttached() {
  DCHECK(host_->native_view());
  if (gtk_widget_get_parent(host_->native_view()))
    gtk_widget_reparent(host_->native_view(), fixed_);
  else
    gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());

  // Let the widget know that the native component has been painted.
  views::NativeWidgetGtk::RegisterChildExposeHandler(host_->native_view());

  if (!destroy_signal_id_) {
    destroy_signal_id_ = g_signal_connect(host_->native_view(),
                                          "destroy", G_CALLBACK(CallDestroy),
                                          this);
  }

  if (!focus_signal_id_) {
    focus_signal_id_ = g_signal_connect(host_->native_view(),
                                        "focus-in-event",
                                        G_CALLBACK(CallFocusIn), this);
  }

  // Always layout though.
  host_->Layout();

  // We own the native view as long as it's attached, so that we can safely
  // reparent it in multiple passes.
  gtk_widget_ref(host_->native_view());

  // TODO(port): figure out focus.
}

void NativeViewHostGtk::NativeViewDetaching(bool destroyed) {
  DCHECK(host_->native_view());

  g_signal_handler_disconnect(G_OBJECT(host_->native_view()),
                              destroy_signal_id_);
  destroy_signal_id_ = 0;

  g_signal_handler_disconnect(G_OBJECT(host_->native_view()),
                              focus_signal_id_);
  focus_signal_id_ = 0;

  installed_clip_ = false;

  if (fixed_ && !destroyed) {
    DCHECK_NE(static_cast<gfx::NativeView>(NULL),
              gtk_widget_get_parent(host_->native_view()));
    gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());
    DCHECK_EQ(
        0U, g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));
  }

  g_object_unref(G_OBJECT(host_->native_view()));
}

void NativeViewHostGtk::AddedToWidget() {
  if (!fixed_)
    CreateFixed(false);
  if (gtk_widget_get_parent(fixed_))
    GetHostWidget()->ReparentChild(fixed_);
  else
    GetHostWidget()->AddChild(fixed_);

  if (!host_->native_view())
    return;

  if (gtk_widget_get_parent(host_->native_view()))
    gtk_widget_reparent(host_->native_view(), fixed_);
  else
    gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());

  if (host_->IsVisibleInRootView())
    gtk_widget_show(fixed_);
  else
    gtk_widget_hide(fixed_);
  host_->Layout();
}

void NativeViewHostGtk::RemovedFromWidget() {
  if (!host_->native_view())
    return;
  DestroyFixed();
}

void NativeViewHostGtk::InstallClip(int x, int y, int w, int h) {
  DCHECK(w > 0 && h > 0);
  installed_clip_bounds_.SetRect(x, y, w, h);
  if (!installed_clip_) {
    installed_clip_ = true;

    // We only re-create the fixed with a window when a cliprect is installed.
    // Because the presence of a X Window will prevent transparency from working
    // properly, we only want it to be active for the duration of a clip
    // (typically during animations and scrolling.)
    CreateFixed(true);
  }
}

bool NativeViewHostGtk::HasInstalledClip() {
  return installed_clip_;
}

void NativeViewHostGtk::UninstallClip() {
  installed_clip_ = false;
  // We now re-create the fixed without a X Window so transparency works again.
  CreateFixed(false);
}

void NativeViewHostGtk::ShowWidget(int x, int y, int w, int h) {
  // x and y are the desired position of host_ in NativeWidgetGtk coordinates.
  int fixed_x = x;
  int fixed_y = y;
  int fixed_w = w;
  int fixed_h = h;
  int child_x = 0;
  int child_y = 0;
  int child_w = w;
  int child_h = h;
  if (installed_clip_) {
    child_x = -installed_clip_bounds_.x();
    child_y = -installed_clip_bounds_.y();
    fixed_x += -child_x;
    fixed_y += -child_y;
    fixed_w = std::min(installed_clip_bounds_.width(), w);
    fixed_h = std::min(installed_clip_bounds_.height(), h);
  }

  // Don't call gtk_widget_size_allocate now, as we're possibly in the
  // middle of a re-size, and it kicks off another re-size, and you
  // get flashing.  Instead, we'll set the desired size as properties
  // on the widget and queue the re-size.
  gtk_views_fixed_set_widget_size(host_->native_view(), child_w, child_h);
  gtk_fixed_move(GTK_FIXED(fixed_), host_->native_view(), child_x, child_y);

  // Size and place the fixed_.
  GetHostWidget()->PositionChild(fixed_, fixed_x, fixed_y, fixed_w, fixed_h);

  gtk_widget_show(fixed_);
  gtk_widget_show(host_->native_view());
}

void NativeViewHostGtk::HideWidget() {
  if (fixed_)
    gtk_widget_hide(fixed_);
}

void NativeViewHostGtk::SetFocus() {
  DCHECK(host_->native_view());
  gtk_widget_grab_focus(host_->native_view());
}

gfx::NativeViewAccessible NativeViewHostGtk::GetNativeViewAccessible() {
  return NULL;
}

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostGtk, private:

void NativeViewHostGtk::CreateFixed(bool needs_window) {
  GtkWidget* focused_widget = GetFocusedDescendant();

  bool focus_event_blocked = false;
  // We move focus around and do not want focus events to be emitted
  // during this process.
  if (fixed_) {
    BlockFocusSignals(GetHostWidget()->GetNativeView(), NULL);
    focus_event_blocked = true;
  }

  if (focused_widget) {
    // A descendant of our fixed has focus. When we destroy the fixed focus is
    // automatically moved. Temporarily move focus to our host widget, then
    // restore focus after we create the new fixed_. This way focus hasn't
    // really moved.
    gtk_widget_grab_focus(GetHostWidget()->GetNativeView());
  }

  DestroyFixed();

  fixed_ = gtk_views_fixed_new();
  gtk_widget_set_name(fixed_, "views-native-view-host-fixed");
  gtk_fixed_set_has_window(GTK_FIXED(fixed_), needs_window);
  // Defeat refcounting. We need to own the fixed.
  gtk_widget_ref(fixed_);

  NativeWidgetGtk* widget_gtk = GetHostWidget();
  if (widget_gtk)
    widget_gtk->AddChild(fixed_);

  if (host_->native_view())
    gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());

  if (widget_gtk && host_->native_view() && focused_widget) {
    gtk_widget_grab_focus(focused_widget);
  }
  if (focus_event_blocked) {
    // Unblocking a signal handler that is not blocked fails.
    // Unblock only when it's unblocked.
    UnblockFocusSignals(GetHostWidget()->GetNativeView(), NULL);
  }
}

void NativeViewHostGtk::DestroyFixed() {
  if (!fixed_)
    return;

  gtk_widget_hide(fixed_);
  GetHostWidget()->RemoveChild(fixed_);

  if (host_->native_view()) {
    // We can safely remove the widget from its container since we own the
    // widget from the moment it is attached.
    gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());
  }
  // fixed_ should not have any children this point.
  DCHECK_EQ(0U,
            g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));
  gtk_widget_destroy(fixed_);
  fixed_ = NULL;
}

NativeWidgetGtk* NativeViewHostGtk::GetHostWidget() const {
  return static_cast<NativeWidgetGtk*>(host_->GetWidget()->native_widget());
}

GtkWidget* NativeViewHostGtk::GetFocusedDescendant() {
  if (!fixed_)
    return NULL;
  NativeWidgetGtk* host = GetHostWidget();
  if (!host)
    return NULL;
  GtkWidget* top_level = gtk_widget_get_toplevel(host->GetNativeView());
  if (!top_level || !GTK_IS_WINDOW(top_level))
    return NULL;
  GtkWidget* focused = gtk_window_get_focus(GTK_WINDOW(top_level));
  if (!focused)
    return NULL;
  return (focused == fixed_ || gtk_widget_is_ancestor(focused, fixed_)) ?
      focused : NULL;
}

// static
void NativeViewHostGtk::CallDestroy(GtkObject* object,
                                    NativeViewHostGtk* host) {
  host->host_->NativeViewDestroyed();
}

// static
gboolean NativeViewHostGtk::CallFocusIn(GtkWidget* widget,
                                        GdkEventFocus* event,
                                        NativeViewHostGtk* host) {
  FocusManager* focus_manager =
      FocusManager::GetFocusManagerForNativeView(widget);
  if (!focus_manager) {
    // TODO(jcampan): http://crbug.com/21378 Reenable this NOTREACHED() when the
    // options page is only based on views.
    // NOTREACHED();
    NOTIMPLEMENTED();
    return false;
  }
  focus_manager->SetFocusedView(host->host_->focus_view());
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// NativeViewHostWrapper, public:

// static
NativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper(
    NativeViewHost* host) {
  if (Widget::IsPureViews())
    return new NativeViewHostViews(host);
  else
    return new NativeViewHostGtk(host);
}

}  // namespace views
<|endoftext|>


<commit_before>// Copyright WRLD Ltd (2018-), All Rights Reserved

#include "SearchWidgetController.h"
#include "SearchResultSectionItemSelectedMessage.h"
#include "SearchServicesResult.h"
#include "IMenuSectionViewModel.h"
#include "IMenuView.h"
#include "IMenuOption.h"
#include "MenuItemModel.h"
#include "IMenuModel.h"

namespace ExampleApp
{
    namespace SearchMenu
    {
        namespace View
        {
            SearchWidgetController::SearchWidgetController(ISearchWidgetView& view,
                                                           SearchServices& searchServices,
														   Modality::View::IModalBackgroundView& modalBackgroundView,
                                                           Menu::View::IMenuViewModel& viewModel,
                                                           ExampleAppMessaging::TMessageBus& messageBus)
            : m_view(view)
			, m_modalBackgroundView(modalBackgroundView)
            , m_viewModel(viewModel)
            , m_messageBus(messageBus)
            , m_searchServices(searchServices)
            , m_onSearchResultsClearedCallback(this, &SearchWidgetController::OnSearchResultsCleared)
            , m_onSearchResultSelectedCallback(this, &SearchWidgetController::OnSearchResultSelected)
            , m_onSearchQueryRefreshedHandler(this, &SearchWidgetController::OnSearchQueryRefreshedMessage)
            , m_onSearchQueryResultsLoadedHandler(this, &SearchWidgetController::OnSearchResultsLoaded)
            , m_deepLinkRequestedHandler(this, &SearchWidgetController::OnSearchDeepLinkRequestedMessage)
            , m_menuContentsChanged(true)
			, m_inInteriorMode(false)
            , m_onAppModeChanged(this, &SearchWidgetController::OnAppModeChanged)
            , m_onItemSelectedCallback(this, &SearchWidgetController::OnItemSelected)
            , m_onItemAddedCallback(this, &SearchWidgetController::OnItemAdded)
            , m_onItemRemovedCallback(this, &SearchWidgetController::OnItemRemoved)
            , m_onScreenStateChanged(this, &SearchWidgetController::OnScreenControlStateChanged)
            , m_onOpenableStateChanged(this, &SearchWidgetController::OnOpenableStateChanged)
			, m_onModalBackgroundTouchCallback(this, &SearchWidgetController::OnModalBackgroundTouch)
            , m_onViewOpenedCallback(this, &SearchWidgetController::OnViewOpened)
            , m_onViewClosedCallback(this, &SearchWidgetController::OnViewClosed)
			, m_tagCollection(m_messageBus)
            , m_shouldSelectFirstResult(false)
            {
                m_view.InsertSearchClearedCallback(m_onSearchResultsClearedCallback);
				m_view.InsertResultSelectedCallback(m_onSearchResultSelectedCallback);
                m_view.InsertOnItemSelected(m_onItemSelectedCallback);
                m_view.InsertOnViewClosed(m_onViewClosedCallback);
                m_view.InsertOnViewOpened(m_onViewOpenedCallback);

                m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);
                m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);

				m_modalBackgroundView.InsertTouchCallback(m_onModalBackgroundTouchCallback);

                m_messageBus.SubscribeUi(m_onSearchQueryRefreshedHandler);

                m_messageBus.SubscribeUi(m_onSearchQueryResultsLoadedHandler);
                m_messageBus.SubscribeUi(m_deepLinkRequestedHandler);
                m_messageBus.SubscribeUi(m_onAppModeChanged);

                for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)
                {
                    Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(static_cast<int>(i)));
					SetGroupStart(section);
                    Menu::View::IMenuModel& menuModel = section.GetModel();
                    menuModel.InsertItemAddedCallback(m_onItemAddedCallback);
                    menuModel.InsertItemRemovedCallback(m_onItemRemovedCallback);
                }
            }

            SearchWidgetController::~SearchWidgetController()
            {
				for(int i = static_cast<int>(m_viewModel.SectionsCount()); --i >= 0;)
				{
					Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));
					Menu::View::IMenuModel& menuModel = section.GetModel();
					menuModel.RemoveItemAddedCallback(m_onItemAddedCallback);
					menuModel.RemoveItemRemovedCallback(m_onItemRemovedCallback);
				}

                m_messageBus.UnsubscribeUi(m_onAppModeChanged);
                m_messageBus.UnsubscribeUi(m_onSearchQueryRefreshedHandler);
                m_messageBus.UnsubscribeUi(m_onSearchQueryResultsLoadedHandler);
                m_messageBus.UnsubscribeUi(m_deepLinkRequestedHandler);

				m_modalBackgroundView.RemoveTouchCallback(m_onModalBackgroundTouchCallback);

                m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);
                m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);

                m_view.RemoveOnViewOpened(m_onViewOpenedCallback);
                m_view.RemoveOnViewClosed(m_onViewClosedCallback);
                m_view.RemoveResultSelectedCallback(m_onSearchResultSelectedCallback);
                m_view.RemoveSearchClearedCallback(m_onSearchResultsClearedCallback);
                m_view.RemoveOnItemSelected(m_onItemSelectedCallback);
			}

			void SearchWidgetController::SetGroupStart(Menu::View::IMenuSectionViewModel& section)
			{
				if (section.Name() == "Find" ||
					section.Name() == "Drop Pin" ||
					section.Name() == "Weather")
				{
					section.SetGroupStart(true);
				}
            }

            void SearchWidgetController::OnItemAdded(Menu::View::MenuItemModel& item) {
                m_menuContentsChanged = true;
            }

            void SearchWidgetController::OnItemRemoved(Menu::View::MenuItemModel& item){
                m_menuContentsChanged = true;
            }

            void SearchWidgetController::OnSearchResultsCleared()
            {
                m_messageBus.Publish(SearchResultSection::SearchResultViewClearedMessage());
            }

            void SearchWidgetController::OnSearchResultSelected(int& index)
            {
                const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_searchServices.GetSdkSearchResultByIndex(index);

                m_messageBus.Publish(SearchResultSection::SearchResultSectionItemSelectedMessage(
                    sdkSearchResult.GetLocation().ToECEF(),
                    sdkSearchResult.IsInterior(),
                    sdkSearchResult.GetBuildingId(),
                    sdkSearchResult.GetFloor(),
                    m_searchServices.GetResultOriginalIndexFromCurrentIndex(index),
                    sdkSearchResult.GetIdentifier()));
            }

            void SearchWidgetController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)
            {
                if (m_shouldSelectFirstResult && message.GetResults().size() > 0){
                    int val = 0;
                    OnSearchResultSelected(val);
                    m_shouldSelectFirstResult = false;
                }
            }

            void SearchWidgetController::OnSearchQueryRefreshedMessage(const Search::SearchQueryRefreshedMessage& message)
            {
                const Search::SdkModel::SearchQuery &query = message.Query();

				std::string visibleText = query.Query();
				std::string tagText     = "";

				if (query.IsTag())
				{
					tagText = visibleText;

					const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);

					visibleText = tagInfo.VisibleText();
				}

                m_view.PerformSearch(visibleText,
                                     QueryContext(false,
                                                  query.IsTag(),
                                                  tagText,
                                                  query.ShouldTryInteriorSearch(),
                                                  message.Location(),
                                                  message.Radius()));
            }

            void SearchWidgetController::OnSearchDeepLinkRequestedMessage(const Search::DeepLinkedSearchQueryRequestMessage& message)
            {
                auto query = message.Query();
                auto clearPreviousResults = false;
                std::string visibleText = query.Query();
                std::string tagText = "";

                if (query.IsTag())
                {
                    tagText = visibleText;

                    if (m_tagCollection.HasText(tagText))
                    {
                        const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);

                        visibleText = tagInfo.VisibleText();
                    }
                }

                auto queryContext = QueryContext(clearPreviousResults,
                                                 query.IsTag(),
                                                 tagText,
                                                 query.ShouldTryInteriorSearch(),
                                                 query.Location(),
                                                 query.Radius());
                m_shouldSelectFirstResult = true;
                m_view.PerformSearch(visibleText, queryContext);
            }

            void SearchWidgetController::UpdateUiThread(float dt)
            {
				RefreshPresentation();
            }

            void SearchWidgetController::OnAppModeChanged(const AppModes::AppModeChangedMessage &message)
            {
				m_menuContentsChanged = true;
				m_inInteriorMode = message.GetAppMode() == AppModes::SdkModel::AppMode::InteriorMode;

                RefreshPresentation();
            }

            void SearchWidgetController::OnItemSelected(const std::string& menuText, int& sectionIndex, int& itemIndex)
            {
                Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);

				if (m_tagCollection.HasTag(menuText))
				{
					m_view.ClearSearchResults();

					TagCollection::TagInfo tagInfo = m_tagCollection.GetInfoByText(menuText);

					m_view.PerformSearch(menuText,
										 QueryContext(true, true, tagInfo.Tag(),
													  tagInfo.ShouldTryInterior()));
				}
                else if(!section.IsExpandable() || section.GetTotalItemCount()>0)
                {
                    section.GetItemAtIndex(itemIndex).MenuOption().Select();
                }
            }

            void SearchWidgetController::RefreshPresentation()
            {
                if (!m_menuContentsChanged)
                {
                    return;
                }
                m_menuContentsChanged = false;

                const size_t numSections = m_viewModel.SectionsCount();
                Menu::View::TSections sections;
                sections.reserve(numSections);

                for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)
                {
                    Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(static_cast<int>(groupIndex));

					if (section.Name() != "Discover" || !m_inInteriorMode)
					{
						sections.push_back(&section);
					}
                }

                m_view.UpdateMenuSectionViews(sections);
            }

            void SearchWidgetController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel, float& state)
            {
                if(m_viewModel.IsAddedToScreen())
                {
                    if (m_viewModel.IsFullyClosed() || m_viewModel.IsFullyOpen())
                    {
                        m_view.SetFullyOnScreen();
                    }
                    else
                    {
                        m_view.SetOnScreenStateToIntermediateValue(state);
                    }
                }
                else
                {
                    m_view.SetFullyOffScreen();
                }
            }

            void SearchWidgetController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel, float& state)
            {
                if (m_viewModel.IsFullyOnScreen())
                {
                    m_view.SetFullyOnScreen();
                }
                else if (m_viewModel.IsFullyOffScreen())
                {
                    m_view.SetFullyOffScreen();
                }
                else
                {
                    m_view.SetOnScreenStateToIntermediateValue(state);
                }
            }

            void SearchWidgetController::OnViewOpened()
            {
                if(!m_viewModel.IsFullyOpen())
                {
                    m_viewModel.Open();
                }

                if(m_viewModel.HasReactorControl())
                {
                    m_viewModel.ReleaseReactorControl();
                }
            }

            void SearchWidgetController::OnViewClosed()
            {

                if(!m_viewModel.IsFullyClosed())
                {
                    m_viewModel.Close(false);
                }

                if(m_viewModel.HasReactorControl())
                {
                    m_viewModel.ReleaseReactorControl();
                }
            }

			void SearchWidgetController::OnModalBackgroundTouch()
			{
				// the modal background goes away after the first touch, so no need to throttle

				m_view.CloseMenu();
			}
        }
    }
}
<commit_msg>Fix to MPLY-9710: crash on startup queries<commit_after>// Copyright WRLD Ltd (2018-), All Rights Reserved

#include "SearchWidgetController.h"
#include "SearchResultSectionItemSelectedMessage.h"
#include "SearchServicesResult.h"
#include "IMenuSectionViewModel.h"
#include "IMenuView.h"
#include "IMenuOption.h"
#include "MenuItemModel.h"
#include "IMenuModel.h"

namespace ExampleApp
{
    namespace SearchMenu
    {
        namespace View
        {
            SearchWidgetController::SearchWidgetController(ISearchWidgetView& view,
                                                           SearchServices& searchServices,
														   Modality::View::IModalBackgroundView& modalBackgroundView,
                                                           Menu::View::IMenuViewModel& viewModel,
                                                           ExampleAppMessaging::TMessageBus& messageBus)
            : m_view(view)
			, m_modalBackgroundView(modalBackgroundView)
            , m_viewModel(viewModel)
            , m_messageBus(messageBus)
            , m_searchServices(searchServices)
            , m_onSearchResultsClearedCallback(this, &SearchWidgetController::OnSearchResultsCleared)
            , m_onSearchResultSelectedCallback(this, &SearchWidgetController::OnSearchResultSelected)
            , m_onSearchQueryRefreshedHandler(this, &SearchWidgetController::OnSearchQueryRefreshedMessage)
            , m_onSearchQueryResultsLoadedHandler(this, &SearchWidgetController::OnSearchResultsLoaded)
            , m_deepLinkRequestedHandler(this, &SearchWidgetController::OnSearchDeepLinkRequestedMessage)
            , m_menuContentsChanged(true)
			, m_inInteriorMode(false)
            , m_onAppModeChanged(this, &SearchWidgetController::OnAppModeChanged)
            , m_onItemSelectedCallback(this, &SearchWidgetController::OnItemSelected)
            , m_onItemAddedCallback(this, &SearchWidgetController::OnItemAdded)
            , m_onItemRemovedCallback(this, &SearchWidgetController::OnItemRemoved)
            , m_onScreenStateChanged(this, &SearchWidgetController::OnScreenControlStateChanged)
            , m_onOpenableStateChanged(this, &SearchWidgetController::OnOpenableStateChanged)
			, m_onModalBackgroundTouchCallback(this, &SearchWidgetController::OnModalBackgroundTouch)
            , m_onViewOpenedCallback(this, &SearchWidgetController::OnViewOpened)
            , m_onViewClosedCallback(this, &SearchWidgetController::OnViewClosed)
			, m_tagCollection(m_messageBus)
            , m_shouldSelectFirstResult(false)
            {
                m_view.InsertSearchClearedCallback(m_onSearchResultsClearedCallback);
				m_view.InsertResultSelectedCallback(m_onSearchResultSelectedCallback);
                m_view.InsertOnItemSelected(m_onItemSelectedCallback);
                m_view.InsertOnViewClosed(m_onViewClosedCallback);
                m_view.InsertOnViewOpened(m_onViewOpenedCallback);

                m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);
                m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);

				m_modalBackgroundView.InsertTouchCallback(m_onModalBackgroundTouchCallback);

                m_messageBus.SubscribeUi(m_onSearchQueryRefreshedHandler);

                m_messageBus.SubscribeUi(m_onSearchQueryResultsLoadedHandler);
                m_messageBus.SubscribeUi(m_deepLinkRequestedHandler);
                m_messageBus.SubscribeUi(m_onAppModeChanged);

                for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)
                {
                    Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(static_cast<int>(i)));
					SetGroupStart(section);
                    Menu::View::IMenuModel& menuModel = section.GetModel();
                    menuModel.InsertItemAddedCallback(m_onItemAddedCallback);
                    menuModel.InsertItemRemovedCallback(m_onItemRemovedCallback);
                }
            }

            SearchWidgetController::~SearchWidgetController()
            {
				for(int i = static_cast<int>(m_viewModel.SectionsCount()); --i >= 0;)
				{
					Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));
					Menu::View::IMenuModel& menuModel = section.GetModel();
					menuModel.RemoveItemAddedCallback(m_onItemAddedCallback);
					menuModel.RemoveItemRemovedCallback(m_onItemRemovedCallback);
				}

                m_messageBus.UnsubscribeUi(m_onAppModeChanged);
                m_messageBus.UnsubscribeUi(m_onSearchQueryRefreshedHandler);
                m_messageBus.UnsubscribeUi(m_onSearchQueryResultsLoadedHandler);
                m_messageBus.UnsubscribeUi(m_deepLinkRequestedHandler);

				m_modalBackgroundView.RemoveTouchCallback(m_onModalBackgroundTouchCallback);

                m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);
                m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);

                m_view.RemoveOnViewOpened(m_onViewOpenedCallback);
                m_view.RemoveOnViewClosed(m_onViewClosedCallback);
                m_view.RemoveResultSelectedCallback(m_onSearchResultSelectedCallback);
                m_view.RemoveSearchClearedCallback(m_onSearchResultsClearedCallback);
                m_view.RemoveOnItemSelected(m_onItemSelectedCallback);
			}

			void SearchWidgetController::SetGroupStart(Menu::View::IMenuSectionViewModel& section)
			{
				if (section.Name() == "Find" ||
					section.Name() == "Drop Pin" ||
					section.Name() == "Weather")
				{
					section.SetGroupStart(true);
				}
            }

            void SearchWidgetController::OnItemAdded(Menu::View::MenuItemModel& item) {
                m_menuContentsChanged = true;
            }

            void SearchWidgetController::OnItemRemoved(Menu::View::MenuItemModel& item){
                m_menuContentsChanged = true;
            }

            void SearchWidgetController::OnSearchResultsCleared()
            {
                m_messageBus.Publish(SearchResultSection::SearchResultViewClearedMessage());
            }

            void SearchWidgetController::OnSearchResultSelected(int& index)
            {
                const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_searchServices.GetSdkSearchResultByIndex(index);

                m_messageBus.Publish(SearchResultSection::SearchResultSectionItemSelectedMessage(
                    sdkSearchResult.GetLocation().ToECEF(),
                    sdkSearchResult.IsInterior(),
                    sdkSearchResult.GetBuildingId(),
                    sdkSearchResult.GetFloor(),
                    m_searchServices.GetResultOriginalIndexFromCurrentIndex(index),
                    sdkSearchResult.GetIdentifier()));
            }

            void SearchWidgetController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)
            {
                if (m_shouldSelectFirstResult && message.GetResults().size() > 0){
                    int val = 0;
                    OnSearchResultSelected(val);
                    m_shouldSelectFirstResult = false;
                }
            }

            void SearchWidgetController::OnSearchQueryRefreshedMessage(const Search::SearchQueryRefreshedMessage& message)
            {
                const Search::SdkModel::SearchQuery &query = message.Query();

				std::string visibleText = query.Query();
				std::string tagText     = "";

				if (query.IsTag())
				{
					tagText = visibleText;

					const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);

					visibleText = tagInfo.VisibleText();
				}

                m_view.PerformSearch(visibleText,
                                     QueryContext(false,
                                                  query.IsTag(),
                                                  tagText,
                                                  query.ShouldTryInteriorSearch(),
                                                  message.Location(),
                                                  message.Radius()));
            }

            void SearchWidgetController::OnSearchDeepLinkRequestedMessage(const Search::DeepLinkedSearchQueryRequestMessage& message)
            {
                // needed to avoid a reentrant call on the reactor logic on startup queries / deeplinks
                m_view.CloseMenu();

                auto query = message.Query();
                auto clearPreviousResults = false;
                std::string visibleText = query.Query();
                std::string tagText = "";

                if (query.IsTag())
                {
                    tagText = visibleText;

                    if (m_tagCollection.HasText(tagText))
                    {
                        const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);

                        visibleText = tagInfo.VisibleText();
                    }
                }

                auto queryContext = QueryContext(clearPreviousResults,
                                                 query.IsTag(),
                                                 tagText,
                                                 query.ShouldTryInteriorSearch(),
                                                 query.Location(),
                                                 query.Radius());
                m_shouldSelectFirstResult = true;
                m_view.PerformSearch(visibleText, queryContext);
            }

            void SearchWidgetController::UpdateUiThread(float dt)
            {
				RefreshPresentation();
            }

            void SearchWidgetController::OnAppModeChanged(const AppModes::AppModeChangedMessage &message)
            {
				m_menuContentsChanged = true;
				m_inInteriorMode = message.GetAppMode() == AppModes::SdkModel::AppMode::InteriorMode;

                RefreshPresentation();
            }

            void SearchWidgetController::OnItemSelected(const std::string& menuText, int& sectionIndex, int& itemIndex)
            {
                Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);

				if (m_tagCollection.HasTag(menuText))
				{
					m_view.ClearSearchResults();

					TagCollection::TagInfo tagInfo = m_tagCollection.GetInfoByText(menuText);

					m_view.PerformSearch(menuText,
										 QueryContext(true, true, tagInfo.Tag(),
													  tagInfo.ShouldTryInterior()));
				}
                else if(!section.IsExpandable() || section.GetTotalItemCount()>0)
                {
                    section.GetItemAtIndex(itemIndex).MenuOption().Select();
                }
            }

            void SearchWidgetController::RefreshPresentation()
            {
                if (!m_menuContentsChanged)
                {
                    return;
                }
                m_menuContentsChanged = false;

                const size_t numSections = m_viewModel.SectionsCount();
                Menu::View::TSections sections;
                sections.reserve(numSections);

                for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)
                {
                    Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(static_cast<int>(groupIndex));

					if (section.Name() != "Discover" || !m_inInteriorMode)
					{
						sections.push_back(&section);
					}
                }

                m_view.UpdateMenuSectionViews(sections);
            }

            void SearchWidgetController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel, float& state)
            {
                if(m_viewModel.IsAddedToScreen())
                {
                    if (m_viewModel.IsFullyClosed() || m_viewModel.IsFullyOpen())
                    {
                        m_view.SetFullyOnScreen();
                    }
                    else
                    {
                        m_view.SetOnScreenStateToIntermediateValue(state);
                    }
                }
                else
                {
                    m_view.SetFullyOffScreen();
                }
            }

            void SearchWidgetController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel, float& state)
            {
                if (m_viewModel.IsFullyOnScreen())
                {
                    m_view.SetFullyOnScreen();
                }
                else if (m_viewModel.IsFullyOffScreen())
                {
                    m_view.SetFullyOffScreen();
                }
                else
                {
                    m_view.SetOnScreenStateToIntermediateValue(state);
                }
            }

            void SearchWidgetController::OnViewOpened()
            {
                if(!m_viewModel.IsFullyOpen())
                {
                    m_viewModel.Open();
                }

                if(m_viewModel.HasReactorControl())
                {
                    m_viewModel.ReleaseReactorControl();
                }
            }

            void SearchWidgetController::OnViewClosed()
            {
                if(!m_viewModel.IsFullyClosed())
                {
                    m_viewModel.Close();
                }

                if(m_viewModel.HasReactorControl())
                {
                    m_viewModel.ReleaseReactorControl();
                }
            }

			void SearchWidgetController::OnModalBackgroundTouch()
			{
				// the modal background goes away after the first touch, so no need to throttle

				m_view.CloseMenu();
			}
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Renderer/OpenGL.hpp>
#include <Nazara/Renderer/DebugDrawer.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/Shader.hpp>
#include <Nazara/Utility/AxisAlignedBox.hpp>
#include <Nazara/Utility/Skeleton.hpp>
#include <Nazara/Utility/VertexBuffer.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp>
#include <Nazara/Utility/VertexStruct.hpp>
#include <Nazara/Renderer/Debug.hpp>

///TODO: Améliorer

namespace
{
	static NzColor primaryColor = NzColor::Red;
	static NzColor secondaryColor = NzColor::Green;
	static NzShader* shader = nullptr;
	static NzVertexBuffer* vertexBuffer = nullptr;
	static NzVertexDeclaration* vertexDeclaration = nullptr;
	static bool depthTest = true;
	static bool initialized = false;
	static float lineWidth = 2.f;
	static float pointSize = 3.f;
	static int colorLocation = -1;
}

void NzDebugDrawer::Draw(const NzAxisAlignedBox& aabb)
{
	if (!aabb.IsFinite())
		return;

	Draw(aabb.GetCube());
}

void NzDebugDrawer::Draw(const NzCubei& cube)
{
	Draw(NzCubef(cube));
}

void NzDebugDrawer::Draw(const NzCubef& cube)
{
	if (!initialized)
	{
		NazaraError("Debug drawer is not initialized");
		return;
	}

	NzVertexStruct_XYZ* vertex = reinterpret_cast<NzVertexStruct_XYZ*>(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, 24));
	if (!vertex)
	{
		NazaraError("Failed to map buffer");
		return;
	}

	NzVector3f max, min;
	max = cube.GetPosition() + cube.GetSize();
	min = cube.GetPosition();

	vertex->position.Set(min.x, min.y, min.z);
	vertex++;
	vertex->position.Set(max.x, min.y, min.z);
	vertex++;

	vertex->position.Set(min.x, min.y, min.z);
	vertex++;
	vertex->position.Set(min.x, max.y, min.z);
	vertex++;

	vertex->position.Set(min.x, min.y, min.z);
	vertex++;
	vertex->position.Set(min.x, min.y, max.z);
	vertex++;

	vertex->position.Set(max.x, max.y, max.z);
	vertex++;
	vertex->position.Set(min.x, max.y, max.z);
	vertex++;

	vertex->position.Set(max.x, max.y, max.z);
	vertex++;
	vertex->position.Set(max.x, min.y, max.z);
	vertex++;

	vertex->position.Set(max.x, max.y, max.z);
	vertex++;
	vertex->position.Set(max.x, max.y, min.z);
	vertex++;

	vertex->position.Set(min.x, min.y, max.z);
	vertex++;
	vertex->position.Set(max.x, min.y, max.z);
	vertex++;

	vertex->position.Set(min.x, min.y, max.z);
	vertex++;
	vertex->position.Set(min.x, max.y, max.z);
	vertex++;

	vertex->position.Set(min.x, max.y, min.z);
	vertex++;
	vertex->position.Set(max.x, max.y, min.z);
	vertex++;

	vertex->position.Set(min.x, max.y, min.z);
	vertex++;
	vertex->position.Set(min.x, max.y, max.z);
	vertex++;

	vertex->position.Set(max.x, min.y, min.z);
	vertex++;
	vertex->position.Set(max.x, max.y, min.z);
	vertex++;

	vertex->position.Set(max.x, min.y, min.z);
	vertex++;
	vertex->position.Set(max.x, min.y, max.z);
	vertex++;

	if (!vertexBuffer->Unmap())
		NazaraWarning("Failed to unmap buffer");

	NzShader* oldShader = NzRenderer::GetShader();

	if (!NzRenderer::SetShader(shader))
	{
		NazaraError("Failed to set debug shader");
		return;
	}

	bool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);
	if (depthTestActive != depthTest)
		NzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);

	NzRenderer::SetVertexBuffer(vertexBuffer);

	shader->SendColor(colorLocation, primaryColor);

	NzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, 24);

	if (depthTestActive != depthTest)
		NzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);

	if (!NzRenderer::SetShader(oldShader))
		NazaraWarning("Failed to reset shader");
}

void NzDebugDrawer::Draw(const NzCubeui& cube)
{
	Draw(NzCubef(cube));
}

void NzDebugDrawer::Draw(const NzSkeleton* skeleton)
{
	if (!initialized)
	{
		NazaraError("Debug drawer is not initialized");
		return;
	}

	unsigned int jointCount = skeleton->GetJointCount();
	if (vertexBuffer->GetVertexCount() < jointCount*2)
	{
		NazaraError("Debug buffer not length enougth to draw object");
		return;
	}

	NzVertexStruct_XYZ* vertex = reinterpret_cast<NzVertexStruct_XYZ*>(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, jointCount*2));
	if (!vertex)
	{
		NazaraError("Failed to map buffer");
		return;
	}

	unsigned int vertexCount = 0;
	for (unsigned int i = 0; i < jointCount; ++i)
	{
		const NzNode* joint = skeleton->GetJoint(i);
		const NzNode* parent = joint->GetParent();
		if (parent)
		{
			vertex->position = joint->GetDerivedTranslation();
			vertex++;

			vertex->position = parent->GetDerivedTranslation();
			vertex++;

			vertexCount += 2;
		}
	}

	if (!vertexBuffer->Unmap())
		NazaraWarning("Failed to unmap buffer");

	if (vertexCount > 0)
	{
		NzShader* oldShader = NzRenderer::GetShader();

		if (!NzRenderer::SetShader(shader))
		{
			NazaraError("Failed to set debug shader");
			return;
		}

		bool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);
		if (depthTestActive != depthTest)
			NzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);

		NzRenderer::SetVertexBuffer(vertexBuffer);

		shader->SendColor(colorLocation, primaryColor);
		NzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, vertexCount);

		float oldPointSize = NzRenderer::GetPointSize();
		NzRenderer::SetPointSize(pointSize);

		shader->SendColor(colorLocation, secondaryColor);
		NzRenderer::DrawPrimitives(nzPrimitiveType_PointList, 0, vertexCount);

		NzRenderer::SetPointSize(oldPointSize);

		if (depthTestActive != depthTest)
			NzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);

		if (!NzRenderer::SetShader(oldShader))
			NazaraWarning("Failed to reset shader");
	}
}

bool NzDebugDrawer::Initialize()
{
	if (!initialized)
	{
		// Shader
		{
			const char* fragmentSource110 =
			"#version 110\n"
			"uniform vec3 color;\n"
			"void main()\n"
			"{\n"
			"	gl_FragColor = vec4(color, 1.0);\n"
			"}\n";

			const char* fragmentSource140 =
			"#version 140\n"
			"uniform vec3 color;\n"
			"out vec4 RenderTarget0;\n"
			"void main()\n"
			"{\n"
			"	RenderTarget0 = vec4(color, 1.0);\n"
			"}\n";

			const char* vertexSource110 =
			"#version 110\n"
			"attribute vec3 Position;\n"
			"uniform mat4 WorldViewProjMatrix;\n"
			"void main()\n"
			"{\n"
			"    gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\n"
			"}\n";

			const char* vertexSource140 =
			"#version 140\n"
			"in vec3 Position;\n"
			"uniform mat4 WorldViewProjMatrix;\n"
			"void main()\n"
			"{\n"
			"    gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\n"
			"}\n";

			bool useGLSL140 = (NzOpenGL::GetVersion() >= 310);

			shader = new NzShader(nzShaderLanguage_GLSL);
			if (!shader->Load(nzShaderType_Fragment, (useGLSL140) ? fragmentSource140 : fragmentSource110))
			{
				NazaraError("Failed to load fragment shader");
				Uninitialize();

				return false;
			}

			if (!shader->Load(nzShaderType_Vertex, (useGLSL140) ? vertexSource140 : vertexSource110))
			{
				NazaraError("Failed to load vertex shader");
				Uninitialize();

				return false;
			}

			if (!shader->Compile())
			{
				NazaraError("Failed to compile shader");
				Uninitialize();

				return false;
			}

			colorLocation = shader->GetUniformLocation("color");
		}

		// VertexDeclaration
		{
			NzVertexElement element;
			element.offset = 0;
			element.type = nzElementType_Float3;
			element.usage = nzElementUsage_Position;

			vertexDeclaration = new NzVertexDeclaration;
			if (!vertexDeclaration->Create(&element, 1))
			{
				NazaraError("Failed to create declaration");
				Uninitialize();

				return false;
			}
		}

		// VertexBuffer (Nécessite la déclaration)
		{
			vertexBuffer = new NzVertexBuffer(vertexDeclaration, 256, nzBufferStorage_Hardware, nzBufferUsage_Dynamic);
			if (!vertexBuffer->GetBuffer()->IsValid())
			{
				NazaraError("Failed to create buffer");
				Uninitialize();

				return false;
			}
		}

		initialized = true;
	}

	return true;
}

bool NzDebugDrawer::GetDepthTest()
{
	return depthTest;
}

float NzDebugDrawer::GetLineWidth()
{
	return lineWidth;
}

float NzDebugDrawer::GetPointSize()
{
	return pointSize;
}

NzColor NzDebugDrawer::GetPrimaryColor()
{
	return primaryColor;
}

NzColor NzDebugDrawer::GetSecondaryColor()
{
	return secondaryColor;
}

void NzDebugDrawer::SetDepthTest(bool shouldTest)
{
	depthTest = shouldTest;
}

void NzDebugDrawer::SetLineWidth(float width)
{
	lineWidth = width;
}

void NzDebugDrawer::SetPointSize(float size)
{
	pointSize = size;
}

void NzDebugDrawer::SetPrimaryColor(const NzColor& color)
{
	primaryColor = color;
}

void NzDebugDrawer::SetSecondaryColor(const NzColor& color)
{
	secondaryColor = color;
}

void NzDebugDrawer::Uninitialize()
{
	if (shader)
	{
		delete shader;
		shader = nullptr;
	}

	if (vertexBuffer)
	{
		delete vertexBuffer;
		vertexBuffer = nullptr;
	}

	if (vertexDeclaration)
	{
		delete vertexDeclaration;
		vertexDeclaration = nullptr;
	}

	initialized = false;
}
<commit_msg>Fixed debug drawer not setting line width<commit_after>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Renderer/OpenGL.hpp>
#include <Nazara/Renderer/DebugDrawer.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/Shader.hpp>
#include <Nazara/Utility/AxisAlignedBox.hpp>
#include <Nazara/Utility/Skeleton.hpp>
#include <Nazara/Utility/VertexBuffer.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp>
#include <Nazara/Utility/VertexStruct.hpp>
#include <Nazara/Renderer/Debug.hpp>

///TODO: Améliorer

namespace
{
	static NzColor primaryColor = NzColor::Red;
	static NzColor secondaryColor = NzColor::Green;
	static NzShader* shader = nullptr;
	static NzVertexBuffer* vertexBuffer = nullptr;
	static NzVertexDeclaration* vertexDeclaration = nullptr;
	static bool depthTest = true;
	static bool initialized = false;
	static float lineWidth = 2.f;
	static float pointSize = 3.f;
	static int colorLocation = -1;
}

void NzDebugDrawer::Draw(const NzAxisAlignedBox& aabb)
{
	if (!aabb.IsFinite())
		return;

	Draw(aabb.GetCube());
}

void NzDebugDrawer::Draw(const NzCubei& cube)
{
	Draw(NzCubef(cube));
}

void NzDebugDrawer::Draw(const NzCubef& cube)
{
	if (!initialized)
	{
		NazaraError("Debug drawer is not initialized");
		return;
	}

	NzVertexStruct_XYZ* vertex = reinterpret_cast<NzVertexStruct_XYZ*>(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, 24));
	if (!vertex)
	{
		NazaraError("Failed to map buffer");
		return;
	}

	NzVector3f max, min;
	max = cube.GetPosition() + cube.GetSize();
	min = cube.GetPosition();

	vertex->position.Set(min.x, min.y, min.z);
	vertex++;
	vertex->position.Set(max.x, min.y, min.z);
	vertex++;

	vertex->position.Set(min.x, min.y, min.z);
	vertex++;
	vertex->position.Set(min.x, max.y, min.z);
	vertex++;

	vertex->position.Set(min.x, min.y, min.z);
	vertex++;
	vertex->position.Set(min.x, min.y, max.z);
	vertex++;

	vertex->position.Set(max.x, max.y, max.z);
	vertex++;
	vertex->position.Set(min.x, max.y, max.z);
	vertex++;

	vertex->position.Set(max.x, max.y, max.z);
	vertex++;
	vertex->position.Set(max.x, min.y, max.z);
	vertex++;

	vertex->position.Set(max.x, max.y, max.z);
	vertex++;
	vertex->position.Set(max.x, max.y, min.z);
	vertex++;

	vertex->position.Set(min.x, min.y, max.z);
	vertex++;
	vertex->position.Set(max.x, min.y, max.z);
	vertex++;

	vertex->position.Set(min.x, min.y, max.z);
	vertex++;
	vertex->position.Set(min.x, max.y, max.z);
	vertex++;

	vertex->position.Set(min.x, max.y, min.z);
	vertex++;
	vertex->position.Set(max.x, max.y, min.z);
	vertex++;

	vertex->position.Set(min.x, max.y, min.z);
	vertex++;
	vertex->position.Set(min.x, max.y, max.z);
	vertex++;

	vertex->position.Set(max.x, min.y, min.z);
	vertex++;
	vertex->position.Set(max.x, max.y, min.z);
	vertex++;

	vertex->position.Set(max.x, min.y, min.z);
	vertex++;
	vertex->position.Set(max.x, min.y, max.z);
	vertex++;

	if (!vertexBuffer->Unmap())
		NazaraWarning("Failed to unmap buffer");

	NzShader* oldShader = NzRenderer::GetShader();

	if (!NzRenderer::SetShader(shader))
	{
		NazaraError("Failed to set debug shader");
		return;
	}

	bool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);
	if (depthTestActive != depthTest)
		NzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);

	NzRenderer::SetVertexBuffer(vertexBuffer);

	shader->SendColor(colorLocation, primaryColor);

	NzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, 24);

	if (depthTestActive != depthTest)
		NzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);

	if (!NzRenderer::SetShader(oldShader))
		NazaraWarning("Failed to reset shader");
}

void NzDebugDrawer::Draw(const NzCubeui& cube)
{
	Draw(NzCubef(cube));
}

void NzDebugDrawer::Draw(const NzSkeleton* skeleton)
{
	if (!initialized)
	{
		NazaraError("Debug drawer is not initialized");
		return;
	}

	unsigned int jointCount = skeleton->GetJointCount();
	if (vertexBuffer->GetVertexCount() < jointCount*2)
	{
		NazaraError("Debug buffer not length enougth to draw object");
		return;
	}

	NzVertexStruct_XYZ* vertex = reinterpret_cast<NzVertexStruct_XYZ*>(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, jointCount*2));
	if (!vertex)
	{
		NazaraError("Failed to map buffer");
		return;
	}

	unsigned int vertexCount = 0;
	for (unsigned int i = 0; i < jointCount; ++i)
	{
		const NzNode* joint = skeleton->GetJoint(i);
		const NzNode* parent = joint->GetParent();
		if (parent)
		{
			vertex->position = joint->GetDerivedTranslation();
			vertex++;

			vertex->position = parent->GetDerivedTranslation();
			vertex++;

			vertexCount += 2;
		}
	}

	if (!vertexBuffer->Unmap())
		NazaraWarning("Failed to unmap buffer");

	if (vertexCount > 0)
	{
		NzShader* oldShader = NzRenderer::GetShader();

		if (!NzRenderer::SetShader(shader))
		{
			NazaraError("Failed to set debug shader");
			return;
		}

		bool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);
		if (depthTestActive != depthTest)
			NzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);

		NzRenderer::SetVertexBuffer(vertexBuffer);

		float oldLineWidth = NzRenderer::GetLineWidth();
		NzRenderer::SetLineWidth(lineWidth);

		shader->SendColor(colorLocation, primaryColor);
		NzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, vertexCount);

		float oldPointSize = NzRenderer::GetPointSize();
		NzRenderer::SetPointSize(pointSize);

		shader->SendColor(colorLocation, secondaryColor);
		NzRenderer::DrawPrimitives(nzPrimitiveType_PointList, 0, vertexCount);

		NzRenderer::SetLineWidth(oldLineWidth);
		NzRenderer::SetPointSize(oldPointSize);

		if (depthTestActive != depthTest)
			NzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);

		if (!NzRenderer::SetShader(oldShader))
			NazaraWarning("Failed to reset shader");
	}
}

bool NzDebugDrawer::Initialize()
{
	if (!initialized)
	{
		// Shader
		{
			const char* fragmentSource110 =
			"#version 110\n"
			"uniform vec3 color;\n"
			"void main()\n"
			"{\n"
			"	gl_FragColor = vec4(color, 1.0);\n"
			"}\n";

			const char* fragmentSource140 =
			"#version 140\n"
			"uniform vec3 color;\n"
			"out vec4 RenderTarget0;\n"
			"void main()\n"
			"{\n"
			"	RenderTarget0 = vec4(color, 1.0);\n"
			"}\n";

			const char* vertexSource110 =
			"#version 110\n"
			"attribute vec3 Position;\n"
			"uniform mat4 WorldViewProjMatrix;\n"
			"void main()\n"
			"{\n"
			"    gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\n"
			"}\n";

			const char* vertexSource140 =
			"#version 140\n"
			"in vec3 Position;\n"
			"uniform mat4 WorldViewProjMatrix;\n"
			"void main()\n"
			"{\n"
			"    gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\n"
			"}\n";

			bool useGLSL140 = (NzOpenGL::GetVersion() >= 310);

			shader = new NzShader(nzShaderLanguage_GLSL);
			if (!shader->Load(nzShaderType_Fragment, (useGLSL140) ? fragmentSource140 : fragmentSource110))
			{
				NazaraError("Failed to load fragment shader");
				Uninitialize();

				return false;
			}

			if (!shader->Load(nzShaderType_Vertex, (useGLSL140) ? vertexSource140 : vertexSource110))
			{
				NazaraError("Failed to load vertex shader");
				Uninitialize();

				return false;
			}

			if (!shader->Compile())
			{
				NazaraError("Failed to compile shader");
				Uninitialize();

				return false;
			}

			colorLocation = shader->GetUniformLocation("color");
		}

		// VertexDeclaration
		{
			NzVertexElement element;
			element.offset = 0;
			element.type = nzElementType_Float3;
			element.usage = nzElementUsage_Position;

			vertexDeclaration = new NzVertexDeclaration;
			if (!vertexDeclaration->Create(&element, 1))
			{
				NazaraError("Failed to create declaration");
				Uninitialize();

				return false;
			}
		}

		// VertexBuffer (Nécessite la déclaration)
		{
			vertexBuffer = new NzVertexBuffer(vertexDeclaration, 256, nzBufferStorage_Hardware, nzBufferUsage_Dynamic);
			if (!vertexBuffer->GetBuffer()->IsValid())
			{
				NazaraError("Failed to create buffer");
				Uninitialize();

				return false;
			}
		}

		initialized = true;
	}

	return true;
}

bool NzDebugDrawer::GetDepthTest()
{
	return depthTest;
}

float NzDebugDrawer::GetLineWidth()
{
	return lineWidth;
}

float NzDebugDrawer::GetPointSize()
{
	return pointSize;
}

NzColor NzDebugDrawer::GetPrimaryColor()
{
	return primaryColor;
}

NzColor NzDebugDrawer::GetSecondaryColor()
{
	return secondaryColor;
}

void NzDebugDrawer::SetDepthTest(bool shouldTest)
{
	depthTest = shouldTest;
}

void NzDebugDrawer::SetLineWidth(float width)
{
	lineWidth = width;
}

void NzDebugDrawer::SetPointSize(float size)
{
	pointSize = size;
}

void NzDebugDrawer::SetPrimaryColor(const NzColor& color)
{
	primaryColor = color;
}

void NzDebugDrawer::SetSecondaryColor(const NzColor& color)
{
	secondaryColor = color;
}

void NzDebugDrawer::Uninitialize()
{
	if (shader)
	{
		delete shader;
		shader = nullptr;
	}

	if (vertexBuffer)
	{
		delete vertexBuffer;
		vertexBuffer = nullptr;
	}

	if (vertexDeclaration)
	{
		delete vertexDeclaration;
		vertexDeclaration = nullptr;
	}

	initialized = false;
}
<|endoftext|>


<commit_before>// Copyright (C) 2014-2016  CEA/DEN, EDF R&D, OPEN CASCADE
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// Author: Adrien Bruneton (CEA)

#include "PVViewer_Behaviors.h"

#include <QMainWindow>

#include <pqInterfaceTracker.h>
#include <pqApplicationCore.h>
#include <pqPluginManager.h>
#include <pqStandardPropertyWidgetInterface.h>
#include <pqStandardViewFrameActionsImplementation.h>
#include <pqPropertiesPanel.h>

#include <pqAlwaysConnectedBehavior.h>
#include <pqAutoLoadPluginXMLBehavior.h>
#include <pqCommandLineOptionsBehavior.h>
#include <pqCrashRecoveryBehavior.h>
#include <pqDataTimeStepBehavior.h>
#include <pqDefaultViewBehavior.h>
#include <pqObjectPickingBehavior.h>
#include <pqPersistentMainWindowStateBehavior.h>
#include <pqPipelineContextMenuBehavior.h>
#include <pqPluginActionGroupBehavior.h>
#include <pqPluginDockWidgetsBehavior.h>
#include <pqSpreadSheetVisibilityBehavior.h>
#include <pqUndoRedoBehavior.h>
#include <pqViewStreamingBehavior.h>
#include <pqCollaborationBehavior.h>
#include <pqVerifyRequiredPluginBehavior.h>
#include <pqPluginSettingsBehavior.h>
#include <pqFixPathsInStateFilesBehavior.h>
#include <pqApplyBehavior.h>

#include <pqPropertiesPanel.h>

int PVViewer_Behaviors::BehaviorLoadingLevel = 0;

PVViewer_Behaviors::PVViewer_Behaviors(QMainWindow * parent)
  : QObject(parent)
{
}

/**! Instanciate minimal ParaView behaviors needed when using an instance of PVViewer.
 * This method should be updated at each new version of ParaView with what is found in
 *    Qt/ApplicationComponents/pqParaViewBehaviors.cxx
 */
void PVViewer_Behaviors::instanciateMinimalBehaviors(QMainWindow * desk)
{
  if (BehaviorLoadingLevel < 1)
    {
      // Register ParaView interfaces.
      pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();

      // Register standard types of property widgets.
      pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
      // Register standard types of view-frame actions.
      pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));

      // Load plugins distributed with application.
      pqApplicationCore::instance()->loadDistributedPlugins();

      new pqDefaultViewBehavior(this);  // shows a 3D view as soon as a server connection is made
      new pqAlwaysConnectedBehavior(this);  // client always connected to a server
      new pqVerifyRequiredPluginBehavior(this);
      new pqPluginSettingsBehavior(this);
      new pqFixPathsInStateFilesBehavior(this);
      new pqCrashRecoveryBehavior(this);
      new pqCommandLineOptionsBehavior(this);

      BehaviorLoadingLevel = 1;
    }
}

/**! Instanciate usual ParaView behaviors.
 * This method should be updated at each new version of ParaView with what is found in
 *    Qt/ApplicationComponents/pqParaViewBehaviors.cxx
 */
void PVViewer_Behaviors::instanciateAllBehaviors(QMainWindow * desk)
{
  //    "new pqParaViewBehaviors(anApp->desktop(), this);"
  // -> (which loads all standard ParaView behaviors at once) has to be replaced in order to
  // exclude using of pqQtMessageHandlerBehaviour

  // Define application behaviors.
  if (BehaviorLoadingLevel < 1)
    instanciateMinimalBehaviors(desk);

  if (BehaviorLoadingLevel < 2)
    {
      //new pqQtMessageHandlerBehavior(this);   // THIS ONE TO EXCLUDE !! see comment above
      new pqDataTimeStepBehavior(this);
      new pqSpreadSheetVisibilityBehavior(this);
      new pqPipelineContextMenuBehavior(this);
      new pqUndoRedoBehavior(this);
      new pqAutoLoadPluginXMLBehavior(this);  // auto load plugins GUI stuff
      new pqPluginDockWidgetsBehavior(desk);
      new pqPluginActionGroupBehavior(desk);
      new pqPersistentMainWindowStateBehavior(desk);
      new pqObjectPickingBehavior(desk);
      new pqCollaborationBehavior(this);
      new pqViewStreamingBehavior(this);

      pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);
      foreach (pqPropertiesPanel* ppanel, desk->findChildren<pqPropertiesPanel*>())
      {
        applyBehavior->registerPanel(ppanel);
      }
      BehaviorLoadingLevel = 2;
    }
}
<commit_msg>Fix for the '0023265: [CEA 1809] In PARAVIS, th field vtkBlockColors is displayed with a continute scalar bar instead of a discrete one' issue.<commit_after>// Copyright (C) 2014-2016  CEA/DEN, EDF R&D, OPEN CASCADE
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// Author: Adrien Bruneton (CEA)

#include "PVViewer_Behaviors.h"

#include <QMainWindow>

#include <pqInterfaceTracker.h>
#include <pqApplicationCore.h>
#include <pqPluginManager.h>
#include <pqStandardPropertyWidgetInterface.h>
#include <pqStandardViewFrameActionsImplementation.h>
#include <pqPropertiesPanel.h>

#include <pqAlwaysConnectedBehavior.h>
#include <pqAutoLoadPluginXMLBehavior.h>
#include <pqCommandLineOptionsBehavior.h>
#include <pqCrashRecoveryBehavior.h>
#include <pqDataTimeStepBehavior.h>
#include <pqDefaultViewBehavior.h>
#include <pqObjectPickingBehavior.h>
#include <pqPersistentMainWindowStateBehavior.h>
#include <pqPipelineContextMenuBehavior.h>
#include <pqPluginActionGroupBehavior.h>
#include <pqPluginDockWidgetsBehavior.h>
#include <pqSpreadSheetVisibilityBehavior.h>
#include <pqUndoRedoBehavior.h>
#include <pqViewStreamingBehavior.h>
#include <pqCollaborationBehavior.h>
#include <pqStandardArrayColorMapsBehavior.h>
#include <pqVerifyRequiredPluginBehavior.h>
#include <pqPluginSettingsBehavior.h>
#include <pqFixPathsInStateFilesBehavior.h>
#include <pqApplyBehavior.h>

#include <pqPropertiesPanel.h>

int PVViewer_Behaviors::BehaviorLoadingLevel = 0;

PVViewer_Behaviors::PVViewer_Behaviors(QMainWindow * parent)
  : QObject(parent)
{
}

/**! Instanciate minimal ParaView behaviors needed when using an instance of PVViewer.
 * This method should be updated at each new version of ParaView with what is found in
 *    Qt/ApplicationComponents/pqParaViewBehaviors.cxx
 */
void PVViewer_Behaviors::instanciateMinimalBehaviors(QMainWindow * desk)
{
  if (BehaviorLoadingLevel < 1)
    {
      // Register ParaView interfaces.
      pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();

      // Register standard types of property widgets.
      pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
      // Register standard types of view-frame actions.
      pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));

      // Load plugins distributed with application.
      pqApplicationCore::instance()->loadDistributedPlugins();

      new pqDefaultViewBehavior(this);  // shows a 3D view as soon as a server connection is made
      new pqAlwaysConnectedBehavior(this);  // client always connected to a server
      new pqVerifyRequiredPluginBehavior(this);
      new pqPluginSettingsBehavior(this);
      new pqFixPathsInStateFilesBehavior(this);
      new pqCrashRecoveryBehavior(this);
      new pqCommandLineOptionsBehavior(this);

      BehaviorLoadingLevel = 1;
    }
}

/**! Instanciate usual ParaView behaviors.
 * This method should be updated at each new version of ParaView with what is found in
 *    Qt/ApplicationComponents/pqParaViewBehaviors.cxx
 */
void PVViewer_Behaviors::instanciateAllBehaviors(QMainWindow * desk)
{
  //    "new pqParaViewBehaviors(anApp->desktop(), this);"
  // -> (which loads all standard ParaView behaviors at once) has to be replaced in order to
  // exclude using of pqQtMessageHandlerBehaviour

  // Define application behaviors.
  if (BehaviorLoadingLevel < 1)
    instanciateMinimalBehaviors(desk);

  if (BehaviorLoadingLevel < 2)
    {
      //new pqQtMessageHandlerBehavior(this);   // THIS ONE TO EXCLUDE !! see comment above
      new pqDataTimeStepBehavior(this);
      new pqSpreadSheetVisibilityBehavior(this);
      new pqPipelineContextMenuBehavior(this);
      new pqUndoRedoBehavior(this);
      new pqAutoLoadPluginXMLBehavior(this);  // auto load plugins GUI stuff
      new pqPluginDockWidgetsBehavior(desk);
      new pqPluginActionGroupBehavior(desk);
      new pqPersistentMainWindowStateBehavior(desk);
      new pqObjectPickingBehavior(desk);
      new pqCollaborationBehavior(this);
      new pqViewStreamingBehavior(this);
      new pqStandardArrayColorMapsBehavior(this);

      pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);
      foreach (pqPropertiesPanel* ppanel, desk->findChildren<pqPropertiesPanel*>())
      {
        applyBehavior->registerPanel(ppanel);
      }
      BehaviorLoadingLevel = 2;
    }
}
<|endoftext|>


<commit_before>#include <Eigen/Core>
#include <Eigen/SVD>
#include <cstdio>
#include <cstring>
#include <string>
#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
#include <locale>
#include <codecvt>
#include <algorithm>
#include <vector>
#include <map>
#include <utility>

namespace corpus {
#include "lword.hh"
#include "corpus.hh"
#include "file2eigen.hh"
};
using namespace corpus;

void usage() {
  std::cout << "tools (lword|lbalance|corpus|toc|redig|stat|reconstruct|diff)" << std::endl;
}

const int szwindow(200);
const int szblock(8000);
const int Mbalance(40);
const double threshin(.1);
std::vector<std::string> delimiter;
std::vector<std::string> csvelim;
std::vector<std::string> csvdelim;

std::pair<std::string, std::string> loadbuf(const char* filename) {
  std::ifstream input;
  std::string   line;
  std::string   inbuf;
  input.open(filename);
  while(getline(input, line)) {
    inbuf += line + std::string("\n");
    if(input.eof() || input.bad())
      break;
  }
  input.close();

  std::string name0(filename);
  int slash = - 1;
  for(int j = 0; j < name0.size(); j ++)
    if(name0[j] == '/')
      slash = j;
  std::string name;
  slash ++;
  for(int j = slash; j < name0.size(); j ++)
    name += name0[j];

  return std::make_pair(name, inbuf);
}

int main(int argc, const char* argv[]) {
  if(argc < 3) {
    usage();
    return - 2;
  }
  delimiter.push_back(string("."));
  delimiter.push_back(string(","));
  delimiter.push_back(string("\'"));
  delimiter.push_back(string("\""));
  delimiter.push_back(string("。"));
  delimiter.push_back(string("、"));
  delimiter.push_back(string("「"));
  delimiter.push_back(string("」"));
  delimiter.push_back(string("("));
  delimiter.push_back(string(")"));
  csvelim.push_back(string(" "));
  csvelim.push_back(string("\t"));
  csvdelim.push_back(string(","));
  csvdelim.push_back(string("\r"));
  csvdelim.push_back(string("\n"));
        auto csv(cutText(loadbuf(argv[3]).second, csvelim, csvdelim, true));
  const auto input(loadbuf(argv[2]).second);
  if(std::strcmp(argv[1], "lword") == 0) {
    csv.insert(csv.end(), csvelim.begin(),  csvelim.end());
    csv.insert(csv.end(), csvdelim.begin(), csvdelim.end());
    const auto inputs(cutText(input, csv, delimiter));
    lword<char32_t, std::u32string> stat;
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
    for(int j = 0; j < inputs.size(); j ++) {
      std::u32string itrans(converter.from_bytes(inputs[j]));
      for(int i0 = 0; i0 <= input.size() / szblock; i0 ++)
        for(int i = 2; i < 20; i ++) {
          stat.init(60, i, i);
          auto words(stat.compute(itrans.substr(i0 * szblock, szblock)));
          for(auto itr = words.begin(); itr != words.end(); ++ itr)
            if(itr->str.size() > 2 && itr->count >= i) {
              std::cout << converter.to_bytes(itr->str) << ", ";
              std::cout << itr->count << std::endl;
            }
        }
    }
  } else if(std::strcmp(argv[1], "lbalance") == 0) {
    const auto cinput(cutText(input, csvelim, delimiter));
    const auto idxs(pseudoWordsBalance<double, std::string>(cinput, csv, Mbalance));
    std::cout << idxs.size() << "sets." << std::endl;
    for(int i = 0; i < idxs.size(); i ++)
      std::cout << cinput[idxs[i]] << std::endl;
  } /* else if(std::strcmp(argv[1], "corpus") == 0) {
    corpus<double, std::string> stat;
    for(int i = 0; i < input.size() / szwindow + 1; i ++) {
      stat.init(csv, 0, 120);
      const auto& words(stat.getWords());
      stat.compute(input.substr(i * szwindow, szwindow), delimiter);
      const auto& corpus(stat.getCorpus());
      std::cout << words  << std::endl;
      // std::cout << corpus << std::endl;
    }
  } */ else if(std::strcmp(argv[1], "toc") == 0 ||
            std::strcmp(argv[1], "lack") == 0) {
    std::vector<std::string> details;
    std::vector<std::string> tocs;
    std::vector<std::string> detailwords;
    std::vector<std::string> tocwords;
    bool toc(false);
    for(int iidx = 4; iidx < argc; iidx ++) {
      if(std::string(argv[iidx]) == std::string("-toc")) {
        toc = true;
        continue;
      }
      const auto work(loadbuf(argv[iidx]));
      if(toc) {
        tocs.push_back(work.second);
        tocwords.push_back(work.first);
      } else {
        details.push_back(work.second);
        detailwords.push_back(work.first);
      }
    }
    csv.insert(csv.end(), tocwords.begin(),    tocwords.end());
    csv.insert(csv.end(), detailwords.begin(), detailwords.end());
    std::sort(csv.begin(), csv.end());
    csv.erase(std::unique(csv.begin(), csv.end()), csv.end());
    std::cout << std::string("<link rel=\"stylesheet\" type=\"text/css\" href=\"../../style.css\">") << std::endl;
    std::cout << std::string("");
    std::cout << preparedTOC<double, std::string>(input, csv, detailwords, details, tocwords, tocs, delimiter, szwindow, 8, threshin, .125, std::strcmp(argv[1], "lack") == 0) << std::string("
") << std::endl;
    std::cout << std::string("");
  } else if(std::strcmp(argv[1], "reconstruct") == 0) {
    corpus<double, std::string> stat;
    stat.compute(input, delimiter, csv);
    corpushl<double, std::string> recons(stat);
    std::cout << recons.serialize();
  } else if(std::strcmp(argv[1], "redig") == 0) {
    std::vector<double> emph;
    emph.push_back(4.);
    emph.push_back(1.);
    emph.push_back(.25);
    for(int ei = 0; ei < emph.size(); ei ++) {
      for(int i = 0; i < input.size() / szwindow + 1; i ++) {
        corpus<double, std::string> stat;
        stat.compute(input.substr(i * szwindow, szwindow), delimiter, csv);
        corpushl<double, std::string> recons(stat);
        recons.reDig(emph[ei]);
        std::cout << recons.serialize() << std::endl;
      }
      std::cout << std::endl << std::endl;
    }
  } else if(std::strcmp(argv[1], "diff") == 0) {
    std::vector<std::string> details, details2;
    std::vector<std::string> detailwords, detailwords2;
    bool second(false);
    for(int iidx = 4; iidx < argc; iidx ++) {
      if(std::string(argv[iidx]) == std::string("-dict")) {
        second = false;
        continue;
      } else if(std::string(argv[iidx]) == std::string("-dict2")) {
        second = true;
        continue;
      }
      const auto work(loadbuf(argv[iidx]));
      if(second) {
        details2.push_back(work.second);
        detailwords2.push_back(work.first);
      } else {
        details.push_back(work.second);
        detailwords.push_back(work.first);
      }
    }
    csv.insert(csv.end(), detailwords.begin(),  detailwords.end());
    csv.insert(csv.end(), detailwords2.begin(), detailwords2.end());
    std::sort(csv.begin(), csv.end());
    csv.erase(std::unique(csv.begin(), csv.end()), csv.end());
    std::cout << std::string("<link rel=\"stylesheet\" type=\"text/css\" href=\"../../style.css\">") << std::endl;
    std::cout << std::string("");
    std::cout << diff<double, std::string>(input, csv, details, detailwords, details2, detailwords2, delimiter, szwindow, threshin) << std::string("
") << std::endl;
    std::cout << "" << std::endl;
  } else if(std::strcmp(argv[1], "stat") == 0 ||
            std::strcmp(argv[1], "findroot") == 0) {
    std::vector<std::string> rdetails;
    std::vector<std::string> rdetailwords;
    for(int iidx = 4; iidx < argc; iidx ++) {
      const auto work(loadbuf(argv[iidx]));
      rdetails.push_back(work.second);
      rdetailwords.push_back(work.first);
    }
    csv.insert(csv.end(), rdetailwords.begin(), rdetailwords.end());
    std::sort(csv.begin(), csv.end());
    csv.erase(std::unique(csv.begin(), csv.end()), csv.end());
    std::cout << std::string("<link rel=\"stylesheet\" type=\"text/css\" href=\"../../style.css\">") << std::endl;
    std::cout << std::string("");
    std::cout << optimizeTOC<double, std::string>(input, csv, rdetails, rdetailwords, delimiter, szwindow, 8, threshin, 1., std::strcmp(argv[1], "findroot") == 0) << std::string("
") << std::endl;
    std::cout << std::string("");
  } else if(std::strcmp(argv[1], "prep") == 0) {
    std::vector<std::string> buf;
    corpus<double, std::string> stat;
    for(int i = 0; i < input.size() / szwindow + 1; i ++) {
      stat.compute(input.substr(i * szwindow, szwindow), delimiter, csv);
      const auto work(corpushl<double,std::string>(stat).reverseLink());
      buf.insert(buf.end(), work.begin(), work.end());
    }
    std::sort(buf.begin(), buf.end());
    buf.erase(std::unique(buf.begin(), buf.end()), buf.end());
    for(int i = 0; i < buf.size(); i ++)
      std::cout << buf[i] << std::endl;
  } else if(std::strcmp(argv[1], "optdict") == 0)
    assert(0 && "group dicts: not implemented around NOT word tables.");
  else if(std::strcmp(argv[1], "conflict") == 0)
    assert(0 && "conflict : not implemented around NOT word tables.");
  else if(std::strcmp(argv[1], "negate") == 0)
    assert(0 && "negate: not implemented around NOT word tables.");
  else if(std::strcmp(argv[1], "consistency") == 0)
    assert(0 && "consistancy : Logics check so far...");
  else if(std::strcmp(argv[1], "logiccheck") == 0)
    assert(0 && "logic check : Logics check so far...");
  else {
    usage();
    return - 2;
  }
  return 0;
}

<commit_msg>Delete test.cc<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2014 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: test.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hjm211324@gmail.com
 *  Date: Dec. 29, 2014
 *  Time: 11:10:09
 *  Description:
 *****************************************************************************/
#include <iostream>

int main() {
    std::cout << "Hello world!" << std::endl;

}

<commit_msg>--allow-empty_message<commit_after>/******************************************************************************
 *  Copyright (c) 2014 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: test.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hjm211324@gmail.com
 *  Date: Dec. 29, 2014
 *  Time: 11:10:09
 *  Description:
 *****************************************************************************/
#include <iostream>

int main() {
    std::cout << "Hello world!" << std::endl;

}

<|endoftext|>