View Javadoc
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 static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_ADD;
18  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_BACK_SPACE;
19  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_DECIMAL;
20  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_DELETE;
21  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_DIVIDE;
22  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_DOWN;
23  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_END;
24  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_EQUALS;
25  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_HOME;
26  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_LEFT;
27  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_MULTIPLY;
28  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_NUMPAD0;
29  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_NUMPAD9;
30  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_RIGHT;
31  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_SEMICOLON;
32  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_SEPARATOR;
33  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_SPACE;
34  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_SUBTRACT;
35  import static org.htmlunit.javascript.host.event.KeyboardEvent.DOM_VK_UP;
36  
37  import java.io.Serializable;
38  import java.util.HashMap;
39  import java.util.Map;
40  
41  import org.htmlunit.ClipboardHandler;
42  import org.htmlunit.html.impl.SelectionDelegate;
43  
44  /**
45   * The processor for {@link HtmlElement#doType(char, boolean)}
46   * and {@link HtmlElement#doType(int, boolean)}.
47   *
48   * @author Marc Guillemot
49   * @author Ronald Brill
50   * @author Ahmed Ashour
51   */
52  class DoTypeProcessor implements Serializable {
53  
54      private static final Map<Integer, Character> SPECIAL_KEYS_MAP_ = new HashMap<>();
55  
56      /**
57       * Either {@link HtmlElement} or {@link DomText}.
58       */
59      private final DomNode domNode_;
60  
61      static {
62          SPECIAL_KEYS_MAP_.put(DOM_VK_ADD, '+');
63          SPECIAL_KEYS_MAP_.put(DOM_VK_DECIMAL, '.');
64          SPECIAL_KEYS_MAP_.put(DOM_VK_DIVIDE, '/');
65          SPECIAL_KEYS_MAP_.put(DOM_VK_EQUALS, '=');
66          SPECIAL_KEYS_MAP_.put(DOM_VK_MULTIPLY, '*');
67          SPECIAL_KEYS_MAP_.put(DOM_VK_SEMICOLON, ';');
68          SPECIAL_KEYS_MAP_.put(DOM_VK_SEPARATOR, ',');
69          SPECIAL_KEYS_MAP_.put(DOM_VK_SPACE, ' ');
70          SPECIAL_KEYS_MAP_.put(DOM_VK_SUBTRACT, '-');
71  
72          for (int i = DOM_VK_NUMPAD0; i <= DOM_VK_NUMPAD9; i++) {
73              SPECIAL_KEYS_MAP_.put(i, (char) ('0' + i - DOM_VK_NUMPAD0));
74          }
75      }
76  
77      DoTypeProcessor(final DomNode domNode) {
78          domNode_ = domNode;
79      }
80  
81      void doType(final String currentValue, final SelectionDelegate selectionDelegate,
82              final char c, final HtmlElement element, final boolean lastType) {
83  
84          int selectionStart = selectionDelegate.getSelectionStart();
85          selectionStart = Math.max(0, Math.min(selectionStart, currentValue.length()));
86  
87          int selectionEnd = selectionDelegate.getSelectionEnd();
88          selectionEnd = Math.max(selectionStart, Math.min(selectionEnd, currentValue.length()));
89  
90          final StringBuilder newValue = new StringBuilder(currentValue);
91          if (c == '\b') {
92              if (selectionStart > 0) {
93                  newValue.deleteCharAt(selectionStart - 1);
94                  selectionStart--;
95                  selectionEnd--;
96              }
97          }
98          else if (acceptChar(c)) {
99              final boolean ctrlKey = element.isCtrlPressed();
100             if (ctrlKey && (c == 'C' || c == 'c')) {
101                 final ClipboardHandler clipboardHandler = element.getPage().getWebClient().getClipboardHandler();
102                 if (clipboardHandler != null) {
103                     final String content = newValue.substring(selectionStart, selectionEnd);
104                     clipboardHandler.setClipboardContent(content);
105                 }
106             }
107             else if (ctrlKey && (c == 'V' || c == 'v')) {
108                 final ClipboardHandler clipboardHandler = element.getPage().getWebClient().getClipboardHandler();
109                 if (clipboardHandler != null) {
110                     final String content = clipboardHandler.getClipboardContent();
111                     add(newValue, content, selectionStart, selectionEnd);
112                     selectionStart += content.length();
113                     selectionEnd = selectionStart;
114                 }
115             }
116             else if (ctrlKey && (c == 'X' || c == 'x')) {
117                 final ClipboardHandler clipboardHandler = element.getPage().getWebClient().getClipboardHandler();
118                 if (clipboardHandler != null) {
119                     final String content = newValue.substring(selectionStart, selectionEnd);
120                     clipboardHandler.setClipboardContent(content);
121                     newValue.delete(selectionStart, selectionEnd);
122                     selectionEnd = selectionStart;
123                 }
124             }
125             else if (ctrlKey && (c == 'A' || c == 'a')) {
126                 selectionStart = 0;
127                 selectionEnd = newValue.length();
128             }
129             else if (!element.isTypingSuppressedByModifiers()) {
130                 // like in the browsers, control (or for some browsers meta) together with a char does not type it
131                 add(newValue, c, selectionStart, selectionEnd);
132                 selectionStart++;
133                 selectionEnd = selectionStart;
134             }
135         }
136 
137         typeDone(newValue.toString(), lastType);
138 
139         selectionDelegate.setSelectionStart(selectionStart);
140         selectionDelegate.setSelectionEnd(selectionEnd);
141     }
142 
143     private static void add(final StringBuilder newValue, final char c, final int selectionStart,
144             final int selectionEnd) {
145         if (selectionStart == newValue.length()) {
146             newValue.append(c);
147         }
148         else {
149             newValue.replace(selectionStart, selectionEnd, Character.toString(c));
150         }
151     }
152 
153     private static void add(final StringBuilder newValue, final String string, final int selectionStart,
154             final int selectionEnd) {
155         if (selectionStart == newValue.length()) {
156             newValue.append(string);
157         }
158         else {
159             newValue.replace(selectionStart, selectionEnd, string);
160         }
161     }
162 
163     private void typeDone(final String newValue, final boolean notifyAttributeChangeListeners) {
164         if (domNode_ instanceof DomText text) {
165             text.setData(newValue);
166         }
167         else {
168             ((HtmlElement) domNode_).typeDone(newValue, notifyAttributeChangeListeners);
169         }
170     }
171 
172     private boolean acceptChar(final char ch) {
173         if (domNode_ instanceof DomText text) {
174             return text.acceptChar(ch);
175         }
176         return ((HtmlElement) domNode_).acceptChar(ch);
177     }
178 
179     void doType(final String currentValue, final SelectionDelegate selectionDelegate,
180             final int keyCode, final HtmlElement element, final boolean lastType) {
181 
182         int selectionStart = selectionDelegate.getSelectionStart();
183         selectionStart = Math.max(0, Math.min(selectionStart, currentValue.length()));
184 
185         int selectionEnd = selectionDelegate.getSelectionEnd();
186         selectionEnd = Math.max(selectionStart, Math.min(selectionEnd, currentValue.length()));
187 
188         final Character ch = SPECIAL_KEYS_MAP_.get(keyCode);
189         if (ch != null) {
190             doType(currentValue, selectionDelegate, ch, element, lastType);
191             return;
192         }
193 
194         final StringBuilder newValue = new StringBuilder(currentValue);
195         switch (keyCode) {
196             case DOM_VK_BACK_SPACE:
197                 if (selectionEnd != selectionStart) {
198                     newValue.delete(selectionStart, selectionEnd);
199                     selectionEnd = selectionStart;
200                     break;
201                 }
202 
203                 if (selectionStart > 0) {
204                     if (element.isCtrlPressed()) {
205                         int targetStart = selectionStart;
206                         while (targetStart > 0 && Character.isWhitespace(newValue.charAt(targetStart - 1))) {
207                             targetStart--;
208                         }
209                         while (targetStart > 0 && !Character.isWhitespace(newValue.charAt(targetStart - 1))) {
210                             targetStart--;
211                         }
212                         newValue.delete(targetStart, selectionStart);
213                         selectionStart = targetStart;
214                     }
215                     else {
216                         newValue.deleteCharAt(selectionStart - 1);
217                         selectionStart--;
218                     }
219                 }
220                 break;
221 
222             case DOM_VK_LEFT:
223                 if (element.isCtrlPressed()) {
224                     int targetPos = selectionStart;
225                     // 1. Skip whitespace to the left of caret
226                     while (targetPos > 0 && Character.isWhitespace(newValue.charAt(targetPos - 1))) {
227                         targetPos--;
228                     }
229                     // 2. Skip word characters to the left
230                     while (targetPos > 0 && !Character.isWhitespace(newValue.charAt(targetPos - 1))) {
231                         targetPos--;
232                     }
233                     selectionStart = targetPos;
234                 }
235                 else if (element.isShiftPressed()) {
236                     if (selectionStart > 0) {
237                         selectionStart--;
238                     }
239                 }
240                 else if (selectionStart > 0) {
241                     selectionStart--;
242                 }
243                 break;
244 
245             case DOM_VK_RIGHT:
246                 if (element.isCtrlPressed()) {
247                     int targetPos = selectionStart;
248                     // 1. Skip word characters to the right
249                     while (targetPos < newValue.length() && !Character.isWhitespace(newValue.charAt(targetPos))) {
250                         targetPos++;
251                     }
252                     // 2. Skip whitespace to the right
253                     while (targetPos < newValue.length() && Character.isWhitespace(newValue.charAt(targetPos))) {
254                         targetPos++;
255                     }
256                     if (element.isShiftPressed()) {
257                         selectionEnd = targetPos;
258                     }
259                     else {
260                         selectionStart = targetPos;
261                     }
262                 }
263                 else if (element.isShiftPressed()) {
264                     if (selectionEnd < newValue.length()) {
265                         selectionEnd++;
266                     }
267                 }
268                 else if (selectionStart < newValue.length()) {
269                     selectionStart++;
270                 }
271                 break;
272 
273             case DOM_VK_UP:
274                 final int lastLfUp = currentValue.lastIndexOf('\n', selectionStart - 1);
275                 final int lastCrUp = currentValue.lastIndexOf('\r', selectionStart - 1);
276                 final int lastBreakUp = Math.max(lastLfUp, lastCrUp);
277 
278                 if (lastBreakUp == -1) {
279                     selectionStart = 0;
280                 }
281                 else {
282                     final int currentLineStart = lastBreakUp + 1;
283                     final int column = selectionStart - currentLineStart;
284 
285                     final int prevLineEnd = (lastBreakUp > 0 && newValue.charAt(lastBreakUp) == '\n'
286                             && newValue.charAt(lastBreakUp - 1) == '\r') ? lastBreakUp - 1 : lastBreakUp;
287 
288                     final int prevLf = currentValue.lastIndexOf('\n', prevLineEnd - 1);
289                     final int prevCr = currentValue.lastIndexOf('\r', prevLineEnd - 1);
290                     final int prevBreak = Math.max(prevLf, prevCr);
291 
292                     final int prevLineStart = (prevBreak == -1) ? 0 : prevBreak + 1;
293                     final int prevLineLength = prevLineEnd - prevLineStart;
294 
295                     selectionStart = prevLineStart + Math.min(column, prevLineLength);
296                 }
297                 break;
298 
299             case DOM_VK_DOWN:
300                 final int lastLfDown = currentValue.lastIndexOf('\n', selectionStart - 1);
301                 final int lastCrDown = currentValue.lastIndexOf('\r', selectionStart - 1);
302                 final int lastBreakDown = Math.max(lastLfDown, lastCrDown);
303                 final int currentLineStartDown = (lastBreakDown == -1) ? 0 : lastBreakDown + 1;
304                 final int columnDown = selectionStart - currentLineStartDown;
305 
306                 final int nextLfDown = currentValue.indexOf('\n', selectionStart);
307                 final int nextCrDown = currentValue.indexOf('\r', selectionStart);
308                 final int nextBreakDown;
309                 if (nextLfDown == -1) {
310                     nextBreakDown = nextCrDown;
311                 }
312                 else if (nextCrDown == -1) {
313                     nextBreakDown = nextLfDown;
314                 }
315                 else {
316                     nextBreakDown = Math.min(nextLfDown, nextCrDown);
317                 }
318 
319                 final int targetDown;
320                 if (nextBreakDown == -1) {
321                     targetDown = newValue.length();
322                 }
323                 else {
324                     int nextLineStart = nextBreakDown + 1;
325                     if (newValue.charAt(nextBreakDown) == '\r' && nextLineStart < newValue.length()
326                             && newValue.charAt(nextLineStart) == '\n') {
327                         nextLineStart++;
328                     }
329 
330                     final int followingLf = currentValue.indexOf('\n', nextLineStart);
331                     final int followingCr = currentValue.indexOf('\r', nextLineStart);
332                     final int followingBreak;
333                     if (followingLf == -1) {
334                         followingBreak = followingCr;
335                     }
336                     else if (followingCr == -1) {
337                         followingBreak = followingLf;
338                     }
339                     else {
340                         followingBreak = Math.min(followingLf, followingCr);
341                     }
342 
343                     final int nextLineEnd = (followingBreak == -1) ? newValue.length() : followingBreak;
344                     final int nextLineLength = nextLineEnd - nextLineStart;
345 
346                     targetDown = nextLineStart + Math.min(columnDown, nextLineLength);
347                 }
348 
349                 if (element.isShiftPressed()) {
350                     selectionEnd = targetDown;
351                 }
352                 else {
353                     selectionStart = targetDown;
354                 }
355                 break;
356 
357             case DOM_VK_HOME:
358                 final int targetHome;
359                 if (element.isCtrlPressed()) {
360                     targetHome = 0;
361                 }
362                 else {
363                     final int lastLf = currentValue.lastIndexOf('\n', selectionStart - 1);
364                     final int lastCr = currentValue.lastIndexOf('\r', selectionStart - 1);
365                     // Use Math.max to find the closest line break before the caret,
366                     // so the line start is positioned right after it
367                     final int lastBreak = Math.max(lastLf, lastCr);
368                     targetHome = (lastBreak == -1) ? 0 : lastBreak + 1;
369                 }
370 
371                 if (element.isShiftPressed()) {
372                     selectionStart = targetHome;
373                 }
374                 else {
375                     selectionStart = targetHome;
376                     selectionEnd = targetHome;
377                 }
378                 break;
379 
380             case DOM_VK_END:
381                 int targetEnd;
382                 if (element.isCtrlPressed()) {
383                     targetEnd = newValue.length();
384                 }
385                 else {
386                     final int nextLf = currentValue.indexOf('\n', selectionStart);
387                     final int nextCr = currentValue.indexOf('\r', selectionStart);
388                     if (nextLf == -1) {
389                         targetEnd = nextCr;
390                     }
391                     else if (nextCr == -1) {
392                         targetEnd = nextLf;
393                     }
394                     else {
395                         targetEnd = Math.min(nextLf, nextCr);
396                     }
397                     if (targetEnd == -1) {
398                         targetEnd = newValue.length();
399                     }
400                 }
401 
402                 if (element.isShiftPressed()) {
403                     selectionEnd = targetEnd;
404                 }
405                 else {
406                     selectionStart = targetEnd;
407                 }
408                 break;
409 
410             case DOM_VK_DELETE:
411                 if (selectionEnd != selectionStart) {
412                     newValue.delete(selectionStart, selectionEnd);
413                     selectionEnd = selectionStart;
414                     break;
415                 }
416 
417                 if (selectionStart < newValue.length()) {
418                     if (element.isCtrlPressed()) {
419                         int delTargetEnd = selectionStart;
420                         // 1. Skip initial whitespace at caret (if caret is on a space)
421                         while (delTargetEnd < newValue.length()
422                                 && Character.isWhitespace(newValue.charAt(delTargetEnd))) {
423                             delTargetEnd++;
424                         }
425                         // 2. Skip word characters
426                         while (delTargetEnd < newValue.length()
427                                 && !Character.isWhitespace(newValue.charAt(delTargetEnd))) {
428                             delTargetEnd++;
429                         }
430                         // 3. Skip trailing whitespace after the word
431                         while (delTargetEnd < newValue.length()
432                                 && Character.isWhitespace(newValue.charAt(delTargetEnd))) {
433                             delTargetEnd++;
434                         }
435                         newValue.delete(selectionStart, delTargetEnd);
436                     }
437                     else {
438                         newValue.deleteCharAt(selectionStart);
439                     }
440                 }
441                 break;
442 
443             default:
444                 return;
445         }
446 
447         if (!element.isShiftPressed()) {
448             selectionEnd = selectionStart;
449         }
450 
451         typeDone(newValue.toString(), lastType);
452 
453         selectionDelegate.setSelectionStart(selectionStart);
454         selectionDelegate.setSelectionEnd(selectionEnd);
455     }
456 }