File: LineNumbersRuler.java

package info (click to toggle)
libjsyntaxpane-java 0.9.6~r156-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,400 kB
  • ctags: 1,100
  • sloc: java: 6,098; xml: 116; sh: 14; makefile: 11
file content (327 lines) | stat: -rw-r--r-- 10,061 bytes parent folder | download | duplicates (4)
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
/*
 * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License
 *       at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jsyntaxpane.components;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import jsyntaxpane.SyntaxDocument;
import jsyntaxpane.SyntaxView;
import jsyntaxpane.actions.ActionUtils;
import jsyntaxpane.actions.gui.GotoLineDialog;
import jsyntaxpane.util.Configuration;

/**
 * This class will display line numbers for a related text component. The text
 * component must use the same line height for each line. 
 *
 * This class was designed to be used as a component added to the row header
 * of a JScrollPane.
 *
 * Original code from http://tips4java.wordpress.com/2009/05/23/text-component-line-number/
 *
 * @author Rob Camick
 *
 * Revised for jsyntaxpane
 * 
 * @author Ayman Al-Sairafi
 */
public class LineNumbersRuler extends JPanel
	implements CaretListener, DocumentListener, PropertyChangeListener, SyntaxComponent {

	public static final String PROPERTY_BACKGROUND = "LineNumbers.Background";
	public static final String PROPERTY_FOREGROUND = "LineNumbers.Foreground";
	public static final String PROPERTY_CURRENT_BACK = "LineNumbers.CurrentBack";
	public static final String PROPERTY_LEFT_MARGIN = "LineNumbers.LeftMargin";
	public static final String PROPERTY_RIGHT_MARGIN = "LineNumbers.RightMargin";
	public static final String PROPERTY_Y_OFFSET = "LineNumbers.YOFFset";
	public static final int DEFAULT_R_MARGIN = 5;
	public static final int DEFAULT_L_MARGIN = 5;
	private Status status;
	private final static int MAX_HEIGHT = Integer.MAX_VALUE - 1000000;
	//  Text component this TextTextLineNumber component is in sync with
	private JEditorPane editor;
	private int minimumDisplayDigits = 2;
	//  Keep history information to reduce the number of times the component
	//  needs to be repainted
	private int lastDigits;
	private int lastHeight;
	private int lastLine;
	private MouseListener mouseListener = null;
	// The formatting to use for displaying numbers.  Use in String.format(numbersFormat, line)
	private String numbersFormat = "%3d";

	private Color currentLineColor;

	/**
	 * Get the JscrollPane that contains this EditorPane, or null if no
	 * JScrollPane is the parent of this editor
	 * @param editorPane
	 * @return
	 */
	public JScrollPane getScrollPane(JTextComponent editorPane) {
		Container p = editorPane.getParent();
		while (p != null) {
			if (p instanceof JScrollPane) {
				return (JScrollPane) p;
			}
			p = p.getParent();
		}
		return null;
	}

	@Override
	public void config(Configuration config) {
		int right = config.getInteger(PROPERTY_RIGHT_MARGIN, DEFAULT_R_MARGIN);
		int left = config.getInteger(PROPERTY_LEFT_MARGIN, DEFAULT_L_MARGIN);
		Color foreground = config.getColor(PROPERTY_FOREGROUND, Color.BLACK);
		setForeground(foreground);
		Color back = config.getColor(PROPERTY_BACKGROUND, Color.WHITE);
		setBackground(back);
		setBorder(BorderFactory.createEmptyBorder(0, left, 0, right));
		currentLineColor = config.getColor(PROPERTY_CURRENT_BACK, back);
	}

	@Override
	public void install(final JEditorPane editor) {
		this.editor = editor;

		setFont(editor.getFont());

		// setMinimumDisplayDigits(3);

		editor.getDocument().addDocumentListener(this);
		editor.addCaretListener(this);
		editor.addPropertyChangeListener(this);
		JScrollPane sp = getScrollPane(editor);
	   	if (sp != null)
			sp.setRowHeaderView(this);
		mouseListener = new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				GotoLineDialog.showForEditor(editor);
			}
		};
		addMouseListener(mouseListener);
		status = Status.INSTALLING;
        documentChanged();
	}

	@Override
	public void deinstall(JEditorPane editor) {
		removeMouseListener(mouseListener);
		status = Status.DEINSTALLING;
		this.editor.getDocument().removeDocumentListener(this);
		editor.removeCaretListener(this);
		editor.removePropertyChangeListener(this);
		JScrollPane sp = getScrollPane(editor);
		if (sp != null) {
			editor.getDocument().removeDocumentListener(this);
			sp.setRowHeaderView(null);
		}
	}

	/**
	 *  Gets the minimum display digits
	 *
	 *  @return the minimum display digits
	 */
	public int getMinimumDisplayDigits() {
		return minimumDisplayDigits;
	}

	/**
	 *  Specify the minimum number of digits used to calculate the preferred
	 *  width of the component. Default is 3.
	 *
	 *  @param minimumDisplayDigits  the number digits used in the preferred
	 *                               width calculation
	 */
	public void setMinimumDisplayDigits(int minimumDisplayDigits) {
		this.minimumDisplayDigits = minimumDisplayDigits;
		setPreferredWidth();
	}

	/**
	 *  Calculate the width needed to display the maximum line number
	 */
	private void setPreferredWidth() {
		int lines = ActionUtils.getLineCount(editor);
		int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits);

		//  Update sizes when number of digits in the line number changes

		if (lastDigits != digits) {
			lastDigits = digits;
			numbersFormat = "%" + digits + "d";
			FontMetrics fontMetrics = getFontMetrics(getFont());
			int width = fontMetrics.charWidth('0') * digits;
			Insets insets = getInsets();
			int preferredWidth = insets.left + insets.right + width;

			Dimension d = getPreferredSize();
			d.setSize(preferredWidth, MAX_HEIGHT);
			setPreferredSize(d);
			setSize(d);

		}
	}

	/**
	 *  Draw the line numbers
	 */
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);

		FontMetrics fontMetrics = editor.getFontMetrics(editor.getFont());
		Insets insets = getInsets();
		int currentLine = -1;
		try {
			// get current line, and add one as we start from 1 for the display
			currentLine = ActionUtils.getLineNumber(editor, editor.getCaretPosition()) + 1;
		} catch (BadLocationException ex) {
			// this wont happen, even if it does, we can ignore it and we will not have
			// a current line to worry about...
		}

		int lh = fontMetrics.getHeight();
		int maxLines = ActionUtils.getLineCount(editor);
		SyntaxView.setRenderingHits((Graphics2D) g);

		int topLine = (int) (g.getClip().getBounds().getY() / lh) + 1;
		int bottomLine = (int) (g.getClip().getBounds().getHeight()) + topLine;
		
		for (int line = topLine; line <= bottomLine; line++) {
			String lineNumber = String.format(numbersFormat, line);
			int y = line * lh;
			if (line == currentLine) {
				g.setColor(currentLineColor);
				g.fillRect(0, y - lh + fontMetrics.getDescent() - 1, getWidth(), lh);
				g.setColor(getForeground());
				g.drawString(lineNumber, insets.left, y);
			} else {
				g.drawString(lineNumber, insets.left, y);
			}
		}
	}

