/******************************************************************************* * 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 *******************************************************************************/ /* * * @author Toni Kalajainen */ package org.simantics.g2d.dnd; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.simantics.utils.datastructures.context.Context; import org.simantics.utils.datastructures.hints.HintContext; import org.simantics.utils.datastructures.hints.IHintContext; /** * Contains an ordered set of context items (see {@link #orderedItems}) which * works around the fact that {@link Context} base implementation does not * preserve any kind of order information for the added drag items, which is * often useful for user experience's sake. * * WARNING DnDContext is not as thread-safe as its base implementation * {@link Context}. * * @author Tuukka Lehtonen */ public class DnDContext extends Context implements IDnDContext { IHintContext hintCtx = new HintContext(); List orderedItems = new ArrayList(); Map itemPositions = new HashMap(); public DnDContext() { super(IDragItem.class); } @Override public IHintContext getHints() { return hintCtx; } @Override public synchronized void setItemPosition(IDragItem item, Point2D pos) { if (item == null) throw new NullPointerException("trying to set position " + pos + " for null IDragItem"); if (pos == null) throw new NullPointerException("trying to set null position for dragged item " + item); itemPositions.put(item, pos); } @Override public synchronized Point2D getItemPosition(IDragItem item) { return itemPositions.get(item); } @Override public void add(IDragItem item) { assertNotDisposed(); orderedItems.add(item); boolean added = false; try { super.add(item); added = true; } finally { if (!added) orderedItems.remove(item); } } @Override public boolean remove(IDragItem item) { assertNotDisposed(); boolean existed = super.remove(item); if (existed) orderedItems.remove(item); return existed; } @Override public void clear() { assertNotDisposed(); orderedItems.clear(); super.clear(); } @Override public IDragItem[] toArray() { assertNotDisposed(); return orderedItems.toArray(new IDragItem[orderedItems.size()]); } }