001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2012 GRANITE DATA SERVICES S.A.S.
004
005 This file is part of Granite Data Services.
006
007 Granite Data Services is free software; you can redistribute it and/or modify
008 it under the terms of the GNU Library General Public License as published by
009 the Free Software Foundation; either version 2 of the License, or (at your
010 option) any later version.
011
012 Granite Data Services is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 for more details.
016
017 You should have received a copy of the GNU Library General Public License
018 along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020
021 package org.granite.client.util.javafx;
022
023 import java.lang.reflect.Array;
024 import java.util.Arrays;
025
026 import javafx.beans.WeakListener;
027
028
029 public class ListenerUtil {
030
031 public static <T> T[] add(Class<?> listenerInterface, T[] listeners, T listener) {
032 if (listeners == null) {
033 @SuppressWarnings("unchecked")
034 T[] newListeners = (T[])Array.newInstance(listenerInterface, 1);
035 newListeners[0] = listener;
036 return newListeners;
037 }
038 else {
039 for (T l : listeners) {
040 if (listener.equals(l))
041 return listeners;
042 }
043 }
044
045 int newSize = 0;
046 int length = listeners.length;
047 for (int i = 0; i < length; i++) {
048 final T l = listeners[i];
049 if (l instanceof WeakListener && ((WeakListener)l).wasGarbageCollected()) {
050 if (i < length-1)
051 System.arraycopy(listeners, i+1, listeners, i, length-i-1);
052 length--;
053 i--;
054 }
055 else
056 newSize++;
057 }
058 T[] newListeners = Arrays.copyOf(listeners, newSize+1);
059 newListeners[newSize] = listener;
060 return newListeners;
061 }
062
063 public static <T> T[] remove(Class<?> listenerClass, T[] listeners, T listener) {
064 if (listeners == null)
065 return null;
066
067 int index = -1;
068 for (int i = 0; i < listeners.length; i++) {
069 if (listeners[i].equals(listener)) {
070 index = i;
071 break;
072 }
073 }
074 if (index < 0)
075 return listeners;
076
077 if (listeners.length == 1)
078 return null;
079
080 int newSize = 0;
081 int length = listeners.length;
082 for (int i = 0; i < length; i++) {
083 final T l = listeners[i];
084 if ((l instanceof WeakListener && ((WeakListener)l).wasGarbageCollected()) || l.equals(listener)) {
085 if (i < length-1)
086 System.arraycopy(listeners, i+1, listeners, i, length-i-1);
087 length--;
088 i--;
089 }
090 else
091 newSize++;
092 }
093 if (newSize == 0)
094 return null;
095
096 return Arrays.copyOf(listeners, newSize);
097 }
098
099 }