Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Modeling » Graphiti » Save as ... Image, without editor(is it plan ?)
Save as ... Image, without editor [message #638807] Fri, 12 November 2010 16:06 Go to next message
Tristan Faure is currently offline Tristan Faure
Messages: 227
Registered: July 2009
Senior Member
Hi !
I'm very interesting in Graphiti and I would like to know if it exists (or if it is plan to develop) an equivalent to the GMF OffscrenEditPartFactory ?

This mechanism allows plugins to render a diagram and export it in image file (for example) without opening the editor.

Another example from GMF is the class CopyToImageUtil allowing developers to automatically export a diagram at a specific folder.

Regards
Tristan FAURE



Re: Save as ... Image, without editor [message #639893 is a reply to message #638807] Thu, 18 November 2010 10:08 Go to previous messageGo to next message
Michael Wenz is currently offline Michael Wenz
Messages: 1595
Registered: July 2009
Location: Walldorf, Germany
Senior Member
Tristan,

such a feature is currently not planned. What we have is the possibility to
trigger a saveAs or print from the opened diagram editor.

Michael


"Tristan FAURE" <tristan.faure@atosorigin.com> wrote in message
news:ibjoet$om9$1@news.eclipse.org...
> Hi !
> I'm very interesting in Graphiti and I would like to know if it exists (or
> if it is plan to develop) an equivalent to the GMF OffscrenEditPartFactory
> ?
>
> This mechanism allows plugins to render a diagram and export it in image
> file (for example) without opening the editor.
>
> Another example from GMF is the class CopyToImageUtil allowing developers
> to automatically export a diagram at a specific folder.
> Regards
> Tristan FAURE
>
>
>
>
Re: Save as ... Image, without editor [message #663806 is a reply to message #639893] Wed, 06 April 2011 14:37 Go to previous messageGo to next message
J. Weimar is currently offline J. Weimar
Messages: 8
Registered: March 2011
Location: Germany
Junior Member
Dear Micheal,

the DefaultSaveImageFeature does not implement anything yet, so how can I programmatically trigger the action (Save as Image...) that is avaliable from the context menu? The comment in the code
// not relevant (actual work is done in SaveImageAction)
does not help me.

Thanks, Jörg.
Re: Save as ... Image, without editor [message #664057 is a reply to message #663806] Thu, 07 April 2011 10:34 Go to previous messageGo to next message
Michael Wenz is currently offline Michael Wenz
Messages: 1595
Registered: July 2009
Location: Walldorf, Germany
Senior Member
Jörg,

you can simply call canExecute and execute on that feature (or your subclass
of it). Just keep in mind that in case you do any modifications to EObjects
during these calls, you need to perform the calls within a command on the
EMF command stack.

HTH,
Michael


"J. Weimar" wrote in message news:inhte1$lun$1@news.eclipse.org...

Dear Micheal,

the DefaultSaveImageFeature does not implement anything yet, so how can I
programmatically trigger the action (Save as Image...) that is avaliable
from the context menu? The comment in the code
// not relevant (actual work is done in SaveImageAction)
does not help me.

Thanks, Jörg.
Re: Save as ... Image, without editor [message #664292 is a reply to message #664057] Fri, 08 April 2011 10:06 Go to previous messageGo to next message
J. Weimar is currently offline J. Weimar
Messages: 8
Registered: March 2011
Location: Germany
Junior Member
Dear Micheal,

unfortunately, it doesn't help. I use the following code to create a custom feature, but it does not do anything. As far as I can tell, the comment in file
DefaultSaveImageFeature.java:28 instead of
/**
* The Class DefaultSaveImageFeature. It is planned to use this for save as
* image support. Not yet supported perfectly.
*/
should read
/**
* The Class DefaultSaveImageFeature. It is planned to use this for save as
* image support. Does not yet support any saving!
*/

package de.jweimar.mockup.mockplug.export;

import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.IContext;
import org.eclipse.graphiti.features.context.ICustomContext;
import org.eclipse.graphiti.features.custom.ICustomFeature;
import org.eclipse.graphiti.features.impl.DefaultSaveImageFeature;

/**
 * @author weimar  
 *
 */
public class PreviewExporter2 extends DefaultSaveImageFeature implements ICustomFeature{
		
	public PreviewExporter2(IFeatureProvider fp){
		super(fp);
	}

	@Override
	public boolean canExecute(IContext context) {
		return super.canExecute(context);
	}

	@Override
	public boolean canExecute(ICustomContext context) {
		return true;
	}

	@Override
	public String getDescription() {
		return "(2) Export preview to export/preview.jpg";
	}

	@Override
	public String getName() {
		return "&Preview2";
	}

	@Override
	public String getImageId() {
		return null;
	}

	public void execute(ISaveImageContext context){
		super.execute(context);
	}

	@Override
	public void execute(ICustomContext context) {
		ISaveImageContext saveImageContext = new SaveImageContext();
		this.execute(saveImageContext);
		
//		ISaveImageFeature sif = getFeatureProvider().getSaveImageFeature();
//		if(sif.canExecute(saveImageContext)){
//			sif.execute(saveImageContext);
//			// TODO: apparently has no effect.
//			// I need to save as JPG file, all others are only 8 bit or too big.
//			// TODO: move to MockExportSelectFilesPage
//		}
	}
}
Re: Save as ... Image, without editor [message #664319 is a reply to message #664292] Fri, 08 April 2011 11:33 Go to previous message
J. Weimar is currently offline J. Weimar
Messages: 8
Registered: March 2011
Location: Germany
Junior Member
Dear Micheal, for your information, after extensive copying form the sources, I have created my custom feature which can save the diagram as an image with the properties I need. Code cleanup and documentation can still be improved, but I refactored the method initScaledImage to also work efficiently for scale factor 1.0.
Best regards, Jörg.

/*******************************************************************************
 * <copyright>
 *
 * Copyright (c) 2005, 2010 SAP AG.
 * 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:
 *    SAP AG - initial API, implementation and documentation
 *
 * </copyright>
 *
 *******************************************************************************/

package de.jweimar.mockup.mockplug.export;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.SWTGraphics;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.editparts.LayerManager;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.ICustomContext;
import org.eclipse.graphiti.features.custom.AbstractCustomFeature;
import org.eclipse.graphiti.internal.util.T;
import org.eclipse.graphiti.ui.internal.editor.DiagramEditorInternal;
import org.eclipse.graphiti.ui.internal.editor.GFFigureCanvas;
import org.eclipse.graphiti.ui.internal.fixed.FixedScaledGraphics;
import org.eclipse.graphiti.ui.internal.services.GraphitiUiInternal;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

/**
 * @author weimar Most code copied from
 *         org.eclipse.graphiti.ui.internal.util.ui.
 *         print.AbstractFigureSelectionDialog
 * 
 */
public class PreviewExporter extends AbstractCustomFeature {

	// initial values
	protected GraphicalViewer _graphicalViewer;

	protected final String folderName = "export";
	protected final String fileName = "preview.jpg";
	protected final double scale = 1.5;

	/**
	 * <code>_allFigure</code> represents a figure that contains all printable
	 * layers
	 */
	protected IFigure _allFigure;

	protected boolean _insideInternalModify = false;

	// selected values

	/**
	 * Image corresponding to the whole diagram (scaled version)
	 */
	private Image _image;

	public PreviewExporter(IFeatureProvider fp) {
		super(fp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.graphiti.features.custom.AbstractCustomFeature#canExecute
	 * (org.eclipse.graphiti.features.context.ICustomContext)
	 */
	@Override
	public boolean canExecute(ICustomContext context) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public String getDescription() {
		return "Export preview to " + folderName + "/" + fileName;
	}

	@Override
	public String getName() {
		return "&Preview";
	}

	@SuppressWarnings("restriction")
	public void execute(ICustomContext context) {
		IFile destination;
		try {
			destination = createDirectoryResource(
					this.getDiagram().eResource(), folderName)
					.getFile(fileName);
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}

		// get the graphical Viewer

		_graphicalViewer = (GraphicalViewer) ((DiagramEditorInternal) super
				.getDiagramEditor()).getAdapter(GraphicalViewer.class);

		_allFigure = determineRootFigure();
		// create the image
		setScaledImage(scale);

		startSaveAsImageWithoutDialog(_image, destination);

	}

	/**
	 * creates or returns a folder in the root directory of the current project
	 * (as given by the resource)
	 * 
	 * @param diagramResource
	 *            used only to determine the current project.
	 * @param folderName
	 *            name of the (top level) folder in the project.
	 * @return the folder, which is created if it did not exist.
	 * @throws CoreException
	 */
	private IFolder createDirectoryResource(Resource diagramResource,
			String folderName) throws CoreException {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IWorkspaceRoot root = workspace.getRoot();
		IProject project = root.getProject(diagramResource.getURI().segment(1));
		IFolder folder = project.getFolder(folderName);
		// at this point, no resources have been created
		if (!project.exists()) {
			return null;
			// project.create(null);
		}
		if (!project.isOpen())
			project.open(null);
		if (!folder.exists())
			folder.create(IResource.NONE, true, null);
		return folder;
	}

	/*
	 * copied from UiService and modified.
	 */
	public byte[] createImage(Image image, int format) throws Exception {
		ByteArrayOutputStream result = new ByteArrayOutputStream();

		try {
			ImageData imDat = image.getImageData();

			ImageLoader imageLoader = new ImageLoader();
			imageLoader.data = new ImageData[] { imDat };
			try {
				imageLoader.save(result, format);
			} catch (SWTException e) {
				String error = "Depth: " + Integer.toString(image.getImageData().depth) + "\n" + "X: " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						+ Integer.toString(image.getImageData().x)
						+ "\n" + "Y: " + Integer.toString(image.getImageData().y); //$NON-NLS-1$ //$NON-NLS-2$
				throw new IllegalStateException(error, e);
			}
		} finally {
			image.dispose();
		}
		return result.toByteArray();
	}

	/*
	 * copied from UiService
	 */
	public void startSaveAsImageWithoutDialog(Image im, IFile destination) {
		final Shell shell = GraphitiUiInternal.getWorkbenchService().getShell();

		try {
			WorkspaceModifyOperation operation;
			int imageFormat = SWT.IMAGE_JPEG;
			byte image[] = createImage(im, imageFormat);
			operation = getSaveToFileOp(destination, image);
			new ProgressMonitorDialog(shell).run(false, false, operation);
		} catch (Exception e) {
			String message = "Can not save image: "; //$NON-NLS-1$
			MessageDialog.openError(shell,
					"Can not save image", message + e.getMessage()); //$NON-NLS-1$
			e.printStackTrace();
		}
	}

	/**
	 * Returns a WorkspeceModifyOperation, which saves the given contents to a
	 * File with the given filename.
	 * 
	 * @param filename
	 *            The name of the file, where to save the contents.
	 * @param contents
	 *            The contents to save into the file.
	 * @throws Exception
	 *             On any errors that occur. copied from UiService
	 */
	private WorkspaceModifyOperation getSaveToFileOp(final IFile destination,
			final byte contents[]) throws Exception {
		WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
			@Override
			protected void execute(IProgressMonitor monitor)
					throws CoreException {
				try {
					InputStream source = new ByteArrayInputStream(contents);
					if (!destination.exists()) {
						destination.create(source, IResource.NONE, null);
					} else {
						destination.setContents(source, IResource.NONE, null);
					}
				} catch (Exception e) {
					// convert exceptions to CoreExceptions
					Status status = new Status(
							IStatus.ERROR,
							"de.jweimar.mockup", IStatus.ERROR, "Can not save image as file: " //$NON-NLS-1$
									+ e.getMessage(), e);
					throw new CoreException(status);
				}
			}
		};

		return operation;
	}

	@SuppressWarnings("restriction")
	private IFigure determineRootFigure() {
		// Code snipped copied from AbstractFigureSelectionDialog
		org.eclipse.swt.widgets.Control control = _graphicalViewer.getControl();
		if (control instanceof GFFigureCanvas) {
			GFFigureCanvas canvas = (GFFigureCanvas) control;
			canvas.regainSpace();
		}

		EditPart rootEditPart = _graphicalViewer.getRootEditPart();
		if (!(rootEditPart instanceof GraphicalEditPart))
			return null;

		// determine _allFigure
		GraphicalEditPart graphicalRootEditPart = (GraphicalEditPart) rootEditPart;
		IFigure rootFigure = ((LayerManager) graphicalRootEditPart)
				.getLayer(LayerConstants.PRINTABLE_LAYERS);
		if (rootFigure == null)
			return null;

		return rootFigure;

	}

	// Code snipped copied from AbstractFigureSelectionDialog
	public void setScaledImage(double scaleFactor) {
		cleanUp();
		_image = null;

		double upperBoundPixels = 3000.0d;

		initScaledImage(scaleFactor, upperBoundPixels);
	}

	@SuppressWarnings("restriction")
	private void initScaledImage(double scaleFactor, double upperBoundPixels) {
		GC gc = null;
		// if the scale factor is too high, the operating system will
		// not be able to provide a handle,
		// because the Image would require too much space. "no more
		// Handles"-Exception or "out of Memory" Error
		// will be thrown
		if (scaleFactor * _allFigure.getBounds().width > upperBoundPixels
				|| scaleFactor * _allFigure.getBounds().height > upperBoundPixels) {
			scaleFactor = Math.min(upperBoundPixels
					/ _allFigure.getBounds().width, upperBoundPixels
					/ _allFigure.getBounds().height);
		}

		_image = new Image(Display.getDefault(),
				(int) (_allFigure.getBounds().width * scaleFactor),
				(int) (scaleFactor * _allFigure.getBounds().height));
		gc = new GC(_image);
		Graphics graphics = null;
		if (scaleFactor != 1.0) {
			FixedScaledGraphics fsg = new FixedScaledGraphics(new SWTGraphics(
					gc));
			fsg.scale(scaleFactor);
			graphics = fsg;
		} else {
			graphics = new SWTGraphics(gc);
		}

		/* move all figures into the positive region */
		EditPart contents = _graphicalViewer.getContents();
		if (contents instanceof GraphicalEditPart) {
			IFigure contentsFigure = ((GraphicalEditPart) contents).getFigure();
			Rectangle contentBounds = contentsFigure.getBounds();
			graphics.translate(-contentBounds.x, -contentBounds.y);
		}

		_allFigure.paint(graphics);

		if (gc != null)
			gc.dispose();
		if (graphics != null)
			graphics.dispose();
	}

	public Image getScaledImage() {
		return _image;
	}

	public void cleanUp() {
		if (_image != null)
			_image.dispose();
	}

}

Previous Topic:Avoiding editing domain ?
Next Topic:Zoom handling in multi-page editors
Goto Forum:
  


Current Time: Fri Sep 19 12:02:29 GMT 2014

Powered by FUDForum. Page generated in 0.10525 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software