View | Details | Raw Unified | Return to bug 196834 | Differences between
and this patch

Collapse All | Expand All

(-)plugin.xml (+11 lines)
Lines 23-28 Link Here
23
      </editpartProvider>
23
      </editpartProvider>
24
   </extension>
24
   </extension>
25
   
25
   
26
    <extension id="printingExperimentalContributionItemProvider" name="Printing_Experimental" point="org.eclipse.gmf.runtime.common.ui.services.action.contributionItemProviders">
27
      <contributionItemProvider class="org.eclipse.gmf.runtime.diagram.ui.render.internal.providers.PrintingExperimentalContributionItemProvider">
28
         <Priority name="Low">
29
         </Priority>
30
         <partContribution class="org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart">
31
            <partAction menubarPath="/file/print" id="printExperimentalAction">
32
            </partAction>
33
         </partContribution>
34
      </contributionItemProvider>
35
   </extension>
36
   
26
   <extension id="DiagramUIRenderContributionItemProvider" name="%ContributionItemProvider.name" point="org.eclipse.gmf.runtime.common.ui.services.action.contributionItemProviders">
37
   <extension id="DiagramUIRenderContributionItemProvider" name="%ContributionItemProvider.name" point="org.eclipse.gmf.runtime.common.ui.services.action.contributionItemProviders">
27
      <contributionItemProvider class="org.eclipse.gmf.runtime.diagram.ui.render.internal.providers.DiagramUIRenderContributionItemProvider">
38
      <contributionItemProvider class="org.eclipse.gmf.runtime.diagram.ui.render.internal.providers.DiagramUIRenderContributionItemProvider">
28
         <Priority name="Low">
39
         <Priority name="Low">
(-)META-INF/MANIFEST.MF (-1 / +3 lines)
Lines 25-29 Link Here
25
 org.eclipse.gmf.runtime.draw2d.ui.render;bundle-version="[1.0.0,2.0.0)",
25
 org.eclipse.gmf.runtime.draw2d.ui.render;bundle-version="[1.0.0,2.0.0)",
26
 org.eclipse.gmf.runtime.emf.commands.core;bundle-version="[1.0.0,2.0.0)",
26
 org.eclipse.gmf.runtime.emf.commands.core;bundle-version="[1.0.0,2.0.0)",
27
 org.eclipse.gmf.runtime.diagram.ui.providers;bundle-version="[1.0.0,2.0.0)",
27
 org.eclipse.gmf.runtime.diagram.ui.providers;bundle-version="[1.0.0,2.0.0)",
28
 org.eclipse.gmf.runtime.draw2d.ui.render.awt;bundle-version="[1.0.0,2.0.0)"
28
 org.eclipse.gmf.runtime.draw2d.ui.render.awt;bundle-version="[1.0.0,2.0.0)",
29
 org.eclipse.gmf.runtime.diagram.ui.printing.render,
30
 org.eclipse.gmf.runtime.diagram.ui.printing
