summaryrefslogtreecommitdiff
path: root/NET/worlds/console/FocusPreservingTextField.java
blob: 57b656b042773c61af8ccda4935f5821c7bdf5e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package NET.worlds.console;

import NET.worlds.scape.EventQueue;
import NET.worlds.scape.Pilot;
import java.awt.Event;
import java.awt.Font;
import java.awt.TextField;

class FocusPreservingTextField extends TextField {
   private static final long serialVersionUID = 7475622191515920214L;
   private static FocusPreservingTextField lostFocus;
   private static FocusPreservingTextField hasFocus;
   private static FocusPreservingTextField chatLine;
   private static Object hasFocusMutex = new Object();
   private static Font font = new Font(Console.message("GammaTextFont"), 0, 12);
   boolean preserveFocus;
   boolean takeNextFocus;

   public FocusPreservingTextField() {
      super(30);
      this.setFocusable(true);
      this.setFont(font);
   }

   public void isChatLine() {
      chatLine = this;
   }

   @Override
   public void requestFocus() {
      if (!this.takeNextFocus) {
         synchronized (hasFocusMutex) {
            this.preserveFocus = hasFocus != null && hasFocus.getText().length() != 0 || chatLine != null && chatLine.getText().length() != 0;
         }
      } else {
         this.takeNextFocus = false;
      }

      if (!this.preserveFocus) {
         super.requestFocus();
      }
   }

   public void takeNextFocus() {
      this.preserveFocus = false;
      this.takeNextFocus = true;
   }

   @Override
   public boolean handleEvent(Event e) {
      synchronized (hasFocusMutex) {
         if (e.id == 1005) {
            if (hasFocus == this) {
               lostFocus = this;
               hasFocus = null;
               this.preserveFocus = false;
            }
         } else if (e.id == 1004) {
            hasFocus = this;
            if (this.preserveFocus && lostFocus != null) {
               lostFocus.takeNextFocus();
               lostFocus.requestFocus();
            }

            lostFocus = null;
            this.preserveFocus = false;
         }
      }

      if (e.id == 401) {
         Console.wake();
         if (e.key == 27) {
            this.setText("");
            return true;
         }

         if ((e.modifiers & 2) != 0 && e.key >= 1 && e.key <= 26 && e.key != 22) {
            Pilot pilot = Pilot.getActive();
            if (pilot != null) {
               pilot.animate("abcdefghijklmnopqrstuvwxyz".substring(e.key - 1, e.key));
            }

            return true;
         }
      }

      return EventQueue.redirectDrivingKeys(e) ? true : super.handleEvent(e);
   }
}