//
//  Implement CaretListener interface
//
	@Override
	public void caretUpdate(CaretEvent e) {
		//  Get the line the caret is positioned on

		int caretPosition = editor.getCaretPosition();
		Element root = editor.getDocument().getDefaultRootElement();
		int currentLine = root.getElementIndex(caretPosition);

		//  Need to repaint so the correct line number can be highlighted

		if (lastLine != currentLine) {
			repaint();
			lastLine = currentLine;
		}
	}

//
//  Implement DocumentListener interface
//
	@Override
	public void changedUpdate(DocumentEvent e) {
		documentChanged();
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		documentChanged();
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		documentChanged();
	}

	/*
	 *  A document change may affect the number of displayed lines of text.
	 *  Therefore the lines numbers will also change.
	 */
	private void documentChanged() {
		//  Preferred size of the component has not been updated at the time
		//  the DocumentEvent is fired

		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				int preferredHeight = editor.getPreferredSize().height;

				//  Document change has caused a change in the number of lines.
				//  Repaint to reflect the new line numbers

				if (lastHeight != preferredHeight) {
					setPreferredWidth();
					repaint();
					lastHeight = preferredHeight;
				}
			}
		});
	}

	/**
	 * Implement PropertyChangeListener interface
	 */
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("document")) {
			if (evt.getOldValue() instanceof SyntaxDocument) {
				SyntaxDocument syntaxDocument = (SyntaxDocument) evt.getOldValue();
				syntaxDocument.removeDocumentListener(this);
			}
			if (evt.getNewValue() instanceof SyntaxDocument && status.equals(Status.INSTALLING)) {
				SyntaxDocument syntaxDocument = (SyntaxDocument) evt.getNewValue();
				syntaxDocument.addDocumentListener(this);
				setPreferredWidth();
				repaint();
			}
		} else if (evt.getNewValue() instanceof Font) {
			setPreferredWidth();
			repaint();
		}
	}
}