Skip to main content
summaryrefslogtreecommitdiffstats
blob: bf4f411b990901eb9175ba136e25d568c6bd8bf5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package org.eclipse.debug.internal.ui.views;

/*
 * (c) Copyright IBM Corp. 2000, 2001.
 * All Rights Reserved.
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.debug.core.model.IStreamsProxy;
import org.eclipse.debug.internal.ui.ConsoleOutputTextStore;
import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.debug.internal.ui.IDebugPreferenceConstants;
import org.eclipse.jface.text.AbstractDocument;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.ITextStore;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;

public class ConsoleDocument extends AbstractDocument implements IDebugEventSetListener {

	private boolean fClosed= false;

	protected IProcess fProcess;
	private IStreamsProxy fProxy;
	private int fLastStreamWriteEnd= 0;
	private int fLastWritePosition= 0;
	private int fNewStreamWriteEnd= 0;
	protected boolean fNeedsToStartReading= true;
	
	class StreamEntry {
		/**
		 * Whether written to std out or std err - one of OUT/ERR
		 */
		private int fKind = -1;
		/**
		 * The text written
		 */
		private String fText = null;
		
		StreamEntry(String text, int kind) {
			fText = text;
			fKind = kind;
		}
		
		/**
		 * Returns the kind of entry - OUT or ERR
		 */
		public int getKind() {
			return fKind;
		}
		
		/**
		 * Returns the text written
		 */
		public String getText() {
			return fText;
		}
	}
	
	/**
	 * A queue of stream entries written to standard out and standard err.
	 * Entries appended to the end of the queue and removed from the front.
	 * Intentionally a vector to obtain synchronization as entries are
	 * added and removed.
	 */
	private Vector fQueue = new Vector(10);
	
	/**
	 * Thread that polls the queue for new output
	 */
	private Thread fPollingThread = null;
	
	/**
	 * Whether associated process has terminated
	 */
	private boolean fTerminated = false;
	
	/**
	 * Whether to keep polling
	 */
	private boolean fPoll = false;
	
	/**
	 * The base number of milliseconds to pause
	 * between polls.
	 */
	private static final long BASE_DELAY= 50L;
		
	public static final int OUT= 0;
	public static final int ERR= 1;
	
	protected List fStyleRanges= new ArrayList(2);

	protected ConsoleViewer fConsoleViewer= null;
	
	protected IStreamListener fSystemOutListener= new IStreamListener() {
				public void streamAppended(String newText, IStreamMonitor monitor) {
					DebugUIPlugin.getDefault().aboutToWriteSystemOut();
					systemOutAppended(newText);
				}
			};
			
	protected IStreamListener fSystemErrListener= new IStreamListener() {
				public void streamAppended(String newText, IStreamMonitor monitor) {
					DebugUIPlugin.getDefault().aboutToWriteSystemErr();
					systemErrAppended(newText);
				}
			};

	public ConsoleDocument(IProcess process) {
		super();
		fProcess= process;
		if (process != null) {
			fProxy= process.getStreamsProxy();			
			fTerminated = process.isTerminated();
			DebugPlugin.getDefault().addDebugEventListener(this);
			setTextStore(new ConsoleOutputTextStore(2500));
		} else {
			fClosed= true;
			fTerminated = true;
			setTextStore(new ConsoleOutputTextStore(0));	
		}
		setLineTracker(new DefaultLineTracker());
		completeInitialization();
	}

	public void close() {
		fClosed= true;
		stopReading();
		DebugPlugin.getDefault().removeDebugEventListener(this);
		fStyleRanges= Collections.EMPTY_LIST;
		set(""); //$NON-NLS-1$
	}

	/**
	 * Fires the <code>DocumentEvent</code>, but also
	 * writes to the proxy if the user is entering input and
	 * has hit "Enter".
	 */
	protected void fireDocumentChanged(DocumentEvent event) {
		super.fireDocumentChanged(event);
		String eventText= event.getText();
		if (eventText == null || 0 >= eventText.length() || eventText.length() > 2 || isClosed()) {
			return;
		}
		String[] lineDelimiters= event.getDocument().getLegalLineDelimiters();
		for (int i= 0; i < lineDelimiters.length; i++) {
			if (lineDelimiters[i].equals(eventText)) {
				try {
					String inText= event.getDocument().get();
					fLastWritePosition = fLastStreamWriteEnd;
					inText= inText.substring(fLastWritePosition, inText.length());
					if (inText.length() == 0) {
						return;
					}
					fProxy.write(inText);
					fLastStreamWriteEnd= getLength();
					return;
				} catch (IOException ioe) {
					if (!isClosed()) {
						DebugUIPlugin.log(ioe);
					}
				}
			}
		}
	}

	public boolean isClosed() {
		return fClosed;
	}
	
	/**
	 * @see IDocument#replace(int, int, String)
	 */
	public void replace(int pos, int replaceLength, String text) {
		if (isReadOnly() || pos < getStartOfEditableContent()) {
			return;
		}

		replace0(pos, replaceLength, text);
		int docLength= getLength();
		if (docLength == fNewStreamWriteEnd) {
			//removed all of the user input text
			fStyleRanges.remove(fStyleRanges.size() - 1);
		} else {
			updateInputStyleRange(docLength);
			//notify the viewer that the style ranges have changed.
			fireDocumentChanged(new DocumentEvent(this, 0, 0, "")); //$NON-NLS-1$
		}
	}
	
	/**
	 * Replace text used to add content from streams even though
	 * the process is terminated (and therefore the doc is "read only")
	 */
	protected void replace0(int pos, int replaceLength, String text) {
		try {		
			super.replace(pos, replaceLength, text);
		} catch (BadLocationException ble) {
			DebugUIPlugin.log(ble);
		}
	}

	
	/**
	 * @see IDocument#set(String)
	 */
	public void set(String text) {
		fNewStreamWriteEnd= text.length();
		super.set(text);
		fLastStreamWriteEnd= fNewStreamWriteEnd;
	}

	public void startReading() {
		if (fProxy == null) {
			return;
		}
		
		if (!fNeedsToStartReading) {
			return;
		}
		fNeedsToStartReading= false;
		IStreamMonitor monitor= fProxy.getOutputStreamMonitor();
		if (monitor != null) {
			monitor.addListener(fSystemOutListener);
			String contents= monitor.getContents();
			if (contents.length() > 0) {
				systemOutAppended(contents);
			}
		}
		monitor= fProxy.getErrorStreamMonitor();
		if (monitor != null) {
			monitor.addListener(fSystemErrListener);
			String contents= monitor.getContents();
			if (contents.length() > 0) {
				systemErrAppended(contents);
			}
		}
		Runnable r = new Runnable() {
			public void run() {
				pollAndSleep();
			}
		};
		fPoll = true;
		fPollingThread = new Thread(r, "Console Polling Thread");
		fPollingThread.start();
	}
	
	/**
	 * Polls and sleeps until closed or the associated
	 * process terminates
	 */
	protected void pollAndSleep() {
		while (fPoll && (!fTerminated || !fQueue.isEmpty())) {
			poll();
			try {
				Thread.sleep(BASE_DELAY);
			} catch (InterruptedException e) {
			}
		}
	}
	
	/**
	 * Polls the queue for new output and updates this document
	 */
	protected void poll() {
		synchronized(fQueue) {
			StringBuffer buffer = null;
			StreamEntry prev = null;
			int processed = 0;
			int amount = 0;
			while (processed < fQueue.size() && amount < 256) {
				StreamEntry entry = (StreamEntry)fQueue.get(processed);
				if (prev == null) {
					buffer = new StringBuffer(entry.getText());
				} else {
					if (prev.getKind() == entry.getKind()) {
						buffer.append(entry.getText());
					} else {
						appendToDocument(buffer.toString(),prev.getKind());
						buffer = new StringBuffer(entry.getText());
					}
				}
				prev = entry;
				processed++;
				amount+= entry.getText().length();
			}
			if (buffer != null) {
				appendToDocument(buffer.toString(), prev.getKind());
			}
			for (int i = 0; i < processed; i++) {
				fQueue.remove(0);
			}
		}
	}

	protected void stopReading() {
		fPoll = false;
		if (fProxy == null) {
			return;
		}
		fNeedsToStartReading= true;
		IStreamMonitor monitor= fProxy.getOutputStreamMonitor();
		monitor.removeListener(fSystemOutListener);
		monitor= fProxy.getErrorStreamMonitor();
		monitor.removeListener(fSystemErrListener);
	}

	/**
	 * System out or System error has had text append to it.
	 * Adds the new text to the document.
	 * 
	 * @see IStreamListener#streamAppended(String, IStreamMonitor)
	 */
	protected void appendToDocument(final String text, final int source) {
		update(new Runnable() {
			public void run() {
				int appendedLength= text.length();
				fNewStreamWriteEnd= fLastStreamWriteEnd + appendedLength;
				replace0(fLastStreamWriteEnd, 0, text);
				updateOutputStyleRanges(source);
				fLastStreamWriteEnd= fNewStreamWriteEnd;
			}
		});
	}
	
	/**
	 * System out or System error has had text append to it.
	 * Adds a new entry to the queue.
	 */
	protected void streamAppended(String text, int source) {
		fQueue.add(new StreamEntry(text, source));
	}
			
	/**
	 * @see IStreamListener#streamAppended(String, IStreamMonitor)
	 */
	protected void systemErrAppended(String text) {
		streamAppended(text, ERR);
	}

	/**
	 * @see IStreamListener#streamAppended(String, IStreamMonitor)
	 */
	protected void systemOutAppended(String text) {
		streamAppended(text, OUT);
	}

	
	/**
	 * @see Object#equals(Object)
	 */
	public boolean equals(Object obj) {
			boolean correctInstance= obj instanceof ConsoleDocument;
			if (fProcess != null) {
				return correctInstance && fProcess.equals(((ConsoleDocument)obj).fProcess);
			} else {
				return correctInstance && ((ConsoleDocument)obj).fProcess == null;
			}
    }
    
	/**
	 * @see Object#hashCode()
	 */
    public int hashCode() {
    	return (fProcess != null) ? fProcess.hashCode() : super.hashCode();
    }
    
	protected StyleRange[] getStyleRanges() {
		if (fStyleRanges.isEmpty()) {
			return new StyleRange[]{};
		} 
		StyleRange[] sRanges= new StyleRange[fStyleRanges.size()];
		return (StyleRange[])fStyleRanges.toArray(sRanges);
	}
	
	/**
	 * Coalese that last two style ranges if they are similar
	 */
	protected void coaleseRanges() {
		int size= fStyleRanges.size();
		if (size > 1) {
			StyleRange last= (StyleRange) fStyleRanges.get(size - 1);
			StyleRange nextToLast= (StyleRange) fStyleRanges.get(size - 2);
			if (last.similarTo(nextToLast)) {//same color?
				StyleRange newRange= new StyleRange(nextToLast.start, last.length + nextToLast.length, last.foreground, null);
				fStyleRanges.remove(size - 1);
				fStyleRanges.remove(size - 2);
				addNewStyleRange(newRange);
			}
		}
	}

	/**
	 * Returns whether the document's underlying process is
	 * terminated.
	 */
	protected boolean isReadOnly() {
		return (fProcess != null) ? fProcess.isTerminated() : true;
	}
	
	/**
	 * Updates the current input style range.
	 */
	protected void updateInputStyleRange(int docLength) {
		if (fClosed) {
			return;
		}
		if (docLength != fNewStreamWriteEnd) {
			StyleRange input= 
				new StyleRange(fNewStreamWriteEnd, docLength - fNewStreamWriteEnd, 
						DebugUIPlugin.getPreferenceColor(IDebugPreferenceConstants.CONSOLE_SYS_IN_RGB),
						null);
			if (!fStyleRanges.isEmpty()) {
				if (((StyleRange)fStyleRanges.get(fStyleRanges.size() - 1)).similarTo(input)) {
					//remove the top "input" range...continuing input
					fStyleRanges.remove(fStyleRanges.size() - 1);
				}
			} 
			
			addNewStyleRange(input);
		}
	}

	protected void updateOutputStyleRanges(int sourceStream) {
		if (fClosed) {
			return;
		}
		int docLength= getLength();
		if (docLength == 0) {
			return;
		}
		
		if ((fNewStreamWriteEnd == 0) && (0 == fLastStreamWriteEnd)) {
			return;
		}
		
		if (fNewStreamWriteEnd == fLastStreamWriteEnd) {
			return;
		}

		Color newRangeColor= 
			(sourceStream == ConsoleDocument.OUT) ? DebugUIPlugin.getPreferenceColor(IDebugPreferenceConstants.CONSOLE_SYS_OUT_RGB) : DebugUIPlugin.getPreferenceColor(IDebugPreferenceConstants.CONSOLE_SYS_ERR_RGB);

		StyleRange newRange= new StyleRange(fLastStreamWriteEnd, fNewStreamWriteEnd - fLastStreamWriteEnd, newRangeColor, null);
		if (!fStyleRanges.isEmpty()) {
			if ((docLength != fNewStreamWriteEnd) && 
				((StyleRange)fStyleRanges.get(fStyleRanges.size() - 1)).foreground ==
				DebugUIPlugin.getPreferenceColor(IDebugPreferenceConstants.CONSOLE_SYS_IN_RGB)) {
				//remove the top "input" range..it will get recalculated in updateInputStyleRanges
				fStyleRanges.remove(fStyleRanges.size() - 1);
			}
		}
		
		addNewStyleRange(newRange);
		coaleseRanges();
		updateInputStyleRange(docLength);
		//notify the viewer that the style ranges have changed.
		fireDocumentChanged(new DocumentEvent(this, 0, 0, null));
	}	
	
	/**
	 * Adds a new style range if the document is not closed.
	 * Note that the document can be closed by a separate thread.
	 * This is the reason for the copy of the style ranges.
	 */
	protected void addNewStyleRange(StyleRange newRange) {
		List tempRanges= fStyleRanges;
		if (fClosed) {
			return;
		}
		tempRanges.add(newRange);
	}
	
	protected void setStyleRanges(List ranges) {
		fStyleRanges= ranges;
	}

	protected void clearDocument() {
		fQueue.clear();
		fStyleRanges= new ArrayList(2);
		set(""); //$NON-NLS-1$
	}
	
	/**
	 * Returns the position after which editing of the
	 * content is allowable.
	 */
	protected int getStartOfEditableContent() {
		return fLastStreamWriteEnd;
	}
	
	/**
	 * Make visible to the ConsoleViewer
	 */
	protected ITextStore getStore() {
		return super.getStore();
	}
	
	/**
	 * @see IDebugEventListener#handleDebugEvents(DebugEvent[])
	 */
	public void handleDebugEvents(DebugEvent[] events) {
		if (fProcess == null) {
			return;
		}
		for (int i = 0; i < events.length; i++) {
			DebugEvent event = events[i];
			if (event.getKind() == DebugEvent.TERMINATE) {
				Object element= event.getSource();
				if (element != null && element.equals(fProcess)) {
					fTerminated = true;
					update( new Runnable() {
						public void run() {
							fireDocumentChanged(new DocumentEvent(ConsoleDocument.this, 0, 0, null));
						}
					});
				}					
			}
		}
	}
	
	/**
	 * Posts the update code "behind" the running operation if the 
	 * UI will be updated.
	 */
	protected void update(Runnable runnable) {
		if (fConsoleViewer != null && fConsoleViewer.getControl() != null && !fConsoleViewer.getControl().isDisposed()) {
			fConsoleViewer.getControl().getDisplay().asyncExec(runnable);
		} else {
			Display display= DebugUIPlugin.getDefault().getStandardDisplay();
			if (display != null && !display.isDisposed()) {
				display.asyncExec(runnable);
			}
		}
	}

	/**
	 * Sets the console viewer that this document is viewed within.
	 * Can be set to <code>null</code> if no longer currently being
	 * viewed.
	 */
	protected void setConsoleViewer(ConsoleViewer viewer) {
		fConsoleViewer = viewer;
	}

}

Back to the top