nrelm 0.1.0

An idiomatic GUI library inspired by Elm and based on gtk3-rs
use crate::ContainerChild;
use gtk::prelude::*;

/// Extension trait that adds a typed `remove` operation to containers.
pub trait RelmRemoveExt: ContainerChild {
    /// Removes a child widget from the container.
    fn container_remove(&self, child: &impl AsRef<Self::Child>);
}

macro_rules! remove_impl {
    ($($type:ty),+) => {
        $(
            impl RelmRemoveExt for $type {
                fn container_remove(&self, widget: &impl AsRef<Self::Child>) {
                    let self_ref: &gtk::Container = self.upcast_ref();
                    // Only remove a widget that is actually a child of this
                    // container; removing a widget whose parent is elsewhere
                    // (for example a loading widget already replaced by the
                    // view) would print a GTK warning.
                    if widget.as_ref().parent().as_ref() == Some(self_ref.upcast_ref()) {
                        self_ref.remove(widget.as_ref());
                    }
                }
            }
        )+
    }
}

remove_impl! {
    gtk::Box,
    gtk::Fixed,
    gtk::Grid,
    gtk::ActionBar,
    gtk::Stack,
    gtk::HeaderBar,
    gtk::ListBox,
    gtk::FlowBox,
    gtk::InfoBar,
    gtk::Window,
    gtk::ApplicationWindow
}

/// Extension trait that removes all children of a container at once.
pub trait RelmRemoveAllExt {
    /// Removes all children of the container.
    fn remove_all(&self);
}

macro_rules! remove_all_impl {
    ($($type:ty),+) => {
        $(
            impl RelmRemoveAllExt for $type {
                fn remove_all(&self) {
                    let self_ref: &gtk::Container = self.upcast_ref();
                    let children: Vec<gtk::Widget> = self_ref.children();
                    for child in children {
                        self_ref.remove(&child);
                    }
                }
            }
        )+
    }
}

remove_all_impl! {
    gtk::Box,
    gtk::FlowBox,
    gtk::Stack,
    gtk::Grid
}

impl RelmRemoveAllExt for gtk::ListBox {
    fn remove_all(&self) {
        let self_ref: &gtk::Container = self.upcast_ref();
        let children: Vec<gtk::Widget> = self_ref.children();
        for child in children {
            self_ref.remove(&child);
        }
    }
}