Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 80318 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/uml2/diagram/parser/lookup/LookupResolverImpl.java (+106 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import java.util.List;
16
17
import org.eclipse.core.commands.ExecutionException;
18
import org.eclipse.core.runtime.IAdaptable;
19
import org.eclipse.core.runtime.IProgressMonitor;
20
import org.eclipse.emf.ecore.EObject;
21
import org.eclipse.emf.transaction.TransactionalEditingDomain;
22
import org.eclipse.gef.commands.Command;
23
import org.eclipse.gef.requests.CreateRequest;
24
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
25
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
26
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateUnspecifiedTypeRequest;
27
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
28
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
29
import org.eclipse.gmf.runtime.notation.View;
30
import org.eclipse.uml2.uml.NamedElement;
31
32
33
public class LookupResolverImpl implements LookupResolver {
34
	private LookupResolveRequest myTheOnlyRequest;
35
	private Callback myTheOnlyCallback;
36
	private boolean myIsMultipleResolveRequired;
37
	private final IGraphicalEditPart myResolvingEditPart;
38
	
39
	public LookupResolverImpl(IGraphicalEditPart resolvingEditPart){
40
		myResolvingEditPart = resolvingEditPart;
41
	}
42
	
43
	public void addLookupResolveRequest(LookupResolveRequest request, Callback callback){
44
		if (isEmpty()){
45
			myTheOnlyCallback = callback;
46
			myTheOnlyRequest = request;
47
		} else {
48
			myIsMultipleResolveRequired = true;
49
		}
50
	}
51
	
52
	public boolean isEmpty(){
53
		return myTheOnlyCallback == null && myTheOnlyRequest == null;
54
	}
55
	
56
	public boolean canResolve(){
57
		return !isEmpty() && !myIsMultipleResolveRequired;
58
	}
59
	
60
	public AbstractTransactionalCommand getResolveCommand() {
61
		if (!canResolve()){
62
			return null;
63
		}
64
		TransactionalEditingDomain domain = myResolvingEditPart.getEditingDomain();
65
		final CreateUnspecifiedTypeRequest createRequest = new CreateUnspecifiedTypeRequest(myTheOnlyRequest.getElementTypes(), myResolvingEditPart.getDiagramPreferencesHint());
66
		final Command gefCommand = myResolvingEditPart.getCommand(createRequest);
67
		if (!gefCommand.canExecute()){
68
			return null;
69
		}
70
		//XXX gef inside transactional command???
71
		return new AbstractTransactionalCommand(domain, "", null){
72
			@Override
73
			protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
74
				gefCommand.execute();
75
				NamedElement resolution = getNewObject();
76
				if (resolution != null){
77
					resolution.eSet(myTheOnlyRequest.getInitFeature(), myTheOnlyRequest.getInitValue());
78
					myTheOnlyCallback.lookupResolved(resolution);
79
				}
80
				return CommandResult.newOKCommandResult();
81
			}
82
			
83
			private NamedElement getNewObject(){
84
				for (Object next : createRequest.getElementTypes()){
85
					IElementType nextElementType = (IElementType)next;
86
					CreateRequest nextRequest = createRequest.getRequestForType(nextElementType);
87
					List allNew = (List)nextRequest.getNewObject();
88
					for (Object nextCreated : allNew){
89
						if (nextCreated instanceof IAdaptable){
90
							View createdView = (View) ((IAdaptable)nextCreated).getAdapter(View.class);
91
							if (createdView != null) {
92
								EObject createdEntity = createdView.getElement(); 
93
								if (createdEntity instanceof NamedElement){
94
									return (NamedElement)createdEntity;
95
								}
96
							}
97
						}
98
					}
99
				}
100
				return null;
101
			}
102
		};
103
	}
104
	
105
106
}
(-)build.properties (+4 lines)
Added Link Here
1
source.. = src/
2
output.. = bin/
3
bin.includes = META-INF/,\
4
               .
