//
// C++ Interface: qgarbagecollector
//
// Description: Garbage Collector class for Qt4
//
// Copyright: (c) AMD, 2005
// Author: Konrad Rosenbaum <konrad.rosenbaum@amd.com>
//
// with permission from AMD refactored by
// (c) Konrad Rosenbaum, 2005
// published under the GNU GPL, v.2

#ifndef MISC_QGARBAGECOLLECTOR_H
#define MISC_QGARBAGECOLLECTOR_H

#include <QtCore/QObject>
#include <QtCore/QList>

/**counts references from objects (supervisors) using other objects (children)

The garbage collector deletes all its children and itself after all supervisors are gone
or removed. It also deletes itself after all children are gone - supervisors should listen
to the destroyed signal to catch this case.*/
class QGarbageCollector:public QObject
{
	Q_OBJECT
	public:
		/**instantiate the GC with one supervised child object and one supervisor*/
		QGarbageCollector(QObject*child,QObject*supervisor);
		/**deletes the collector and all its children, this should normally 
		never be called by the user, since the collector deletes itself*/
		~QGarbageCollector();
		
	public slots:
		/**add a child object*/
		void addChild(QObject*);
		/**remove a child object, delete the collector when the last one was removed*/
		void removeChild(QObject*);
		/**add a supervisor*/
		void addSupervisor(QObject*);
		/**remove a supervisor, delete the children and the collector when the last one was removed*/
		void removeSupervisor(QObject*);
		
		/**check whether this is a child*/
		bool isChild(QObject*);
		/**check whether this is a supervisor*/
		bool isSupervisor(QObject*);
		
	signals:
		/**emit this signal before children are deleted, this signal can be used to "rescue" the children
		by adding a valid supervisor in a directly connected slot, using queued slots will most probably lead
		to a segmentation fault*/
		void aboutToDelete();
		
	private:
		/**stores the children this GC object cares about*/
		QList<QObject*>children;
		/**stores the supervisors of this GC object*/
		QList<QObject*>supervisors;
};

#endif
