/******************************************************************************* * Copyright (c) 2007, 2013 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 * Semantum Oy - issue #4214 *******************************************************************************/ package org.simantics.ui.icons; import java.io.ByteArrayInputStream; import java.util.Arrays; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.simantics.databoard.Bindings; import org.simantics.db.ReadGraph; import org.simantics.db.RequestProcessor; import org.simantics.db.Resource; import org.simantics.db.common.primitiverequest.PossibleValue; import org.simantics.db.exception.DatabaseException; /** * @author Hannu Niemistö * @author Tuukka Lehtonen */ public class GraphImageDescriptor extends ImageDescriptor { private Resource resource; private long resourceId; private byte[] data; private int hash; public GraphImageDescriptor(ReadGraph graph, Resource resource) throws DatabaseException { this.resource = resource; this.resourceId = resource.getResourceId(); this.data = getImageDataBytes(graph); this.hash = (Arrays.hashCode(this.data) * 31 + (int)(resourceId>>>32)) * 31 + ((int)resourceId); } private byte[] getImageDataBytes(RequestProcessor processor) throws DatabaseException { return processor.syncRequest(new PossibleValue(resource, Bindings.BYTE_ARRAY)); } private ImageData toImageData(byte[] data) throws SWTException { ImageData[] images = new ImageLoader().load(new ByteArrayInputStream(data)); if (images.length == 0) SWT.error(SWT.ERROR_INVALID_IMAGE, null, "No images found in image data of resource $" + resourceId); return images[0]; } @Override public ImageData getImageData() { try { ImageData imageData = toImageData(data); return imageData; } catch (SWTException e) { return null; } } public Resource getResource() { return resource; } @Override public String toString() { return super.toString() + "[" + resource + "]"; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GraphImageDescriptor other = (GraphImageDescriptor) obj; if (!resource.equals(other.resource)) return false; if (!Arrays.equals(data, other.data)) return false; return true; } }