KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > text > edits > MoveSourceEdit


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.text.edits;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Arrays JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Map JavaDoc;
19
20 import org.eclipse.core.runtime.Assert;
21
22 import org.eclipse.jface.text.BadLocationException;
23 import org.eclipse.jface.text.IDocument;
24 import org.eclipse.jface.text.IRegion;
25 import org.eclipse.jface.text.Region;
26
27 /**
28  * A move source edit denotes the source of a move operation. Move
29  * source edits are only valid inside an edit tree if they have a
30  * corresponding target edit. Furthermore the corresponding target
31  * edit can't be a direct or indirect child of the source edit.
32  * Violating one of two requirements will result in a <code>
33  * MalformedTreeException</code> when executing the edit tree.
34  * <p>
35  * A move source edit can manage an optional source modifier. A
36  * source modifier can provide a set of replace edits which will
37  * to applied to the source before it gets inserted at the target
38  * position.
39  *
40  * @see org.eclipse.text.edits.MoveTargetEdit
41  * @see org.eclipse.text.edits.CopySourceEdit
42  *
43  * @since 3.0
44  */

45 public final class MoveSourceEdit extends TextEdit {
46
47     private MoveTargetEdit fTarget;
48     private ISourceModifier fModifier;
49
50     private String JavaDoc fSourceContent;
51     private MultiTextEdit fSourceRoot;
52
53     /**
54      * Constructs a new move source edit.
55      *
56      * @param offset the edit's offset
57      * @param length the edit's length
58      */

59     public MoveSourceEdit(int offset, int length) {
60         super(offset, length);
61     }
62
63     /**
64      * Constructs a new copy source edit.
65      *
66      * @param offset the edit's offset
67      * @param length the edit's length
68      * @param target the edit's target
69      */

70     public MoveSourceEdit(int offset, int length, MoveTargetEdit target) {
71         this(offset, length);
72         setTargetEdit(target);
73     }
74
75     /*
76      * Copy constructor
77      */

78     private MoveSourceEdit(MoveSourceEdit other) {
79         super(other);
80         if (other.fModifier != null)
81             fModifier= other.fModifier.copy();
82     }
83
84     /**
85      * Returns the associated target edit or <code>null</code>
86      * if no target edit is associated yet.
87      *
88      * @return the target edit or <code>null</code>
89      */

90     public MoveTargetEdit getTargetEdit() {
91         return fTarget;
92     }
93
94     /**
95      * Sets the target edit.
96      *
97      * @param edit the new target edit.
98      *
99      * @exception MalformedTreeException is thrown if the target edit
100      * is a direct or indirect child of the source edit
101      */

102     public void setTargetEdit(MoveTargetEdit edit) {
103         fTarget= edit;
104         fTarget.setSourceEdit(this);
105     }
106
107     /**
108      * Returns the current source modifier or <code>null</code>
109      * if no source modifier is set.
110      *
111      * @return the source modifier
112      */

113     public ISourceModifier getSourceModifier() {
114         return fModifier;
115     }
116
117     /**
118      * Sets the optional source modifier.
119      *
120      * @param modifier the source modifier or <code>null</code>
121      * if no source modification is need.
122      */

123     public void setSourceModifier(ISourceModifier modifier) {
124         fModifier= modifier;
125     }
126
127     //---- API for MoveTargetEdit ---------------------------------------------
128

129     String JavaDoc getContent() {
130         // The source content can be null if the edit wasn't executed
131
// due to an exclusion list of the text edit processor. Return
132
// the empty string which can be moved without any harm.
133
if (fSourceContent == null)
134             return ""; //$NON-NLS-1$
135
return fSourceContent;
136     }
137
138     MultiTextEdit getSourceRoot() {
139         return fSourceRoot;
140     }
141
142     void clearContent() {
143         fSourceContent= null;
144         fSourceRoot= null;
145     }
146
147     //---- Copying -------------------------------------------------------------
148

149     /*
150      * @see TextEdit#doCopy
151      */

152     protected TextEdit doCopy() {
153         return new MoveSourceEdit(this);
154     }
155
156     /*
157      * @see TextEdit#postProcessCopy
158      */

159     protected void postProcessCopy(TextEditCopier copier) {
160         if (fTarget != null) {
161             MoveSourceEdit source= (MoveSourceEdit)copier.getCopy(this);
162             MoveTargetEdit target= (MoveTargetEdit)copier.getCopy(fTarget);
163             if (source != null && target != null)
164                 source.setTargetEdit(target);
165         }
166     }
167
168     //---- Visitor -------------------------------------------------------------
169

170     /*
171      * @see TextEdit#accept0
172      */

173     protected void accept0(TextEditVisitor visitor) {
174         boolean visitChildren= visitor.visit(this);
175         if (visitChildren) {
176             acceptChildren(visitor);
177         }
178     }
179
180     //---- consistency check ----------------------------------------------------------------
181

182     int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List JavaDoc sourceEdits) {
183         int result= super.traverseConsistencyCheck(processor, document, sourceEdits);
184         // Since source computation takes place in a recursive fashion (see
185
// performSourceComputation) we only do something if we don't have a
186
// computed source already.
187
if (fSourceContent == null) {
188             if (sourceEdits.size() <= result) {
189                 List JavaDoc list= new ArrayList JavaDoc();
190                 list.add(this);
191                 for (int i= sourceEdits.size(); i < result; i++)
192                     sourceEdits.add(null);
193                 sourceEdits.add(list);
194             } else {
195                 List JavaDoc list= (List JavaDoc)sourceEdits.get(result);
196                 if (list == null) {
197                     list= new ArrayList JavaDoc();
198                     sourceEdits.add(result, list);
199                 }
200                 list.add(this);
201             }
202         }
203         return result;
204     }
205
206     void performConsistencyCheck(TextEditProcessor processor, IDocument document) throws MalformedTreeException {
207         if (fTarget == null)
208             throw new MalformedTreeException(getParent(), this, TextEditMessages.getString("MoveSourceEdit.no_target")); //$NON-NLS-1$
209
if (fTarget.getSourceEdit() != this)
210             throw new MalformedTreeException(getParent(), this, TextEditMessages.getString("MoveSourceEdit.different_source")); //$NON-NLS-1$
211
/* Causes AST rewrite to fail
212         if (getRoot() != fTarget.getRoot())
213             throw new MalformedTreeException(getParent(), this, TextEditMessages.getString("MoveSourceEdit.different_tree")); //$NON-NLS-1$
214         */

215     }
216
217     //---- source computation --------------------------------------------------------------
218

