All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nu.zoom.swing.desktop.component.stringmenu.impl.StringMenuImpl Maven / Gradle / Ivy

Go to download

A zoom.nu desktop plugin that makes the stock java filechooser remember where it was the last time.

The newest version!
/*
 * Copyright (C) 2006 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.swing.desktop.component.stringmenu.impl;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.Icon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;

import nu.zoom.swing.desktop.Workbench;
import nu.zoom.swing.desktop.WorkbenchListener;
import nu.zoom.swing.desktop.common.BackendException;
import nu.zoom.swing.desktop.common.action.WorkbenchMessageAction;
import nu.zoom.swing.desktop.component.stringmenu.StringMenu;
import nu.zoom.swing.desktop.component.stringmenu.StringMenuItem;
import nu.zoom.swing.desktop.component.stringmenu.StringMenuListener;
import nu.zoom.swing.desktop.preferences.InvalidDataTypeException;
import nu.zoom.swing.desktop.preferences.Preferences;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ops4j.gaderian.Messages;

public class StringMenuImpl & Serializable> implements StringMenu, WorkbenchListener  
{
	private Log log = LogFactory.getLog(getClass());

	private HashMap, JMenuItem> itemStringToJMenuItem = new HashMap, JMenuItem>();

	private ArrayList> listeners = new ArrayList>();

	private ArrayList> itemStrings = new ArrayList>();

	private JMenu menu = null;

	private Preferences preferences;

	private String preferencesKey;

	private String menuName;

	private Icon icon = null;

	private Messages messages;

	/**
	 * Instantiate a new menu
	 * 
	 * @param preferences
	 * @param workbench
	 * @param preferencesKey
	 * @param menuName
	 * @param icon
	 */
	StringMenuImpl(Preferences preferences, Workbench workbench,
			Messages messages, String preferencesKey, String menuName, Icon icon) {
		this.preferences = preferences;
		this.preferencesKey = preferencesKey;
		this.menuName = menuName;
		this.icon = icon;
		this.messages = messages;
		log.trace("New String menu is registering as workbench listener");
		workbench.addWorkBenchListener(this);
	}

	/**
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#addListener(nu.zoom.swing.desktop.component.stringmenu.StringMenuListener)
	 */
	public synchronized void addListener(StringMenuListener listener) {
		if (listener == null) {
			throw new IllegalArgumentException("Listener may not be null");
		}
		log.trace("Registering a string menu listener: " + listener);
		listeners.add(listener);
	}

	/**
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#removeListener(nu.zoom.swing.desktop.component.stringmenu.StringMenuListener)
	 */
	public synchronized void removeListener(StringMenuListener listener) {
		log.trace("Removing a string menu listener: " + listener);
		listeners.remove(listener);
	}

	/**
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#getJMenu()
	 */
	public synchronized JMenu getJMenu() {
		if (menu == null) {
			restoreMenu();
			if (menu == null) {
				log.trace("Menu not restored from preferences, creating new.");
				createJMenu();
			}
		}
		return menu;
	}

	/**
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#addItem(java.lang.String)
	 */
	public synchronized void addItem(final StringMenuItem menuItem) {
		if (menuItem == null) {
			log.fatal("Item may not be null");
			throw new IllegalArgumentException("Item may not be null");
		}
		if (!EventQueue.isDispatchThread()) {
			log.fatal("Must be called on the EventQueue dispatch thread");
			throw new IllegalStateException(
					"Must be called on the EventQueue dispatch thread");
		}
		if (!itemStringToJMenuItem.containsKey(menuItem)) {
			log.trace("Adding item to menu");
			addItemInternal(menuItem);
		}
	}

	/**
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#removeItem(java.lang.String)
	 */
	public synchronized void removeItem(StringMenuItem menuItem) {
		if (!EventQueue.isDispatchThread()) {
			log.fatal("Must be called on the EventQueue dispatch thread");
			throw new IllegalStateException(
					"Must be called on the EventQueue dispatch thread");
		}

		if (menuItem != null) {
			log.trace("Looking for menu item to remove");
			final JMenuItem cachedJMenuItem = itemStringToJMenuItem
					.get(menuItem);
			log.trace("Cache returned item: " + cachedJMenuItem);
			if (cachedJMenuItem != null) {
				log.trace("Removing item from JMenu");
				getJMenu().remove(cachedJMenuItem);

				log.trace("Removing item from key list");
				itemStrings.remove(menuItem);

				log.trace("Removing item from cache");
				itemStringToJMenuItem.remove(menuItem);

				log.trace("Removing ALL action listeners from JMenuItem");
				ActionListener[] listeners = cachedJMenuItem
						.getActionListeners();
				for (ActionListener listener : listeners) {
					cachedJMenuItem.removeActionListener(listener);
				}
			}
		}
	}

	private synchronized void fireMenuItemSelected(
			final StringMenuItem menuItem) {
		for (final StringMenuListener listener : listeners) {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					log.trace("Informing listener:" + listener + " that item: "
							+ menuItem + " was selected");
					listener.menuItemSelected(menuItem);
				}
			});
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see nu.zoom.swing.desktop.WorkbenchListener#close()
	 */
	public synchronized void close() {
		try {
			log.trace("Trying to serialize key list to preferences");
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream outs = new ObjectOutputStream(baos);
			outs.writeObject(itemStrings);
			outs.flush();

			preferences.setBytes(preferencesKey, baos.toByteArray());
		} catch (BackendException e) {
			log.warn(e);
		} catch (IOException e) {
			log.warn(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see nu.zoom.swing.desktop.WorkbenchListener#start()
	 */
	public void start() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see nu.zoom.swing.desktop.WorkbenchListener#start()
	 */
	@SuppressWarnings("unchecked")
	private synchronized void restoreMenu() {
		try {
			log.trace("Trying to deserialize key list from preferences");
			byte[] data = preferences.getBytes(preferencesKey);
			if (data != null) {
				ObjectInputStream ins = new ObjectInputStream(
						new ByteArrayInputStream(data));

				// Generates unchecked warnings but we know
				ArrayList> restoredKeys = (ArrayList>) ins
						.readObject();
				createJMenu();

				for (final StringMenuItem item : restoredKeys) {
					addItemInternal(item);
				}
			}
		} catch (InvalidDataTypeException e) {
			log.warn(e);
		} catch (BackendException e) {
			log.warn(e);
		} catch (IOException e) {
			log.warn(e);
		} catch (ClassNotFoundException e) {
			log.warn(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#clear()
	 */
	@SuppressWarnings("unchecked")
	public void clear() {
		ArrayList> keyClone = (ArrayList>) itemStrings
				.clone();
		for (StringMenuItem item : keyClone) {
			removeItem(item);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see nu.zoom.swing.desktop.component.stringmenu.StringMenu#getNumberOfItems()
	 */
	public synchronized int getNumberOfItems() {
		int numKeys = itemStrings.size();
		log.trace("Getting the number of items on the menu: " + numKeys);
		return numKeys;
	}

	private void createJMenu() {
		log.trace("Creating new JMenu with name: " + menuName);
		menu = new JMenu(menuName);
		if (icon != null) {
			log.trace("Setting menu icon to " + icon);
			menu.setIcon(icon);
		}
		menu.add(new ClearAction(messages));
		menu.add(new JSeparator(JSeparator.HORIZONTAL));
	}

	private synchronized void addItemInternal(
			final StringMenuItem stringMenuItem) {
		log.trace("Creating JMenu item");
		JMenuItem jMenuItem = createJMenuItem(stringMenuItem);

		log.trace("Adding cache entry for item: " + stringMenuItem);
		itemStringToJMenuItem.put(stringMenuItem, jMenuItem);

		log.trace("Adding key to key list");
		itemStrings.add(stringMenuItem);

		log.trace("Addin JMenuItem: " + jMenuItem + " to JMenu");
		getJMenu().insert(jMenuItem, 2);
	}

	private JMenuItem createJMenuItem(final StringMenuItem stringMenuItem) {
		JMenuItem jMenuItem = new JMenuItem(stringMenuItem
				.getPresentationName());
		jMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				fireMenuItemSelected(stringMenuItem);
			}
		});
		return jMenuItem;
	}

	@SuppressWarnings("serial")
	class ClearAction extends WorkbenchMessageAction {

		public ClearAction(Messages messages) {
			super(messages);
			setNameFromMessages("stringmenu.clear");
			setToolTipFromMessages("stringmenu.clear.tt");
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			clear();
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy