/* Copyright (C) 1998-2002 The gtkmm Development Team
 *
 * 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, see <https://www.gnu.org/licenses/>.
 */

#include <glibmm/vectorutils.h>

#include <gtkmm/adjustment.h>
#include <gtkmm/scrolledwindow.h>
#include <gtk/gtk.h>


namespace
{

// Marks a widget that has been automatically created and added by gtk_container_add().
// The only reason we must use this GQuark or a similar trick, is that we want
// to restore the state of a managed removed object.
// gtk_container_remove() does not do that.
GQuark quark_auto_added_widget = g_quark_from_static_string("gtkmm_Container::auto_added_widget");

static void container_foreach_callback(GtkWidget* widget_gobj, void* data)
{
  try
  {
    const auto & slot = *static_cast<Gtk::Container::ForeachSlot*>(data);
    const auto widget = Glib::wrap(widget_gobj);

    g_return_if_fail(widget != nullptr);

    slot(*widget);
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
}


//Copy of generated callback:
static void Container_signal_remove_callback_normal(GtkContainer* self, GtkWidget* p0,void* data)
{
  using namespace Gtk;
  typedef sigc::slot< void,Widget* > SlotType;

  // Do not try to call a signal on a disassociated wrapper.
  if(Glib::ObjectBase::_get_current_wrapper((GObject*) self))
  {
    try
    {
      if(sigc::slot_base *const slot = Glib::SignalProxyNormal::data_to_slot(data))
        (*static_cast<SlotType*>(slot))(Glib::wrap(p0)
);
    }
    catch(...)
    {
      Glib::exception_handlers_invoke();
    }
  }
}

static void Container_signal_remove_callback(GtkContainer* self, GtkWidget* p0, void* data)
{
  //GTKMM_LIFECYCLE

#ifdef GLIBMM_DEBUG_REFCOUNTING
  g_warning("Container_signal_remove_callback()");
#endif

  //Don't call wrap() on a GTK+ instance whose gtkmm instance has been deleted - just call the original C callback.
  const bool gtkmm_child_already_deleted = Glib::_gobject_cppinstance_already_deleted((GObject*)p0);

  if(!gtkmm_child_already_deleted)
  {
    //Call the regular, generated callback:
    Container_signal_remove_callback_normal(self, p0, data);
  }
  else
  {
    //Do nothing.
  }
}

} // anonymous namespace


namespace Gtk
{

//Copy of generated callback:
void Container_Class::remove_callback_normal(GtkContainer* self, GtkWidget* p0)
{
  const auto obj = dynamic_cast<CppObjectType*>(
      Glib::ObjectBase::_get_current_wrapper((GObject*)self));

  // Non-gtkmmproc-generated custom classes implicitly call the default
  // Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
  // generated classes can use this optimisation, which avoids the unnecessary
  // parameter conversions if there is no possibility of the virtual function
  // being overridden:
  if(obj && obj->is_derived_())
  {
    try // Trap C++ exceptions which would normally be lost because this is a C callback.
    {
      // Call the virtual member method, which derived classes might override.
      obj->on_remove(Glib::wrap(p0)
);
    }
    catch(...)
    {
      Glib::exception_handlers_invoke();
    }
  }
  else
  {
    const auto base = static_cast<BaseClassType*>(
        g_type_class_peek_parent(G_OBJECT_GET_CLASS(self)) // Get the parent class of the object class (The original underlying C class).
    );

    // Call the original underlying C function:
    if(base && base->remove)
      (*base->remove)(self, p0);
  }
}

//Custom hand-coded callback:
void Container_Class::remove_callback(GtkContainer* self, GtkWidget* p0)
{
  //GTKMM_LIFECYCLE

#ifdef GLIBMM_DEBUG_REFCOUNTING
  g_warning("Container_Class::remove_callback_custom() C self=%p: C child=%p\n", (void*)self, (void*)p0);
  g_warning("gtypename self: %s\n, gtypename child: %s", G_OBJECT_TYPE_NAME(G_OBJECT(self)), G_OBJECT_TYPE_NAME(G_OBJECT(p0)));
#endif

  //Don't call wrap() on a GTK+ instance whose gtkmm instance has been deleted - just call the original C callback.
  const bool gtkmm_child_already_deleted = Glib::_gobject_cppinstance_already_deleted((GObject*)p0);

  if(!gtkmm_child_already_deleted)
  {
    //Call the regular, generated callback:
    Container_Class::remove_callback_normal(self, p0);
  }
  else
  {
    BaseClassType *const base =
      static_cast<BaseClassType*>(g_type_class_peek_parent(G_OBJECT_GET_CLASS(self)));

    // Do not try to call the default implementation of the virtual function
    // GtkContainerClass::remove(), because it unhelpfully informs us that
    // it isn't implemented.  This leaves us with no generic means to check
    // whether it is implemented.
    if(base && G_TYPE_FROM_CLASS(base) != GTK_TYPE_CONTAINER && base->remove)
      (*base->remove)(self, p0);
  }
}

void Container::foreach(const Container::ForeachSlot& slot)
{
  ForeachSlot slot_copy (slot);
  gtk_container_foreach(gobj(), &container_foreach_callback, &slot_copy);
}

void Container::forall(const Container::ForeachSlot& slot)
{
  ForeachSlot slot_copy (slot);
  gtk_container_forall(gobj(), &container_foreach_callback, &slot_copy);
}

// Why not let both add() and remove() be virtual, and override them in ScrolledWindow?
// Because a virtual add() has an unwanted side-effect in Gtk::Stack.
// See https://bugzilla.gnome.org/show_bug.cgi?id=724732
// And a virtual remove() can be problematic because ScrolledWindow and other
// subclasses of Bin have a remove() overload with no parameter.

void Container::add(Widget& widget)
{
  auto scrolled_window = dynamic_cast<ScrolledWindow*>(this);
  if (scrolled_window)
  {
    auto old_child = gtk_bin_get_child(scrolled_window->Bin::gobj()); // Normally nullptr
    gtk_container_add(gobj(), widget.gobj());
    auto child = gtk_bin_get_child(scrolled_window->Bin::gobj());
    if (child && child != old_child)
    {
      // If the child is not the inserted widget, gtk_scrolled_window_add() has
      // created and inserted a GtkViewport. Mark this GtkViewport as automatically
      // added. Container::remove() needs this information.
      const gpointer qdata_value = (child != widget.gobj()) ? child : nullptr;
      g_object_set_qdata(G_OBJECT(child), quark_auto_added_widget, qdata_value);
    }
  }
  else
    gtk_container_add(gobj(), widget.gobj());
}

#ifndef GTKMM_DISABLE_DEPRECATED
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
bool Container::has_focus_chain() const
{
  return gtk_container_get_focus_chain(const_cast<GtkContainer*>(gobj()), nullptr);
}

std::vector<Widget*> Container::get_focus_chain()
{
  GList* list = nullptr;
  gtk_container_get_focus_chain(gobj(), &list);

  return Glib::ListHandler<Widget*>::list_to_vector(list, Glib::OWNERSHIP_SHALLOW);
}

std::vector<const Widget*> Container::get_focus_chain() const
{
  GList* list = nullptr;
  gtk_container_get_focus_chain(const_cast<GtkContainer*>(gobj()), &list);

  return Glib::ListHandler<const Widget*>::list_to_vector(list, Glib::OWNERSHIP_SHALLOW);
}
G_GNUC_END_IGNORE_DEPRECATIONS
#endif // GTKMM_DISABLE_DEPRECATED

void Container::show_all_children(bool recursive)
{
  // Plain C version if this turns out to be performance-critical:
  //GtkCallback callback = (GtkCallback) ((recursive) ? &gtk_widget_show_all : &gtk_widget_show);
  //gtk_container_foreach(gobj(), callback, 0);

  // This could also be done with get_children() and an explicit loop,
  // if any problems should arise.  In gtkmm-1.2, foreach() is known to
  // cause segfaults eventually, but it seems to work now.

  foreach(sigc::mem_fun((recursive) ? &Widget::show_all : &Widget::show));
}

void Container::remove(Widget& widget)
{
  auto child_to_float = &widget;
  if (g_object_get_qdata(widget.Glib::Object::gobj(), quark_auto_added_widget))
  {
    // If widget was created by gtk_scrolled_window_add(),
    // don't restore the floating state of that widget. Instead, restore the
    // state of that widget's child, which was added by add().
    auto scrolled_window = dynamic_cast<ScrolledWindow*>(this);
    if (scrolled_window)
    {
      auto bin = dynamic_cast<Bin*>(&widget);
      if (bin)
        child_to_float = bin->get_child();
    }
  }

  // If this is a managed widget, then do an extra ref so that it will not be
  // destroyed when it is removed, and restore the floating state of the ref.
  // This should leave it in the same state as when it was instantiated,
  // before being added to the container.
  if (child_to_float && child_to_float->is_managed_())
  {
    child_to_float->reference();
    g_object_force_floating(child_to_float->Glib::Object::gobj());
  }

  // gtk_container_remove() removes what gtk_container_add() added, even if
  // gtk_container_add() added an extra GtkViewport in a GtkScrolledWindow.
  // See https://bugzilla.gnome.org/show_bug.cgi?id=710471
  gtk_container_remove(gobj(), widget.gobj());
}

} // namespace Gtk