219     void traverseSourceComputation(TextEditProcessor processor, IDocument document) {
220         // always perform source computation independent of processor.considerEdit
221
// The target might need the source and the source is computed in a
222
// temporary buffer.
223
performSourceComputation(processor, document);
224     }
225
226     void performSourceComputation(TextEditProcessor processor, IDocument document) {
227         try {
228             TextEdit[] children= removeChildren();
229             if (children.length > 0) {
230                 String JavaDoc content= document.get(getOffset(), getLength());
231                 EditDocument subDocument= new EditDocument(content);
232                 fSourceRoot= new MultiTextEdit(getOffset(), getLength());
233                 fSourceRoot.addChildren(children);
234                 fSourceRoot.internalMoveTree(-getOffset());
235                 int processingStyle= getStyle(processor);
236                 TextEditProcessor subProcessor= TextEditProcessor.createSourceComputationProcessor(subDocument, fSourceRoot, processingStyle);
237                 subProcessor.performEdits();
238                 if (needsTransformation())
239                     applyTransformation(subDocument, processingStyle);
240                 fSourceContent= subDocument.get();
241             } else {
242                 fSourceContent= document.get(getOffset(), getLength());
243                 if (needsTransformation()) {
244                     EditDocument subDocument= new EditDocument(fSourceContent);
245                     applyTransformation(subDocument, getStyle(processor));
246                     fSourceContent= subDocument.get();
247                 }
248             }
249         } catch (BadLocationException cannotHappen) {
250             Assert.isTrue(false);
251         }
252     }
253
254     private int getStyle(TextEditProcessor processor) {
255         // we never need undo while performing local edits.
256
if ((processor.getStyle() & TextEdit.UPDATE_REGIONS) != 0)
257             return TextEdit.UPDATE_REGIONS;
258         return TextEdit.NONE;
259     }
260
261     //---- document updating ----------------------------------------------------------------
262

263     int performDocumentUpdating(IDocument document) throws BadLocationException {
264         document.replace(getOffset(), getLength(), ""); //$NON-NLS-1$
265
fDelta= -getLength();
266         return fDelta;
267     }
268
269     //---- region updating --------------------------------------------------------------
270

271     /*
272      * @see TextEdit#deleteChildren
273      */

274     boolean deleteChildren() {
275         return false;
276     }
277
278     //---- content transformation --------------------------------------------------
279

