Fix OOB, expose triple buffer
[nikiroo-utils.git] / src / jexer / io / SwingScreen.java
CommitLineData
daa4106c 1/*
1ac2ccb1
KL
2 * Jexer - Java Text User Interface
3 *
e16dda65 4 * The MIT License (MIT)
1ac2ccb1 5 *
a2018e99 6 * Copyright (C) 2017 Kevin Lamonte
1ac2ccb1 7 *
e16dda65
KL
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
1ac2ccb1 14 *
e16dda65
KL
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
1ac2ccb1 17 *
e16dda65
KL
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
1ac2ccb1
KL
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29package jexer.io;
30
1ac2ccb1
KL
31import java.awt.Color;
32import java.awt.Cursor;
33import java.awt.Font;
34import java.awt.FontMetrics;
1ac2ccb1 35import java.awt.Graphics;
c8165631 36import java.awt.Graphics2D;
84614868 37import java.awt.Insets;
30bd4abd
KL
38import java.awt.Point;
39import java.awt.Rectangle;
40import java.awt.Toolkit;
1ac2ccb1 41import java.awt.geom.Rectangle2D;
30bd4abd 42import java.awt.image.BufferedImage;
e3dfbd23 43import java.awt.image.BufferStrategy;
84614868 44import java.io.InputStream;
b5f2a6db 45import java.util.Date;
c8165631 46import java.util.HashMap;
aed33687
KL
47import javax.swing.JFrame;
48import javax.swing.SwingUtilities;
1ac2ccb1 49
b5f2a6db
KL
50import jexer.bits.Cell;
51import jexer.bits.CellAttributes;
52import jexer.session.SwingSessionInfo;
53
1ac2ccb1 54/**
a4406f4e 55 * This Screen implementation draws to a Java Swing JFrame.
1ac2ccb1 56 */
a4406f4e 57public final class SwingScreen extends Screen {
1ac2ccb1 58
e3dfbd23 59 /**
1d14ffab 60 * If true, use triple buffering thread.
e3dfbd23 61 */
e685a47d 62 private static boolean tripleBuffer = true;
e3dfbd23 63
b5f2a6db
KL
64 /**
65 * Cursor style to draw.
66 */
67 public enum CursorStyle {
68 /**
69 * Use an underscore for the cursor.
70 */
71 UNDERLINE,
72
73 /**
74 * Use a solid block for the cursor.
75 */
76 BLOCK,
77
78 /**
79 * Use an outlined block for the cursor.
80 */
81 OUTLINE
82 }
83
84614868
KL
84 private static Color MYBLACK;
85 private static Color MYRED;
86 private static Color MYGREEN;
87 private static Color MYYELLOW;
88 private static Color MYBLUE;
89 private static Color MYMAGENTA;
90 private static Color MYCYAN;
91 private static Color MYWHITE;
92
93 private static Color MYBOLD_BLACK;
94 private static Color MYBOLD_RED;
95 private static Color MYBOLD_GREEN;
96 private static Color MYBOLD_YELLOW;
97 private static Color MYBOLD_BLUE;
98 private static Color MYBOLD_MAGENTA;
99 private static Color MYBOLD_CYAN;
100 private static Color MYBOLD_WHITE;
101
102 private static boolean dosColors = false;
103
104 /**
a4406f4e 105 * Setup Swing colors to match DOS color palette.
84614868
KL
106 */
107 private static void setDOSColors() {
108 if (dosColors) {
109 return;
110 }
111 MYBLACK = new Color(0x00, 0x00, 0x00);
112 MYRED = new Color(0xa8, 0x00, 0x00);
113 MYGREEN = new Color(0x00, 0xa8, 0x00);
114 MYYELLOW = new Color(0xa8, 0x54, 0x00);
115 MYBLUE = new Color(0x00, 0x00, 0xa8);
116 MYMAGENTA = new Color(0xa8, 0x00, 0xa8);
117 MYCYAN = new Color(0x00, 0xa8, 0xa8);
118 MYWHITE = new Color(0xa8, 0xa8, 0xa8);
119 MYBOLD_BLACK = new Color(0x54, 0x54, 0x54);
120 MYBOLD_RED = new Color(0xfc, 0x54, 0x54);
121 MYBOLD_GREEN = new Color(0x54, 0xfc, 0x54);
122 MYBOLD_YELLOW = new Color(0xfc, 0xfc, 0x54);
123 MYBOLD_BLUE = new Color(0x54, 0x54, 0xfc);
124 MYBOLD_MAGENTA = new Color(0xfc, 0x54, 0xfc);
125 MYBOLD_CYAN = new Color(0x54, 0xfc, 0xfc);
126 MYBOLD_WHITE = new Color(0xfc, 0xfc, 0xfc);
127
128 dosColors = true;
129 }
130
1ac2ccb1 131 /**
a4406f4e 132 * SwingFrame is our top-level hook into the Swing system.
1ac2ccb1 133 */
a4406f4e 134 class SwingFrame extends JFrame {
1ac2ccb1 135
cf9af8df
KL
136 /**
137 * Serializable version.
138 */
139 private static final long serialVersionUID = 1;
140
84614868
KL
141 /**
142 * The terminus font resource filename.
143 */
144 private static final String FONTFILE = "terminus-ttf-4.39/TerminusTTF-Bold-4.39.ttf";
145
e3dfbd23 146 /**
1d14ffab 147 * The BufferStrategy object needed for triple-buffering.
e3dfbd23
KL
148 */
149 private BufferStrategy bufferStrategy;
150
c8165631
KL
151 /**
152 * A cache of previously-rendered glyphs for blinking text, when it
153 * is not visible.
154 */
155 private HashMap<Cell, BufferedImage> glyphCacheBlink;
156
157 /**
158 * A cache of previously-rendered glyphs for non-blinking, or
159 * blinking-and-visible, text.
160 */
161 private HashMap<Cell, BufferedImage> glyphCache;
162
1ac2ccb1
KL
163 /**
164 * The TUI Screen data.
165 */
a4406f4e 166 SwingScreen screen;
1ac2ccb1 167
55d2b2c2
KL
168 /**
169 * If true, we were successful getting Terminus.
170 */
171 private boolean gotTerminus = false;
172
1ac2ccb1
KL
173 /**
174 * Width of a character cell.
175 */
176 private int textWidth = 1;
177
178 /**
179 * Height of a character cell.
180 */
181 private int textHeight = 1;
182
84614868
KL
183 /**
184 * Descent of a character cell.
185 */
186 private int maxDescent = 0;
187
847a4bc5
KL
188 /**
189 * System-dependent Y adjustment for text in the character cell.
190 */
191 private int textAdjustY = 0;
192
193 /**
194 * System-dependent X adjustment for text in the character cell.
195 */
196 private int textAdjustX = 0;
197
1ac2ccb1 198 /**
b5f2a6db 199 * Top pixel absolute location.
1ac2ccb1
KL
200 */
201 private int top = 30;
84614868 202
1ac2ccb1 203 /**
b5f2a6db 204 * Left pixel absolute location.
1ac2ccb1
KL
205 */
206 private int left = 30;
84614868 207
b5f2a6db
KL
208 /**
209 * The cursor style to draw.
210 */
211 private CursorStyle cursorStyle = CursorStyle.UNDERLINE;
212
213 /**
214 * The number of millis to wait before switching the blink from
215 * visible to invisible.
216 */
217 private long blinkMillis = 500;
218
219 /**
220 * If true, the cursor should be visible right now based on the blink
221 * time.
222 */
223 private boolean cursorBlinkVisible = true;
224
225 /**
226 * The time that the blink last flipped from visible to invisible or
227 * from invisible to visible.
228 */
229 private long lastBlinkTime = 0;
230
84614868 231 /**
a4406f4e 232 * Convert a CellAttributes foreground color to an Swing Color.
84614868
KL
233 *
234 * @param attr the text attributes
a4406f4e 235 * @return the Swing Color
84614868
KL
236 */
237 private Color attrToForegroundColor(final CellAttributes attr) {
7c870d89 238 if (attr.isBold()) {
84614868
KL
239 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
240 return MYBOLD_BLACK;
241 } else if (attr.getForeColor().equals(jexer.bits.Color.RED)) {
242 return MYBOLD_RED;
243 } else if (attr.getForeColor().equals(jexer.bits.Color.BLUE)) {
244 return MYBOLD_BLUE;
245 } else if (attr.getForeColor().equals(jexer.bits.Color.GREEN)) {
246 return MYBOLD_GREEN;
247 } else if (attr.getForeColor().equals(jexer.bits.Color.YELLOW)) {
248 return MYBOLD_YELLOW;
249 } else if (attr.getForeColor().equals(jexer.bits.Color.CYAN)) {
250 return MYBOLD_CYAN;
251 } else if (attr.getForeColor().equals(jexer.bits.Color.MAGENTA)) {
252 return MYBOLD_MAGENTA;
253 } else if (attr.getForeColor().equals(jexer.bits.Color.WHITE)) {
254 return MYBOLD_WHITE;
255 }
256 } else {
257 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
258 return MYBLACK;
259 } else if (attr.getForeColor().equals(jexer.bits.Color.RED)) {
260 return MYRED;
261 } else if (attr.getForeColor().equals(jexer.bits.Color.BLUE)) {
262 return MYBLUE;
263 } else if (attr.getForeColor().equals(jexer.bits.Color.GREEN)) {
264 return MYGREEN;
265 } else if (attr.getForeColor().equals(jexer.bits.Color.YELLOW)) {
266 return MYYELLOW;
267 } else if (attr.getForeColor().equals(jexer.bits.Color.CYAN)) {
268 return MYCYAN;
269 } else if (attr.getForeColor().equals(jexer.bits.Color.MAGENTA)) {
270 return MYMAGENTA;
271 } else if (attr.getForeColor().equals(jexer.bits.Color.WHITE)) {
272 return MYWHITE;
273 }
274 }
c8165631
KL
275 throw new IllegalArgumentException("Invalid color: " +
276 attr.getForeColor().getValue());
84614868
KL
277 }
278
279 /**
a4406f4e 280 * Convert a CellAttributes background color to an Swing Color.
84614868
KL
281 *
282 * @param attr the text attributes
a4406f4e 283 * @return the Swing Color
84614868
KL
284 */
285 private Color attrToBackgroundColor(final CellAttributes attr) {
84614868
KL
286 if (attr.getBackColor().equals(jexer.bits.Color.BLACK)) {
287 return MYBLACK;
288 } else if (attr.getBackColor().equals(jexer.bits.Color.RED)) {
289 return MYRED;
290 } else if (attr.getBackColor().equals(jexer.bits.Color.BLUE)) {
291 return MYBLUE;
292 } else if (attr.getBackColor().equals(jexer.bits.Color.GREEN)) {
293 return MYGREEN;
294 } else if (attr.getBackColor().equals(jexer.bits.Color.YELLOW)) {
295 return MYYELLOW;
296 } else if (attr.getBackColor().equals(jexer.bits.Color.CYAN)) {
297 return MYCYAN;
298 } else if (attr.getBackColor().equals(jexer.bits.Color.MAGENTA)) {
299 return MYMAGENTA;
300 } else if (attr.getBackColor().equals(jexer.bits.Color.WHITE)) {
301 return MYWHITE;
302 }
c8165631
KL
303 throw new IllegalArgumentException("Invalid color: " +
304 attr.getBackColor().getValue());
84614868
KL
305 }
306
1ac2ccb1
KL
307 /**
308 * Public constructor.
84614868
KL
309 *
310 * @param screen the Screen that Backend talks to
1ac2ccb1 311 */
a4406f4e 312 public SwingFrame(final SwingScreen screen) {
84614868
KL
313 this.screen = screen;
314 setDOSColors();
315
b5f2a6db 316 // Figure out my cursor style
c8165631
KL
317 String cursorStyleString = System.getProperty(
318 "jexer.Swing.cursorStyle", "underline").toLowerCase();
b5f2a6db
KL
319
320 if (cursorStyleString.equals("underline")) {
321 cursorStyle = CursorStyle.UNDERLINE;
322 } else if (cursorStyleString.equals("outline")) {
323 cursorStyle = CursorStyle.OUTLINE;
324 } else if (cursorStyleString.equals("block")) {
325 cursorStyle = CursorStyle.BLOCK;
326 }
327
e685a47d
KL
328 if (System.getProperty("jexer.Swing.tripleBuffer").
329 equals("false")) {
330
331 SwingScreen.tripleBuffer = false;
332 }
333
1ac2ccb1 334 setTitle("Jexer Application");
aed33687 335 setBackground(Color.black);
84614868
KL
336
337 try {
30bd4abd 338 // Always try to use Terminus, the one decent font.
c8165631
KL
339 ClassLoader loader = Thread.currentThread().
340 getContextClassLoader();
84614868
KL
341 InputStream in = loader.getResourceAsStream(FONTFILE);
342 Font terminusRoot = Font.createFont(Font.TRUETYPE_FONT, in);
55d2b2c2 343 Font terminus = terminusRoot.deriveFont(Font.PLAIN, 20);
84614868 344 setFont(terminus);
55d2b2c2 345 gotTerminus = true;
84614868
KL
346 } catch (Exception e) {
347 e.printStackTrace();
348 // setFont(new Font("Liberation Mono", Font.PLAIN, 24));
349 setFont(new Font(Font.MONOSPACED, Font.PLAIN, 24));
350 }
aed33687 351 pack();
30bd4abd
KL
352
353 // Kill the X11 cursor
354 // Transparent 16 x 16 pixel cursor image.
355 BufferedImage cursorImg = new BufferedImage(16, 16,
356 BufferedImage.TYPE_INT_ARGB);
30bd4abd
KL
357 // Create a new blank cursor.
358 Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
359 cursorImg, new Point(0, 0), "blank cursor");
360 setCursor(blankCursor);
091d8a06
KL
361
362 // Be capable of seeing Tab / Shift-Tab
363 setFocusTraversalKeysEnabled(false);
364
365 // Save the text cell width/height
bd8d51fa 366 getFontDimensions();
e3dfbd23 367
c8165631
KL
368 // Cache glyphs as they are rendered
369 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
370 glyphCache = new HashMap<Cell, BufferedImage>();
371
1d14ffab
KL
372 // Setup triple-buffering
373 if (SwingScreen.tripleBuffer) {
e3dfbd23 374 setIgnoreRepaint(true);
1d14ffab 375 createBufferStrategy(3);
e3dfbd23
KL
376 bufferStrategy = getBufferStrategy();
377 }
1ac2ccb1
KL
378 }
379
380 /**
bd8d51fa 381 * Figure out my font dimensions.
1ac2ccb1 382 */
bd8d51fa 383 private void getFontDimensions() {
84614868
KL
384 Graphics gr = getGraphics();
385 FontMetrics fm = gr.getFontMetrics();
386 maxDescent = fm.getMaxDescent();
387 Rectangle2D bounds = fm.getMaxCharBounds(gr);
388 int leading = fm.getLeading();
389 textWidth = (int)Math.round(bounds.getWidth());
55d2b2c2
KL
390 // textHeight = (int)Math.round(bounds.getHeight()) - maxDescent;
391
392 // This produces the same number, but works better for ugly
84614868
KL
393 // monospace.
394 textHeight = fm.getMaxAscent() + maxDescent - leading;
847a4bc5 395
55d2b2c2
KL
396 if (gotTerminus == true) {
397 textHeight++;
398 }
399
847a4bc5
KL
400 if (System.getProperty("os.name").startsWith("Windows")) {
401 textAdjustY = -1;
402 textAdjustX = 0;
403 }
55d2b2c2
KL
404 if (System.getProperty("os.name").startsWith("Mac")) {
405 textAdjustY = -1;
406 textAdjustX = 0;
407 }
bd8d51fa 408 }
84614868 409
bd8d51fa
KL
410 /**
411 * Resize to font dimensions.
412 */
413 public void resizeToScreen() {
84614868
KL
414 // Figure out the thickness of borders and use that to set the
415 // final size.
416 Insets insets = getInsets();
417 left = insets.left;
418 top = insets.top;
419
420 setSize(textWidth * screen.width + insets.left + insets.right,
421 textHeight * screen.height + insets.top + insets.bottom);
1ac2ccb1
KL
422 }
423
30bd4abd
KL
424 /**
425 * Update redraws the whole screen.
426 *
a4406f4e 427 * @param gr the Swing Graphics context
30bd4abd
KL
428 */
429 @Override
430 public void update(final Graphics gr) {
431 // The default update clears the area. Don't do that, instead
432 // just paint it directly.
433 paint(gr);
434 }
435
c8165631
KL
436 /**
437 * Draw one glyph to the screen.
438 *
439 * @param gr the Swing Graphics context
440 * @param cell the Cell to draw
441 * @param xPixel the x-coordinate to render to. 0 means the
442 * left-most pixel column.
443 * @param yPixel the y-coordinate to render to. 0 means the top-most
444 * pixel row.
445 */
446 private void drawGlyph(final Graphics gr, final Cell cell,
447 final int xPixel, final int yPixel) {
448
449 BufferedImage image = null;
450 if (cell.isBlink() && !cursorBlinkVisible) {
451 image = glyphCacheBlink.get(cell);
452 } else {
453 image = glyphCache.get(cell);
454 }
455 if (image != null) {
456 gr.drawImage(image, xPixel, yPixel, this);
457 return;
458 }
459
460 // Generate glyph and draw it.
e685a47d
KL
461 Graphics2D gr2 = null;
462 int gr2x = xPixel;
463 int gr2y = yPixel;
464 if (tripleBuffer) {
465 image = new BufferedImage(textWidth, textHeight,
466 BufferedImage.TYPE_INT_ARGB);
467 gr2 = image.createGraphics();
468 gr2.setFont(getFont());
469 gr2x = 0;
470 gr2y = 0;
471 } else {
472 gr2 = (Graphics2D) gr;
473 }
c8165631
KL
474
475 Cell cellColor = new Cell();
476 cellColor.setTo(cell);
477
478 // Check for reverse
479 if (cell.isReverse()) {
480 cellColor.setForeColor(cell.getBackColor());
481 cellColor.setBackColor(cell.getForeColor());
482 }
483
484 // Draw the background rectangle, then the foreground character.
485 gr2.setColor(attrToBackgroundColor(cellColor));
e685a47d 486 gr2.fillRect(gr2x, gr2y, textWidth, textHeight);
c8165631
KL
487
488 // Handle blink and underline
489 if (!cell.isBlink()
490 || (cell.isBlink() && cursorBlinkVisible)
491 ) {
492 gr2.setColor(attrToForegroundColor(cellColor));
493 char [] chars = new char[1];
494 chars[0] = cell.getChar();
e685a47d
KL
495 gr2.drawChars(chars, 0, 1, gr2x + textAdjustX,
496 gr2y + textHeight - maxDescent + textAdjustY);
c8165631
KL
497
498 if (cell.isUnderline()) {
e685a47d 499 gr2.fillRect(gr2x, gr2y + textHeight - 2, textWidth, 2);
c8165631
KL
500 }
501 }
c8165631 502
e685a47d
KL
503 if (tripleBuffer) {
504 gr2.dispose();
505
506 // We need a new key that will not be mutated by
507 // invertCell().
508 Cell key = new Cell();
509 key.setTo(cell);
510 if (cell.isBlink() && !cursorBlinkVisible) {
511 glyphCacheBlink.put(key, image);
512 } else {
513 glyphCache.put(key, image);
514 }
515
516 gr.drawImage(image, xPixel, yPixel, this);
c8165631
KL
517 }
518
c8165631
KL
519 }
520
521 /**
522 * Check if the cursor is visible, and if so draw it.
523 *
524 * @param gr the Swing Graphics context
525 */
526 private void drawCursor(final Graphics gr) {
527
528 if (cursorVisible
529 && (cursorY <= screen.height - 1)
530 && (cursorX <= screen.width - 1)
531 && cursorBlinkVisible
532 ) {
533 int xPixel = cursorX * textWidth + left;
534 int yPixel = cursorY * textHeight + top;
535 Cell lCell = screen.logical[cursorX][cursorY];
536 gr.setColor(attrToForegroundColor(lCell));
537 switch (cursorStyle) {
538 default:
539 // Fall through...
540 case UNDERLINE:
541 gr.fillRect(xPixel, yPixel + textHeight - 2, textWidth, 2);
542 break;
543 case BLOCK:
544 gr.fillRect(xPixel, yPixel, textWidth, textHeight);
545 break;
546 case OUTLINE:
547 gr.drawRect(xPixel, yPixel, textWidth - 1, textHeight - 1);
548 break;
549 }
550 }
551 }
552
1ac2ccb1
KL
553 /**
554 * Paint redraws the whole screen.
555 *
a4406f4e 556 * @param gr the Swing Graphics context
1ac2ccb1
KL
557 */
558 @Override
84614868 559 public void paint(final Graphics gr) {
87a17f3c
KL
560 // Do nothing until the screen reference has been set.
561 if (screen == null) {
562 return;
563 }
564 if (screen.frame == null) {
565 return;
566 }
567
b5f2a6db
KL
568 // See if it is time to flip the blink time.
569 long nowTime = (new Date()).getTime();
570 if (nowTime > blinkMillis + lastBlinkTime) {
571 lastBlinkTime = nowTime;
572 cursorBlinkVisible = !cursorBlinkVisible;
573 }
574
87a17f3c
KL
575 int xCellMin = 0;
576 int xCellMax = screen.width;
577 int yCellMin = 0;
578 int yCellMax = screen.height;
579
30bd4abd 580 Rectangle bounds = gr.getClipBounds();
87a17f3c
KL
581 if (bounds != null) {
582 // Only update what is in the bounds
583 xCellMin = screen.textColumn(bounds.x);
bd8d51fa 584 xCellMax = screen.textColumn(bounds.x + bounds.width);
87a17f3c
KL
585 if (xCellMax > screen.width) {
586 xCellMax = screen.width;
587 }
588 if (xCellMin >= xCellMax) {
589 xCellMin = xCellMax - 2;
590 }
591 if (xCellMin < 0) {
592 xCellMin = 0;
593 }
594 yCellMin = screen.textRow(bounds.y);
bd8d51fa 595 yCellMax = screen.textRow(bounds.y + bounds.height);
87a17f3c
KL
596 if (yCellMax > screen.height) {
597 yCellMax = screen.height;
598 }
599 if (yCellMin >= yCellMax) {
600 yCellMin = yCellMax - 2;
601 }
602 if (yCellMin < 0) {
603 yCellMin = 0;
604 }
bd8d51fa
KL
605 } else {
606 // We need a total repaint
607 reallyCleared = true;
87a17f3c 608 }
1ac2ccb1 609
87a17f3c
KL
610 // Prevent updates to the screen's data from the TApplication
611 // threads.
612 synchronized (screen) {
613 /*
614 System.err.printf("bounds %s X %d %d Y %d %d\n",
615 bounds, xCellMin, xCellMax, yCellMin, yCellMax);
616 */
617
618 for (int y = yCellMin; y < yCellMax; y++) {
619 for (int x = xCellMin; x < xCellMax; x++) {
620
621 int xPixel = x * textWidth + left;
622 int yPixel = y * textHeight + top;
623
624 Cell lCell = screen.logical[x][y];
625 Cell pCell = screen.physical[x][y];
626
55b4f29b
KL
627 if (!lCell.equals(pCell)
628 || lCell.isBlink()
629 || reallyCleared) {
e3dfbd23 630
c8165631 631 drawGlyph(gr, lCell, xPixel, yPixel);
87a17f3c
KL
632
633 // Physical is always updated
634 physical[x][y].setTo(lCell);
30bd4abd
KL
635 }
636 }
87a17f3c 637 }
c8165631 638 drawCursor(gr);
30bd4abd 639
87a17f3c
KL
640 dirty = false;
641 reallyCleared = false;
642 } // synchronized (screen)
1ac2ccb1 643 }
bd8d51fa 644
a4406f4e 645 } // class SwingFrame
1ac2ccb1
KL
646
647 /**
a4406f4e 648 * The raw Swing JFrame. Note package private access.
1ac2ccb1 649 */
a4406f4e 650 SwingFrame frame;
1ac2ccb1 651
e3dfbd23
KL
652 /**
653 * Restore terminal to normal state.
654 */
655 public void shutdown() {
656 frame.dispose();
657 }
658
1ac2ccb1
KL
659 /**
660 * Public constructor.
661 */
a4406f4e 662 public SwingScreen() {
aed33687
KL
663 try {
664 SwingUtilities.invokeAndWait(new Runnable() {
665 public void run() {
a4406f4e
KL
666 SwingScreen.this.frame = new SwingFrame(SwingScreen.this);
667 SwingScreen.this.sessionInfo =
668 new SwingSessionInfo(SwingScreen.this.frame,
bd8d51fa
KL
669 frame.textWidth,
670 frame.textHeight);
671
a4406f4e 672 SwingScreen.this.setDimensions(sessionInfo.getWindowWidth(),
bd8d51fa
KL
673 sessionInfo.getWindowHeight());
674
a4406f4e
KL
675 SwingScreen.this.frame.resizeToScreen();
676 SwingScreen.this.frame.setVisible(true);
aed33687 677 }
329fd62e 678 });
aed33687
KL
679 } catch (Exception e) {
680 e.printStackTrace();
681 }
1ac2ccb1
KL
682 }
683
bd8d51fa
KL
684 /**
685 * The sessionInfo.
686 */
a4406f4e 687 private SwingSessionInfo sessionInfo;
bd8d51fa 688
30bd4abd 689 /**
a4406f4e 690 * Create the SwingSessionInfo. Note package private access.
30bd4abd
KL
691 *
692 * @return the sessionInfo
693 */
a4406f4e 694 SwingSessionInfo getSessionInfo() {
30bd4abd
KL
695 return sessionInfo;
696 }
697
1ac2ccb1
KL
698 /**
699 * Push the logical screen to the physical device.
700 */
701 @Override
702 public void flushPhysical() {
87a17f3c 703
1d14ffab
KL
704 /*
705 System.err.printf("flushPhysical(): reallyCleared %s dirty %s\n",
706 reallyCleared, dirty);
707 */
708
709 // If reallyCleared is set, we have to draw everything.
710 if ((frame.bufferStrategy != null) && (reallyCleared == true)) {
711 // Triple-buffering: we have to redraw everything on this thread.
712 Graphics gr = frame.bufferStrategy.getDrawGraphics();
713 frame.paint(gr);
714 gr.dispose();
715 frame.bufferStrategy.show();
716 // sync() doesn't seem to help the tearing for me.
717 // Toolkit.getDefaultToolkit().sync();
718 return;
719 } else if ((frame.bufferStrategy == null) && (reallyCleared == true)) {
720 // Repaint everything on the Swing thread.
721 frame.repaint();
87a17f3c
KL
722 return;
723 }
724
725 // Do nothing if nothing happened.
726 if (!dirty) {
727 return;
728 }
729
c8165631
KL
730 if (frame.bufferStrategy != null) {
731 // See if it is time to flip the blink time.
732 long nowTime = (new Date()).getTime();
733 if (nowTime > frame.blinkMillis + frame.lastBlinkTime) {
734 frame.lastBlinkTime = nowTime;
735 frame.cursorBlinkVisible = !frame.cursorBlinkVisible;
736 }
737
738 Graphics gr = frame.bufferStrategy.getDrawGraphics();
739
740 synchronized (this) {
741 for (int y = 0; y < height; y++) {
742 for (int x = 0; x < width; x++) {
743 Cell lCell = logical[x][y];
744 Cell pCell = physical[x][y];
745
746 int xPixel = x * frame.textWidth + frame.left;
747 int yPixel = y * frame.textHeight + frame.top;
748
749 if (!lCell.equals(pCell)
750 || ((x == cursorX)
751 && (y == cursorY)
752 && cursorVisible)
753 || (lCell.isBlink())
754 ) {
755 frame.drawGlyph(gr, lCell, xPixel, yPixel);
756 physical[x][y].setTo(lCell);
757 }
758 }
759 }
760 frame.drawCursor(gr);
761 } // synchronized (this)
762
763 gr.dispose();
764 frame.bufferStrategy.show();
765 // sync() doesn't seem to help the tearing for me.
766 // Toolkit.getDefaultToolkit().sync();
767 return;
768 }
769
770 // Swing thread version: request a repaint, but limit it to the area
771 // that has changed.
87a17f3c 772
30bd4abd
KL
773 // Find the minimum-size damaged region.
774 int xMin = frame.getWidth();
775 int xMax = 0;
776 int yMin = frame.getHeight();
777 int yMax = 0;
30bd4abd 778
87a17f3c
KL
779 synchronized (this) {
780 for (int y = 0; y < height; y++) {
781 for (int x = 0; x < width; x++) {
782 Cell lCell = logical[x][y];
783 Cell pCell = physical[x][y];
784
785 int xPixel = x * frame.textWidth + frame.left;
786 int yPixel = y * frame.textHeight + frame.top;
787
788 if (!lCell.equals(pCell)
789 || ((x == cursorX)
790 && (y == cursorY)
791 && cursorVisible)
55b4f29b 792 || lCell.isBlink()
87a17f3c
KL
793 ) {
794 if (xPixel < xMin) {
795 xMin = xPixel;
796 }
797 if (xPixel + frame.textWidth > xMax) {
798 xMax = xPixel + frame.textWidth;
799 }
800 if (yPixel < yMin) {
801 yMin = yPixel;
802 }
803 if (yPixel + frame.textHeight > yMax) {
804 yMax = yPixel + frame.textHeight;
805 }
30bd4abd
KL
806 }
807 }
808 }
809 }
87a17f3c
KL
810 if (xMin + frame.textWidth >= xMax) {
811 xMax += frame.textWidth;
812 }
813 if (yMin + frame.textHeight >= yMax) {
814 yMax += frame.textHeight;
815 }
30bd4abd 816
87a17f3c 817 // Repaint the desired area
1d14ffab
KL
818 /*
819 System.err.printf("REPAINT X %d %d Y %d %d\n", xMin, xMax,
820 yMin, yMax);
821 */
822 if (frame.bufferStrategy != null) {
c8165631
KL
823 // This path should never be taken, but is left here for
824 // completeness.
e3dfbd23
KL
825 Graphics gr = frame.bufferStrategy.getDrawGraphics();
826 Rectangle bounds = new Rectangle(xMin, yMin, xMax - xMin,
827 yMax - yMin);
828 gr.setClip(bounds);
829 frame.paint(gr);
830 gr.dispose();
831 frame.bufferStrategy.show();
1d14ffab
KL
832 // sync() doesn't seem to help the tearing for me.
833 // Toolkit.getDefaultToolkit().sync();
e3dfbd23 834 } else {
c8165631 835 // Repaint on the Swing thread.
e3dfbd23
KL
836 frame.repaint(xMin, yMin, xMax - xMin, yMax - yMin);
837 }
1ac2ccb1 838 }
30bd4abd
KL
839
840 /**
841 * Put the cursor at (x,y).
842 *
843 * @param visible if true, the cursor should be visible
844 * @param x column coordinate to put the cursor on
845 * @param y row coordinate to put the cursor on
846 */
847 @Override
848 public void putCursor(final boolean visible, final int x, final int y) {
b5f2a6db
KL
849
850 if ((visible == cursorVisible) && ((x == cursorX) && (y == cursorY))) {
851 // See if it is time to flip the blink time.
852 long nowTime = (new Date()).getTime();
853 if (nowTime < frame.blinkMillis + frame.lastBlinkTime) {
854 // Nothing has changed, so don't do anything.
855 return;
856 }
857 }
858
859 if (cursorVisible
30bd4abd
KL
860 && (cursorY <= height - 1)
861 && (cursorX <= width - 1)
862 ) {
863 // Make the current cursor position dirty
87a17f3c 864 if (physical[cursorX][cursorY].getChar() == 'Q') {
30bd4abd
KL
865 physical[cursorX][cursorY].setChar('X');
866 } else {
87a17f3c 867 physical[cursorX][cursorY].setChar('Q');
30bd4abd
KL
868 }
869 }
870
871 super.putCursor(visible, x, y);
872 }
873
87a17f3c
KL
874 /**
875 * Convert pixel column position to text cell column position.
876 *
877 * @param x pixel column position
878 * @return text cell column position
879 */
880 public int textColumn(final int x) {
881 return ((x - frame.left) / frame.textWidth);
882 }
883
884 /**
885 * Convert pixel row position to text cell row position.
886 *
887 * @param y pixel row position
888 * @return text cell row position
889 */
890 public int textRow(final int y) {
891 return ((y - frame.top) / frame.textHeight);
892 }
893
55d2b2c2
KL
894 /**
895 * Set the window title.
896 *
897 * @param title the new title
898 */
899 public void setTitle(final String title) {
900 frame.setTitle(title);
901 }
902
1ac2ccb1 903}