1/*
2 * This file is part of gitg
3 *
4 * Copyright (C) 2012 - Jesse van den Kieboom
5 *
6 * gitg is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * gitg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with gitg. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20namespace Gitg
21{
22	public class WhenMapped
23	{
24		public delegate void OnMapped();
25
26		private unowned Gtk.Widget? d_widget;
27		private unowned Object? d_lifetime;
28		private ulong d_sid;
29
30		public WhenMapped(Gtk.Widget widget)
31		{
32			d_sid = 0;
33			d_widget = widget;
34
35			d_widget.weak_ref(weak_notify);
36		}
37
38		private void weak_notify(Object o)
39		{
40			d_widget = null;
41			d_sid = 0;
42
43			if (d_lifetime != null)
44			{
45				d_lifetime.weak_unref(lifetime_weak_notify);
46				d_lifetime = null;
47			}
48		}
49
50		~WhenMapped()
51		{
52			if (d_widget != null)
53			{
54				if (d_sid != 0 && SignalHandler.is_connected(d_widget, d_sid))
55				{
56					d_widget.disconnect(d_sid);
57				}
58
59				d_widget.weak_unref(weak_notify);
60				d_widget = null;
61			}
62
63			if (d_lifetime != null)
64			{
65				d_lifetime.weak_unref(lifetime_weak_notify);
66				d_lifetime = null;
67			}
68		}
69
70		private void lifetime_weak_notify(Object o)
71		{
72			if (d_sid != 0 && d_widget != null)
73			{
74				d_widget.disconnect(d_sid);
75				d_sid = 0;
76			}
77
78			d_lifetime = null;
79		}
80
81		public void update(owned OnMapped mapped, Object? lifetime = null)
82		{
83			if (d_widget == null)
84			{
85				return;
86			}
87
88			if (d_sid != 0)
89			{
90				d_widget.disconnect(d_sid);
91				d_sid = 0;
92			}
93
94			if (d_lifetime != null)
95			{
96				d_lifetime.weak_unref(lifetime_weak_notify);
97				d_lifetime = null;
98			}
99
100			if (d_widget.get_mapped())
101			{
102				mapped();
103			}
104			else
105			{
106				d_sid = d_widget.map.connect(() => {
107					d_widget.disconnect(d_sid);
108					d_sid = 0;
109
110					if (d_lifetime != null)
111					{
112						d_lifetime.weak_unref(lifetime_weak_notify);
113						d_lifetime = null;
114					}
115
116					mapped();
117				});
118
119				d_lifetime = lifetime;
120
121				if (d_lifetime != null)
122				{
123					d_lifetime.weak_ref(lifetime_weak_notify);
124				}
125			}
126		}
127	}
128}
129
130// ex:ts=4 noet
131