/*
 * Copyright 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <gtkmm/scrollbar.h>
#include <gtkmm/viewport.h>
#include <gtkmm/adjustment.h>
#include <gtk/gtk.h>


namespace Gtk
{

void ScrolledWindow::add(Gtk::Widget& widget)
{
  //TODO: Remove this method overload completely when we can break ABI.
  //We used to do what GTK+ now does for us:
  //See https://bugzilla.gnome.org/show_bug.cgi?id=693015
  Bin::add(widget);
}

void ScrolledWindow::remove_with_viewport()
{
  GtkWidget* child = gtk_bin_get_child(Bin::gobj());
  if (child)
  {
    if (GTK_IS_VIEWPORT(child))
    {
      // Remove the Viewport's child, if any, from the Viewport.
      GtkWidget* grandchild = gtk_bin_get_child(GTK_BIN(child)); // A GtkViewport is a GtkBin
      if (grandchild)
      {
        Gtk::Widget* cppGrandchild = Glib::wrap(grandchild);

        //If the grandchild 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 first container.
        if (cppGrandchild->is_managed_())
        {
          cppGrandchild->reference();
          g_object_force_floating(static_cast<Glib::Object*>(cppGrandchild)->gobj());
        }

        gtk_container_remove(GTK_CONTAINER(child), grandchild);
      }

      // Remove the Viewport.
      // Don't do an extra ref on the child (the Viewport). If it's added
      // by ScrolledWindow::add() or created as a managed widget,
      // let it be deleted, when it's removed and the ref count reaches 0.
      gtk_container_remove(Container::gobj(), child);
    }
    else
    {
      // The child is not a Viewport. Just remove it.
      Bin::remove();
    }
  }
}

} //namespace Gtk
