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