01: package org.drools.eclipse.dsl.editor;
02:
03: import org.eclipse.jface.text.AbstractDocument;
04: import org.eclipse.jface.text.DefaultLineTracker;
05: import org.eclipse.jface.text.DocumentEvent;
06: import org.eclipse.jface.text.IDocument;
07: import org.eclipse.jface.text.IDocumentListener;
08: import org.eclipse.jface.text.ITextStore;
09:
10: /**
11: * A document that transforms the input of the original document
12: * to something else. Changing something in this document will
13: * NOT change the original document (as the transformation is only
14: * defined in one way). All changes will also be overridden as soon
15: * as the original document changes.
16: *
17: * @author <a href="mailto:kris_verlaenen@hotmail.com">Kris Verlaenen</a>
18: */
19: public abstract class TransformedDocument extends AbstractDocument {
20:
21: private IDocument parentDocument;
22: private boolean changed = true;
23:
24: public TransformedDocument(IDocument parentDocument) {
25: this .parentDocument = parentDocument;
26: parentDocument.addDocumentListener(new IDocumentListener() {
27: public void documentAboutToBeChanged(DocumentEvent event) {
28: // Do nothing
29: }
30:
31: public void documentChanged(DocumentEvent event) {
32: changed = true;
33: }
34: });
35: setTextStore(new StringTextStore());
36: setLineTracker(new DefaultLineTracker());
37: completeInitialization();
38: }
39:
40: /**
41: * Always check that the store is up-to-date.
42: * All read operations access the store so this method makes sure
43: * that the document is updated whenever necessary.
44: */
45: protected ITextStore getStore() {
46: if (changed) {
47: update();
48: }
49: return super .getStore();
50: }
51:
52: private void update() {
53: String translation = transformInput(parentDocument.get());
54: super .getStore().set(translation);
55: getTracker().set(translation);
56: changed = false;
57: }
58:
59: /**
60: * Transforms the original content of the document.
61: */
62: protected abstract String transformInput(String content);
63:
64: /**
65: * Default text store.
66: */
67: private static class StringTextStore implements ITextStore {
68:
69: private String fContent;
70:
71: public StringTextStore() {
72: }
73:
74: public char get(int offset) {
75: return fContent.charAt(offset);
76: }
77:
78: public String get(int offset, int length) {
79: return fContent.substring(offset, offset + length);
80: }
81:
82: public int getLength() {
83: return fContent.length();
84: }
85:
86: public void replace(int offset, int length, String text) {
87: }
88:
89: public void set(String text) {
90: this.fContent = text;
91: }
92: }
93:
94: }
|