29
Eclipse-LazyStart: true
31
Eclipse-LazyStart: true
(-)src/org/eclipse/gmf/runtime/diagram/ui/render/internal/providers/PrintingExperimentalContributionItemProvider.java (+40 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.render.internal.providers;
13
14
import org.eclipse.gmf.runtime.common.ui.services.action.contributionitem.AbstractContributionItemProvider;
15
import org.eclipse.gmf.runtime.common.ui.util.IWorkbenchPartDescriptor;
16
import org.eclipse.jface.action.IAction;
17
18
19
/**
20
 * This class is strictly temporary while we introduce the printing via the
21
 * Print Service API.
22
 * 
23
 * @author James Bruck (jbruck)
24
 */
25
public class PrintingExperimentalContributionItemProvider extends
26
		AbstractContributionItemProvider {
27
	
28
	/**
29
	 * @see org.eclipse.gmf.runtime.common.ui.services.action.contributionitem.AbstractContributionItemProvider#createAction(java.lang.String, org.eclipse.gmf.runtime.common.ui.services.contributionitem.IWorkbenchPartDescriptor)
30
	 */
31
	protected IAction createAction(
32
		String actionId,
33
		IWorkbenchPartDescriptor partDescriptor) {
34
35
		if (actionId.equals(PrintExperimentalAction.ID))
36
			return new PrintExperimentalAction();
37
38
		return super.createAction(actionId, partDescriptor);
39
	}
40
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/render/internal/providers/PrintExperimentalAction.java (+138 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.render.internal.providers;
13
14
import org.eclipse.core.runtime.IStatus;
15
import org.eclipse.gef.RootEditPart;
16
import org.eclipse.gmf.runtime.common.core.util.Log;
17
import org.eclipse.gmf.runtime.common.core.util.Trace;
18
import org.eclipse.gmf.runtime.common.ui.action.actions.IPrintActionHelper;
19
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
20
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
21
import org.eclipse.gmf.runtime.diagram.ui.editparts.IDiagramPreferenceSupport;
22
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
23
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
24
import org.eclipse.gmf.runtime.diagram.ui.printing.render.actions.EnhancedPrintActionHelper;
25
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.DiagramUIPrintingRenderDebugOptions;
26
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.DiagramUIPrintingRenderPlugin;
27
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.JPSDiagramPrinter;
28
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.JPSDiagramPrinterHelper;
29
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
30
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
31
import org.eclipse.jface.action.Action;
32
import org.eclipse.jface.action.IAction;
33
import org.eclipse.jface.viewers.ISelection;
34
import org.eclipse.ui.IWorkbenchPart;
35
import org.eclipse.ui.IWorkbenchWindow;
36
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
37
import org.eclipse.ui.PlatformUI;
38
39
/**
40
 * This class is strictly temporary while we introduce the printing via the
41
 * Print Service API.
42
 * 
43
 * @author James Bruck (jbruck)
44
 */
45
public class PrintExperimentalAction extends Action implements
46
		IWorkbenchWindowActionDelegate {
47
48
	/**
49
	 * ID for this page setup action
50
	 */
51
	public static final String ID = "printExperimentalAction";//$NON-NLS-1$
52
53
	/**
54
	 * Constructor sets the id and label that is displayed in the menu bar.
55
	 */
56
	public PrintExperimentalAction() {
57
		setId(ID);
58
		setText("Print (Experimental)..."); //$NON-NLS-1$
59
	}
60
61
	/**
62
	 * We override the print to always use the newer JPS printing options.
63
	 */
64
	public void run() {
65
66
		IPrintActionHelper helper = new EnhancedPrintActionHelper() {
67
			@Override
68
			public void doPrint(IWorkbenchPart workbenchPart) {
69
70
				DiagramEditor diagramEditor = null;
71
72
				if (workbenchPart instanceof DiagramEditor) {
73
					diagramEditor = (DiagramEditor) workbenchPart;
74
				} else {
75
					Log.error(DiagramUIPrintingRenderPlugin.getInstance(),
76
							IStatus.ERROR, "Invalid IWorkbenchPart"); //$NON-NLS-1$
77
					IllegalArgumentException e = new IllegalArgumentException(
78
							"Invalid IWorkbenchPart."); //$NON-NLS-1$
79
					Trace
80
							.throwing(
81
									DiagramUIPrintingRenderPlugin.getInstance(),
82
									DiagramUIPrintingRenderDebugOptions.EXCEPTIONS_THROWING,
83
									EnhancedPrintActionHelper.class,
84
									"doPrint()", e); //$NON-NLS-1$
85
					throw e;
86
				}
87
88
				IDiagramGraphicalViewer viewer = diagramEditor
89
						.getDiagramGraphicalViewer();
90
				RootEditPart rootEP = (viewer == null) ? null : viewer
91
						.getRootEditPart();
92
				PreferencesHint preferencesHint = (rootEP instanceof IDiagramPreferenceSupport) ? ((IDiagramPreferenceSupport) rootEP)
93
						.getPreferencesHint()
94
						: PreferencesHint.USE_DEFAULTS;
95
96
				IMapMode mapMode = (rootEP instanceof DiagramRootEditPart) ? ((DiagramRootEditPart) rootEP)
97
						.getMapMode()
98
						: MapModeUtil.getMapMode();
99
100
				JPSDiagramPrinterHelper
101
						.getDiagramPrinterHelper()
102
						.printWithSettings(diagramEditor, createDiagramMap(),
103
								new JPSDiagramPrinter(preferencesHint, mapMode));
104
			}
105
		};
106
107
		helper.doPrint(PlatformUI.getWorkbench().getActiveWorkbenchWindow()
108
				.getActivePage().getActivePart());
109
	}
110
111
	/**
112
	 * The run method does the real run action. From IActionDelegate
113
	 */
114
	public void run(IAction action) {
115
		run();
116
	}
117
118
	/**
119
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
120
	 */
121
	public void dispose() {
122
		// do nothing
123
	}
124
125
	/**
126
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(IWorkbenchWindow)
127
	 */
128
	public void init(IWorkbenchWindow window) {
129
		// do nothing
130
	}
131
132
	/**
133
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
134
	 */
135
	public void selectionChanged(IAction action, ISelection selection) {
136
		//do nothing
137
	}
138
}
(-)META-INF/MANIFEST.MF (-1 / +1 lines)
Lines 7-13 Link Here
7
Bundle-Vendor: %Plugin.providerName
7
Bundle-Vendor: %Plugin.providerName
8
Bundle-Localization: plugin
8
Bundle-Localization: plugin
9
Export-Package: org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
9
Export-Package: org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
10
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.graphics;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
10
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.graphics;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.printing.render",
11
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.image;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
11
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.image;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
12
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.svg;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
12
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.svg;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
13
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.svg.export;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
13
 org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.svg.export;x-friends:="org.eclipse.gmf.tests.runtime.draw2d.ui.render,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render",
(-)META-INF/MANIFEST.MF (-1 / +6 lines)
Lines 15-19 Link Here
15
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
15
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
 org.eclipse.gmf.runtime.diagram.ui;bundle-version="[1.0.0,2.0.0)",
16
 org.eclipse.gmf.runtime.diagram.ui;bundle-version="[1.0.0,2.0.0)",
17
 org.eclipse.gmf.runtime.diagram.ui.printing;bundle-version="[1.0.0,2.0.0)",
17
 org.eclipse.gmf.runtime.diagram.ui.printing;bundle-version="[1.0.0,2.0.0)",
18
 org.eclipse.gmf.runtime.draw2d.ui.render;bundle-version="[1.0.0,2.0.0)"
18
 org.eclipse.gmf.runtime.draw2d.ui.render;bundle-version="[1.0.0,2.0.0)",
19
 org.eclipse.core.databinding;bundle-version="[1.1.0,2.0.0)",
20
 org.eclipse.core.databinding.beans;bundle-version="[1.0.0,2.0.0)",
21
 org.eclipse.jface.databinding;bundle-version="[1.2.0,2.0.0)",
22
  org.eclipse.gmf.runtime.common.ui.printing;bundle-version="[1.0.0,2.0.0)",
23
 org.eclipse.gmf.runtime.draw2d.ui.render.awt;bundle-version="[1.0.0,2.0.0)"
19
Eclipse-LazyStart: true
24
Eclipse-LazyStart: true
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/actions/EnhancedPrintActionHelper.java (-17 / +25 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2005, 2006 IBM Corporation and others.
2
 * Copyright (c) 2005, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 18-23 Link Here
18
18
19
import org.eclipse.core.resources.IFile;
19
import org.eclipse.core.resources.IFile;
20
import org.eclipse.core.runtime.IStatus;
20
import org.eclipse.core.runtime.IStatus;
21
import org.eclipse.core.runtime.Platform;
21
import org.eclipse.gef.RootEditPart;
22
import org.eclipse.gef.RootEditPart;
22
import org.eclipse.gmf.runtime.common.core.util.Log;
23
import org.eclipse.gmf.runtime.common.core.util.Log;
23
import org.eclipse.gmf.runtime.common.core.util.Trace;
24
import org.eclipse.gmf.runtime.common.core.util.Trace;
Lines 28-40 Link Here
28
import org.eclipse.gmf.runtime.diagram.ui.editparts.IDiagramPreferenceSupport;
29
import org.eclipse.gmf.runtime.diagram.ui.editparts.IDiagramPreferenceSupport;
29
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
30
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
30
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
31
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
31
import org.eclipse.gmf.runtime.diagram.ui.printing.actions.DefaultPrintActionHelper;
32
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.DiagramUIPrintingRenderDebugOptions;
32
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.DiagramUIPrintingRenderDebugOptions;
33
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.DiagramUIPrintingRenderPlugin;
33
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.DiagramUIPrintingRenderPlugin;
34
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.JPSDiagramPrinter;
35
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.JPSDiagramPrinterHelper;
34
import org.eclipse.gmf.runtime.diagram.ui.printing.render.util.RenderedDiagramPrinter;
36
import org.eclipse.gmf.runtime.diagram.ui.printing.render.util.RenderedDiagramPrinter;
35
import org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil;
37
import org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil;
36
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
38
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
37
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
39
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
40
import org.eclipse.gmf.runtime.notation.Diagram;
38
import org.eclipse.ui.IEditorInput;
41
import org.eclipse.ui.IEditorInput;
39
import org.eclipse.ui.IWorkbenchPart;
42
import org.eclipse.ui.IWorkbenchPart;
40
43
Lines 58-63 Link Here
58
	 * 
61
	 * 
59
	 * @param IWorkbenchPart the workbenchPart containing the diagram to print
62
	 * @param IWorkbenchPart the workbenchPart containing the diagram to print
60
	 */
63
	 */
64
	
61
	public void doPrint(IWorkbenchPart workbenchPart) {
65
	public void doPrint(IWorkbenchPart workbenchPart) {
62
		DiagramEditor diagramEditor = null;
66
		DiagramEditor diagramEditor = null;
63
67
Lines 83-100 Link Here
83
		
87
		
84
		//get actual map mode, default is MapModeUtil.getMapMode()
88
		//get actual map mode, default is MapModeUtil.getMapMode()
85
		IMapMode mapMode = (rootEP instanceof DiagramRootEditPart) ? ((DiagramRootEditPart) rootEP)
89
		IMapMode mapMode = (rootEP instanceof DiagramRootEditPart) ? ((DiagramRootEditPart) rootEP)
86
			.getMapMode()
90
				.getMapMode()
87
			: MapModeUtil.getMapMode();
91
				: MapModeUtil.getMapMode();
88
		
89
		if (!System.getProperty("os.name").toUpperCase().startsWith("WIN")) { //$NON-NLS-1$ //$NON-NLS-2$
90
			//do default action when not Windows and this action is enabled
91
			DefaultPrintActionHelper.doRun(diagramEditor,
92
				new RenderedDiagramPrinter(preferencesHint, mapMode));
93
			return;
94
		}
95
		
92
		
96
		DiagramPrinterUtil.printWithSettings(diagramEditor, createDiagramMap(),
93
		if (Platform.getOS().startsWith(Platform.OS_WIN32)) {
97
			new RenderedDiagramPrinter(preferencesHint, mapMode));
94
			DiagramPrinterUtil.printWithSettings(diagramEditor,
95
					createDiagramMap(), new RenderedDiagramPrinter(
96
							preferencesHint, mapMode));
97
		} 
98
		//
99
		// Eventually the windows based printing will be replaced with the
100
		// JPSDiagramPrinter.
101
		//
102
		// else {
103
		// 		JPSDiagramPrinterHelper.getDiagramPrinterHelper().printWithSettings(
104
		// 		diagramEditor, createDiagramMap(),
105
		// 		new JPSDiagramPrinter(preferencesHint, mapMode));
106
		//	}
98
	}
107
	}
99
108
100
	/**
109
	/**
Lines 105-113 Link Here
105
	 * All entries in the map correspond to open editors with the
114
	 * All entries in the map correspond to open editors with the
106
	 * diagramEditor's id. 
115
	 * diagramEditor's id. 
107
	 */
116
	 */
108
	private Map createDiagramMap() {
117
	protected Map<String, Diagram> createDiagramMap() {
109
		
118
		
110
		Map diagramMap = new HashMap();
119
		Map<String, Diagram> diagramMap = new HashMap<String, Diagram>();
111
		
120
		
112
		//get all diagram editors with the matching id 
121
		//get all diagram editors with the matching id 
113
		List diagramEditors = EditorService.getInstance().getRegisteredEditorParts();
122
		List diagramEditors = EditorService.getInstance().getRegisteredEditorParts();
Lines 122-129 Link Here
122
				String diagramName = null;
131
				String diagramName = null;
123
				
132
				
124
				IEditorInput editorInput = dEditor.getEditorInput();
133
				IEditorInput editorInput = dEditor.getEditorInput();
125
				
134
				          
126
                
127
                
135
                
128
				//try to be more descriptive and get the IFile path which includes the project
136
				//try to be more descriptive and get the IFile path which includes the project
129
				IFile file = (IFile)(editorInput.getAdapter(IFile.class));
137
				IFile file = (IFile)(editorInput.getAdapter(IFile.class));
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/util/RenderedDiagramPrinter.java (-3 / +2 lines)
Lines 12-20 Link Here
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.util;
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.util;
13
13
14
import org.eclipse.draw2d.Graphics;
14
import org.eclipse.draw2d.Graphics;
15
16
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
15
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
17
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.DiagramPrinter;
16
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinter;
18
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
17
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
19
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.PrinterGraphics;
18
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.PrinterGraphics;
20
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
19
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
Lines 28-34 Link Here
28
 * @author cmahoney
27
 * @author cmahoney
29
 */
28
 */
30
public class RenderedDiagramPrinter
29
public class RenderedDiagramPrinter
31
	extends DiagramPrinter {
30
	extends SWTDiagramPrinter {
32
31
33
	/**
32
	/**
34
	 * Creates a new instance.
33
	 * Creates a new instance.
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/ActionsBlock.java (+103 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
13
14
import org.eclipse.gmf.runtime.common.ui.action.actions.IPrintActionHelper;
15
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
16
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.printpreview.PrintPreviewHelper;
17
import org.eclipse.gmf.runtime.diagram.ui.printing.render.actions.EnhancedPrintActionHelper;
18
import org.eclipse.gmf.runtime.diagram.ui.printing.render.internal.printpreview.RenderedPrintPreviewHelper;
19
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
20
import org.eclipse.swt.SWT;
21
import org.eclipse.swt.events.SelectionAdapter;
22
import org.eclipse.swt.events.SelectionEvent;
23
import org.eclipse.swt.widgets.Button;
24
import org.eclipse.swt.widgets.Composite;
25
import org.eclipse.swt.widgets.Control;
26
27
/**
28
 * A section of the JPS print dialog that handles extra actions. In this case,
29
 * we contribute print preview capabilities.
30
 * 
31
 * @author Christian Damus (cdamus)
32
 * @author James Bruck (jbruck)
33
 */
34
class ActionsBlock extends DialogBlock {
35
	private final PrintOptions options;
36
37
	private Button printPreview;
38
	private PrintPreviewHelper printPreviewHelper;
39
	private IPrintActionHelper printActionHelper;
40
41
	
42
	ActionsBlock(IDialogUnitConverter dluConverter, PrintOptions options) {
43
		super(dluConverter);
44
		this.options = options;
45
	}
46
47
	/*
48
	 * (non-Javadoc)
49
	 * 
50
	 * @see org.eclipse.gmf.runtime.common.ui.printing.internal.dialogs.DialogBlock#createContents(org.eclipse.swt.widgets.Composite)
51
	 */
52
	public Control createContents(Composite parent) {
53
		printPreview = new Button(parent, SWT.PUSH);
54
		printPreview.setData(new Integer(2));
55
		printPreview
56
				.setText(DiagramUIPrintingMessages.JPSPrintDialog_Button_PrintPreview);
57
58
		printPreview.addSelectionListener(new SelectionAdapter() {
59
			public void widgetSelected(SelectionEvent event) {
60
				buttonPressed(((Integer) event.widget.getData()).intValue());
61
			}
62
		});
63
		layoutVerticalIndent(layoutAlignLeft(printPreview));
64
65
		return printPreview;
66
	}
67
68
	/**
69
	 * Bring up the print preview with printing disabled.
70
	 * 
71
	 * @param buttonId
72
	 */
73
	protected void buttonPressed(int buttonId) {
74
		switch (buttonId) {
75
		case -1:
76
			break;
77
		default:
78
			getPrintPreviewHelper().enablePrinting(false);
79
		    getPrintPreviewHelper().doPrintPreview(getPrintActionHelper());
80
		}
81
	}
82
83
	/**
84
	 * Return the print preview helper responsible for performing the print
85
	 * preview.
86
	 * 
87
	 * @return PrintPreviewHelper the print preview helper.
88
	 */
89
	private PrintPreviewHelper getPrintPreviewHelper() {
90
		if (printPreviewHelper == null) {
91
			printPreviewHelper = new RenderedPrintPreviewHelper();
92
		}		
93
		return printPreviewHelper;
94
	}
95
96
	private IPrintActionHelper getPrintActionHelper() {
97
		if (printActionHelper == null) {
98
			printActionHelper = new EnhancedPrintActionHelper();
99
		}
100
		return printActionHelper;
101
	}
102
103
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/PrinterBlock.java (+293 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
13
14
import java.util.List;
15
import java.util.Locale;
16
17
import javax.print.DocFlavor;
18
import javax.print.PrintService;
19
import javax.print.PrintServiceLookup;
20
import javax.print.attribute.AttributeSet;
21
import javax.print.attribute.HashPrintServiceAttributeSet;
22
import javax.print.attribute.PrintServiceAttributeSet;
23
import javax.print.attribute.standard.PrinterLocation;
24
import javax.print.attribute.standard.PrinterMakeAndModel;
25
import javax.print.attribute.standard.PrinterMessageFromOperator;
26
import javax.print.attribute.standard.PrinterName;
27
import javax.print.attribute.standard.PrinterState;
28
29
import org.eclipse.core.databinding.DataBindingContext;
30
import org.eclipse.core.databinding.beans.BeansObservables;
31
import org.eclipse.core.databinding.observable.Realm;
32
import org.eclipse.core.databinding.observable.value.IObservableValue;
33
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
34
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintDestination;
35
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
36
import org.eclipse.jface.databinding.viewers.ViewersObservables;
37
import org.eclipse.jface.viewers.ComboViewer;
38
import org.eclipse.jface.viewers.ISelectionChangedListener;
39
import org.eclipse.jface.viewers.IStructuredContentProvider;
40
import org.eclipse.jface.viewers.LabelProvider;
41
import org.eclipse.jface.viewers.SelectionChangedEvent;
42
import org.eclipse.jface.viewers.StructuredSelection;
43
import org.eclipse.jface.viewers.Viewer;
44
import org.eclipse.swt.events.SelectionAdapter;
45
import org.eclipse.swt.events.SelectionEvent;
46
import org.eclipse.swt.widgets.Button;
47
import org.eclipse.swt.widgets.Composite;
48
import org.eclipse.swt.widgets.Control;
49
import org.eclipse.swt.widgets.Label;
50
51
/**
52
 * A section of the JPS print dialog that adds printer options.
53
 * 
54
 * @author Christian Damus (cdamus)
55
 * @author James Bruck (jbruck)
56
 */
57
class PrinterBlock extends DialogBlock {
58
	private final DataBindingContext bindings;
59
	private final PrintOptions options;
60
61
	private List<PrintDestination> destinations = new java.util.ArrayList<PrintDestination>();
62
63
	private ComboViewer combo;
64
65
	private Label resultStatusLabel;
66
	private Label resultTypeLabel;
67
	private Label resultWhereLabel;
68
	private Label resultCommentLabel;
69
70
	PrinterBlock(IDialogUnitConverter dluConverter,
71
			DataBindingContext bindings, PrintOptions options) {
72
73
		super(dluConverter);
74
75
		this.bindings = bindings;
76
		this.options = options;
77
	}
78
79
	/*
80
	 * (non-Javadoc)
81
	 * 
82
	 * @see org.eclipse.gmf.runtime.common.ui.printing.internal.dialogs.DialogBlock#createContents(org.eclipse.swt.widgets.Composite)
83
	 */
84
	public Control createContents(Composite parent) {
85
		final Realm realm = bindings.getValidationRealm();
86
87
		Composite result = group(parent,
88
				DiagramUIPrintingMessages.JPSPrintDialog_Printer);
89
		layout(result, 3);
90
91
		label(result, DiagramUIPrintingMessages.JPSPrintDialog_Name);
92
		combo = combo(result);
93
		//
94
		// The JPS API does not correctly return the printer status
95
		// information under windows. These options will be temporarily disabled
96
		// until a workaround can be discovered.
97
		//
98
		
99
		// combo.addSelectionChangedListener(new ISelectionChangedListener() {
100
		//
101
		// public void selectionChanged(SelectionChangedEvent event) {
102
		// if (event != null) {
103
		// handlePrinterSelectionChanged(event);
104
		// }
105
		// }
106
		//		});
107
108
		layoutFillHorizontal(combo.getControl());
109
110
		Button propertiesButton = button(result,
111
				DiagramUIPrintingMessages.JPSPrintDialog_Properties);
112
		propertiesButton.setEnabled(false);
113
114
		propertiesButton.addSelectionListener(new SelectionAdapter() {
115
			public void widgetSelected(SelectionEvent e) {
116
				// TODO: Introduce new dialog in phase 2
117
			}
118
		});
119
120
		IObservableValue destination = BeansObservables.observeValue(realm,
121
				options, PrintOptions.PROPERTY_DESTINATION);
122
		bindings.bindValue(ViewersObservables.observeSingleSelection(combo),
123
				destination, null, null);
124
		
125
		// Label statusLabel = label(result, "Status:");
126
		// layoutAlignLeft(statusLabel);
127
		// resultStatusLabel = label(result, "");
128
		// layoutFillHorizontal(layoutSpanHorizontal(resultStatusLabel, 2));
129
		//				
130
		// Label typeLabel = label(result, "Type:");
131
		// layoutAlignLeft(typeLabel);
132
		// resultTypeLabel = label(result, "");
133
		// layoutFillHorizontal(layoutSpanHorizontal(resultTypeLabel, 2));
134
		// 
135
		// Label whereLabel = label(result, "Where:");
136
		// layoutAlignLeft(whereLabel);
137
		// resultWhereLabel = label(result, "");
138
		// layoutFillHorizontal(layoutSpanHorizontal(resultWhereLabel, 2));
139
		// 
140
		// Label commentLabel = label(result, "Comment:");
141
		// layoutAlignLeft(commentLabel);
142
		// resultCommentLabel = label(result, "");
143
		// layoutFillHorizontal(resultCommentLabel);
144
145
		Button printToFile = check(result,
146
				DiagramUIPrintingMessages.JPSPrintDialog_PrintToFile);
147
		layoutSpanHorizontal(printToFile, 3);
148
149
		// TODO: implement in phase 2
150
		printToFile.setEnabled(false);
151
152
		init();
153
154
		return result;
155
	}
156
157
	/**
158
	 * When the printer selection has changed, we update the status information.
159
	 * The print service API does not currently update the status correctly in Windows
160
	 * 
161
	 * This will be re-enabled when a workaround for obtaining printer attributes will 
162
	 * be discovered.
163
	 * 
164
	 * @param selectionChangedEvent
165
	 */
166
	private void handlePrinterSelectionChanged(
167
			SelectionChangedEvent selectionChangedEvent) {
168
169
		StructuredSelection selection = (StructuredSelection) selectionChangedEvent
170
				.getSelection();
171
172
		if (selection != null) {
173
			PrintDestination destination = (PrintDestination) selection
174
					.getFirstElement();
175
			if (destination != null) {
176
177
				String printerName = destination.getName();
178
179
				AttributeSet attributes = new HashPrintServiceAttributeSet(
180
						new PrinterName(printerName, Locale.getDefault()));
181
182
				PrintService[] services = PrintServiceLookup
183
						.lookupPrintServices(
184
								DocFlavor.SERVICE_FORMATTED.PRINTABLE,
185
								attributes);
186
187
				PrintService printService = services[0];
188
189
				PrintServiceAttributeSet printServiceAttributes = printService
190
						.getAttributes();
191
192
				PrinterState printerState = (PrinterState) printServiceAttributes
193
						.get(PrinterState.class);
194
195
				PrinterLocation printerLocation = (PrinterLocation) printServiceAttributes
196
						.get(PrinterLocation.class);
197
198
				PrinterMakeAndModel printerMakeAndModel = (PrinterMakeAndModel) printServiceAttributes
199
						.get(PrinterMakeAndModel.class);
200
201
				PrinterMessageFromOperator printerComment = (PrinterMessageFromOperator) printServiceAttributes
202
						.get(PrinterMessageFromOperator.class);
203
204
				if (printerState != null) {
205
					resultStatusLabel.setText(printerState.getName());
206
				}
207
				if (printerLocation != null) {
208
					resultWhereLabel.setText(printerLocation.getName());
209
				}
210
				if (printerComment != null) {
211
					resultCommentLabel.setText(printerComment.getName());
212
				}
213
				if (printerMakeAndModel != null) {
214
					resultTypeLabel.setText(printerMakeAndModel.getName());
215
				}
216
			}
217
		}
218
	}
219
220
	/**
221
	 * At initialization time, we lookup all the print services and select the default one.
222
	 */
223
	private void init() {
224
		PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
225
				null, null);
226
		PrintService defaultPrintService = PrintServiceLookup
227
				.lookupDefaultPrintService();
228
229
		for (PrintService printService : printServices) {
230
			destinations.add(new PrintDestination(printService.getName()));
231
		}
232
		
233
		PrintDestination defaultPrintDestination = getPrinterByName(defaultPrintService.getName());
234
235
		combo.setContentProvider(new PrinterContentProvider());
236
		combo.setLabelProvider(new PrinterLabelProvider());
237
238
		initializePrinterCombo(defaultPrintDestination);
239
	}
240
241
	/**
242
	 * Initialize the list of printers.
243
     *
244
	 * @param selection
245
	 */
246
	private void initializePrinterCombo(PrintDestination selection) {
247
		combo.setInput(destinations);
248
		combo.setSelection(new StructuredSelection(selection));
249
	}
250
251
	/**
252
	 * 
253
	 * @param name
254
	 * @return
255
	 */
256
	private PrintDestination getPrinterByName(String name) {
257
258
		PrintDestination result = null;
259
		for (PrintDestination printDestination : destinations) {
260
			if (printDestination.getName().equals(name)) {
261
				result = printDestination;
262
				break;
263
			}
264
		}
265
		return result;
266
	}
267
268
	/**
269
	 * A helper class used to retrieve label text
270
	 * 
271
	 * @author Christian Damus (cdamus)
272
	 * @author James Bruck (jbruck)
273
	 */
274
	private class PrinterContentProvider implements IStructuredContentProvider {
275
		public Object[] getElements(Object inputElement) {
276
			return destinations.toArray();
277
		}
278
279
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
280
			// input never changes
281
		}
282
283
		public void dispose() {
284
			// nothing to dispose
285
		}
286
	}
287
288
	private class PrinterLabelProvider extends LabelProvider {
289
		public String getText(Object element) {
290
			return ((PrintDestination) element).getName();
291
		}
292
	}
293
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/util/PrintHelper.java (+138 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
13
14
package org.eclipse.gmf.runtime.diagram.ui.printing.render.util;
15
16
import java.util.List;
17
18
import org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper;
19
import org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs.JPSPrintDialog;
20
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
21
import org.eclipse.jface.dialogs.IDialogConstants;
22
import org.eclipse.swt.printing.PrinterData;
23
import org.eclipse.ui.PlatformUI;
24
25
/**
26
 * Default implementation of a print-helper.
27
 * 
28
 * @author Christian W. Damus (cdamus)
29
 */
30
public class PrintHelper implements IPrintHelper {
31
	private final PrintOptions options = new PrintOptions();
32
33
	public PrintHelper() {
34
		initPrintOptions();
35
	}
36
37
	/**
38
	 * Initialize the default options.
39
	 */
40
	private void initPrintOptions() {
41
		options.setPercentScaling(true);
42
		options.setScaleFactor(100);
43
		options.setFitToPagesWidth(1);
44
		options.setFitToPagesHeight(1);
45
46
		options.setAllPages(true);
47
		options.setRangeFrom(1);
48
		options.setRangeTo(1);
49
50
		options.setCopies(1);
51
		options.setCollate(false);
52
	}
53
54
	/*
55
	 * (non-Javadoc)
56
	 * @see org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper#openPrintDlg(java.util.List)
57
	 */
58
	public PrinterData openPrintDlg(List diagramList) {
59
		PrinterData result = null;
60
		JPSPrintDialog dlg = new JPSPrintDialog(PlatformUI.getWorkbench()
61
				.getActiveWorkbenchWindow(), options);
62
63
		if (dlg.open() == IDialogConstants.OK_ID) {
64
			if (options.getDestination() != null) {
65
				result = options.getDestination().getPrinterData();
66
			}
67
		} else {
68
			// revert
69
			initPrintOptions();
70
		}
71
		return result;
72
	}
73
74
	public boolean getDlgCollate() {
75
		return options.isCollate();
76
	}
77
78
	public int getDlgNumberOfCopies() {
79
		return options.getCopies();
80
	}
81
82
	public int getDlgPagesFrom() {
83
		return options.getRangeFrom();
84
	}
85
86
	public int getDlgPagesTo() {
87
		return options.getRangeTo();
88
	}
89
90
	public boolean getDlgPrintRangeAll() {
91
		return options.isAllPages();
92
	}
93
94
	public boolean getDlgPrintRangePages() {
95
		return !getDlgPrintRangeAll();
96
	}
97
98
	public int getDlgScaleFitToM() {
99
		return options.getFitToPagesWidth();
100
	}
101
102
	public int getDlgScaleFitToN() {
103
		return options.getFitToPagesHeight();
104
	}
105
106
	public int getDlgScalePercent() {
107
		return options.isPercentScaling() ? options.getScaleFactor() : -1;
108
	}
109
110
	public void setDlgOrientation(boolean landscape) {
111
		// TODO Auto-generated method stub
112
	}
113
114
	public void setDlgPaperSize(int index, double width, double length) {
115
		// TODO Auto-generated method stub
116
	}
117
118
	public boolean getDlgDiagramPrintRangeCurrent() {
119
		// TODO Not supported by the JPS dialog
120
		return true;
121
	}
122
123
	public boolean getDlgDiagramPrintRangeSelection() {
124
		// TODO Not supported by the JPS dialog
125
		return false;
126
	}
127
128
	public boolean isDlgDiagramSelected(int index) {
129
		// TODO Not supported by the JPS dialog
130
		return false;
131
	}
132
133
	public boolean getDlgDiagramPrintRangeAll() {
134
		// TODO Not supported by the JPS dialog
135
		return false;
136
	}
137
138
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/ScalingBlock.java (+114 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
13
14
import org.eclipse.core.databinding.DataBindingContext;
15
import org.eclipse.core.databinding.beans.BeansObservables;
16
import org.eclipse.core.databinding.observable.Realm;
17
import org.eclipse.core.databinding.observable.value.ComputedValue;
18
import org.eclipse.core.databinding.observable.value.IObservableValue;
19
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
20
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
21
import org.eclipse.jface.databinding.swt.SWTObservables;
22
import org.eclipse.swt.SWT;
23
import org.eclipse.swt.widgets.Button;
24
import org.eclipse.swt.widgets.Composite;
25
import org.eclipse.swt.widgets.Control;
26
import org.eclipse.swt.widgets.Text;
27
28
29
/**
30
 * A section of the JPS print dialog that adds scaling support.
31
 * 
32
 * @author Christian Damus (cdamus)
33
 * @author James Bruck (jbruck)
34
 */
35
class ScalingBlock extends DialogBlock {
36
	private final DataBindingContext bindings;
37
	private final PrintOptions options;
38
39
	ScalingBlock(IDialogUnitConverter dluConverter,
40
			DataBindingContext bindings, PrintOptions options) {
41
		super(dluConverter);
42
43
		this.bindings = bindings;
44
		this.options = options;
45
	}
46
47
	/*
48
	 * (non-Javadoc)
49
	 * @see org.eclipse.gmf.runtime.common.ui.printing.internal.dialogs.DialogBlock#createContents(org.eclipse.swt.widgets.Composite)
50
	 */
51
	public Control createContents(Composite parent) {
52
		final Realm realm = bindings.getValidationRealm();
53
54
		Composite result = group(parent,
55
				DiagramUIPrintingMessages.JPSPrintDialog_Scaling);
56
		layout(result, 5);
57
58
		Button adjustRadio = radio(result,
59
				DiagramUIPrintingMessages.JPSPrintDialog_Adjust);
60
		layoutSpanHorizontal(adjustRadio, 2);
61
		Text textScale = text(result, 20);
62
		layoutSpanHorizontal(blank(result), 2);
63
64
		final IObservableValue scalingValue = BeansObservables.observeValue(
65
				realm, options, PrintOptions.PROPERTY_PERCENT_SCALING);
66
		
67
		bindings.bindValue(SWTObservables.observeSelection(adjustRadio),
68
				scalingValue, null, null);
69
70
		bindings.bindValue(SWTObservables.observeText(textScale, SWT.Modify),
71
				BeansObservables.observeValue(realm, options,
72
						PrintOptions.PROPERTY_SCALE_FACTOR), null, null);
73
		bindings.bindValue(SWTObservables.observeEnabled(textScale),
74
				scalingValue, null, null);
75
76
		Button fitToRadio = radio(result,
77
				DiagramUIPrintingMessages.JPSPrintDialog_FitTo);
78
		
79
		IObservableValue fitToValue = new ComputedValue(realm) {
80
			protected Object calculate() {
81
				return Boolean.valueOf(!((Boolean) scalingValue.getValue())
82
						.booleanValue());
83
			}
84
		};
85
		
86
		bindings.bindValue(SWTObservables.observeSelection(fitToRadio),
87
				fitToValue, null, null);
88
89
		layoutHorizontalIndent(layoutAlignRight(label(result,
90
				DiagramUIPrintingMessages.JPSPrintDialog_PagesWide)));
91
		
92
		Text textWide = text(result, 20);
93
		
94
		layoutHorizontalIndent(layoutAlignRight(label(result,
95
				DiagramUIPrintingMessages.JPSPrintDialog_PagesTall)));
96
		Text textTall = text(result, 20);
97
98
		bindings.bindValue(SWTObservables.observeText(textWide, SWT.Modify),
99
				BeansObservables.observeValue(realm, options,
100
						PrintOptions.PROPERTY_FIT_TO_WIDTH), null, null);
101
		
102
		bindings.bindValue(SWTObservables.observeEnabled(textWide), fitToValue,
103
				null, null);
104
		
105
		bindings.bindValue(SWTObservables.observeText(textTall, SWT.Modify),
106
				BeansObservables.observeValue(realm, options,
107
						PrintOptions.PROPERTY_FIT_TO_HEIGHT), null, null);
108
		
109
		bindings.bindValue(SWTObservables.observeEnabled(textTall), fitToValue,
110
				null, null);
111
112
		return result;
113
	}
114
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/model/PrintModelElement.java (+73 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.model;
13
14
import java.beans.PropertyChangeListener;
15
import java.beans.PropertyChangeSupport;
16
17
/**
18
 * This class is used as the model in the MVC infrastructure required for databindings
19
 * used with the JPS dialog.
20
 *
21
 * @author Christian Damus (cdamus)
22
 * @author James Bruck (jbruck)
23
 */
24
abstract class PrintModelElement {
25
    protected final PropertyChangeSupport bean = new PropertyChangeSupport(this);
26
    
27
    public PrintModelElement() {
28
        super();
29
    }
30
31
    public void addPropertyChangeListener(PropertyChangeListener listener) {
32
        bean.addPropertyChangeListener(listener);
33
    }
34
35
    public void addPropertyChangeListener(String propertyName,
36
            PropertyChangeListener listener) {
37
        bean.addPropertyChangeListener(propertyName, listener);
38
    }
39
40
    public PropertyChangeListener[] getPropertyChangeListeners() {
41
        return bean.getPropertyChangeListeners();
42
    }
43
44
    public PropertyChangeListener[] getPropertyChangeListeners(
45
            String propertyName) {
46
        return bean.getPropertyChangeListeners(propertyName);
47
    }
48
49
    public boolean hasListeners(String propertyName) {
50
        return bean.hasListeners(propertyName);
51
    }
52
53
    public void removePropertyChangeListener(PropertyChangeListener listener) {
54
        bean.removePropertyChangeListener(listener);
55
    }
56
57
    public void removePropertyChangeListener(String propertyName,
58
            PropertyChangeListener listener) {
59
        bean.removePropertyChangeListener(propertyName, listener);
60
    }
61
    
62
    protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
63
        bean.firePropertyChange(propertyName, oldValue, newValue);
64
    }
65
    
66
    protected void firePropertyChange(String propertyName, int oldValue, int newValue) {
67
        bean.firePropertyChange(propertyName, oldValue, newValue);
68
    }
69
    
70
    protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
71
        bean.firePropertyChange(propertyName, oldValue, newValue);
72
    }
73
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/internal/JPSDiagramPrinter.java (+547 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.internal;
13
14
import java.awt.print.PageFormat;
15
import java.awt.print.PrinterException;
16
import java.util.Iterator;
17
import java.util.List;
18
import java.util.Locale;
19
20
import javax.print.Doc;
21
import javax.print.DocFlavor;
22
import javax.print.DocPrintJob;
23
import javax.print.PrintException;
24
import javax.print.PrintService;
25
import javax.print.PrintServiceLookup;
26
import javax.print.SimpleDoc;
27
import javax.print.attribute.AttributeSet;
28
import javax.print.attribute.HashDocAttributeSet;
29
import javax.print.attribute.HashPrintRequestAttributeSet;
30
import javax.print.attribute.HashPrintServiceAttributeSet;
31
import javax.print.attribute.PrintRequestAttributeSet;
32
import javax.print.attribute.standard.Copies;
33
import javax.print.attribute.standard.JobName;
34
import javax.print.attribute.standard.MediaSizeName;
35
import javax.print.attribute.standard.OrientationRequested;
36
import javax.print.attribute.standard.PrinterName;
37
import javax.print.attribute.standard.SheetCollate;
38
39
import org.eclipse.draw2d.Graphics;
40
import org.eclipse.draw2d.geometry.Rectangle;
41
import org.eclipse.gef.LayerConstants;
42
import org.eclipse.gef.RootEditPart;
43
import org.eclipse.gmf.runtime.common.core.util.Log;
44
import org.eclipse.gmf.runtime.common.core.util.Trace;
45
import org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper;
46
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
47
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
48
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
49
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
50
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper;
51
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupPageType;
52
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper.PageMargins;
53
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
54
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
55
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
56
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingDebugOptions;
57
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingPlugin;
58
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingStatusCodes;
59
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
60
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.DiagramPrinter;
61
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.PrintHelperUtil;
62
import org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil;
63
import org.eclipse.gmf.runtime.diagram.ui.util.DiagramEditorUtil;
64
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.ScaledGraphics;
65
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
66
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
67
import org.eclipse.gmf.runtime.draw2d.ui.render.awt.internal.graphics.GraphicsToGraphics2DAdaptor;
68
import org.eclipse.gmf.runtime.notation.Diagram;
69
import org.eclipse.jface.dialogs.MessageDialog;
70
import org.eclipse.jface.preference.IPreferenceStore;
71
import org.eclipse.jface.resource.JFaceResources;
72
import org.eclipse.swt.graphics.FontData;
73
import org.eclipse.swt.graphics.Point;
74
import org.eclipse.swt.widgets.Display;
75
import org.eclipse.swt.widgets.Shell;
76
77
/**
78
 * This class supports printing using the Java Print Service API.
79
 * The logic of calculating page break etc. follows that of SWT printing
80
 * but the actual printing is done asynchronously in a platform independent way.
81
 * 
82
 * Much of the paging code was derived from the previous DiagramPrinter.
83
 *
84
 * @author James Bruck (jbruck)
85
 */
86
public class JPSDiagramPrinter extends DiagramPrinter implements
87
		java.awt.print.Printable {
88
89
	private PrintService printService;
90
	private PageData[] pages;
91
	private IPrintHelper printHelper;
92
93
	public JPSDiagramPrinter(PreferencesHint preferencesHint, IMapMode mm) {
94
		super(preferencesHint, mm);
95
		this.preferencesHint = preferencesHint;
96
		this.mapMode = mm;
97
	}
98
99
	public JPSDiagramPrinter(PreferencesHint preferencesHint) {
100
		this(preferencesHint, MapModeUtil.getMapMode());
101
	}
102
103
	public void setPrintHelper(IPrintHelper helper) {
104
		this.printHelper = helper;
105
	}
106
107
	/**
108
	 * Create a new print service given a printer name.
109
	 * 
110
	 * @param printerName
111
	 */
112
	public void setPrinter(String printerName) {
113
		AttributeSet attributes = new HashPrintServiceAttributeSet(
114
				new PrinterName(printerName, Locale.getDefault()));
115
		PrintService[] services = PrintServiceLookup.lookupPrintServices(
116
				DocFlavor.SERVICE_FORMATTED.PRINTABLE, attributes);
117
		printService = services[0];
118
	}
119
120
	/**
121
	 * Prints the contents of the diagram editor part.
122
	 */
123
	public void run() {
124
125
		Iterator<Diagram> it = diagrams.iterator();
126
		Shell shell = new Shell();
127
		try {
128
			while (it.hasNext()) {
129
				Diagram diagram = it.next();
130
				DiagramEditor openedDiagramEditor = DiagramEditorUtil
131
						.findOpenedDiagramEditorForID(ViewUtil
132
								.getIdStr(diagram));
133
				DiagramEditPart dgrmEP = openedDiagramEditor == null ? PrintHelperUtil
134
						.createDiagramEditPart(diagram, preferencesHint, shell)
135
						: openedDiagramEditor.getDiagramEditPart();
136
137
				boolean loadedPreferences = openedDiagramEditor != null
138
						|| PrintHelperUtil.initializePreferences(dgrmEP,
139
								preferencesHint);
140
141
				RootEditPart rep = dgrmEP.getRoot();
142
				if (rep instanceof DiagramRootEditPart) {
143
					this.mapMode = ((DiagramRootEditPart) rep).getMapMode();
144
				}
145
146
				IPreferenceStore preferenceStore = ((DiagramGraphicalViewer) dgrmEP
147
						.getViewer()).getWorkspaceViewerPreferenceStore();
148
				if (preferenceStore
149
						.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
150
					if (dgrmEP.getDiagramPreferencesHint().getPreferenceStore() != null) {
151
						preferenceStore = (IPreferenceStore) dgrmEP
152
								.getDiagramPreferencesHint()
153
								.getPreferenceStore();
154
					}
155
				}
156
				doPrintDiagram(printService.createPrintJob(), dgrmEP,
157
						loadedPreferences, preferenceStore);
158
			}
159
		} finally {
160
			dispose();
161
			shell.dispose();
162
		}
163
	}
164
165
	/**
166
	 * Print the diagram figure using specified scale factor.
167
	 * 
168
	 * @param dgrmEP The diagram edit part to print
169
	 * @param loadedPreferences true if existing prefs could be loaded
170
     * 		successfully, false if not and defaults are being used.  This parameter
171
     * 		is important to obtain the correct page break bounds.
172
	 * @param fPreferences the preferenceStore that could either contain
173
     * 		existing preferences or defaults
174
	 */
175
	protected void printToScale(DiagramEditPart dgrmEP,
176
			boolean loadedPreferences, IPreferenceStore fPreferences) {
177
178
		Rectangle figureBounds = PrintHelperUtil.getPageBreakBounds(dgrmEP,
179
				loadedPreferences);
180
181
		org.eclipse.draw2d.geometry.Point pageBounds = PageInfoHelper
182
				.getPageSize(fPreferences, getMapMode());
183
		//
184
		// Translate to offset initial figure position
185
		//
186
		translated = new Point((int) (-figureBounds.x * userScale),
187
				(int) (-figureBounds.y * userScale));
188
		//
189
		// Calculate the number of page rows and columns
190
		//
191
		int numRows = 0, numCols = 0;
192
193
		PageMargins margins = adjustMarginsToScale(PageInfoHelper
194
				.getPageMargins(fPreferences, getMapMode()));
195
196
		FontData fontData = JFaceResources.getDefaultFont().getFontData()[0];
197
198
		org.eclipse.draw2d.geometry.Point pageCount = getPageCount(dgrmEP,
199
				figureBounds, pageBounds, true);
200
201
		numCols = pageCount.x;
202
		numRows = pageCount.y;
203
204
		int row = 1, col = 1, finalRow = 0, finalColumn = 0;
205
206
		List<PageData> pageList = new java.util.ArrayList<PageData>();
207
208
		if (this.printRangePageSelection) {
209
			//
210
			// Print only the pages specified in the page range...
211
			//
212
			row = calculateRowFromPage(this.pageFrom, numCols);
213
			col = calculateColumnFromPage(this.pageFrom, numCols, row);
214
215
			finalRow = calculateRowFromPage(this.pageTo, numCols);
216
			finalColumn = calculateColumnFromPage(this.pageTo, numCols,
217
					finalRow);
218
		}
219
		//
220
		// Print the pages in row, column order
221
		//
222
		for (; row <= numRows; row++) {
223
			for (; col <= numCols; col++) {
224
225
				pageList.add(new PageData(pageList.size(), row, col, dgrmEP,
226
						figureBounds, margins, fontData, fPreferences));
227
228
				if (row == finalRow && col == finalColumn
229
						&& this.printRangePageSelection == true) {
230
					break;
231
				}
232
			}
233
			if (row == finalRow && col == finalColumn
234
					&& this.printRangePageSelection == true) {
235
				break;
236
			}
237
			col = 1;
238
		}
239
		pages =  pageList.toArray(new PageData[pageList.size()]);
240
	}
241
242
	/**
243
	 * Print the diagram figure to fit the number and rows and columns
244
     * specified by the user.
245
	 * 
246
	 * @param dgrmEP The diagram edit part to print
247
	 * @param loadedPreferences true if existing prefs could be loaded
248
     * 		successfully, false if not and defaults are being used.  This parameter
249
     * 		is important to obtain the correct page break bounds.
250
	 * @param fPreferences the preferenceStore that could either contain
251
     * 		existing preferences or defaults
252
	 */
253
	protected void printToPages(DiagramEditPart dgrmEP,
254
			boolean loadedPreferences, IPreferenceStore fPreferences) {
255
256
		Rectangle figureBounds = PrintHelperUtil.getPageBreakBounds(dgrmEP,
257
				loadedPreferences);
258
259
		org.eclipse.draw2d.geometry.Point pageBounds = PageInfoHelper
260
				.getPageSize(fPreferences, getMapMode());
261
		org.eclipse.draw2d.geometry.Point pageCount = getPageCount(dgrmEP,
262
				figureBounds, pageBounds, false);
263
		int numCols = pageCount.x;
264
		int numRows = pageCount.y;
265
266
		float actualWidth = 0;
267
		float actualHeight = 0;
268
		if (this.rows == 1 && this.columns == 1 && fitToPage) {
269
			figureBounds = dgrmEP.getChildrenBounds();
270
			actualWidth = figureBounds.width;
271
			actualHeight = figureBounds.height;
272
		} else {
273
			actualWidth = numCols * pageBounds.x;
274
			actualHeight = numRows * pageBounds.y;
275
		}
276
277
		int totalHeight = (this.rows * pageBounds.y);
278
		int totalWidth = (this.columns * pageBounds.x);
279
280
		float vScale = totalHeight / actualHeight;
281
		float hScale = totalWidth / actualWidth;
282
283
		this.userScale = Math.min(hScale, vScale);
284
285
		PageMargins margins = adjustMarginsToScale(PageInfoHelper
286
				.getPageMargins(fPreferences, getMapMode()));
287
288
		translated = new Point((int) (-figureBounds.x * userScale),
289
				(int) (-figureBounds.y * userScale));
290
291
		FontData fontData = JFaceResources.getDefaultFont().getFontData()[0];
292
293
		int row = 1, col = 1, finalRow = 0, finalColumn = 0;
294
		List<PageData> pageList = new java.util.ArrayList<PageData>();
295
296
		if (this.printRangePageSelection) {
297
			//
298
			// Print only the pages specified in the page range
299
			// this corresponds to the physical pages, not the print range of
300
			// pages on one physical page.
301
			//
302
			row = calculateRowFromPage(this.pageFrom, this.columns);
303
			col = calculateColumnFromPage(this.pageFrom, this.columns, row);
304
305
			finalRow = calculateRowFromPage(this.pageTo, this.columns);
306
			finalColumn = calculateColumnFromPage(this.pageTo, this.columns,
307
					finalRow);
308
		}
309
310
		for (; row <= rows; row++) {
311
			for (; col <= columns; col++) {
312
313
				pageList.add(new PageData(pageList.size(), row, col, dgrmEP,
314
						figureBounds, margins, fontData, fPreferences));
315
316
				if (row == finalRow && col == finalColumn
317
						&& this.printRangePageSelection == true) {
318
					break;
319
				}
320
			}
321
			if (row == finalRow && col == finalColumn
322
					&& this.printRangePageSelection == true) {
323
				break;
324
			}
325
			col = 1;
326
		}
327
		pages = pageList.toArray(new PageData[pageList.size()]);
328
	}
329
330
	/*
331
	 * (non-Javadoc)
332
	 * 
333
	 * @see java.awt.print.Printable#print(java.awt.Graphics,
334
	 *      java.awt.print.PageFormat, int)
335
	 */
336
	public int print(java.awt.Graphics printGraphics, PageFormat pageFormat,
337
			int pageIndex) throws PrinterException {
338
339
		if (pageIndex >= pages.length) {
340
			return java.awt.print.Printable.NO_SUCH_PAGE;
341
		}
342
		
343
		try {
344
			swtGraphics = new GraphicsToGraphics2DAdaptor(
345
					(java.awt.Graphics2D) printGraphics, new Rectangle(0, 0,
346
							(int) pageFormat.getWidth(), (int) pageFormat
347
									.getHeight()));
348
			
349
			graphics = createMapModeGraphics(new ScaledGraphics(swtGraphics));
350
			//
351
			// Take into account screen display DPI and the graphic DPI
352
			// 72.0 DPI is an AWT constant @see java.awt.Graphics2D
353
			//
354
			graphics.scale(72.0 / display_dpi.x);
355
356
			drawPage(pages[pageIndex]);
357
		} finally {
358
			dispose();
359
		}
360
361
		return java.awt.print.Printable.PAGE_EXISTS;
362
	}
363
	
364
	/**
365
	 * Set printing options in a format that is suitable for the Java print service
366
	 * 
367
	 * @param jobName  The printer job name to use
368
	 * @param fPreferences obtain page information from preferences
369
	 * @return PrintRequestAttribute set suitable for Java print service
370
	 */
371
	protected PrintRequestAttributeSet initializePrintOptions(
372
			String jobName,
373
			IPreferenceStore fPreferences) {
374
375
		PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
376
377
		if (fPreferences
378
				.getBoolean(WorkspaceViewerProperties.PREF_USE_PORTRAIT)) {
379
			printRequestAttributeSet.add(OrientationRequested.PORTRAIT);
380
		} else {
381
			printRequestAttributeSet.add(OrientationRequested.LANDSCAPE);
382
		}
383
384
		String pageSize = fPreferences
385
				.getString(WorkspaceViewerProperties.PREF_PAGE_SIZE);
386
387
		if (pageSize.compareToIgnoreCase(PageSetupPageType.LETTER.getName()) == 0) {
388
			printRequestAttributeSet.add(MediaSizeName.NA_LETTER);
389
		} else if (pageSize.compareToIgnoreCase(PageSetupPageType.LEGAL
390
				.getName()) == 0) {
391
			printRequestAttributeSet.add(MediaSizeName.NA_LEGAL);
392
		} else if (pageSize.compareToIgnoreCase(PageSetupPageType.EXECUTIVE
393
				.getName()) == 0) {
394
			printRequestAttributeSet.add(MediaSizeName.EXECUTIVE);
395
		} else if (pageSize.compareToIgnoreCase(PageSetupPageType.A3.getName()) == 0) {
396
			printRequestAttributeSet.add(MediaSizeName.ISO_A3);
397
		} else if (pageSize.compareToIgnoreCase(PageSetupPageType.A4.getName()) == 0) {
398
			printRequestAttributeSet.add(MediaSizeName.ISO_A4);
399
		} else if (pageSize.compareToIgnoreCase(PageSetupPageType.B4.getName()) == 0) {
400
			printRequestAttributeSet.add(MediaSizeName.ISO_B4);
401
		} else if (pageSize.compareToIgnoreCase(PageSetupPageType.B5.getName()) == 0) {
402
			printRequestAttributeSet.add(MediaSizeName.ISO_B5);
403
		}
404
405
		printRequestAttributeSet.add(new Copies(printHelper
406
				.getDlgNumberOfCopies()));
407
408
		if (printHelper.getDlgCollate()) {
409
			printRequestAttributeSet.add(SheetCollate.COLLATED);
410
		} else {
411
			printRequestAttributeSet.add(SheetCollate.UNCOLLATED);
412
		}
413
414
		printRequestAttributeSet.add(new JobName(jobName, Locale.getDefault()));
415
416
		return printRequestAttributeSet;
417
	}
418
419
	/**
420
	 * Prints to scale or prints to rows x columns pages
421
	 * 
422
	 * @param printJob
423
	 * @param diagramEditPart
424
	 * @param loadedPreferences
425
	 * @param fPreferences
426
	 */
427
	protected void doPrintDiagram(DocPrintJob printJob,
428
			DiagramEditPart diagramEditPart, boolean loadedPreferences,
429
			IPreferenceStore fPreferences) {
430
431
		if (isScaledPercent) {
432
			printToScale(diagramEditPart, loadedPreferences, fPreferences);
433
		} else {
434
			printToPages(diagramEditPart, loadedPreferences, fPreferences);
435
		}
436
437
		PrintRequestAttributeSet printRequestAttributeSet = initializePrintOptions(
438
				diagramEditPart
439
				.getDiagramView().getName(), fPreferences);
440
441
		Doc doc = new SimpleDoc(this, DocFlavor.SERVICE_FORMATTED.PRINTABLE,
442
				new HashDocAttributeSet());
443
444
		try {
445
			printJob.print(doc, printRequestAttributeSet);
446
		} catch (PrintException e) {
447
448
			Trace.catching(DiagramPrintingPlugin.getInstance(),
449
					DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
450
					DiagramPrinterUtil.class, e.getMessage(), e);
451
			Log.warning(DiagramPrintingPlugin.getInstance(),
452
					DiagramPrintingStatusCodes.RESOURCE_FAILURE,
453
					e.getMessage(), e);
454
455
			MessageDialog
456
					.openError(
457
							Display.getDefault().getActiveShell(),
458
							DiagramUIPrintingMessages.JPSDiagramPrinterUtil_ErrorTitle,
459
							DiagramUIPrintingMessages.JPSDiagramPrinterUtil_ErrorMessage);
460
		}
461
	}
462
463
	/**
464
	 * 
465
	 * This method paints a portion of the diagram. (The area painted
466
     * representing one page.)
467
     * 
468
	 * @param page indicates which page to print.
469
	 */
470
	protected void drawPage(PageData page) {
471
		this.graphics.pushState();
472
473
		internalDrawPage(page.diagram, page.bounds, page.preferences,
474
				page.margins, graphics, page.row, page.column, false);
475
		
476
		// TODO: Re-enable printing of header and footer in phase 2
477
		this.graphics.popState();
478
	}
479
480
	/**
481
	 * The real rendering of the page to the given graphical object occurs here.
482
	 */
483
	protected void internalDrawPage(DiagramEditPart dgrmEP,
484
			Rectangle figureBounds, IPreferenceStore fPreferences,
485
			PageMargins margins, Graphics g, int rowIndex, int colIndex,
486
			boolean RTL_ENABLED) {
487
488
		org.eclipse.draw2d.geometry.Point pageSize = PageInfoHelper
489
				.getPageSize(fPreferences, false, getMapMode());
490
491
		int width = pageSize.x, height = pageSize.y;
492
493
		g.pushState();
494
495
		g.translate(translated.x, translated.y);
496
		g.scale(userScale);
497
498
		int translateX = -(width * (colIndex - 1));
499
		int translateY = -(height * (rowIndex - 1));
500
501
		int scaledTranslateX = (int) (translateX / userScale);
502
		int scaledTranslateY = (int) (translateY / userScale);
503
504
		int scaledWidth = (int) (width / userScale);
505
		int scaledHeight = (int) (height / userScale);
506
507
		if (RTL_ENABLED) {
508
			scaledTranslateX += (margins.left * (colIndex - 1))
509
					+ (margins.right * (colIndex));
510
			scaledTranslateY += ((margins.top * rowIndex) + (margins.bottom * (rowIndex - 1)));
511
		} else {
512
			scaledTranslateX += ((margins.left * colIndex) + (margins.right * (colIndex - 1)));
513
			scaledTranslateY += ((margins.top * rowIndex) + (margins.bottom * (rowIndex - 1)));
514
		}
515
516
		g.translate(scaledTranslateX, scaledTranslateY);
517
518
		Rectangle clip = new Rectangle(
519
				(scaledWidth - margins.left - margins.right) * (colIndex - 1)
520
						+ figureBounds.x, (scaledHeight
521
						- margins.bottom - margins.top)
522
						* (rowIndex - 1) + figureBounds.y, scaledWidth
523
						- margins.right - margins.left, scaledHeight
524
						- margins.top - margins.bottom);
525
		g.clipRect(clip);
526
527
		dgrmEP.getLayer(LayerConstants.PRINTABLE_LAYERS).paint(g);
528
529
		g.popState();
530
	}
531
	
532
	/**
533
	 *  Adjust the page margins to be compatible with the user scale.
534
	 *  
535
	 * @param margins the page margins to adjust
536
	 * @return adjusted page margins
537
	 */
538
	private PageMargins adjustMarginsToScale(PageMargins margins) {
539
		margins.left /= userScale;
540
		margins.top /= userScale;
541
		margins.bottom /= userScale;
542
		margins.right /= userScale;
543
544
		return margins;
545
	}
546
547
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/internal/JPSDiagramPrinterHelper.java (+137 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
package org.eclipse.gmf.runtime.diagram.ui.printing.render.internal;
12
13
import java.util.ArrayList;
14
import java.util.Collections;
15
import java.util.List;
16
import java.util.Map;
17
18
import org.eclipse.gmf.runtime.common.core.util.Log;
19
import org.eclipse.gmf.runtime.common.core.util.Trace;
20
import org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper;
21
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
22
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
23
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingDebugOptions;
24
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingPlugin;
25
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingStatusCodes;
26
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
27
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.DiagramPrinterHelper;
28
import org.eclipse.gmf.runtime.diagram.ui.printing.render.util.PrintHelper;
29
import org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil;
30
import org.eclipse.gmf.runtime.notation.Diagram;
31
import org.eclipse.jface.dialogs.MessageDialog;
32
import org.eclipse.swt.printing.PrinterData;
33
import org.eclipse.swt.widgets.Display;
34
import org.eclipse.ui.IEditorPart;
35
36
/**
37
 * Utility for using the DiagramPrinter to print diagrams after displaying
38
 * a print dialog box to the user.  Diagrams are printed using the
39
 * DiagramPrinter and respect the settings chosen by the user in the print
40
 * dialog. 
41
 * 
42
 * This class uses the java print service API to accomplish its task.
43
 * This class was derived from @see org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil
44
 * 
45
 * This class is subject to change/removal during phase 2 of printing enhancements
46
 * 
47
 */
48
public class JPSDiagramPrinterHelper extends DiagramPrinterHelper {
49
50
	private static JPSDiagramPrinterHelper jpsDiagramPrinterHelper;
51
52
	public static JPSDiagramPrinterHelper getDiagramPrinterHelper() {
53
		if(jpsDiagramPrinterHelper == null){
54
			jpsDiagramPrinterHelper = new JPSDiagramPrinterHelper();
55
		}
56
		return jpsDiagramPrinterHelper;
57
	}
58
59
	/**
60
	 * Prevent instantiation.
61
	 */
62
	private JPSDiagramPrinterHelper() {
63
	}
64
65
	/**
66
	 * Opens up the print diagrams dialog, allows the user to choose the
67
	 * settings, and prints.
68
	 * 
69
	 * @param editorPart
70
	 *            current editor part
71
	 * @param diagramMap
72
	 *            map of String names to Diagram objects. Should be initialized
73
	 *            by caller of this method. String names will show up in the
74
	 *            print dialog that allows the user to choose which diagrams to
75
	 *            print from a list.
76
	 * @param jpsDiagramPrinter
77
	 *            the diagram printer that does the work of actually printing the diagrams
78
	 */
79
	public void printWithSettings(IEditorPart editorPart,
80
			Map<String, Diagram> diagramMap, JPSDiagramPrinter jpsDiagramPrinter) {
81
82
		try {
83
			IPrintHelper helper = new PrintHelper();
84
			List<String> diagramNames = new ArrayList<String>(diagramMap
85
					.keySet());
86
87
			PrinterData printerData = collectPrintInformation(
88
					jpsDiagramPrinter, helper, diagramNames, editorPart,
89
					diagramMap);
90
91
			if (printerData != null) {
92
93
				jpsDiagramPrinter.setPrinter(printerData.name);
94
				jpsDiagramPrinter.setDisplayDPI(Display.getDefault().getDPI());
95
				jpsDiagramPrinter.setPrintHelper(helper);
96
97
				if (helper.getDlgDiagramPrintRangeCurrent()) {
98
					DiagramEditPart dgrmEP = ((IDiagramWorkbenchPart) editorPart)
99
							.getDiagramEditPart();
100
					assert dgrmEP != null;
101
					jpsDiagramPrinter
102
							.setDiagrams(Collections.singletonList(dgrmEP
103
									.getDiagramView().getDiagram()));
104
				} else if (helper.getDlgDiagramPrintRangeAll()) {
105
					jpsDiagramPrinter.setDiagrams(diagramMap.values());
106
				} else if (helper.getDlgDiagramPrintRangeSelection()) {
107
					Object obj;
108
					List<Diagram> list = new ArrayList<Diagram>();
109
					for (int i = 0; i < diagramNames.size(); i++) {
110
						if (helper.isDlgDiagramSelected(i)) {
111
							obj = diagramMap.get(diagramNames.get(i));
112
							if (obj instanceof Diagram) {
113
								list.add((Diagram) obj);
114
							}
115
						}
116
					}
117
					jpsDiagramPrinter.setDiagrams(list);
118
				}
119
				printDiagrams(jpsDiagramPrinter, helper);
120
			}
121
		} catch (Throwable e) {
122
123
			Trace.catching(DiagramPrintingPlugin.getInstance(),
124
					DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
125
					DiagramPrinterUtil.class, e.getMessage(), e);
126
			Log.warning(DiagramPrintingPlugin.getInstance(),
127
					DiagramPrintingStatusCodes.RESOURCE_FAILURE,
128
					e.getMessage(), e);
129
130
			MessageDialog
131
					.openError(
132
							Display.getDefault().getActiveShell(),
133
							DiagramUIPrintingMessages.JPSDiagramPrinterUtil_ErrorTitle,
134
							DiagramUIPrintingMessages.JPSDiagramPrinterUtil_ErrorMessage);
135
		}
136
	}
137
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/model/PrintDestination.java (+73 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.model;
13
14
import org.eclipse.swt.printing.PrinterData;
15
16
17
/**
18
 * This class is used as part of the infrastructure required for data-bindings
19
 * used with the JPS dialog.
20
 *
21
 * @author Christian Damus (cdamus)
22
 * @author James Bruck (jbruck)
23
 */
24
public class PrintDestination extends PrintModelElement {
25
    public static String PROPERTY_NAME = "name"; //$NON-NLS-1$
26
    public static String PROPERTY_PRINT_TO_FILE = "printToFile"; //$NON-NLS-1$
27
    public static String PROPERTY_FILE_PATH = "filePath"; //$NON-NLS-1$
28
    
29
   
30
    protected PrinterData printerData;
31
           
32
    public PrinterData getPrinterData(){
33
    	if(printerData == null){
34
    		printerData = new PrinterData();
35
    	}
36
    	return printerData;
37
    }
38
    
39
    public PrintDestination(String printerName) {
40
    	getPrinterData().name = printerName;
41
    }
42
    
43
    public String getName() {
44
        return getPrinterData().name;
45
    }
46
    
47
    public void setName(String name) {
48
        String oldName = this.getPrinterData().name;
49
        this.getPrinterData().name = name;
50
        firePropertyChange(PROPERTY_NAME, oldName, name);
51
    }
52
    
53
    public boolean isPrintToFile() {
54
        return getPrinterData().printToFile;
55
    }
56
    
57
    public void setPrintToFile(boolean printToFile) {
58
        boolean oldToFile = getPrinterData().printToFile;
59
        getPrinterData().printToFile = printToFile;
60
        firePropertyChange(PROPERTY_PRINT_TO_FILE, oldToFile, printToFile);
61
    }
62
    
63
    public String getFilePath() {
64
        return getPrinterData().fileName;
65
    }
66
    
67
    public void setFilePath(String filePath) {
68
        String oldPath = getPrinterData().fileName;
69
        getPrinterData().fileName = filePath;
70
        firePropertyChange(PROPERTY_FILE_PATH, oldPath, filePath);
71
    }
72
      
73
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/RangeBlock.java (+101 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
13
14
import org.eclipse.core.databinding.DataBindingContext;
15
import org.eclipse.core.databinding.beans.BeansObservables;
16
import org.eclipse.core.databinding.observable.Realm;
17
import org.eclipse.core.databinding.observable.value.ComputedValue;
18
import org.eclipse.core.databinding.observable.value.IObservableValue;
19
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
20
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
21
import org.eclipse.jface.databinding.swt.SWTObservables;
22
import org.eclipse.swt.SWT;
23
import org.eclipse.swt.widgets.Button;
24
import org.eclipse.swt.widgets.Composite;
25
import org.eclipse.swt.widgets.Control;
26
import org.eclipse.swt.widgets.Text;
27
28
29
/**
30
 * A section of the JPS print dialog that adds range checking.
31
 * 
32
 * @author Christian Damus (cdamus)
33
 * @author James Bruck (jbruck)
34
 */
35
class RangeBlock extends DialogBlock {
36
	private final DataBindingContext bindings;
37
	private final PrintOptions options;
38
39
	RangeBlock(IDialogUnitConverter dluConverter, DataBindingContext bindings,
40
			PrintOptions options) {
41
		super(dluConverter);
42
43
		this.bindings = bindings;
44
		this.options = options;
45
	}
46
47
	/*
48
	 * (non-Javadoc)
49
	 * @see org.eclipse.gmf.runtime.common.ui.printing.internal.dialogs.DialogBlock#createContents(org.eclipse.swt.widgets.Composite)
50
	 */
51
	public Control createContents(Composite parent) {
52
		final Realm realm = bindings.getValidationRealm();
53
54
		Composite result = group(parent,
55
				DiagramUIPrintingMessages.JPSPrintDialog_PrintRange);
56
		layout(result, 4);
57
58
		Button allRadio = radio(result,
59
				DiagramUIPrintingMessages.JPSPrintDialog_All);
60
		layoutSpanHorizontal(allRadio, 4);
61
62
		final IObservableValue allValue = BeansObservables.observeValue(realm,
63
				options, PrintOptions.PROPERTY_ALL_PAGES);
64
		bindings.bindValue(SWTObservables.observeSelection(allRadio), allValue,
65
				null, null);
66
67
		Button rangeRadio = radio(result,
68
				DiagramUIPrintingMessages.JPSPrintDialog_Pages);
69
		layoutSpanHorizontal(rangeRadio, 4);
70
71
		IObservableValue rangeValue = new ComputedValue(realm) {
72
			protected Object calculate() {
73
				return Boolean.valueOf(!((Boolean) allValue.getValue())
74
						.booleanValue());
75
			}
76
		};
77
		bindings.bindValue(SWTObservables.observeSelection(rangeRadio),
78
				rangeValue, null, null);
79
80
		layoutHorizontalIndent(label(result,
81
				DiagramUIPrintingMessages.JPSPrintDialog_From));
82
		Text textFrom = text(result, 20);
83
		
84
		layoutHorizontalIndent(label(result,
85
				DiagramUIPrintingMessages.JPSPrintDialog_To));
86
		Text textTo = text(result, 20);
87
88
		bindings.bindValue(SWTObservables.observeText(textFrom, SWT.Modify),
89
				BeansObservables.observeValue(realm, options,
90
						PrintOptions.PROPERTY_RANGE_FROM), null, null);
91
		bindings.bindValue(SWTObservables.observeEnabled(textFrom), rangeValue,
92
				null, null);
93
		bindings.bindValue(SWTObservables.observeText(textTo, SWT.Modify),
94
				BeansObservables.observeValue(realm, options,
95
						PrintOptions.PROPERTY_RANGE_TO), null, null);
96
		bindings.bindValue(SWTObservables.observeEnabled(textTo), rangeValue,
97
				null, null);
98
99
		return result;
100
	}
101
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/internal/PageData.java (+57 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
13
package org.eclipse.gmf.runtime.diagram.ui.printing.render.internal;
14
15
import org.eclipse.draw2d.geometry.Rectangle;
16
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
17
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper.PageMargins;
18
import org.eclipse.jface.preference.IPreferenceStore;
19
import org.eclipse.swt.graphics.FontData;
20
21
 
22
 /**
23
 * PageData is used during the JPS printing process to cache
24
 * information that will be used later when printing is invoked
25
 * through a call-back mechanism.
26
 *  
27
 * @author Christian Damus (cdamus)
28
 * @author James Bruck (jbruck)
29
 *
30
 */
31
 
32
public class PageData {
33
	
34
	final int index;
35
	final int row;
36
	final int column;
37
38
	final DiagramEditPart diagram;
39
	final Rectangle bounds;
40
	final PageMargins margins;
41
	final FontData font;
42
	final IPreferenceStore preferences;
43
44
	PageData(int index, int row, int column, DiagramEditPart diagram,
45
			Rectangle bounds, PageMargins margins, FontData font,
46
			IPreferenceStore preferences) {
47
		
48
		this.index = index;
49
		this.row = row;
50
		this.column = column;
51
		this.diagram = diagram;
52
		this.bounds = bounds;
53
		this.margins = margins;
54
		this.font = font;
55
		this.preferences = preferences;
56
	}
57
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/model/PrintOptions.java (+154 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.model;
13
14
15
/**
16
 * This class is used as part of the infrastructure required for data-bindings
17
 * used with the JPS dialog.
18
 *
19
 * @author Christian Damus (cdamus)
20
 * @author James Bruck (jbruck)
21
 */
22
public class PrintOptions extends PrintModelElement {
23
    public static String PROPERTY_DESTINATION = "destination"; //$NON-NLS-1$
24
    
25
    public static String PROPERTY_PERCENT_SCALING = "percentScaling"; //$NON-NLS-1$
26
    public static String PROPERTY_SCALE_FACTOR = "scaleFactor"; //$NON-NLS-1$
27
    public static String PROPERTY_FIT_TO_WIDTH = "fitToPagesWidth"; //$NON-NLS-1$
28
    public static String PROPERTY_FIT_TO_HEIGHT = "fitToPagesHeight"; //$NON-NLS-1$
29
    
30
    public static String PROPERTY_ALL_PAGES = "allPages"; //$NON-NLS-1$
31
    public static String PROPERTY_RANGE_FROM = "rangeFrom"; //$NON-NLS-1$
32
    public static String PROPERTY_RANGE_TO = "rangeTo"; //$NON-NLS-1$
33
    
34
    public static String PROPERTY_COPIES = "copies"; //$NON-NLS-1$
35
    public static String PROPERTY_COLLATE = "collate"; //$NON-NLS-1$
36
37
    private PrintDestination destination;
38
    
39
    private boolean percentScaling;
40
    private int scaleFactor;
41
    private int fitToPagesWidth;
42
    private int fitToPagesHeight;
43
    
44
    private boolean allPages;
45
    private int rangeFrom;
46
    private int rangeTo;
47
    
48
    private int copies;
49
    private boolean collate;
50
    
51
    public PrintOptions() {
52
        super();
53
    }
54
55
    public PrintDestination getDestination() {
56
        return destination;
57
    }
58
    
59
    public void setDestination(PrintDestination destination) {
60
        PrintDestination oldDestination = this.destination;
61
        this.destination = destination;
62
        firePropertyChange(PROPERTY_DESTINATION, oldDestination, destination);
63
    }
64
    
65
    public boolean isPercentScaling() {
66
        return percentScaling;
67
    }
68
    
69
    public void setPercentScaling(boolean percentScaling) {
70
        boolean oldScaling = this.percentScaling;
71
        this.percentScaling = percentScaling;
72
        firePropertyChange(PROPERTY_PERCENT_SCALING, oldScaling, percentScaling);
73
    }
74
    
75
    public int getScaleFactor() {
76
        return scaleFactor;
77
    }
78
    
79
    public void setScaleFactor(int scaleFactor) {
80
        int oldFactor = this.scaleFactor;
81
        this.scaleFactor = scaleFactor;
82
        firePropertyChange(PROPERTY_SCALE_FACTOR, oldFactor, scaleFactor);
83
    }
84
    
85
    public int getFitToPagesWidth() {
86
        return fitToPagesWidth;
87
    }
88
    
89
    public void setFitToPagesWidth(int fitToPagesWidth) {
90
        int oldWidth = this.fitToPagesWidth;
91
        this.fitToPagesWidth = fitToPagesWidth;
92
        firePropertyChange(PROPERTY_FIT_TO_WIDTH, oldWidth, fitToPagesWidth);
93
    }
94
95
    public int getFitToPagesHeight() {
96
        return fitToPagesHeight;
97
    }
98
    
99
    public void setFitToPagesHeight(int fitToPagesHeight) {
100
        int oldHeight = this.fitToPagesHeight;
101
        this.fitToPagesHeight = fitToPagesHeight;
102
        firePropertyChange(PROPERTY_FIT_TO_HEIGHT, oldHeight, fitToPagesHeight);
103
    }
104
105
    public boolean isAllPages() {
106
        return allPages;
107
    }
108
    
109
    public void setAllPages(boolean allPages) {
110
        boolean oldAll = this.allPages;
111
        this.allPages = allPages;
112
        firePropertyChange(PROPERTY_ALL_PAGES, oldAll, allPages);
113
    }
114
115
    public int getRangeFrom() {
116
        return rangeFrom;
117
    }
118
    
119
    public void setRangeFrom(int rangeFrom) {
120
        int oldFrom = this.rangeFrom;
121
        this.rangeFrom = rangeFrom;
122
        firePropertyChange(PROPERTY_RANGE_FROM, oldFrom, rangeFrom);
123
    }
124
    
125
    public int getRangeTo() {
126
        return rangeTo;
127
    }
128
    
129
    public void setRangeTo(int rangeTo) {
130
        int oldTo = this.rangeTo;
131
        this.rangeTo = rangeTo;
132
        firePropertyChange(PROPERTY_RANGE_TO, oldTo, rangeTo);
133
    }
134
    
135
    public int getCopies() {
136
        return copies;
137
    }
138
    
139
    public void setCopies(int copies) {
140
        int oldCopies = this.copies;
141
        this.copies = copies;
142
        firePropertyChange(PROPERTY_COPIES, oldCopies, copies);
143
    }
144
    
145
    public boolean isCollate() {
146
        return collate;
147
    }
148
    
149
    public void setCollate(boolean collate) {
150
        boolean oldCollate = this.collate;
151
        this.collate = collate;
152
        firePropertyChange(PROPERTY_COLLATE, oldCollate, collate);
153
    }
154
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/DialogBlock.java (+236 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
13
14
import org.eclipse.jface.viewers.ComboViewer;
15
import org.eclipse.swt.SWT;
16
import org.eclipse.swt.layout.GridData;
17
import org.eclipse.swt.layout.GridLayout;
18
import org.eclipse.swt.widgets.Button;
19
import org.eclipse.swt.widgets.Composite;
20
import org.eclipse.swt.widgets.Control;
21
import org.eclipse.swt.widgets.Group;
22
import org.eclipse.swt.widgets.Label;
23
import org.eclipse.swt.widgets.Shell;
24
import org.eclipse.swt.widgets.Spinner;
25
import org.eclipse.swt.widgets.Text;
26
27
/**
28
 * Intended to be used as a base for other specializing dialog blocks.
29
 * Provides common layout functionality
30
 *
31
 * @author Christian Damus (cdamus)
32
 * @author James Bruck (jbruck)
33
 */
34
abstract class DialogBlock {
35
	private final IDialogUnitConverter dluConverter;
36
37
	DialogBlock(IDialogUnitConverter dluConverter) {
38
		this.dluConverter = dluConverter;
39
	}
40
41
	protected Shell getShell() {
42
		return dluConverter.getShell();
43
	}
44
45
	
46
	static Composite layout(Composite composite, int columns) {
47
		GridLayout g = new GridLayout(columns, false);
48
		g.marginLeft = 6;
49
		g.marginRight = 6;
50
		g.marginTop = 6;
51
		g.marginBottom = 3;
52
		composite.setLayout(g);
53
54
		return composite;
55
	}
56
57
	GridData getLayoutData(Control control) {
58
		GridData result = (GridData) control.getLayoutData();
59
60
		if (result == null) {
61
			result = new GridData();
62
			control.setLayoutData(result);
63
		}
64
65
		return result;
66
	}
67
68
	Control layoutFillHorizontal(Control control) {
69
		layoutFillHorizontal(control, true);
70
71
		return control;
72
	}
73
74
	Control layoutFillHorizontal(Control control, boolean grab) {
75
		GridData data = getLayoutData(control);
76
77
		data.horizontalAlignment = SWT.FILL;
78
		data.grabExcessHorizontalSpace = grab;
79
80
		return control;
81
	}
82
83
	Control layoutFillVertical(Control control) {
84
		GridData data = getLayoutData(control);
85
86
		data.verticalAlignment = SWT.FILL;
87
		data.grabExcessVerticalSpace = true;
88
89
		return control;
90
	}
91
92
	Control layoutAlignLeft(Control control) {
93
		GridData data = getLayoutData(control);
94
95
		data.horizontalAlignment = SWT.BEGINNING;
96
		data.grabExcessHorizontalSpace = false;
97
98
		return control;
99
	}
100
101
	Control layoutAlignRight(Control control) {
102
		GridData data = getLayoutData(control);
103
104
		data.horizontalAlignment = SWT.END;
105
		data.grabExcessHorizontalSpace = false;
106
107
		return control;
108
	}
109
110
	Control layoutFillBoth(Control control) {
111
		GridData data = getLayoutData(control);
112
113
		data.horizontalAlignment = SWT.FILL;
114
		data.grabExcessHorizontalSpace = true;
115
		data.verticalAlignment = SWT.FILL;
116
		data.grabExcessVerticalSpace = true;
117
118
		return control;
119
	}
120
121
	Control layoutSpanHorizontal(Control control, int span) {
122
		GridData data = getLayoutData(control);
123
124
		data.horizontalSpan = span;
125
126
		return control;
127
	}
128
129
	Control layoutSpanVertical(Control control, int span) {
130
		GridData data = getLayoutData(control);
131
132
		data.verticalSpan = span;
133
134
		return control;
135
	}
136
137
	Control layoutHorizontalIndent(Control control) {
138
		layoutHorizontalIndent(control, 15);
139
140
		return control;
141
	}
142
143
	Control layoutHorizontalIndent(Control control, int inset) {
144
		GridData data = getLayoutData(control);
145
		data.horizontalIndent = inset;
146
147
		return control;
148
	}
149
150
	Control layoutVerticalIndent(Control control) {
151
		layoutVerticalIndent(control, 15);
152
153
		return control;
154
	}
155
156
	Control layoutVerticalIndent(Control control, int inset) {
157
		GridData data = getLayoutData(control);
158
		data.verticalIndent = inset;
159
160
		return control;
161
	}
162
163
	Control layoutWidth(Control control, int dlus) {
164
		if (dlus > 0) {
165
			GridData data = getLayoutData(control);
166
			data.widthHint = dluConverter.convertHorizontalDLUsToPixels(dlus);
167
		}
168
169
		return control;
170
	}
171
172
	Group group(Composite parent, String text) {
173
		Group result = new Group(parent, SWT.NONE);
174
		result.setText(text);
175
		layoutFillBoth(result);
176
		return result;
177
	}
178
179
	Label label(Composite parent, String text) {
180
		Label result = new Label(parent, SWT.NONE);
181
		result.setText(text);
182
		return result;
183
	}
184
185
	Text text(Composite parent, int width) {
186
		Text result = new Text(parent, SWT.SINGLE | SWT.BORDER);
187
		layoutFillHorizontal(result, false);
188
		layoutWidth(result, width);
189
190
		return result;
191
	}
192
193
	ComboViewer combo(Composite parent) {
194
		ComboViewer result = new ComboViewer(parent);
195
		return result;
196
	}
197
198
	Button button(Composite parent, String text) {
199
		Button result = new Button(parent, SWT.PUSH);
200
		result.setText(text);
201
		return result;
202
	}
203
204
	Button radio(Composite parent, String text) {
205
		Button result = new Button(parent, SWT.RADIO);
206
		result.setText(text);
207
		return result;
208
	}
209
210
	Button check(Composite parent, String text) {
211
		Button result = new Button(parent, SWT.CHECK);
212
		result.setText(text);
213
		return result;
214
	}
215
216
	Spinner spinner(Composite parent, int min, int max) {
217
		Spinner result = new Spinner(parent, SWT.BORDER);
218
		result.setMinimum(min);
219
		result.setMaximum(max);
220
221
		return result;
222
	}
223
224
	Control blank(Composite parent) {
225
		Label result = new Label(parent, SWT.NONE);
226
		return result;
227
	}
228
229
	public abstract Control createContents(Composite parent);
230
231
	public static interface IDialogUnitConverter {
232
		int convertHorizontalDLUsToPixels(int dlus);
233
234
		Shell getShell();
235
	}
236
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/CopiesBlock.java (+72 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
13
14
import org.eclipse.core.databinding.DataBindingContext;
15
import org.eclipse.core.databinding.beans.BeansObservables;
16
import org.eclipse.core.databinding.observable.Realm;
17
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
18
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
19
import org.eclipse.jface.databinding.swt.SWTObservables;
20
import org.eclipse.swt.widgets.Button;
21
import org.eclipse.swt.widgets.Composite;
22
import org.eclipse.swt.widgets.Control;
23
import org.eclipse.swt.widgets.Spinner;
24
25
26
/**
27
 * A section of the JPS print dialog that handles the number of copies of
28
 * a diagram to print.
29
 * 
30
 * @author Christian Damus (cdamus)
31
 * @author James Bruck (jbruck)
32
 */
33
class CopiesBlock extends DialogBlock {
34
	
35
    private final DataBindingContext bindings;
36
    private final PrintOptions options;
37
    
38
    CopiesBlock(IDialogUnitConverter dluConverter, DataBindingContext bindings,
39
            PrintOptions options) {
40
        super(dluConverter);
41
        
42
        this.bindings = bindings;
43
        this.options = options;
44
    }
45
    
46
    /*
47
     * (non-Javadoc)
48
     * @see org.eclipse.gmf.runtime.common.ui.printing.internal.dialogs.DialogBlock#createContents(org.eclipse.swt.widgets.Composite)
49
     */
50
    public Control createContents(Composite parent) {
51
        final Realm realm = bindings.getValidationRealm();
52
        
53
        Composite result = group(parent, DiagramUIPrintingMessages.JPSPrintDialog_Copies);
54
        layout(result, 2);
55
        
56
        label(result, DiagramUIPrintingMessages.JPSPrintDialog_NumberOfCopies);
57
        Spinner copiesSpinner = spinner(result, 1, 999);
58
        
59
        bindings.bindValue(SWTObservables.observeSelection(copiesSpinner),
60
            BeansObservables.observeValue(realm, options, PrintOptions.PROPERTY_COPIES),
61
            null, null);
62
        
63
        blank(result);
64
        Button collateCheck = check(result, DiagramUIPrintingMessages.JPSPrintDialog_Collate);
65
        
66
        bindings.bindValue(SWTObservables.observeSelection(collateCheck),
67
            BeansObservables.observeValue(realm, options, PrintOptions.PROPERTY_COLLATE),
68
            null, null);
69
        
70
        return result;
71
    }
72
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/render/dialogs/JPSPrintDialog.java (+158 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
13
14
package org.eclipse.gmf.runtime.diagram.ui.printing.render.dialogs;
15
16
import org.eclipse.core.databinding.DataBindingContext;
17
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
18
import org.eclipse.gmf.runtime.diagram.ui.printing.render.model.PrintOptions;
19
import org.eclipse.jface.databinding.swt.SWTObservables;
20
import org.eclipse.jface.dialogs.IDialogConstants;
21
import org.eclipse.jface.dialogs.TrayDialog;
22
import org.eclipse.jface.window.IShellProvider;
23
import org.eclipse.swt.SWT;
24
import org.eclipse.swt.widgets.Composite;
25
import org.eclipse.swt.widgets.Control;
26
import org.eclipse.swt.widgets.Shell;
27
28
29
/**
30
 * A dialog that supports platform independent printing based on the 
31
 * Java Printing Service API.
32
 * 
33
 * @author Christian Damus (cdamus)
34
 * @author James Bruck (jbruck)
35
 */
36
public class JPSPrintDialog
37
    extends TrayDialog {
38
39
    private DataBindingContext bindings;
40
    private final PrintOptions options;
41
    
42
    protected PrinterBlock printerBlock;
43
    protected ScalingBlock scalingBlock;
44
    private RangeBlock rangeBlock;
45
    private CopiesBlock copiesBlock;
46
    private ActionsBlock actionsBlock;
47
    
48
    private final DialogBlock.IDialogUnitConverter dluConverter =
49
        new DialogBlock.IDialogUnitConverter() {
50
        
51
        public int convertHorizontalDLUsToPixels(int dlus) {
52
            return JPSPrintDialog.this.convertHorizontalDLUsToPixels(dlus);
53
        }
54
        
55
        public Shell getShell() {
56
            return JPSPrintDialog.this.getShell();
57
        }};
58
    
59
    public JPSPrintDialog(IShellProvider parentShell, PrintOptions options) {
60
        super(parentShell);
61
        this.options = options;
62
    }
63
64
    public JPSPrintDialog(Shell shell, PrintOptions options) {
65
        super(shell);
66
        this.options = options;
67
    }
68
69
    protected void configureShell(Shell newShell) {
70
        super.configureShell(newShell);
71
        
72
        newShell.setText(DiagramUIPrintingMessages.JPSPrintDialog_Title);
73
    }
74
    
75
    /*
76
     * (non-Javadoc)
77
     * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
78
     */
79
    protected Control createDialogArea(Composite parent) {
80
        bindings = new DataBindingContext(SWTObservables.getRealm(parent.getDisplay()));
81
     
82
        Composite result = new Composite(parent,SWT.NONE);
83
        DialogBlock.layout(result, 2);
84
                      
85
        createPrinterBlockArea(result);
86
        createScalingBlockArea(result);
87
        createExtensibleBlockArea(result);
88
        createRangeBlockArea(result);
89
        createCopiesBlockArea(result);
90
        createActionsBlockArea(result);
91
                     
92
        return result;
93
    }
94
    
95
    protected void createPrinterBlockArea(Composite result) {
96
		printerBlock = new PrinterBlock(dluConverter, bindings, options);
97
		printerBlock.layoutSpanHorizontal(printerBlock.createContents(result),
98
				2);
99
	}
100
    
101
    protected void createScalingBlockArea(Composite result) {
102
    	 scalingBlock = new ScalingBlock(dluConverter, bindings, options);
103
         scalingBlock.layoutSpanHorizontal(scalingBlock.createContents(result), 2);
104
	}
105
    
106
    protected void createRangeBlockArea(Composite result) {
107
    	 rangeBlock = new RangeBlock(dluConverter, bindings, options);
108
         rangeBlock.createContents(result);
109
	}
110
    
111
    protected void createCopiesBlockArea(Composite result) {
112
    	  copiesBlock = new CopiesBlock(dluConverter, bindings, options);
113
          copiesBlock.createContents(result);
114
	}
115
    
116
    protected void createActionsBlockArea(Composite result) {
117
    	 actionsBlock = new ActionsBlock(dluConverter, options);
118
         actionsBlock.layoutSpanHorizontal(actionsBlock.createContents(result), 2);
119
	}
120
    
121
    protected void createExtensibleBlockArea(Composite result) {
122
    	  // meant to be overiden by subclasses to add additional blocks.
123
  	}
124
    
125
        
126
    protected void createButtonsForButtonBar(Composite parent) {
127
        createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
128
        createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
129
    }
130
    
131
    protected void buttonPressed(int buttonId) {
132
        switch (buttonId) {
133
            case -1:
134
                break;
135
            default:
136
                super.buttonPressed(buttonId);
137
        }
138
    }
139
    
140
    public boolean close() {
141
        bindings.dispose();
142
        return super.close();
143
    }
144
    
145
    protected void cancelPressed() {
146
        super.cancelPressed();
147
    }
148
    
149
    /**
150
     * Obtains the user's selected printing options, or <code>null</code> if
151
     * the user canceled the print operation.
152
     * 
153
     * @return the printing  options, or <code>null</code> if canceled
154
     */
155
    public PrintOptions getPrintOptions() {
156
        return options;
157
    }
158
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/internal/pagesetup/DefaultValues.java (-1 / +13 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2002, 2005 IBM Corporation and others.
2
 * Copyright (c) 2002, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 61-66 Link Here
61
	
61
	
62
	/** Represents default value for WorkspaceViewerProperties.PREF_MARGIN_RIGHT. */
62
	/** Represents default value for WorkspaceViewerProperties.PREF_MARGIN_RIGHT. */
63
	public static double DEFAULT_MARGIN_RIGHT = 0.5;
63
	public static double DEFAULT_MARGIN_RIGHT = 0.5;
64
			
65
	/** Enforce a minimum margin to take printer limitations into account */
66
	public static double MINIMUM_MARGIN_TOP = 0.2;
67
	
68
	/** Enforce a minimum margin to take printer limitations into account */
69
	public static double MINIMUM_MARGIN_BOTTOM = 0.2;
70
	
71
	/** Enforce a minimum margin to take printer limitations into account */
72
	public static double MINIMUM_MARGIN_LEFT = 0.2;
73
	
74
	/** Enforce a minimum margin to take printer limitations into account */
75
	public static double MINIMUM_MARGIN_RIGHT = 0.2;
64
	
76
	
65
	/**
77
	/**
66
	 * Returns locale specific page size.
78
	 * Returns locale specific page size.
(-)src/org/eclipse/gmf/runtime/diagram/ui/internal/dialogs/PageSetupConfigBlock.java (-10 / +102 lines)
Lines 12-22 Link Here
12
package org.eclipse.gmf.runtime.diagram.ui.internal.dialogs;
12
package org.eclipse.gmf.runtime.diagram.ui.internal.dialogs;
13
13
14
14
15
import java.awt.print.PageFormat;
16
import java.awt.print.Paper;
17
import java.awt.print.PrinterJob;
15
import java.text.ParseException;
18
import java.text.ParseException;
16
import java.util.ArrayList;
19
import java.util.ArrayList;
17
20
21
import org.eclipse.draw2d.geometry.PrecisionPoint;
22
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.DefaultValues;
23
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.ILabels;
24
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupPageType;
25
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupWidgetFactory;
26
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
27
import org.eclipse.gmf.runtime.diagram.ui.preferences.PrintingPreferencePage;
18
import org.eclipse.jface.preference.IPreferenceStore;
28
import org.eclipse.jface.preference.IPreferenceStore;
19
import org.eclipse.swt.SWT;
29
import org.eclipse.swt.SWT;
30
import org.eclipse.swt.events.FocusEvent;
31
import org.eclipse.swt.events.FocusListener;
20
import org.eclipse.swt.events.ModifyEvent;
32
import org.eclipse.swt.events.ModifyEvent;
21
import org.eclipse.swt.events.ModifyListener;
33
import org.eclipse.swt.events.ModifyListener;
22
import org.eclipse.swt.events.SelectionEvent;
34
import org.eclipse.swt.events.SelectionEvent;
Lines 33-45 Link Here
33
import org.eclipse.swt.widgets.TabItem;
45
import org.eclipse.swt.widgets.TabItem;
34
import org.eclipse.swt.widgets.Text;
46
import org.eclipse.swt.widgets.Text;
35
47
36
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.DefaultValues;
37
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.ILabels;
38
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupPageType;
39
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupWidgetFactory;
40
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
41
import org.eclipse.gmf.runtime.diagram.ui.preferences.PrintingPreferencePage;
42
43
import com.ibm.icu.text.NumberFormat;
48
import com.ibm.icu.text.NumberFormat;
44
49
45
/**
50
/**
Lines 388-394 Link Here
388
		}
393
		}
389
		
394
		
390
	}
395
	}
391
		
396
	
397
	/**
398
	 * Determine if the current set of units are in inches.
399
	 *  	
400
	 * @return true if the current units are in inches.
401
	 */
402
	private boolean isUnitsInInch() {
403
		return (fCurrentUnit.startsWith("inc")); //$NON-NLS-1$
404
	}
405
	
392
	/** 
406
	/** 
393
	 * Create part of PSDialog allowing the user to specify page margin values. 
407
	 * Create part of PSDialog allowing the user to specify page margin values. 
394
	 */
408
	 */
Lines 409-422 Link Here
409
		fLabelMarginRight = PageSetupWidgetFactory.createLabel(group, LABEL_MARGIN_RIGHT_INCHES);
423
		fLabelMarginRight = PageSetupWidgetFactory.createLabel(group, LABEL_MARGIN_RIGHT_INCHES);
410
		fTextMarginRight = PageSetupWidgetFactory.createTextMargin(group);
424
		fTextMarginRight = PageSetupWidgetFactory.createTextMargin(group);
411
        
425
        
426
		
427
		fTextMarginTop.addFocusListener(new FocusListener() {
428
429
			public void focusGained(FocusEvent e) {
430
				// do nothing.
431
			}
432
433
			public void focusLost(FocusEvent e) {
434
				double marginTop = getDblFromString(fTextMarginTop.getText());
435
				double minimumTop = DefaultValues.MINIMUM_MARGIN_TOP;
436
				if (!isUnitsInInch()) {
437
					marginTop = fConvertor.convertMilimToInches(marginTop);
438
					minimumTop = fConvertor.convertInchesToMilim(minimumTop);
439
				}
440
				if (marginTop < DefaultValues.MINIMUM_MARGIN_TOP) {
441
					fTextMarginTop.setText(fNumberFormat.format(minimumTop));
442
				}
443
			}
444
		});
412
		fTextMarginTop.addModifyListener(new ModifyListener() {
445
		fTextMarginTop.addModifyListener(new ModifyListener() {
413
			public void modifyText(ModifyEvent e) {
446
			public void modifyText(ModifyEvent e) {
414
				if (fTextMarginTop.isFocusControl()) {
447
				if (fTextMarginTop.isFocusControl()) {
415
					setOkButtonEnableStatus();
448
					setOkButtonEnableStatus();
416
				}
449
				}
417
			}
450
			}
451
			
452
		});
453
				
454
		fTextMarginBottom.addFocusListener(new FocusListener() {
455
			public void focusGained(FocusEvent e) {
456
				// do nothing.
457
			}
458
			/**
459
			 * Ensure we have minimum margins set.
460
			 */
461
			public void focusLost(FocusEvent e) {
462
				double marginBottom = getDblFromString(fTextMarginBottom.getText());
463
				double minimumBottom = DefaultValues.MINIMUM_MARGIN_BOTTOM;
464
				if (!isUnitsInInch()) {
465
					marginBottom = fConvertor.convertMilimToInches(marginBottom);
466
					minimumBottom = fConvertor.convertInchesToMilim(minimumBottom);
467
				}
468
				if (marginBottom < DefaultValues.MINIMUM_MARGIN_BOTTOM) {
469
					fTextMarginBottom.setText(fNumberFormat.format(minimumBottom));
470
				}
471
			}
418
		});
472
		});
419
		
420
		fTextMarginBottom.addModifyListener(new ModifyListener() {
473
		fTextMarginBottom.addModifyListener(new ModifyListener() {
421
			public void modifyText(ModifyEvent e) {
474
			public void modifyText(ModifyEvent e) {
422
				if (fTextMarginBottom.isFocusControl()) {
475
				if (fTextMarginBottom.isFocusControl()) {
Lines 425-430 Link Here
425
			}
478
			}
426
		});
479
		});
427
		
480
		
481
482
		fTextMarginLeft.addFocusListener(new FocusListener() {
483
			public void focusGained(FocusEvent e) {
484
				// do nothing.
485
			}
486
			/**
487
			 * Ensure we have minimum margins set.
488
			 */
489
			public void focusLost(FocusEvent e) {
490
				double marginLeft = getDblFromString(fTextMarginLeft.getText());
491
				double minimumLeft = DefaultValues.MINIMUM_MARGIN_LEFT;
492
				if (!isUnitsInInch()) {
493
					marginLeft = fConvertor.convertMilimToInches(marginLeft);
494
					minimumLeft = fConvertor.convertInchesToMilim(minimumLeft);
495
				}
496
				if (marginLeft < DefaultValues.MINIMUM_MARGIN_LEFT) {
497
					fTextMarginLeft.setText(fNumberFormat.format(minimumLeft));
498
				}
499
			}
500
		});
428
		fTextMarginLeft.addModifyListener(new ModifyListener() {
501
		fTextMarginLeft.addModifyListener(new ModifyListener() {
429
			public void modifyText(ModifyEvent e) {
502
			public void modifyText(ModifyEvent e) {
430
				if (fTextMarginLeft.isFocusControl()) {
503
				if (fTextMarginLeft.isFocusControl()) {
Lines 433-438 Link Here
433
			}
506
			}
434
		});
507
		});
435
		
508
		
509
		fTextMarginRight.addFocusListener(new FocusListener() {
510
			public void focusGained(FocusEvent e) {
511
				// do nothing.
512
			}
513
			/**
514
			 * Ensure we have minimum margins set.
515
			 */
516
			public void focusLost(FocusEvent e) {
517
				double marginRight = getDblFromString(fTextMarginRight.getText());
518
				double minimumRight = DefaultValues.MINIMUM_MARGIN_RIGHT;
519
				if (!isUnitsInInch()) {
520
					marginRight = fConvertor.convertMilimToInches(marginRight);
521
					minimumRight = fConvertor.convertInchesToMilim(minimumRight);
522
				}
523
				if (marginRight < DefaultValues.MINIMUM_MARGIN_RIGHT) {
524
					fTextMarginRight.setText(fNumberFormat.format(minimumRight));
525
				}
526
			}
527
		});
436
		fTextMarginRight.addModifyListener(new ModifyListener() {
528
		fTextMarginRight.addModifyListener(new ModifyListener() {
437
			public void modifyText(ModifyEvent e) {
529
			public void modifyText(ModifyEvent e) {
438
				if (fTextMarginRight.isFocusControl()) {
530
				if (fTextMarginRight.isFocusControl()) {
Lines 828-834 Link Here
828
			Button b = (Button) e.getSource();
920
			Button b = (Button) e.getSource();
829
			if (b.getSelection()) { 
921
			if (b.getSelection()) { 
830
				super.widgetSelected(e);
922
				super.widgetSelected(e);
831
				if (fCurrentUnit.startsWith("inc")) { //$NON-NLS-1$
923
				if (isUnitsInInch()) { 
832
					convertValuesToMillimetres();
924
					convertValuesToMillimetres();
833
					fCurrentUnit = "mil"; //$NON-NLS-1$
925
					fCurrentUnit = "mil"; //$NON-NLS-1$
834
				}
926
				}
(-)META-INF/MANIFEST.MF (-2 / +2 lines)
Lines 25-33 Link Here
25
 org.eclipse.gmf.runtime.diagram.ui.internal.figures;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
25
 org.eclipse.gmf.runtime.diagram.ui.internal.figures;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
26
 org.eclipse.gmf.runtime.diagram.ui.internal.handles;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
26
 org.eclipse.gmf.runtime.diagram.ui.internal.handles;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
27
 org.eclipse.gmf.runtime.diagram.ui.internal.l10n;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
27
 org.eclipse.gmf.runtime.diagram.ui.internal.l10n;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
28
 org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
28
 org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions,org.eclipse.gmf.runtime.diagram.ui.printing.render",
29
 org.eclipse.gmf.runtime.diagram.ui.internal.parts;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
29
 org.eclipse.gmf.runtime.diagram.ui.internal.parts;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
30
 org.eclipse.gmf.runtime.diagram.ui.internal.properties;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
30
 org.eclipse.gmf.runtime.diagram.ui.internal.properties;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions,org.eclipse.gmf.runtime.diagram.ui.printing.render",
31
 org.eclipse.gmf.runtime.diagram.ui.internal.requests;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
31
 org.eclipse.gmf.runtime.diagram.ui.internal.requests;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
32
 org.eclipse.gmf.runtime.diagram.ui.internal.resources;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
32
 org.eclipse.gmf.runtime.diagram.ui.internal.resources;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
33
 org.eclipse.gmf.runtime.diagram.ui.internal.ruler;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
33
 org.eclipse.gmf.runtime.diagram.ui.internal.ruler;x-friends:="org.eclipse.gmf.tests.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.render,org.eclipse.gmf.runtime.diagram.ui.providers.ide,org.eclipse.gmf.runtime.diagram.ui.providers,org.eclipse.gmf.runtime.diagram.ui.properties,org.eclipse.gmf.runtime.diagram.ui.printing,org.eclipse.gmf.runtime.diagram.ui.geoshapes,org.eclipse.gmf.runtime.diagram.ui,org.eclipse.gmf.runtime.diagram.ui.actions",
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/actions/PrintPreviewAction.java (-19 / +2 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2002, 2006 IBM Corporation and others.
2
 * Copyright (c) 2002, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 117-139 Link Here
117
	 */
117
	 */
118
	protected void setPrintPreviewHelper(PrintPreviewHelper printPreviewHelper) {
118
	protected void setPrintPreviewHelper(PrintPreviewHelper printPreviewHelper) {
119
		this.printPreviewHelper = printPreviewHelper;
119
		this.printPreviewHelper = printPreviewHelper;
120
	}
120
	}    
121
    
122
    
123
    //TODO: remove the following two methods when printing on
124
    //other platforms is supported.
125
126
    /**
127
     * Enable the menu item if Platform is running on Windows.
128
     */
129
    public boolean isEnabled() {
130
        return isWindows();
131
    }
132
    
121
    
133
    private boolean isWindows() {
134
        if (Platform.getOS() != null) 
135
            if (Platform.getOS().startsWith(Platform.OS_WIN32))
136
                return true;
137
        return false;
138
    }
139
}
122
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/actions/DefaultPrintActionHelper.java (-2 / +2 lines)
Lines 16-22 Link Here
16
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
16
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
17
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
17
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
18
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
18
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
19
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.DiagramPrinter;
19
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinter;
20
import org.eclipse.jface.dialogs.MessageDialog;
20
import org.eclipse.jface.dialogs.MessageDialog;
21
import org.eclipse.swt.SWT;
21
import org.eclipse.swt.SWT;
22
import org.eclipse.swt.printing.PrintDialog;
22
import org.eclipse.swt.printing.PrintDialog;
Lines 42-48 Link Here
42
	 *            the diagram printer that does the work of actually printing
42
	 *            the diagram printer that does the work of actually printing
43
	 *            the diagrams
43
	 *            the diagrams
44
	 */
44
	 */
45
	public static void doRun(IEditorPart editorPart, DiagramPrinter diagramPrinter) {
45
	public static void doRun(IEditorPart editorPart, SWTDiagramPrinter diagramPrinter) {
46
		// print the editor contents.
46
		// print the editor contents.
47
		final PrintDialog dialog =
47
		final PrintDialog dialog =
48
			new PrintDialog(editorPart.getSite().getShell(), SWT.NULL);
48
			new PrintDialog(editorPart.getSite().getShell(), SWT.NULL);
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/util/DiagramPrinterUtil.java (-243 / +10 lines)
Lines 11-88 Link Here
11
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.util;
12
package org.eclipse.gmf.runtime.diagram.ui.printing.util;
13
13
14
import java.text.ParseException;
15
import java.util.ArrayList;
16
import java.util.Collections;
17
import java.util.List;
18
import java.util.Map;
14
import java.util.Map;
19
15
20
import org.eclipse.gmf.runtime.common.core.util.Log;
16
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinter;
21
import org.eclipse.gmf.runtime.common.core.util.Trace;
17
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinterHelper;
22
import org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper;
23
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
24
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupPageType;
25
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
26
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
27
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
28
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
29
import org.eclipse.gmf.runtime.diagram.ui.printing.actions.DefaultPrintActionHelper;
30
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingDebugOptions;
31
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingPlugin;
32
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingStatusCodes;
33
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
34
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.DiagramPrinter;
35
import org.eclipse.gmf.runtime.notation.Diagram;
36
import org.eclipse.jface.dialogs.MessageDialog;
37
import org.eclipse.jface.preference.IPreferenceStore;
38
import org.eclipse.jface.util.Assert;
39
import org.eclipse.swt.printing.Printer;
40
import org.eclipse.swt.printing.PrinterData;
41
import org.eclipse.swt.widgets.Display;
42
import org.eclipse.ui.IEditorPart;
18
import org.eclipse.ui.IEditorPart;
43
19
44
import com.ibm.icu.text.NumberFormat;
45
46
/**
20
/**
47
 * Utility for using the DiagramPrinter to print diagrams after displaying
21
 * Utility for using the DiagramPrinter to print diagrams after displaying
48
 * a print dialog box to the user.  Diagrams are printed using the
22
 * a print dialog box to the user.  Diagrams are printed using the
49
 * DiagramPrinter and respect the settings chosen by the user in the print
23
 * DiagramPrinter and respect the settings chosen by the user in the print
50
 * dialog. 
24
 * dialog. 
51
 * 
25
 * 
26
 * This class now delegates its functionality to helpers that isolate out the 
27
 * printing via SWT printing. 
28
 * 
29
 * This class is subject to change/deprecation in phase 2 of the printing enhancements.
30
 * 
52
 * @author wdiu, Wayne Diu
31
 * @author wdiu, Wayne Diu
53
 */
32
 */
54
public class DiagramPrinterUtil {
33
public class DiagramPrinterUtil {
55
34
56
	/**
35
	/**
57
	 * Prints a diagram with the settings from the helper onto the printer
58
	 * 
59
	 * @param diagramPrinter
60
	 *            the diagram printer that does the work of actually printing the diagrams
61
	 * @param helper
62
	 *            IPrintHelper with the user's choice of settings
63
	 */
64
	private static void printDiagrams(DiagramPrinter diagramPrinter,
65
			IPrintHelper helper) {
66
        
67
        if (helper.getDlgPrintRangePages()) {
68
            diagramPrinter.setPrintRangePageSelection(true);
69
            diagramPrinter.setPrintRangePages(helper.getDlgPagesFrom(), helper.getDlgPagesTo());
70
            diagramPrinter.setFitToPage(false);
71
        }
72
        
73
		if (helper.getDlgScalePercent() == -1) {
74
            diagramPrinter.setColumns(helper.getDlgScaleFitToM());
75
			diagramPrinter.setRows(helper.getDlgScaleFitToN());
76
            diagramPrinter.setFitToPage(true);
77
		} else {
78
			diagramPrinter.setScaledPercent(helper.getDlgScalePercent());
79
            diagramPrinter.setFitToPage(false);
80
		}
81
82
		diagramPrinter.run();
83
	}
84
85
	/**
86
	 * Opens up the print diagrams dialog, allows the user to choose the
36
	 * Opens up the print diagrams dialog, allows the user to choose the
87
	 * settings, and prints.
37
	 * settings, and prints.
88
	 * 
38
	 * 
Lines 97-288 Link Here
97
	 *            the diagram printer that does the work of actually printing the diagrams
47
	 *            the diagram printer that does the work of actually printing the diagrams
98
	 */
48
	 */
99
	public static void printWithSettings(IEditorPart editorPart,
49
	public static void printWithSettings(IEditorPart editorPart,
100
			Map diagramMap, DiagramPrinter diagramPrinter) {
50
			Map diagramMap, SWTDiagramPrinter diagramPrinter) {
101
		
102
		List diagramNames;
103
		PrinterData printerData;
104
		IPrintHelper helper;
105
        IPreferenceStore pref = null;
106
107
		try {
108
			Class printhelperClass = Class
109
				.forName(IPrintHelper.PRINT_HELPER_CLASS_NAME);
110
			helper = (IPrintHelper) printhelperClass.newInstance();
111
			diagramNames = new ArrayList(diagramMap.keySet());
112
            
113
            //get the preferences store currently in use...
114
            
115
            if (editorPart instanceof IDiagramWorkbenchPart) {
116
                
117
                IDiagramGraphicalViewer viewer = ((IDiagramWorkbenchPart)editorPart).getDiagramGraphicalViewer();
118
                if (viewer instanceof DiagramGraphicalViewer) {
119
                    
120
                    //default to diagram settings...
121
                    pref = ((DiagramGraphicalViewer) viewer)
122
                        .getWorkspaceViewerPreferenceStore();
123
                    
124
                    if (pref.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
125
                        
126
                        //get workspace settings...
127
                        if (((IDiagramWorkbenchPart)editorPart).getDiagramEditPart().
128
                                getDiagramPreferencesHint().getPreferenceStore() != null)
129
                            pref = (IPreferenceStore)((IDiagramWorkbenchPart)editorPart).getDiagramEditPart().
130
                                getDiagramPreferencesHint().getPreferenceStore(); 
131
                    }
132
                }
133
            }
134
            
135
            //set the preferences for the print dialog...
136
            if (pref != null) {
137
                
138
                //the orientation...
139
                helper.setDlgOrientation(pref.getBoolean(WorkspaceViewerProperties.PREF_USE_LANDSCAPE));
140
                
141
                //the paper size...
142
                PageSetupPageType storedPageType = PageSetupPageType.LETTER; //default value
143
                String strPageType = pref.getString(WorkspaceViewerProperties.PREF_PAGE_SIZE);
144
                for (int i=0; i<PageSetupPageType.pages.length; i++) {
145
                    if (strPageType.startsWith(PageSetupPageType.pages[i].getName())) {
146
                        storedPageType = PageSetupPageType.pages[i];
147
                        break;
148
                    }
149
                }
150
                
151
                if (storedPageType.getIndex() == PageSetupPageType.USER_DEFINED.getIndex()) { //user defined size
152
                    //get the width and height...
153
                    
154
                    NumberFormat fNumberFormat = NumberFormat.getNumberInstance();;
155
                    String strWidth = pref.getString(WorkspaceViewerProperties.PREF_PAGE_WIDTH);
156
                    String strHeight= pref.getString(WorkspaceViewerProperties.PREF_PAGE_HEIGHT);
157
                    double width = 0, height = 0;
158
                    
159
                    try {
160
                        Number num = fNumberFormat.parse(strWidth);
161
                        width = num.doubleValue() / 0.0394d; //convert from inches to mm
162
                        
163
                        num = fNumberFormat.parse(strHeight);
164
                        height = num.doubleValue() / 0.0394d;
165
                        
166
                        helper.setDlgPaperSize(PageSetupPageType.USER_DEFINED.getIndex(), width, height);
167
                    } 
168
                    catch (ParseException e) {
169
                        Log.warning(
170
                            DiagramPrintingPlugin.getInstance(),
171
                            DiagramPrintingStatusCodes.IGNORED_EXCEPTION_WARNING,
172
                            e.getMessage(),
173
                            e);
174
                    }
175
                }
176
                else
177
                    helper.setDlgPaperSize(storedPageType.getIndex(), 0, 0);
178
179
            }
180
            
181
			printerData = helper.openPrintDlg(diagramNames);
182
		}
183
		catch (Throwable e) {
184
			//if there's a problem with the fragment, try doing the default
185
			//this is better than nothing
186
			Trace.catching(
187
				DiagramPrintingPlugin.getInstance(),
188
				DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
189
				DiagramPrinterUtil.class,
190
				e.getMessage(),
191
				e);
192
			Log.warning(
193
				DiagramPrintingPlugin.getInstance(),
194
				DiagramPrintingStatusCodes.RESOURCE_FAILURE,
195
				e.getMessage(),
196
				e);
197
198
			if (MessageDialog.openQuestion(Display.getDefault().getActiveShell(), DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorTitle, 
199
				DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part1
200
				+"\n" //$NON-NLS-1$
201
				+DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part2
202
				+"\n" //$NON-NLS-1$
203
				+DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part3
204
				+"\n\n" //$NON-NLS-1$
205
				+DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part4)) { 
206
					DefaultPrintActionHelper.doRun(editorPart, diagramPrinter);
207
				}
208
209
			//do not continue
210
			return;
211
		}
212
		
213
		Assert.isNotNull(diagramNames);
214
		Assert.isNotNull(helper);
215
216
		if (printerData != null) { //ok pressed
217
218
			//uncomment this code for debug information
219
			/*if (helper.getDlgDiagramPrintRangeAll()) {
220
			    Trace.trace(ModelerPlugin.getInstance(), "All diagrams");
221
			} else if (helper.getDlgDiagramPrintRangeCurrent()) {
222
			    Trace.trace(ModelerPlugin.getInstance(), "Current diagram");
223
			} else if (helper.getDlgDiagramPrintRangeSelection()) {
224
			    Trace.trace(ModelerPlugin.getInstance(), "Selected diagrams");
225
			}
226
			
227
			if (helper.getDlgScalePercent() != -1) {
228
			    Trace.trace(ModelerPlugin.getInstance(), 
229
			        "Scale to " + helper.getDlgScalePercent() + " percent");
230
			} else {
231
			    Trace.trace(ModelerPlugin.getInstance(), 
232
			        "Scale to "
233
			            + helper.getDlgScaleFitToM()
234
			            + "x"
235
			            + helper.getDlgScaleFitToN()
236
			            + " pages");
237
			}
238
			
239
			if (helper.getDlgPrintRangeAll()) {
240
			    Trace.trace(ModelerPlugin.getInstance(), "All");
241
			}
242
			if (helper.getDlgPrintRangePages()) {
243
			    Trace.trace(ModelerPlugin.getInstance(), 
244
			        "Pages " + helper.getDlgPagesFrom() + " to " + helper.getDlgPagesTo());
245
			}
246
			
247
			Trace.trace(ModelerPlugin.getInstance(), helper.getDlgNumberOfCopies() + " copies");
248
			
249
			if (helper.getDlgCollate()) {
250
			    Trace.trace(ModelerPlugin.getInstance(), "Collate");
251
			} else {
252
			    Trace.trace(ModelerPlugin.getInstance(), "Do not collate");
253
			}*/
254
			
255
			final Printer printer = new Printer(printerData);
256
			
257
			diagramPrinter.setPrinter(printer);
258
			diagramPrinter.setDisplayDPI(Display.getDefault().getDPI());
259
260
			if (helper.getDlgDiagramPrintRangeCurrent()) {
261
				DiagramEditPart dgrmEP = ((IDiagramWorkbenchPart) editorPart).getDiagramEditPart();
262
				assert dgrmEP != null;
263
				diagramPrinter.setDiagrams(Collections.singletonList(dgrmEP.getDiagramView().getDiagram()));
264
			} else if (helper.getDlgDiagramPrintRangeAll()) {
265
				diagramPrinter.setDiagrams(diagramMap.values());
266
			} else if (helper.getDlgDiagramPrintRangeSelection()) {
267
				Object obj;
268
				List list = new ArrayList();
269
				for (int i = 0; i < diagramNames.size(); i++) {
270
					//is the diagram selected?
271
					//we are only printing the selected ones
272
					if (helper.isDlgDiagramSelected(i)) {
273
						obj = diagramMap.get(diagramNames.get(i));
274
						Assert.isTrue(obj instanceof Diagram);
275
276
						list.add(obj);
277
					}
278
				}
279
				diagramPrinter.setDiagrams(list);
280
			}
281
				
282
			printDiagrams(diagramPrinter, helper);
283
284
			printer.dispose();
285
		}
286
51
52
		SWTDiagramPrinterHelper.getDiagramPrinterHelper().printWithSettings(
53
				editorPart, diagramMap, diagramPrinter);
287
	}
54
	}
288
}
55
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/printpreview/PrintPreviewHelper.java (-16 / +27 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2002, 2007 IBM Corporation and others.
2
 * Copyright (c) 2002, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 14-19 Link Here
14
import java.util.ArrayList;
14
import java.util.ArrayList;
15
import java.util.List;
15
import java.util.List;
16
16
17
import javax.print.PrintService;
18
import javax.print.PrintServiceLookup;
19
17
import org.eclipse.draw2d.Graphics;
20
import org.eclipse.draw2d.Graphics;
18
import org.eclipse.draw2d.SWTGraphics;
21
import org.eclipse.draw2d.SWTGraphics;
19
import org.eclipse.draw2d.geometry.Rectangle;
22
import org.eclipse.draw2d.geometry.Rectangle;
Lines 40-46 Link Here
40
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
43
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
41
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingPluginImages;
44
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingPluginImages;
42
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.HeaderAndFooterHelper;
45
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.HeaderAndFooterHelper;
43
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.PrintHelper;
46
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.PrintHelperUtil;
44
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
47
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
45
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.ScaledGraphics;
48
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.ScaledGraphics;
46
import org.eclipse.gmf.runtime.draw2d.ui.internal.mapmode.DiagramMapModeUtil;
49
import org.eclipse.gmf.runtime.draw2d.ui.internal.mapmode.DiagramMapModeUtil;
Lines 61-67 Link Here
61
import org.eclipse.swt.graphics.Point;
64
import org.eclipse.swt.graphics.Point;
62
import org.eclipse.swt.layout.GridData;
65
import org.eclipse.swt.layout.GridData;
63
import org.eclipse.swt.layout.GridLayout;
66
import org.eclipse.swt.layout.GridLayout;
64
import org.eclipse.swt.printing.Printer;
65
import org.eclipse.swt.widgets.Composite;
67
import org.eclipse.swt.widgets.Composite;
66
import org.eclipse.swt.widgets.Display;
68
import org.eclipse.swt.widgets.Display;
67
import org.eclipse.swt.widgets.Label;
69
import org.eclipse.swt.widgets.Label;
Lines 161-166 Link Here
161
	 * Print item on toolbar
163
	 * Print item on toolbar
162
	 */
164
	 */
163
	protected ToolItem printTool;
165
	protected ToolItem printTool;
166
	
167
	/**
168
	 * Enable or disable the print option
169
	 */
170
	protected boolean enablePrinting = true;
164
171
165
	/**
172
	/**
166
	 * Pages item on toolbar
173
	 * Pages item on toolbar
Lines 304-309 Link Here
304
	}
311
	}
305
312
306
	/**
313
	/**
314
	 * Enable or disable printing depending on where the print preview is invoked from.
315
	 * 
316
	 * @param enablePrinting
317
	 */
318
	public void enablePrinting(boolean enablePrinting){
319
		this.enablePrinting = enablePrinting;
320
	}
321
	
322
	/**
307
	 * Do the print preview.
323
	 * Do the print preview.
308
	 * 
324
	 * 
309
	 * @param printActionHelper,
325
	 * @param printActionHelper,
Lines 408-414 Link Here
408
			}
424
			}
409
		});
425
		});
410
426
411
		if (printActionHelper == null) {
427
		if (printActionHelper == null || !enablePrinting) {
412
			printTool.setEnabled(false);
428
			printTool.setEnabled(false);
413
		}
429
		}
414
430
Lines 778-784 Link Here
778
	 */
794
	 */
779
	protected Rectangle getPageBreakBounds() {
795
	protected Rectangle getPageBreakBounds() {
780
		if (pageBreakBounds == null) {
796
		if (pageBreakBounds == null) {
781
			pageBreakBounds = PrintHelper.getPageBreakBounds(getDiagramEditPart(), true);
797
			pageBreakBounds = PrintHelperUtil.getPageBreakBounds(getDiagramEditPart(), true);
782
		}
798
		}
783
		return pageBreakBounds;
799
		return pageBreakBounds;
784
	}
800
	}
Lines 810-817 Link Here
810
		if (diagramEditPart == null) {
826
		if (diagramEditPart == null) {
811
			Diagram diagram = getDiagramEditorPart().getDiagram(); //do not getDiagramEditPart
827
			Diagram diagram = getDiagramEditorPart().getDiagram(); //do not getDiagramEditPart
812
			PreferencesHint preferencesHint = getPreferencesHint(getDiagramEditorPart());
828
			PreferencesHint preferencesHint = getPreferencesHint(getDiagramEditorPart());
813
			diagramEditPart = PrintHelper.createDiagramEditPart(diagram, preferencesHint, getTempShell());
829
			diagramEditPart = PrintHelperUtil.createDiagramEditPart(diagram, preferencesHint, getTempShell());
814
			PrintHelper.initializePreferences(diagramEditPart, preferencesHint);
830
			PrintHelperUtil.initializePreferences(diagramEditPart, preferencesHint);
815
		}
831
		}
816
		return diagramEditPart;
832
		return diagramEditPart;
817
	}
833
	}
Lines 859-870 Link Here
859
	 * Call this immediately with the rest of the initialization.
875
	 * Call this immediately with the rest of the initialization.
860
	 */
876
	 */
861
	protected boolean isPrinterInstalled() {
877
	protected boolean isPrinterInstalled() {
862
		Printer printer = null;
863
		try {
878
		try {
864
			printer = new Printer();
879
			PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
880
					null, null);
881
			return printServices.length > 0;
865
		} catch (SWTError e) {
882
		} catch (SWTError e) {
866
			//I cannot printer.dispose(); because it may not have been
867
			//initialized
868
			Trace.catching(DiagramPrintingPlugin.getInstance(),
883
			Trace.catching(DiagramPrintingPlugin.getInstance(),
869
				DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
884
				DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
870
				PrintPreviewHelper.class, "isPrinterInstalled", //$NON-NLS-1$
885
				PrintPreviewHelper.class, "isPrinterInstalled", //$NON-NLS-1$
Lines 887-897 Link Here
887
				PrintPreviewHelper.class, "isPrinterInstalled", //$NON-NLS-1$
902
				PrintPreviewHelper.class, "isPrinterInstalled", //$NON-NLS-1$
888
				e);
903
				e);
889
			throw e;
904
			throw e;
890
		}
905
		}	
891
892
		printer.dispose();
893
894
		return true;
895
	}
906
	}
896
907
897
	/**
908
	/**
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/providers/DiagramWithPrintGlobalActionHandler.java (-4 / +5 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
2
 * Copyright (c) 2005, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 19-25 Link Here
19
import org.eclipse.gmf.runtime.diagram.ui.editparts.IDiagramPreferenceSupport;
19
import org.eclipse.gmf.runtime.diagram.ui.editparts.IDiagramPreferenceSupport;
20
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
20
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
21
import org.eclipse.gmf.runtime.diagram.ui.printing.actions.DefaultPrintActionHelper;
21
import org.eclipse.gmf.runtime.diagram.ui.printing.actions.DefaultPrintActionHelper;
22
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.DiagramPrinter;
22
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.util.SWTDiagramPrinter;
23
import org.eclipse.gmf.runtime.diagram.ui.providers.DiagramGlobalActionHandler;
23
import org.eclipse.gmf.runtime.diagram.ui.providers.DiagramGlobalActionHandler;
24
import org.eclipse.ui.IEditorPart;
24
import org.eclipse.ui.IEditorPart;
25
25
Lines 57-66 Link Here
57
	 * @param cntxt
57
	 * @param cntxt
58
	 */
58
	 */
59
	protected void doPrint(IGlobalActionContext cntxt) {
59
	protected void doPrint(IGlobalActionContext cntxt) {
60
	
60
		DefaultPrintActionHelper.doRun((IEditorPart) cntxt.getActivePart(),
61
		DefaultPrintActionHelper.doRun((IEditorPart) cntxt.getActivePart(),
61
			new DiagramPrinter(getPreferencesHint((IEditorPart) cntxt
62
			new SWTDiagramPrinter(getPreferencesHint((IEditorPart) cntxt
62
				.getActivePart()), getMapMode(cntxt)));
63
				.getActivePart()), getMapMode(cntxt)));
63
	}
64
		}
64
65
65
	/**
66
	/**
66
	 * Checks if we will allow a print
67
	 * Checks if we will allow a print
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/l10n/DiagramUIPrintingMessages.properties (-1 / +29 lines)
Lines 1-6 Link Here
1
# ==============================================================================
1
# ==============================================================================
2
#*+------------------------------------------------------------------------+
2
#*+------------------------------------------------------------------------+
3
#*| Copyright (c) 2005  IBM Corporation and others.                        |
3
#*| Copyright (c) 2005, 2008  IBM Corporation and others.                        |
4
#*| All rights reserved. This program and the accompanying materials       |
4
#*| All rights reserved. This program and the accompanying materials       |
5
#*| are made available under the terms of the Eclipse Public License v1.0  |
5
#*| are made available under the terms of the Eclipse Public License v1.0  |
6
#*| which accompanies this distribution, and is available at               |
6
#*| which accompanies this distribution, and is available at               |
Lines 33-38 Link Here
33
Print_MessageDialogTitle=Print Diagram
33
Print_MessageDialogTitle=Print Diagram
34
Print_MessageDialogMessage=Print to fit the diagram?
34
Print_MessageDialogMessage=Print to fit the diagram?
35
35
36
37
38
# ==============================================================================
39
# Print Dialog - Translation Instruction : section to be translated
40
# ==============================================================================
41
JPSPrintDialog_Title=Print Diagram
42
JPSPrintDialog_Button_PrintPreview=Print Preview...
43
JPSPrintDialog_Copies=&Copies
44
JPSPrintDialog_NumberOfCopies=&Number of copies:
45
JPSPrintDialog_Collate=C&ollate
46
JPSPrintDialog_Printer=Printer
47
JPSPrintDialog_Name=&Name:
48
JPSPrintDialog_Properties=Properties...
49
JPSPrintDialog_PrintToFile=Print to &file
50
JPSPrintDialog_PrintRange=Print &range
51
JPSPrintDialog_All=A&ll
52
JPSPrintDialog_Pages=&Pages
53
JPSPrintDialog_From=Fr&om:
54
JPSPrintDialog_To=&To:
55
JPSPrintDialog_Scaling=&Scaling
56
JPSPrintDialog_Adjust=A&djust to percentage of normal size:
57
JPSPrintDialog_FitTo=Fit &to:
58
JPSPrintDialog_PagesWide=Pages &wide:
59
JPSPrintDialog_PagesTall=Pages &tall:
60
36
# DiagramPrinterUtil related resource strings
61
# DiagramPrinterUtil related resource strings
37
# ================================ BEGIN ==================================================
62
# ================================ BEGIN ==================================================
38
DiagramPrinterUtil_DLLErrorTitle=Error loading printing library
63
DiagramPrinterUtil_DLLErrorTitle=Error loading printing library
Lines 43-45 Link Here
43
DiagramPrinterUtil_DLLErrorMessage_part3=This problem can be fixed by reinstalling the product.
68
DiagramPrinterUtil_DLLErrorMessage_part3=This problem can be fixed by reinstalling the product.
44
DiagramPrinterUtil_DLLErrorMessage_part4=Would you like to continue printing with reduced functionality anyway?
69
DiagramPrinterUtil_DLLErrorMessage_part4=Would you like to continue printing with reduced functionality anyway?
45
# ==================================== END ================================================
70
# ==================================== END ================================================
71
72
JPSDiagramPrinterUtil_ErrorTitle=Error printing
73
JPSDiagramPrinterUtil_ErrorMessage=Please ensure that at least one printer is installed and retry.
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/l10n/DiagramUIPrintingMessages.java (-1 / +22 lines)
Lines 46-52 Link Here
46
	public static String DiagramPrinterUtil_DLLErrorMessage_part2;
46
	public static String DiagramPrinterUtil_DLLErrorMessage_part2;
47
	public static String DiagramPrinterUtil_DLLErrorMessage_part3;
47
	public static String DiagramPrinterUtil_DLLErrorMessage_part3;
48
	public static String DiagramPrinterUtil_DLLErrorMessage_part4;
48
	public static String DiagramPrinterUtil_DLLErrorMessage_part4;
49
49
	public static String JPSPrintDialog_Title;
50
	public static String JPSPrintDialog_Button_PrintPreview;
51
	public static String JPSPrintDialog_Copies;
52
	public static String JPSPrintDialog_NumberOfCopies;
53
	public static String JPSPrintDialog_Collate;
54
	public static String JPSPrintDialog_Printer;
55
	public static String JPSPrintDialog_Name;
56
	public static String JPSPrintDialog_Properties;
57
	public static String JPSPrintDialog_PrintToFile;
58
	public static String JPSPrintDialog_PrintRange;
59
	public static String JPSPrintDialog_All;
60
	public static String JPSPrintDialog_Pages;
61
	public static String JPSPrintDialog_From;
62
	public static String JPSPrintDialog_To;
63
	public static String JPSPrintDialog_Scaling;
64
	public static String JPSPrintDialog_Adjust;
65
	public static String JPSPrintDialog_FitTo;
66
	public static String JPSPrintDialog_PagesWide;
67
	public static String JPSPrintDialog_PagesTall;
68
	public static String JPSDiagramPrinterUtil_ErrorTitle;
69
	public static String JPSDiagramPrinterUtil_ErrorMessage;
70
				
50
	static {
71
	static {
51
		NLS.initializeMessages(BUNDLE_NAME, DiagramUIPrintingMessages.class);
72
		NLS.initializeMessages(BUNDLE_NAME, DiagramUIPrintingMessages.class);
52
	}
73
	}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/util/PrintHelper.java (-296 lines)
Removed Link Here
1
/******************************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
13
14
import java.io.File;
15
16
import org.eclipse.core.runtime.IPath;
17
import org.eclipse.draw2d.geometry.Rectangle;
18
import org.eclipse.gef.RootEditPart;
19
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
20
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
21
import org.eclipse.gmf.runtime.diagram.ui.OffscreenEditPartFactory;
22
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
23
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
24
import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin;
25
import org.eclipse.gmf.runtime.diagram.ui.internal.editparts.PageBreakEditPart;
26
import org.eclipse.gmf.runtime.diagram.ui.internal.figures.PageBreaksFigure;
27
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper;
28
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
29
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
30
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
31
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
32
import org.eclipse.gmf.runtime.diagram.ui.util.DiagramEditorUtil;
33
import org.eclipse.gmf.runtime.notation.Diagram;
34
import org.eclipse.jface.preference.IPreferenceStore;
35
import org.eclipse.jface.preference.PreferenceStore;
36
import org.eclipse.swt.widgets.Display;
37
import org.eclipse.swt.widgets.Shell;
38
39
/**
40
 * Helper to assist in making an offscreen diagram suitable for printing or
41
 * previewing.
42
 * 
43
 * @author wdiu, Wayne Diu
44
 */
45
public class PrintHelper {
46
	/**
47
     * Creates a <code>DiagramEditPart</code> given the <code>Diagram</code>
48
     * without opening an editor.
49
     * 
50
	 * @param diagram the <code>Diagram</code>
51
	 * @param preferencesHint the preferences hint to use for intiializing the
52
	 * preferences of the root edit part
53
	 * @return the new populated <code>DiagramEditPart</code>
54
     * @deprecated Please use
55
     *             {@link #createDiagramEditPart(Diagram, PreferencesHint, Shell)}
56
     *             instead as this method does not dispose the new Shell that it
57
     *             creates.
58
     */
59
	public static DiagramEditPart createDiagramEditPart(Diagram diagram,
60
            PreferencesHint preferencesHint) {
61
			
62
            DiagramEditPart diagramEditPart =  OffscreenEditPartFactory.getInstance().createDiagramEditPart(
63
            diagram, new Shell(), preferencesHint);
64
            // since some of the diagram updates are ASync we need to give the 
65
            // inter-thread messages a chance to get processed processed before we
66
            // continue; check bugzilla 170332
67
            while (Display.getDefault().readAndDispatch ()){
68
                // nothing special to do 
69
            }
70
             return diagramEditPart;
71
        }
72
    
73
    /**
74
     * Creates a <code>DiagramEditPart</code> given the <code>Diagram</code>
75
     * without opening an editor.
76
     * 
77
     * @param diagram the <code>Diagram</code>
78
     * @param preferencesHint the preferences hint to use for intiializing the
79
     * preferences of the root edit part
80
     * @return the new populated <code>DiagramEditPart</code>
81
     */
82
    public static DiagramEditPart createDiagramEditPart(Diagram diagram,
83
        PreferencesHint preferencesHint, Shell shell) {
84
        DiagramEditPart diagramEditPart = OffscreenEditPartFactory.getInstance().createDiagramEditPart(
85
                diagram, shell, preferencesHint);
86
        // since some of the diagram updates are ASync we need to give the 
87
        // inter-thread messages a chance to get processed before we
88
        // continue; check bugzilla 170332
89
        while (Display.getDefault().readAndDispatch ()){
90
            // nothing special to do 
91
        }
92
         return diagramEditPart;
93
    }
94
	
95
	/**
96
	 * Initialize the preferences for a diagram edit part, specifically
97
	 * including page breaks and margins.
98
	 * 
99
	 * Typically, the diagram edit part is created using
100
	 * createDiagramEditPart() and the diagram edit part is passed in as the
101
	 * first parameter of this method.
102
	 * 
103
	 * @param diagramEditPart the DiagramEditPart to pass in 
104
	 * @param preferencesHint the preferences hint to use for intiializing the preferences
105
	 * 
106
	 * @return true if the preferences could be loaded, false if they weren't
107
	 * loaded and defaults had to be used instead
108
	 */
109
	public static boolean initializePreferences(DiagramEditPart diagramEditPart, PreferencesHint preferencesHint) {
110
		assert diagramEditPart.getViewer() instanceof DiagramGraphicalViewer;
111
		
112
		DiagramGraphicalViewer viewer = (DiagramGraphicalViewer)diagramEditPart.getViewer();
113
114
		boolean loadedPreferences = true;
115
116
		IPreferenceStore fPreferences = getPreferenceStoreForDiagram(diagramEditPart);
117
		
118
		if (fPreferences == null) {
119
			loadedPreferences = false;
120
			//leave at default x and y
121
			PreferenceStore defaults = new PreferenceStore();
122
			DiagramEditor.addDefaultPreferences(defaults, preferencesHint);
123
124
			fPreferences = getWorkspacePreferenceStore(preferencesHint);
125
		} else if (!fPreferences
126
			.getBoolean(WorkspaceViewerProperties.PREF_USE_DIAGRAM_SETTINGS)) {
127
			//if we aren't supposed to use the diagram settings, switch to the
128
			//workspace settings
129
130
			//we have to use the page break x and y settings from the diagram
131
			int x = fPreferences.getInt(WorkspaceViewerProperties.PAGEBREAK_X), y = fPreferences
132
				.getInt(WorkspaceViewerProperties.PAGEBREAK_Y);
133
134
			//minor performance optimization, use the existing
135
			//preferences from the workspace instead of making a new one
136
			fPreferences = getWorkspacePreferenceStore(preferencesHint);
137
			fPreferences.setValue(WorkspaceViewerProperties.PAGEBREAK_X, x);
138
			fPreferences.setValue(WorkspaceViewerProperties.PAGEBREAK_Y, y);
139
		}
140
141
		viewer.hookWorkspacePreferenceStore(fPreferences);
142
143
		diagramEditPart.refreshPageBreaks();
144
		
145
		return loadedPreferences;
146
	}
147
148
	/**
149
	 * Returns the workspace viewer <code>PreferenceStore</code> for a given diagram edit part.
150
	 * 
151
	 * @param diagramEP the DiagramEditPart to obtain the preference store for
152
	 * 
153
	 * @return the <code>PreferenceStore</code> for the given diagram edit part
154
	 * Could return null if it couldn't be loaded 
155
	 */
156
	private static IPreferenceStore getPreferenceStoreForDiagram(DiagramEditPart diagramEP) {
157
		// Try to load it
158
		String id = ViewUtil.getIdStr(diagramEP.getDiagramView());
159
160
		//try and get preferences from the open diagrams first
161
		//loadedPreferences will be set to true only if the preferences could
162
		// be
163
		//successfully loaded
164
		IPreferenceStore fPreferences = loadPreferencesFromOpenDiagram(id);
165
		if (fPreferences != null) {
166
			//loadPreferencesFromOpenDiagram will have set preferences
167
			return fPreferences;
168
		}
169
170
		IPath path = DiagramUIPlugin.getInstance().getStateLocation();
171
172
		String fileName = path.toString() + "/" + id;//$NON-NLS-1$
173
		java.io.File file = new File(fileName);
174
		fPreferences = new PreferenceStore(fileName);
175
		if (file.exists()) {
176
			// Load it
177
			try {
178
				((PreferenceStore) fPreferences).load();
179
180
				return fPreferences;
181
			} catch (Exception e) {
182
				return null;
183
			}
184
		}
185
		return null; //fPreferences couldn't be loaded
186
	}
187
	
188
	/**
189
	 * Load the preferences from an open diagram that has the given guid.
190
	 * 
191
	 * @param id guid of the open diagram to load the preferences for 
192
	 */
193
	private static IPreferenceStore loadPreferencesFromOpenDiagram(String id) {
194
195
		DiagramEditor diagramEditor = DiagramEditorUtil.findOpenedDiagramEditorForID(id);
196
		if (diagramEditor != null) {
197
			IDiagramGraphicalViewer viewer = diagramEditor
198
					.getDiagramGraphicalViewer();
199
			if (diagramEditor.getDiagramEditPart().getRoot() instanceof DiagramRootEditPart) {
200
				PageBreakEditPart pageBreakEditPart = ((DiagramRootEditPart) diagramEditor
201
						.getDiagramEditPart().getRoot()).getPageBreakEditPart();
202
				pageBreakEditPart.resize(diagramEditor.getDiagramEditPart()
203
						.getChildrenBounds());
204
				pageBreakEditPart.updatePreferenceStore();
205
			}
206
			if (viewer instanceof DiagramGraphicalViewer) {
207
				DiagramGraphicalViewer diagramGraphicalViewer = (DiagramGraphicalViewer) viewer;
208
209
				// preferences loaded
210
				return diagramGraphicalViewer
211
						.getWorkspaceViewerPreferenceStore();
212
			}
213
		}
214
215
		// no matching guid found
216
		return null;
217
	}
218
	
219
	/**
220
	 * Return the preference store for the given PreferenceHint
221
	 * @param preferencesHint to return the preference store for.
222
	 * 
223
	 * @return preference store for the given PreferenceHint
224
	 */
225
	private static IPreferenceStore getWorkspacePreferenceStore(PreferencesHint preferencesHint) {
226
		return (IPreferenceStore) preferencesHint.getPreferenceStore();
227
	}
228
	
229
	/**
230
	 * Returns the page break bounds on the diagram. If the bounds cannot be
231
	 * found the diagram bounds is returned.
232
	 * 
233
	 * @param dgrmEP the diagram edit part to return the page break bounds for
234
	 * @param loadedPreferences true if preferences were previously loaded,
235
	 * false if they couldn't be.  For consistency when printing, we have to
236
	 * treat page breaks differently depending on whether preferences were
237
	 * successfully loaded or not.
238
	 * 
239
	 * @return Rectangle with the page break bounds for the given diagram edit
240
	 * part. If the page break bounds cannot be found the diagram bounds
241
	 * Rectangle is returned.
242
	 */
243
	public static Rectangle getPageBreakBounds(DiagramEditPart dgrmEP, boolean loadedPreferences) {
244
		
245
		Rectangle pageBreakBounds = null;
246
		assert dgrmEP.getViewer() instanceof DiagramGraphicalViewer;
247
        
248
        
249
        //get the preferences in use...
250
        IPreferenceStore fPreferences = ((DiagramGraphicalViewer)dgrmEP.getViewer()).getWorkspaceViewerPreferenceStore();
251
        
252
        if (fPreferences.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
253
            
254
            //get workspace settings...
255
            if (dgrmEP.getDiagramPreferencesHint().getPreferenceStore() != null)
256
                fPreferences = (IPreferenceStore)dgrmEP.getDiagramPreferencesHint().getPreferenceStore(); 
257
        }
258
        
259
		RootEditPart rootEditPart = dgrmEP.getRoot();
260
		if (rootEditPart instanceof DiagramRootEditPart) {
261
			DiagramRootEditPart diagramRootEditPart = (DiagramRootEditPart) rootEditPart;
262
			PageBreakEditPart pageBreakEditPart = diagramRootEditPart
263
				.getPageBreakEditPart();
264
265
			if (pageBreakEditPart != null) {
266
				//resize must be called. Otherwise you get the 64 x 32 default
267
				pageBreakEditPart.resize(dgrmEP.getChildrenBounds());
268
269
				if (loadedPreferences) {
270
					//if preferences were loaded, we'll always do this for
271
					//consistency when printing.
272
					//this is necessary when printing using workspace
273
					//preferences, which is "if (getWorkspacePreferenceStore()
274
					//== fPreferences)"
275
276
					//if preferences were not loaded, we do not set the figure
277
					//location. we'll just leave them at defaults.
278
					org.eclipse.draw2d.geometry.Point p = new org.eclipse.draw2d.geometry.Point(
279
						fPreferences
280
							.getInt(WorkspaceViewerProperties.PAGEBREAK_X),
281
						fPreferences
282
							.getInt(WorkspaceViewerProperties.PAGEBREAK_Y));
283
					pageBreakEditPart.set(p, PageInfoHelper.getChildrenBounds(
284
						(DiagramEditPart) diagramRootEditPart.getContents(),
285
						PageBreaksFigure.class));
286
				}
287
288
				pageBreakBounds = pageBreakEditPart.getFigure().getBounds();
289
			} else {
290
				pageBreakBounds = dgrmEP.getFigure().getBounds();
291
			}
292
		}
293
294
		return pageBreakBounds;
295
	}	
296
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/util/DiagramPrinter.java (-909 / +271 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2002, 2007 IBM Corporation and others.
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 12-888 Link Here
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
13
13
14
import java.util.Collection;
14
import java.util.Collection;
15
import java.util.Iterator;
16
15
17
import org.eclipse.core.runtime.Assert;
18
import org.eclipse.draw2d.Graphics;
16
import org.eclipse.draw2d.Graphics;
19
import org.eclipse.draw2d.SWTGraphics;
20
import org.eclipse.draw2d.geometry.Rectangle;
17
import org.eclipse.draw2d.geometry.Rectangle;
21
import org.eclipse.gef.LayerConstants;
22
import org.eclipse.gef.RootEditPart;
18
import org.eclipse.gef.RootEditPart;
23
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
19
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
24
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
25
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
20
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
26
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
21
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
27
import org.eclipse.gmf.runtime.diagram.ui.internal.editparts.PageBreakEditPart;
22
import org.eclipse.gmf.runtime.diagram.ui.internal.editparts.PageBreakEditPart;
28
import org.eclipse.gmf.runtime.diagram.ui.internal.figures.PageBreaksFigure;
23
import org.eclipse.gmf.runtime.diagram.ui.internal.figures.PageBreaksFigure;
29
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper;
30
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper.PageMargins;
31
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
32
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
33
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
34
import org.eclipse.gmf.runtime.diagram.ui.util.DiagramEditorUtil;
35
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
24
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
36
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.PrinterGraphics;
37
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.ScaledGraphics;
38
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
25
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
39
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
40
import org.eclipse.gmf.runtime.notation.Diagram;
26
import org.eclipse.gmf.runtime.notation.Diagram;
41
import org.eclipse.jface.preference.IPreferenceStore;
42
import org.eclipse.jface.resource.JFaceResources;
43
import org.eclipse.swt.SWT;
44
import org.eclipse.swt.graphics.Font;
45
import org.eclipse.swt.graphics.FontData;
46
import org.eclipse.swt.graphics.GC;
47
import org.eclipse.swt.graphics.Image;
48
import org.eclipse.swt.graphics.Point;
27
import org.eclipse.swt.graphics.Point;
49
import org.eclipse.swt.printing.Printer;
50
import org.eclipse.swt.widgets.Display;
51
import org.eclipse.swt.widgets.Shell;
52
import org.eclipse.ui.PlatformUI;
53
28
54
/*
55
 * @canBeSeenBy %level1
56
 */
57
public class DiagramPrinter
58
    implements Runnable {
59
60
    protected Printer printer;
61
62
    private Point display_dpi;
63
64
    private boolean isScaledPercent = false;
65
66
    private int rows = 1;
67
68
    private int columns = 1;
69
    
70
    private boolean printRangePageSelection = false;
71
    
72
    private int pageFrom = 1, pageTo = 1;
73
74
    private GC gc;
75
    
76
    private Graphics swtGraphics;
77
    
78
    private Graphics graphics;
79
    
80
    private PrinterGraphics printerGraphics;
81
    
82
    protected Point printerOffset;
83
84
    protected Rectangle logicalClientArea;
85
86
    private float userScale;
87
88
    /**
89
     * Used when a Collection of Diagram objects are passed in instead of an
90
     * IEditorPart.
91
     */
92
    protected Collection diagrams;
93
94
    /**
95
     * The initial amount that the diagram should be translated, set by
96
     * printToScale or printToPages which calls drawToFitRowsColumns.
97
     */
98
    private Point translated = null;
99
    
100
    /**
101
     * The hint used to find the appropriate preference store from which general
102
     * diagramming preference values for properties of shapes, connections, and
103
     * diagrams can be retrieved. This hint is mapped to a preference store in
104
     * the {@link DiagramPreferencesRegistry}.
105
     */
106
    private PreferencesHint preferencesHint;
107
    private IMapMode mm;
108
    
109
    private boolean fitToPage = false;
110
    
111
    /**
112
     * change the fit to page state
113
     * @param fitToPage the new fit to page state
114
     */
115
    public void setFitToPage(boolean fitToPage){
116
        this.fitToPage = fitToPage;
117
    }
118
119
    /**
120
     * Creates a new instance. The following variables must be initialized
121
     * before calling <code>run()</code>:
122
     * <li><code>printer</code></li>
123
     * <li><code>display_dpi</code></li>
124
     * <li><code>diagrams</code></li>
125
     * @param mm <code>IMapMode</code> to do the coordinate mapping
126
     */
127
    public DiagramPrinter(PreferencesHint preferencesHint, IMapMode mm) {
128
        super();
129
        this.preferencesHint = preferencesHint;
130
        this.mm = mm;
131
    }
132
    
133
    /**
134
     * Creates a new instance. The following variables must be initialized
135
     * before calling <code>run()</code>:
136
     * <li><code>printer</code></li>
137
     * <li><code>display_dpi</code></li>
138
     * <li><code>diagrams</code></li>
139
     * @param mm <code>IMapMode</code> to do the coordinate mapping
140
     */
141
    public DiagramPrinter(PreferencesHint preferencesHint) {
142
        this(preferencesHint, MapModeUtil.getMapMode());
143
    }
144
    
145
    /**
146
     * @return <code>IMapMode</code> to do the coordinate mapping
147
     */
148
    protected IMapMode getMapMode() {
149
        return mm;
150
    }
151
    
152
    /**
153
     * Sets the columns.
154
     * 
155
     * @param columns
156
     *            The columns to set.
157
     */
158
    public void setColumns(int columns) {
159
        this.columns = columns;
160
    }
161
162
    /**
163
     * Sets the diagrams.
164
     * 
165
     * @param diagrams
166
     *            a Collection of Diagram objects
167
     */
168
    public void setDiagrams(Collection diagrams) {
169
        this.diagrams = diagrams;
170
    }
171
172
    /**
173
     * Sets the display DPI.
174
     * 
175
     * @param display_dpi
176
     *            The display_dpi to set.
177
     */
178
    public void setDisplayDPI(Point display_dpi) {
179
        this.display_dpi = new Point(display_dpi.x, display_dpi.y);
180
    }
181
182
    /**
183
     * Sets the printer.
184
     * 
185
     * @param printer
186
     *            The printer to set.
187
     */
188
    public void setPrinter(Printer printer) {
189
        this.printer = printer;
190
    }
191
    
192
    public void setPrintRangePageSelection(boolean isPrintRangePageSelected) {
193
        this.printRangePageSelection = isPrintRangePageSelected;
194
    }
195
    
196
    public void setPrintRangePages(int pageFrom, int pageTo) {
197
        assert pageFrom > 0 : "From page in print range page selection must be bigger than zero."; //$NON-NLS-1$
198
        assert (pageTo > 0 && pageTo >= pageFrom) : "To page in print range page selection must be bigger than zero and from page.";  //$NON-NLS-1$
199
        this.pageFrom = pageFrom;
200
        this.pageTo = pageTo;
201
    }
202
203
    /**
204
     * Sets the rows.
205
     * 
206
     * @param rows
207
     *            The rows to set.
208
     */
209
    public void setRows(int rows) {
210
        this.rows = rows;
211
    }
212
213
    /**
214
     * Sets the scaled percent.
215
     * 
216
     * @param scalePercent
217
     */
218
    public void setScaledPercent(int scalePercent) {
219
        this.isScaledPercent = true;
220
        this.userScale = (scalePercent) / 100.0f;
221
222
    }
223
224
    /**
225
     * Prints the contents of the diagram editor part.
226
     */
227
    public void run() {
228
        assert null != printer : "printer must be set"; //$NON-NLS-1$
229
        if (!(printer.startJob("Printing"))) { //$NON-NLS-1$
230
          return;
231
        }
232
        
233
        assert diagrams != null;
234
        Iterator it = diagrams.iterator();
235
236
        Shell shell = new Shell();
237
        try {
238
            while (it.hasNext()) {
239
                Object obj = it.next();
240
                //the diagrams List is only supposed to have Diagram objects
241
                Assert.isTrue(obj instanceof Diagram);
242
                Diagram diagram = (Diagram)obj;
243
                DiagramEditor openedDiagramEditor = DiagramEditorUtil
244
						.findOpenedDiagramEditorForID(ViewUtil
245
								.getIdStr(diagram));
246
				DiagramEditPart dgrmEP = openedDiagramEditor == null ? PrintHelper
247
						.createDiagramEditPart(diagram, preferencesHint, shell)
248
						: openedDiagramEditor.getDiagramEditPart();
249
                
250
                boolean loadedPreferences = openedDiagramEditor != null || PrintHelper.initializePreferences(dgrmEP, preferencesHint);
251
252
                RootEditPart rep = dgrmEP.getRoot();
253
                if (rep instanceof DiagramRootEditPart) 
254
                    this.mm = ((DiagramRootEditPart)rep).getMapMode();
255
                
256
                initialize();
257
                
258
                
259
                IPreferenceStore pref = null;
260
                
261
                assert dgrmEP.getViewer() instanceof DiagramGraphicalViewer;
262
        
263
                pref = ((DiagramGraphicalViewer)dgrmEP.getViewer()).getWorkspaceViewerPreferenceStore();
264
                
265
                if (pref.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
266
                    
267
                    //get workspace settings...
268
                    if (dgrmEP.getDiagramPreferencesHint().getPreferenceStore() != null)
269
                        pref = (IPreferenceStore)dgrmEP.getDiagramPreferencesHint().getPreferenceStore(); 
270
                }
271
                
272
                doPrintDiagram(dgrmEP, loadedPreferences, pref);
273
                
274
                dispose();
275
            }
276
            printer.endJob();
277
        } finally {
278
            shell.dispose();
279
        }        
280
    }
281
    
282
    /**
283
     * Calculates the row in a grid, given a page number.
284
     * | 1 | 2 | 3 |
285
     * | 4 | 5 | 6 |
286
     * | 7 | 8 | 9 |
287
     * 
288
     * Given pageNum=5 and totalNumColumns=3, will return 2
289
     * (2nd row).
290
     * 
291
     * @param pageNum the page number in the grid.
292
     * @param totalNumColumns total number of columns of the grid.
293
     * @return row number corresponding to the page number.
294
     */
295
    private int calculateRowFromPage(int pageNum, int totalNumColumns) {
296
        int row = pageNum / totalNumColumns;
297
        if (pageNum % totalNumColumns != 0)
298
            row++;
299
        return row;
300
    }
301
    
302
    /**
303
     * Calculates the column in a grid, given a page number.
304
     * | 1 | 2 | 3 |
305
     * | 4 | 5 | 6 |
306
     * | 7 | 8 | 9 |
307
     * 
308
     * Given pageNum=5 and totalNumColumns=3, will return 2
309
     * (2nd column).
310
     *  
311
     * @param pageNum the page number in the grid.
312
     * @param totalNumColumns total number of columns of the grid.
313
     * @param cRow the corresponding row of the page number.
314
     * @return row number corresponding to the page number.
315
     */
316
    private int calculateColumnFromPage(int pageNum, int totalNumColumns, int cRow) {
317
        int col = pageNum - ((cRow - 1) * totalNumColumns);
318
        return col;
319
    }
320
    
321
    /**
322
     * Obtains the total number of pages that span columns and rows
323
     * @param dgrmEP
324
     * @return Point.x contains the total number of pages that span in a column
325
     *         Point.y contains the total number of pages that span in a row
326
     */
327
    private org.eclipse.draw2d.geometry.Point getPageCount(DiagramEditPart dgrmEP, Rectangle figureBounds, org.eclipse.draw2d.geometry.Point pageSize, boolean applyUserScale) {
328
        RootEditPart rootEditPart = dgrmEP.getRoot();
329
        if (rootEditPart instanceof DiagramRootEditPart) {
330
            //this is the most accurate way to obtain total rows and columns...
331
            
332
            DiagramRootEditPart diagramRootEditPart = (DiagramRootEditPart) rootEditPart;
333
            PageBreakEditPart pageBreakEditPart = diagramRootEditPart
334
                .getPageBreakEditPart();
335
            float fNumCols = ((PageBreaksFigure)pageBreakEditPart.getFigure()).getPageCount().y * 
336
                (applyUserScale ? userScale : 1);
337
            float fNumRows = ((PageBreaksFigure)pageBreakEditPart.getFigure()).getPageCount().x * 
338
                (applyUserScale ? userScale : 1);
339
            
340
            int numCols = (int) Math.ceil(fNumCols);
341
            int numRows = (int) Math.ceil(fNumRows);
342
            
343
            return new org.eclipse.draw2d.geometry.Point(numCols,numRows);
344
        }
345
        else {
346
            //otherwise, calculate manually...
347
            
348
            float fNumRows = (figureBounds.height * (applyUserScale ? userScale : 1))
349
                / pageSize.y;
350
            int numRows = (int) Math.ceil(fNumRows);
351
352
            float fNumCols = (figureBounds.width * (applyUserScale ? userScale : 1))
353
                / pageSize.x;
354
            int numCols = (int) Math.ceil(fNumCols);
355
            
356
            return new org.eclipse.draw2d.geometry.Point(numCols, numRows);
357
        }
358
    }
359
360
    /**
361
     * Prints to scale or prints to rows x columns pages
362
     */
363
    private void doPrintDiagram(DiagramEditPart dgrmEP, boolean loadedPreferences, IPreferenceStore fPreferences) {
364
        this.graphics.pushState();
365
        if (isScaledPercent) {
366
            printToScale(dgrmEP, loadedPreferences, fPreferences);
367
        } else {
368
            printToPages(dgrmEP, loadedPreferences, fPreferences);
369
        }
370
        this.graphics.popState();
371
    }
372
373
    private void initialize() {
374
375
        assert null != printer : "printer must be set"; //$NON-NLS-1$
376
        
377
        //check for rtl orientation...
378
        int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle();
379
        if ((style & SWT.MIRRORED) != 0)
380
            this.gc = new GC(printer, SWT.RIGHT_TO_LEFT);
381
        else
382
            this.gc = new GC(printer);
383
384
        gc.setXORMode(false);
385
386
        this.swtGraphics = new SWTGraphics(gc);
387
        this.printerGraphics = createPrinterGraphics(swtGraphics);
388
        this.graphics = createMapModeGraphics(printerGraphics);
389
        this.graphics.scale(computePrinterDisplayScale());
390
        
391
        this.logicalClientArea = this.graphics.getClip(new Rectangle(
392
            this.printer.getClientArea()));
393
        
394
    }
395
    
396
    /**
397
     * Usually, the printable area is less than the page.
398
     * This method returns the offset for each x margin and each y margin.
399
     * x margins are left and right
400
     * y margins are top and bottom
401
     * 
402
     * We'll assume the left and right offsets are the same and the
403
     * top and bottom offsets are the same.
404
     * 
405
     * @return Point with x and y offsets
406
     */
407
    protected Point getPrinterOffset() {
408
        if (printerOffset == null) {
409
            int offsetX = this.printer.getBounds().width
410
            - this.printer.getClientArea().width;
411
            int offsetY = this.printer.getBounds().height
412
            - this.printer.getClientArea().height;
413
        
414
            // assume half on each side
415
            offsetX = (int) (getMapMode()
416
                .DPtoLP((int) (offsetX / 2.0f * display_dpi.x / printer.getDPI().x)) / userScale);
417
            offsetY = (int) (getMapMode()
418
                .DPtoLP((int) (offsetY / 2.0f * display_dpi.y / printer.getDPI().y)) / userScale);
419
            
420
            printerOffset = new Point(offsetX, offsetY);
421
        }
422
        
423
        return printerOffset;
424
    }
425
426
    /**
427
     * Print the diagram figure using specified scale factor.
428
     * 
429
     * @param dgrmEP the DiagramEditPart that will be printed
430
     * @param loadedPreferences true if existing prefs could be loaded
431
     * successfully, false if not and defaults are being used.  This parameter
432
     * is important to obtain the correct page break bounds.
433
     * @param fPreferences the preferenceStore that could either contain
434
     * existing preferences or defaults
435
     */
436
    protected void printToScale(DiagramEditPart dgrmEP, boolean loadedPreferences, IPreferenceStore fPreferences) {
437
438
        assert null != printer : "printer must be set"; //$NON-NLS-1$
439
        Rectangle figureBounds = PrintHelper.getPageBreakBounds(dgrmEP, loadedPreferences);
440
        org.eclipse.draw2d.geometry.Point pageBounds = PageInfoHelper.getPageSize(fPreferences, getMapMode());
441
442
        //translate to offset initial figure position
443
        translated = new Point((int) (-figureBounds.x * userScale), (int) (-figureBounds.y * userScale));
444
        
445
        //calculate the number of page rows and columns
446
        int numRows = 0, numCols = 0;
447
        
448
        PageMargins margins = PageInfoHelper.getPageMargins(fPreferences, getMapMode());
449
        adjustMargins(margins, userScale, getPrinterOffset());
450
451
        GC gc_ = new GC(Display.getDefault(),this.gc.getStyle());
452
        gc_.setAntialias(this.gc.getAntialias());
453
454
        FontData fontData = JFaceResources.getDefaultFont().getFontData()[0];
455
        Font font = new Font(printer, fontData);
456
        
457
        org.eclipse.draw2d.geometry.Point pageCount = getPageCount(dgrmEP, figureBounds, pageBounds, true);
458
        numCols = pageCount.x;
459
        numRows = pageCount.y;
460
461
        //finalRow and finalColumn will be used if we are printing within a page range...
462
        int row = 1, col = 1, finalRow = 0, finalColumn = 0;
463
        
464
        if (this.printRangePageSelection) {
465
            //print only the pages specified in the page range...
466
            row = calculateRowFromPage(this.pageFrom, numCols);
467
            col = calculateColumnFromPage(this.pageFrom, numCols, row);
468
            
469
            finalRow = calculateRowFromPage(this.pageTo, numCols);
470
            finalColumn = calculateColumnFromPage(this.pageTo, numCols, finalRow);
471
        }
472
        
473
        try {
474
            //print the pages in row, column order
475
            for (; row <= numRows; row++) {
476
                for (; col <= numCols; col++) {
477
                    printer.startPage();
478
                    drawPage(gc_, dgrmEP, fPreferences, figureBounds, margins, font, row, col);
479
                    printer.endPage();
480
                    
481
                    if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
482
                        break;
483
                }
484
                
485
                if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
486
                    break;
487
                
488
                col = 1;
489
            }
490
        } finally {
491
            //must dispose resources
492
            font.dispose();
493
            gc_.dispose();
494
        }
495
    }
496
497
    /**
498
     * Draw the header and footer
499
     * 
500
     * @param gc_,
501
     *            a graphics context that is not null which this method will use
502
     *            for figuring ouyt the font's extent
503
     * @param figureBounds,
504
     *            Rectangle with the bounds of the figure
505
     * @param rowIndex,
506
     *            int
507
     * @param colIndex,
508
     *            int
509
     */
510
    protected void drawHeaderAndFooter(GC gc_, DiagramEditPart dgrmEP, Rectangle figureBounds,
511
            Font font, int rowIndex, int colIndex) {
512
513
        int width = this.logicalClientArea.width;
514
        int height = this.logicalClientArea.height;
515
516
        this.graphics.pushState(); //draw text, don't make it too small or big
517
        this.graphics.setFont(font);
518
519
        this.graphics.scale(1.0f / userScale);
520
        this.graphics.translate(-translated.x, -translated.y);
521
522
        String headerOrFooter = HeaderAndFooterHelper.makeHeaderOrFooterString(
523
            WorkspaceViewerProperties.HEADER_PREFIX, rowIndex, colIndex,
524
            dgrmEP);
525
526
        this.graphics.drawText(headerOrFooter,
527
            getMapMode().DPtoLP(HeaderAndFooterHelper.LEFT_MARGIN_DP)
528
                + (width - getMapMode().DPtoLP(gc_.textExtent(headerOrFooter).x))
529
                / 2, getMapMode().DPtoLP(HeaderAndFooterHelper.TOP_MARGIN_DP));
530
531
        headerOrFooter = HeaderAndFooterHelper.makeHeaderOrFooterString(
532
            WorkspaceViewerProperties.FOOTER_PREFIX, rowIndex, colIndex,
533
            dgrmEP);
534
535
        this.graphics.drawText(headerOrFooter,
536
            getMapMode().DPtoLP(HeaderAndFooterHelper.LEFT_MARGIN_DP)
537
                + (width - getMapMode().DPtoLP(gc_.textExtent(headerOrFooter).x))
538
                / 2, height - getMapMode().DPtoLP(HeaderAndFooterHelper.BOTTOM_MARGIN_DP));
539
540
        this.graphics.popState(); //for drawing the text
541
29
542
    }
30
/**
543
    
31
 * Basic page calculation operations have been factored out into this class.
544
    /**
32
 * This class was derived from the previous DiagramPrinter.
545
     * This method paints a portion of the diagram. (The area painted
33
 * 
546
     * representing one page.)
34
 * @author James Bruck (jbruck)
547
     * 
35
 */
548
     * @param gc_ a graphics context that is not null which this method will use
36
public abstract class DiagramPrinter implements Runnable {
549
     * for figuring out the font's extent
550
     * @param dgrmEP the DiagramEditPart that will be printed
551
     * @param fPreferences the preferenceStore that could either contain
552
     * existing preferences or defaults
553
     * @param figureBounds the page break bounds we'll have to offset by
554
     * @param font the Font to print the header or footer with
555
     * @param rowIndex index of row we're printing
556
     * @param colIndex index of column we're priniting
557
     * to check if it is the first time the method is getting called for the current
558
     * print.
559
     */
560
    protected void drawPage(GC gc_, DiagramEditPart dgrmEP,
561
            IPreferenceStore fPreferences, Rectangle figureBounds,
562
            PageMargins margins, Font font, int rowIndex, int colIndex) {
563
564
        org.eclipse.draw2d.geometry.Point pageSize = PageInfoHelper
565
            .getPageSize(fPreferences, false, getMapMode());
566
        boolean rtlEnabled = ((this.gc.getStyle() & SWT.MIRRORED) != 0);
567
        if (rtlEnabled) 
568
        {
569
            // draw everything on an offscreen image first and then draw that image
570
            // onto the printer gc...this takes care of certain drawing bugs.
571
            // This causes issues with printing resolution as it uses a display image
572
            // which is typically 72dpi
573
            // This code should be removed when a resolution to Bugzilla 162459 is found
574
575
            Image image = new Image(Display.getDefault(), getMapMode().LPtoDP(pageSize.x), getMapMode().LPtoDP(pageSize.y));
576
577
            GC imgGC = new GC(image, (rtlEnabled) ? SWT.RIGHT_TO_LEFT : SWT.LEFT_TO_RIGHT);
578
            imgGC.setXORMode(false);
579
      
580
            SWTGraphics sg = new SWTGraphics(imgGC);
581
              
582
            //for scaling
583
            ScaledGraphics g1 = new ScaledGraphics(sg);
584
          
585
            //for himetrics and svg
586
            MapModeGraphics mmg = createMapModeGraphics(g1);
587
              
588
            //if mmg's font is null, gc.setFont will use a default font
589
            imgGC.setFont(mmg.getFont());
590
              
591
            internalDrawPage(dgrmEP,figureBounds,fPreferences,margins,mmg,rowIndex, colIndex,true);
592
            
593
            this.graphics.pushState();
594
        
595
            this.graphics.drawImage(image, 0, 0);
596
              
597
            this.graphics.popState();
598
599
            //draw the header and footer after drawing the image to avoid getting the image getting drawn over them
600
            drawHeaderAndFooter(gc_, dgrmEP, figureBounds, font, rowIndex, colIndex);
601
            disposeImageVars(imgGC, image, sg, g1, mmg);
602
        } else {
603
            internalDrawPage(dgrmEP,figureBounds,fPreferences,margins,this.graphics,rowIndex, colIndex,false);
604
            //draw the header and footer after drawing the image to avoid getting the image getting drawn over them
605
            drawHeaderAndFooter(gc_, dgrmEP, figureBounds, font, rowIndex, colIndex);
606
        }
607
    }
608
    
609
    private void internalDrawPage(DiagramEditPart dgrmEP,
610
            Rectangle figureBounds, IPreferenceStore fPreferences,
611
            PageMargins margins, Graphics g, int rowIndex, int colIndex,
612
            boolean RTL_ENABLED) {
613
        org.eclipse.draw2d.geometry.Point pageSize = PageInfoHelper
614
            .getPageSize(fPreferences, false, getMapMode());
615
616
        int width = pageSize.x, height = pageSize.y;
617
618
        g.pushState();
619
620
        g.translate(translated.x, translated.y);
621
        g.scale(userScale);
622
623
        int translateX = -(width * (colIndex - 1));
624
        int translateY = -(height * (rowIndex - 1));
625
626
        int scaledTranslateX = (int) (translateX / userScale);
627
        int scaledTranslateY = (int) (translateY / userScale);
628
629
        int scaledWidth = (int) (width / userScale);
630
        int scaledHeight = (int) (height / userScale);
631
632
        if (RTL_ENABLED) {
633
            scaledTranslateX += (margins.left * (colIndex - 1))
634
                + (margins.right * (colIndex));
635
            scaledTranslateY += ((margins.top * rowIndex) + (margins.bottom * (rowIndex - 1)));
636
        } else {
637
            scaledTranslateX += ((margins.left * colIndex) + (margins.right * (colIndex - 1)));
638
            scaledTranslateY += ((margins.top * rowIndex) + (margins.bottom * (rowIndex - 1)));
639
        }
640
641
        g.translate(scaledTranslateX, scaledTranslateY);
642
643
        Rectangle clip = new Rectangle(
644
            (scaledWidth - margins.left - margins.right) * (colIndex - 1)
645
                + figureBounds.x, (scaledHeight - margins.bottom - margins.top)
646
                * (rowIndex - 1) + figureBounds.y, scaledWidth - margins.right
647
                - margins.left, scaledHeight - margins.top - margins.bottom);
648
        g.clipRect(clip);
649
650
        dgrmEP.getLayer(LayerConstants.PRINTABLE_LAYERS).paint(g);
651
652
        g.popState();
653
    }
654
37
655
    /**
38
	protected Point display_dpi;
656
     * Print the diagram figure to fit the number and rows and columns
39
	protected Collection<Diagram> diagrams;
657
     * specified by the user.
40
	protected PreferencesHint preferencesHint;
658
     * 
41
	protected IMapMode mapMode;
659
     * @param dgrmEP the DiagramEditPart that will be printed
42
	protected Point translated;
660
     * @param loadedPreferences true if existing prefs could be loaded
43
661
     * successfully, false if not and defaults are being used.  This parameter
44
	protected float userScale;
662
     * is important to obtain the correct page break bounds.
45
	protected boolean isScaledPercent = false;
663
     * @param fPreferences the preferenceStore that could either contain
46
	protected boolean fitToPage = false;
664
     * existing preferences or defaults
47
	protected boolean printRangePageSelection = false;
665
     */
48
666
    protected void printToPages(DiagramEditPart dgrmEP,
49
	protected int pageFrom = 1, pageTo = 1;
667
            boolean loadedPreferences, IPreferenceStore fPreferences) {
50
	protected int rows = 1;
668
        assert null != printer : "printer must be set"; //$NON-NLS-1$
51
669
52
	protected int columns = 1;
670
        Rectangle figureBounds = PrintHelper.getPageBreakBounds(dgrmEP,
53
671
            loadedPreferences);
54
	protected Graphics swtGraphics;
672
        
55
	protected Graphics graphics;
673
        PageMargins margins = PageInfoHelper.getPageMargins(fPreferences, getMapMode());
56
674
        //do not include margins
57
	public DiagramPrinter(PreferencesHint preferencesHint, IMapMode mm) {
675
        org.eclipse.draw2d.geometry.Point pageBounds = PageInfoHelper
58
		super();
676
            .getPageSize(fPreferences, getMapMode());
59
		this.preferencesHint = preferencesHint;
677
        org.eclipse.draw2d.geometry.Point pageCount = getPageCount(dgrmEP, figureBounds, pageBounds, false);
60
		this.mapMode = mm;
678
        int numCols = pageCount.x;
61
	}
679
        int numRows = pageCount.y;
62
680
        
63
	/**
681
        float actualWidth = 0;
64
	 * Obtains the total number of pages that span columns and rows
682
        float actualHeight = 0;
65
	 * @param dgrmEP
683
        if (this.rows==1 && this.columns==1 && fitToPage){
66
	 * @return Point.x contains the total number of pages that span in a column
684
        	figureBounds = dgrmEP.getChildrenBounds();
67
	 *         Point.y contains the total number of pages that span in a row
685
            actualWidth = figureBounds.width;
68
	 */
686
            actualHeight = figureBounds.height;
69
	protected org.eclipse.draw2d.geometry.Point getPageCount(
687
        }else {
70
			DiagramEditPart dgrmEP, Rectangle figureBounds,
688
            actualWidth = numCols * pageBounds.x;
71
			org.eclipse.draw2d.geometry.Point pageSize, boolean applyUserScale) {
689
            actualHeight = numRows * pageBounds.y;
72
		RootEditPart rootEditPart = dgrmEP.getRoot();
690
        }
73
691
74
		if (rootEditPart instanceof DiagramRootEditPart) {
692
        int totalHeight = (this.rows * pageBounds.y);
75
693
        int totalWidth  = (this.columns * pageBounds.x);
76
			DiagramRootEditPart diagramRootEditPart = (DiagramRootEditPart) rootEditPart;
694
77
			PageBreakEditPart pageBreakEditPart = diagramRootEditPart
695
        float vScale =  totalHeight / actualHeight;
78
					.getPageBreakEditPart();
696
        float hScale = totalWidth / actualWidth;
79
697
80
			float fNumCols = ((PageBreaksFigure) pageBreakEditPart.getFigure())
698
        this.userScale = Math.min(hScale, vScale);
81
					.getPageCount().y
699
82
					* (applyUserScale ? userScale : 1);
700
        // translate to offset figure position
83
701
        translated = new Point((int) (-figureBounds.x * userScale),
84
			float fNumRows = ((PageBreaksFigure) pageBreakEditPart.getFigure())
702
            (int) (-figureBounds.y * userScale));
85
					.getPageCount().x
703
86
					* (applyUserScale ? userScale : 1);
704
        adjustMargins(margins, userScale, getPrinterOffset());
87
705
88
			int numCols = (int) Math.ceil(fNumCols);
706
        GC gc_ = new GC(Display.getDefault());
89
			int numRows = (int) Math.ceil(fNumRows);
707
90
708
        FontData fontData = JFaceResources.getDefaultFont().getFontData()[0];
91
			return new org.eclipse.draw2d.geometry.Point(numCols, numRows);
709
        Font font = new Font(printer, fontData);
92
710
93
		} else {
711
        int row = 1, col = 1, finalRow = 0, finalColumn = 0;
94
712
        
95
			float fNumRows = (figureBounds.height * (applyUserScale ? userScale
713
        if (this.printRangePageSelection) {
96
					: 1))
714
            //print only the pages specified in the page range
97
					/ pageSize.y;
715
            //this corresponds to the physical pages, not the print range of pages on one physical page.
98
			int numRows = (int) Math.ceil(fNumRows);
716
            row = calculateRowFromPage(this.pageFrom, this.columns);
99
717
            col = calculateColumnFromPage(this.pageFrom, this.columns, row);
100
			float fNumCols = (figureBounds.width * (applyUserScale ? userScale
718
            
101
					: 1))
719
            finalRow = calculateRowFromPage(this.pageTo, this.columns);
102
					/ pageSize.x;
720
            finalColumn = calculateColumnFromPage(this.pageTo, this.columns, finalRow);
103
			int numCols = (int) Math.ceil(fNumCols);
721
        }
104
722
        
105
			return new org.eclipse.draw2d.geometry.Point(numCols, numRows);
723
        try {
106
		}
724
            // print the pages in row, column order
107
	}
725
            for (; row <= rows; row++) {
108
726
                for (; col <= columns; col++) {
109
	/**
727
                    printer.startPage();
110
	 * Calculates the row in a grid, given a page number.
728
                    drawPage(gc_, dgrmEP, fPreferences, figureBounds, margins,
111
	 * | 1 | 2 | 3 |
729
                        font, row, col);
112
	 * | 4 | 5 | 6 |
730
                    printer.endPage();
113
	 * | 7 | 8 | 9 |
731
                    
114
	 * 
732
                    if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
115
	 * Given pageNum=5 and totalNumColumns=3, will return 2
733
                        break;
116
	 * (2nd row).
734
                }
117
	 * 
735
                
118
	 * @param pageNum the page number in the grid.
736
                if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
119
	 * @param totalNumColumns total number of columns of the grid.
737
                    break;
120
	 * @return row number corresponding to the page number.
738
                
121
	 */
739
                col = 1;
122
	protected int calculateRowFromPage(int pageNum, int totalNumColumns) {
740
            }
123
		int row = pageNum / totalNumColumns;
741
        } finally {
124
		if (pageNum % totalNumColumns != 0) {
742
            // must dispose resources
125
			row++;
743
            font.dispose();
126
		}
744
            gc_.dispose();
127
		return row;
745
        }
128
	}
746
    }
129
130
	/**
131
	 * Calculates the column in a grid, given a page number.
132
	 * | 1 | 2 | 3 |
133
	 * | 4 | 5 | 6 |
134
	 * | 7 | 8 | 9 |
135
	 * 
136
	 * Given pageNum=5 and totalNumColumns=3, will return 2
137
	 * (2nd column).
138
	 *  
139
	 * @param pageNum the page number in the grid.
140
	 * @param totalNumColumns total number of columns of the grid.
141
	 * @param cRow the corresponding row of the page number.
142
	 * @return row number corresponding to the page number.
143
	 */
144
	protected int calculateColumnFromPage(int pageNum, int totalNumColumns,
145
			int cRow) {
146
147
		return (pageNum - ((cRow - 1) * totalNumColumns));
148
	}
149
150
	
151
	/**
152
	 * Disposes of the resources.
153
	 */
154
	protected void dispose() {
155
		if (this.graphics != null) {
156
			try {
157
				this.graphics.dispose();
158
			} catch (NullPointerException e) {
159
				//do nothing
160
			} finally {
161
				this.graphics = null;
162
			}
163
		}
164
165
		if (this.swtGraphics != null) {
166
			try {
167
				this.swtGraphics.dispose();
168
			} catch (NullPointerException e) {
169
				//do nothing
170
			} finally {
171
				this.swtGraphics = null;
172
			}
173
		}
174
	}
747
175
748
    /**
176
	/**
749
     * Return scale factor between printer and display.
750
     * 
751
     * @return float
752
     */
753
    private float computePrinterDisplayScale() {
754
        assert null != printer : "printer must be set"; //$NON-NLS-1$
755
        assert null != display_dpi : "display_dpi must be set"; //$NON-NLS-1$
756
757
        Point dpi = printer.getDPI();
758
        float scale = dpi.x / (float) display_dpi.x;
759
        
760
        return scale;
761
    }
762
763
    /**
764
     * Disposes of the resources.
765
     */
766
    private void dispose() {
767
        if (this.graphics != null) {
768
            try {
769
                this.graphics.dispose();
770
            }
771
            catch (NullPointerException e) {
772
                //do nothing
773
            }
774
            finally {
775
                this.graphics = null;                
776
            }
777
        }
778
        
779
        if (this.printerGraphics != null) {
780
            try {
781
                this.printerGraphics.dispose();
782
            }
783
            catch (NullPointerException e) {
784
                //do nothing
785
            }
786
            finally {
787
                this.printerGraphics = null;
788
            }
789
        }
790
        
791
        if (this.swtGraphics != null) {
792
            try {
793
                this.swtGraphics.dispose();
794
            }
795
            catch (NullPointerException e) {
796
                //do nothing
797
            }
798
            finally {
799
                this.swtGraphics = null;
800
            }
801
        }
802
        
803
        if (this.gc != null) {
804
            try {
805
                this.gc.dispose();
806
            }
807
            catch (NullPointerException e) {
808
                //do nothing
809
            }
810
            finally {
811
                this.gc = null;
812
            }
813
        }
814
        
815
        //reset the printer offset, just in case the next diagram to be printed 
816
        //uses a different map mode.
817
        printerOffset = null;
818
        
819
    }
820
    
821
    private void disposeImageVars(GC imgGC, Image image, SWTGraphics sg, 
822
            ScaledGraphics g1, MapModeGraphics mmg) {
823
        
824
        if (mmg != null) {
825
            try {
826
                mmg.dispose();
827
            }
828
            catch (NullPointerException e) {
829
                //do nothing
830
            }
831
            finally {
832
                mmg = null;                
833
            }
834
        }
835
        
836
        if (g1 != null) {
837
            try {
838
                g1.dispose();
839
            }
840
            catch (NullPointerException e) {
841
                //do nothing
842
            }
843
            finally {
844
                g1 = null;                
845
            }
846
        }
847
        
848
        if (sg != null) {
849
            try {
850
                sg.dispose();
851
            }
852
            catch (NullPointerException e) {
853
                //do nothing
854
            }
855
            finally {
856
                sg = null;                
857
            }
858
        }
859
        
860
        if (imgGC != null) {
861
            try {
862
                imgGC.dispose();
863
            }
864
            catch (NullPointerException e) {
865
                //do nothing
866
            }
867
            finally {
868
                imgGC = null;                
869
            }
870
        }
871
        
872
        if (image != null) {
873
            try {
874
                image.dispose();
875
            }
876
            catch (NullPointerException e) {
877
                //do nothing
878
            }
879
            finally {
880
                image = null;                
881
            }
882
        }
883
    }
884
885
    /**
886
     * Creates the <code>MapModeGraphics</code>.
177
     * Creates the <code>MapModeGraphics</code>.
887
     * 
178
     * 
888
     * @param theGraphics
179
     * @param theGraphics
Lines 893-949 Link Here
893
        return new MapModeGraphics(theGraphics, getMapMode());
184
        return new MapModeGraphics(theGraphics, getMapMode());
894
    }
185
    }
895
    
186
    
896
    /**
187
	public void setPrintRangePages(int pageFrom, int pageTo) {
897
     * Creates the <code>PrinterGraphics</code>.
188
		assert pageFrom > 0 : "From page in print range page selection must be bigger than zero."; //$NON-NLS-1$
898
     * 
189
		assert (pageTo > 0 && pageTo >= pageFrom) : "To page in print range page selection must be bigger than zero and from page."; //$NON-NLS-1$
899
     * @param theGraphics
190
		this.pageFrom = pageFrom;
900
     *          the <code>Graphics</code> object
191
		this.pageTo = pageTo;
901
     * @return the new <code>PrinterGraphics</code>
192
	}
902
     */
193
903
    protected PrinterGraphics createPrinterGraphics(Graphics theGraphics) {
194
	public Point getDisplayDPI() {
904
        return new PrinterGraphics(theGraphics, printer, true);
195
		return display_dpi;
905
    }
196
	}
906
    
197
907
    /**
198
	public void setDisplayDPI(Point display_dpi) {
908
     * Gets the preferences hint that is to be used to find the appropriate
199
		this.display_dpi = display_dpi;
909
     * preference store from which to retrieve diagram preference values. The
200
	}
910
     * preference hint is mapped to a preference store in the preference
201
911
     * registry <@link DiagramPreferencesRegistry>.
202
	public PreferencesHint getPreferencesHint() {
912
     * 
203
		return preferencesHint;
913
     * @return the preferences hint
204
	}
914
     */
205
915
    protected PreferencesHint getPreferencesHint() {
206
	public void setPreferencesHint(PreferencesHint preferencesHint) {
916
        return preferencesHint;
207
		this.preferencesHint = preferencesHint;
917
    }
208
	}
918
    
209
919
    /**
210
	public IMapMode getMapMode() {
920
     * Adjust the given PageMargins by the scale and offset
211
		return mapMode;
921
     * 
212
	}
922
     * @param margins PageMargins to adjust
213
923
     * @param scale margins will be scaled by this amount
214
	public void setMapMode(IMapMode mm) {
924
     * @param offset to adjust margins by
215
		this.mapMode = mm;
925
     */
216
	}
926
    protected void adjustMargins(PageMargins margins, float scale, Point offset) {
217
927
        //scale
218
	public Point getTranslated() {
928
        margins.left /= scale;
219
		return translated;
929
        margins.top /= scale;
220
	}
930
        margins.right /= scale;
221
931
        margins.bottom /= scale;
222
	public void setTranslated(Point translated) {
932
        
223
		this.translated = translated;
933
        //offsets
224
	}
934
        margins.left -= offset.x; 
225
935
        margins.right += offset.x;
226
	public float getUserScale() {
936
        margins.top -= offset.y;
227
		return userScale;
937
        margins.bottom += offset.y;
228
	}
938
        
229
939
        // this is more readable than doing Math.min for all the above
230
	public void setScaledPercent(int scalePercent) {
940
        if (margins.left < 0)
231
		this.isScaledPercent = true;
941
            margins.left = 0;
232
		this.userScale = (scalePercent) / 100.0f;
942
        if (margins.right < 0)
233
	}
943
            margins.right = 0;
234
944
        if (margins.top < 0)
235
	public void setScaledPercent(boolean isScaledPercent) {
945
            margins.top = 0;
236
		this.isScaledPercent = isScaledPercent;
946
        if (margins.bottom < 0)
237
	}
947
            margins.bottom = 0;
238
948
    }
239
	public boolean isFitToPage() {
949
}
240
		return fitToPage;
241
	}
242
243
	public void setFitToPage(boolean fitToPage) {
244
		this.fitToPage = fitToPage;
245
	}
246
247
	public boolean isPrintRangePageSelection() {
248
		return printRangePageSelection;
249
	}
250
251
	public void setPrintRangePageSelection(boolean printRangePageSelection) {
252
		this.printRangePageSelection = printRangePageSelection;
253
	}
254
255
	public int getPageFrom() {
256
		return pageFrom;
257
	}
258
259
	public void setPageFrom(int pageFrom) {
260
		this.pageFrom = pageFrom;
261
	}
262
263
	public int getPageTo() {
264
		return pageTo;
265
	}
266
267
	public void setPageTo(int pageTo) {
268
		this.pageTo = pageTo;
269
	}
270
271
	public int getRows() {
272
		return rows;
273
	}
274
275
	public void setRows(int rows) {
276
		this.rows = rows;
277
	}
278
279
	public int getColumns() {
280
		return columns;
281
	}
282
283
	public void setColumns(int columns) {
284
		this.columns = columns;
285
	}
286
287
	public Graphics getSwtGraphics() {
288
		return swtGraphics;
289
	}
290
291
	public void setSwtGraphics(Graphics swtGraphics) {
292
		this.swtGraphics = swtGraphics;
293
	}
294
295
	public Graphics getGraphics() {
296
		return graphics;
297
	}
298
299
	public void setGraphics(Graphics graphics) {
300
		this.graphics = graphics;
301
	}
302
303
	public void setDiagrams(Collection<Diagram> diagrams) {
304
		this.diagrams = diagrams;
305
	}
306
307
	public Collection<Diagram> getDiagrams() {
308
		return diagrams;
309
	}
310
311
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/util/SWTDiagramPrinter.java (+732 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2002, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
13
14
import java.util.Iterator;
15
16
import org.eclipse.core.runtime.Assert;
17
import org.eclipse.draw2d.Graphics;
18
import org.eclipse.draw2d.SWTGraphics;
19
import org.eclipse.draw2d.geometry.Rectangle;
20
import org.eclipse.gef.LayerConstants;
21
import org.eclipse.gef.RootEditPart;
22
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
23
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
24
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
25
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
26
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper;
27
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper.PageMargins;
28
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
29
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
30
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
31
import org.eclipse.gmf.runtime.diagram.ui.util.DiagramEditorUtil;
32
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.MapModeGraphics;
33
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.PrinterGraphics;
34
import org.eclipse.gmf.runtime.draw2d.ui.internal.graphics.ScaledGraphics;
35
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
36
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
37
import org.eclipse.gmf.runtime.notation.Diagram;
38
import org.eclipse.jface.preference.IPreferenceStore;
39
import org.eclipse.jface.resource.JFaceResources;
40
import org.eclipse.swt.SWT;
41
import org.eclipse.swt.graphics.Font;
42
import org.eclipse.swt.graphics.FontData;
43
import org.eclipse.swt.graphics.GC;
44
import org.eclipse.swt.graphics.Image;
45
import org.eclipse.swt.graphics.Point;
46
import org.eclipse.swt.printing.Printer;
47
import org.eclipse.swt.widgets.Display;
48
import org.eclipse.swt.widgets.Shell;
49
import org.eclipse.ui.PlatformUI;
50
51
/**
52
 * This class supports printing using the SWT printing constructs.
53
 * Much of the paging code was derived from the previous <code> DiagramPrinter </code>.
54
 *
55
 * @author James Bruck (jbruck)
56
 */
57
public class SWTDiagramPrinter extends DiagramPrinter
58
    implements Runnable {
59
60
	protected Printer printer;
61
    
62
    private GC gc;
63
        
64
    private PrinterGraphics printerGraphics;
65
    
66
    private Point printerOffset;
67
68
    private Rectangle logicalClientArea;
69
        
70
  
71
    /**
72
     * Creates a new instance. The following variables must be initialized
73
     * before calling <code>run()</code>:
74
     * <li><code>printer</code></li>
75
     * <li><code>display_dpi</code></li>
76
     * <li><code>diagrams</code></li>
77
     * @param mm <code>IMapMode</code> to do the coordinate mapping
78
     */    
79
    public SWTDiagramPrinter(PreferencesHint preferencesHint, IMapMode mm) {
80
		super(preferencesHint, mm);
81
	}
82
    
83
    /**
84
     * Creates a new instance. The following variables must be initialized
85
     * before calling <code>run()</code>:
86
     * <li><code>printer</code></li>
87
     * <li><code>display_dpi</code></li>
88
     * <li><code>diagrams</code></li>
89
     * @param mapMode <code>IMapMode</code> to do the coordinate mapping
90
     */
91
    public SWTDiagramPrinter(PreferencesHint preferencesHint) {
92
        this(preferencesHint, MapModeUtil.getMapMode());
93
  }
94
     /**
95
     * Sets the printer.
96
     * 
97
     * @param printer
98
     *            The printer to set.
99
     */
100
    public void setPrinter(Printer printer) {
101
        this.printer = printer;
102
    }
103
     
104
105
    /**
106
     * Prints the contents of the diagram editor part.
107
     */
108
    public void run() {
109
        assert null != printer : "printer must be set"; //$NON-NLS-1$
110
        if (!(printer.startJob("Printing"))) { //$NON-NLS-1$
111
          return;
112
        }
113
        
114
        assert diagrams != null;
115
        Iterator it = diagrams.iterator();
116
117
        Shell shell = new Shell();
118
        try {
119
            while (it.hasNext()) {
120
                Object obj = it.next();
121
                //the diagrams List is only supposed to have Diagram objects
122
                Assert.isTrue(obj instanceof Diagram);
123
                Diagram diagram = (Diagram)obj;
124
                DiagramEditor openedDiagramEditor = DiagramEditorUtil
125
						.findOpenedDiagramEditorForID(ViewUtil
126
								.getIdStr(diagram));
127
				DiagramEditPart dgrmEP = openedDiagramEditor == null ? PrintHelperUtil
128
						.createDiagramEditPart(diagram, preferencesHint, shell)
129
						: openedDiagramEditor.getDiagramEditPart();
130
                
131
                boolean loadedPreferences = openedDiagramEditor != null || PrintHelperUtil.initializePreferences(dgrmEP, preferencesHint);
132
133
                RootEditPart rep = dgrmEP.getRoot();
134
                if (rep instanceof DiagramRootEditPart) 
135
                    this.mapMode = ((DiagramRootEditPart)rep).getMapMode();
136
                
137
                initialize();
138
                
139
                
140
                IPreferenceStore pref = null;
141
                
142
                assert dgrmEP.getViewer() instanceof DiagramGraphicalViewer;
143
        
144
                pref = ((DiagramGraphicalViewer)dgrmEP.getViewer()).getWorkspaceViewerPreferenceStore();
145
                
146
                if (pref.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
147
                    
148
                    //get workspace settings...
149
                    if (dgrmEP.getDiagramPreferencesHint().getPreferenceStore() != null)
150
                        pref = (IPreferenceStore)dgrmEP.getDiagramPreferencesHint().getPreferenceStore(); 
151
                }
152
                
153
                doPrintDiagram(dgrmEP, loadedPreferences, pref);
154
                
155
                dispose();
156
            }
157
            printer.endJob();
158
        } finally {
159
            shell.dispose();
160
        }        
161
    }
162
       
163
164
    /**
165
     * Prints to scale or prints to rows x columns pages
166
     */
167
    protected void doPrintDiagram(DiagramEditPart dgrmEP, boolean loadedPreferences, IPreferenceStore fPreferences) {
168
        this.graphics.pushState();
169
        if (isScaledPercent) {
170
            printToScale(dgrmEP, loadedPreferences, fPreferences);
171
        } else {
172
            printToPages(dgrmEP, loadedPreferences, fPreferences);
173
        }
174
        this.graphics.popState();
175
    }
176
177
    protected void initialize() {
178
179
        assert null != printer : "printer must be set"; //$NON-NLS-1$
180
        
181
        //check for rtl orientation...
182
        int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle();
183
        if ((style & SWT.MIRRORED) != 0)
184
            this.gc = new GC(printer, SWT.RIGHT_TO_LEFT);
185
        else
186
            this.gc = new GC(printer);
187
188
        gc.setXORMode(false);
189
190
        this.swtGraphics = new SWTGraphics(gc);
191
        this.printerGraphics = createPrinterGraphics(swtGraphics);
192
        this.graphics = createMapModeGraphics(printerGraphics);
193
        this.graphics.scale(computePrinterDisplayScale());
194
        
195
        this.logicalClientArea = this.graphics.getClip(new Rectangle(
196
            this.printer.getClientArea()));
197
        
198
    }
199
    
200
    /**
201
     * Usually, the printable area is less than the page.
202
     * This method returns the offset for each x margin and each y margin.
203
     * x margins are left and right
204
     * y margins are top and bottom
205
     * 
206
     * We'll assume the left and right offsets are the same and the
207
     * top and bottom offsets are the same.
208
     * 
209
     * @return Point with x and y offsets
210
     */
211
    protected Point getPrinterOffset() {
212
        if (printerOffset == null) {
213
            int offsetX = this.printer.getBounds().width
214
            - this.printer.getClientArea().width;
215
            int offsetY = this.printer.getBounds().height
216
            - this.printer.getClientArea().height;
217
        
218
            // assume half on each side
219
            offsetX = (int) (getMapMode()
220
                .DPtoLP((int) (offsetX / 2.0f * display_dpi.x / printer.getDPI().x)) / userScale);
221
            offsetY = (int) (getMapMode()
222
                .DPtoLP((int) (offsetY / 2.0f * display_dpi.y / printer.getDPI().y)) / userScale);
223
            
224
            printerOffset = new Point(offsetX, offsetY);
225
        }
226
        
227
        return printerOffset;
228
    }
229
230
    /**
231
     * Print the diagram figure using specified scale factor.
232
     * 
233
     * @param dgrmEP the DiagramEditPart that will be printed
234
     * @param loadedPreferences true if existing prefs could be loaded
235
     * successfully, false if not and defaults are being used.  This parameter
236
     * is important to obtain the correct page break bounds.
237
     * @param fPreferences the preferenceStore that could either contain
238
     * existing preferences or defaults
239
     */
240
    protected void printToScale(DiagramEditPart dgrmEP, boolean loadedPreferences, IPreferenceStore fPreferences) {
241
242
        assert null != printer : "printer must be set"; //$NON-NLS-1$
243
        Rectangle figureBounds = PrintHelperUtil.getPageBreakBounds(dgrmEP, loadedPreferences);
244
        org.eclipse.draw2d.geometry.Point pageBounds = PageInfoHelper.getPageSize(fPreferences, getMapMode());
245
246
        //translate to offset initial figure position
247
        translated = new Point((int) (-figureBounds.x * userScale), (int) (-figureBounds.y * userScale));
248
        
249
        //calculate the number of page rows and columns
250
        int numRows = 0, numCols = 0;
251
        
252
        PageMargins margins = PageInfoHelper.getPageMargins(fPreferences, getMapMode());
253
        adjustMargins(margins, userScale, getPrinterOffset());
254
255
        GC gc_ = new GC(Display.getDefault(),this.gc.getStyle());
256
        gc_.setAntialias(this.gc.getAntialias());
257
258
        FontData fontData = JFaceResources.getDefaultFont().getFontData()[0];
259
        Font font = new Font(printer, fontData);
260
        
261
        org.eclipse.draw2d.geometry.Point pageCount = getPageCount(dgrmEP, figureBounds, pageBounds, true);
262
        numCols = pageCount.x;
263
        numRows = pageCount.y;
264
265
        //finalRow and finalColumn will be used if we are printing within a page range...
266
        int row = 1, col = 1, finalRow = 0, finalColumn = 0;
267
        
268
        if (this.printRangePageSelection) {
269
            //print only the pages specified in the page range...
270
            row = calculateRowFromPage(this.pageFrom, numCols);
271
            col = calculateColumnFromPage(this.pageFrom, numCols, row);
272
            
273
            finalRow = calculateRowFromPage(this.pageTo, numCols);
274
            finalColumn = calculateColumnFromPage(this.pageTo, numCols, finalRow);
275
        }
276
        
277
        try {
278
            //print the pages in row, column order
279
            for (; row <= numRows; row++) {
280
                for (; col <= numCols; col++) {
281
                    printer.startPage();
282
                    drawPage(gc_, dgrmEP, fPreferences, figureBounds, margins, font, row, col);
283
                    printer.endPage();
284
                    
285
                    if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
286
                        break;
287
                }
288
                
289
                if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
290
                    break;
291
                
292
                col = 1;
293
            }
294
        } finally {
295
            //must dispose resources
296
            font.dispose();
297
            gc_.dispose();
298
        }
299
    }
300
301
    /**
302
     * Draw the header and footer
303
     * 
304
     * @param gc_,
305
     *            a graphics context that is not null which this method will use
306
     *            for figuring ouyt the font's extent
307
     * @param figureBounds,
308
     *            Rectangle with the bounds of the figure
309
     * @param rowIndex,
310
     *            int
311
     * @param colIndex,
312
     *            int
313
     */
314
    protected void drawHeaderAndFooter(GC gc_, DiagramEditPart dgrmEP, Rectangle figureBounds,
315
            Font font, int rowIndex, int colIndex) {
316
317
        int width = this.logicalClientArea.width;
318
        int height = this.logicalClientArea.height;
319
320
        this.graphics.pushState(); //draw text, don't make it too small or big
321
        this.graphics.setFont(font);
322
323
        this.graphics.scale(1.0f / userScale);
324
        this.graphics.translate(-translated.x, -translated.y);
325
326
        String headerOrFooter = HeaderAndFooterHelper.makeHeaderOrFooterString(
327
            WorkspaceViewerProperties.HEADER_PREFIX, rowIndex, colIndex,
328
            dgrmEP);
329
330
        this.graphics.drawText(headerOrFooter,
331
            getMapMode().DPtoLP(HeaderAndFooterHelper.LEFT_MARGIN_DP)
332
                + (width - getMapMode().DPtoLP(gc_.textExtent(headerOrFooter).x))
333
                / 2, getMapMode().DPtoLP(HeaderAndFooterHelper.TOP_MARGIN_DP));
334
335
        headerOrFooter = HeaderAndFooterHelper.makeHeaderOrFooterString(
336
            WorkspaceViewerProperties.FOOTER_PREFIX, rowIndex, colIndex,
337
            dgrmEP);
338
339
        this.graphics.drawText(headerOrFooter,
340
            getMapMode().DPtoLP(HeaderAndFooterHelper.LEFT_MARGIN_DP)
341
                + (width - getMapMode().DPtoLP(gc_.textExtent(headerOrFooter).x))
342
                / 2, height - getMapMode().DPtoLP(HeaderAndFooterHelper.BOTTOM_MARGIN_DP));
343
344
        this.graphics.popState(); //for drawing the text
345
346
    }
347
    
348
    /**
349
     * This method paints a portion of the diagram. (The area painted
350
     * representing one page.)
351
     * 
352
     * @param gc_ a graphics context that is not null which this method will use
353
     * for figuring out the font's extent
354
     * @param dgrmEP the DiagramEditPart that will be printed
355
     * @param fPreferences the preferenceStore that could either contain
356
     * existing preferences or defaults
357
     * @param figureBounds the page break bounds we'll have to offset by
358
     * @param font the Font to print the header or footer with
359
     * @param rowIndex index of row we're printing
360
     * @param colIndex index of column we're priniting
361
     * to check if it is the first time the method is getting called for the current
362
     * print.
363
     */
364
    protected void drawPage(GC gc_, DiagramEditPart dgrmEP,
365
            IPreferenceStore fPreferences, Rectangle figureBounds,
366
            PageMargins margins, Font font, int rowIndex, int colIndex) {
367
368
        org.eclipse.draw2d.geometry.Point pageSize = PageInfoHelper
369
            .getPageSize(fPreferences, false, getMapMode());
370
        boolean rtlEnabled = ( this.gc !=null) && ((this.gc.getStyle() & SWT.MIRRORED) != 0);
371
        if (rtlEnabled) 
372
        {
373
            // draw everything on an offscreen image first and then draw that image
374
            // onto the printer gc...this takes care of certain drawing bugs.
375
            // This causes issues with printing resolution as it uses a display image
376
            // which is typically 72dpi
377
            // This code should be removed when a resolution to Bugzilla 162459 is found
378
379
            Image image = new Image(Display.getDefault(), getMapMode().LPtoDP(pageSize.x), getMapMode().LPtoDP(pageSize.y));
380
381
            GC imgGC = new GC(image, (rtlEnabled) ? SWT.RIGHT_TO_LEFT : SWT.LEFT_TO_RIGHT);
382
            imgGC.setXORMode(false);
383
      
384
            SWTGraphics sg = new SWTGraphics(imgGC);
385
              
386
            //for scaling
387
            ScaledGraphics g1 = new ScaledGraphics(sg);
388
          
389
            //for himetrics and svg
390
            MapModeGraphics mmg = createMapModeGraphics(g1);
391
              
392
            //if mmg's font is null, gc.setFont will use a default font
393
            imgGC.setFont(mmg.getFont());
394
              
395
            internalDrawPage(dgrmEP,figureBounds,fPreferences,margins,mmg,rowIndex, colIndex,true);
396
            
397
            this.graphics.pushState();
398
        
399
            this.graphics.drawImage(image, 0, 0);
400
              
401
            this.graphics.popState();
402
403
            //draw the header and footer after drawing the image to avoid getting the image getting drawn over them
404
            drawHeaderAndFooter(gc_, dgrmEP, figureBounds, font, rowIndex, colIndex);
405
            disposeImageVars(imgGC, image, sg, g1, mmg);
406
        } else {
407
            internalDrawPage(dgrmEP,figureBounds,fPreferences,margins,this.graphics,rowIndex, colIndex,false);
408
            //draw the header and footer after drawing the image to avoid getting the image getting drawn over them
409
           drawHeaderAndFooter(gc_, dgrmEP, figureBounds, font, rowIndex, colIndex);
410
        }
411
    }
412
    
413
    protected void internalDrawPage(DiagramEditPart dgrmEP,
414
            Rectangle figureBounds, IPreferenceStore fPreferences,
415
            PageMargins margins, Graphics g, int rowIndex, int colIndex,
416
            boolean RTL_ENABLED) {
417
        org.eclipse.draw2d.geometry.Point pageSize = PageInfoHelper
418
            .getPageSize(fPreferences, false, getMapMode());
419
420
        int width = pageSize.x, height = pageSize.y;
421
422
        g.pushState();
423
424
        g.translate(translated.x, translated.y);
425
        g.scale(userScale);
426
427
        int translateX = -(width * (colIndex - 1));
428
        int translateY = -(height * (rowIndex - 1));
429
430
        int scaledTranslateX = (int) (translateX / userScale);
431
        int scaledTranslateY = (int) (translateY / userScale);
432
433
        int scaledWidth = (int) (width / userScale);
434
        int scaledHeight = (int) (height / userScale);
435
436
        if (RTL_ENABLED) {
437
            scaledTranslateX += (margins.left * (colIndex - 1))
438
                + (margins.right * (colIndex));
439
            scaledTranslateY += ((margins.top * rowIndex) + (margins.bottom * (rowIndex - 1)));
440
        } else {
441
            scaledTranslateX += ((margins.left * colIndex) + (margins.right * (colIndex - 1)));
442
            scaledTranslateY += ((margins.top * rowIndex) + (margins.bottom * (rowIndex - 1)));
443
        }
444
445
        g.translate(scaledTranslateX, scaledTranslateY);
446
447
        Rectangle clip = new Rectangle(
448
            (scaledWidth - margins.left - margins.right) * (colIndex - 1)
449
                + figureBounds.x, (scaledHeight - margins.bottom - margins.top)
450
                * (rowIndex - 1) + figureBounds.y, scaledWidth - margins.right
451
                - margins.left, scaledHeight - margins.top - margins.bottom);
452
        g.clipRect(clip);
453
454
        dgrmEP.getLayer(LayerConstants.PRINTABLE_LAYERS).paint(g);
455
456
        g.popState();
457
    }
458
459
    /**
460
     * Print the diagram figure to fit the number and rows and columns
461
     * specified by the user.
462
     * 
463
     * @param dgrmEP the DiagramEditPart that will be printed
464
     * @param loadedPreferences true if existing prefs could be loaded
465
     * successfully, false if not and defaults are being used.  This parameter
466
     * is important to obtain the correct page break bounds.
467
     * @param fPreferences the preferenceStore that could either contain
468
     * existing preferences or defaults
469
     */
470
    protected void printToPages(DiagramEditPart dgrmEP,
471
            boolean loadedPreferences, IPreferenceStore fPreferences) {
472
        assert null != printer : "printer must be set"; //$NON-NLS-1$
473
474
        Rectangle figureBounds = PrintHelperUtil.getPageBreakBounds(dgrmEP,
475
            loadedPreferences);
476
        
477
        PageMargins margins = PageInfoHelper.getPageMargins(fPreferences, getMapMode());
478
        //do not include margins
479
        org.eclipse.draw2d.geometry.Point pageBounds = PageInfoHelper
480
            .getPageSize(fPreferences, getMapMode());
481
        org.eclipse.draw2d.geometry.Point pageCount = getPageCount(dgrmEP, figureBounds, pageBounds, false);
482
        int numCols = pageCount.x;
483
        int numRows = pageCount.y;
484
        
485
        float actualWidth = 0;
486
        float actualHeight = 0;
487
        if (this.rows==1 && this.columns==1 && fitToPage){
488
        	figureBounds = dgrmEP.getChildrenBounds();
489
            actualWidth = figureBounds.width;
490
            actualHeight = figureBounds.height;
491
        }else {
492
            actualWidth = numCols * pageBounds.x;
493
            actualHeight = numRows * pageBounds.y;
494
        }
495
496
        int totalHeight = (this.rows * pageBounds.y);
497
        int totalWidth  = (this.columns * pageBounds.x);
498
499
        float vScale =  totalHeight / actualHeight;
500
        float hScale = totalWidth / actualWidth;
501
502
        this.userScale = Math.min(hScale, vScale);
503
504
        // translate to offset figure position
505
        translated = new Point((int) (-figureBounds.x * userScale),
506
            (int) (-figureBounds.y * userScale));
507
508
        adjustMargins(margins, userScale, getPrinterOffset());
509
510
        GC gc_ = new GC(Display.getDefault());
511
512
        FontData fontData = JFaceResources.getDefaultFont().getFontData()[0];
513
        Font font = new Font(printer, fontData);
514
515
        int row = 1, col = 1, finalRow = 0, finalColumn = 0;
516
        
517
        if (this.printRangePageSelection) {
518
            //print only the pages specified in the page range
519
            //this corresponds to the physical pages, not the print range of pages on one physical page.
520
            row = calculateRowFromPage(this.pageFrom, this.columns);
521
            col = calculateColumnFromPage(this.pageFrom, this.columns, row);
522
            
523
            finalRow = calculateRowFromPage(this.pageTo, this.columns);
524
            finalColumn = calculateColumnFromPage(this.pageTo, this.columns, finalRow);
525
        }
526
        
527
        try {
528
            // print the pages in row, column order
529
            for (; row <= rows; row++) {
530
                for (; col <= columns; col++) {
531
                    printer.startPage();
532
                    drawPage(gc_, dgrmEP, fPreferences, figureBounds, margins,
533
                        font, row, col);
534
                    printer.endPage();
535
                    
536
                    if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
537
                        break;
538
                }
539
                
540
                if (row == finalRow && col == finalColumn && this.printRangePageSelection == true)
541
                    break;
542
                
543
                col = 1;
544
            }
545
        } finally {
546
            // must dispose resources
547
            font.dispose();
548
            gc_.dispose();
549
        }
550
    }
551
552
    /**
553
     * Return scale factor between printer and display.
554
     * 
555
     * @return float
556
     */
557
    private float computePrinterDisplayScale() {
558
        assert null != printer : "printer must be set"; //$NON-NLS-1$
559
        assert null != display_dpi : "display_dpi must be set"; //$NON-NLS-1$
560
561
        Point dpi = printer.getDPI();
562
        float scale = dpi.x / (float) display_dpi.x;
563
        
564
        return scale;
565
    }
566
567
    /**
568
     * Disposes of the resources.
569
     */
570
    protected void dispose() {
571
        if (this.graphics != null) {
572
            try {
573
                this.graphics.dispose();
574
            }
575
            catch (NullPointerException e) {
576
                //do nothing
577
            }
578
            finally {
579
                this.graphics = null;                
580
            }
581
        }
582
        
583
        if (this.printerGraphics != null) {
584
            try {
585
                this.printerGraphics.dispose();
586
            }
587
            catch (NullPointerException e) {
588
                //do nothing
589
            }
590
            finally {
591
                this.printerGraphics = null;
592
            }
593
        }
594
        
595
        if (this.swtGraphics != null) {
596
            try {
597
                this.swtGraphics.dispose();
598
            }
599
            catch (NullPointerException e) {
600
                //do nothing
601
            }
602
            finally {
603
                this.swtGraphics = null;
604
            }
605
        }
606
        
607
        if (this.gc != null) {
608
            try {
609
                this.gc.dispose();
610
            }
611
            catch (NullPointerException e) {
612
                //do nothing
613
            }
614
            finally {
615
                this.gc = null;
616
            }
617
        }
618
        
619
        //reset the printer offset, just in case the next diagram to be printed 
620
        //uses a different map mode.
621
        printerOffset = null;
622
        
623
    }
624
    
625
    private void disposeImageVars(GC imgGC, Image image, SWTGraphics sg, 
626
            ScaledGraphics g1, MapModeGraphics mmg) {
627
        
628
        if (mmg != null) {
629
            try {
630
                mmg.dispose();
631
            }
632
            catch (NullPointerException e) {
633
                //do nothing
634
            }
635
            finally {
636
                mmg = null;                
637
            }
638
        }
639
        
640
        if (g1 != null) {
641
            try {
642
                g1.dispose();
643
            }
644
            catch (NullPointerException e) {
645
                //do nothing
646
            }
647
            finally {
648
                g1 = null;                
649
            }
650
        }
651
        
652
        if (sg != null) {
653
            try {
654
                sg.dispose();
655
            }
656
            catch (NullPointerException e) {
657
                //do nothing
658
            }
659
            finally {
660
                sg = null;                
661
            }
662
        }
663
        
664
        if (imgGC != null) {
665
            try {
666
                imgGC.dispose();
667
            }
668
            catch (NullPointerException e) {
669
                //do nothing
670
            }
671
            finally {
672
                imgGC = null;                
673
            }
674
        }
675
        
676
        if (image != null) {
677
            try {
678
                image.dispose();
679
            }
680
            catch (NullPointerException e) {
681
                //do nothing
682
            }
683
            finally {
684
                image = null;                
685
            }
686
        }
687
    }
688
689
       
690
    /**
691
     * Creates the <code>PrinterGraphics</code>.
692
     * 
693
     * @param theGraphics
694
     *          the <code>Graphics</code> object
695
     * @return the new <code>PrinterGraphics</code>
696
     */
697
    protected PrinterGraphics createPrinterGraphics(Graphics theGraphics) {
698
        return new PrinterGraphics(theGraphics, printer, true);
699
    }
700
    
701
       
702
    /**
703
     * Adjust the given PageMargins by the scale and offset
704
     * 
705
     * @param margins PageMargins to adjust
706
     * @param scale margins will be scaled by this amount
707
     * @param offset to adjust margins by
708
     */
709
    protected void adjustMargins(PageMargins margins, float scale, Point offset) {
710
        //scale
711
        margins.left /= scale;
712
        margins.top /= scale;
713
        margins.right /= scale;
714
        margins.bottom /= scale;
715
        
716
        //offsets
717
        margins.left -= offset.x; 
718
        margins.right += offset.x;
719
        margins.top -= offset.y;
720
        margins.bottom += offset.y;
721
        
722
        // this is more readable than doing Math.min for all the above
723
        if (margins.left < 0)
724
            margins.left = 0;
725
        if (margins.right < 0)
726
            margins.right = 0;
727
        if (margins.top < 0)
728
            margins.top = 0;
729
        if (margins.bottom < 0)
730
            margins.bottom = 0;
731
    }
732
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/util/PrintHelperUtil.java (+296 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
13
14
import java.io.File;
15
16
import org.eclipse.core.runtime.IPath;
17
import org.eclipse.draw2d.geometry.Rectangle;
18
import org.eclipse.gef.RootEditPart;
19
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
20
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
21
import org.eclipse.gmf.runtime.diagram.ui.OffscreenEditPartFactory;
22
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
23
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
24
import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin;
25
import org.eclipse.gmf.runtime.diagram.ui.internal.editparts.PageBreakEditPart;
26
import org.eclipse.gmf.runtime.diagram.ui.internal.figures.PageBreaksFigure;
27
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageInfoHelper;
28
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
29
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
30
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
31
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
32
import org.eclipse.gmf.runtime.diagram.ui.util.DiagramEditorUtil;
33
import org.eclipse.gmf.runtime.notation.Diagram;
34
import org.eclipse.jface.preference.IPreferenceStore;
35
import org.eclipse.jface.preference.PreferenceStore;
36
import org.eclipse.swt.widgets.Display;
37
import org.eclipse.swt.widgets.Shell;
38
39
/**
40
 * Helper to assist in making an offscreen diagram suitable for printing or
41
 * previewing.
42
 * 
43
 * @author wdiu, Wayne Diu
44
 */
45
public class PrintHelperUtil {
46
	/**
47
     * Creates a <code>DiagramEditPart</code> given the <code>Diagram</code>
48
     * without opening an editor.
49
     * 
50
	 * @param diagram the <code>Diagram</code>
51
	 * @param preferencesHint the preferences hint to use for intiializing the
52
	 * preferences of the root edit part
53
	 * @return the new populated <code>DiagramEditPart</code>
54
     * @deprecated Please use
55
     *             {@link #createDiagramEditPart(Diagram, PreferencesHint, Shell)}
56
     *             instead as this method does not dispose the new Shell that it
57
     *             creates.
58
     */
59
	public static DiagramEditPart createDiagramEditPart(Diagram diagram,
60
            PreferencesHint preferencesHint) {
61
			
62
            DiagramEditPart diagramEditPart =  OffscreenEditPartFactory.getInstance().createDiagramEditPart(
63
            diagram, new Shell(), preferencesHint);
64
            // since some of the diagram updates are ASync we need to give the 
65
            // inter-thread messages a chance to get processed processed before we
66
            // continue; check bugzilla 170332
67
            while (Display.getDefault().readAndDispatch ()){
68
                // nothing special to do 
69
            }
70
             return diagramEditPart;
71
        }
72
    
73
    /**
74
     * Creates a <code>DiagramEditPart</code> given the <code>Diagram</code>
75
     * without opening an editor.
76
     * 
77
     * @param diagram the <code>Diagram</code>
78
     * @param preferencesHint the preferences hint to use for intiializing the
79
     * preferences of the root edit part
80
     * @return the new populated <code>DiagramEditPart</code>
81
     */
82
    public static DiagramEditPart createDiagramEditPart(Diagram diagram,
83
        PreferencesHint preferencesHint, Shell shell) {
84
        DiagramEditPart diagramEditPart = OffscreenEditPartFactory.getInstance().createDiagramEditPart(
85
                diagram, shell, preferencesHint);
86
        // since some of the diagram updates are ASync we need to give the 
87
        // inter-thread messages a chance to get processed before we
88
        // continue; check bugzilla 170332
89
        while (Display.getDefault().readAndDispatch ()){
90
            // nothing special to do 
91
        }
92
         return diagramEditPart;
93
    }
94
	
95
	/**
96
	 * Initialize the preferences for a diagram edit part, specifically
97
	 * including page breaks and margins.
98
	 * 
99
	 * Typically, the diagram edit part is created using
100
	 * createDiagramEditPart() and the diagram edit part is passed in as the
101
	 * first parameter of this method.
102
	 * 
103
	 * @param diagramEditPart the DiagramEditPart to pass in 
104
	 * @param preferencesHint the preferences hint to use for intiializing the preferences
105
	 * 
106
	 * @return true if the preferences could be loaded, false if they weren't
107
	 * loaded and defaults had to be used instead
108
	 */
109
	public static boolean initializePreferences(DiagramEditPart diagramEditPart, PreferencesHint preferencesHint) {
110
		assert diagramEditPart.getViewer() instanceof DiagramGraphicalViewer;
111
		
112
		DiagramGraphicalViewer viewer = (DiagramGraphicalViewer)diagramEditPart.getViewer();
113
114
		boolean loadedPreferences = true;
115
116
		IPreferenceStore fPreferences = getPreferenceStoreForDiagram(diagramEditPart);
117
		
118
		if (fPreferences == null) {
119
			loadedPreferences = false;
120
			//leave at default x and y
121
			PreferenceStore defaults = new PreferenceStore();
122
			DiagramEditor.addDefaultPreferences(defaults, preferencesHint);
123
124
			fPreferences = getWorkspacePreferenceStore(preferencesHint);
125
		} else if (!fPreferences
126
			.getBoolean(WorkspaceViewerProperties.PREF_USE_DIAGRAM_SETTINGS)) {
127
			//if we aren't supposed to use the diagram settings, switch to the
128
			//workspace settings
129
130
			//we have to use the page break x and y settings from the diagram
131
			int x = fPreferences.getInt(WorkspaceViewerProperties.PAGEBREAK_X), y = fPreferences
132
				.getInt(WorkspaceViewerProperties.PAGEBREAK_Y);
133
134
			//minor performance optimization, use the existing
135
			//preferences from the workspace instead of making a new one
136
			fPreferences = getWorkspacePreferenceStore(preferencesHint);
137
			fPreferences.setValue(WorkspaceViewerProperties.PAGEBREAK_X, x);
138
			fPreferences.setValue(WorkspaceViewerProperties.PAGEBREAK_Y, y);
139
		}
140
141
		viewer.hookWorkspacePreferenceStore(fPreferences);
142
143
		diagramEditPart.refreshPageBreaks();
144
		
145
		return loadedPreferences;
146
	}
147
148
	/**
149
	 * Returns the workspace viewer <code>PreferenceStore</code> for a given diagram edit part.
150
	 * 
151
	 * @param diagramEP the DiagramEditPart to obtain the preference store for
152
	 * 
153
	 * @return the <code>PreferenceStore</code> for the given diagram edit part
154
	 * Could return null if it couldn't be loaded 
155
	 */
156
	private static IPreferenceStore getPreferenceStoreForDiagram(DiagramEditPart diagramEP) {
157
		// Try to load it
158
		String id = ViewUtil.getIdStr(diagramEP.getDiagramView());
159
160
		//try and get preferences from the open diagrams first
161
		//loadedPreferences will be set to true only if the preferences could
162
		// be
163
		//successfully loaded
164
		IPreferenceStore fPreferences = loadPreferencesFromOpenDiagram(id);
165
		if (fPreferences != null) {
166
			//loadPreferencesFromOpenDiagram will have set preferences
167
			return fPreferences;
168
		}
169
170
		IPath path = DiagramUIPlugin.getInstance().getStateLocation();
171
172
		String fileName = path.toString() + "/" + id;//$NON-NLS-1$
173
		java.io.File file = new File(fileName);
174
		fPreferences = new PreferenceStore(fileName);
175
		if (file.exists()) {
176
			// Load it
177
			try {
178
				((PreferenceStore) fPreferences).load();
179
180
				return fPreferences;
181
			} catch (Exception e) {
182
				return null;
183
			}
184
		}
185
		return null; //fPreferences couldn't be loaded
186
	}
187
	
188
	/**
189
	 * Load the preferences from an open diagram that has the given guid.
190
	 * 
191
	 * @param id guid of the open diagram to load the preferences for 
192
	 */
193
	private static IPreferenceStore loadPreferencesFromOpenDiagram(String id) {
194
195
		DiagramEditor diagramEditor = DiagramEditorUtil.findOpenedDiagramEditorForID(id);
196
		if (diagramEditor != null) {
197
			IDiagramGraphicalViewer viewer = diagramEditor
198
					.getDiagramGraphicalViewer();
199
			if (diagramEditor.getDiagramEditPart().getRoot() instanceof DiagramRootEditPart) {
200
				PageBreakEditPart pageBreakEditPart = ((DiagramRootEditPart) diagramEditor
201
						.getDiagramEditPart().getRoot()).getPageBreakEditPart();
202
				pageBreakEditPart.resize(diagramEditor.getDiagramEditPart()
203
						.getChildrenBounds());
204
				pageBreakEditPart.updatePreferenceStore();
205
			}
206
			if (viewer instanceof DiagramGraphicalViewer) {
207
				DiagramGraphicalViewer diagramGraphicalViewer = (DiagramGraphicalViewer) viewer;
208
209
				// preferences loaded
210
				return diagramGraphicalViewer
211
						.getWorkspaceViewerPreferenceStore();
212
			}
213
		}
214
215
		// no matching guid found
216
		return null;
217
	}
218
	
219
	/**
220
	 * Return the preference store for the given PreferenceHint
221
	 * @param preferencesHint to return the preference store for.
222
	 * 
223
	 * @return preference store for the given PreferenceHint
224
	 */
225
	private static IPreferenceStore getWorkspacePreferenceStore(PreferencesHint preferencesHint) {
226
		return (IPreferenceStore) preferencesHint.getPreferenceStore();
227
	}
228
	
229
	/**
230
	 * Returns the page break bounds on the diagram. If the bounds cannot be
231
	 * found the diagram bounds is returned.
232
	 * 
233
	 * @param dgrmEP the diagram edit part to return the page break bounds for
234
	 * @param loadedPreferences true if preferences were previously loaded,
235
	 * false if they couldn't be.  For consistency when printing, we have to
236
	 * treat page breaks differently depending on whether preferences were
237
	 * successfully loaded or not.
238
	 * 
239
	 * @return Rectangle with the page break bounds for the given diagram edit
240
	 * part. If the page break bounds cannot be found the diagram bounds
241
	 * Rectangle is returned.
242
	 */
243
	public static Rectangle getPageBreakBounds(DiagramEditPart dgrmEP, boolean loadedPreferences) {
244
		
245
		Rectangle pageBreakBounds = null;
246
		assert dgrmEP.getViewer() instanceof DiagramGraphicalViewer;
247
        
248
        
249
        //get the preferences in use...
250
        IPreferenceStore fPreferences = ((DiagramGraphicalViewer)dgrmEP.getViewer()).getWorkspaceViewerPreferenceStore();
251
        
252
        if (fPreferences.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
253
            
254
            //get workspace settings...
255
            if (dgrmEP.getDiagramPreferencesHint().getPreferenceStore() != null)
256
                fPreferences = (IPreferenceStore)dgrmEP.getDiagramPreferencesHint().getPreferenceStore(); 
257
        }
258
        
259
		RootEditPart rootEditPart = dgrmEP.getRoot();
260
		if (rootEditPart instanceof DiagramRootEditPart) {
261
			DiagramRootEditPart diagramRootEditPart = (DiagramRootEditPart) rootEditPart;
262
			PageBreakEditPart pageBreakEditPart = diagramRootEditPart
263
				.getPageBreakEditPart();
264
265
			if (pageBreakEditPart != null) {
266
				//resize must be called. Otherwise you get the 64 x 32 default
267
				pageBreakEditPart.resize(dgrmEP.getChildrenBounds());
268
269
				if (loadedPreferences) {
270
					//if preferences were loaded, we'll always do this for
271
					//consistency when printing.
272
					//this is necessary when printing using workspace
273
					//preferences, which is "if (getWorkspacePreferenceStore()
274
					//== fPreferences)"
275
276
					//if preferences were not loaded, we do not set the figure
277
					//location. we'll just leave them at defaults.
278
					org.eclipse.draw2d.geometry.Point p = new org.eclipse.draw2d.geometry.Point(
279
						fPreferences
280
							.getInt(WorkspaceViewerProperties.PAGEBREAK_X),
281
						fPreferences
282
							.getInt(WorkspaceViewerProperties.PAGEBREAK_Y));
283
					pageBreakEditPart.set(p, PageInfoHelper.getChildrenBounds(
284
						(DiagramEditPart) diagramRootEditPart.getContents(),
285
						PageBreaksFigure.class));
286
				}
287
288
				pageBreakBounds = pageBreakEditPart.getFigure().getBounds();
289
			} else {
290
				pageBreakBounds = dgrmEP.getFigure().getBounds();
291
			}
292
		}
293
294
		return pageBreakBounds;
295
	}	
296
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/util/DiagramPrinterHelper.java (+169 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
13
14
import java.text.NumberFormat;
15
import java.text.ParseException;
16
import java.util.List;
17
import java.util.Map;
18
19
import org.eclipse.gmf.runtime.common.core.util.Log;
20
import org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper;
21
import org.eclipse.gmf.runtime.diagram.ui.internal.pagesetup.PageSetupPageType;
22
import org.eclipse.gmf.runtime.diagram.ui.internal.properties.WorkspaceViewerProperties;
23
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
24
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
25
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
26
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingPlugin;
27
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingStatusCodes;
28
import org.eclipse.jface.preference.IPreferenceStore;
29
import org.eclipse.swt.printing.PrinterData;
30
import org.eclipse.ui.IEditorPart;
31
32
/**
33
 * Utility for using the DiagramPrinter to print diagrams after displaying
34
 * a print dialog box to the user.  Diagrams are printed using the
35
 * DiagramPrinter and respect the settings chosen by the user in the print
36
 * dialog. 
37
 * 
38
 * Basic functionality was factored into this class from the DiagramPrinterUtil.
39
 * This class and its specializing classes:
40
 * JPSDiagramPrinterHelper and SWTDiagramPrinterHelper will be subject to change
41
 * during phase 2 of printing enhancement changes.
42
 * 
43
 */
44
public class DiagramPrinterHelper {
45
46
	/**
47
	 * Prints a diagram with the settings from the helper onto the printer
48
	 * 
49
	 * @param diagramPrinter
50
	 *            the diagram printer that does the work of actually
51
	 *            printing the diagrams
52
	 * @param helper
53
	 *            IPrintHelper with the user's choice of settings
54
	 */
55
	protected void printDiagrams(DiagramPrinter diagramPrinter,
56
			IPrintHelper helper) {
57
58
		if (helper.getDlgPrintRangePages()) {
59
			diagramPrinter.setPrintRangePageSelection(true);
60
			diagramPrinter.setPrintRangePages(helper.getDlgPagesFrom(), helper
61
					.getDlgPagesTo());
62
			diagramPrinter.setFitToPage(false);
63
		}
64
65
		if (helper.getDlgScalePercent() == -1) {
66
			diagramPrinter.setColumns(helper.getDlgScaleFitToM());
67
			diagramPrinter.setRows(helper.getDlgScaleFitToN());
68
			diagramPrinter.setFitToPage(true);
69
		} else {
70
			diagramPrinter.setScaledPercent(helper.getDlgScalePercent());
71
			diagramPrinter.setFitToPage(false);
72
		}
73
74
		diagramPrinter.run();
75
	}
76
77
	/**
78
	 *   A helper that simply collects printing information.
79
	 *  
80
	 * @param diagramPrinter
81
	 * @param helper
82
	 * @param diagramNames
83
	 * @param editorPart
84
	 * @param diagramMap
85
	 * @return
86
	 */
87
	protected PrinterData collectPrintInformation(
88
			DiagramPrinter diagramPrinter, IPrintHelper helper,
89
			List diagramNames, IEditorPart editorPart, Map diagramMap) {
90
91
		PrinterData printerData;
92
93
		IPreferenceStore pref = null;
94
95
		if (editorPart instanceof IDiagramWorkbenchPart) {
96
97
			IDiagramGraphicalViewer viewer = ((IDiagramWorkbenchPart) editorPart)
98
					.getDiagramGraphicalViewer();
99
			if (viewer instanceof DiagramGraphicalViewer) {
100
101
				pref = ((DiagramGraphicalViewer) viewer)
102
						.getWorkspaceViewerPreferenceStore();
103
104
				if (pref
105
						.getBoolean(WorkspaceViewerProperties.PREF_USE_WORKSPACE_SETTINGS)) {
106
107
					if (((IDiagramWorkbenchPart) editorPart)
108
							.getDiagramEditPart().getDiagramPreferencesHint()
109
							.getPreferenceStore() != null) {
110
						pref = (IPreferenceStore) ((IDiagramWorkbenchPart) editorPart)
111
								.getDiagramEditPart()
112
								.getDiagramPreferencesHint()
113
								.getPreferenceStore();
114
					}
115
				}
116
			}
117
		}
118
		if (pref != null) {
119
			helper.setDlgOrientation(pref
120
					.getBoolean(WorkspaceViewerProperties.PREF_USE_LANDSCAPE));
121
122
			PageSetupPageType storedPageType = PageSetupPageType.LETTER; //default value
123
			String strPageType = pref
124
					.getString(WorkspaceViewerProperties.PREF_PAGE_SIZE);
125
			for (int i = 0; i < PageSetupPageType.pages.length; i++) {
126
				if (strPageType
127
						.startsWith(PageSetupPageType.pages[i].getName())) {
128
					storedPageType = PageSetupPageType.pages[i];
129
					break;
130
				}
131
			}
132
			if (storedPageType.getIndex() == PageSetupPageType.USER_DEFINED
133
					.getIndex()) {
134
135
				NumberFormat fNumberFormat = NumberFormat.getNumberInstance();
136
137
				String strWidth = pref
138
						.getString(WorkspaceViewerProperties.PREF_PAGE_WIDTH);
139
				String strHeight = pref
140
						.getString(WorkspaceViewerProperties.PREF_PAGE_HEIGHT);
141
				double width = 0, height = 0;
142
143
				try {
144
					Number num = fNumberFormat.parse(strWidth);
145
					width = num.doubleValue() / 0.0394d; //convert from inches to mm
146
147
					num = fNumberFormat.parse(strHeight);
148
					height = num.doubleValue() / 0.0394d;
149
150
					helper.setDlgPaperSize(PageSetupPageType.USER_DEFINED
151
							.getIndex(), width, height);
152
				} catch (ParseException e) {
153
					Log
154
							.warning(
155
									DiagramPrintingPlugin.getInstance(),
156
									DiagramPrintingStatusCodes.IGNORED_EXCEPTION_WARNING,
157
									e.getMessage(), e);
158
				}
159
			} else {
160
				helper.setDlgPaperSize(storedPageType.getIndex(), 0, 0);
161
			}
162
		}
163
164
		printerData = helper.openPrintDlg(diagramNames);
165
166
		return printerData;
167
	}
168
169
}
(-)src/org/eclipse/gmf/runtime/diagram/ui/printing/internal/util/SWTDiagramPrinterHelper.java (+209 lines)
Added Link Here
1
/******************************************************************************
2
 * Copyright (c) 2004,2006 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *    IBM Corporation - initial API and implementation 
10
 ****************************************************************************/
11
12
package org.eclipse.gmf.runtime.diagram.ui.printing.internal.util;
13
14
import java.util.ArrayList;
15
import java.util.Collections;
16
import java.util.List;
17
import java.util.Map;
18
19
import org.eclipse.gmf.runtime.common.core.util.Log;
20
import org.eclipse.gmf.runtime.common.core.util.Trace;
21
import org.eclipse.gmf.runtime.common.ui.printing.IPrintHelper;
22
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
23
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
24
import org.eclipse.gmf.runtime.diagram.ui.printing.actions.DefaultPrintActionHelper;
25
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingDebugOptions;
26
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingPlugin;
27
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.DiagramPrintingStatusCodes;
28
import org.eclipse.gmf.runtime.diagram.ui.printing.internal.l10n.DiagramUIPrintingMessages;
29
import org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil;
30
import org.eclipse.gmf.runtime.notation.Diagram;
31
import org.eclipse.jface.dialogs.MessageDialog;
32
import org.eclipse.swt.printing.Printer;
33
import org.eclipse.swt.printing.PrinterData;
34
import org.eclipse.swt.widgets.Display;
35
import org.eclipse.ui.IEditorPart;
36
37
/**
38
 * Utility for using the DiagramPrinter to print diagrams after displaying a
39
 * print dialog box to the user. Diagrams are printed using the DiagramPrinter
40
 * and respect the settings chosen by the user in the print dialog.
41
 * 
42
 * This class uses the SWT printing to accomplish its task. This class was
43
 * derived from
44
 * 
45
 * @see org.eclipse.gmf.runtime.diagram.ui.printing.util.DiagramPrinterUtil
46
 * 
47
 * This class is subject to change/removal during phase 2 of printing
48
 * enhancements
49
 * 
50
 */
51
public class SWTDiagramPrinterHelper extends DiagramPrinterHelper {
52
53
	private static SWTDiagramPrinterHelper diagramPrinterHelper;
54
55
	public static SWTDiagramPrinterHelper getDiagramPrinterHelper() {
56
		if (diagramPrinterHelper == null) {
57
			diagramPrinterHelper = new SWTDiagramPrinterHelper();
58
		}
59
		return diagramPrinterHelper;
60
	}
61
62
	/**
63
	 * Prevent instantiation.
64
	 */
65
	private SWTDiagramPrinterHelper() {
66
	}
67
68
	/**
69
	 * Opens up the print diagrams dialog, allows the user to choose the
70
	 * settings, and prints.
71
	 * 
72
	 * @param editorPart
73
	 *            current editor part
74
	 * @param diagramMap
75
	 *            map of String names to Diagram objects. Should be initialized
76
	 *            by caller of this method. String names will show up in the
77
	 *            print dialog that allows the user to choose which diagrams to
78
	 *            print from a list.
79
	 * @param diagramPrinter
80
	 *            the diagram printer that does the work of actually printing
81
	 *            the diagrams
82
	 */
83
	public void printWithSettings(IEditorPart editorPart, Map<String, Diagram> diagramMap,
84
			SWTDiagramPrinter diagramPrinter) {
85
86
		List diagramNames;
87
		PrinterData printerData;
88
		IPrintHelper helper;
89
90
		try {
91
			Class printhelperClass = Class
92
					.forName(IPrintHelper.PRINT_HELPER_CLASS_NAME);
93
			helper = (IPrintHelper) printhelperClass.newInstance();
94
			diagramNames = new ArrayList(diagramMap.keySet());
95
96
			printerData = collectPrintInformation(diagramPrinter, helper,
97
					diagramNames, editorPart, diagramMap);
98
99
			if (printerData != null) {
100
				
101
				final Printer printer = new Printer(printerData);
102
103
				diagramPrinter.setPrinter(printer);
104
				diagramPrinter.setDisplayDPI(Display.getDefault().getDPI());
105
106
				if (helper.getDlgDiagramPrintRangeCurrent()) {
107
					DiagramEditPart dgrmEP = ((IDiagramWorkbenchPart) editorPart)
108
							.getDiagramEditPart();
109
					assert dgrmEP != null;
110
					diagramPrinter.setDiagrams(Collections.singletonList(dgrmEP
111
							.getDiagramView().getDiagram()));
112
				} else if (helper.getDlgDiagramPrintRangeAll()) {
113
					diagramPrinter.setDiagrams(diagramMap.values());
114
				} else if (helper.getDlgDiagramPrintRangeSelection()) {
115
					Object obj;
116
					List list = new ArrayList();
117
					for (int i = 0; i < diagramNames.size(); i++) {
118
						// is the diagram selected?
119
						// we are only printing the selected ones
120
						if (helper.isDlgDiagramSelected(i)) {
121
122
							obj = diagramMap.get(diagramNames.get(i));
123
							if (obj instanceof Diagram) {
124
125
								list.add(obj);
126
							}
127
						}
128
					}
129
					diagramPrinter.setDiagrams(list);
130
				}
131
132
				printDiagrams(diagramPrinter, helper);
133
134
				printer.dispose();
135
			}
136
		} catch (Throwable e) {
137
			// if there's a problem with the fragment, try doing the default
138
			// this is better than nothing
139
			Trace.catching(DiagramPrintingPlugin.getInstance(),
140
					DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
141
					DiagramPrinterUtil.class, e.getMessage(), e);
142
			Log.warning(DiagramPrintingPlugin.getInstance(),
143
					DiagramPrintingStatusCodes.RESOURCE_FAILURE,
144
					e.getMessage(), e);
145
146
			if (MessageDialog
147
					.openQuestion(
148
							Display.getDefault().getActiveShell(),
149
							DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorTitle,
150
							DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part1
151
									+ "\n" //$NON-NLS-1$
152
									+ DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part2
153
									+ "\n" //$NON-NLS-1$
154
									+ DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part3
155
									+ "\n\n" //$NON-NLS-1$
156
									+ DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part4)) {
157
				DefaultPrintActionHelper.doRun(editorPart, diagramPrinter);
158
			}
159
160
			return;
161
		}
162
163
	}
164
165
	/**
166
	 * A helper that simply collects printing information.
167
	 * 
168
	 * @param diagramPrinter
169
	 * @param helper
170
	 * @param diagramNames
171
	 * @param editorPart
172
	 * @param diagramMap
173
	 * @return
174
	 */
175
	private PrinterData collectPrintInformation(
176
			SWTDiagramPrinter diagramPrinter, IPrintHelper helper,
177
			List diagramNames, IEditorPart editorPart, Map diagramMap) {
178
179
		PrinterData printerData = null;
180
		try {
181
			printerData = super.collectPrintInformation(diagramPrinter, helper,
182
					diagramNames, editorPart, diagramMap);
183
		} catch (Throwable e) {
184
			// if there's a problem with the fragment, try doing the default
185
			// this is better than nothing
186
			Trace.catching(DiagramPrintingPlugin.getInstance(),
187
					DiagramPrintingDebugOptions.EXCEPTIONS_CATCHING,
188
					DiagramPrinterUtil.class, e.getMessage(), e);
189
			Log.warning(DiagramPrintingPlugin.getInstance(),
190
					DiagramPrintingStatusCodes.RESOURCE_FAILURE,
191
					e.getMessage(), e);
192
193
			if (MessageDialog
194
					.openQuestion(
195
							Display.getDefault().getActiveShell(),
196
							DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorTitle,
197
							DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part1
198
									+ "\n" //$NON-NLS-1$
199
									+ DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part2
200
									+ "\n" //$NON-NLS-1$
201
									+ DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part3
202
									+ "\n\n" //$NON-NLS-1$
203
									+ DiagramUIPrintingMessages.DiagramPrinterUtil_DLLErrorMessage_part4)) {
204
				DefaultPrintActionHelper.doRun(editorPart, diagramPrinter);
205
			}
206
		}
207
		return printerData;
208
	}
209
}
(-)src/org/eclipse/gmf/runtime/common/ui/action/actions/global/GlobalPrintAction.java (-10 / +10 lines)
Lines 1-5 Link Here
1
/******************************************************************************
1
/******************************************************************************
2
 * Copyright (c) 2002, 2005 IBM Corporation and others.
2
 * Copyright (c) 2002, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
Lines 10-26 Link Here
10
 ****************************************************************************/
10
 ****************************************************************************/
11
11
12
package org.eclipse.gmf.runtime.common.ui.action.actions.global;
12
package org.eclipse.gmf.runtime.common.ui.action.actions.global;
13
import org.eclipse.jface.resource.ImageDescriptor;
14
import org.eclipse.ui.IWorkbenchPage;
15
import org.eclipse.ui.IWorkbenchPart;
16
import org.eclipse.ui.PlatformUI;
17
18
import org.eclipse.gmf.runtime.common.ui.action.global.GlobalAction;
13
import org.eclipse.gmf.runtime.common.ui.action.global.GlobalAction;
19
import org.eclipse.gmf.runtime.common.ui.action.global.GlobalActionId;
14
import org.eclipse.gmf.runtime.common.ui.action.global.GlobalActionId;
20
import org.eclipse.gmf.runtime.common.ui.action.internal.CommonUIActionPlugin;
15
import org.eclipse.gmf.runtime.common.ui.action.internal.CommonUIActionPlugin;
21
import org.eclipse.gmf.runtime.common.ui.action.internal.IHelpContextIds;
16
import org.eclipse.gmf.runtime.common.ui.action.internal.IHelpContextIds;
22
import org.eclipse.gmf.runtime.common.ui.action.internal.l10n.CommonUIActionMessages;
17
import org.eclipse.gmf.runtime.common.ui.action.internal.l10n.CommonUIActionMessages;
23
import org.eclipse.gmf.runtime.common.ui.action.internal.l10n.CommonUIActionPluginImages;
18
import org.eclipse.gmf.runtime.common.ui.action.internal.l10n.CommonUIActionPluginImages;
19
import org.eclipse.jface.resource.ImageDescriptor;
20
import org.eclipse.ui.IWorkbenchPage;
21
import org.eclipse.ui.IWorkbenchPart;
22
import org.eclipse.ui.PlatformUI;
24
23
25
/**
24
/**
26
 * Global action for printing
25
 * Global action for printing
Lines 88-99 Link Here
88
	 * @see org.eclipse.gmf.runtime.common.ui.action.IRepeatableAction#refresh()
87
	 * @see org.eclipse.gmf.runtime.common.ui.action.IRepeatableAction#refresh()
89
	 */
88
	 */
90
	public void refresh() {
89
	public void refresh() {
91
		//also only allows printing for windows, don't test for windows in the
90
		//
92
		//global action handler's canHandle, because that's for selection
91
		// In phase 2 of printing enhancements we will remove the OS restriction.
93
		//changes
92
		//
94
		setEnabled(!getGlobalActionHandlerData().isEmpty() && System.getProperty("os.name").toUpperCase().startsWith("WIN")); //$NON-NLS-1$ //$NON-NLS-2$
93
		setEnabled(!getGlobalActionHandlerData().isEmpty() && System.getProperty("os.name").toUpperCase().startsWith("WIN")); //$NON-NLS-1$ //$NON-NLS-2$
94
		
95
	}
95
	}
96
96
	
97
	/* (non-Javadoc)
97
	/* (non-Javadoc)
98
	 * @see org.eclipse.gmf.runtime.common.ui.action.AbstractActionHandler#isSelectionListener()
98
	 * @see org.eclipse.gmf.runtime.common.ui.action.AbstractActionHandler#isSelectionListener()
99
	 */
99
	 */

Return to bug 196834