1 /*
2 * Copyright (c) 2002-2025 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 * Keeps track of the typed keys.
24 *
25 * @author Ahmed Ashour
26 */
27 public class Keyboard {
28
29 private final List<Object[]> keys_ = new ArrayList<>();
30 private final boolean startAtEnd_;
31
32 /**
33 * Creates a new instance.
34 */
35 public Keyboard() {
36 this(false);
37 }
38
39 /**
40 * Creates a new instance, specifying whether typing should start at the text end or not.
41 * @param startAtEnd whether typing should start at the text end or not
42 */
43 public Keyboard(final boolean startAtEnd) {
44 startAtEnd_ = startAtEnd;
45 }
46
47 /**
48 * Types the specified character.
49 * @param ch the character
50 */
51 public void type(final char ch) {
52 keys_.add(new Object[] {ch});
53 }
54
55 /**
56 * Press the specified key code (without releasing it).
57 * <p>
58 * An example of predefined values is
59 * {@link org.htmlunit.javascript.host.event.KeyboardEvent#DOM_VK_PAGE_DOWN}.
60 *
61 * @param keyCode the key code
62 */
63 public void press(final int keyCode) {
64 if (keyCode >= KeyboardEvent.DOM_VK_A && keyCode <= KeyboardEvent.DOM_VK_Z) {
65 throw new IllegalArgumentException("For key code " + keyCode + ", use type(char) instead");
66 }
67 keys_.add(new Object[] {keyCode, true});
68 }
69
70 /**
71 * Releases the specified key code.
72 * <p>
73 * An example of predefined values is
74 * {@link org.htmlunit.javascript.host.event.KeyboardEvent#DOM_VK_PAGE_DOWN}.
75 *
76 * @param keyCode the key code.
77 */
78 public void release(final int keyCode) {
79 keys_.add(new Object[] {keyCode, false});
80 }
81
82 /**
83 * Clears all keys.
84 */
85 public void clear() {
86 keys_.clear();
87 }
88
89 /**
90 * Returns the keys.
91 * <p>
92 * If the length of the item is 1, then it is a character.
93 * If the length of the item is 2, the first is the key code, the second is boolean whether pressing or not
94 *
95 * @return the keys
96 */
97 List<Object[]> getKeys() {
98 return keys_;
99 }
100
101 /**
102 * Returns whether typing should start at the text end or not.
103 * @return whether typing should start at the text end or not
104 */
105 public boolean isStartAtEnd() {
106 return startAtEnd_;
107 }
108 }