--- /dev/null
+package org.simantics.g3d.tools;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+\r
+import org.eclipse.core.runtime.IAdaptable;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.simantics.utils.Container;\r
+\r
+/**\r
+ * @author Antti Villberg\r
+ * @author Marko Luukkainen\r
+ * \r
+ * TODO: merge to os.ui.utils.\r
+ */\r
+public class AdaptationUtils {\r
+ /**\r
+ * \r
+ * @param o\r
+ * @param clazz\r
+ * @return object of given class or null\r
+ */\r
+ @SuppressWarnings("unchecked")\r
+ public static <T> T adaptToSingle(Object o, Class<T> clazz) {\r
+ if (o instanceof IStructuredSelection) {\r
+ IStructuredSelection iss = (IStructuredSelection) o;\r
+ if (iss.size() != 1)\r
+ return null;\r
+ Object element = iss.getFirstElement();\r
+ return adaptToSingle(element, clazz);\r
+ } else if (o instanceof Collection<?>) {\r
+ Collection<?> c = (Collection<?>) o;\r
+ if (c.size() != 1)\r
+ return null;\r
+ Object element = c.iterator().next();\r
+ return adaptToSingle(element, clazz);\r
+ } else if (o instanceof IAdaptable) {\r
+ IAdaptable a = (IAdaptable) o;\r
+ return (T)a.getAdapter(clazz);\r
+ } else if (clazz.isInstance(o)) {\r
+ return (T)o;\r
+ } else if (o instanceof Container<?>) {\r
+ Object obj = ((Container<?>) o).get();\r
+ if (obj == o)\r
+ return null;\r
+ return adaptToSingle(obj, clazz);\r
+ }\r
+ return null;\r
+ }\r
+ /**\r
+ * \r
+ * @param o\r
+ * @param clazz\r
+ * @return collection of objects of given class. \r
+ */\r
+ @SuppressWarnings("unchecked")\r
+ public static <T> Collection<T> adaptToCollection(Object o, Class<T> clazz) {\r
+ if (clazz.isInstance(o)) {\r
+ return Collections.singletonList((T)o);\r
+ } else if (o instanceof IStructuredSelection) {\r
+ IStructuredSelection iss = (IStructuredSelection) o;\r
+ return adaptToCollection(iss.toArray(), clazz);\r
+ } else if (o instanceof Collection<?>) {\r
+ Collection<?> c = (Collection<?>) o;\r
+ return adaptToCollection(c.toArray(), clazz);\r
+ } else if (o instanceof IAdaptable) {\r
+ IAdaptable a = (IAdaptable) o;\r
+ return Collections.singletonList((T)a.getAdapter(clazz));\r
+ } else if (o instanceof Container<?>) {\r
+ Object obj = ((Container<?>) o).get();\r
+ if (obj == o)\r
+ return Collections.EMPTY_LIST;\r
+ return adaptToCollection(obj, clazz);\r
+ }\r
+ return Collections.EMPTY_LIST;\r
+ }\r
+ \r
+ public static <T> Collection<T> adaptToCollection(Object arr[], Class<T> clazz) {\r
+ Collection<T> result = new ArrayList<T>();\r
+ for (Object o : arr) {\r
+ Collection<T> tColl = adaptToCollection(o, clazz); \r
+ for (T t : tColl)\r
+ if (t != null && !result.contains(t))\r
+ result.add(t);\r
+ }\r
+ return result;\r
+ }\r
+}\r