/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.utils.ui; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.viewers.IStructuredSelection; import org.simantics.utils.Container; /** * @author Antti Villberg * @author Marko Luukkainen */ public class AdaptionUtils { @SuppressWarnings("unchecked") public static T adaptToSingle(Object o, Class clazz) { if (clazz.isInstance(o)) { return (T)o; } else if (o instanceof IStructuredSelection) { IStructuredSelection iss = (IStructuredSelection) o; if (iss.size() != 1) return null; Object element = iss.getFirstElement(); return adaptToSingle(element, clazz); } else if (o instanceof Collection) { Collection c = (Collection) o; if (c.size() != 1) return null; Object element = c.iterator().next(); return adaptToSingle(element, clazz); } else if (o instanceof IAdaptable) { IAdaptable a = (IAdaptable) o; return (T)a.getAdapter(clazz); } else if (o instanceof Container) { Object obj = ((Container) o).get(); if (obj == o) return null; return adaptToSingle(obj, clazz); } return null; } /** * Adapts given object to collection of objects of given class. * @param o * @param clazz * @return collection of objects of given class. */ @SuppressWarnings("unchecked") public static Collection adaptToCollection(Object o, Class clazz) { if (clazz.isInstance(o)) { return Collections.singletonList((T)o); } else if (o instanceof IStructuredSelection) { IStructuredSelection iss = (IStructuredSelection) o; return adaptToCollection(iss.toArray(), clazz); } else if (o instanceof Collection) { Collection c = (Collection) o; return adaptToCollection(c.toArray(), clazz); } else if (o instanceof IAdaptable) { IAdaptable a = (IAdaptable) o; return Collections.singletonList((T)a.getAdapter(clazz)); } else if (o instanceof Container) { Object obj = ((Container) o).get(); if (obj == o) return Collections.EMPTY_LIST; return adaptToCollection(obj, clazz); } return Collections.EMPTY_LIST; } public static Collection adaptToCollection(Object arr[], Class clazz) { Collection result = new ArrayList(); for (Object o : arr) { Collection tColl = adaptToCollection(o, clazz); for (T t : tColl) if (t != null && !result.contains(t)) result.add(t); } return result; } }