1 package org.simantics.g3d.tools;
\r
3 import java.util.ArrayList;
\r
4 import java.util.Collection;
\r
5 import java.util.Collections;
\r
7 import org.eclipse.core.runtime.IAdaptable;
\r
8 import org.eclipse.jface.viewers.IStructuredSelection;
\r
9 import org.simantics.utils.Container;
\r
12 * @author Antti Villberg
\r
13 * @author Marko Luukkainen
\r
15 * TODO: merge to os.ui.utils.
\r
17 public class AdaptationUtils {
\r
22 * @return object of given class or null
\r
24 @SuppressWarnings("unchecked")
\r
25 public static <T> T adaptToSingle(Object o, Class<T> clazz) {
\r
26 if (o instanceof IStructuredSelection) {
\r
27 IStructuredSelection iss = (IStructuredSelection) o;
\r
28 if (iss.size() != 1)
\r
30 Object element = iss.getFirstElement();
\r
31 return adaptToSingle(element, clazz);
\r
32 } else if (o instanceof Collection<?>) {
\r
33 Collection<?> c = (Collection<?>) o;
\r
36 Object element = c.iterator().next();
\r
37 return adaptToSingle(element, clazz);
\r
38 } else if (o instanceof IAdaptable) {
\r
39 IAdaptable a = (IAdaptable) o;
\r
40 return (T)a.getAdapter(clazz);
\r
41 } else if (clazz.isInstance(o)) {
\r
43 } else if (o instanceof Container<?>) {
\r
44 Object obj = ((Container<?>) o).get();
\r
47 return adaptToSingle(obj, clazz);
\r
55 * @return collection of objects of given class.
\r
57 @SuppressWarnings("unchecked")
\r
58 public static <T> Collection<T> adaptToCollection(Object o, Class<T> clazz) {
\r
59 if (clazz.isInstance(o)) {
\r
60 return Collections.singletonList((T)o);
\r
61 } else if (o instanceof IStructuredSelection) {
\r
62 IStructuredSelection iss = (IStructuredSelection) o;
\r
63 return adaptToCollection(iss.toArray(), clazz);
\r
64 } else if (o instanceof Collection<?>) {
\r
65 Collection<?> c = (Collection<?>) o;
\r
66 return adaptToCollection(c.toArray(), clazz);
\r
67 } else if (o instanceof IAdaptable) {
\r
68 IAdaptable a = (IAdaptable) o;
\r
69 return Collections.singletonList((T)a.getAdapter(clazz));
\r
70 } else if (o instanceof Container<?>) {
\r
71 Object obj = ((Container<?>) o).get();
\r
73 return Collections.EMPTY_LIST;
\r
74 return adaptToCollection(obj, clazz);
\r
76 return Collections.EMPTY_LIST;
\r
79 public static <T> Collection<T> adaptToCollection(Object arr[], Class<T> clazz) {
\r
80 Collection<T> result = new ArrayList<T>();
\r
81 for (Object o : arr) {
\r
82 Collection<T> tColl = adaptToCollection(o, clazz);
\r
84 if (t != null && !result.contains(t))
\r