(-)src/org/eclipse/uml2/diagram/parser/ParserAdapter.java (+208 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import java.util.Iterator;
16
import java.util.LinkedList;
17
import java.util.List;
18
19
import org.eclipse.core.commands.ExecutionException;
20
import org.eclipse.core.runtime.IAdaptable;
21
import org.eclipse.core.runtime.IProgressMonitor;
22
import org.eclipse.emf.common.notify.Notification;
23
import org.eclipse.emf.ecore.EObject;
24
import org.eclipse.emf.ecore.EStructuralFeature;
25
import org.eclipse.emf.transaction.TransactionalEditingDomain;
26
import org.eclipse.emf.transaction.util.TransactionUtil;
27
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
28
import org.eclipse.gmf.runtime.common.core.command.ICommand;
29
import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand;
30
import org.eclipse.gmf.runtime.common.ui.services.parser.IParser;
31
import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus;
32
import org.eclipse.gmf.runtime.common.ui.services.parser.ParserEditStatus;
33
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
34
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
35
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
36
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
37
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
38
import org.eclipse.uml2.diagram.parser.lookup.LookupResolver;
39
import org.eclipse.uml2.diagram.parser.lookup.LookupResolverImpl;
40
import org.eclipse.uml2.diagram.parser.lookup.LookupSuite;
41
import org.eclipse.uml2.internal.diagram.parser.MDTDiagramParserPlugin;
42
43
public class ParserAdapter implements IParser {
44
	private static final String NOT_AN_OBJECT = "Unknown";
45
	private final ExternalParserBase myDelegate;
46
	private final EObject myTester;
47
	private final ApplyStrategy myApplier;
48
	private final ExternalToString myView;
49
	private final ExternalToString myEdit;
50
	private final static MessageFormatEscaper ourMessageFormatEscaper = new MessageFormatEscaper();
51
	
52
	public ParserAdapter(ExternalParserBase delegate, ApplyStrategy applier){
53
		this(delegate, applier, ExternalToString.NOT_IMPLEMENTED);
54
	}
55
	
56
	public ParserAdapter(ExternalParserBase delegate, ApplyStrategy applier, ExternalToString viewAndEdit){
57
		this(delegate, applier, viewAndEdit, viewAndEdit);
58
	}
59
60
	public ParserAdapter(ExternalParserBase delegate, ApplyStrategy applier, ExternalToString view, ExternalToString edit){
61
		myDelegate = delegate;
62
		myApplier = applier;
63
		myView = view;
64
		myEdit = edit;
65
		myTester = myDelegate.createSubjectPrototype();
66
	}
67
	
68
	public IContentAssistProcessor getCompletionProcessor(IAdaptable element) {
69
		return null;
70
	}
71
	
72
	public String getEditString(IAdaptable element, int flags) {
73
		return getToString(element, flags, myEdit);
74
	}
75
	
76
	public String getPrintString(IAdaptable element, int flags) {
77
		return getToString(element, flags, myView);
78
	}
79
	
80
	public final boolean isAffectingEvent(Object event, int flags) {
81
		return isAffectingEvent(event);
82
	}
83
	
84
	protected boolean isAffectingEvent(Object event){
85
		if (event instanceof Notification) {
86
			Object feature = ((Notification) event).getFeature();
87
			return (feature instanceof EStructuralFeature) && myView.isAffectingFeature((EStructuralFeature)feature);
88
		}
89
		return false;
90
	}
91
	
92
	public IParserEditStatus isValidEditString(IAdaptable adapter, String editString) {
93
		EObject modelObject = (EObject) adapter.getAdapter(EObject.class);
94
		if (modelObject == null) {
95
			return new ParserEditStatus(
96
					MDTDiagramParserPlugin.getPluginID(), IParserEditStatus.UNEDITABLE, 
97
					"Can not find context object");			
98
		}
99
		
100
		LookupSuite oldLookup = myDelegate.getLookupSuite();
101
		try {
102
			myDelegate.setLookupSuite(LookupSuite.NULL_SUITE);
103
			myDelegate.parse(myTester, editString, modelObject);
104
			return ParserEditStatus.EDITABLE_STATUS;
105
		} catch (ExternalParserException e) {
106
			//CellEditor uses MessageFormat to format the message
107
			//we need to escape '{', '}', '\' to prevent failure while formatting an error
108
			String message = e.getMessage();
109
			if (message == null){
110
				message = "";
111
			}
112
			message = ourMessageFormatEscaper.getEscaped(message);
113
			return new ParserEditStatus(
114
					MDTDiagramParserPlugin.getPluginID(), IParserEditStatus.UNEDITABLE, 
115
					"Invalid input: " + message);			
116
		} finally {
117
			myDelegate.setLookupSuite(oldLookup);
118
		}
119
	}
120
	
121
	public ICommand getParseCommand(IAdaptable adapter, String newString, int flags) {
122
		final EObject modelObject = (EObject) adapter.getAdapter(EObject.class);
123
		if (modelObject == null) {
124
			return UnexecutableCommand.INSTANCE;
125
		}
126
		TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(modelObject);
127
		if (editingDomain == null) {
128
			return UnexecutableCommand.INSTANCE;
129
		}
130
		
131
		IGraphicalEditPart diagramEditPart = (DiagramEditPart)adapter.getAdapter(DiagramEditPart.class);
132
		LookupResolver resolver = LookupResolver.NULL;
133
		if (diagramEditPart != null){
134
			resolver = new LookupResolverImpl(diagramEditPart);
135
		}
136
		myDelegate.setLookupResolver(resolver);
137
		
138
		final EObject parsed; 
139
		try {
140
			parsed = myDelegate.parseNewObject(modelObject, newString);
141
		} catch (ExternalParserException e){
142
			//strange
143
			//e.printStackTrace();
144
			return UnexecutableCommand.INSTANCE;
145
		} finally {
146
			myDelegate.setLookupResolver(null);
147
		}
148
		
149
		List commandList = new LinkedList();
150
		if (resolver.canResolve()){
151
			AbstractTransactionalCommand resolveCommand = resolver.getResolveCommand();
152
			AbstractTransactionalCommand computeAndApplyCommand = new AbstractTransactionalCommand(editingDomain, "", null){
153
				@Override
154
				protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
155
					for (Iterator applyCommands = myApplier.apply(modelObject, parsed).iterator(); applyCommands.hasNext();){
156
						ICommand next = (ICommand)applyCommands.next();
157
						next.execute(monitor, info);
158
					}
159
					return CommandResult.newOKCommandResult();
160
				}
161
			};
162
			commandList.add(resolveCommand);
163
			commandList.add(computeAndApplyCommand);
164
		} else {
165
			commandList.addAll(myApplier.apply(modelObject, parsed));
166
		}
167
		return new CompositeTransactionalCommand(editingDomain, getCommandLabel(commandList), commandList);
168
	}
169
	
170
	protected final ExternalToString getViewToString() {
171
		return myView;
172
	}
173
	
174
	private String getToString(IAdaptable element, int flags, ExternalToString toString) {
175
		EObject modelObject = (EObject) element.getAdapter(EObject.class);
176
		return isValidElement(modelObject) ? toString.getToString(modelObject, flags) : NOT_AN_OBJECT;
177
	}
178
	
179
	private String getCommandLabel(List/*1.5 <ICommand>*/ commandList){
180
		return "-not-implemented-";
181
	}
182
	
183
	protected final boolean isValidElement(Object object){
184
		return object != null && myDelegate.getSubjectClass().isInstance(object);
185
	}
186
	
187
	private static class MessageFormatEscaper {
188
		private final char S_QUOTE = '\'';
189
		
190
		public String getEscaped(String input){
191
			if (!input.contains("'")){
192
				return "'" + input + "'";
193
			}
194
			StringBuffer result = new StringBuffer(input.length() + 5);
195
			result.append(S_QUOTE);
196
			for (int i = 0; i < input.length(); i++){
197
				char next = result.charAt(i);
198
				if (next == S_QUOTE){
199
					result.append(S_QUOTE);
200
				}
201
				result.append(next);
202
			}
203
			result.append(S_QUOTE);
204
			return result.toString();
205
		}
206
	}
207
	
208
}
(-)src/org/eclipse/uml2/diagram/parser/lookup/LookupResolveRequest.java (+43 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import java.util.List;
16
17
import org.eclipse.emf.ecore.EStructuralFeature;
18
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
19
20
public class LookupResolveRequest {
21
	private final List<IElementType> myElementTypes;
22
	private final EStructuralFeature myInitFeature;
23
	private final Object myInitValue;
24
25
	public LookupResolveRequest(List<IElementType> elementTypes, EStructuralFeature initFeature, Object initValue){
26
		myElementTypes = elementTypes;
27
		myInitFeature = initFeature;
28
		myInitValue = initValue;
29
	}
30
	
31
	public List<IElementType> getElementTypes() {
32
		return myElementTypes;
33
	}
34
	
35
	public EStructuralFeature getInitFeature() {
36
		return myInitFeature;
37
	}
38
	
39
	public Object getInitValue() {
40
		return myInitValue;
41
	}
42
	
43
}
(-)src/org/eclipse/uml2/diagram/parser/ApplyStrategy.java (+25 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import java.util.Collections;
16
import java.util.List;
17
18
import org.eclipse.emf.ecore.EObject;
19
import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand;
20
21
public interface ApplyStrategy {
22
	public List/*1.5 <ICommand>*/ apply(EObject modelObject, EObject parsedObject);
23
	
24
	public static final List/*1.5 <ICommand>*/ NOT_EXECUTABLE = Collections.singletonList(UnexecutableCommand.INSTANCE);
25
}
(-)src/org/eclipse/uml2/diagram/parser/lookup/LookupSuiteImpl.java (+44 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import java.util.HashMap;
16
17
public class LookupSuiteImpl implements LookupSuite {
18
	private final HashMap<Class, Lookup> myLookups = new HashMap<Class, Lookup>();
19
	private LookupResolver myLookupResolver = LookupResolver.NULL;
20
	
21
	public <T> void addLookup(Class<T> clazz, Lookup<T> lookup){
22
		if (myLookups.containsKey(clazz)){
23
			throw new IllegalArgumentException("I already have lookup for :" + clazz);
24
		}
25
		myLookups.put(clazz, lookup);
26
	}
27
	
28
	public <T> Lookup<T> getLookup(Class<T> clazz) {
29
		Lookup<T> result = myLookups.get(clazz);
30
		return result == null ? NULL_LOOKUP : result;
31
	}
32
	
33
	public void setLookupResolver(LookupResolver lookupResolver){
34
		myLookupResolver = lookupResolver;
35
		if (myLookupResolver == null){
36
			myLookupResolver = LookupResolver.NULL;
37
		}
38
	}
39
	
40
	public LookupResolver getLookupResolver() {
41
		return myLookupResolver;
42
	}
43
44
}
(-).classpath (+7 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" path="src"/>
4
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
5
	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
6
	<classpathentry kind="output" path="bin"/>
7
</classpath>
(-)META-INF/MANIFEST.MF (+28 lines)
Added Link Here
1
Manifest-Version: 1.0
2
Bundle-ManifestVersion: 2
3
Bundle-Name: UML Diagrams Parser Plug-in
4
Bundle-SymbolicName: org.eclipse.uml2.diagram.parser; singleton:=true
5
Bundle-Version: 1.0.0
6
Bundle-Localization: plugin
7
Bundle-Activator: org.eclipse.uml2.internal.diagram.parser.MDTDiagramParserPlugin
8
Require-Bundle: org.eclipse.core.runtime,
9
 org.eclipse.jface,
10
 org.eclipse.emf.ecore,
11
 org.eclipse.emf.ecore.xmi,
12
 org.eclipse.emf.edit.ui,
13
 org.eclipse.gef;visibility:=reexport,
14
 org.eclipse.gmf.runtime.emf.core,
15
 org.eclipse.gmf.runtime.emf.commands.core,
16
 org.eclipse.gmf.runtime.emf.ui.properties,
17
 org.eclipse.gmf.runtime.diagram.ui,
18
 org.eclipse.gmf.runtime.diagram.ui.properties,
19
 org.eclipse.uml2.uml;visibility:=reexport,
20
 org.eclipse.uml2.uml.edit;visibility:=reexport,
21
 org.eclipse.emf.ecore;visibility:=reexport,
22
 org.eclipse.emf.ecore.edit;visibility:=reexport,
23
 org.eclipse.emf.query.ocl;visibility:=reexport,
24
 org.eclipse.emf.ocl;visibility:=reexport
25
Export-Package: org.eclipse.uml2.diagram.parser,
26
 org.eclipse.uml2.diagram.parser.lookup
27
Eclipse-LazyStart: true
28
(-)src/org/eclipse/uml2/internal/diagram/parser/MDTDiagramParserPlugin.java (+40 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.internal.diagram.parser;
14
15
import org.eclipse.core.runtime.Plugin;
16
import org.osgi.framework.Bundle;
17
import org.osgi.framework.BundleContext;
18
19
public class MDTDiagramParserPlugin extends Plugin {
20
	private static MDTDiagramParserPlugin anInstance;
21
22
	public void start(BundleContext context) throws Exception {
23
		super.start(context);
24
		anInstance = this;
25
	}
26
27
	public void stop(BundleContext context) throws Exception {
28
		anInstance = null;
29
		super.stop(context);
30
	}
31
32
	public static String getPluginID() {
33
		return getDefault().getSymbolicName();
34
	}
35
36
	public static Bundle getDefault() {
37
		return anInstance.getBundle();
38
	}
39
40
}
(-)src/org/eclipse/uml2/diagram/parser/lookup/LookupSuite.java (+39 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import java.util.Collections;
16
import java.util.List;
17
18
import org.eclipse.emf.ecore.EObject;
19
20
public interface LookupSuite {
21
	public <T> Lookup<T> getLookup(Class<T> clazz);
22
	
23
	public static final Lookup NULL_LOOKUP = new Lookup(){
24
		public Object lookup(String name, EObject context){
25
			return null;
26
		}
27
		
28
		public List getResolutionElementTypes() {
29
			return Collections.emptyList();
30
		}
31
	};
32
	
33
	public static final LookupSuite NULL_SUITE = new LookupSuite(){
34
		public <T> Lookup<T> getLookup(Class<T> clazz) {
35
			return NULL_LOOKUP;
36
		}
37
	};
38
	
39
}
(-)plugin.xml (+5 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<?eclipse version="3.0"?>
3
4
<plugin>
5
</plugin>
(-)src/org/eclipse/uml2/diagram/parser/ExternalParserException.java (+25 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
public class ExternalParserException extends Exception {
16
17
	public ExternalParserException() {
18
		super();
19
	}
20
21
	public ExternalParserException(String message) {
22
		super(message);
23
	}
24
25
}
(-)src/org/eclipse/uml2/diagram/parser/ExternalParserBase.java (+109 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
package org.eclipse.uml2.diagram.parser;
13
14
import java.util.List;
15
16
import org.eclipse.emf.ecore.EClass;
17
import org.eclipse.emf.ecore.EObject;
18
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
19
import org.eclipse.uml2.diagram.parser.lookup.Lookup;
20
import org.eclipse.uml2.diagram.parser.lookup.LookupResolveRequest;
21
import org.eclipse.uml2.diagram.parser.lookup.LookupResolver;
22
import org.eclipse.uml2.diagram.parser.lookup.LookupSuite;
23
import org.eclipse.uml2.uml.NamedElement;
24
import org.eclipse.uml2.uml.UMLPackage;
25
26
public abstract class ExternalParserBase {
27
	private LookupSuite myLookups = LookupSuite.NULL_SUITE;
28
	private LookupResolver myLookupResolver = LookupResolver.NULL;
29
	
30
	private EObject myContext;
31
	
32
	public abstract EClass getSubjectClass();
33
34
	public abstract void parse(EObject target, String text) throws ExternalParserException;
35
	
36
	public final EObject parseNewObject(EObject context, String text) throws ExternalParserException {
37
		myContext = context;
38
		try {
39
			EObject result = createSubjectPrototype();
40
			parse(result, text);
41
			return result;
42
		} finally {
43
			myContext = null;
44
		}
45
	}
46
	
47
	public final void parse(EObject target, String text, EObject context) throws ExternalParserException {
48
		myContext = context;
49
		try {
50
			parse(target, text);
51
		} finally {
52
			myContext = null;
53
		}
54
	}
55
	
56
	public final void setLookupSuite(LookupSuite suite){
57
		myLookups = suite;
58
		if (myLookups == null){
59
			myLookups = LookupSuite.NULL_SUITE;
60
		}
61
	}
62
	
63
	public final void setLookupResolver(LookupResolver lookupResolver){
64
		myLookupResolver = lookupResolver;
65
		if (myLookupResolver == null){
66
			myLookupResolver = LookupResolver.NULL;
67
		}
68
	}
69
	
70
	public final LookupSuite getLookupSuite(){
71
		return myLookups;
72
	}
73
	
74
	public final <T> T lookup(Class<T> clazz, String name){
75
		Lookup<T> lookup = getLookupSuite().getLookup(clazz);
76
		return lookup.lookup(name, getContext());
77
	}
78
	
79
	public EObject createSubjectPrototype(){
80
		EClass subjectClass = getSubjectClass();
81
		return subjectClass.getEPackage().getEFactoryInstance().create(subjectClass);
82
	}
83
	
84
	protected final EObject getContext(){
85
		return myContext;
86
	}
87
	
88
	protected final void checkContext(){
89
		if (getContext() == null){
90
			throw new IllegalStateException("I need context element to perform lookups");
91
		}
92
	}
93
	
94
	protected <T extends NamedElement> void applyLookup(Class<T> clazz, String name, LookupResolver.Callback callback){
95
		Lookup<T> lookup = getLookupSuite().getLookup(clazz);
96
		T result = lookup.lookup(name, getContext());
97
		if (result != null){
98
			callback.lookupResolved(result);
99
			return;
100
		}
101
		List<IElementType> allowedTypes = lookup.getResolutionElementTypes();
102
		if (allowedTypes.isEmpty()){
103
			return;
104
		}
105
		LookupResolveRequest request = new LookupResolveRequest(allowedTypes, UMLPackage.eINSTANCE.getNamedElement_Name(), name);
106
		myLookupResolver.addLookupResolveRequest(request, callback);
107
	}
108
	
109
}
(-)src/org/eclipse/uml2/diagram/parser/SemanticLabelDirectEditPolicy.java (+36 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import org.eclipse.gef.commands.Command;
16
import org.eclipse.gef.requests.DirectEditRequest;
17
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.LabelDirectEditPolicy;
18
19
public class SemanticLabelDirectEditPolicy extends LabelDirectEditPolicy {
20
	@Override
21
	protected Command getDirectEditCommand(DirectEditRequest edit) {
22
		Command applyChanges = super.getDirectEditCommand(edit);
23
		Command postRefresh = null;
24
		if (applyChanges != null && applyChanges.canExecute()){
25
			postRefresh = new PostRefreshCommand();
26
		}
27
		return applyChanges.chain(postRefresh);
28
	}
29
	
30
	private class PostRefreshCommand extends Command {
31
		@Override
32
		public void execute() {
33
			getHost().refresh();
34
		}
35
	}
36
}
(-)src/org/eclipse/uml2/diagram/parser/lookup/LookupResolver.java (+52 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
16
import org.eclipse.uml2.uml.NamedElement;
17
18
public interface LookupResolver {
19
20
	public abstract void addLookupResolveRequest(LookupResolveRequest request, Callback callback);
21
22
	public abstract boolean isEmpty();
23
24
	public abstract boolean canResolve();
25
26
	public abstract AbstractTransactionalCommand getResolveCommand();
27
28
	public static interface Callback {
29
		public void lookupResolved(NamedElement resolution);
30
	}
31
32
	public static final LookupResolver NULL = new LookupResolver() {
33
34
		public boolean isEmpty() {
35
			return true;
36
		}
37
38
		public AbstractTransactionalCommand getResolveCommand() {
39
			return null;
40
		}
41
42
		public boolean canResolve() {
43
			return false;
44
		}
45
46
		public void addLookupResolveRequest(LookupResolveRequest request, Callback callback) {
47
			//
48
		}
49
50
	};
51
52
}
(-).project (+28 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>org.eclipse.uml2.diagram.parser</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
		<buildCommand>
9
			<name>org.eclipse.jdt.core.javabuilder</name>
10
			<arguments>
11
			</arguments>
12
		</buildCommand>
13
		<buildCommand>
14
			<name>org.eclipse.pde.ManifestBuilder</name>
15
			<arguments>
16
			</arguments>
17
		</buildCommand>
18
		<buildCommand>
19
			<name>org.eclipse.pde.SchemaBuilder</name>
20
			<arguments>
21
			</arguments>
22
		</buildCommand>
23
	</buildSpec>
24
	<natures>
25
		<nature>org.eclipse.pde.PluginNature</nature>
26
		<nature>org.eclipse.jdt.core.javanature</nature>
27
	</natures>
28
</projectDescription>
(-)src/org/eclipse/uml2/diagram/parser/AbstractToString.java (+126 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import org.eclipse.uml2.uml.LiteralUnlimitedNatural;
16
import org.eclipse.uml2.uml.MultiplicityElement;
17
import org.eclipse.uml2.uml.NamedElement;
18
import org.eclipse.uml2.uml.Type;
19
import org.eclipse.uml2.uml.TypedElement;
20
import org.eclipse.uml2.uml.VisibilityKind;
21
22
public abstract class AbstractToString implements ExternalToString {
23
	protected String getVisibility(NamedElement namedElement) {
24
		VisibilityKind visibility = namedElement.getVisibility(); 
25
		switch (visibility.getValue()){
26
			case VisibilityKind.PACKAGE : 
27
				return "~";
28
			case VisibilityKind.PRIVATE : 
29
				return "-";
30
			case VisibilityKind.PROTECTED : 
31
				return "#";
32
			case VisibilityKind.PUBLIC : 
33
				return ""; //omitted
34
		}
35
		throw new IllegalArgumentException("Unknown visibility for :" + namedElement + ", that is: " + visibility);
36
	}
37
	
38
	protected void appendName(StringBuffer result, NamedElement namedElement){
39
		if (namedElement == null){
40
			return;
41
		}
42
		String name = namedElement.getName();
43
		if (!isEmpty(name)){
44
			result.append(name);
45
		}
46
	}
47
48
	protected void appendType(StringBuffer result, TypedElement typedElement) {
49
		if (typedElement == null){
50
			return;
51
		}
52
		Type type = typedElement.getType();
53
		if (type == null){
54
			return;
55
		}
56
		appendType(result, type.getName());
57
	}
58
	
59
	protected static void appendType(StringBuffer result, String typeName) {
60
		if (isEmpty(typeName)){
61
			return;
62
		}
63
		result.append(" : ");
64
		result.append(typeName);
65
	}
66
	
67
	protected static boolean isEmpty(String text){
68
		return text == null || text.trim().length() == 0;
69
	}
70
71
	protected void appendMultiplicity(StringBuffer result, MultiplicityElement element) {
72
		if (element == null){
73
			return;
74
		}
75
		int lower = element.getLower();
76
		int upper = element.getUpper();
77
		if (upper == 1 && lower == 1){
78
			return;
79
		}
80
		result.append(" [");
81
		if (lower != upper){
82
			result.append(lower);
83
			result.append('.').append('.');
84
		}
85
		if (upper == LiteralUnlimitedNatural.UNLIMITED){
86
			result.append('*');
87
		} else {
88
			result.append(upper);
89
		}
90
		result.append(']');
91
	}
92
	
93
	protected static class ModifiersBuilder {
94
		private final StringBuffer myBuffer;
95
		
96
		public ModifiersBuilder(){
97
			myBuffer = new StringBuffer();
98
		}
99
		
100
		public void appendModifier(String modifier){
101
			if (modifier.length() == 0){
102
				return;
103
			}
104
			if (myBuffer.length() != 0){
105
				myBuffer.append(", ");
106
			}
107
			myBuffer.append(modifier);
108
		}
109
		
110
		public void writeInto(StringBuffer output){
111
			if (myBuffer.length() == 0){
112
				return;
113
			}
114
			output.append(" ");
115
			output.append("{ ");
116
			output.append(myBuffer);
117
			output.append(" }");
118
		}
119
		
120
		public String toString() {
121
			return super.toString();
122
		}
123
		
124
	}
125
126
}
(-)src/org/eclipse/uml2/diagram/parser/ExternalToString.java (+39 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import java.util.List;
16
17
import org.eclipse.emf.ecore.EObject;
18
import org.eclipse.emf.ecore.EStructuralFeature;
19
20
public interface ExternalToString {
21
	public String getToString(EObject object, int flags);
22
	
23
	public boolean isAffectingFeature(EStructuralFeature feature);
24
	
25
	public static final ExternalToString NOT_IMPLEMENTED = new ExternalToString(){
26
	
27
		public String getToString(EObject object, int flags) {
28
			return "-NOT-IMPLEMENTED-";
29
		}
30
		
31
		public boolean isAffectingFeature(EStructuralFeature feature) {
32
			return false;
33
		}
34
	};
35
	
36
	public static interface WithReferences extends ExternalToString {
37
		public List getAdditionalReferencedElements(EObject object);
38
	}
39
}
(-)src/org/eclipse/uml2/diagram/parser/lookup/Lookup.java (+23 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import java.util.List;
16
17
import org.eclipse.emf.ecore.EObject;
18
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
19
20
public interface Lookup<T> {
21
	public T lookup(String name, EObject context);
22
	public List<IElementType> getResolutionElementTypes(); 
23
}
(-)src/org/eclipse/uml2/diagram/parser/BasicApplyStrategy.java (+79 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import java.util.Iterator;
16
import java.util.LinkedList;
17
import java.util.List;
18
19
import org.eclipse.emf.ecore.EObject;
20
import org.eclipse.emf.ecore.EReference;
21
import org.eclipse.emf.ecore.EStructuralFeature;
22
import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyReferenceCommand;
23
import org.eclipse.gmf.runtime.emf.type.core.commands.SetValueCommand;
24
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyReferenceRequest;
25
import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
26
27
public class BasicApplyStrategy implements ApplyStrategy {
28
	public List/*1.5 <ICommand>*/ apply(EObject modelObject, EObject parsedObject) {
29
		List result = new LinkedList(); 
30
		for (Iterator it = parsedObject.eClass().getEAllStructuralFeatures().iterator(); it.hasNext();){
31
			EStructuralFeature next = (EStructuralFeature) it.next();
32
			if (parsedObject.eIsSet(next) && !next.isDerived()){
33
				transferValue(result, modelObject, parsedObject, next);
34
			}
35
		}
36
		return result.isEmpty() ? NOT_EXECUTABLE : result;
37
	}
38
	
39
	protected final void transferValue(List output, EObject model, EObject parsed, EStructuralFeature feature){
40
		if (feature.isDerived() || !parsed.eIsSet(feature)){
41
			return;
42
		}
43
		Object parsedValue = parsed.eGet(feature);
44
		Object actualValue = model.eGet(feature);
45
		if (safeEquals(parsedValue, actualValue)){
46
			return;
47
		}	
48
		//XXX: workaround for : #152080
49
		//XXX: can not set multi-valued properties using SetValueCommand,  
50
		//XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=152080
51
		if (feature instanceof EReference && feature.isMany()){
52
			transferValuesList(output, model, parsed, (EReference)feature);
53
			return;
54
		}
55
		SetRequest request = new SetRequest(model, feature, parsedValue);
56
		output.add(new SetValueCommand(request));
57
	}
58
	
59
	private void transferValuesList(List output, EObject model, EObject parsed, EReference isManyReference){
60
		assert isManyReference.isMany();
61
		List<EObject> actualValues = (List<EObject>) model.eGet(isManyReference);
62
		List<EObject> parsedValues = (List<EObject>) parsed.eGet(isManyReference);
63
		
64
		for (EObject nextActual : actualValues){
65
			DestroyReferenceRequest nextRequest = new DestroyReferenceRequest(model, isManyReference, nextActual, false);
66
			output.add(new DestroyReferenceCommand(nextRequest));
67
		}
68
		
69
		for (EObject nextParsed : parsedValues){
70
			SetRequest nextRequest = new SetRequest(model, isManyReference, nextParsed);
71
			output.add(new SetValueCommand(nextRequest));
72
		}
73
	}
74
75
	protected static <T> boolean safeEquals(T o1, T o2){
76
		return o1 == null ? o2 == null : o1.equals(o2);
77
	}
78
79
}
(-).cvsignore (+1 lines)
Added Link Here
1
bin
(-)src/org/eclipse/uml2/diagram/parser/lookup/OCLLookup.java (+65 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser.lookup;
14
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Collection;
18
import java.util.Collections;
19
import java.util.LinkedList;
20
import java.util.List;
21
22
import org.eclipse.emf.ecore.EObject;
23
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
24
import org.eclipse.uml2.uml.NamedElement;
25
26
public class OCLLookup<T extends NamedElement> implements Lookup<T> {
27
	public static interface Expression {
28
		public Object evaluate(Object context);
29
	}
30
	
31
	private Expression mySelector;
32
	private final ArrayList<IElementType> myResolutionTypes;
33
	private static final IElementType[] NO_RESOLUTIONS = new IElementType[0];
34
	
35
	public OCLLookup(Expression ocl, IElementType[] resolutions){
36
		mySelector = ocl;
37
		if (resolutions == null){
38
			resolutions = NO_RESOLUTIONS;
39
		}
40
		myResolutionTypes = new ArrayList<IElementType>(Arrays.asList(resolutions));
41
	}
42
	
43
	public List getResolutionElementTypes() {
44
		return new ArrayList<IElementType>(myResolutionTypes);
45
	}
46
	
47
	public List<T> computeScope(EObject context){
48
		Object result = mySelector.evaluate(context);
49
		if (result instanceof Collection){
50
			return new LinkedList<T>((Collection<T>)result);
51
		}
52
		return Collections.emptyList();
53
	}
54
	
55
	public T lookup(String name, EObject context) {
56
		List<T> scope = computeScope(context);
57
		for (T next : scope){
58
			if (name.equals(next.getName()) || name.equals(next.getQualifiedName())){
59
				return next;
60
			}
61
		}
62
		return null;
63
	}
64
65
}
(-)src/org/eclipse/uml2/diagram/parser/SemanticParserAdapter.java (+45 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.parser;
14
15
import java.util.Collections;
16
import java.util.List;
17
18
import org.eclipse.emf.ecore.EObject;
19
import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
20
21
public class SemanticParserAdapter extends ParserAdapter implements ISemanticParser {
22
23
	public SemanticParserAdapter(ExternalParserBase delegate, ApplyStrategy applier, ExternalToString.WithReferences view, ExternalToString edit) {
24
		super(delegate, applier, view, edit);
25
	}
26
27
	public SemanticParserAdapter(ExternalParserBase delegate, ApplyStrategy applier, ExternalToString.WithReferences viewAndEdit) {
28
		this(delegate, applier, viewAndEdit, viewAndEdit);
29
	}
30
31
	public boolean areSemanticElementsAffected(EObject listener, Object notification) {
32
		return isAffectingEvent(notification);
33
	}
34
	
35
	public List getSemanticElementsBeingParsed(EObject element) {
36
		return isValidElement(element) ? 
37
				getViewToStringImpl().getAdditionalReferencedElements(element) : 
38
				Collections.EMPTY_LIST;
39
	}
40
	
41
	private ExternalToString.WithReferences getViewToStringImpl(){
42
		return (ExternalToString.WithReferences)getViewToString();
43
	}
44
45
}
(-)build.properties (+4 lines)
Added Link Here
1
source.. = src/
2
output.. = bin/
3
bin.includes = META-INF/,\
4
               .
(-)src/org/eclipse/uml2/diagram/common/draw2d/PolylineContainer.java (+28 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.common.draw2d;
14
15
import org.eclipse.draw2d.RectangleFigure;
16
17
public class PolylineContainer extends RectangleFigure {
18
	public PolylineContainer(){
19
		super();
20
		setOutline(false);
21
		setFill(false);
22
	}
23
24
	protected boolean useLocalCoordinates() {
25
		return true;
26
	}
27
	
28
}
(-)src/org/eclipse/uml2/diagram/common/draw2d/AssociationDecoration.java (+71 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.common.draw2d;
14
15
import org.eclipse.draw2d.ColorConstants;
16
import org.eclipse.draw2d.Graphics;
17
import org.eclipse.draw2d.PolygonDecoration;
18
import org.eclipse.draw2d.geometry.PointList;
19
import org.eclipse.swt.graphics.Color;
20
import org.eclipse.uml2.uml.AggregationKind;
21
import org.eclipse.uml2.uml.Association;
22
import org.eclipse.uml2.uml.Property;
23
24
public class AssociationDecoration extends PolygonDecoration {
25
	private static final PointList RHOMB = new PointList(new int[] { //
26
			//
27
					-1, 1, // 
28
					0, 0, //
29
					-1, -1, //
30
					-2, 0, //
31
					-1, 1, //
32
			});
33
34
	/**
35
	 * XXX: navigability arrows and owner-dot decorations are not implemented yet
36
	 */
37
	private static final PointList ARROW = new PointList(new int[] { //
38
			//
39
					-1, 1, // 
40
					0, 0, //
41
					-1, -1, //
42
					0, 0, // 
43
					-1, 1, //
44
			});
45
46
	public AssociationDecoration() {
47
		setTemplate(RHOMB.getCopy());
48
		setScale(7, 3);
49
		setVisible(false);
50
		setFill(true);
51
	}
52
53
	public void update(AggregationKind kind) {
54
		if (kind == AggregationKind.COMPOSITE_LITERAL) {
55
			setVisible(true);
56
			if (getParent() != null && getParent().getForegroundColor() != null){
57
				setBackgroundColor(getParent().getForegroundColor());	
58
			}
59
		} else if (kind == AggregationKind.SHARED_LITERAL) {
60
			setVisible(true);
61
			setBackgroundColor(ColorConstants.white);
62
		} else {
63
			setVisible(false);
64
		}
65
	}
66
	
67
	public void update(Association association, Property associationEnd) {
68
		update(associationEnd.getAggregation());
69
	}
70
71
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/TokenMgrError.java (+144 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
public class TokenMgrError extends Error
16
{
17
   /*
18
    * Ordinals for various reasons why an Error of this type can be thrown.
19
    */
20
21
   /**
22
    * Lexical error occured.
23
    */
24
   static final int LEXICAL_ERROR = 0;
25
26
   /**
27
    * An attempt wass made to create a second instance of a static token manager.
28
    */
29
   static final int STATIC_LEXER_ERROR = 1;
30
31
   /**
32
    * Tried to change to an invalid lexical state.
33
    */
34
   static final int INVALID_LEXICAL_STATE = 2;
35
36
   /**
37
    * Detected (and bailed out of) an infinite loop in the token manager.
38
    */
39
   static final int LOOP_DETECTED = 3;
40
41
   /**
42
    * Indicates the reason why the exception is thrown. It will have
43
    * one of the above 4 values.
44
    */
45
   int errorCode;
46
47
   /**
48
    * Replaces unprintable characters by their espaced (or unicode escaped)
49
    * equivalents in the given string
50
    */
51
   protected static final String addEscapes(String str) {
52
      StringBuffer retval = new StringBuffer();
53
      char ch;
54
      for (int i = 0; i < str.length(); i++) {
55
        switch (str.charAt(i))
56
        {
57
           case 0 :
58
              continue;
59
           case '\b':
60
              retval.append("\\b");
61
              continue;
62
           case '\t':
63
              retval.append("\\t");
64
              continue;
65
           case '\n':
66
              retval.append("\\n");
67
              continue;
68
           case '\f':
69
              retval.append("\\f");
70
              continue;
71
           case '\r':
72
              retval.append("\\r");
73
              continue;
74
           case '\"':
75
              retval.append("\\\"");
76
              continue;
77
           case '\'':
78
              retval.append("\\\'");
79
              continue;
80
           case '\\':
81
              retval.append("\\\\");
82
              continue;
83
           default:
84
              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
85
                 String s = "0000" + Integer.toString(ch, 16);
86
                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));
87
              } else {
88
                 retval.append(ch);
89
              }
90
              continue;
91
        }
92
      }
93
      return retval.toString();
94
   }
95
96
   /**
97
    * Returns a detailed message for the Error when it is thrown by the
98
    * token manager to indicate a lexical error.
99
    * Parameters : 
100
    *    EOFSeen     : indicates if EOF caused the lexicl error
101
    *    curLexState : lexical state in which this error occured
102
    *    errorLine   : line number when the error occured
103
    *    errorColumn : column number when the error occured
104
    *    errorAfter  : prefix that was seen before this error occured
105
    *    curchar     : the offending character
106
    * Note: You can customize the lexical error message by modifying this method.
107
    */
108
   protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
109
      return("Lexical error at line " +
110
           errorLine + ", column " +
111
           errorColumn + ".  Encountered: " +
112
           (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
113
           "after : \"" + addEscapes(errorAfter) + "\"");
114
   }
115
116
   /**
117
    * You can also modify the body of this method to customize your error messages.
118
    * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
119
    * of end-users concern, so you can return something like : 
120
    *
121
    *     "Internal Error : Please file a bug report .... "
122
    *
123
    * from this method for such cases in the release version of your parser.
124
    */
125
   public String getMessage() {
126
      return super.getMessage();
127
   }
128
129
   /*
130
    * Constructors of various flavors follow.
131
    */
132
133
   public TokenMgrError() {
134
   }
135
136
   public TokenMgrError(String message, int reason) {
137
      super(message);
138
      errorCode = reason;
139
   }
140
141
   public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
142
      this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
143
   }
144
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/PortToString.java (+77 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
import java.util.Arrays;
16
import java.util.LinkedList;
17
import java.util.List;
18
19
import org.eclipse.emf.ecore.EObject;
20
import org.eclipse.emf.ecore.EStructuralFeature;
21
import org.eclipse.uml2.diagram.parser.AbstractToString;
22
import org.eclipse.uml2.diagram.parser.ExternalToString.WithReferences;
23
import org.eclipse.uml2.uml.Port;
24
import org.eclipse.uml2.uml.UMLPackage;
25
import org.eclipse.uml2.uml.ValueSpecification;
26
27
public class PortToString extends AbstractToString implements WithReferences {
28
	public String getToString(EObject object, int flags) {
29
		Port port = asPort(object);
30
		StringBuffer result = new StringBuffer();
31
		appendName(result, port);
32
		appendType(result, port);
33
		appendMultiplicity(result, port);
34
		return result.toString();
35
	}
36
	
37
	private static final List AFFECTING = Arrays.asList(new EStructuralFeature[] {
38
			UMLPackage.eINSTANCE.getNamedElement_Visibility(),
39
			UMLPackage.eINSTANCE.getNamedElement_Name(),
40
			UMLPackage.eINSTANCE.getTypedElement_Type(),
41
			UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue(),
42
			UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue(),
43
			UMLPackage.eINSTANCE.getLiteralUnlimitedNatural_Value(), 
44
			UMLPackage.eINSTANCE.getLiteralInteger_Value(),
45
			UMLPackage.eINSTANCE.getLiteralString_Value(),
46
		});
47
48
	public boolean isAffectingFeature(EStructuralFeature feature) {
49
		return AFFECTING.contains(feature);
50
	}
51
	
52
	public List getAdditionalReferencedElements(EObject object) {
53
		Port port = asPort(object);
54
		List result = new LinkedList();
55
		result.add(port);
56
		ValueSpecification upper = port.getUpperValue();
57
		if (upper != null){
58
			result.add(upper);
59
		}
60
		ValueSpecification lower = port.getLowerValue();
61
		if (lower != null){
62
			result.add(lower);
63
		}
64
		if (port.getType() != null){
65
			result.add(port.getType());
66
		}
67
		return result;
68
	}
69
70
	protected Port asPort(EObject object){
71
		if (false == object instanceof Port){
72
			throw new IllegalStateException("I can not provide toString for: " + object);
73
		}
74
		return (Port)object;
75
	}
76
	
77
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/ParseException.java (+205 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
import org.eclipse.uml2.diagram.parser.ExternalParserException;
16
17
/**
18
 * This exception is thrown when parse errors are encountered.
19
 * You can explicitly create objects of this exception type by
20
 * calling the method generateParseException in the generated
21
 * parser.
22
 *
23
 * You can modify this class to customize your error reporting
24
 * mechanisms so long as you retain the public fields.
25
 */
26
public class ParseException extends ExternalParserException {
27
28
  /**
29
   * This constructor is used by the method "generateParseException"
30
   * in the generated parser.  Calling this constructor generates
31
   * a new object of this type with the fields "currentToken",
32
   * "expectedTokenSequences", and "tokenImage" set.  The boolean
33
   * flag "specialConstructor" is also set to true to indicate that
34
   * this constructor was used to create this object.
35
   * This constructor calls its super class with the empty string
36
   * to force the "toString" method of parent class "Throwable" to
37
   * print the error message in the form:
38
   *     ParseException: <result of getMessage>
39
   */
40
  public ParseException(Token currentTokenVal,
41
                        int[][] expectedTokenSequencesVal,
42
                        String[] tokenImageVal
43
                       )
44
  {
45
    super("");
46
    specialConstructor = true;
47
    currentToken = currentTokenVal;
48
    expectedTokenSequences = expectedTokenSequencesVal;
49
    tokenImage = tokenImageVal;
50
  }
51
52
  /**
53
   * The following constructors are for use by you for whatever
54
   * purpose you can think of.  Constructing the exception in this
55
   * manner makes the exception behave in the normal way - i.e., as
56
   * documented in the class "Throwable".  The fields "errorToken",
57
   * "expectedTokenSequences", and "tokenImage" do not contain
58
   * relevant information.  The JavaCC generated code does not use
59
   * these constructors.
60
   */
61
62
  public ParseException() {
63
    super();
64
    specialConstructor = false;
65
  }
66
67
  public ParseException(String message) {
68
    super(message);
69
    specialConstructor = false;
70
  }
71
72
  /**
73
   * This variable determines which constructor was used to create
74
   * this object and thereby affects the semantics of the
75
   * "getMessage" method (see below).
76
   */
77
  protected boolean specialConstructor;
78
79
  /**
80
   * This is the last token that has been consumed successfully.  If
81
   * this object has been created due to a parse error, the token
82
   * followng this token will (therefore) be the first error token.
83
   */
84
  public Token currentToken;
85
86
  /**
87
   * Each entry in this array is an array of integers.  Each array
88
   * of integers represents a sequence of tokens (by their ordinal
89
   * values) that is expected at this point of the parse.
90
   */
91
  public int[][] expectedTokenSequences;
92
93
  /**
94
   * This is a reference to the "tokenImage" array of the generated
95
   * parser within which the parse error occurred.  This array is
96
   * defined in the generated ...Constants interface.
97
   */
98
  public String[] tokenImage;
99
100
  /**
101
   * This method has the standard behavior when this object has been
102
   * created using the standard constructors.  Otherwise, it uses
103
   * "currentToken" and "expectedTokenSequences" to generate a parse
104
   * error message and returns it.  If this object has been created
105
   * due to a parse error, and you do not catch it (it gets thrown
106
   * from the parser), then this method is called during the printing
107
   * of the final stack trace, and hence the correct error message
108
   * gets displayed.
109
   */
110
  public String getMessage() {
111
    if (!specialConstructor) {
112
      return super.getMessage();
113
    }
114
    String expected = "";
115
    int maxSize = 0;
116
    for (int i = 0; i < expectedTokenSequences.length; i++) {
117
      if (maxSize < expectedTokenSequences[i].length) {
118
        maxSize = expectedTokenSequences[i].length;
119
      }
120
      for (int j = 0; j < expectedTokenSequences[i].length; j++) {
121
        expected += tokenImage[expectedTokenSequences[i][j]] + " ";
122
      }
123
      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
124
        expected += "...";
125
      }
126
      expected += eol + "    ";
127
    }
128
    String retval = "Encountered \"";
129
    Token tok = currentToken.next;
130
    for (int i = 0; i < maxSize; i++) {
131
      if (i != 0) retval += " ";
132
      if (tok.kind == 0) {
133
        retval += tokenImage[0];
134
        break;
135
      }
136
      retval += add_escapes(tok.image);
137
      tok = tok.next; 
138
    }
139
    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
140
    retval += "." + eol;
141
    if (expectedTokenSequences.length == 1) {
142
      retval += "Was expecting:" + eol + "    ";
143
    } else {
144
      retval += "Was expecting one of:" + eol + "    ";
145
    }
146
    retval += expected;
147
    return retval;
148
  }
149
150
  /**
151
   * The end of line string for this machine.
152
   */
153
  protected String eol = System.getProperty("line.separator", "\n");
154
 
155
  /**
156
   * Used to convert raw characters to their escaped version
157
   * when these raw version cannot be used as part of an ASCII
158
   * string literal.
159
   */
160
  protected String add_escapes(String str) {
161
      StringBuffer retval = new StringBuffer();
162
      char ch;
163
      for (int i = 0; i < str.length(); i++) {
164
        switch (str.charAt(i))
165
        {
166
           case 0 :
167
              continue;
168
           case '\b':
169
              retval.append("\\b");
170
              continue;
171
           case '\t':
172
              retval.append("\\t");
173
              continue;
174
           case '\n':
175
              retval.append("\\n");
176
              continue;
177
           case '\f':
178
              retval.append("\\f");
179
              continue;
180
           case '\r':
181
              retval.append("\\r");
182
              continue;
183
           case '\"':
184
              retval.append("\\\"");
185
              continue;
186
           case '\'':
187
              retval.append("\\\'");
188
              continue;
189
           case '\\':
190
              retval.append("\\\\");
191
              continue;
192
           default:
193
              if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
194
                 String s = "0000" + Integer.toString(ch, 16);
195
                 retval.append("\\u" + s.substring(s.length() - 4, s.length()));
196
              } else {
197
                 retval.append(ch);
198
              }
199
              continue;
200
        }
201
      }
202
      return retval.toString();
203
   }
204
205
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/Token.java (+92 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
/**
16
 * Describes the input token stream.
17
 */
18
19
public class Token {
20
21
  /**
22
   * An integer that describes the kind of this token.  This numbering
23
   * system is determined by JavaCCParser, and a table of these numbers is
24
   * stored in the file ...Constants.java.
25
   */
26
  public int kind;
27
28
  /**
29
   * beginLine and beginColumn describe the position of the first character
30
   * of this token; endLine and endColumn describe the position of the
31
   * last character of this token.
32
   */
33
  public int beginLine, beginColumn, endLine, endColumn;
34
35
  /**
36
   * The string image of the token.
37
   */
38
  public String image;
39
40
  /**
41
   * A reference to the next regular (non-special) token from the input
42
   * stream.  If this is the last token from the input stream, or if the
43
   * token manager has not read tokens beyond this one, this field is
44
   * set to null.  This is true only if this token is also a regular
45
   * token.  Otherwise, see below for a description of the contents of
46
   * this field.
47
   */
48
  public Token next;
49
50
  /**
51
   * This field is used to access special tokens that occur prior to this
52
   * token, but after the immediately preceding regular (non-special) token.
53
   * If there are no such special tokens, this field is set to null.
54
   * When there are more than one such special token, this field refers
55
   * to the last of these special tokens, which in turn refers to the next
56
   * previous special token through its specialToken field, and so on
57
   * until the first special token (whose specialToken field is null).
58
   * The next fields of special tokens refer to other special tokens that
59
   * immediately follow it (without an intervening regular token).  If there
60
   * is no such token, this field is null.
61
   */
62
  public Token specialToken;
63
64
  /**
65
   * Returns the image.
66
   */
67
  public String toString()
68
  {
69
     return image;
70
  }
71
72
  /**
73
   * Returns a new Token object, by default. However, if you want, you
74
   * can create and return subclass objects based on the value of ofKind.
75
   * Simply add the cases to the switch for all those special cases.
76
   * For example, if you have a subclass of Token called IDToken that
77
   * you want to create if ofKind is ID, simlpy add something like :
78
   *
79
   *    case MyParserConstants.ID : return new IDToken();
80
   *
81
   * to the following switch statement. Then you can cast matchedToken
82
   * variable to the appropriate type and use it in your lexical actions.
83
   */
84
  public static final Token newToken(int ofKind)
85
  {
86
     switch(ofKind)
87
     {
88
       default : return new Token();
89
     }
90
  }
91
92
}
(-)src/org/eclipse/uml2/diagram/common/draw2d/CenterLayout.java (+41 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.common.draw2d;
14
15
import java.util.List;
16
17
import org.eclipse.draw2d.IFigure;
18
import org.eclipse.draw2d.StackLayout;
19
import org.eclipse.draw2d.geometry.Dimension;
20
import org.eclipse.draw2d.geometry.Rectangle;
21
22
public class CenterLayout extends StackLayout {
23
	private static final Rectangle RECTANGLE = new Rectangle();
24
	
25
	public void layout(IFigure figure) {
26
		Rectangle r = figure.getClientArea();
27
		final int centerX = r.x + r.width / 2;
28
		final int centerY = r.y + r.height / 2;
29
		List children = figure.getChildren();
30
		IFigure child;
31
		for (int i = 0; i < children.size(); i++) {
32
			child = (IFigure)children.get(i);
33
			Dimension prefSize = child.getPreferredSize();
34
			RECTANGLE.x = centerX - prefSize.width / 2;
35
			RECTANGLE.y = centerY - prefSize.height / 2;
36
			RECTANGLE.width = prefSize.width;
37
			RECTANGLE.height = prefSize.height;
38
			child.setBounds(RECTANGLE);
39
		}
40
	}
41
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/PortParserConstants.java (+79 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. PortParserConstants.java */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
public interface PortParserConstants {
16
17
  int EOF = 0;
18
  int SLASH = 3;
19
  int COLON = 4;
20
  int EQUALS = 5;
21
  int LBRACKET = 6;
22
  int RBRACKET = 7;
23
  int LCURLY = 8;
24
  int RCURLY = 9;
25
  int COMMA = 10;
26
  int PLUS = 11;
27
  int MINUS = 12;
28
  int NUMBER_SIGN = 13;
29
  int TILDE = 14;
30
  int DOT = 15;
31
  int STAR = 16;
32
  int READ_ONLY = 17;
33
  int UNION = 18;
34
  int SUBSETS = 19;
35
  int REDEFINES = 20;
36
  int ORDERED = 21;
37
  int UNORDERED = 22;
38
  int UNIQUE = 23;
39
  int NON_UNIQUE = 24;
40
  int INTEGER_LITERAL = 25;
41
  int IDENTIFIER = 26;
42
  int LETTER = 27;
43
  int DIGIT = 28;
44
45
  int DEFAULT = 0;
46
47
  String[] tokenImage = {
48
    "<EOF>",
49
    "\" \"",
50
    "\"\\t\"",
51
    "\"/\"",
52
    "\":\"",
53
    "\"=\"",
54
    "\"[\"",
55
    "\"]\"",
56
    "\"{\"",
57
    "\"}\"",
58
    "\",\"",
59
    "\"+\"",
60
    "\"-\"",
61
    "\"#\"",
62
    "\"~\"",
63
    "\".\"",
64
    "\"*\"",
65
    "\"readOnly\"",
66
    "\"union\"",
67
    "\"subsets\"",
68
    "\"redefines\"",
69
    "\"ordered\"",
70
    "\"unordered\"",
71
    "\"unique\"",
72
    "\"nonunique\"",
73
    "<INTEGER_LITERAL>",
74
    "<IDENTIFIER>",
75
    "<LETTER>",
76
    "<DIGIT>",
77
  };
78
79
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/PortParser.java (+509 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. PortParser.java */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
import java.io.*;
16
import org.eclipse.emf.ecore.EClass;
17
import org.eclipse.emf.ecore.EObject;
18
import org.eclipse.uml2.diagram.parser.*;
19
import org.eclipse.uml2.diagram.parser.lookup.LookupResolver;
20
import org.eclipse.uml2.diagram.parser.lookup.LookupSuite;
21
import org.eclipse.uml2.uml.*;
22
23
public class PortParser extends ExternalParserBase implements PortParserConstants {
24
        private Port mySubject;
25
26
    private static class TypeLookupCallback implements LookupResolver.Callback {
27
        private final Port myPort;
28
29
                public TypeLookupCallback(Port property){
30
                        myPort = property;
31
        }
32
33
        public void lookupResolved(NamedElement resolution) {
34
                if (resolution instanceof Type){
35
                        myPort.setType((Type)resolution);
36
                }
37
        }
38
    }
39
40
    public PortParser(){
41
        this(new StringReader(""));
42
    }
43
44
    public PortParser(LookupSuite lookup){
45
        this();
46
        setLookupSuite(lookup);
47
    }
48
49
        public EClass getSubjectClass(){
50
                return UMLPackage.eINSTANCE.getPort();
51
        }
52
53
        public void parse(EObject target, String text) throws ExternalParserException {
54
                checkContext();
55
                ReInit(new StringReader(text));
56
                mySubject = (Port)target;
57
                Declaration();
58
                mySubject = null;
59
        }
60
61
        protected static int parseInt(Token t) throws ParseException {
62
                if (t.kind != PortParserConstants.INTEGER_LITERAL){
63
                        throw new IllegalStateException("Token: " + t + ", image: " + t.image);
64
                }
65
                try {
66
                        return Integer.parseInt(t.image); //XXX: "0005", "99999999999999999999999"
67
                } catch (NumberFormatException e){
68
                        throw new ParseException("Not supported integer value:" + t.image);
69
                }
70
        }
71
72
  final public void Declaration() throws ParseException {
73
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
74
    case PLUS:
75
    case MINUS:
76
    case NUMBER_SIGN:
77
    case TILDE:
78
      Visibility();
79
      break;
80
    default:
81
      jj_la1[0] = jj_gen;
82
      ;
83
    }
84
    PortName();
85
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
86
    case COLON:
87
      PortType();
88
      break;
89
    default:
90
      jj_la1[1] = jj_gen;
91
      ;
92
    }
93
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
94
    case LBRACKET:
95
      Multiplicity();
96
      break;
97
    default:
98
      jj_la1[2] = jj_gen;
99
      ;
100
    }
101
    jj_consume_token(0);
102
  }
103
104
  final public void PortName() throws ParseException {
105
        String name;
106
    name = NameWithSpaces();
107
                mySubject.setName(name);
108
  }
109
110
  final public void Visibility() throws ParseException {
111
        VisibilityKind kind;
112
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
113
    case PLUS:
114
      jj_consume_token(PLUS);
115
                         kind = VisibilityKind.PUBLIC_LITERAL;
116
      break;
117
    case MINUS:
118
      jj_consume_token(MINUS);
119
                          kind = VisibilityKind.PRIVATE_LITERAL;
120
      break;
121
    case NUMBER_SIGN:
122
      jj_consume_token(NUMBER_SIGN);
123
                                kind = VisibilityKind.PROTECTED_LITERAL;
124
      break;
125
    case TILDE:
126
      jj_consume_token(TILDE);
127
                          kind = VisibilityKind.PACKAGE_LITERAL;
128
      break;
129
    default:
130
      jj_la1[3] = jj_gen;
131
      jj_consume_token(-1);
132
      throw new ParseException();
133
    }
134
                mySubject.setVisibility(kind);
135
  }
136
137
  final public void Multiplicity() throws ParseException {
138
    MultiplicityRange();
139
  }
140
141
/* XXX: Parse conflict in case of empty default value
142
void MultiplicityDesignator() :
143
{ }
144
{
145
	<LCURLY> 
146
	(
147
		( MultiplicityUnique() [ MultiplicityOrdered() ] ) 
148
		|
149
		( MultiplicityOrdered() [ MultiplicityUnique() ] ) 
150
	) 
151
	<RCURLY>
152
}
153
154
void MultiplicityUnique() :
155
{}
156
{
157
		<UNIQUE> { mySubject.setIsUnique(true); }
158
	|
159
		<NON_UNIQUE> { mySubject.setIsUnique(false); }	
160
}
161
162
void MultiplicityOrdered() :
163
{}
164
{
165
		<ORDERED> { mySubject.setIsOrdered(true); }
166
	|
167
		<UNORDERED> { mySubject.setIsOrdered(false); }
168
}
169
170
*/
171
172
/* XXX: ValueSpecification -- how to parse */
173
  final public void MultiplicityRange() throws ParseException {
174
        Token tLower = null;
175
        Token tUpper;
176
    jj_consume_token(LBRACKET);
177
    if (jj_2_1(2)) {
178
      tLower = jj_consume_token(INTEGER_LITERAL);
179
      jj_consume_token(DOT);
180
      jj_consume_token(DOT);
181
                                                                        mySubject.setLower(parseInt(tLower));
182
    } else {
183
      ;
184
    }
185
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
186
    case STAR:
187
      tUpper = jj_consume_token(STAR);
188
                                if (tLower == null){
189
                                        mySubject.setLower(0);
190
                                }
191
                                mySubject.setUpper(LiteralUnlimitedNatural.UNLIMITED);
192
      break;
193
    case INTEGER_LITERAL:
194
      tUpper = jj_consume_token(INTEGER_LITERAL);
195
                                if (tLower == null){
196
                                        mySubject.setLower(parseInt(tUpper));
197
                                }
198
                                mySubject.setUpper(parseInt(tUpper));
199
      break;
200
    default:
201
      jj_la1[4] = jj_gen;
202
      jj_consume_token(-1);
203
      throw new ParseException();
204
    }
205
    jj_consume_token(RBRACKET);
206
  }
207
208
  final public void PortType() throws ParseException {
209
        String type;
210
    jj_consume_token(COLON);
211
    type = NameWithSpaces();
212
                                          applyLookup(Type.class, type, new TypeLookupCallback(mySubject));
213
  }
214
215
  final public String NameWithSpaces() throws ParseException {
216
        StringBuffer result = new StringBuffer();
217
        Token t;
218
    t = jj_consume_token(IDENTIFIER);
219
                                   result.append(t.image);
220
    label_1:
221
    while (true) {
222
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
223
      case IDENTIFIER:
224
        ;
225
        break;
226
      default:
227
        jj_la1[5] = jj_gen;
228
        break label_1;
229
      }
230
      t = jj_consume_token(IDENTIFIER);
231
                                     result.append(' '); result.append(t.image);
232
    }
233
                {if (true) return result.toString();}
234
    throw new Error("Missing return statement in function");
235
  }
236
237
  final private boolean jj_2_1(int xla) {
238
    jj_la = xla; jj_lastpos = jj_scanpos = token;
239
    try { return !jj_3_1(); }
240
    catch(LookaheadSuccess ls) { return true; }
241
    finally { jj_save(0, xla); }
242
  }
243
244
  final private boolean jj_3_1() {
245
    if (jj_scan_token(INTEGER_LITERAL)) return true;
246
    if (jj_scan_token(DOT)) return true;
247
    return false;
248
  }
249
250
  public PortParserTokenManager token_source;
251
  JavaCharStream jj_input_stream;
252
  public Token token, jj_nt;
253
  private int jj_ntk;
254
  private Token jj_scanpos, jj_lastpos;
255
  private int jj_la;
256
  public boolean lookingAhead = false;
257
  private boolean jj_semLA;
258
  private int jj_gen;
259
  final private int[] jj_la1 = new int[6];
260
  static private int[] jj_la1_0;
261
  static {
262
      jj_la1_0();
263
   }
264
   private static void jj_la1_0() {
265
      jj_la1_0 = new int[] {0x7800,0x10,0x40,0x7800,0x2010000,0x4000000,};
266
   }
267
  final private JJCalls[] jj_2_rtns = new JJCalls[1];
268
  private boolean jj_rescan = false;
269
  private int jj_gc = 0;
270
271
  public PortParser(java.io.InputStream stream) {
272
    jj_input_stream = new JavaCharStream(stream, 1, 1);
273
    token_source = new PortParserTokenManager(jj_input_stream);
274
    token = new Token();
275
    jj_ntk = -1;
276
    jj_gen = 0;
277
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
278
    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
279
  }
280
281
  public void ReInit(java.io.InputStream stream) {
282
    jj_input_stream.ReInit(stream, 1, 1);
283
    token_source.ReInit(jj_input_stream);
284
    token = new Token();
285
    jj_ntk = -1;
286
    jj_gen = 0;
287
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
288
    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
289
  }
290
291
  public PortParser(java.io.Reader stream) {
292
    jj_input_stream = new JavaCharStream(stream, 1, 1);
293
    token_source = new PortParserTokenManager(jj_input_stream);
294
    token = new Token();
295
    jj_ntk = -1;
296
    jj_gen = 0;
297
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
298
    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
299
  }
300
301
  public void ReInit(java.io.Reader stream) {
302
    jj_input_stream.ReInit(stream, 1, 1);
303
    token_source.ReInit(jj_input_stream);
304
    token = new Token();
305
    jj_ntk = -1;
306
    jj_gen = 0;
307
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
308
    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
309
  }
310
311
  public PortParser(PortParserTokenManager tm) {
312
    token_source = tm;
313
    token = new Token();
314
    jj_ntk = -1;
315
    jj_gen = 0;
316
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
317
    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
318
  }
319
320
  public void ReInit(PortParserTokenManager tm) {
321
    token_source = tm;
322
    token = new Token();
323
    jj_ntk = -1;
324
    jj_gen = 0;
325
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
326
    for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
327
  }
328
329
  final private Token jj_consume_token(int kind) throws ParseException {
330
    Token oldToken;
331
    if ((oldToken = token).next != null) token = token.next;
332
    else token = token.next = token_source.getNextToken();
333
    jj_ntk = -1;
334
    if (token.kind == kind) {
335
      jj_gen++;
336
      if (++jj_gc > 100) {
337
        jj_gc = 0;
338
        for (int i = 0; i < jj_2_rtns.length; i++) {
339
          JJCalls c = jj_2_rtns[i];
340
          while (c != null) {
341
            if (c.gen < jj_gen) c.first = null;
342
            c = c.next;
343
          }
344
        }
345
      }
346
      return token;
347
    }
348
    token = oldToken;
349
    jj_kind = kind;
350
    throw generateParseException();
351
  }
352
353
  static private final class LookaheadSuccess extends java.lang.Error { }
354
  final private LookaheadSuccess jj_ls = new LookaheadSuccess();
355
  final private boolean jj_scan_token(int kind) {
356
    if (jj_scanpos == jj_lastpos) {
357
      jj_la--;
358
      if (jj_scanpos.next == null) {
359
        jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
360
      } else {
361
        jj_lastpos = jj_scanpos = jj_scanpos.next;
362
      }
363
    } else {
364
      jj_scanpos = jj_scanpos.next;
365
    }
366
    if (jj_rescan) {
367
      int i = 0; Token tok = token;
368
      while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
369
      if (tok != null) jj_add_error_token(kind, i);
370
    }
371
    if (jj_scanpos.kind != kind) return true;
372
    if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
373
    return false;
374
  }
375
376
  final public Token getNextToken() {
377
    if (token.next != null) token = token.next;
378
    else token = token.next = token_source.getNextToken();
379
    jj_ntk = -1;
380
    jj_gen++;
381
    return token;
382
  }
383
384
  final public Token getToken(int index) {
385
    Token t = lookingAhead ? jj_scanpos : token;
386
    for (int i = 0; i < index; i++) {
387
      if (t.next != null) t = t.next;
388
      else t = t.next = token_source.getNextToken();
389
    }
390
    return t;
391
  }
392
393
  final private int jj_ntk() {
394
    if ((jj_nt=token.next) == null)
395
      return (jj_ntk = (token.next=token_source.getNextToken()).kind);
396
    else
397
      return (jj_ntk = jj_nt.kind);
398
  }
399
400
  private java.util.Vector jj_expentries = new java.util.Vector();
401
  private int[] jj_expentry;
402
  private int jj_kind = -1;
403
  private int[] jj_lasttokens = new int[100];
404
  private int jj_endpos;
405
406
  private void jj_add_error_token(int kind, int pos) {
407
    if (pos >= 100) return;
408
    if (pos == jj_endpos + 1) {
409
      jj_lasttokens[jj_endpos++] = kind;
410
    } else if (jj_endpos != 0) {
411
      jj_expentry = new int[jj_endpos];
412
      for (int i = 0; i < jj_endpos; i++) {
413
        jj_expentry[i] = jj_lasttokens[i];
414
      }
415
      boolean exists = false;
416
      for (java.util.Enumeration e = jj_expentries.elements(); e.hasMoreElements();) {
417
        int[] oldentry = (int[])(e.nextElement());
418
        if (oldentry.length == jj_expentry.length) {
419
          exists = true;
420
          for (int i = 0; i < jj_expentry.length; i++) {
421
            if (oldentry[i] != jj_expentry[i]) {
422
              exists = false;
423
              break;
424
            }
425
          }
426
          if (exists) break;
427
        }
428
      }
429
      if (!exists) jj_expentries.addElement(jj_expentry);
430
      if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;
431
    }
432
  }
433
434
  public ParseException generateParseException() {
435
    jj_expentries.removeAllElements();
436
    boolean[] la1tokens = new boolean[29];
437
    for (int i = 0; i < 29; i++) {
438
      la1tokens[i] = false;
439
    }
440
    if (jj_kind >= 0) {
441
      la1tokens[jj_kind] = true;
442
      jj_kind = -1;
443
    }
444
    for (int i = 0; i < 6; i++) {
445
      if (jj_la1[i] == jj_gen) {
446
        for (int j = 0; j < 32; j++) {
447
          if ((jj_la1_0[i] & (1<<j)) != 0) {
448
            la1tokens[j] = true;
449
          }
450
        }
451
      }
452
    }
453
    for (int i = 0; i < 29; i++) {
454
      if (la1tokens[i]) {
455
        jj_expentry = new int[1];
456
        jj_expentry[0] = i;
457
        jj_expentries.addElement(jj_expentry);
458
      }
459
    }
460
    jj_endpos = 0;
461
    jj_rescan_token();
462
    jj_add_error_token(0, 0);
463
    int[][] exptokseq = new int[jj_expentries.size()][];
464
    for (int i = 0; i < jj_expentries.size(); i++) {
465
      exptokseq[i] = (int[])jj_expentries.elementAt(i);
466
    }
467
    return new ParseException(token, exptokseq, tokenImage);
468
  }
469
470
  final public void enable_tracing() {
471
  }
472
473
  final public void disable_tracing() {
474
  }
475
476
  final private void jj_rescan_token() {
477
    jj_rescan = true;
478
    for (int i = 0; i < 1; i++) {
479
      JJCalls p = jj_2_rtns[i];
480
      do {
481
        if (p.gen > jj_gen) {
482
          jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
483
          switch (i) {
484
            case 0: jj_3_1(); break;
485
          }
486
        }
487
        p = p.next;
488
      } while (p != null);
489
    }
490
    jj_rescan = false;
491
  }
492
493
  final private void jj_save(int index, int xla) {
494
    JJCalls p = jj_2_rtns[index];
495
    while (p.gen > jj_gen) {
496
      if (p.next == null) { p = p.next = new JJCalls(); break; }
497
      p = p.next;
498
    }
499
    p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;
500
  }
501
502
  static final class JJCalls {
503
    int gen;
504
    Token first;
505
    int arg;
506
    JJCalls next;
507
  }
508
509
}
(-)src/org/eclipse/uml2/diagram/common/parser/port/JavaCharStream.java (+558 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 3.0 */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
15
/**
16
 * An implementation of interface CharStream, where the stream is assumed to
17
 * contain only ASCII characters (with java-like unicode escape processing).
18
 */
19
20
public class JavaCharStream
21
{
22
  public static final boolean staticFlag = false;
23
  static final int hexval(char c) throws java.io.IOException {
24
    switch(c)
25
    {
26
       case '0' :
27
          return 0;
28
       case '1' :
29
          return 1;
30
       case '2' :
31
          return 2;
32
       case '3' :
33
          return 3;
34
       case '4' :
35
          return 4;
36
       case '5' :
37
          return 5;
38
       case '6' :
39
          return 6;
40
       case '7' :
41
          return 7;
42
       case '8' :
43
          return 8;
44
       case '9' :
45
          return 9;
46
47
       case 'a' :
48
       case 'A' :
49
          return 10;
50
       case 'b' :
51
       case 'B' :
52
          return 11;
53
       case 'c' :
54
       case 'C' :
55
          return 12;
56
       case 'd' :
57
       case 'D' :
58
          return 13;
59
       case 'e' :
60
       case 'E' :
61
          return 14;
62
       case 'f' :
63
       case 'F' :
64
          return 15;
65
    }
66
67
    throw new java.io.IOException(); // Should never come here
68
  }
69
70
  public int bufpos = -1;
71
  int bufsize;
72
  int available;
73
  int tokenBegin;
74
  protected int bufline[];
75
  protected int bufcolumn[];
76
77
  protected int column = 0;
78
  protected int line = 1;
79
80
  protected boolean prevCharIsCR = false;
81
  protected boolean prevCharIsLF = false;
82
83
  protected java.io.Reader inputStream;
84
85
  protected char[] nextCharBuf;
86
  protected char[] buffer;
87
  protected int maxNextCharInd = 0;
88
  protected int nextCharInd = -1;
89
  protected int inBuf = 0;
90
91
  protected void ExpandBuff(boolean wrapAround)
92
  {
93
     char[] newbuffer = new char[bufsize + 2048];
94
     int newbufline[] = new int[bufsize + 2048];
95
     int newbufcolumn[] = new int[bufsize + 2048];
96
97
     try
98
     {
99
        if (wrapAround)
100
        {
101
           System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
102
           System.arraycopy(buffer, 0, newbuffer,
103
                                             bufsize - tokenBegin, bufpos);
104
           buffer = newbuffer;
105
106
           System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
107
           System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
108
           bufline = newbufline;
109
110
           System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
111
           System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
112
           bufcolumn = newbufcolumn;
113
114
           bufpos += (bufsize - tokenBegin);
115
        }
116
        else
117
        {
118
           System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
119
           buffer = newbuffer;
120
121
           System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
122
           bufline = newbufline;
123
124
           System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
125
           bufcolumn = newbufcolumn;
126
127
           bufpos -= tokenBegin;
128
        }
129
     }
130
     catch (Throwable t)
131
     {
132
        throw new Error(t.getMessage());
133
     }
134
135
     available = (bufsize += 2048);
136
     tokenBegin = 0;
137
  }
138
139
  protected void FillBuff() throws java.io.IOException
140
  {
141
     int i;
142
     if (maxNextCharInd == 4096)
143
        maxNextCharInd = nextCharInd = 0;
144
145
     try {
146
        if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
147
                                            4096 - maxNextCharInd)) == -1)
148
        {
149
           inputStream.close();
150
           throw new java.io.IOException();
151
        }
152
        else
153
           maxNextCharInd += i;
154
        return;
155
     }
156
     catch(java.io.IOException e) {
157
        if (bufpos != 0)
158
        {
159
           --bufpos;
160
           backup(0);
161
        }
162
        else
163
        {
164
           bufline[bufpos] = line;
165
           bufcolumn[bufpos] = column;
166
        }
167
        throw e;
168
     }
169
  }
170
171
  protected char ReadByte() throws java.io.IOException
172
  {
173
     if (++nextCharInd >= maxNextCharInd)
174
        FillBuff();
175
176
     return nextCharBuf[nextCharInd];
177
  }
178
179
  public char BeginToken() throws java.io.IOException
180
  {     
181
     if (inBuf > 0)
182
     {
183
        --inBuf;
184
185
        if (++bufpos == bufsize)
186
           bufpos = 0;
187
188
        tokenBegin = bufpos;
189
        return buffer[bufpos];
190
     }
191
192
     tokenBegin = 0;
193
     bufpos = -1;
194
195
     return readChar();
196
  }     
197
198
  protected void AdjustBuffSize()
199
  {
200
     if (available == bufsize)
201
     {
202
        if (tokenBegin > 2048)
203
        {
204
           bufpos = 0;
205
           available = tokenBegin;
206
        }
207
        else
208
           ExpandBuff(false);
209
     }
210
     else if (available > tokenBegin)
211
        available = bufsize;
212
     else if ((tokenBegin - available) < 2048)
213
        ExpandBuff(true);
214
     else
215
        available = tokenBegin;
216
  }
217
218
  protected void UpdateLineColumn(char c)
219
  {
220
     column++;
221
222
     if (prevCharIsLF)
223
     {
224
        prevCharIsLF = false;
225
        line += (column = 1);
226
     }
227
     else if (prevCharIsCR)
228
     {
229
        prevCharIsCR = false;
230
        if (c == '\n')
231
        {
232
           prevCharIsLF = true;
233
        }
234
        else
235
           line += (column = 1);
236
     }
237
238
     switch (c)
239
     {
240
        case '\r' :
241
           prevCharIsCR = true;
242
           break;
243
        case '\n' :
244
           prevCharIsLF = true;
245
           break;
246
        case '\t' :
247
           column--;
248
           column += (8 - (column & 07));
249
           break;
250
        default :
251
           break;
252
     }
253
254
     bufline[bufpos] = line;
255
     bufcolumn[bufpos] = column;
256
  }
257
258
  public char readChar() throws java.io.IOException
259
  {
260
     if (inBuf > 0)
261
     {
262
        --inBuf;
263
264
        if (++bufpos == bufsize)
265
           bufpos = 0;
266
267
        return buffer[bufpos];
268
     }
269
270
     char c;
271
272
     if (++bufpos == available)
273
        AdjustBuffSize();
274
275
     if ((buffer[bufpos] = c = ReadByte()) == '\\')
276
     {
277
        UpdateLineColumn(c);
278
279
        int backSlashCnt = 1;
280
281
        for (;;) // Read all the backslashes
282
        {
283
           if (++bufpos == available)
284
              AdjustBuffSize();
285
286
           try
287
           {
288
              if ((buffer[bufpos] = c = ReadByte()) != '\\')
289
              {
290
                 UpdateLineColumn(c);
291
                 // found a non-backslash char.
292
                 if ((c == 'u') && ((backSlashCnt & 1) == 1))
293
                 {
294
                    if (--bufpos < 0)
295
                       bufpos = bufsize - 1;
296
297
                    break;
298
                 }
299
300
                 backup(backSlashCnt);
301
                 return '\\';
302
              }
303
           }
304
           catch(java.io.IOException e)
305
           {
306
              if (backSlashCnt > 1)
307
                 backup(backSlashCnt);
308
309
              return '\\';
310
           }
311
312
           UpdateLineColumn(c);
313
           backSlashCnt++;
314
        }
315
316
        // Here, we have seen an odd number of backslash's followed by a 'u'
317
        try
318
        {
319
           while ((c = ReadByte()) == 'u')
320
              ++column;
321
322
           buffer[bufpos] = c = (char)(hexval(c) << 12 |
323
                                       hexval(ReadByte()) << 8 |
324
                                       hexval(ReadByte()) << 4 |
325
                                       hexval(ReadByte()));
326
327
           column += 4;
328
        }
329
        catch(java.io.IOException e)
330
        {
331
           throw new Error("Invalid escape character at line " + line +
332
                                         " column " + column + ".");
333
        }
334
335
        if (backSlashCnt == 1)
336
           return c;
337
        else
338
        {
339
           backup(backSlashCnt - 1);
340
           return '\\';
341
        }
342
     }
343
     else
344
     {
345
        UpdateLineColumn(c);
346
        return (c);
347
     }
348
  }
349
350
  /**
351
   * @deprecated 
352
   * @see #getEndColumn
353
   */
354
355
  public int getColumn() {
356
     return bufcolumn[bufpos];
357
  }
358
359
  /**
360
   * @deprecated 
361
   * @see #getEndLine
362
   */
363
364
  public int getLine() {
365
     return bufline[bufpos];
366
  }
367
368
  public int getEndColumn() {
369
     return bufcolumn[bufpos];
370
  }
371
372
  public int getEndLine() {
373
     return bufline[bufpos];
374
  }
375
376
  public int getBeginColumn() {
377
     return bufcolumn[tokenBegin];
378
  }
379
380
  public int getBeginLine() {
381
     return bufline[tokenBegin];
382
  }
383
384
  public void backup(int amount) {
385
386
    inBuf += amount;
387
    if ((bufpos -= amount) < 0)
388
       bufpos += bufsize;
389
  }
390
391
  public JavaCharStream(java.io.Reader dstream,
392
                 int startline, int startcolumn, int buffersize)
393
  {
394
    inputStream = dstream;
395
    line = startline;
396
    column = startcolumn - 1;
397
398
    available = bufsize = buffersize;
399
    buffer = new char[buffersize];
400
    bufline = new int[buffersize];
401
    bufcolumn = new int[buffersize];
402
    nextCharBuf = new char[4096];
403
  }
404
405
  public JavaCharStream(java.io.Reader dstream,
406
                                        int startline, int startcolumn)
407
  {
408
     this(dstream, startline, startcolumn, 4096);
409
  }
410
411
  public JavaCharStream(java.io.Reader dstream)
412
  {
413
     this(dstream, 1, 1, 4096);
414
  }
415
  public void ReInit(java.io.Reader dstream,
416
                 int startline, int startcolumn, int buffersize)
417
  {
418
    inputStream = dstream;
419
    line = startline;
420
    column = startcolumn - 1;
421
422
    if (buffer == null || buffersize != buffer.length)
423
    {
424
      available = bufsize = buffersize;
425
      buffer = new char[buffersize];
426
      bufline = new int[buffersize];
427
      bufcolumn = new int[buffersize];
428
      nextCharBuf = new char[4096];
429
    }
430
    prevCharIsLF = prevCharIsCR = false;
431
    tokenBegin = inBuf = maxNextCharInd = 0;
432
    nextCharInd = bufpos = -1;
433
  }
434
435
  public void ReInit(java.io.Reader dstream,
436
                                        int startline, int startcolumn)
437
  {
438
     ReInit(dstream, startline, startcolumn, 4096);
439
  }
440
441
  public void ReInit(java.io.Reader dstream)
442
  {
443
     ReInit(dstream, 1, 1, 4096);
444
  }
445
  public JavaCharStream(java.io.InputStream dstream, int startline,
446
  int startcolumn, int buffersize)
447
  {
448
     this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
449
  }
450
451
  public JavaCharStream(java.io.InputStream dstream, int startline,
452
                                                           int startcolumn)
453
  {
454
     this(dstream, startline, startcolumn, 4096);
455
  }
456
457
  public JavaCharStream(java.io.InputStream dstream)
458
  {
459
     this(dstream, 1, 1, 4096);
460
  }
461
462
  public void ReInit(java.io.InputStream dstream, int startline,
463
  int startcolumn, int buffersize)
464
  {
465
     ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
466
  }
467
  public void ReInit(java.io.InputStream dstream, int startline,
468
                                                           int startcolumn)
469
  {
470
     ReInit(dstream, startline, startcolumn, 4096);
471
  }
472
  public void ReInit(java.io.InputStream dstream)
473
  {
474
     ReInit(dstream, 1, 1, 4096);
475
  }
476
477
  public String GetImage()
478
  {
479
     if (bufpos >= tokenBegin)
480
        return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
481
     else
482
        return new String(buffer, tokenBegin, bufsize - tokenBegin) +
483
                              new String(buffer, 0, bufpos + 1);
484
  }
485
486
  public char[] GetSuffix(int len)
487
  {
488
     char[] ret = new char[len];
489
490
     if ((bufpos + 1) >= len)
491
        System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
492
     else
493
     {
494
        System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
495
                                                          len - bufpos - 1);
496
        System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
497
     }
498
499
     return ret;
500
  }
501
502
  public void Done()
503
  {
504
     nextCharBuf = null;
505
     buffer = null;
506
     bufline = null;
507
     bufcolumn = null;
508
  }
509
510
  /**
511
   * Method to adjust line and column numbers for the start of a token.
512
   */
513
  public void adjustBeginLineColumn(int newLine, int newCol)
514
  {
515
     int start = tokenBegin;
516
     int len;
517
518
     if (bufpos >= tokenBegin)
519
     {
520
        len = bufpos - tokenBegin + inBuf + 1;
521
     }
522
     else
523
     {
524
        len = bufsize - tokenBegin + bufpos + 1 + inBuf;
525
     }
526
527
     int i = 0, j = 0, k = 0;
528
     int nextColDiff = 0, columnDiff = 0;
529
530
     while (i < len &&
531
            bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
532
     {
533
        bufline[j] = newLine;
534
        nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
535
        bufcolumn[j] = newCol + columnDiff;
536
        columnDiff = nextColDiff;
537
        i++;
538
     } 
539
540
     if (i < len)
541
     {
542
        bufline[j] = newLine++;
543
        bufcolumn[j] = newCol + columnDiff;
544
545
        while (i++ < len)
546
        {
547
           if (bufline[j = start % bufsize] != bufline[++start % bufsize])
548
              bufline[j] = newLine++;
549
           else
550
              bufline[j] = newLine;
551
        }
552
     }
553
554
     line = bufline[j];
555
     column = bufcolumn[j];
556
  }
557
558
}
(-)META-INF/MANIFEST.MF (+20 lines)
Added Link Here
1
Manifest-Version: 1.0
2
Bundle-ManifestVersion: 2
3
Bundle-Name: UML Diagram Commons Plug-in
4
Bundle-SymbolicName: org.eclipse.uml2.diagram.common
5
Bundle-Version: 1.0.0
6
Bundle-Localization: plugin
7
Require-Bundle: org.eclipse.core.runtime,
8
 org.eclipse.core.resources,
9
 org.eclipse.uml2.uml;visibility:=reexport,
10
 org.eclipse.uml2.uml.edit;visibility:=reexport,
11
 org.eclipse.emf.ecore;visibility:=reexport,
12
 org.eclipse.emf.ecore.edit;visibility:=reexport,
13
 org.eclipse.emf.query.ocl;visibility:=reexport,
14
 org.eclipse.emf.ocl;visibility:=reexport,
15
 org.eclipse.gmf.runtime.draw2d.ui;visibility:=reexport,
16
 org.eclipse.draw2d;visibility:=reexport,
17
 org.eclipse.uml2.diagram.parser
18
Export-Package: org.eclipse.gmf.internal.codegen.draw2d,
19
 org.eclipse.uml2.diagram.common.draw2d,
20
 org.eclipse.uml2.diagram.common.parser.port;x-friends:="org.eclipse.uml2.diagram.clazz,org.eclipse.uml2.diagram.component"
(-)src/org/eclipse/uml2/diagram/common/parser/port/port.jj (+310 lines)
Added Link Here
1
options {
2
  JAVA_UNICODE_ESCAPE = true;
3
  STATIC=false;
4
}
5
6
PARSER_BEGIN(PortParser)
7
8
/*
9
 * Copyright (c) 2006 Borland Software Corporation
10
 * 
11
 * All rights reserved. This program and the accompanying materials
12
 * are made available under the terms of the Eclipse Public License v1.0
13
 * which accompanies this distribution, and is available at
14
 * http://www.eclipse.org/legal/epl-v10.html
15
 *
16
 * Contributors:
17
 *    Michael Golubev (Borland) - initial API and implementation
18
 */
19
package org.eclipse.uml2.diagram.common.parser.port;
20
21
import java.io.*;
22
import org.eclipse.emf.ecore.EClass;
23
import org.eclipse.emf.ecore.EObject;
24
import org.eclipse.uml2.diagram.parser.*;
25
import org.eclipse.uml2.diagram.parser.lookup.LookupSuite;
26
import org.eclipse.uml2.diagram.parser.lookup.LookupResolver;
27
import org.eclipse.uml2.uml.*;
28
29
public class PortParser extends ExternalParserBase {
30
	private Port mySubject;
31
	
32
    private static class TypeLookupCallback implements LookupResolver.Callback {
33
    	private final Port myPort;
34
35
		public TypeLookupCallback(Port property){
36
			myPort = property;
37
    	}
38
    	
39
    	public void lookupResolved(NamedElement resolution) {
40
    		if (resolution instanceof Type){
41
    			myPort.setType((Type)resolution);
42
    		}
43
    	}
44
    }
45
46
    public PortParser(){
47
    	this(new StringReader(""));
48
    }
49
    
50
    public PortParser(LookupSuite lookup){
51
    	this();
52
    	setLookupSuite(lookup);
53
    }
54
55
	public EClass getSubjectClass(){
56
		return UMLPackage.eINSTANCE.getPort();
57
	}
58
	
59
	public void parse(EObject target, String text) throws ExternalParserException {
60
		checkContext();
61
		ReInit(new StringReader(text));
62
		mySubject = (Port)target;
63
		Declaration();
64
		mySubject = null;
65
	}
66
	
67
	protected static int parseInt(Token t) throws ParseException {
68
		if (t.kind != PortParserConstants.INTEGER_LITERAL){
69
			throw new IllegalStateException("Token: " + t + ", image: " + t.image);
70
		}
71
		try {
72
			return Integer.parseInt(t.image); //XXX: "0005", "99999999999999999999999"
73
		} catch (NumberFormatException e){
74
			throw new ParseException("Not supported integer value:" + t.image);
75
		}
76
	}
77
	
78
}
79
80
PARSER_END(PortParser)
81
82
/* WHITE SPACE */
83
84
SPECIAL_TOKEN :
85
{
86
  " "
87
| "\t"
88
}
89
90
/* SEPARATORS */
91
TOKEN :
92
{
93
	< SLASH: "/" >
94
|	< COLON: ":" >
95
|	< EQUALS: "=" >
96
|	< LBRACKET: "[" >
97
|	< RBRACKET: "]" >
98
|	< LCURLY: "{" >
99
|	< RCURLY: "}" >
100
|	< COMMA: "," >
101
}
102
103
/* SPECIAL_MEANING */
104
TOKEN :
105
{
106
	< PLUS: "+" >
107
|	< MINUS: "-" >
108
|	< NUMBER_SIGN: "#" >
109
|	< TILDE: "~" >
110
|	< DOT: "." >
111
|	< STAR: "*" >
112
}
113
114
/* MODIFIERS */
115
TOKEN :
116
{
117
	< READ_ONLY: "readOnly" >
118
|	< UNION: "union" >
119
|	< SUBSETS: "subsets" >
120
|	< REDEFINES: "redefines" >
121
|	< ORDERED: "ordered" >
122
|	< UNORDERED: "unordered" > 
123
|	< UNIQUE: "unique" >
124
|	< NON_UNIQUE: "nonunique" >
125
}
126
	
127
/* LITERALS */
128
TOKEN: 
129
{
130
	< INTEGER_LITERAL: ["0"-"9"] (["0"-"9"])* >
131
}
132
  
133
TOKEN :
134
{
135
  < IDENTIFIER: <LETTER> (<LETTER>|<DIGIT>)* >
136
|
137
  < #LETTER:
138
      [
139
       "\u0024",
140
       "\u0041"-"\u005a",
141
       "\u005f",
142
       "\u0061"-"\u007a",
143
       "\u00c0"-"\u00d6",
144
       "\u00d8"-"\u00f6",
145
       "\u00f8"-"\u00ff",
146
       "\u0100"-"\u1fff",
147
       "\u3040"-"\u318f",
148
       "\u3300"-"\u337f",
149
       "\u3400"-"\u3d2d",
150
       "\u4e00"-"\u9fff",
151
       "\uf900"-"\ufaff"
152
      ]
153
  >
154
|
155
  < #DIGIT:
156
      [
157
       "\u0030"-"\u0039",
158
       "\u0660"-"\u0669",
159
       "\u06f0"-"\u06f9",
160
       "\u0966"-"\u096f",
161
       "\u09e6"-"\u09ef",
162
       "\u0a66"-"\u0a6f",
163
       "\u0ae6"-"\u0aef",
164
       "\u0b66"-"\u0b6f",
165
       "\u0be7"-"\u0bef",
166
       "\u0c66"-"\u0c6f",
167
       "\u0ce6"-"\u0cef",
168
       "\u0d66"-"\u0d6f",
169
       "\u0e50"-"\u0e59",
170
       "\u0ed0"-"\u0ed9",
171
       "\u1040"-"\u1049"
172
      ]
173
  >
174
}
175
176
void Declaration() :
177
{}
178
{
179
	(
180
		[ Visibility() ]
181
		PortName()
182
		[ PortType() ]
183
		[ Multiplicity() ]
184
	) <EOF>
185
}
186
187
void PortName() :
188
{
189
	String name;
190
}
191
{
192
	name = NameWithSpaces() 
193
	{
194
		mySubject.setName(name);
195
	}
196
}
197
198
void Visibility() :
199
{ 
200
	VisibilityKind kind;
201
}
202
{
203
	(
204
		<PLUS> { kind = VisibilityKind.PUBLIC_LITERAL; }
205
	|
206
		<MINUS> { kind = VisibilityKind.PRIVATE_LITERAL; }
207
	|
208
		<NUMBER_SIGN> { kind = VisibilityKind.PROTECTED_LITERAL; }
209
	|
210
		<TILDE> { kind = VisibilityKind.PACKAGE_LITERAL; }
211
	)
212
	{
213
		mySubject.setVisibility(kind);
214
	}
215
}
216
217
void Multiplicity() :
218
{}
219
{
220
	MultiplicityRange() 
221
	/* XXX: Parse conflict in case of empty DefaultValue, consider "a:int[5]{unique}"  
222
	[ MultiplicityDesignator() ] 
223
	*/
224
}
225
226
/* XXX: Parse conflict in case of empty default value
227
void MultiplicityDesignator() :
228
{ }
229
{
230
	<LCURLY> 
231
	(
232
		( MultiplicityUnique() [ MultiplicityOrdered() ] ) 
233
		|
234
		( MultiplicityOrdered() [ MultiplicityUnique() ] ) 
235
	) 
236
	<RCURLY>
237
}
238
239
void MultiplicityUnique() :
240
{}
241
{
242
		<UNIQUE> { mySubject.setIsUnique(true); }
243
	|
244
		<NON_UNIQUE> { mySubject.setIsUnique(false); }	
245
}
246
247
void MultiplicityOrdered() :
248
{}
249
{
250
		<ORDERED> { mySubject.setIsOrdered(true); }
251
	|
252
		<UNORDERED> { mySubject.setIsOrdered(false); }
253
}
254
255
*/
256
257
/* XXX: ValueSpecification -- how to parse */
258
void MultiplicityRange() :
259
{
260
	Token tLower = null;
261
	Token tUpper;
262
}
263
{
264
	<LBRACKET>
265
	(
266
		[ LOOKAHEAD(2) tLower = <INTEGER_LITERAL> <DOT> <DOT> { mySubject.setLower(parseInt(tLower)); } ] 
267
		(
268
			tUpper = <STAR> 
269
			{ 
270
				if (tLower == null){
271
					mySubject.setLower(0);
272
				}
273
				mySubject.setUpper(LiteralUnlimitedNatural.UNLIMITED); 
274
			}
275
		| 
276
			tUpper = <INTEGER_LITERAL> 
277
			{ 
278
				if (tLower == null){
279
					mySubject.setLower(parseInt(tUpper));
280
				}
281
				mySubject.setUpper(parseInt(tUpper)); 
282
			}
283
		)
284
	)
285
	<RBRACKET>
286
}
287
288
void PortType() :
289
{
290
	String type;
291
}
292
{
293
	<COLON> type = NameWithSpaces() { applyLookup(Type.class, type, new TypeLookupCallback(mySubject)); }
294
}
295
296
String NameWithSpaces() :
297
{
298
	StringBuffer result = new StringBuffer();
299
	Token t;
300
}
301
{
302
	(
303
		t = <IDENTIFIER> { result.append(t.image); } 
304
		( t = <IDENTIFIER> { result.append(' '); result.append(t.image); } ) *
305
	)
306
	{
307
		return result.toString();
308
	}
309
}
310
(-)src/org/eclipse/uml2/diagram/common/parser/port/PortParserTokenManager.java (+727 lines)
Added Link Here
1
/* Generated By:JavaCC: Do not edit this line. PortParserTokenManager.java */
2
/*
3
 * Copyright (c) 2006 Borland Software Corporation
4
 * 
5
 * All rights reserved. This program and the accompanying materials
6
 * are made available under the terms of the Eclipse Public License v1.0
7
 * which accompanies this distribution, and is available at
8
 * http://www.eclipse.org/legal/epl-v10.html
9
 *
10
 * Contributors:
11
 *    Michael Golubev (Borland) - initial API and implementation
12
 */
13
package org.eclipse.uml2.diagram.common.parser.port;
14
import java.io.*;
15
import org.eclipse.emf.ecore.EClass;
16
import org.eclipse.emf.ecore.EObject;
17
import org.eclipse.uml2.diagram.parser.*;
18
import org.eclipse.uml2.diagram.parser.lookup.LookupResolver;
19
import org.eclipse.uml2.diagram.parser.lookup.LookupSuite;
20
import org.eclipse.uml2.uml.*;
21
22
public class PortParserTokenManager implements PortParserConstants
23
{
24
  public  java.io.PrintStream debugStream = System.out;
25
  public  void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }
26
private final int jjStopStringLiteralDfa_0(int pos, long active0)
27
{
28
   switch (pos)
29
   {
30
      case 0:
31
         if ((active0 & 0x1fe0000L) != 0L)
32
         {
33
            jjmatchedKind = 26;
34
            return 2;
35
         }
36
         return -1;
37
      case 1:
38
         if ((active0 & 0x1fe0000L) != 0L)
39
         {
40
            jjmatchedKind = 26;
41
            jjmatchedPos = 1;
42
            return 2;
43
         }
44
         return -1;
45
      case 2:
46
         if ((active0 & 0x1fe0000L) != 0L)
47
         {
48
            jjmatchedKind = 26;
49
            jjmatchedPos = 2;
50
            return 2;
51
         }
52
         return -1;
53
      case 3:
54
         if ((active0 & 0x1fe0000L) != 0L)
55
         {
56
            jjmatchedKind = 26;
57
            jjmatchedPos = 3;
58
            return 2;
59
         }
60
         return -1;
61
      case 4:
62
         if ((active0 & 0x40000L) != 0L)
63
            return 2;
64
         if ((active0 & 0x1fa0000L) != 0L)
65
         {
66
            jjmatchedKind = 26;
67
            jjmatchedPos = 4;
68
            return 2;
69
         }
70
         return -1;
71
      case 5:
72
         if ((active0 & 0x800000L) != 0L)
73
            return 2;
74
         if ((active0 & 0x17a0000L) != 0L)
75
         {
76
            jjmatchedKind = 26;
77
            jjmatchedPos = 5;
78
            return 2;
79
         }
80
         return -1;
81
      case 6:
82
         if ((active0 & 0x280000L) != 0L)
83
            return 2;
84
         if ((active0 & 0x1520000L) != 0L)
85
         {
86
            jjmatchedKind = 26;
87
            jjmatchedPos = 6;
88
            return 2;
89
         }
90
         return -1;
91
      case 7:
92
         if ((active0 & 0x20000L) != 0L)
93
            return 2;
94
         if ((active0 & 0x1500000L) != 0L)
95
         {
96
            jjmatchedKind = 26;
97
            jjmatchedPos = 7;
98
            return 2;
99
         }
100
         return -1;
101
      default :
102
         return -1;
103
   }
104
}
105
private final int jjStartNfa_0(int pos, long active0)
106
{
107
   return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);
108
}
109
private final int jjStopAtPos(int pos, int kind)
110
{
111
   jjmatchedKind = kind;
112
   jjmatchedPos = pos;
113
   return pos + 1;
114
}
115
private final int jjStartNfaWithStates_0(int pos, int kind, int state)
116
{
117
   jjmatchedKind = kind;
118
   jjmatchedPos = pos;
119
   try { curChar = input_stream.readChar(); }
120
   catch(java.io.IOException e) { return pos + 1; }
121
   return jjMoveNfa_0(state, pos + 1);
122
}
123
private final int jjMoveStringLiteralDfa0_0()
124
{
125
   switch(curChar)
126
   {
127
      case 9:
128
         return jjStopAtPos(0, 2);
129
      case 32:
130
         return jjStopAtPos(0, 1);
131
      case 35:
132
         return jjStopAtPos(0, 13);
133
      case 42:
134
         return jjStopAtPos(0, 16);
135
      case 43:
136
         return jjStopAtPos(0, 11);
137
      case 44:
138
         return jjStopAtPos(0, 10);
139
      case 45:
140
         return jjStopAtPos(0, 12);
141
      case 46:
142
         return jjStopAtPos(0, 15);
143
      case 47:
144
         return jjStopAtPos(0, 3);
145
      case 58:
146
         return jjStopAtPos(0, 4);
147
      case 61:
148
         return jjStopAtPos(0, 5);
149
      case 91:
150
         return jjStopAtPos(0, 6);
151
      case 93:
152
         return jjStopAtPos(0, 7);
153
      case 110:
154
         return jjMoveStringLiteralDfa1_0(0x1000000L);
155
      case 111:
156
         return jjMoveStringLiteralDfa1_0(0x200000L);
157
      case 114:
158
         return jjMoveStringLiteralDfa1_0(0x120000L);
159
      case 115:
160
         return jjMoveStringLiteralDfa1_0(0x80000L);
161
      case 117:
162
         return jjMoveStringLiteralDfa1_0(0xc40000L);
163
      case 123:
164
         return jjStopAtPos(0, 8);
165
      case 125:
166
         return jjStopAtPos(0, 9);
167
      case 126:
168
         return jjStopAtPos(0, 14);
169
      default :
170
         return jjMoveNfa_0(1, 0);
171
   }
172
}
173
private final int jjMoveStringLiteralDfa1_0(long active0)
174
{
175
   try { curChar = input_stream.readChar(); }
176
   catch(java.io.IOException e) {
177
      jjStopStringLiteralDfa_0(0, active0);
178
      return 1;
179
   }
180
   switch(curChar)
181
   {
182
      case 101:
183
         return jjMoveStringLiteralDfa2_0(active0, 0x120000L);
184
      case 110:
185
         return jjMoveStringLiteralDfa2_0(active0, 0xc40000L);
186
      case 111:
187
         return jjMoveStringLiteralDfa2_0(active0, 0x1000000L);
188
      case 114:
189
         return jjMoveStringLiteralDfa2_0(active0, 0x200000L);
190
      case 117:
191
         return jjMoveStringLiteralDfa2_0(active0, 0x80000L);
192
      default :
193
         break;
194
   }
195
   return jjStartNfa_0(0, active0);
196
}
197
private final int jjMoveStringLiteralDfa2_0(long old0, long active0)
198
{
199
   if (((active0 &= old0)) == 0L)
200
      return jjStartNfa_0(0, old0); 
201
   try { curChar = input_stream.readChar(); }
202
   catch(java.io.IOException e) {
203
      jjStopStringLiteralDfa_0(1, active0);
204
      return 2;
205
   }
206
   switch(curChar)
207
   {
208
      case 97:
209
         return jjMoveStringLiteralDfa3_0(active0, 0x20000L);
210
      case 98:
211
         return jjMoveStringLiteralDfa3_0(active0, 0x80000L);
212
      case 100:
213
         return jjMoveStringLiteralDfa3_0(active0, 0x300000L);
214
      case 105:
215
         return jjMoveStringLiteralDfa3_0(active0, 0x840000L);
216
      case 110:
217
         return jjMoveStringLiteralDfa3_0(active0, 0x1000000L);
218
      case 111:
219
         return jjMoveStringLiteralDfa3_0(active0, 0x400000L);
220
      default :
221
         break;
222
   }
223
   return jjStartNfa_0(1, active0);
224
}
225
private final int jjMoveStringLiteralDfa3_0(long old0, long active0)
226
{
227
   if (((active0 &= old0)) == 0L)
228
      return jjStartNfa_0(1, old0); 
229
   try { curChar = input_stream.readChar(); }
230
   catch(java.io.IOException e) {
231
      jjStopStringLiteralDfa_0(2, active0);
232
      return 3;
233
   }
234
   switch(curChar)
235
   {
236
      case 100:
237
         return jjMoveStringLiteralDfa4_0(active0, 0x20000L);
238
      case 101:
239
         return jjMoveStringLiteralDfa4_0(active0, 0x300000L);
240
      case 111:
241
         return jjMoveStringLiteralDfa4_0(active0, 0x40000L);
242
      case 113:
243
         return jjMoveStringLiteralDfa4_0(active0, 0x800000L);
244
      case 114:
245
         return jjMoveStringLiteralDfa4_0(active0, 0x400000L);
246
      case 115:
247
         return jjMoveStringLiteralDfa4_0(active0, 0x80000L);
248
      case 117:
249
         return jjMoveStringLiteralDfa4_0(active0, 0x1000000L);
250
      default :
251
         break;
252
   }
253
   return jjStartNfa_0(2, active0);
254
}
255
private final int jjMoveStringLiteralDfa4_0(long old0, long active0)
256
{
257
   if (((active0 &= old0)) == 0L)
258
      return jjStartNfa_0(2, old0); 
259
   try { curChar = input_stream.readChar(); }
260
   catch(java.io.IOException e) {
261
      jjStopStringLiteralDfa_0(3, active0);
262
      return 4;
263
   }
264
   switch(curChar)
265
   {
266
      case 79:
267
         return jjMoveStringLiteralDfa5_0(active0, 0x20000L);
268
      case 100:
269
         return jjMoveStringLiteralDfa5_0(active0, 0x400000L);
270
      case 101:
271
         return jjMoveStringLiteralDfa5_0(active0, 0x80000L);
272
      case 102:
273
         return jjMoveStringLiteralDfa5_0(active0, 0x100000L);
274
      case 110:
275
         if ((active0 & 0x40000L) != 0L)
276
            return jjStartNfaWithStates_0(4, 18, 2);
277
         return jjMoveStringLiteralDfa5_0(active0, 0x1000000L);
278
      case 114:
279
         return jjMoveStringLiteralDfa5_0(active0, 0x200000L);
280
      case 117:
281
         return jjMoveStringLiteralDfa5_0(active0, 0x800000L);
282
      default :
283
         break;
284
   }
285
   return jjStartNfa_0(3, active0);
286
}
287
private final int jjMoveStringLiteralDfa5_0(long old0, long active0)
288
{
289
   if (((active0 &= old0)) == 0L)
290
      return jjStartNfa_0(3, old0); 
291
   try { curChar = input_stream.readChar(); }
292
   catch(java.io.IOException e) {
293
      jjStopStringLiteralDfa_0(4, active0);
294
      return 5;
295
   }
296
   switch(curChar)
297
   {
298
      case 101:
299
         if ((active0 & 0x800000L) != 0L)
300
            return jjStartNfaWithStates_0(5, 23, 2);
301
         return jjMoveStringLiteralDfa6_0(active0, 0x600000L);
302
      case 105:
303
         return jjMoveStringLiteralDfa6_0(active0, 0x1100000L);
304
      case 110:
305
         return jjMoveStringLiteralDfa6_0(active0, 0x20000L);
306
      case 116:
307
         return jjMoveStringLiteralDfa6_0(active0, 0x80000L);
308
      default :
309
         break;
310
   }
311
   return jjStartNfa_0(4, active0);
312
}
313
private final int jjMoveStringLiteralDfa6_0(long old0, long active0)
314
{
315
   if (((active0 &= old0)) == 0L)
316
      return jjStartNfa_0(4, old0); 
317
   try { curChar = input_stream.readChar(); }
318
   catch(java.io.IOException e) {
319
      jjStopStringLiteralDfa_0(5, active0);
320
      return 6;
321
   }
322
   switch(curChar)
323
   {
324
      case 100:
325
         if ((active0 & 0x200000L) != 0L)
326
            return jjStartNfaWithStates_0(6, 21, 2);
327
         break;
328
      case 108:
329
         return jjMoveStringLiteralDfa7_0(active0, 0x20000L);
330
      case 110:
331
         return jjMoveStringLiteralDfa7_0(active0, 0x100000L);
332
      case 113:
333
         return jjMoveStringLiteralDfa7_0(active0, 0x1000000L);
334
      case 114:
335
         return jjMoveStringLiteralDfa7_0(active0, 0x400000L);
336
      case 115:
337
         if ((active0 & 0x80000L) != 0L)
338
            return jjStartNfaWithStates_0(6, 19, 2);
339
         break;
340
      default :
341
         break;
342
   }
343
   return jjStartNfa_0(5, active0);
344
}
345
private final int jjMoveStringLiteralDfa7_0(long old0, long active0)
346
{
347
   if (((active0 &= old0)) == 0L)
348
      return jjStartNfa_0(5, old0); 
349
   try { curChar = input_stream.readChar(); }
350
   catch(java.io.IOException e) {
351
      jjStopStringLiteralDfa_0(6, active0);
352
      return 7;
353
   }
354
   switch(curChar)
355
   {
356
      case 101:
357
         return jjMoveStringLiteralDfa8_0(active0, 0x500000L);
358
      case 117:
359
         return jjMoveStringLiteralDfa8_0(active0, 0x1000000L);
360
      case 121:
361
         if ((active0 & 0x20000L) != 0L)
362
            return jjStartNfaWithStates_0(7, 17, 2);
363
         break;
364
      default :
365
         break;
366
   }
367
   return jjStartNfa_0(6, active0);
368
}
369
private final int jjMoveStringLiteralDfa8_0(long old0, long active0)
370
{
371
   if (((active0 &= old0)) == 0L)
372
      return jjStartNfa_0(6, old0); 
373
   try { curChar = input_stream.readChar(); }
374
   catch(java.io.IOException e) {
375
      jjStopStringLiteralDfa_0(7, active0);
376
      return 8;
377
   }
378
   switch(curChar)
379
   {
380
      case 100:
381
         if ((active0 & 0x400000L) != 0L)
382
            return jjStartNfaWithStates_0(8, 22, 2);
383
         break;
384
      case 101:
385
         if ((active0 & 0x1000000L) != 0L)
386
            return jjStartNfaWithStates_0(8, 24, 2);
387
         break;
388
      case 115:
389
         if ((active0 & 0x100000L) != 0L)
390
            return jjStartNfaWithStates_0(8, 20, 2);
391
         break;
392
      default :
393
         break;
394
   }
395
   return jjStartNfa_0(7, active0);
396
}
397
private final void jjCheckNAdd(int state)
398
{
399
   if (jjrounds[state] != jjround)
400
   {
401
      jjstateSet[jjnewStateCnt++] = state;
402
      jjrounds[state] = jjround;
403
   }
404
}
405
private final void jjAddStates(int start, int end)
406
{
407
   do {
408
      jjstateSet[jjnewStateCnt++] = jjnextStates[start];
409
   } while (start++ != end);
410
}
411
private final void jjCheckNAddTwoStates(int state1, int state2)
412
{
413
   jjCheckNAdd(state1);
414
   jjCheckNAdd(state2);
415
}
416
private final void jjCheckNAddStates(int start, int end)
417
{
418
   do {
419
      jjCheckNAdd(jjnextStates[start]);
420
   } while (start++ != end);
421
}
422
private final void jjCheckNAddStates(int start)
423
{
424
   jjCheckNAdd(jjnextStates[start]);
425
   jjCheckNAdd(jjnextStates[start + 1]);
426
}
427
static final long[] jjbitVec0 = {
428
   0x1ff00000fffffffeL, 0xffffffffffffc000L, 0xffffffffL, 0x600000000000000L
429
};
430
static final long[] jjbitVec2 = {
431
   0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL
432
};
433
static final long[] jjbitVec3 = {
434
   0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
435
};
436
static final long[] jjbitVec4 = {
437
   0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L
438
};
439
static final long[] jjbitVec5 = {
440
   0xffffffffffffffffL, 0xffffffffffffffffL, 0x0L, 0x0L
441
};
442
static final long[] jjbitVec6 = {
443
   0x3fffffffffffL, 0x0L, 0x0L, 0x0L
444
};
445
private final int jjMoveNfa_0(int startState, int curPos)
446
{
447
   int[] nextStates;
448
   int startsAt = 0;
449
   jjnewStateCnt = 3;
450
   int i = 1;
451
   jjstateSet[0] = startState;
452
   int j, kind = 0x7fffffff;
453
   for (;;)
454
   {
455
      if (++jjround == 0x7fffffff)
456
         ReInitRounds();
457
      if (curChar < 64)
458
      {
459
         long l = 1L << curChar;
460
         MatchLoop: do
461
         {
462
            switch(jjstateSet[--i])
463
            {
464
               case 1:
465
                  if ((0x3ff000000000000L & l) != 0L)
466
                  {
467
                     if (kind > 25)
468
                        kind = 25;
469
                     jjCheckNAdd(0);
470
                  }
471
                  else if (curChar == 36)
472
                  {
473
                     if (kind > 26)
474
                        kind = 26;
475
                     jjCheckNAdd(2);
476
                  }
477
                  break;
478
               case 0:
479
                  if ((0x3ff000000000000L & l) == 0L)
480
                     break;
481
                  if (kind > 25)
482
                     kind = 25;
483
                  jjCheckNAdd(0);
484
                  break;
485
               case 2:
486
                  if ((0x3ff001000000000L & l) == 0L)
487
                     break;
488
                  if (kind > 26)
489
                     kind = 26;
490
                  jjCheckNAdd(2);
491
                  break;
492
               default : break;
493
            }
494
         } while(i != startsAt);
495
      }
496
      else if (curChar < 128)
497
      {
498
         long l = 1L << (curChar & 077);
499
         MatchLoop: do
500
         {
501
            switch(jjstateSet[--i])
502
            {
503
               case 1:
504
               case 2:
505
                  if ((0x7fffffe87fffffeL & l) == 0L)
506
                     break;
507
                  if (kind > 26)
508
                     kind = 26;
509
                  jjCheckNAdd(2);
510
                  break;
511
               default : break;
512
            }
513
         } while(i != startsAt);
514
      }
515
      else
516
      {
517
         int hiByte = (int)(curChar >> 8);
518
         int i1 = hiByte >> 6;
519
         long l1 = 1L << (hiByte & 077);
520
         int i2 = (curChar & 0xff) >> 6;
521
         long l2 = 1L << (curChar & 077);
522
         MatchLoop: do
523
         {
524
            switch(jjstateSet[--i])
525
            {
526
               case 1:
527
               case 2:
528
                  if (!jjCanMove_0(hiByte, i1, i2, l1, l2))
529
                     break;
530
                  if (kind > 26)
531
                     kind = 26;
532
                  jjCheckNAdd(2);
533
                  break;
534
               default : break;
535
            }
536
         } while(i != startsAt);
537
      }
538
      if (kind != 0x7fffffff)
539
      {
540
         jjmatchedKind = kind;
541
         jjmatchedPos = curPos;
542
         kind = 0x7fffffff;
543
      }
544
      ++curPos;
545
      if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
546
         return curPos;
547
      try { curChar = input_stream.readChar(); }
548
      catch(java.io.IOException e) { return curPos; }
549
   }
550
}
551
static final int[] jjnextStates = {
552
};
553
private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2)
554
{
555
   switch(hiByte)
556
   {
557
      case 0:
558
         return ((jjbitVec2[i2] & l2) != 0L);
559
      case 48:
560
         return ((jjbitVec3[i2] & l2) != 0L);
561
      case 49:
562
         return ((jjbitVec4[i2] & l2) != 0L);
563
      case 51:
564
         return ((jjbitVec5[i2] & l2) != 0L);
565
      case 61:
566
         return ((jjbitVec6[i2] & l2) != 0L);
567
      default : 
568
         if ((jjbitVec0[i1] & l1) != 0L)
569
            return true;
570
         return false;
571
   }
572
}
573
public static final String[] jjstrLiteralImages = {
574
"", null, null, "\57", "\72", "\75", "\133", "\135", "\173", "\175", "\54", 
575
"\53", "\55", "\43", "\176", "\56", "\52", "\162\145\141\144\117\156\154\171", 
576
"\165\156\151\157\156", "\163\165\142\163\145\164\163", "\162\145\144\145\146\151\156\145\163", 
577
"\157\162\144\145\162\145\144", "\165\156\157\162\144\145\162\145\144", "\165\156\151\161\165\145", 
578
"\156\157\156\165\156\151\161\165\145", null, null, null, null, };
579
public static final String[] lexStateNames = {
580
   "DEFAULT", 
581
};
582
static final long[] jjtoToken = {
583
   0x7fffff9L, 
584
};
585
static final long[] jjtoSkip = {
586
   0x6L, 
587
};
588
static final long[] jjtoSpecial = {
589
   0x6L, 
590
};
591
protected JavaCharStream input_stream;
592
private final int[] jjrounds = new int[3];
593
private final int[] jjstateSet = new int[6];
594
protected char curChar;
595
public PortParserTokenManager(JavaCharStream stream)
596
{
597
   if (JavaCharStream.staticFlag)
598
      throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
599
   input_stream = stream;
600
}
601
public PortParserTokenManager(JavaCharStream stream, int lexState)
602
{
603
   this(stream);
604
   SwitchTo(lexState);
605
}
606
public void ReInit(JavaCharStream stream)
607
{
608
   jjmatchedPos = jjnewStateCnt = 0;
609
   curLexState = defaultLexState;
610
   input_stream = stream;
611
   ReInitRounds();
612
}
613
private final void ReInitRounds()
614
{
615
   int i;
616
   jjround = 0x80000001;
617
   for (i = 3; i-- > 0;)
618
      jjrounds[i] = 0x80000000;
619
}
620
public void ReInit(JavaCharStream stream, int lexState)
621
{
622
   ReInit(stream);
623
   SwitchTo(lexState);
624
}
625
public void SwitchTo(int lexState)
626
{
627
   if (lexState >= 1 || lexState < 0)
628
      throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
629
   else
630
      curLexState = lexState;
631
}
632
633
protected Token jjFillToken()
634
{
635
   Token t = Token.newToken(jjmatchedKind);
636
   t.kind = jjmatchedKind;
637
   String im = jjstrLiteralImages[jjmatchedKind];
638
   t.image = (im == null) ? input_stream.GetImage() : im;
639
   t.beginLine = input_stream.getBeginLine();
640
   t.beginColumn = input_stream.getBeginColumn();
641
   t.endLine = input_stream.getEndLine();
642
   t.endColumn = input_stream.getEndColumn();
643
   return t;
644
}
645
646
int curLexState = 0;
647
int defaultLexState = 0;
648
int jjnewStateCnt;
649
int jjround;
650
int jjmatchedPos;
651
int jjmatchedKind;
652
653
public Token getNextToken() 
654
{
655
  int kind;
656
  Token specialToken = null;
657
  Token matchedToken;
658
  int curPos = 0;
659
660
  EOFLoop :
661
  for (;;)
662
  {   
663
   try   
664
   {     
665
      curChar = input_stream.BeginToken();
666
   }     
667
   catch(java.io.IOException e)
668
   {        
669
      jjmatchedKind = 0;
670
      matchedToken = jjFillToken();
671
      matchedToken.specialToken = specialToken;
672
      return matchedToken;
673
   }
674
675
   jjmatchedKind = 0x7fffffff;
676
   jjmatchedPos = 0;
677
   curPos = jjMoveStringLiteralDfa0_0();
678
   if (jjmatchedKind != 0x7fffffff)
679
   {
680
      if (jjmatchedPos + 1 < curPos)
681
         input_stream.backup(curPos - jjmatchedPos - 1);
682
      if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
683
      {
684
         matchedToken = jjFillToken();
685
         matchedToken.specialToken = specialToken;
686
         return matchedToken;
687
      }
688
      else
689
      {
690
         if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
691
         {
692
            matchedToken = jjFillToken();
693
            if (specialToken == null)
694
               specialToken = matchedToken;
695
            else
696
            {
697
               matchedToken.specialToken = specialToken;
698
               specialToken = (specialToken.next = matchedToken);
699
            }
700
         }
701
         continue EOFLoop;
702
      }
703
   }
704
   int error_line = input_stream.getEndLine();
705
   int error_column = input_stream.getEndColumn();
706
   String error_after = null;
707
   boolean EOFSeen = false;
708
   try { input_stream.readChar(); input_stream.backup(1); }
709
   catch (java.io.IOException e1) {
710
      EOFSeen = true;
711
      error_after = curPos <= 1 ? "" : input_stream.GetImage();
712
      if (curChar == '\n' || curChar == '\r') {
713
         error_line++;
714
         error_column = 0;
715
      }
716
      else
717
         error_column++;
718
   }
719
   if (!EOFSeen) {
720
      input_stream.backup(1);
721
      error_after = curPos <= 1 ? "" : input_stream.GetImage();
722
   }
723
   throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
724
  }
725
}
726
727
}
(-).classpath (+7 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" path="src"/>
4
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
5
	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
6
	<classpathentry kind="output" path="bin"/>
7
</classpath>
(-).cvsignore (+2 lines)
Added Link Here
1
bin
2
.settings
(-)src/org/eclipse/gmf/internal/codegen/draw2d/GridLayout.java (+787 lines)
Added Link Here
1
package org.eclipse.gmf.internal.codegen.draw2d;
2
3
import java.util.HashMap;
4
import java.util.List;
5
import java.util.Map;
6
7
import org.eclipse.draw2d.AbstractLayout;
8
import org.eclipse.draw2d.IFigure;
9
import org.eclipse.draw2d.LayoutManager;
10
import org.eclipse.draw2d.geometry.Dimension;
11
import org.eclipse.draw2d.geometry.Rectangle;
12
import org.eclipse.swt.SWT;
13
14
15
/**
16
 * Lays out children into a Grid arrangement in which overall aligment and
17
 * spacing can be configured, as well as specfic layout requirements for the
18
 * each individual member of the GridLayout. This layout is a Draw2D port of the
19
 * swt GridLayout.
20
 * 
21
 * <code>GridLayout</code> has a number of configuration fields, and the
22
 * Figures it lays out can have an associated layout data object, called
23
 * <code>GridLayoutData</code> (similar to the swt GridLayoutData object). The power of
24
 * <code>GridLayout</code> lies in the ability to configure
25
 * <code>GridLayoutData</code> for each Figure in the layout.
26
 * <p>
27
 * The following code creates a container Figure managed by a
28
 * <code>GridLayout</code> with 2 columns, containing 3 RectangleFigure
29
 * shapes, the last of which has been given further layout instructions.
30
 * Note that it is the <code>GridLayout</code> method <code>setConstraint</code>
31
 * that binds the child <code>Figure</code> to its layout <code>GridLayoutData</code> object.
32
 * 
33
 * <pre>
34
 *     Figure container = new Figure();
35
 *     GridLayout gridLayout = new GridLayout();
36
 *     gridLayout.numColumns = 2;
37
 *     container.setLayout(gridLayout);
38
 * 
39
 *     Shape rect;
40
 *     rect = new RectangleFigure();
41
 *     container.add(rect);
42
 * 
43
 *     rect = new RectangleFigure();
44
 *     container.add(rect);
45
 * 
46
 *     rect = new RectangleFigure();
47
 *     GridLayoutData GridLayoutData = new GridLayoutData();
48
 *     GridLayoutData.widthHint = 150;
49
 *     layout.setConstraint(rect, GridLayoutData);
50
 * 
51
 *     container.add(rect);
52
 * </pre>
53
 * 
54
 * <p>
55
 * The <code>numColumns</code> field is the most important field in a
56
 * <code>GridLayout</code>. Widgets are laid out in columns from left to
57
 * right, and a new row is created when <code>numColumns</code>+ 1 figures
58
 * are added to the <code>Figure<code> parent container.
59
 * 
60
 * @see GridLayoutData
61
 * 
62
 * @author Asim Ullah
63
 * created: Sep 10, 2004
64
 */
65
public class GridLayout extends AbstractLayout {
66
	/**
67
	 * numColumns specifies the number of cell columns in the layout.
68
	 * 
69
	 * The default value is 1.
70
	 */
71
	public int numColumns = 1;
72
73
	/**
74
	 * makeColumnsEqualWidth specifies whether all columns in the layout will be
75
	 * forced to have the same width.
76
	 * 
77
	 * The default value is false.
78
	 */
79
	public boolean makeColumnsEqualWidth = false;
80
81
	/**
82
	 * marginWidth specifies the number of pixels of horizontal margin that will
83
	 * be placed along the left and right edges of the layout.
84
	 * 
85
	 * The default value is 5.
86
	 */
87
	public int marginWidth = 5;
88
89
	/**
90
	 * marginHeight specifies the number of pixels of vertical margin that will
91
	 * be placed along the top and bottom edges of the layout.
92
	 * 
93
	 * The default value is 5.
94
	 */
95
	public int marginHeight = 5;
96
97
	/**
98
	 * horizontalSpacing specifies the number of pixels between the right edge
99
	 * of one cell and the left edge of its neighbouring cell to the right.
100
	 * 
101
	 * The default value is 5.
102
	 */
103
	public int horizontalSpacing = 5;
104
105
	/**
106
	 * verticalSpacing specifies the number of pixels between the bottom edge of
107
	 * one cell and the top edge of its neighbouring cell underneath.
108
	 * 
109
	 * The default value is 5.
110
	 */
111
	public int verticalSpacing = 5;
112
113
	/** The layout contraints */
114
	protected Map constraints = new HashMap();
115
116
	/**
117
	 *  Default Constructor
118
	 */
119
	public GridLayout() {
120
		super();
121
	}
122
123
	/**
124
	 * Constructs a new instance of this class given the number of columns, and
125
	 * whether or not the columns should be forced to have the same width.
126
	 * 
127
	 * @param numColumns
128
	 *            the number of columns in the grid
129
	 * @param makeColumnsEqualWidth
130
	 *            whether or not the columns will have equal width
131
	 *  
132
	 */
133
	public GridLayout(int numColumns, boolean makeColumnsEqualWidth) {
134
		this.numColumns = numColumns;
135
		this.makeColumnsEqualWidth = makeColumnsEqualWidth;
136
	}
137
138
	/**
139
	 * @param child
140
	 * @param wHint
141
	 * @param hHint
142
	 * @return
143
	 */
144
	protected Dimension getChildSize(IFigure child, int wHint, int hHint) {
145
		return child.getPreferredSize(wHint, hHint);
146
	}
147
148
	GridLayoutData getData(IFigure[][] grid, int row, int column, int rowCount,
149
			int columnCount, boolean first) {
150
		IFigure figure = grid[row][column];
151
		if (figure != null) {
152
			GridLayoutData data = (GridLayoutData) getConstraint(figure);
153
			int hSpan = Math.max(1, Math.min(data.horizontalSpan, columnCount));
154
			int vSpan = Math.max(1, data.verticalSpan);
155
			int i = first ? row + vSpan - 1 : row - vSpan + 1;
156
			int j = first ? column + hSpan - 1 : column - hSpan + 1;
157
			if (0 <= i && i < rowCount) {
158
				if (0 <= j && j < columnCount) {
159
					if (figure == grid[i][j])
160
						return data;
161
				}
162
			}
163
		}
164
		return null;
165
	}
166
    
167
    void initChildren(IFigure container)
168
    {
169
        List children = container.getChildren();
170
        for (int i = 0; i < children.size(); i++) {
171
            IFigure child = (IFigure) children.get(i);
172
            if (child.getLayoutManager()==null)
173
            	child.setLayoutManager(this);
174
        }
175
    }
176
177
	/*
178
	 * (non-Javadoc)
179
	 * 
180
	 * @see org.eclipse.draw2d.AbstractLayout#calculatePreferredSize(org.eclipse.draw2d.IFigure,
181
	 *      int, int)
182
	 */
183
	protected Dimension calculatePreferredSize(IFigure container, int wHint,
184
			int hHint) {
185
		Dimension size = layout(container, false, 0, 0, wHint, hHint, /* flushCache */
186
				true);
187
    		if (wHint != SWT.DEFAULT)
188
			size.width = wHint;
189
		if (hHint != SWT.DEFAULT)
190
			size.height = hHint;
191
192
		return size;
193
	}
194
195
	/*
196
	 * (non-Javadoc)
197
	 * 
198
	 * @see org.eclipse.draw2d.LayoutManager#layout(org.eclipse.draw2d.IFigure)
199
	 */
200
	public void layout(IFigure container) {
201
        //initChildren( container);
202
		Rectangle rect = container.getClientArea();
203
		layout(container, true, rect.x, rect.y, rect.width, rect.height, /* flushCache */
204
				true);
205
206
	}
207
208
	Dimension layout(IFigure container, boolean move, int x, int y, int width,
209
			int height, boolean flushCache) {
210
		if (numColumns < 1)
211
			return new Dimension(marginWidth * 2, marginHeight * 2);
212
		List children = container.getChildren();
213
		for (int i = 0; i < children.size(); i++) {
214
			IFigure child = (IFigure) children.get(i);
215
216
			GridLayoutData data = (GridLayoutData) getConstraint(child);
217
			if (data == null)
218
				setConstraint(child, data = new GridLayoutData());
219
			if (flushCache)
220
				data.flushCache();
221
			data.computeSize(child, flushCache);
222
		}
223
224
		/* Build the grid */
225
		int row = 0, column = 0, rowCount = 0, columnCount = numColumns;
226
		IFigure[][] grid = new IFigure[4][columnCount];
227
		for (int i = 0; i < children.size(); i++) {
228
			IFigure child = (IFigure) children.get(i);
229
			GridLayoutData data = (GridLayoutData) getConstraint(child);
230
			int hSpan = Math.max(1, Math.min(data.horizontalSpan, columnCount));
231
			int vSpan = Math.max(1, data.verticalSpan);
232
			while (true) {
233
				int lastRow = row + vSpan;
234
				if (lastRow >= grid.length) {
235
					IFigure[][] newGrid = new IFigure[lastRow + 4][columnCount];
236
					System.arraycopy(grid, 0, newGrid, 0, grid.length);
237
					grid = newGrid;
238
				}
239
				if (grid[row] == null) {
240
					grid[row] = new IFigure[columnCount];
241
				}
242
				while (column < columnCount && grid[row][column] != null) {
243
					column++;
244
				}
245
				int endCount = column + hSpan;
246
				if (endCount <= columnCount) {
247
					int index = column;
248
					while (index < endCount && grid[row][index] == null) {
249
						index++;
250
					}
251
					if (index == endCount)
252
						break;
253
					column = index;
254
				}
255
				if (column + hSpan >= columnCount) {
256
					column = 0;
257
					row++;
258
				}
259
			}
260
			for (int j = 0; j < vSpan; j++) {
261
				if (grid[row + j] == null) {
262
					grid[row + j] = new IFigure[columnCount];
263
				}
264
				for (int k = 0; k < hSpan; k++) {
265
					grid[row + j][column + k] = child;
266
				}
267
			}
268
			rowCount = Math.max(rowCount, row + vSpan);
269
			column += hSpan;
270
		}
271
272
		/* Column widths */
273
		int availableWidth = width - horizontalSpacing * (columnCount - 1)
274
				- marginWidth * 2;
275
		int expandCount = 0;
276
		int[] widths = new int[columnCount];
277
		int[] minWidths = new int[columnCount];
278
		boolean[] expandColumn = new boolean[columnCount];
279
		for (int j = 0; j < columnCount; j++) {
280
			for (int i = 0; i < rowCount; i++) {
281
				GridLayoutData data = getData(grid, i, j, rowCount, columnCount, true);
282
				if (data != null) {
283
					int hSpan = Math.max(1, Math.min(data.horizontalSpan,
284
							columnCount));
285
					if (hSpan == 1) {
286
						int w = data.cacheWidth + data.horizontalIndent;
287
						widths[j] = Math.max(widths[j], w);
288
						if (data.grabExcessHorizontalSpace) {
289
							if (!expandColumn[j])
290
								expandCount++;
291
							expandColumn[j] = true;
292
						}
293
						if (data.widthHint != SWT.DEFAULT
294
								|| !data.grabExcessHorizontalSpace) {
295
							minWidths[j] = Math.max(minWidths[j], w);
296
						}
297
					}
298
				}
299
			}
300
			for (int i = 0; i < rowCount; i++) {
301
				GridLayoutData data = getData(grid, i, j, rowCount, columnCount,
302
						false);
303
				if (data != null) {
304
					int hSpan = Math.max(1, Math.min(data.horizontalSpan,
305
							columnCount));
306
					if (hSpan > 1) {
307
						int spanWidth = 0, spanMinWidth = 0, spanExpandCount = 0;
308
						for (int k = 0; k < hSpan; k++) {
309
							spanWidth += widths[j - k];
310
							spanMinWidth += minWidths[j - k];
311
							if (expandColumn[j - k])
312
								spanExpandCount++;
313
						}
314
						if (data.grabExcessHorizontalSpace
315
								&& spanExpandCount == 0) {
316
							expandCount++;
317
							expandColumn[j] = true;
318
						}
319
						int w = data.cacheWidth + data.horizontalIndent
320
								- spanWidth - (hSpan - 1) * horizontalSpacing;
321
						if (w > 0) {
322
							if (spanExpandCount == 0) {
323
								widths[j] += w;
324
							} else {
325
								int delta = w / spanExpandCount;
326
								int remainder = w % spanExpandCount, last = -1;
327
								for (int k = 0; k < hSpan; k++) {
328
									if (expandColumn[j - k]) {
329
										widths[last = j - k] += delta;
330
									}
331
								}
332
								if (last > -1)
333
									widths[last] += remainder;
334
							}
335
						}
336
						if (data.widthHint != SWT.DEFAULT
337
								|| !data.grabExcessHorizontalSpace) {
338
							w = data.cacheWidth + data.horizontalIndent
339
									- spanMinWidth - (hSpan - 1)
340
									* horizontalSpacing;
341
							if (w > 0) {
342
								if (spanExpandCount == 0) {
343
									minWidths[j] += w;
344
								} else {
345
									int delta = w / spanExpandCount;
346
									int remainder = w % spanExpandCount, last = -1;
347
									for (int k = 0; k < hSpan; k++) {
348
										if (expandColumn[j - k]) {
349
											minWidths[last = j - k] += delta;
350
										}
351
									}
352
									if (last > -1)
353
										minWidths[last] += remainder;
354
								}
355
							}
356
						}
357
					}
358
				}
359
			}
360
		}
361
		if (makeColumnsEqualWidth) {
362
			int minColumnWidth = 0;
363
			int columnWidth = 0;
364
			for (int i = 0; i < columnCount; i++) {
365
				minColumnWidth = Math.max(minColumnWidth, minWidths[i]);
366
				columnWidth = Math.max(columnWidth, widths[i]);
367
			}
368
			columnWidth = width == SWT.DEFAULT || expandCount == 0
369
					? columnWidth
370
					: Math.max(minColumnWidth, availableWidth / columnCount);
371
			for (int i = 0; i < columnCount; i++) {
372
				expandColumn[i] = expandCount > 0;
373
				widths[i] = columnWidth;
374
			}
375
		} else {
376
			if (width != SWT.DEFAULT && expandCount > 0) {
377
				int totalWidth = 0;
378
				for (int i = 0; i < columnCount; i++) {
379
					totalWidth += widths[i];
380
				}
381
				int count = expandCount;
382
				int delta = (availableWidth - totalWidth) / count;
383
				int remainder = (availableWidth - totalWidth) % count;
384
				int last = -1;
385
				while (totalWidth != availableWidth) {
386
					for (int j = 0; j < columnCount; j++) {
387
						if (expandColumn[j]) {
388
							if (widths[j] + delta > minWidths[j]) {
389
								widths[last = j] = widths[j] + delta;
390
							} else {
391
								widths[j] = minWidths[j];
392
								expandColumn[j] = false;
393
								count--;
394
							}
395
						}
396
					}
397
					if (last > -1)
398
						widths[last] += remainder;
399
400
					for (int j = 0; j < columnCount; j++) {
401
						for (int i = 0; i < rowCount; i++) {
402
							GridLayoutData data = getData(grid, i, j, rowCount,
403
									columnCount, false);
404
							if (data != null) {
405
								int hSpan = Math.max(1, Math.min(
406
										data.horizontalSpan, columnCount));
407
								if (hSpan > 1) {
408
									if (data.widthHint != SWT.DEFAULT
409
											|| !data.grabExcessHorizontalSpace) {
410
										int spanWidth = 0, spanExpandCount = 0;
411
										for (int k = 0; k < hSpan; k++) {
412
											spanWidth += widths[j - k];
413
											if (expandColumn[j - k])
414
												spanExpandCount++;
415
										}
416
										int w = data.cacheWidth
417
												+ data.horizontalIndent
418
												- spanWidth - (hSpan - 1)
419
												* horizontalSpacing;
420
										if (w > 0) {
421
											if (spanExpandCount == 0) {
422
												widths[j] += w;
423
											} else {
424
												int delta2 = w
425
														/ spanExpandCount;
426
												int remainder2 = w
427
														% spanExpandCount, last2 = -1;
428
												for (int k = 0; k < hSpan; k++) {
429
													if (expandColumn[j - k]) {
430
														widths[last2 = j - k] += delta2;
431
													}
432
												}
433
												if (last2 > -1)
434
													widths[last2] += remainder2;
435
											}
436
										}
437
									}
438
								}
439
							}
440
						}
441
					}
442
					if (count == 0)
443
						break;
444
					totalWidth = 0;
445
					for (int i = 0; i < columnCount; i++) {
446
						totalWidth += widths[i];
447
					}
448
					delta = (availableWidth - totalWidth) / count;
449
					remainder = (availableWidth - totalWidth) % count;
450
					last = -1;
451
				}
452
			}
453
		}
454
455
		/* Wrapping */
456
		GridLayoutData[] flush = null;
457
		int flushLength = 0;
458
		if (width != SWT.DEFAULT) {
459
			for (int j = 0; j < columnCount; j++) {
460
				for (int i = 0; i < rowCount; i++) {
461
					GridLayoutData data = getData(grid, i, j, rowCount, columnCount,
462
							false);
463
					if (data != null) {
464
						if (data.heightHint == SWT.DEFAULT) {
465
							IFigure child = grid[i][j];
466
							//TEMPORARY CODE
467
							int hSpan = Math.max(1, Math.min(
468
									data.horizontalSpan, columnCount));
469
							int currentWidth = 0;
470
							for (int k = 0; k < hSpan; k++) {
471
								currentWidth += widths[j - k];
472
							}
473
							currentWidth += (hSpan - 1) * horizontalSpacing
474
									- data.horizontalIndent;
475
							if ((currentWidth != data.cacheWidth && data.horizontalAlignment == GridLayoutData.FILL)
476
									|| (data.cacheWidth > currentWidth)) {
477
								int trim = 0;
478
								/*
479
								  // *Note*: Left this in place from SWT
480
								  // GridLayout. Not sure if Draw2D Borders or
481
								  // Scrollbars 'trim' will need to be takeninto account.
482
								  
483
								  if (child instanceof Group) { 
484
                                      Group g =(Group)child; trim = g.getSize ().x -
485
                                      g.getClientArea ().width; 
486
                                  } else if (child instanceof Scrollable) { 
487
                                      Rectangle rect =
488
                                          ((Scrollable) child).computeTrim (0, 0, 0,0);
489
                                           trim = rect.width; } 
490
                                  else {
491
    								  trim = child.getBorderWidth () * 2; 
492
                                  }
493
								 */
494
								int oldWidthHint = data.widthHint;
495
								data.widthHint = Math.max(0, currentWidth
496
										- trim);
497
								data.cacheWidth = data.cacheHeight = SWT.DEFAULT;
498
								data.computeSize(child, false);
499
								data.widthHint = oldWidthHint;
500
								if (flush == null)
501
									flush = new GridLayoutData[children.size()];
502
								flush[flushLength++] = data;
503
							}
504
						}
505
					}
506
				}
507
			}
508
		}
509
510
		/* Row heights */
511
		int availableHeight = height - verticalSpacing * (rowCount - 1)
512
				- marginHeight * 2;
513
		expandCount = 0;
514
		int[] heights = new int[rowCount];
515
		int[] minHeights = new int[rowCount];
516
		boolean[] expandRow = new boolean[rowCount];
517
		for (int i = 0; i < rowCount; i++) {
518
			for (int j = 0; j < columnCount; j++) {
519
				GridLayoutData data = getData(grid, i, j, rowCount, columnCount, true);
520
				if (data != null) {
521
					int vSpan = Math.max(1, Math.min(data.verticalSpan,
522
							rowCount));
523
					if (vSpan == 1) {
524
						int h = data.cacheHeight; // + data.verticalIndent;
525
						heights[i] = Math.max(heights[i], h);
526
						if (data.grabExcessVerticalSpace) {
527
							if (!expandRow[i])
528
								expandCount++;
529
							expandRow[i] = true;
530
						}
531
						if (data.heightHint != SWT.DEFAULT
532
								|| !data.grabExcessVerticalSpace) {
533
							minHeights[i] = Math.max(minHeights[i], h);
534
						}
535
					}
536
				}
537
			}
538
			for (int j = 0; j < columnCount; j++) {
539
				GridLayoutData data = getData(grid, i, j, rowCount, columnCount,
540
						false);
541
				if (data != null) {
542
					int vSpan = Math.max(1, Math.min(data.verticalSpan,
543
							rowCount));
544
					if (vSpan > 1) {
545
						int spanHeight = 0, spanMinHeight = 0, spanExpandCount = 0;
546
						for (int k = 0; k < vSpan; k++) {
547
							spanHeight += heights[i - k];
548
							spanMinHeight += minHeights[i - k];
549
							if (expandRow[i - k])
550
								spanExpandCount++;
551
						}
552
						if (data.grabExcessVerticalSpace
553
								&& spanExpandCount == 0) {
554
							expandCount++;
555
							expandRow[i] = true;
556
						}
557
						int h = data.cacheHeight - spanHeight - (vSpan - 1)
558
								* verticalSpacing; // + data.verticalalIndent
559
						if (h > 0) {
560
							if (spanExpandCount == 0) {
561
								heights[i] += h;
562
							} else {
563
								int delta = h / spanExpandCount;
564
								int remainder = h % spanExpandCount, last = -1;
565
								for (int k = 0; k < vSpan; k++) {
566
									if (expandRow[i - k]) {
567
										heights[last = i - k] += delta;
568
									}
569
								}
570
								if (last > -1)
571
									heights[last] += remainder;
572
							}
573
						}
574
						if (data.heightHint != SWT.DEFAULT
575
								|| !data.grabExcessVerticalSpace) {
576
							h = data.cacheHeight - spanMinHeight - (vSpan - 1)
577
									* verticalSpacing; // + data.verticalIndent
578
							if (h > 0) {
579
								if (spanExpandCount == 0) {
580
									minHeights[i] += h;
581
								} else {
582
									int delta = h / spanExpandCount;
583
									int remainder = h % spanExpandCount, last = -1;
584
									for (int k = 0; k < vSpan; k++) {
585
										if (expandRow[i - k]) {
586
											minHeights[last = i - k] += delta;
587
										}
588
									}
589
									if (last > -1)
590
										minHeights[last] += remainder;
591
								}
592
							}
593
						}
594
					}
595
				}
596
			}
597
		}
598
		if (height != SWT.DEFAULT && expandCount > 0) {
599
			int totalHeight = 0;
600
			for (int i = 0; i < rowCount; i++) {
601
				totalHeight += heights[i];
602
			}
603
			int count = expandCount;
604
			int delta = (availableHeight - totalHeight) / count;
605
			int remainder = (availableHeight - totalHeight) % count;
606
			int last = -1;
607
			while (totalHeight != availableHeight) {
608
				for (int i = 0; i < rowCount; i++) {
609
					if (expandRow[i]) {
610
						if (heights[i] + delta > minHeights[i]) {
611
							heights[last = i] = heights[i] + delta;
612
						} else {
613
							heights[i] = minHeights[i];
614
							expandRow[i] = false;
615
							count--;
616
						}
617
					}
618
				}
619
				if (last > -1)
620
					heights[last] += remainder;
621
622
				for (int i = 0; i < rowCount; i++) {
623
					for (int j = 0; j < columnCount; j++) {
624
						GridLayoutData data = getData(grid, i, j, rowCount,
625
								columnCount, false);
626
						if (data != null) {
627
							int vSpan = Math.max(1, Math.min(data.verticalSpan,
628
									rowCount));
629
							if (vSpan > 1) {
630
								if (data.heightHint != SWT.DEFAULT
631
										|| !data.grabExcessVerticalSpace) {
632
									int spanHeight = 0, spanExpandCount = 0;
633
									for (int k = 0; k < vSpan; k++) {
634
										spanHeight += heights[i - k];
635
										if (expandRow[i - k])
636
											spanExpandCount++;
637
									}
638
									int h = data.cacheHeight - spanHeight
639
											- (vSpan - 1) * verticalSpacing; // +
640
																			 // data.verticalIndent
641
									if (h > 0) {
642
										if (spanExpandCount == 0) {
643
											heights[i] += h;
644
										} else {
645
											int delta2 = h / spanExpandCount;
646
											int remainder2 = h
647
													% spanExpandCount, last2 = -1;
648
											for (int k = 0; k < vSpan; k++) {
649
												if (expandRow[i - k]) {
650
													heights[last2 = i - k] += delta2;
651
												}
652
											}
653
											if (last2 > -1)
654
												heights[last2] += remainder2;
655
										}
656
									}
657
								}
658
							}
659
						}
660
					}
661
				}
662
				if (count == 0)
663
					break;
664
				totalHeight = 0;
665
				for (int i = 0; i < rowCount; i++) {
666
					totalHeight += heights[i];
667
				}
668
				delta = (availableHeight - totalHeight) / count;
669
				remainder = (availableHeight - totalHeight) % count;
670
				last = -1;
671
			}
672
		}
673
674
		/* Position the IFigures */
675
		if (move) {
676
			int gridY = y + marginHeight;
677
			for (int i = 0; i < rowCount; i++) {
678
				int gridX = x + marginWidth;
679
				for (int j = 0; j < columnCount; j++) {
680
					GridLayoutData data = getData(grid, i, j, rowCount, columnCount,
681
							true);
682
					if (data != null) {
683
						int hSpan = Math.max(1, Math.min(data.horizontalSpan,
684
								columnCount));
685
						int vSpan = Math.max(1, data.verticalSpan);
686
						int cellWidth = 0, cellHeight = 0;
687
						for (int k = 0; k < hSpan; k++) {
688
							cellWidth += widths[j + k];
689
						}
690
						for (int k = 0; k < vSpan; k++) {
691
							cellHeight += heights[i + k];
692
						}
693
						cellWidth += horizontalSpacing * (hSpan - 1);
694
						int childX = gridX + data.horizontalIndent;
695
						int childWidth = Math.min(data.cacheWidth, cellWidth);
696
						switch (data.horizontalAlignment) {
697
							case GridLayoutData.CENTER :
698
								childX = gridX
699
										+ Math.max(0,
700
												(cellWidth - childWidth) / 2);
701
								break;
702
							case GridLayoutData.END :
703
								childX = gridX
704
										+ Math.max(0, cellWidth - childWidth);
705
								break;
706
							case GridLayoutData.FILL :
707
								childWidth = cellWidth - data.horizontalIndent;
708
								break;
709
						}
710
						cellHeight += verticalSpacing * (vSpan - 1);
711
						int childY = gridY; // + data.verticalIndent;
712
						int childHeight = Math
713
								.min(data.cacheHeight, cellHeight);
714
						switch (data.verticalAlignment) {
715
							case GridLayoutData.CENTER :
716
								childY = gridY
717
										+ Math.max(0,
718
												(cellHeight - childHeight) / 2);
719
								break;
720
							case GridLayoutData.END :
721
								childY = gridY
722
										+ Math.max(0, cellHeight - childHeight);
723
								break;
724
							case GridLayoutData.FILL :
725
								childHeight = cellHeight; // -
726
														  // data.verticalIndent;
727
								break;
728
						}
729
						IFigure child = grid[i][j];
730
						if (child != null) {
731
							// following param could be replaced by
732
							// Rectangle.SINGLETON
733
							child.setBounds(new Rectangle(childX, childY,
734
									childWidth, childHeight));
735
						}
736
					}
737
					gridX += widths[j] + horizontalSpacing;
738
				}
739
				gridY += heights[i] + verticalSpacing;
740
			}
741
		}
742
743
		// clean up cache
744
		for (int i = 0; i < flushLength; i++) {
745
			flush[i].cacheWidth = flush[i].cacheHeight = -1;
746
		}
747
748
		int totalDefaultWidth = 0;
749
		int totalDefaultHeight = 0;
750
		for (int i = 0; i < columnCount; i++) {
751
			totalDefaultWidth += widths[i];
752
		}
753
		for (int i = 0; i < rowCount; i++) {
754
			totalDefaultHeight += heights[i];
755
		}
756
		totalDefaultWidth += horizontalSpacing * (columnCount - 1)
757
				+ marginWidth * 2;
758
		totalDefaultHeight += verticalSpacing * (rowCount - 1) + marginHeight
759
				* 2;
760
		return new Dimension(totalDefaultWidth, totalDefaultHeight);
761
	}
762
763
	/*
764
	 * (non-Javadoc)
765
	 * 
766
	 * @see org.eclipse.draw2d.LayoutManager#getConstraint(org.eclipse.draw2d.IFigure)
767
	 */
768
	public Object getConstraint(IFigure child) {
769
		return constraints.get(child);
770
	}
771
772
	/**
773
	 * Sets the layout constraint of the given figure. The constraints can only
774
	 * be of type {@link GridLayoutData}.
775
	 * 
776
	 * @see LayoutManager#setConstraint(IFigure, Object)
777
	 */
778
	public void setConstraint(IFigure figure, Object newConstraint) {
779
		super.setConstraint(figure, newConstraint);
780
		if (newConstraint != null)
781
        {
782
			constraints.put(figure, newConstraint);
783
            
784
        }
785
	}
786
787
}
(-)src/org/eclipse/gmf/internal/codegen/draw2d/GridLayoutData.java (+453 lines)
Added Link Here
1
package org.eclipse.gmf.internal.codegen.draw2d;
2
3
import org.eclipse.draw2d.IFigure;
4
import org.eclipse.draw2d.geometry.Dimension;
5
import org.eclipse.swt.SWT;
6
7
8
/**
9
 * <code>GridLayoutData</code> is the layout data object associated with
10
 * <code>GridLayout</code>. To set a <code>GridLayoutData</code> object into a
11
 * <code>Figure</code>, you use the <code>setConstraint()</code> method of
12
 * <code>GridLayout</code> to map the <code>Figure</code> to its layout
13
 * <code>GridLayoutData</code>.
14
 * <p>
15
 * There are two ways to create a <code>GridLayoutData</code> object with certain
16
 * fields set. The first is to set the fields directly, like this:
17
 * 
18
 * <pre>
19
 * GridLayoutData gridData = new GridLayoutData();
20
 * gridData.horizontalAlignment = GridLayoutData.FILL;
21
 * gridData.grabExcessHorizontalSpace = true;
22
 * 
23
 * // associate the figure to the GridLayoutData object
24
 * myGridlayout.setConstraint(myFigure, gridData);
25
 * </pre>
26
 * 
27
 * The second is to take advantage of convenience style bits defined by
28
 * <code>GridLayoutData</code>:
29
 * 
30
 * <pre>
31
 * GridLayoutData gridData = new GridLayoutData(GridLayoutData.HORIZONTAL_ALIGN_FILL | GridLayoutData.GRAB_HORIZONTAL);
32
 * </pre>
33
 * 
34
 * </p>
35
 * <p>
36
 * NOTE: Do not reuse <code>GridLayoutData</code> objects. Every child in the parent
37
 * <code>Figure</code> that is managed by the <code>GridLayout</code> must
38
 * have a unique <code>GridLayoutData</code> object. If the layout data for a Grid
39
 * member in a <code>GridLayout</code> is null at layout time, a unique
40
 * <code>GridLayoutData</code> object is created for it.
41
 * </p>
42
 * 
43
 * [GMF]: NOTE: The set of the ALIGNMENT constants is changed in this class
44
 * comparing to original version to match the set of constants in the generated
45
 * code. E.g, <code>GridLayoutData.BEGINNING = SWT.BEGINNING - 1</code>.
46
 * Thus, this implementation is NOT intended to use SWT.* constants for
47
 * alignment.
48
 * 
49
 * @see GridLayout
50
 */
51
public final class GridLayoutData {
52
    /**
53
	 * verticalAlignment specifies how figures will be positioned vertically
54
	 * within a cell.
55
	 * 
56
	 * The default value is CENTER.
57
	 * 
58
	 * Possible values are:
59
	 * 
60
	 * <code>GridLayoutData.BEGINNING = SWT.BEGINNING - 1</code> (or
61
	 * <code>SWT.TOP - 1</code>): Position the figure at the top of the cell
62
	 * 
63
	 * <code>GridLayoutData.CENTER = SWT.CENTER - 1</code>: Position the
64
	 * figure in the vertical center of the cell
65
	 * 
66
	 * <code>GridLayoutData.END = SWT.END - 1</code> (or
67
	 * <code>SWT.BOTTOM - 1</code>): Position the figure at the bottom of the
68
	 * cell
69
	 * 
70
	 * <code>GridLayoutData.FILL = SWT.FILL - 1</code>: Resize the figure to
71
	 * fill the cell vertically
72
	 */
73
    public int verticalAlignment = CENTER;
74
    
75
    /**
76
	 * horizontalAlignment specifies how figures will be positioned horizontally
77
	 * within a cell.
78
	 * 
79
	 * The default value is BEGINNING.
80
	 * 
81
	 * Possible values are:
82
	 * 
83
	 * <code>GridLayoutData.BEGINNING = SWT.BEGINNING - 1</code> (or
84
	 * <code>SWT.TOP - 1</code>): Position the figure at the left of the cell
85
	 * 
86
	 * <code>GridLayoutData.CENTER = SWT.CENTER - 1</code>: Position the
87
	 * figure in the horizontal center of the cell
88
	 * 
89
	 * <code>GridLayoutData.END = SWT.END - 1</code> (or
90
	 * <code>SWT.BOTTOM - 1</code>): Position the figure at the right of the
91
	 * cell
92
	 * 
93
	 * <code>GridLayoutData.FILL = SWT.FILL - 1</code>: : Resize the figure
94
	 * to fill the cell horizontally
95
	 */
96
    public int horizontalAlignment = BEGINNING;
97
    
98
    /**
99
     * widthHint specifies a minimum width for the column. A value of 
100
     * SWT.DEFAULT indicates that no minimum width is specified.
101
     *
102
     * The default value is SWT.DEFAULT.
103
     */
104
    public int widthHint = SWT.DEFAULT;
105
    
106
    /**
107
     * heightHint specifies a minimum height for the row. A value of
108
     * SWT.DEFAULT indicates that no minimum height is specified.
109
     *
110
     * The default value is SWT.DEFAULT.
111
     */
112
    public int heightHint = SWT.DEFAULT;
113
    
114
    /**
115
     * horizontalIndent specifies the number of pixels of indentation
116
     * that will be placed along the left side of the cell.
117
     *
118
     * The default value is 0.
119
     */
120
    public int horizontalIndent = 0;
121
    
122
    /**
123
     * horizontalSpan specifies the number of column cells that the figure
124
     * will take up.
125
     *
126
     * The default value is 1.
127
     */
128
    public int horizontalSpan = 1;
129
    
130
    /**
131
     * verticalSpan specifies the number of row cells that the figure
132
     * will take up.
133
     *
134
     * The default value is 1.
135
     */
136
    public int verticalSpan = 1;
137
    
138
    /**
139
     * grabExcessHorizontalSpace specifies whether the cell will be made
140
     * wide enough to fit the remaining horizontal space.
141
     *
142
     * The default value is false.
143
     */ 
144
    public boolean grabExcessHorizontalSpace = false;
145
    
146
    /**
147
     * grabExcessVerticalSpace specifies whether the cell will be made
148
     * tall enough to fit the remaining vertical space.
149
     *
150
     * The default value is false.
151
     */ 
152
    public boolean grabExcessVerticalSpace = false;
153
154
    /**
155
     * Value for horizontalAlignment or verticalAlignment.
156
     * Position the figure at the top or left of the cell.
157
     */
158
    public static final int BEGINNING = 0; //SWT.BEGINNING - 1;
159
    
160
    /**
161
     * Value for horizontalAlignment or verticalAlignment.
162
     * Position the figure in the vertical or horizontal center of the cell
163
     */
164
    public static final int CENTER = 1;
165
    
166
    /**
167
     * Value for horizontalAlignment or verticalAlignment.
168
     * Position the figure at the bottom or right of the cell
169
     */
170
    public static final int END = 2;
171
    
172
    /**
173
     * Value for horizontalAlignment or verticalAlignment.
174
     * Resize the figure to fill the cell horizontally or vertically.
175
     */
176
    public static final int FILL = 3; //SWT.FILL - 1;
177
178
    /**
179
     * Style bit for <code>new GridLayoutData(int)</code>.
180
     * Position the figure at the top of the cell.
181
     * Not recommended. Use 
182
     * <code>new GridLayoutData(int, GridLayoutData.BEGINNING, boolean, boolean)</code>
183
     * instead.
184
     */
185
    public static final int VERTICAL_ALIGN_BEGINNING =  1 << 1;
186
    
187
    /**
188
     * Style bit for <code>new GridLayoutData(int)</code> to position the 
189
     * figure in the vertical center of the cell.
190
     * Not recommended. Use
191
     * <code>new GridLayoutData(int, GridLayoutData.CENTER, boolean, boolean)</code>
192
     * instead.
193
     */
194
    public static final int VERTICAL_ALIGN_CENTER = 1 << 2;
195
    
196
    /**
197
     * Style bit for <code>new GridLayoutData(int)</code> to position the 
198
     * figure at the bottom of the cell.
199
     * Not recommended. Use
200
     * <code>new GridLayoutData(int, GridLayoutData.END, boolean, boolean)</code>
201
     * instead.
202
     */
203
    public static final int VERTICAL_ALIGN_END = 1 << 3;
204
    
205
    /**
206
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
207
     * figure to fill the cell vertically.
208
     * Not recommended. Use
209
     * <code>new GridLayoutData(int, GridLayoutData.FILL, boolean, boolean)</code>
210
     * instead
211
     */
212
    public static final int VERTICAL_ALIGN_FILL = 1 << 4;
213
    
214
    /**
215
     * Style bit for <code>new GridLayoutData(int)</code> to position the 
216
     * figure at the left of the cell.
217
     * Not recommended. Use
218
     * <code>new GridLayoutData(GridLayoutData.BEGINNING, int, boolean, boolean)</code>
219
     * instead.
220
     */
221
    public static final int HORIZONTAL_ALIGN_BEGINNING =  1 << 5;
222
    
223
    /**
224
     * Style bit for <code>new GridLayoutData(int)</code> to position the 
225
     * figure in the horizontal center of the cell.
226
     * Not recommended. Use
227
     * <code>new GridLayoutData(GridLayoutData.CENTER, int, boolean, boolean)</code>
228
     * instead.
229
     */
230
    public static final int HORIZONTAL_ALIGN_CENTER = 1 << 6;
231
    
232
    /**
233
     * Style bit for <code>new GridLayoutData(int)</code> to position the 
234
     * figure at the right of the cell.
235
     * Not recommended. Use
236
     * <code>new GridLayoutData(GridLayoutData.END, int, boolean, boolean)</code>
237
     * instead.
238
     */
239
    public static final int HORIZONTAL_ALIGN_END = 1 << 7;
240
    
241
    /**
242
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
243
     * figure to fill the cell horizontally.
244
     * Not recommended. Use
245
     * <code>new GridLayoutData(GridLayoutData.FILL, int, boolean, boolean)</code>
246
     * instead.
247
     */
248
    public static final int HORIZONTAL_ALIGN_FILL = 1 << 8;
249
    
250
    /**
251
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
252
     * figure to fit the remaining horizontal space.
253
     * Not recommended. Use
254
     * <code>new GridLayoutData(int, int, true, boolean)</code>
255
     * instead.
256
     */
257
    public static final int GRAB_HORIZONTAL = 1 << 9;
258
    
259
    /**
260
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
261
     * figure to fit the remaining vertical space.
262
     * Not recommended. Use
263
     * <code>new GridLayoutData(int, int, boolean, true)</code>
264
     * instead.
265
     */
266
    public static final int GRAB_VERTICAL = 1 << 10;
267
    
268
    /**
269
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
270
     * figure to fill the cell vertically and to fit the remaining
271
     * vertical space.
272
     * FILL_VERTICAL = VERTICAL_ALIGN_FILL | GRAB_VERTICAL
273
     * Not recommended. Use
274
     * <code>new GridLayoutData(int, GridLayoutData.FILL, boolean, true)</code>
275
     * instead.
276
     */ 
277
    public static final int FILL_VERTICAL = VERTICAL_ALIGN_FILL | GRAB_VERTICAL;
278
    
279
    /**
280
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
281
     * figure to fill the cell horizontally and to fit the remaining
282
     * horizontal space.
283
     * FILL_HORIZONTAL = HORIZONTAL_ALIGN_FILL | GRAB_HORIZONTAL
284
     * Not recommended. Use
285
     * <code>new GridLayoutData(GridLayoutData.FILL, int, true, boolean)</code>
286
     * instead.
287
     */ 
288
    public static final int FILL_HORIZONTAL = HORIZONTAL_ALIGN_FILL | GRAB_HORIZONTAL;
289
    
290
    /**
291
     * Style bit for <code>new GridLayoutData(int)</code> to resize the 
292
     * figure to fill the cell horizontally and vertically and 
293
     * to fit the remaining horizontal and vertical space.
294
     * FILL_BOTH = FILL_VERTICAL | FILL_HORIZONTAL
295
     * Not recommended. Use
296
     * <code>new GridLayoutData(GridLayoutData.FILL, GridLayoutData.FILL, true, true)</code>
297
     * instead.
298
     */ 
299
    public static final int FILL_BOTH = FILL_VERTICAL | FILL_HORIZONTAL;
300
301
    int cacheWidth = -1, cacheHeight = -1;
302
    int [][] cache = new int[2][4];
303
    int cacheIndex = -1;
304
305
/**
306
 * Constructs a new instance of GridLayoutData using
307
 * default values.
308
 */
309
public GridLayoutData () {
310
    super ();
311
}
312
313
/**
314
 * Constructs a new instance based on the GridLayoutData style.
315
 * This constructor is not recommended.
316
 * 
317
 * @param style the GridLayoutData style
318
 */
319
public GridLayoutData (int style) {
320
    super ();
321
    if ((style & VERTICAL_ALIGN_BEGINNING) != 0) verticalAlignment = BEGINNING;
322
    if ((style & VERTICAL_ALIGN_CENTER) != 0) verticalAlignment = CENTER;
323
    if ((style & VERTICAL_ALIGN_FILL) != 0) verticalAlignment = FILL;
324
    if ((style & VERTICAL_ALIGN_END) != 0) verticalAlignment = END;
325
    if ((style & HORIZONTAL_ALIGN_BEGINNING) != 0) horizontalAlignment = BEGINNING;
326
    if ((style & HORIZONTAL_ALIGN_CENTER) != 0) horizontalAlignment = CENTER;
327
    if ((style & HORIZONTAL_ALIGN_FILL) != 0) horizontalAlignment = FILL;
328
    if ((style & HORIZONTAL_ALIGN_END) != 0) horizontalAlignment = END;
329
    grabExcessHorizontalSpace = (style & GRAB_HORIZONTAL) != 0;
330
    grabExcessVerticalSpace = (style & GRAB_VERTICAL) != 0;
331
}
332
333
/**
334
 * Constructs a new instance of GridLayoutData according to the parameters.
335
 * 
336
 * @param horizontalAlignment how figure will be positioned horizontally within a cell
337
 * @param verticalAlignment how figure will be positioned vertically within a cell
338
 * @param grabExcessHorizontalSpace whether cell will be made wide enough to fit the remaining horizontal space
339
 * @param grabExcessVerticalSpace whether cell will be made high enough to fit the remaining vertical space
340
 * 
341
 */
342
public GridLayoutData (int horizontalAlignment, int verticalAlignment, boolean grabExcessHorizontalSpace, boolean grabExcessVerticalSpace) {
343
    this (horizontalAlignment, verticalAlignment, grabExcessHorizontalSpace, grabExcessVerticalSpace, 1, 1);
344
}
345
346
/**
347
 * Constructs a new instance of GridLayoutData according to the parameters.
348
 *  
349
 * @param horizontalAlignment how figure will be positioned horizontally within a cell
350
 * @param verticalAlignment how figure will be positioned vertically within a cell
351
 * @param grabExcessHorizontalSpace whether cell will be made wide enough to fit the remaining horizontal space
352
 * @param grabExcessVerticalSpace whether cell will be made high enough to fit the remaining vertical space
353
 * @param horizontalSpan the number of column cells that the figure will take up
354
 * @param verticalSpan the number of row cells that the figure will take up
355
 * 
356
 */
357
public GridLayoutData (int horizontalAlignment, int verticalAlignment, boolean grabExcessHorizontalSpace, boolean grabExcessVerticalSpace, int horizontalSpan, int verticalSpan) {
358
    super ();
359
    this.horizontalAlignment = horizontalAlignment;
360
    this.verticalAlignment = verticalAlignment;
361
    this.grabExcessHorizontalSpace = grabExcessHorizontalSpace;
362
    this.grabExcessVerticalSpace = grabExcessVerticalSpace;
363
    this.horizontalSpan = horizontalSpan;
364
    this.verticalSpan = verticalSpan;
365
}
366
367
/**
368
 * Constructs a new instance of GridLayoutData according to the parameters.
369
 * A value of SWT.DEFAULT indicates that no minimum width or
370
 * no minumum height is specified.
371
 * 
372
 * @param width a minimum width for the column
373
 * @param height a minimum height for the row
374
 * 
375
 */
376
public GridLayoutData (int width, int height) {
377
    super ();
378
    this.widthHint = width;
379
    this.heightHint = height;
380
}
381
382
Dimension computeSize (IFigure figure, boolean flushCache) {
383
    if (cacheWidth != -1 && cacheHeight != -1) {
384
        return new Dimension (cacheWidth, cacheHeight);
385
    }
386
    for (int i = 0; i < cacheIndex + 1; i++) {
387
        if (cache [i][0] == widthHint && cache [i][1] == heightHint) {
388
            cacheWidth = cache [i][2];
389
            cacheHeight = cache [i][3];
390
            return new Dimension (cacheWidth, cacheHeight);
391
        }
392
    }
393
394
    Dimension size = figure.getPreferredSize(widthHint,heightHint);
395
    if (widthHint!=-1) size.width = widthHint;
396
    if (heightHint!=-1) size.height = heightHint;    
397
398
    if (cacheIndex < cache.length - 1) cacheIndex++;
399
    cache [cacheIndex][0] = widthHint;
400
    cache [cacheIndex][1] = heightHint;
401
    cacheWidth = cache [cacheIndex][2] = size.width;
402
    cacheHeight = cache [cacheIndex][3] = size.height;
403
    return size;
404
}
405
406
407
void flushCache () {
408
    cacheWidth = cacheHeight = -1;
409
    cacheIndex = -1;
410
}
411
412
String getName () {
413
    String string = getClass ().getName ();
414
    int index = string.lastIndexOf ('.');
415
    if (index == -1) return string;
416
    return string.substring (index + 1, string.length ());
417
}
418
419
public String toString () {
420
421
    String hAlign = "";
422
    switch (horizontalAlignment) {
423
        case FILL: hAlign = "GridLayoutData.FILL"; break;
424
        case BEGINNING: hAlign = "GridLayoutData.BEGINNING"; break;
425
        case END: hAlign = "GridLayoutData.LEFT"; break;
426
        case CENTER: hAlign = "GridLayoutData.CENTER"; break;
427
        default: hAlign = "Undefined "+horizontalAlignment; break;
428
    }
429
    String vAlign = "";
430
    switch (verticalAlignment) {
431
        case FILL: vAlign = "GridLayoutData.FILL"; break;
432
        case BEGINNING: vAlign = "GridLayoutData.BEGINNING"; break;
433
        case END: vAlign = "GridLayoutData.END"; break;
434
        case CENTER: vAlign = "GridLayoutData.CENTER"; break;
435
        default: vAlign = "Undefined "+verticalAlignment; break;
436
    }
437
    String string = getName()+" {";
438
    string += "horizontalAlignment="+hAlign+" ";
439
    if (horizontalIndent != 0) string += "horizontalIndent="+horizontalIndent+" ";
440
    if (horizontalSpan != 1) string += "horizontalSpan="+horizontalSpan+" ";
441
    if (grabExcessHorizontalSpace) string += "grabExcessHorizontalSpace="+grabExcessHorizontalSpace+" ";
442
    if (widthHint != SWT.DEFAULT) string += "widthHint="+widthHint+" ";
443
    string += "verticalAlignment="+vAlign+" ";
444
    if (verticalSpan != 1) string += "verticalSpan="+verticalSpan+" ";
445
    if (grabExcessVerticalSpace) string += "grabExcessVerticalSpace="+grabExcessVerticalSpace+" ";
446
    if (heightHint != SWT.DEFAULT) string += "heightHint="+heightHint+" ";
447
    string = string.trim();
448
    string += "}";
449
    return string;
450
451
}
452
453
}
(-)src/org/eclipse/uml2/diagram/common/draw2d/RequiredInterfaceDecoration.java (+77 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
13
package org.eclipse.uml2.diagram.common.draw2d;
14
15
import org.eclipse.draw2d.Graphics;
16
import org.eclipse.draw2d.PolylineDecoration;
17
import org.eclipse.draw2d.geometry.Point;
18
import org.eclipse.draw2d.geometry.PointList;
19
import org.eclipse.draw2d.geometry.Rectangle;
20
21
public class RequiredInterfaceDecoration extends PolylineDecoration {
22
	private static final Point TEMP_POINT = new Point(); 
23
	private static final Rectangle TEMP_RECTANGLE = new Rectangle();
24
	
25
	private final int GAP = 3;
26
	private int myRadius;
27
	private int myAngle;
28
	
29
	public RequiredInterfaceDecoration(){
30
		setRadius(1);
31
		setScale(1, 1);
32
	}
33
	
34
	public void setRadius(int radius){
35
		myRadius = radius;
36
		setTemplate(new PointList(new int[] {radius - GAP, 0} ));
37
	}
38
	
39
	@Override
40
	public Rectangle getBounds() {
41
		if (bounds == null){
42
			//implicitly sets bounds
43
			super.getBounds();
44
			computeArcBounds(TEMP_RECTANGLE);
45
			TEMP_RECTANGLE.expand(1, 1);
46
			bounds.union(TEMP_RECTANGLE);
47
		}
48
		return bounds;
49
	}
50
	
51
	@Override
52
	public void setRotation(double angle) {
53
		super.setRotation(angle);
54
		myAngle = (int) (angle * 180 / Math.PI);
55
	}
56
	
57
	@Override
58
	protected void fillShape(Graphics g) {
59
		//do nothing
60
	}
61
	
62
	@Override
63
	protected void outlineShape(Graphics g) {
64
		computeArcBounds(TEMP_RECTANGLE);
65
		g.drawArc(TEMP_RECTANGLE, -myAngle + 90, 180);
66
	}
67
	
68
	private void computeArcBounds(Rectangle output){
69
		if (getPoints().size() == 0){
70
			output.setSize(0, 0);
71
			return;
72
		}
73
		getPoints().getPoint(TEMP_POINT, 0);
74
		output.setLocation(TEMP_POINT.x - myRadius, TEMP_POINT.y - myRadius);
75
		output.setSize(2 * myRadius, 2 * myRadius);
76
	}
77
}
(-).project (+28 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>org.eclipse.uml2.diagram.common</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
		<buildCommand>
9
			<name>org.eclipse.jdt.core.javabuilder</name>
10
			<arguments>
11
			</arguments>
12
		</buildCommand>
13
		<buildCommand>
14
			<name>org.eclipse.pde.ManifestBuilder</name>
15
			<arguments>
16
			</arguments>
17
		</buildCommand>
18
		<buildCommand>
19
			<name>org.eclipse.pde.SchemaBuilder</name>
20
			<arguments>
21
			</arguments>
22
		</buildCommand>
23
	</buildSpec>
24
	<natures>
25
		<nature>org.eclipse.pde.PluginNature</nature>
26
		<nature>org.eclipse.jdt.core.javanature</nature>
27
	</natures>
28
</projectDescription>

Return to bug 80318