1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.ui;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
18 import org.eclipse.core.runtime.IAdaptable;
19 import org.eclipse.jface.viewers.IStructuredSelection;
20 import org.simantics.utils.Container;
23 * @author Antti Villberg
24 * @author Marko Luukkainen
26 public class AdaptionUtils {
28 @SuppressWarnings("unchecked")
29 public static <T> T adaptToSingle(Object o, Class<T> clazz) {
30 if (clazz.isInstance(o)) {
32 } else if (o instanceof IStructuredSelection) {
33 IStructuredSelection iss = (IStructuredSelection) o;
36 Object element = iss.getFirstElement();
37 return adaptToSingle(element, clazz);
38 } else if (o instanceof Collection<?>) {
39 Collection<?> c = (Collection<?>) o;
42 Object element = c.iterator().next();
43 return adaptToSingle(element, clazz);
44 } else if (o instanceof IAdaptable) {
45 IAdaptable a = (IAdaptable) o;
46 return (T)a.getAdapter(clazz);
47 } else if (o instanceof Container<?>) {
48 Object obj = ((Container<?>) o).get();
51 return adaptToSingle(obj, clazz);
57 * Adapts given object to collection of objects of given class.
60 * @return collection of objects of given class.
62 @SuppressWarnings("unchecked")
63 public static <T> Collection<T> adaptToCollection(Object o, Class<T> clazz) {
64 if (clazz.isInstance(o)) {
65 return Collections.singletonList((T)o);
66 } else if (o instanceof IStructuredSelection) {
67 IStructuredSelection iss = (IStructuredSelection) o;
68 return adaptToCollection(iss.toArray(), clazz);
69 } else if (o instanceof Collection<?>) {
70 Collection<?> c = (Collection<?>) o;
71 return adaptToCollection(c.toArray(), clazz);
72 } else if (o instanceof IAdaptable) {
73 IAdaptable a = (IAdaptable) o;
74 return Collections.singletonList((T)a.getAdapter(clazz));
75 } else if (o instanceof Container<?>) {
76 Object obj = ((Container<?>) o).get();
78 return Collections.EMPTY_LIST;
79 return adaptToCollection(obj, clazz);
81 return Collections.EMPTY_LIST;
84 public static <T> Collection<T> adaptToCollection(Object arr[], Class<T> clazz) {
85 Collection<T> result = new ArrayList<T>();
86 for (Object o : arr) {
87 Collection<T> tColl = adaptToCollection(o, clazz);
89 if (t != null && !result.contains(t))