/*
 * Copyright (c) 2006-2008 MiniMe. Code released under The MIT/X Window System
 * License. Full license text can be found in license.txt
 */
package minime.core;

import java.util.Vector;

import minime.ui.SoftBar;

/*
 * FocusManager is responsible for managing the list of Component that receive the focus.
 * 
 * A component with the focus will be added to the event list and will receive events 
 * dispatched by EventManager.
 * 
 */
public class FocusManager
{
	private static FocusManager inst ;
	
	public static FocusManager getInstance()
	{
		if (inst==null)
			inst = new FocusManager() ;
		return inst ;
	}
	
	Vector focussed ;
	private FocusManager()
	{
		focussed = new Vector() ;
	}

	/**
	 * Add a component to the list of focused object.   The component will be added to 
	 * the event list and will receive events dispatched by EventDispacher
	 * 
	 * @param c, component to receive the focus
	 */
	public void setFocus(Component c)
	{
		// if focus is set on PopupComponent, we first un-focus all other component
		if (c instanceof PopupComponent)
			unFocusAll() ;
		
		// set the focus to the component, and add it to the list
		c.setFocused(true) ;
		focussed.addElement(c) ;
	}
	
	/**
	 * Remove a component from the list of focused object.   The component will be 
	 * removed from the event list and will no longer receive events dispatched by 
	 * EventDispacher.
	 * 
	 * @param c, component to be removed from the focus
	 */
	public void removeFocus(Component c)
	{
		// set the focus to the component, and remove it from the list
		c.setFocused(false) ;
		focussed.removeElement(c) ;

		// if focus was on a PopupComponent, we re-focus all other component
		if (c instanceof PopupComponent)
			reFocusAll() ;
	}
	
	public void unFocusAll()
	{
		int size = focussed.size() ;
		for(int i=0;i<size;i++)
		{
			Component c = (Component)focussed.elementAt(i) ;
			// don't touch SoftBar
			if (c instanceof SoftBar)
				continue ;
			c.setFocused(false) ;
		}
	}

	public void reFocusAll()
	{
		int size = focussed.size() ;
		for(int i=0;i<size;i++)
		{
			Component c = (Component)focussed.elementAt(i) ;
			// don't touch SoftBar
			if (c instanceof SoftBar)
				continue ;
			c.setFocused(true) ;
		}
	}
	
	public void clearAll()
	{
		focussed.removeAllElements() ;
	}
}
