1 /*
2 * Copyright (c) 2002-2026 Gargoyle Software Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit.html;
16
17 import java.util.ArrayList;
18 import java.util.List;
19
20 import org.htmlunit.javascript.host.event.KeyboardEvent;
21
22 /**
23 * Represents a sequence of keyboard actions—such as typed characters, key presses,
24 * and key releases—used to simulate realistic user input on HTML elements.
25 * <p>
26 * A {@code Keyboard} instance acts as a keystroke recorder that queues key actions
27 * and maintains modifier state ({@code SHIFT}, {@code CONTROL}, {@code ALT}, {@code META}) across
28 * sequential events. When executed against an element via {@code element.type(keyboard)},
29 * it drives the full browser event lifecycle ({@code keydown}, {@code keypress},
30 * {@code input}, and {@code keyup}) and mutates DOM text values accordingly.
31 * </p>
32 *
33 * <h3>Core Features</h3>
34 * <ul>
35 * <li><b>Character and Key Code Queuing:</b> Supports typing printable characters as well
36 * as holding and releasing raw key codes (e.g., navigation, {@code BACK_SPACE}, or modifier keys).</li>
37 * <li><b>Modifier State Persistence:</b> Tracks modifier keys so subsequent keystrokes inherit
38 * the active modifier flags during JavaScript event dispatching.</li>
39 * <li><b>Caret Positioning:</b> Supports configured cursor placement ({@link #isStartAtEnd()})
40 * to position the selection caret at the end of input fields before typing begins.</li>
41 * </ul>
42 *
43 * @author Ahmed Ashour
44 * @author Ronald Brill
45 */
46 public class Keyboard {
47
48 /**
49 * Represents a single keyboard input action.
50 *
51 * <p>A {@code KeyAction} is either a typed character ({@link TypedChar}),
52 * a key-code press or release ({@link KeyCodeAction}) or a single key down or
53 * key up of a character ({@link CharKeyAction}) or a key code ({@link KeyCodeKeyAction}).
54 * </p>
55 */
56 public sealed interface KeyAction permits TypedChar, KeyCodeAction, CharKeyAction, KeyCodeKeyAction {
57 // tagging interface
58 }
59
60 /**
61 * A character typed directly, e.g. via {@link Keyboard#type(char)}.
62 *
63 * @param ch the typed character
64 */
65 public record TypedChar(char ch) implements KeyAction { }
66
67 /**
68 * A key-code press or release, e.g. via {@link Keyboard#press(int)}
69 * or {@link Keyboard#release(int)}.
70 *
71 * @param keyCode the DOM key code
72 * @param pressed {@code true} if the key is being pressed,
73 * {@code false} if it is being released
74 */
75 public record KeyCodeAction(int keyCode, boolean pressed) implements KeyAction { }
76
77 /**
78 * Only the key down or only the key up of a character, e.g. via {@link Keyboard#keyDown(char)}
79 * or {@link Keyboard#keyUp(char)}.
80 *
81 * @param ch the character
82 * @param down {@code true} for the key down, {@code false} for the key up
83 */
84 public record CharKeyAction(char ch, boolean down) implements KeyAction { }
85
86 /**
87 * Only the key down or only the key up of a key code, e.g. via {@link Keyboard#keyDown(int)}
88 * or {@link Keyboard#keyUp(int, int)}.
89 *
90 * @param keyCode the DOM key code
91 * @param location the location of the key (e.g. {@link KeyboardEvent#DOM_KEY_LOCATION_RIGHT})
92 * or {@link #DEFAULT_LOCATION} for the default location of the key code
93 * @param down {@code true} for the key down, {@code false} for the key up
94 */
95 public record KeyCodeKeyAction(int keyCode, int location, boolean down) implements KeyAction { }
96
97 /** Use the default location of the key code (e.g. the left one for the shift key). */
98 public static final int DEFAULT_LOCATION = -1;
99
100 private final List<KeyAction> keys_ = new ArrayList<>();
101 private final boolean startAtEnd_;
102 private boolean[] modifiers_;
103
104 /**
105 * Creates a new instance.
106 */
107 public Keyboard() {
108 this(false);
109 }
110
111 /**
112 * Creates a new instance, specifying whether typing should start at the text end or not.
113 * @param startAtEnd whether typing should start at the text end or not
114 */
115 public Keyboard(final boolean startAtEnd) {
116 startAtEnd_ = startAtEnd;
117 }
118
119 /**
120 * Types the specified character.
121 * @param ch the character
122 */
123 public void type(final char ch) {
124 keys_.add(new TypedChar(ch));
125 }
126
127 /**
128 * Press the specified key code (without releasing it).
129 * <p>
130 * An example of predefined values is
131 * {@link org.htmlunit.javascript.host.event.KeyboardEvent#DOM_VK_PAGE_DOWN}.
132 * </p>
133 *
134 * @param keyCode the key code
135 */
136 public void press(final int keyCode) {
137 if (keyCode >= KeyboardEvent.DOM_VK_A && keyCode <= KeyboardEvent.DOM_VK_Z) {
138 throw new IllegalArgumentException("For key code " + keyCode + ", use type(char) instead");
139 }
140 keys_.add(new KeyCodeAction(keyCode, true));
141 }
142
143 /**
144 * Releases the specified key code.
145 * <p>
146 * An example of predefined values is
147 * {@link org.htmlunit.javascript.host.event.KeyboardEvent#DOM_VK_PAGE_DOWN}.
148 * </p>
149 *
150 * @param keyCode the key code.
151 */
152 public void release(final int keyCode) {
153 if (keyCode >= KeyboardEvent.DOM_VK_A && keyCode <= KeyboardEvent.DOM_VK_Z) {
154 throw new IllegalArgumentException("For key code " + keyCode + ", use type(char) instead");
155 }
156 keys_.add(new KeyCodeAction(keyCode, false));
157 }
158
159 /**
160 * Presses only the key of the specified character; the key stays pressed until
161 * {@link #keyUp(char)} is called for the same character. Like in the browsers, the
162 * {@code keydown} and {@code keypress} events are fired and the character is typed.
163 *
164 * @param ch the character
165 */
166 public void keyDown(final char ch) {
167 keys_.add(new CharKeyAction(ch, true));
168 }
169
170 /**
171 * Releases the key of the specified character pressed by {@link #keyDown(char)};
172 * only the {@code keyup} event is fired.
173 *
174 * @param ch the character
175 */
176 public void keyUp(final char ch) {
177 keys_.add(new CharKeyAction(ch, false));
178 }
179
180 /**
181 * Presses only the specified key code; the key stays pressed until {@link #keyUp(int)}
182 * is called for the same key code (in contrast to {@link #press(int)} no {@code keyup}
183 * is fired for keys that are not modifiers).
184 *
185 * @param keyCode the key code (e.g. {@link KeyboardEvent#DOM_VK_LEFT})
186 */
187 public void keyDown(final int keyCode) {
188 keyDown(keyCode, DEFAULT_LOCATION);
189 }
190
191 /**
192 * Presses only the specified key code at the specified location; the key stays pressed
193 * until {@link #keyUp(int, int)} is called for the same key.
194 *
195 * @param keyCode the key code (e.g. {@link KeyboardEvent#DOM_VK_SHIFT})
196 * @param location the location of the key (e.g. {@link KeyboardEvent#DOM_KEY_LOCATION_RIGHT}
197 * for the right shift key) or {@link #DEFAULT_LOCATION}
198 */
199 public void keyDown(final int keyCode, final int location) {
200 checkKeyCode(keyCode);
201 keys_.add(new KeyCodeKeyAction(keyCode, location, true));
202 }
203
204 /**
205 * Releases the specified key code pressed by {@link #keyDown(int)}; only the
206 * {@code keyup} event is fired.
207 *
208 * @param keyCode the key code (e.g. {@link KeyboardEvent#DOM_VK_LEFT})
209 */
210 public void keyUp(final int keyCode) {
211 keyUp(keyCode, DEFAULT_LOCATION);
212 }
213
214 /**
215 * Releases the specified key code at the specified location pressed by
216 * {@link #keyDown(int, int)}; only the {@code keyup} event is fired.
217 *
218 * @param keyCode the key code (e.g. {@link KeyboardEvent#DOM_VK_SHIFT})
219 * @param location the location of the key (e.g. {@link KeyboardEvent#DOM_KEY_LOCATION_RIGHT}
220 * for the right shift key) or {@link #DEFAULT_LOCATION}
221 */
222 public void keyUp(final int keyCode, final int location) {
223 checkKeyCode(keyCode);
224 keys_.add(new KeyCodeKeyAction(keyCode, location, false));
225 }
226
227 private static void checkKeyCode(final int keyCode) {
228 if (keyCode >= KeyboardEvent.DOM_VK_A && keyCode <= KeyboardEvent.DOM_VK_Z) {
229 throw new IllegalArgumentException("For key code " + keyCode + ", use keyDown(char) instead");
230 }
231 }
232
233 /**
234 * Sets the state of the modifier keys that are already pressed when this keyboard is typed
235 * (e.g. pressed by a previous keyboard); no events are fired for these keys.
236 *
237 * @param shift whether the shift key is pressed
238 * @param ctrl whether the control key is pressed
239 * @param alt whether the alt key is pressed
240 * @param meta whether the meta key is pressed
241 */
242 public void setPressedModifiers(final boolean shift, final boolean ctrl, final boolean alt, final boolean meta) {
243 modifiers_ = new boolean[] {shift, ctrl, alt, meta};
244 }
245
246 /**
247 * Returns the state of the already pressed modifier keys set by
248 * {@link #setPressedModifiers(boolean, boolean, boolean, boolean)}.
249 *
250 * @return the state of the shift, control, alt and meta keys or {@code null} if not set
251 */
252 boolean[] getPressedModifiers() {
253 return modifiers_;
254 }
255
256 /**
257 * Clears all keys.
258 */
259 public void clear() {
260 keys_.clear();
261 }
262
263 /**
264 * Returns the keys.
265 *
266 * @return the key actions
267 */
268 List<KeyAction> getKeys() {
269 return keys_;
270 }
271
272 /**
273 * Returns whether typing should start at the text end or not.
274 * @return whether typing should start at the text end or not
275 */
276 public boolean isStartAtEnd() {
277 return startAtEnd_;
278 }
279 }