misc fixes
[nikiroo-utils.git] / src / jexer / backend / SwingTerminal.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2019 Kevin Lamonte
7 *
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:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
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.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer.backend;
30
31 import java.awt.BorderLayout;
32 import java.awt.Color;
33 import java.awt.Font;
34 import java.awt.FontMetrics;
35 import java.awt.Graphics2D;
36 import java.awt.Graphics;
37 import java.awt.Insets;
38 import java.awt.Rectangle;
39 import java.awt.Toolkit;
40 import java.awt.event.ComponentEvent;
41 import java.awt.event.ComponentListener;
42 import java.awt.event.KeyEvent;
43 import java.awt.event.KeyListener;
44 import java.awt.event.MouseEvent;
45 import java.awt.event.MouseListener;
46 import java.awt.event.MouseMotionListener;
47 import java.awt.event.MouseWheelEvent;
48 import java.awt.event.MouseWheelListener;
49 import java.awt.event.WindowEvent;
50 import java.awt.event.WindowListener;
51 import java.awt.geom.Rectangle2D;
52 import java.awt.image.BufferedImage;
53 import java.io.InputStream;
54 import java.util.HashMap;
55 import java.util.LinkedList;
56 import java.util.List;
57 import java.util.Map;
58 import javax.swing.JComponent;
59 import javax.swing.JFrame;
60 import javax.swing.ImageIcon;
61 import javax.swing.SwingUtilities;
62
63 import jexer.TKeypress;
64 import jexer.bits.Cell;
65 import jexer.bits.CellAttributes;
66 import jexer.event.TCommandEvent;
67 import jexer.event.TInputEvent;
68 import jexer.event.TKeypressEvent;
69 import jexer.event.TMouseEvent;
70 import jexer.event.TResizeEvent;
71 import static jexer.TCommand.*;
72 import static jexer.TKeypress.*;
73
74 /**
75 * This Screen backend reads keystrokes and mouse events and draws to either
76 * a Java Swing JFrame (potentially triple-buffered) or a JComponent.
77 *
78 * This class is a bit of an inversion of typical GUI classes. It performs
79 * all of the drawing logic from SwingTerminal (which is not a Swing class),
80 * and uses a SwingComponent wrapper class to call the JFrame or JComponent
81 * methods.
82 */
83 public class SwingTerminal extends LogicalScreen
84 implements TerminalReader,
85 ComponentListener, KeyListener,
86 MouseListener, MouseMotionListener,
87 MouseWheelListener, WindowListener {
88
89 // ------------------------------------------------------------------------
90 // Constants --------------------------------------------------------------
91 // ------------------------------------------------------------------------
92
93 /**
94 * The icon image location.
95 */
96 private static final String ICONFILE = "jexer_logo_128.png";
97
98 /**
99 * The terminus font resource filename.
100 */
101 private static final String FONTFILE = "terminus-ttf-4.39/TerminusTTF-Bold-4.39.ttf";
102
103 /**
104 * Cursor style to draw.
105 */
106 public enum CursorStyle {
107 /**
108 * Use an underscore for the cursor.
109 */
110 UNDERLINE,
111
112 /**
113 * Use a solid block for the cursor.
114 */
115 BLOCK,
116
117 /**
118 * Use an outlined block for the cursor.
119 */
120 OUTLINE
121 }
122
123 // ------------------------------------------------------------------------
124 // Variables --------------------------------------------------------------
125 // ------------------------------------------------------------------------
126
127 // Colors to map DOS colors to AWT colors.
128 private static Color MYBLACK;
129 private static Color MYRED;
130 private static Color MYGREEN;
131 private static Color MYYELLOW;
132 private static Color MYBLUE;
133 private static Color MYMAGENTA;
134 private static Color MYCYAN;
135 private static Color MYWHITE;
136 private static Color MYBOLD_BLACK;
137 private static Color MYBOLD_RED;
138 private static Color MYBOLD_GREEN;
139 private static Color MYBOLD_YELLOW;
140 private static Color MYBOLD_BLUE;
141 private static Color MYBOLD_MAGENTA;
142 private static Color MYBOLD_CYAN;
143 private static Color MYBOLD_WHITE;
144
145 /**
146 * When true, all the MYBLACK, MYRED, etc. colors are set.
147 */
148 private static boolean dosColors = false;
149
150 /**
151 * The Swing component or frame to draw to.
152 */
153 private SwingComponent swing;
154
155 /**
156 * A cache of previously-rendered glyphs for blinking text, when it is
157 * not visible.
158 */
159 private Map<Cell, BufferedImage> glyphCacheBlink;
160
161 /**
162 * A cache of previously-rendered glyphs for non-blinking, or
163 * blinking-and-visible, text.
164 */
165 private Map<Cell, BufferedImage> glyphCache;
166
167 /**
168 * If true, we were successful at getting the font dimensions.
169 */
170 private boolean gotFontDimensions = false;
171
172 /**
173 * The currently selected font.
174 */
175 private Font font = null;
176
177 /**
178 * The currently selected font size in points.
179 */
180 private int fontSize = 16;
181
182 /**
183 * Width of a character cell in pixels.
184 */
185 private int textWidth = 1;
186
187 /**
188 * Height of a character cell in pixels.
189 */
190 private int textHeight = 1;
191
192 /**
193 * Width of a character cell in pixels, as reported by font.
194 */
195 private int fontTextWidth = 1;
196
197 /**
198 * Height of a character cell in pixels, as reported by font.
199 */
200 private int fontTextHeight = 1;
201
202 /**
203 * Descent of a character cell in pixels.
204 */
205 private int maxDescent = 0;
206
207 /**
208 * System-dependent Y adjustment for text in the character cell.
209 */
210 private int textAdjustY = 0;
211
212 /**
213 * System-dependent X adjustment for text in the character cell.
214 */
215 private int textAdjustX = 0;
216
217 /**
218 * System-dependent height adjustment for text in the character cell.
219 */
220 private int textAdjustHeight = 0;
221
222 /**
223 * System-dependent width adjustment for text in the character cell.
224 */
225 private int textAdjustWidth = 0;
226
227 /**
228 * Top pixel absolute location.
229 */
230 private int top = 30;
231
232 /**
233 * Left pixel absolute location.
234 */
235 private int left = 30;
236
237 /**
238 * The cursor style to draw.
239 */
240 private CursorStyle cursorStyle = CursorStyle.UNDERLINE;
241
242 /**
243 * The number of millis to wait before switching the blink from visible
244 * to invisible. Set to 0 or negative to disable blinking.
245 */
246 private long blinkMillis = 500;
247
248 /**
249 * If true, the cursor should be visible right now based on the blink
250 * time.
251 */
252 private boolean cursorBlinkVisible = true;
253
254 /**
255 * The time that the blink last flipped from visible to invisible or
256 * from invisible to visible.
257 */
258 private long lastBlinkTime = 0;
259
260 /**
261 * The session information.
262 */
263 private SwingSessionInfo sessionInfo;
264
265 /**
266 * The listening object that run() wakes up on new input.
267 */
268 private Object listener;
269
270 /**
271 * The event queue, filled up by a thread reading on input.
272 */
273 private List<TInputEvent> eventQueue;
274
275 /**
276 * The last reported mouse X position.
277 */
278 private int oldMouseX = -1;
279
280 /**
281 * The last reported mouse Y position.
282 */
283 private int oldMouseY = -1;
284
285 /**
286 * true if mouse1 was down. Used to report mouse1 on the release event.
287 */
288 private boolean mouse1 = false;
289
290 /**
291 * true if mouse2 was down. Used to report mouse2 on the release event.
292 */
293 private boolean mouse2 = false;
294
295 /**
296 * true if mouse3 was down. Used to report mouse3 on the release event.
297 */
298 private boolean mouse3 = false;
299
300 // ------------------------------------------------------------------------
301 // Constructors -----------------------------------------------------------
302 // ------------------------------------------------------------------------
303
304 /**
305 * Public constructor creates a new JFrame to render to.
306 *
307 * @param windowWidth the number of text columns to start with
308 * @param windowHeight the number of text rows to start with
309 * @param fontSize the size in points. Good values to pick are: 16, 20,
310 * 22, and 24.
311 * @param listener the object this backend needs to wake up when new
312 * input comes in
313 */
314 public SwingTerminal(final int windowWidth, final int windowHeight,
315 final int fontSize, final Object listener) {
316
317 this.fontSize = fontSize;
318
319 setDOSColors();
320 reloadOptions();
321
322 try {
323 SwingUtilities.invokeAndWait(new Runnable() {
324 public void run() {
325
326 JFrame frame = new JFrame() {
327
328 /**
329 * Serializable version.
330 */
331 private static final long serialVersionUID = 1;
332
333 /**
334 * The code that performs the actual drawing.
335 */
336 public SwingTerminal screen = null;
337
338 /*
339 * Anonymous class initializer saves the screen
340 * reference, so that paint() and the like call out
341 * to SwingTerminal.
342 */
343 {
344 this.screen = SwingTerminal.this;
345 }
346
347 /**
348 * Update redraws the whole screen.
349 *
350 * @param gr the Swing Graphics context
351 */
352 @Override
353 public void update(final Graphics gr) {
354 // The default update clears the area. Don't do
355 // that, instead just paint it directly.
356 paint(gr);
357 }
358
359 /**
360 * Paint redraws the whole screen.
361 *
362 * @param gr the Swing Graphics context
363 */
364 @Override
365 public void paint(final Graphics gr) {
366 if (screen != null) {
367 screen.paint(gr);
368 }
369 }
370 };
371
372 // Set icon
373 ClassLoader loader = Thread.currentThread().
374 getContextClassLoader();
375 frame.setIconImage((new ImageIcon(loader.
376 getResource(ICONFILE))).getImage());
377
378 // Get the Swing component
379 SwingTerminal.this.swing = new SwingComponent(frame);
380
381 // Hang onto top and left for drawing.
382 Insets insets = SwingTerminal.this.swing.getInsets();
383 SwingTerminal.this.left = insets.left;
384 SwingTerminal.this.top = insets.top;
385
386 // Load the font so that we can set sessionInfo.
387 setDefaultFont();
388
389 // Get the default cols x rows and set component size
390 // accordingly.
391 SwingTerminal.this.sessionInfo =
392 new SwingSessionInfo(SwingTerminal.this.swing,
393 SwingTerminal.this.textWidth,
394 SwingTerminal.this.textHeight,
395 windowWidth, windowHeight);
396
397 SwingTerminal.this.setDimensions(sessionInfo.
398 getWindowWidth(), sessionInfo.getWindowHeight());
399
400 SwingTerminal.this.resizeToScreen();
401 SwingTerminal.this.swing.setVisible(true);
402 }
403 });
404 } catch (java.lang.reflect.InvocationTargetException e) {
405 e.printStackTrace();
406 } catch (InterruptedException e) {
407 e.printStackTrace();
408 }
409
410 this.listener = listener;
411 mouse1 = false;
412 mouse2 = false;
413 mouse3 = false;
414 eventQueue = new LinkedList<TInputEvent>();
415
416 // Add listeners to Swing.
417 swing.addKeyListener(this);
418 swing.addWindowListener(this);
419 swing.addComponentListener(this);
420 swing.addMouseListener(this);
421 swing.addMouseMotionListener(this);
422 swing.addMouseWheelListener(this);
423 }
424
425 /**
426 * Public constructor renders to an existing JComponent.
427 *
428 * @param component the Swing component to render to
429 * @param windowWidth the number of text columns to start with
430 * @param windowHeight the number of text rows to start with
431 * @param fontSize the size in points. Good values to pick are: 16, 20,
432 * 22, and 24.
433 * @param listener the object this backend needs to wake up when new
434 * input comes in
435 */
436 public SwingTerminal(final JComponent component, final int windowWidth,
437 final int windowHeight, final int fontSize, final Object listener) {
438
439 this.fontSize = fontSize;
440
441 setDOSColors();
442 reloadOptions();
443
444 try {
445 SwingUtilities.invokeAndWait(new Runnable() {
446 public void run() {
447
448 JComponent newComponent = new JComponent() {
449
450 /**
451 * Serializable version.
452 */
453 private static final long serialVersionUID = 1;
454
455 /**
456 * The code that performs the actual drawing.
457 */
458 public SwingTerminal screen = null;
459
460 /*
461 * Anonymous class initializer saves the screen
462 * reference, so that paint() and the like call out
463 * to SwingTerminal.
464 */
465 {
466 this.screen = SwingTerminal.this;
467 }
468
469 /**
470 * Update redraws the whole screen.
471 *
472 * @param gr the Swing Graphics context
473 */
474 @Override
475 public void update(final Graphics gr) {
476 // The default update clears the area. Don't do
477 // that, instead just paint it directly.
478 paint(gr);
479 }
480
481 /**
482 * Paint redraws the whole screen.
483 *
484 * @param gr the Swing Graphics context
485 */
486 @Override
487 public void paint(final Graphics gr) {
488 if (screen != null) {
489 screen.paint(gr);
490 }
491 }
492 };
493 component.setLayout(new BorderLayout());
494 component.add(newComponent);
495
496 // Allow key events to be received
497 component.setFocusable(true);
498
499 // Get the Swing component
500 SwingTerminal.this.swing = new SwingComponent(component);
501
502 // Hang onto top and left for drawing.
503 Insets insets = SwingTerminal.this.swing.getInsets();
504 SwingTerminal.this.left = insets.left;
505 SwingTerminal.this.top = insets.top;
506
507 // Load the font so that we can set sessionInfo.
508 setDefaultFont();
509
510 // Get the default cols x rows and set component size
511 // accordingly.
512 SwingTerminal.this.sessionInfo =
513 new SwingSessionInfo(SwingTerminal.this.swing,
514 SwingTerminal.this.textWidth,
515 SwingTerminal.this.textHeight);
516 }
517 });
518 } catch (java.lang.reflect.InvocationTargetException e) {
519 e.printStackTrace();
520 } catch (InterruptedException e) {
521 e.printStackTrace();
522 }
523
524 this.listener = listener;
525 mouse1 = false;
526 mouse2 = false;
527 mouse3 = false;
528 eventQueue = new LinkedList<TInputEvent>();
529
530 // Add listeners to Swing.
531 swing.addKeyListener(this);
532 swing.addWindowListener(this);
533 swing.addComponentListener(this);
534 swing.addMouseListener(this);
535 swing.addMouseMotionListener(this);
536 swing.addMouseWheelListener(this);
537 }
538
539 // ------------------------------------------------------------------------
540 // LogicalScreen ----------------------------------------------------------
541 // ------------------------------------------------------------------------
542
543 /**
544 * Set the window title.
545 *
546 * @param title the new title
547 */
548 @Override
549 public void setTitle(final String title) {
550 swing.setTitle(title);
551 }
552
553 /**
554 * Push the logical screen to the physical device.
555 */
556 @Override
557 public void flushPhysical() {
558 // See if it is time to flip the blink time.
559 long nowTime = System.currentTimeMillis();
560 if (nowTime >= blinkMillis + lastBlinkTime) {
561 lastBlinkTime = nowTime;
562 cursorBlinkVisible = !cursorBlinkVisible;
563 // System.err.println("New lastBlinkTime: " + lastBlinkTime);
564 }
565
566 if ((swing.getFrame() != null)
567 && (swing.getBufferStrategy() != null)
568 ) {
569 do {
570 do {
571 drawToSwing();
572 } while (swing.getBufferStrategy().contentsRestored());
573
574 swing.getBufferStrategy().show();
575 Toolkit.getDefaultToolkit().sync();
576 } while (swing.getBufferStrategy().contentsLost());
577
578 } else {
579 // Non-triple-buffered, call drawToSwing() once
580 drawToSwing();
581 }
582 }
583
584 // ------------------------------------------------------------------------
585 // TerminalReader ---------------------------------------------------------
586 // ------------------------------------------------------------------------
587
588 /**
589 * Check if there are events in the queue.
590 *
591 * @return if true, getEvents() has something to return to the backend
592 */
593 public boolean hasEvents() {
594 synchronized (eventQueue) {
595 return (eventQueue.size() > 0);
596 }
597 }
598
599 /**
600 * Return any events in the IO queue.
601 *
602 * @param queue list to append new events to
603 */
604 public void getEvents(final List<TInputEvent> queue) {
605 synchronized (eventQueue) {
606 if (eventQueue.size() > 0) {
607 synchronized (queue) {
608 queue.addAll(eventQueue);
609 }
610 eventQueue.clear();
611 }
612 }
613 }
614
615 /**
616 * Restore terminal to normal state.
617 */
618 public void closeTerminal() {
619 shutdown();
620 }
621
622 /**
623 * Set listener to a different Object.
624 *
625 * @param listener the new listening object that run() wakes up on new
626 * input
627 */
628 public void setListener(final Object listener) {
629 this.listener = listener;
630 }
631
632 /**
633 * Reload options from System properties.
634 */
635 public void reloadOptions() {
636 // Figure out my cursor style.
637 String cursorStyleString = System.getProperty(
638 "jexer.Swing.cursorStyle", "underline").toLowerCase();
639 if (cursorStyleString.equals("underline")) {
640 cursorStyle = CursorStyle.UNDERLINE;
641 } else if (cursorStyleString.equals("outline")) {
642 cursorStyle = CursorStyle.OUTLINE;
643 } else if (cursorStyleString.equals("block")) {
644 cursorStyle = CursorStyle.BLOCK;
645 }
646
647 // Pull the system property for triple buffering.
648 if (System.getProperty("jexer.Swing.tripleBuffer",
649 "true").equals("true")
650 ) {
651 SwingComponent.tripleBuffer = true;
652 } else {
653 SwingComponent.tripleBuffer = false;
654 }
655 }
656
657 // ------------------------------------------------------------------------
658 // SwingTerminal ----------------------------------------------------------
659 // ------------------------------------------------------------------------
660
661 /**
662 * Get the width of a character cell in pixels.
663 *
664 * @return the width in pixels of a character cell
665 */
666 public int getTextWidth() {
667 return textWidth;
668 }
669
670 /**
671 * Get the height of a character cell in pixels.
672 *
673 * @return the height in pixels of a character cell
674 */
675 public int getTextHeight() {
676 return textHeight;
677 }
678
679 /**
680 * Setup Swing colors to match DOS color palette.
681 */
682 private static void setDOSColors() {
683 if (dosColors) {
684 return;
685 }
686 MYBLACK = new Color(0x00, 0x00, 0x00);
687 MYRED = new Color(0xa8, 0x00, 0x00);
688 MYGREEN = new Color(0x00, 0xa8, 0x00);
689 MYYELLOW = new Color(0xa8, 0x54, 0x00);
690 MYBLUE = new Color(0x00, 0x00, 0xa8);
691 MYMAGENTA = new Color(0xa8, 0x00, 0xa8);
692 MYCYAN = new Color(0x00, 0xa8, 0xa8);
693 MYWHITE = new Color(0xa8, 0xa8, 0xa8);
694 MYBOLD_BLACK = new Color(0x54, 0x54, 0x54);
695 MYBOLD_RED = new Color(0xfc, 0x54, 0x54);
696 MYBOLD_GREEN = new Color(0x54, 0xfc, 0x54);
697 MYBOLD_YELLOW = new Color(0xfc, 0xfc, 0x54);
698 MYBOLD_BLUE = new Color(0x54, 0x54, 0xfc);
699 MYBOLD_MAGENTA = new Color(0xfc, 0x54, 0xfc);
700 MYBOLD_CYAN = new Color(0x54, 0xfc, 0xfc);
701 MYBOLD_WHITE = new Color(0xfc, 0xfc, 0xfc);
702
703 dosColors = true;
704 }
705
706 /**
707 * Get the number of millis to wait before switching the blink from
708 * visible to invisible.
709 *
710 * @return the number of milli to wait before switching the blink from
711 * visible to invisible
712 */
713 public long getBlinkMillis() {
714 return blinkMillis;
715 }
716
717 /**
718 * Get the font size in points.
719 *
720 * @return font size in points
721 */
722 public int getFontSize() {
723 return fontSize;
724 }
725
726 /**
727 * Set the font size in points.
728 *
729 * @param fontSize font size in points
730 */
731 public void setFontSize(final int fontSize) {
732 this.fontSize = fontSize;
733 Font newFont = font.deriveFont((float) fontSize);
734 setFont(newFont);
735 }
736
737 /**
738 * Set to a new font, and resize the screen to match its dimensions.
739 *
740 * @param font the new font
741 */
742 public void setFont(final Font font) {
743 synchronized (this) {
744 this.font = font;
745 getFontDimensions();
746 swing.setFont(font);
747 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
748 glyphCache = new HashMap<Cell, BufferedImage>();
749 resizeToScreen();
750 }
751 }
752
753 /**
754 * Get the font this screen was last set to.
755 *
756 * @return the font
757 */
758 public Font getFont() {
759 return font;
760 }
761
762 /**
763 * Set the font to Terminus, the best all-around font for both CP437 and
764 * ISO8859-1.
765 */
766 public void setDefaultFont() {
767 try {
768 ClassLoader loader = Thread.currentThread().getContextClassLoader();
769 InputStream in = loader.getResourceAsStream(FONTFILE);
770 Font terminusRoot = Font.createFont(Font.TRUETYPE_FONT, in);
771 Font terminus = terminusRoot.deriveFont(Font.PLAIN, fontSize);
772 font = terminus;
773 } catch (java.awt.FontFormatException e) {
774 e.printStackTrace();
775 font = new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
776 } catch (java.io.IOException e) {
777 e.printStackTrace();
778 font = new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
779 }
780
781 setFont(font);
782 }
783
784 /**
785 * Get the X text adjustment.
786 *
787 * @return X text adjustment
788 */
789 public int getTextAdjustX() {
790 return textAdjustX;
791 }
792
793 /**
794 * Set the X text adjustment.
795 *
796 * @param textAdjustX the X text adjustment
797 */
798 public void setTextAdjustX(final int textAdjustX) {
799 synchronized (this) {
800 this.textAdjustX = textAdjustX;
801 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
802 glyphCache = new HashMap<Cell, BufferedImage>();
803 clearPhysical();
804 }
805 }
806
807 /**
808 * Get the Y text adjustment.
809 *
810 * @return Y text adjustment
811 */
812 public int getTextAdjustY() {
813 return textAdjustY;
814 }
815
816 /**
817 * Set the Y text adjustment.
818 *
819 * @param textAdjustY the Y text adjustment
820 */
821 public void setTextAdjustY(final int textAdjustY) {
822 synchronized (this) {
823 this.textAdjustY = textAdjustY;
824 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
825 glyphCache = new HashMap<Cell, BufferedImage>();
826 clearPhysical();
827 }
828 }
829
830 /**
831 * Get the height text adjustment.
832 *
833 * @return height text adjustment
834 */
835 public int getTextAdjustHeight() {
836 return textAdjustHeight;
837 }
838
839 /**
840 * Set the height text adjustment.
841 *
842 * @param textAdjustHeight the height text adjustment
843 */
844 public void setTextAdjustHeight(final int textAdjustHeight) {
845 synchronized (this) {
846 this.textAdjustHeight = textAdjustHeight;
847 textHeight = fontTextHeight + textAdjustHeight;
848 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
849 glyphCache = new HashMap<Cell, BufferedImage>();
850 clearPhysical();
851 }
852 }
853
854 /**
855 * Get the width text adjustment.
856 *
857 * @return width text adjustment
858 */
859 public int getTextAdjustWidth() {
860 return textAdjustWidth;
861 }
862
863 /**
864 * Set the width text adjustment.
865 *
866 * @param textAdjustWidth the width text adjustment
867 */
868 public void setTextAdjustWidth(final int textAdjustWidth) {
869 synchronized (this) {
870 this.textAdjustWidth = textAdjustWidth;
871 textWidth = fontTextWidth + textAdjustWidth;
872 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
873 glyphCache = new HashMap<Cell, BufferedImage>();
874 clearPhysical();
875 }
876 }
877
878 /**
879 * Convert a CellAttributes foreground color to an Swing Color.
880 *
881 * @param attr the text attributes
882 * @return the Swing Color
883 */
884 private Color attrToForegroundColor(final CellAttributes attr) {
885 int rgb = attr.getForeColorRGB();
886 if (rgb >= 0) {
887 int red = (rgb >> 16) & 0xFF;
888 int green = (rgb >> 8) & 0xFF;
889 int blue = rgb & 0xFF;
890
891 return new Color(red, green, blue);
892 }
893
894 if (attr.isBold()) {
895 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
896 return MYBOLD_BLACK;
897 } else if (attr.getForeColor().equals(jexer.bits.Color.RED)) {
898 return MYBOLD_RED;
899 } else if (attr.getForeColor().equals(jexer.bits.Color.BLUE)) {
900 return MYBOLD_BLUE;
901 } else if (attr.getForeColor().equals(jexer.bits.Color.GREEN)) {
902 return MYBOLD_GREEN;
903 } else if (attr.getForeColor().equals(jexer.bits.Color.YELLOW)) {
904 return MYBOLD_YELLOW;
905 } else if (attr.getForeColor().equals(jexer.bits.Color.CYAN)) {
906 return MYBOLD_CYAN;
907 } else if (attr.getForeColor().equals(jexer.bits.Color.MAGENTA)) {
908 return MYBOLD_MAGENTA;
909 } else if (attr.getForeColor().equals(jexer.bits.Color.WHITE)) {
910 return MYBOLD_WHITE;
911 }
912 } else {
913 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
914 return MYBLACK;
915 } else if (attr.getForeColor().equals(jexer.bits.Color.RED)) {
916 return MYRED;
917 } else if (attr.getForeColor().equals(jexer.bits.Color.BLUE)) {
918 return MYBLUE;
919 } else if (attr.getForeColor().equals(jexer.bits.Color.GREEN)) {
920 return MYGREEN;
921 } else if (attr.getForeColor().equals(jexer.bits.Color.YELLOW)) {
922 return MYYELLOW;
923 } else if (attr.getForeColor().equals(jexer.bits.Color.CYAN)) {
924 return MYCYAN;
925 } else if (attr.getForeColor().equals(jexer.bits.Color.MAGENTA)) {
926 return MYMAGENTA;
927 } else if (attr.getForeColor().equals(jexer.bits.Color.WHITE)) {
928 return MYWHITE;
929 }
930 }
931 throw new IllegalArgumentException("Invalid color: " +
932 attr.getForeColor().getValue());
933 }
934
935 /**
936 * Convert a CellAttributes background color to an Swing Color.
937 *
938 * @param attr the text attributes
939 * @return the Swing Color
940 */
941 private Color attrToBackgroundColor(final CellAttributes attr) {
942 int rgb = attr.getBackColorRGB();
943 if (rgb >= 0) {
944 int red = (rgb >> 16) & 0xFF;
945 int green = (rgb >> 8) & 0xFF;
946 int blue = rgb & 0xFF;
947
948 return new Color(red, green, blue);
949 }
950
951 if (attr.getBackColor().equals(jexer.bits.Color.BLACK)) {
952 return MYBLACK;
953 } else if (attr.getBackColor().equals(jexer.bits.Color.RED)) {
954 return MYRED;
955 } else if (attr.getBackColor().equals(jexer.bits.Color.BLUE)) {
956 return MYBLUE;
957 } else if (attr.getBackColor().equals(jexer.bits.Color.GREEN)) {
958 return MYGREEN;
959 } else if (attr.getBackColor().equals(jexer.bits.Color.YELLOW)) {
960 return MYYELLOW;
961 } else if (attr.getBackColor().equals(jexer.bits.Color.CYAN)) {
962 return MYCYAN;
963 } else if (attr.getBackColor().equals(jexer.bits.Color.MAGENTA)) {
964 return MYMAGENTA;
965 } else if (attr.getBackColor().equals(jexer.bits.Color.WHITE)) {
966 return MYWHITE;
967 }
968 throw new IllegalArgumentException("Invalid color: " +
969 attr.getBackColor().getValue());
970 }
971
972 /**
973 * Figure out what textAdjustX, textAdjustY, textAdjustHeight, and
974 * textAdjustWidth should be, based on the location of a vertical bar and
975 * a horizontal bar.
976 */
977 private void getFontAdjustments() {
978 BufferedImage image = null;
979
980 // What SHOULD happen is that the topmost/leftmost white pixel is at
981 // position (gr2x, gr2y). But it might also be off by a pixel in
982 // either direction.
983
984 Graphics2D gr2 = null;
985 int gr2x = 3;
986 int gr2y = 3;
987 image = new BufferedImage(fontTextWidth * 2, fontTextHeight * 2,
988 BufferedImage.TYPE_INT_ARGB);
989
990 gr2 = image.createGraphics();
991 gr2.setFont(swing.getFont());
992 gr2.setColor(java.awt.Color.BLACK);
993 gr2.fillRect(0, 0, fontTextWidth * 2, fontTextHeight * 2);
994 gr2.setColor(java.awt.Color.WHITE);
995 char [] chars = new char[1];
996 chars[0] = jexer.bits.GraphicsChars.SINGLE_BAR;
997 gr2.drawChars(chars, 0, 1, gr2x, gr2y + fontTextHeight - maxDescent);
998 chars[0] = jexer.bits.GraphicsChars.VERTICAL_BAR;
999 gr2.drawChars(chars, 0, 1, gr2x, gr2y + fontTextHeight - maxDescent);
1000 gr2.dispose();
1001
1002 int top = fontTextHeight * 2;
1003 int bottom = -1;
1004 int left = fontTextWidth * 2;
1005 int right = -1;
1006 textAdjustX = 0;
1007 textAdjustY = 0;
1008 textAdjustHeight = 0;
1009 textAdjustWidth = 0;
1010
1011 for (int x = 0; x < fontTextWidth * 2; x++) {
1012 for (int y = 0; y < fontTextHeight * 2; y++) {
1013
1014 /*
1015 System.err.println("H X: " + x + " Y: " + y + " " +
1016 image.getRGB(x, y));
1017 */
1018
1019 if ((image.getRGB(x, y) & 0xFFFFFF) != 0) {
1020 // Pixel is present.
1021 if (y < top) {
1022 top = y;
1023 }
1024 if (y > bottom) {
1025 bottom = y;
1026 }
1027 if (x < left) {
1028 left = x;
1029 }
1030 if (x > right) {
1031 right = x;
1032 }
1033 }
1034 }
1035 }
1036 if (left < right) {
1037 textAdjustX = (gr2x - left);
1038 textAdjustWidth = fontTextWidth - (right - left + 1);
1039 }
1040 if (top < bottom) {
1041 textAdjustY = (gr2y - top);
1042 textAdjustHeight = fontTextHeight - (bottom - top + 1);
1043 }
1044 // System.err.println("top " + top + " bottom " + bottom);
1045 // System.err.println("left " + left + " right " + right);
1046
1047 // Special case: do not believe fonts that claim to be wider than
1048 // they are tall.
1049 if (fontTextWidth >= fontTextHeight) {
1050 textAdjustX = 0;
1051 textAdjustWidth = 0;
1052 fontTextWidth = fontTextHeight / 2;
1053 }
1054 }
1055
1056 /**
1057 * Figure out my font dimensions. This code path works OK for the JFrame
1058 * case, and can be called immediately after JFrame creation.
1059 */
1060 private void getFontDimensions() {
1061 swing.setFont(font);
1062 Graphics gr = swing.getGraphics();
1063 if (gr == null) {
1064 return;
1065 }
1066 getFontDimensions(gr);
1067 }
1068
1069 /**
1070 * Figure out my font dimensions. This code path is needed to lazy-load
1071 * the information inside paint().
1072 *
1073 * @param gr Graphics object to use
1074 */
1075 private void getFontDimensions(final Graphics gr) {
1076 swing.setFont(font);
1077 FontMetrics fm = gr.getFontMetrics();
1078 maxDescent = fm.getMaxDescent();
1079 Rectangle2D bounds = fm.getMaxCharBounds(gr);
1080 int leading = fm.getLeading();
1081 fontTextWidth = (int)Math.round(bounds.getWidth());
1082 // fontTextHeight = (int)Math.round(bounds.getHeight()) - maxDescent;
1083
1084 // This produces the same number, but works better for ugly
1085 // monospace.
1086 fontTextHeight = fm.getMaxAscent() + maxDescent - leading;
1087
1088 getFontAdjustments();
1089 textHeight = fontTextHeight + textAdjustHeight;
1090 textWidth = fontTextWidth + textAdjustWidth;
1091
1092 if (sessionInfo != null) {
1093 sessionInfo.setTextCellDimensions(textWidth, textHeight);
1094 }
1095 gotFontDimensions = true;
1096 }
1097
1098 /**
1099 * Resize to font dimensions.
1100 */
1101 public void resizeToScreen() {
1102 swing.setDimensions(textWidth * (width + 1), textHeight * (height + 1));
1103 }
1104
1105 /**
1106 * Draw one cell's image to the screen.
1107 *
1108 * @param gr the Swing Graphics context
1109 * @param cell the Cell to draw
1110 * @param xPixel the x-coordinate to render to. 0 means the
1111 * left-most pixel column.
1112 * @param yPixel the y-coordinate to render to. 0 means the top-most
1113 * pixel row.
1114 */
1115 private void drawImage(final Graphics gr, final Cell cell,
1116 final int xPixel, final int yPixel) {
1117
1118 /*
1119 System.err.println("drawImage(): " + xPixel + " " + yPixel +
1120 " " + cell);
1121 */
1122
1123 // Draw the background rectangle, then the foreground character.
1124 assert (cell.isImage());
1125 gr.setColor(cell.getBackground());
1126 gr.fillRect(xPixel, yPixel, textWidth, textHeight);
1127
1128 BufferedImage image = cell.getImage();
1129 if (image != null) {
1130 if (swing.getFrame() != null) {
1131 gr.drawImage(image, xPixel, yPixel, swing.getFrame());
1132 } else {
1133 gr.drawImage(image, xPixel, yPixel, swing.getComponent());
1134 }
1135 return;
1136 }
1137 }
1138
1139 /**
1140 * Draw one glyph to the screen.
1141 *
1142 * @param gr the Swing Graphics context
1143 * @param cell the Cell to draw
1144 * @param xPixel the x-coordinate to render to. 0 means the
1145 * left-most pixel column.
1146 * @param yPixel the y-coordinate to render to. 0 means the top-most
1147 * pixel row.
1148 */
1149 private void drawGlyph(final Graphics gr, final Cell cell,
1150 final int xPixel, final int yPixel) {
1151
1152 /*
1153 System.err.println("drawGlyph(): " + xPixel + " " + yPixel +
1154 " " + cell);
1155 */
1156
1157 BufferedImage image = null;
1158 if (cell.isBlink() && !cursorBlinkVisible) {
1159 image = glyphCacheBlink.get(cell);
1160 } else {
1161 image = glyphCache.get(cell);
1162 }
1163 if (image != null) {
1164 if (swing.getFrame() != null) {
1165 gr.drawImage(image, xPixel, yPixel, swing.getFrame());
1166 } else {
1167 gr.drawImage(image, xPixel, yPixel, swing.getComponent());
1168 }
1169 return;
1170 }
1171
1172 // Generate glyph and draw it.
1173 Graphics2D gr2 = null;
1174 int gr2x = xPixel;
1175 int gr2y = yPixel;
1176 if ((SwingComponent.tripleBuffer) && (swing.getFrame() != null)) {
1177 image = new BufferedImage(textWidth, textHeight,
1178 BufferedImage.TYPE_INT_ARGB);
1179 gr2 = image.createGraphics();
1180 gr2.setFont(swing.getFont());
1181 gr2x = 0;
1182 gr2y = 0;
1183 } else {
1184 gr2 = (Graphics2D) gr;
1185 }
1186
1187 Cell cellColor = new Cell();
1188 cellColor.setTo(cell);
1189
1190 // Check for reverse
1191 if (cell.isReverse()) {
1192 cellColor.setForeColor(cell.getBackColor());
1193 cellColor.setBackColor(cell.getForeColor());
1194 }
1195
1196 // Draw the background rectangle, then the foreground character.
1197 gr2.setColor(attrToBackgroundColor(cellColor));
1198 gr2.fillRect(gr2x, gr2y, textWidth, textHeight);
1199
1200 // Handle blink and underline
1201 if (!cell.isBlink()
1202 || (cell.isBlink() && cursorBlinkVisible)
1203 ) {
1204 gr2.setColor(attrToForegroundColor(cellColor));
1205 char [] chars = new char[1];
1206 chars[0] = cell.getChar();
1207 gr2.drawChars(chars, 0, 1, gr2x + textAdjustX,
1208 gr2y + textHeight - maxDescent + textAdjustY);
1209
1210 if (cell.isUnderline()) {
1211 gr2.fillRect(gr2x, gr2y + textHeight - 2, textWidth, 2);
1212 }
1213 }
1214
1215 if ((SwingComponent.tripleBuffer) && (swing.getFrame() != null)) {
1216 gr2.dispose();
1217
1218 // We need a new key that will not be mutated by
1219 // invertCell().
1220 Cell key = new Cell();
1221 key.setTo(cell);
1222 if (cell.isBlink() && !cursorBlinkVisible) {
1223 glyphCacheBlink.put(key, image);
1224 } else {
1225 glyphCache.put(key, image);
1226 }
1227
1228 if (swing.getFrame() != null) {
1229 gr.drawImage(image, xPixel, yPixel, swing.getFrame());
1230 } else {
1231 gr.drawImage(image, xPixel, yPixel, swing.getComponent());
1232 }
1233 }
1234
1235 }
1236
1237 /**
1238 * Check if the cursor is visible, and if so draw it.
1239 *
1240 * @param gr the Swing Graphics context
1241 */
1242 private void drawCursor(final Graphics gr) {
1243
1244 if (cursorVisible
1245 && (cursorY >= 0)
1246 && (cursorX >= 0)
1247 && (cursorY <= height - 1)
1248 && (cursorX <= width - 1)
1249 && cursorBlinkVisible
1250 ) {
1251 int xPixel = cursorX * textWidth + left;
1252 int yPixel = cursorY * textHeight + top;
1253 Cell lCell = logical[cursorX][cursorY];
1254 gr.setColor(attrToForegroundColor(lCell));
1255 switch (cursorStyle) {
1256 default:
1257 // Fall through...
1258 case UNDERLINE:
1259 gr.fillRect(xPixel, yPixel + textHeight - 2, textWidth, 2);
1260 break;
1261 case BLOCK:
1262 gr.fillRect(xPixel, yPixel, textWidth, textHeight);
1263 break;
1264 case OUTLINE:
1265 gr.drawRect(xPixel, yPixel, textWidth - 1, textHeight - 1);
1266 break;
1267 }
1268 }
1269 }
1270
1271 /**
1272 * Reset the blink timer.
1273 */
1274 private void resetBlinkTimer() {
1275 lastBlinkTime = System.currentTimeMillis();
1276 cursorBlinkVisible = true;
1277 }
1278
1279 /**
1280 * Paint redraws the whole screen.
1281 *
1282 * @param gr the Swing Graphics context
1283 */
1284 public void paint(final Graphics gr) {
1285
1286 if (gotFontDimensions == false) {
1287 // Lazy-load the text width/height
1288 getFontDimensions(gr);
1289 /*
1290 System.err.println("textWidth " + textWidth +
1291 " textHeight " + textHeight);
1292 System.err.println("FONT: " + swing.getFont() + " font " + font);
1293 */
1294 }
1295
1296 if ((swing.getFrame() != null)
1297 && (swing.getBufferStrategy() != null)
1298 && (SwingUtilities.isEventDispatchThread())
1299 ) {
1300 // System.err.println("paint(), skip first paint on swing thread");
1301 return;
1302 }
1303
1304 int xCellMin = 0;
1305 int xCellMax = width;
1306 int yCellMin = 0;
1307 int yCellMax = height;
1308
1309 Rectangle bounds = gr.getClipBounds();
1310 if (bounds != null) {
1311 // Only update what is in the bounds
1312 xCellMin = textColumn(bounds.x);
1313 xCellMax = textColumn(bounds.x + bounds.width);
1314 if (xCellMax > width) {
1315 xCellMax = width;
1316 }
1317 if (xCellMin >= xCellMax) {
1318 xCellMin = xCellMax - 2;
1319 }
1320 if (xCellMin < 0) {
1321 xCellMin = 0;
1322 }
1323 yCellMin = textRow(bounds.y);
1324 yCellMax = textRow(bounds.y + bounds.height);
1325 if (yCellMax > height) {
1326 yCellMax = height;
1327 }
1328 if (yCellMin >= yCellMax) {
1329 yCellMin = yCellMax - 2;
1330 }
1331 if (yCellMin < 0) {
1332 yCellMin = 0;
1333 }
1334 } else {
1335 // We need a total repaint
1336 reallyCleared = true;
1337 }
1338
1339 // Prevent updates to the screen's data from the TApplication
1340 // threads.
1341 synchronized (this) {
1342
1343 /*
1344 System.err.printf("bounds %s X %d %d Y %d %d\n",
1345 bounds, xCellMin, xCellMax, yCellMin, yCellMax);
1346 */
1347
1348 for (int y = yCellMin; y < yCellMax; y++) {
1349 for (int x = xCellMin; x < xCellMax; x++) {
1350
1351 int xPixel = x * textWidth + left;
1352 int yPixel = y * textHeight + top;
1353
1354 Cell lCell = logical[x][y];
1355 Cell pCell = physical[x][y];
1356
1357 if (!lCell.equals(pCell)
1358 || lCell.isBlink()
1359 || reallyCleared
1360 || (swing.getFrame() == null)) {
1361
1362 if (lCell.isImage()) {
1363 drawImage(gr, lCell, xPixel, yPixel);
1364 } else {
1365 drawGlyph(gr, lCell, xPixel, yPixel);
1366 }
1367
1368 // Physical is always updated
1369 physical[x][y].setTo(lCell);
1370 }
1371 }
1372 }
1373 drawCursor(gr);
1374
1375 reallyCleared = false;
1376 } // synchronized (this)
1377 }
1378
1379 /**
1380 * Restore terminal to normal state.
1381 */
1382 public void shutdown() {
1383 swing.dispose();
1384 }
1385
1386 /**
1387 * Push the logical screen to the physical device.
1388 */
1389 private void drawToSwing() {
1390
1391 /*
1392 System.err.printf("drawToSwing(): reallyCleared %s dirty %s\n",
1393 reallyCleared, dirty);
1394 */
1395
1396 // If reallyCleared is set, we have to draw everything.
1397 if ((swing.getFrame() != null)
1398 && (swing.getBufferStrategy() != null)
1399 && (reallyCleared == true)
1400 ) {
1401 // Triple-buffering: we have to redraw everything on this thread.
1402 Graphics gr = swing.getBufferStrategy().getDrawGraphics();
1403 swing.paint(gr);
1404 gr.dispose();
1405 swing.getBufferStrategy().show();
1406 Toolkit.getDefaultToolkit().sync();
1407 return;
1408 } else if (((swing.getFrame() != null)
1409 && (swing.getBufferStrategy() == null))
1410 || (reallyCleared == true)
1411 ) {
1412 // Repaint everything on the Swing thread.
1413 // System.err.println("REPAINT ALL");
1414 swing.repaint();
1415 return;
1416 }
1417
1418 if ((swing.getFrame() != null) && (swing.getBufferStrategy() != null)) {
1419 Graphics gr = swing.getBufferStrategy().getDrawGraphics();
1420
1421 synchronized (this) {
1422 for (int y = 0; y < height; y++) {
1423 for (int x = 0; x < width; x++) {
1424 Cell lCell = logical[x][y];
1425 Cell pCell = physical[x][y];
1426
1427 int xPixel = x * textWidth + left;
1428 int yPixel = y * textHeight + top;
1429
1430 if (!lCell.equals(pCell)
1431 || ((x == cursorX)
1432 && (y == cursorY)
1433 && cursorVisible)
1434 || (lCell.isBlink())
1435 ) {
1436 if (lCell.isImage()) {
1437 drawImage(gr, lCell, xPixel, yPixel);
1438 } else {
1439 drawGlyph(gr, lCell, xPixel, yPixel);
1440 }
1441 physical[x][y].setTo(lCell);
1442 }
1443 }
1444 }
1445 drawCursor(gr);
1446 } // synchronized (this)
1447
1448 gr.dispose();
1449 swing.getBufferStrategy().show();
1450 Toolkit.getDefaultToolkit().sync();
1451 return;
1452 }
1453
1454 // Swing thread version: request a repaint, but limit it to the area
1455 // that has changed.
1456
1457 // Find the minimum-size damaged region.
1458 int xMin = swing.getWidth();
1459 int xMax = 0;
1460 int yMin = swing.getHeight();
1461 int yMax = 0;
1462
1463 synchronized (this) {
1464 for (int y = 0; y < height; y++) {
1465 for (int x = 0; x < width; x++) {
1466 Cell lCell = logical[x][y];
1467 Cell pCell = physical[x][y];
1468
1469 int xPixel = x * textWidth + left;
1470 int yPixel = y * textHeight + top;
1471
1472 if (!lCell.equals(pCell)
1473 || ((x == cursorX)
1474 && (y == cursorY)
1475 && cursorVisible)
1476 || lCell.isBlink()
1477 ) {
1478 if (xPixel < xMin) {
1479 xMin = xPixel;
1480 }
1481 if (xPixel + textWidth > xMax) {
1482 xMax = xPixel + textWidth;
1483 }
1484 if (yPixel < yMin) {
1485 yMin = yPixel;
1486 }
1487 if (yPixel + textHeight > yMax) {
1488 yMax = yPixel + textHeight;
1489 }
1490 }
1491 }
1492 }
1493 }
1494 if (xMin + textWidth >= xMax) {
1495 xMax += textWidth;
1496 }
1497 if (yMin + textHeight >= yMax) {
1498 yMax += textHeight;
1499 }
1500
1501 // Repaint the desired area
1502 /*
1503 System.err.printf("REPAINT X %d %d Y %d %d\n", xMin, xMax,
1504 yMin, yMax);
1505 */
1506
1507 if ((swing.getFrame() != null) && (swing.getBufferStrategy() != null)) {
1508 // This path should never be taken, but is left here for
1509 // completeness.
1510 Graphics gr = swing.getBufferStrategy().getDrawGraphics();
1511 Rectangle bounds = new Rectangle(xMin, yMin, xMax - xMin,
1512 yMax - yMin);
1513 gr.setClip(bounds);
1514 swing.paint(gr);
1515 gr.dispose();
1516 swing.getBufferStrategy().show();
1517 Toolkit.getDefaultToolkit().sync();
1518 } else {
1519 // Repaint on the Swing thread.
1520 swing.repaint(xMin, yMin, xMax - xMin, yMax - yMin);
1521 }
1522 }
1523
1524 /**
1525 * Convert pixel column position to text cell column position.
1526 *
1527 * @param x pixel column position
1528 * @return text cell column position
1529 */
1530 public int textColumn(final int x) {
1531 int column = ((x - left) / textWidth);
1532 if (column < 0) {
1533 column = 0;
1534 }
1535 if (column > width - 1) {
1536 column = width - 1;
1537 }
1538 return column;
1539 }
1540
1541 /**
1542 * Convert pixel row position to text cell row position.
1543 *
1544 * @param y pixel row position
1545 * @return text cell row position
1546 */
1547 public int textRow(final int y) {
1548 int row = ((y - top) / textHeight);
1549 if (row < 0) {
1550 row = 0;
1551 }
1552 if (row > height - 1) {
1553 row = height - 1;
1554 }
1555 return row;
1556 }
1557
1558 /**
1559 * Getter for sessionInfo.
1560 *
1561 * @return the SessionInfo
1562 */
1563 public SessionInfo getSessionInfo() {
1564 return sessionInfo;
1565 }
1566
1567 /**
1568 * Getter for the underlying Swing component.
1569 *
1570 * @return the SwingComponent
1571 */
1572 public SwingComponent getSwingComponent() {
1573 return swing;
1574 }
1575
1576 // ------------------------------------------------------------------------
1577 // KeyListener ------------------------------------------------------------
1578 // ------------------------------------------------------------------------
1579
1580 /**
1581 * Pass Swing keystrokes into the event queue.
1582 *
1583 * @param key keystroke received
1584 */
1585 public void keyReleased(final KeyEvent key) {
1586 // Ignore release events
1587 }
1588
1589 /**
1590 * Pass Swing keystrokes into the event queue.
1591 *
1592 * @param key keystroke received
1593 */
1594 public void keyTyped(final KeyEvent key) {
1595 // Ignore typed events
1596 }
1597
1598 /**
1599 * Pass Swing keystrokes into the event queue.
1600 *
1601 * @param key keystroke received
1602 */
1603 public void keyPressed(final KeyEvent key) {
1604 boolean alt = false;
1605 boolean shift = false;
1606 boolean ctrl = false;
1607 char ch = ' ';
1608 boolean isKey = false;
1609 if (key.isActionKey()) {
1610 isKey = true;
1611 } else {
1612 ch = key.getKeyChar();
1613 }
1614 alt = key.isAltDown();
1615 ctrl = key.isControlDown();
1616 shift = key.isShiftDown();
1617
1618 /*
1619 System.err.printf("Swing Key: %s\n", key);
1620 System.err.printf(" isKey: %s\n", isKey);
1621 System.err.printf(" alt: %s\n", alt);
1622 System.err.printf(" ctrl: %s\n", ctrl);
1623 System.err.printf(" shift: %s\n", shift);
1624 System.err.printf(" ch: %s\n", ch);
1625 */
1626
1627 // Special case: not return the bare modifier presses
1628 switch (key.getKeyCode()) {
1629 case KeyEvent.VK_ALT:
1630 return;
1631 case KeyEvent.VK_ALT_GRAPH:
1632 return;
1633 case KeyEvent.VK_CONTROL:
1634 return;
1635 case KeyEvent.VK_SHIFT:
1636 return;
1637 case KeyEvent.VK_META:
1638 return;
1639 default:
1640 break;
1641 }
1642
1643 TKeypress keypress = null;
1644 if (isKey) {
1645 switch (key.getKeyCode()) {
1646 case KeyEvent.VK_F1:
1647 keypress = new TKeypress(true, TKeypress.F1, ' ',
1648 alt, ctrl, shift);
1649 break;
1650 case KeyEvent.VK_F2:
1651 keypress = new TKeypress(true, TKeypress.F2, ' ',
1652 alt, ctrl, shift);
1653 break;
1654 case KeyEvent.VK_F3:
1655 keypress = new TKeypress(true, TKeypress.F3, ' ',
1656 alt, ctrl, shift);
1657 break;
1658 case KeyEvent.VK_F4:
1659 keypress = new TKeypress(true, TKeypress.F4, ' ',
1660 alt, ctrl, shift);
1661 break;
1662 case KeyEvent.VK_F5:
1663 keypress = new TKeypress(true, TKeypress.F5, ' ',
1664 alt, ctrl, shift);
1665 break;
1666 case KeyEvent.VK_F6:
1667 keypress = new TKeypress(true, TKeypress.F6, ' ',
1668 alt, ctrl, shift);
1669 break;
1670 case KeyEvent.VK_F7:
1671 keypress = new TKeypress(true, TKeypress.F7, ' ',
1672 alt, ctrl, shift);
1673 break;
1674 case KeyEvent.VK_F8:
1675 keypress = new TKeypress(true, TKeypress.F8, ' ',
1676 alt, ctrl, shift);
1677 break;
1678 case KeyEvent.VK_F9:
1679 keypress = new TKeypress(true, TKeypress.F9, ' ',
1680 alt, ctrl, shift);
1681 break;
1682 case KeyEvent.VK_F10:
1683 keypress = new TKeypress(true, TKeypress.F10, ' ',
1684 alt, ctrl, shift);
1685 break;
1686 case KeyEvent.VK_F11:
1687 keypress = new TKeypress(true, TKeypress.F11, ' ',
1688 alt, ctrl, shift);
1689 break;
1690 case KeyEvent.VK_F12:
1691 keypress = new TKeypress(true, TKeypress.F12, ' ',
1692 alt, ctrl, shift);
1693 break;
1694 case KeyEvent.VK_HOME:
1695 keypress = new TKeypress(true, TKeypress.HOME, ' ',
1696 alt, ctrl, shift);
1697 break;
1698 case KeyEvent.VK_END:
1699 keypress = new TKeypress(true, TKeypress.END, ' ',
1700 alt, ctrl, shift);
1701 break;
1702 case KeyEvent.VK_PAGE_UP:
1703 keypress = new TKeypress(true, TKeypress.PGUP, ' ',
1704 alt, ctrl, shift);
1705 break;
1706 case KeyEvent.VK_PAGE_DOWN:
1707 keypress = new TKeypress(true, TKeypress.PGDN, ' ',
1708 alt, ctrl, shift);
1709 break;
1710 case KeyEvent.VK_INSERT:
1711 keypress = new TKeypress(true, TKeypress.INS, ' ',
1712 alt, ctrl, shift);
1713 break;
1714 case KeyEvent.VK_DELETE:
1715 keypress = new TKeypress(true, TKeypress.DEL, ' ',
1716 alt, ctrl, shift);
1717 break;
1718 case KeyEvent.VK_RIGHT:
1719 keypress = new TKeypress(true, TKeypress.RIGHT, ' ',
1720 alt, ctrl, shift);
1721 break;
1722 case KeyEvent.VK_LEFT:
1723 keypress = new TKeypress(true, TKeypress.LEFT, ' ',
1724 alt, ctrl, shift);
1725 break;
1726 case KeyEvent.VK_UP:
1727 keypress = new TKeypress(true, TKeypress.UP, ' ',
1728 alt, ctrl, shift);
1729 break;
1730 case KeyEvent.VK_DOWN:
1731 keypress = new TKeypress(true, TKeypress.DOWN, ' ',
1732 alt, ctrl, shift);
1733 break;
1734 case KeyEvent.VK_TAB:
1735 // Special case: distinguish TAB vs BTAB
1736 if (shift) {
1737 keypress = kbShiftTab;
1738 } else {
1739 keypress = kbTab;
1740 }
1741 break;
1742 case KeyEvent.VK_ENTER:
1743 keypress = new TKeypress(true, TKeypress.ENTER, ' ',
1744 alt, ctrl, shift);
1745 break;
1746 case KeyEvent.VK_ESCAPE:
1747 keypress = new TKeypress(true, TKeypress.ESC, ' ',
1748 alt, ctrl, shift);
1749 break;
1750 case KeyEvent.VK_BACK_SPACE:
1751 keypress = kbBackspace;
1752 break;
1753 default:
1754 // Unsupported, ignore
1755 return;
1756 }
1757 }
1758
1759 if (keypress == null) {
1760 switch (ch) {
1761 case 0x08:
1762 // Disambiguate ^H from Backspace.
1763 if (KeyEvent.getKeyText(key.getKeyCode()).equals("H")) {
1764 // This is ^H.
1765 keypress = kbBackspace;
1766 } else {
1767 // We are emulating Xterm here, where the backspace key
1768 // on the keyboard returns ^?.
1769 keypress = kbBackspaceDel;
1770 }
1771 break;
1772 case 0x0A:
1773 keypress = kbEnter;
1774 break;
1775 case 0x1B:
1776 keypress = kbEsc;
1777 break;
1778 case 0x0D:
1779 keypress = kbEnter;
1780 break;
1781 case 0x09:
1782 if (shift) {
1783 keypress = kbShiftTab;
1784 } else {
1785 keypress = kbTab;
1786 }
1787 break;
1788 case 0x7F:
1789 keypress = kbDel;
1790 break;
1791 default:
1792 if (!alt && ctrl && !shift) {
1793 ch = KeyEvent.getKeyText(key.getKeyCode()).charAt(0);
1794 }
1795 // Not a special key, put it together
1796 keypress = new TKeypress(false, 0, ch, alt, ctrl, shift);
1797 }
1798 }
1799
1800 // Save it and we are done.
1801 synchronized (eventQueue) {
1802 eventQueue.add(new TKeypressEvent(keypress));
1803 resetBlinkTimer();
1804 }
1805 if (listener != null) {
1806 synchronized (listener) {
1807 listener.notifyAll();
1808 }
1809 }
1810 }
1811
1812 // ------------------------------------------------------------------------
1813 // WindowListener ---------------------------------------------------------
1814 // ------------------------------------------------------------------------
1815
1816 /**
1817 * Pass window events into the event queue.
1818 *
1819 * @param event window event received
1820 */
1821 public void windowActivated(final WindowEvent event) {
1822 // Force a total repaint
1823 synchronized (this) {
1824 clearPhysical();
1825 }
1826 }
1827
1828 /**
1829 * Pass window events into the event queue.
1830 *
1831 * @param event window event received
1832 */
1833 public void windowClosed(final WindowEvent event) {
1834 // Ignore
1835 }
1836
1837 /**
1838 * Pass window events into the event queue.
1839 *
1840 * @param event window event received
1841 */
1842 public void windowClosing(final WindowEvent event) {
1843 // Drop a cmAbort and walk away
1844 synchronized (eventQueue) {
1845 eventQueue.add(new TCommandEvent(cmAbort));
1846 resetBlinkTimer();
1847 }
1848 if (listener != null) {
1849 synchronized (listener) {
1850 listener.notifyAll();
1851 }
1852 }
1853 }
1854
1855 /**
1856 * Pass window events into the event queue.
1857 *
1858 * @param event window event received
1859 */
1860 public void windowDeactivated(final WindowEvent event) {
1861 // Ignore
1862 }
1863
1864 /**
1865 * Pass window events into the event queue.
1866 *
1867 * @param event window event received
1868 */
1869 public void windowDeiconified(final WindowEvent event) {
1870 // Ignore
1871 }
1872
1873 /**
1874 * Pass window events into the event queue.
1875 *
1876 * @param event window event received
1877 */
1878 public void windowIconified(final WindowEvent event) {
1879 // Ignore
1880 }
1881
1882 /**
1883 * Pass window events into the event queue.
1884 *
1885 * @param event window event received
1886 */
1887 public void windowOpened(final WindowEvent event) {
1888 // Ignore
1889 }
1890
1891 // ------------------------------------------------------------------------
1892 // ComponentListener ------------------------------------------------------
1893 // ------------------------------------------------------------------------
1894
1895 /**
1896 * Pass component events into the event queue.
1897 *
1898 * @param event component event received
1899 */
1900 public void componentHidden(final ComponentEvent event) {
1901 // Ignore
1902 }
1903
1904 /**
1905 * Pass component events into the event queue.
1906 *
1907 * @param event component event received
1908 */
1909 public void componentShown(final ComponentEvent event) {
1910 // Ignore
1911 }
1912
1913 /**
1914 * Pass component events into the event queue.
1915 *
1916 * @param event component event received
1917 */
1918 public void componentMoved(final ComponentEvent event) {
1919 // Ignore
1920 }
1921
1922 /**
1923 * Pass component events into the event queue.
1924 *
1925 * @param event component event received
1926 */
1927 public void componentResized(final ComponentEvent event) {
1928 if (gotFontDimensions == false) {
1929 // We are still waiting to get font information. Don't pass a
1930 // resize event up.
1931 // System.err.println("size " + swing.getComponent().getSize());
1932 return;
1933 }
1934
1935 // Drop a new TResizeEvent into the queue
1936 sessionInfo.queryWindowSize();
1937 synchronized (eventQueue) {
1938 TResizeEvent windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
1939 sessionInfo.getWindowWidth(), sessionInfo.getWindowHeight());
1940 eventQueue.add(windowResize);
1941 resetBlinkTimer();
1942 /*
1943 System.err.println("Add resize event: " + windowResize.getWidth() +
1944 " x " + windowResize.getHeight());
1945 */
1946 }
1947 if (listener != null) {
1948 synchronized (listener) {
1949 listener.notifyAll();
1950 }
1951 }
1952 }
1953
1954 // ------------------------------------------------------------------------
1955 // MouseMotionListener ----------------------------------------------------
1956 // ------------------------------------------------------------------------
1957
1958 /**
1959 * Pass mouse events into the event queue.
1960 *
1961 * @param mouse mouse event received
1962 */
1963 public void mouseDragged(final MouseEvent mouse) {
1964 int modifiers = mouse.getModifiersEx();
1965 boolean eventMouse1 = false;
1966 boolean eventMouse2 = false;
1967 boolean eventMouse3 = false;
1968 if ((modifiers & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
1969 eventMouse1 = true;
1970 }
1971 if ((modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0) {
1972 eventMouse2 = true;
1973 }
1974 if ((modifiers & MouseEvent.BUTTON3_DOWN_MASK) != 0) {
1975 eventMouse3 = true;
1976 }
1977 mouse1 = eventMouse1;
1978 mouse2 = eventMouse2;
1979 mouse3 = eventMouse3;
1980 int x = textColumn(mouse.getX());
1981 int y = textRow(mouse.getY());
1982
1983 TMouseEvent mouseEvent = new TMouseEvent(TMouseEvent.Type.MOUSE_MOTION,
1984 x, y, x, y, mouse1, mouse2, mouse3, false, false);
1985
1986 synchronized (eventQueue) {
1987 eventQueue.add(mouseEvent);
1988 resetBlinkTimer();
1989 }
1990 if (listener != null) {
1991 synchronized (listener) {
1992 listener.notifyAll();
1993 }
1994 }
1995 }
1996
1997 /**
1998 * Pass mouse events into the event queue.
1999 *
2000 * @param mouse mouse event received
2001 */
2002 public void mouseMoved(final MouseEvent mouse) {
2003 int x = textColumn(mouse.getX());
2004 int y = textRow(mouse.getY());
2005 if ((x == oldMouseX) && (y == oldMouseY)) {
2006 // Bail out, we've moved some pixels but not a whole text cell.
2007 return;
2008 }
2009 oldMouseX = x;
2010 oldMouseY = y;
2011
2012 TMouseEvent mouseEvent = new TMouseEvent(TMouseEvent.Type.MOUSE_MOTION,
2013 x, y, x, y, mouse1, mouse2, mouse3, false, false);
2014
2015 synchronized (eventQueue) {
2016 eventQueue.add(mouseEvent);
2017 resetBlinkTimer();
2018 }
2019 if (listener != null) {
2020 synchronized (listener) {
2021 listener.notifyAll();
2022 }
2023 }
2024 }
2025
2026 // ------------------------------------------------------------------------
2027 // MouseListener ----------------------------------------------------------
2028 // ------------------------------------------------------------------------
2029
2030 /**
2031 * Pass mouse events into the event queue.
2032 *
2033 * @param mouse mouse event received
2034 */
2035 public void mouseClicked(final MouseEvent mouse) {
2036 // Ignore
2037 }
2038
2039 /**
2040 * Pass mouse events into the event queue.
2041 *
2042 * @param mouse mouse event received
2043 */
2044 public void mouseEntered(final MouseEvent mouse) {
2045 // Ignore
2046 }
2047
2048 /**
2049 * Pass mouse events into the event queue.
2050 *
2051 * @param mouse mouse event received
2052 */
2053 public void mouseExited(final MouseEvent mouse) {
2054 // Ignore
2055 }
2056
2057 /**
2058 * Pass mouse events into the event queue.
2059 *
2060 * @param mouse mouse event received
2061 */
2062 public void mousePressed(final MouseEvent mouse) {
2063 int modifiers = mouse.getModifiersEx();
2064 boolean eventMouse1 = false;
2065 boolean eventMouse2 = false;
2066 boolean eventMouse3 = false;
2067 if ((modifiers & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
2068 eventMouse1 = true;
2069 }
2070 if ((modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0) {
2071 eventMouse2 = true;
2072 }
2073 if ((modifiers & MouseEvent.BUTTON3_DOWN_MASK) != 0) {
2074 eventMouse3 = true;
2075 }
2076 mouse1 = eventMouse1;
2077 mouse2 = eventMouse2;
2078 mouse3 = eventMouse3;
2079 int x = textColumn(mouse.getX());
2080 int y = textRow(mouse.getY());
2081
2082 TMouseEvent mouseEvent = new TMouseEvent(TMouseEvent.Type.MOUSE_DOWN,
2083 x, y, x, y, mouse1, mouse2, mouse3, false, false);
2084
2085 synchronized (eventQueue) {
2086 eventQueue.add(mouseEvent);
2087 resetBlinkTimer();
2088 }
2089 if (listener != null) {
2090 synchronized (listener) {
2091 listener.notifyAll();
2092 }
2093 }
2094 }
2095
2096 /**
2097 * Pass mouse events into the event queue.
2098 *
2099 * @param mouse mouse event received
2100 */
2101 public void mouseReleased(final MouseEvent mouse) {
2102 int modifiers = mouse.getModifiersEx();
2103 boolean eventMouse1 = false;
2104 boolean eventMouse2 = false;
2105 boolean eventMouse3 = false;
2106 if ((modifiers & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
2107 eventMouse1 = true;
2108 }
2109 if ((modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0) {
2110 eventMouse2 = true;
2111 }
2112 if ((modifiers & MouseEvent.BUTTON3_DOWN_MASK) != 0) {
2113 eventMouse3 = true;
2114 }
2115 if (mouse1) {
2116 mouse1 = false;
2117 eventMouse1 = true;
2118 }
2119 if (mouse2) {
2120 mouse2 = false;
2121 eventMouse2 = true;
2122 }
2123 if (mouse3) {
2124 mouse3 = false;
2125 eventMouse3 = true;
2126 }
2127 int x = textColumn(mouse.getX());
2128 int y = textRow(mouse.getY());
2129
2130 TMouseEvent mouseEvent = new TMouseEvent(TMouseEvent.Type.MOUSE_UP,
2131 x, y, x, y, eventMouse1, eventMouse2, eventMouse3, false, false);
2132
2133 synchronized (eventQueue) {
2134 eventQueue.add(mouseEvent);
2135 resetBlinkTimer();
2136 }
2137 if (listener != null) {
2138 synchronized (listener) {
2139 listener.notifyAll();
2140 }
2141 }
2142 }
2143
2144 // ------------------------------------------------------------------------
2145 // MouseWheelListener -----------------------------------------------------
2146 // ------------------------------------------------------------------------
2147
2148 /**
2149 * Pass mouse events into the event queue.
2150 *
2151 * @param mouse mouse event received
2152 */
2153 public void mouseWheelMoved(final MouseWheelEvent mouse) {
2154 int modifiers = mouse.getModifiersEx();
2155 boolean eventMouse1 = false;
2156 boolean eventMouse2 = false;
2157 boolean eventMouse3 = false;
2158 boolean mouseWheelUp = false;
2159 boolean mouseWheelDown = false;
2160 if ((modifiers & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
2161 eventMouse1 = true;
2162 }
2163 if ((modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0) {
2164 eventMouse2 = true;
2165 }
2166 if ((modifiers & MouseEvent.BUTTON3_DOWN_MASK) != 0) {
2167 eventMouse3 = true;
2168 }
2169 mouse1 = eventMouse1;
2170 mouse2 = eventMouse2;
2171 mouse3 = eventMouse3;
2172 int x = textColumn(mouse.getX());
2173 int y = textRow(mouse.getY());
2174 if (mouse.getWheelRotation() > 0) {
2175 mouseWheelDown = true;
2176 }
2177 if (mouse.getWheelRotation() < 0) {
2178 mouseWheelUp = true;
2179 }
2180
2181 TMouseEvent mouseEvent = new TMouseEvent(TMouseEvent.Type.MOUSE_DOWN,
2182 x, y, x, y, mouse1, mouse2, mouse3, mouseWheelUp, mouseWheelDown);
2183
2184 synchronized (eventQueue) {
2185 eventQueue.add(mouseEvent);
2186 resetBlinkTimer();
2187 }
2188 if (listener != null) {
2189 synchronized (listener) {
2190 listener.notifyAll();
2191 }
2192 }
2193 }
2194
2195 }