280     private boolean needsTransformation() {
281         return fModifier != null;
282     }
283
284     private void applyTransformation(IDocument document, int style) throws MalformedTreeException {
285         if ((style & TextEdit.UPDATE_REGIONS) != 0 && fSourceRoot != null) {
286             Map JavaDoc editMap= new HashMap JavaDoc();
287             TextEdit newEdit= createEdit(editMap);
288             List JavaDoc replaces= new ArrayList JavaDoc(Arrays.asList(fModifier.getModifications(document.get())));
289             insertEdits(newEdit, replaces);
290             try {
291                 newEdit.apply(document, style);
292             } catch (BadLocationException cannotHappen) {
293                 Assert.isTrue(false);
294             }
295             restorePositions(editMap);
296         } else {
297             MultiTextEdit newEdit= new MultiTextEdit(0, document.getLength());
298             TextEdit[] replaces= fModifier.getModifications(document.get());
299             for (int i= 0; i < replaces.length; i++) {
300                 newEdit.addChild(replaces[i]);
301             }
302             try {
303                 newEdit.apply(document, style);
304             } catch (BadLocationException cannotHappen) {
305                 Assert.isTrue(false);
306             }
307         }
308     }
309
310     private TextEdit createEdit(Map JavaDoc editMap) {
311         MultiTextEdit result= new MultiTextEdit(0, fSourceRoot.getLength());
312         editMap.put(result, fSourceRoot);
313         createEdit(fSourceRoot, result, editMap);
314         return result;
315     }
316
317     private static void createEdit(TextEdit source, TextEdit target, Map JavaDoc editMap) {
318         TextEdit[] children= source.getChildren();
319         for (int i= 0; i < children.length; i++) {
320             TextEdit child= children[i];
321             // a deleted child remains deleted even if the temporary buffer
322
// gets modified.
323
if (child.isDeleted())
324                 continue;
325             RangeMarker marker= new RangeMarker(child.getOffset(), child.getLength());
326             target.addChild(marker);
327             editMap.put(marker, child);
328             createEdit(child, marker, editMap);
329         }
330     }
331
332     private void insertEdits(TextEdit root, List JavaDoc edits) {
333         while(edits.size() > 0) {
334             ReplaceEdit edit= (ReplaceEdit)edits.remove(0);
335             insert(root, edit, edits);
336         }
337     }
338     private static void insert(TextEdit parent, ReplaceEdit edit, List JavaDoc edits) {
339         if (!parent.hasChildren()) {
340             parent.addChild(edit);
341             return;
342         }
343         TextEdit[] children= parent.getChildren();
344         // First dive down to find the right parent.
345
int removed= 0;
346         for (int i= 0; i < children.length; i++) {
347             TextEdit child= children[i];
348             if (child.covers(edit)) {
349                 insert(child, edit, edits);
350                 return;
351             } else if (edit.covers(child)) {
352                 parent.removeChild(i - removed++);
353                 edit.addChild(child);
354             } else {
355                 IRegion intersect= intersect(edit, child);
356                 if (intersect != null) {
357                     ReplaceEdit[] splits= splitEdit(edit, intersect);
358                     insert(child, splits[0], edits);
359                     edits.add(splits[1]);
360                     return;
361                 }
362             }
363         }
364         parent.addChild(edit);
365     }
366
367     public static IRegion intersect(TextEdit op1, TextEdit op2) {
368         int offset1= op1.getOffset();
369         int length1= op1.getLength();
370         int end1= offset1 + length1 - 1;
371         int offset2= op2.getOffset();
372         if (end1 < offset2)
373             return null;
374         int length2= op2.getLength();
375         int end2= offset2 + length2 - 1;
376         if (end2 < offset1)
377             return null;
378         
379         int end= Math.min(end1, end2);
380         if (offset1 < offset2) {
381             return new Region(offset2, end - offset2 + 1);
382         }
383         return new Region(offset1, end - offset1 + 1);
384     }
385
386     private static ReplaceEdit[] splitEdit(ReplaceEdit edit, IRegion intersect) {
387         if (edit.getOffset() != intersect.getOffset())
388             return splitIntersectRight(edit, intersect);
389         return splitIntersectLeft(edit, intersect);
390     }
391
392     private static ReplaceEdit[] splitIntersectRight(ReplaceEdit edit, IRegion intersect) {
393         ReplaceEdit[] result= new ReplaceEdit[2];
394         // this is the actual delete. We use replace to only deal with one type
395
result[0]= new ReplaceEdit(intersect.getOffset(), intersect.getLength(), ""); //$NON-NLS-1$
396
result[1]= new ReplaceEdit(
397                             edit.getOffset(),
398                             intersect.getOffset() - edit.getOffset(),
399                             edit.getText());
400         return result;
401     }
402
403     private static ReplaceEdit[] splitIntersectLeft(ReplaceEdit edit, IRegion intersect) {
404         ReplaceEdit[] result= new ReplaceEdit[2];
405         result[0]= new ReplaceEdit(intersect.getOffset(), intersect.getLength(), edit.getText());
406         result[1]= new ReplaceEdit( // this is the actual delete. We use replace to only deal with one type
407
intersect.getOffset() + intersect.getLength(),
408                             edit.getLength() - intersect.getLength(),
409                             ""); //$NON-NLS-1$
410
return result;
411     }
412
413     private static void restorePositions(Map JavaDoc editMap) {
414         for (Iterator JavaDoc iter= editMap.keySet().iterator(); iter.hasNext();) {
415             TextEdit marker= (TextEdit)iter.next();
416             TextEdit edit= (TextEdit)editMap.get(marker);
417             if (marker.isDeleted()) {
418                 edit.markAsDeleted();
419             } else {
420                 edit.adjustOffset(marker.getOffset() - edit.getOffset());
421                 edit.adjustLength(marker.getLength() - edit.getLength());
422             }
423         }
424     }
425 }
426
Popular Tags