1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.html;
16
17 import static org.htmlunit.BrowserVersionFeatures.HTMLELEMENT_REMOVE_ACTIVE_TRIGGERS_BLUR_EVENT;
18 import static org.htmlunit.BrowserVersionFeatures.KEYBOARD_EVENT_META_NO_KEYPRESS;
19 import static org.htmlunit.css.CssStyleSheet.ABSOLUTE;
20 import static org.htmlunit.css.CssStyleSheet.FIXED;
21 import static org.htmlunit.css.CssStyleSheet.STATIC;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Locale;
27 import java.util.Map;
28 import java.util.Set;
29
30 import org.htmlunit.ClipboardHandler;
31 import org.htmlunit.ElementNotFoundException;
32 import org.htmlunit.Page;
33 import org.htmlunit.ScriptResult;
34 import org.htmlunit.SgmlPage;
35 import org.htmlunit.WebAssert;
36 import org.htmlunit.WebClient;
37 import org.htmlunit.WebWindow;
38 import org.htmlunit.css.ComputedCssStyleDeclaration;
39 import org.htmlunit.html.impl.SelectableTextInput;
40 import org.htmlunit.javascript.HtmlUnitScriptable;
41 import org.htmlunit.javascript.host.dom.Document;
42 import org.htmlunit.javascript.host.dom.MutationObserver;
43 import org.htmlunit.javascript.host.event.Event;
44 import org.htmlunit.javascript.host.event.EventTarget;
45 import org.htmlunit.javascript.host.event.InputEvent;
46 import org.htmlunit.javascript.host.event.KeyboardEvent;
47 import org.htmlunit.javascript.host.html.HTMLDocument;
48 import org.htmlunit.javascript.host.html.HTMLElement;
49 import org.htmlunit.util.StringUtils;
50 import org.w3c.dom.Attr;
51 import org.w3c.dom.CDATASection;
52 import org.w3c.dom.Comment;
53 import org.w3c.dom.DOMException;
54 import org.w3c.dom.Element;
55 import org.w3c.dom.EntityReference;
56 import org.w3c.dom.Node;
57 import org.w3c.dom.ProcessingInstruction;
58 import org.w3c.dom.Text;
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80 public abstract class HtmlElement extends DomElement {
81
82
83
84
85 public enum DisplayStyle {
86
87 EMPTY(""),
88
89 NONE("none"),
90
91 BLOCK("block"),
92
93 CONTENTS("contents"),
94
95 INLINE("inline"),
96
97 INLINE_BLOCK("inline-block"),
98
99 LIST_ITEM("list-item"),
100
101 TABLE("table"),
102
103 TABLE_CELL("table-cell"),
104
105 TABLE_COLUMN("table-column"),
106
107 TABLE_COLUMN_GROUP("table-column-group"),
108
109 TABLE_ROW("table-row"),
110
111 TABLE_ROW_GROUP("table-row-group"),
112
113 TABLE_HEADER_GROUP("table-header-group"),
114
115 TABLE_FOOTER_GROUP("table-footer-group"),
116
117 TABLE_CAPTION("table-caption"),
118
119 RUBY("ruby"),
120
121 RUBY_BASE("ruby-base"),
122
123 RUBY_TEXT("ruby-text"),
124
125 RUBY_TEXT_CONTAINER("ruby-text-container");
126
127 private final String value_;
128 DisplayStyle(final String value) {
129 value_ = value;
130 }
131
132
133
134
135
136 public String value() {
137 return value_;
138 }
139 }
140
141
142
143
144
145
146
147 public static final Short TAB_INDEX_OUT_OF_BOUNDS = Short.valueOf(Short.MIN_VALUE);
148
149
150 protected static final String ATTRIBUTE_REQUIRED = "required";
151
152 protected static final String ATTRIBUTE_CHECKED = "checked";
153
154 protected static final String ATTRIBUTE_HIDDEN = "hidden";
155
156 protected static final String ATTRIBUTE_READONLY = "readonly";
157
158
159
160
161
162
163 private static final Set<String> VOID_ELEMENTS = Set.of("area", "base", "basefont", "bgsound", "br", "col",
164 "embed", "frame", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr");
165
166
167 private final List<HtmlAttributeChangeListener> attributeListeners_ = new ArrayList<>();
168
169
170 private HtmlForm owningForm_;
171
172 private boolean shiftPressed_;
173 private boolean ctrlPressed_;
174 private boolean altPressed_;
175 private boolean metaPressed_;
176
177
178
179
180
181
182
183
184
185 protected HtmlElement(final String qualifiedName, final SgmlPage page,
186 final Map<String, DomAttr> attributes) {
187 this(Html.XHTML_NAMESPACE, qualifiedName, page, attributes);
188 }
189
190
191
192
193
194
195
196
197
198
199 protected HtmlElement(final String namespaceURI, final String qualifiedName, final SgmlPage page,
200 final Map<String, DomAttr> attributes) {
201 super(namespaceURI, qualifiedName, page, attributes);
202 }
203
204
205
206
207 @Override
208 protected void setAttributeNS(final String namespaceURI, final String qualifiedName,
209 final String attributeValue, final boolean notifyAttributeChangeListeners,
210 final boolean notifyMutationObservers) {
211
212 final HtmlPage htmlPage = getHtmlPageOrNull();
213
214
215 if (htmlPage == null) {
216 super.setAttributeNS(namespaceURI, qualifiedName, attributeValue, notifyAttributeChangeListeners,
217 notifyMutationObservers);
218 return;
219 }
220
221 final String oldAttributeValue = getAttribute(qualifiedName);
222 final boolean mappedElement = isAttachedToPage()
223 && (DomElement.NAME_ATTRIBUTE.equals(qualifiedName) || DomElement.ID_ATTRIBUTE.equals(qualifiedName));
224 if (mappedElement) {
225
226 htmlPage.removeMappedElement(this, false, false);
227 }
228
229 final HtmlAttributeChangeEvent event;
230 if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
231 event = new HtmlAttributeChangeEvent(this, qualifiedName, attributeValue);
232 }
233 else {
234 event = new HtmlAttributeChangeEvent(this, qualifiedName, oldAttributeValue);
235 }
236
237 super.setAttributeNS(namespaceURI, qualifiedName, attributeValue, notifyAttributeChangeListeners,
238 notifyMutationObservers);
239
240 if (notifyAttributeChangeListeners) {
241 notifyAttributeChangeListeners(event, this, oldAttributeValue, notifyMutationObservers);
242 }
243
244 fireAttributeChangeImpl(event, htmlPage, mappedElement, oldAttributeValue);
245 }
246
247
248
249
250
251
252
253
254 protected static void notifyAttributeChangeListeners(final HtmlAttributeChangeEvent event,
255 final HtmlElement element, final String oldAttributeValue, final boolean notifyMutationObservers) {
256 final List<HtmlAttributeChangeListener> listeners = new ArrayList<>(element.attributeListeners_);
257 if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
258 synchronized (listeners) {
259 for (final HtmlAttributeChangeListener listener : listeners) {
260 if (notifyMutationObservers || !(listener instanceof MutationObserver)) {
261 listener.attributeAdded(event);
262 }
263 }
264 }
265 }
266 else {
267 synchronized (listeners) {
268 for (final HtmlAttributeChangeListener listener : listeners) {
269 if (notifyMutationObservers || !(listener instanceof MutationObserver)) {
270 listener.attributeReplaced(event);
271 }
272 }
273 }
274 }
275
276 final DomNode parentNode = element.getParentNode();
277 if (parentNode instanceof HtmlElement htmlElement) {
278 notifyAttributeChangeListeners(event, htmlElement, oldAttributeValue, notifyMutationObservers);
279 }
280 }
281
282 private void fireAttributeChangeImpl(final HtmlAttributeChangeEvent event,
283 final HtmlPage htmlPage, final boolean mappedElement, final String oldAttributeValue) {
284 if (mappedElement) {
285 htmlPage.addMappedElement(this, false);
286 }
287
288 if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
289 fireHtmlAttributeAdded(event);
290 htmlPage.fireHtmlAttributeAdded(event);
291 }
292 else {
293 fireHtmlAttributeReplaced(event);
294 htmlPage.fireHtmlAttributeReplaced(event);
295 }
296 }
297
298
299
300
301
302
303
304
305
306
307 @Override
308 public Attr setAttributeNode(final Attr attribute) {
309 final HtmlPage htmlPage = getHtmlPageOrNull();
310
311
312 if (htmlPage == null) {
313 return super.setAttributeNode(attribute);
314 }
315
316 final String qualifiedName = attribute.getName();
317 final String oldAttributeValue = getAttribute(qualifiedName);
318
319 final boolean mappedElement = isAttachedToPage()
320 && (DomElement.NAME_ATTRIBUTE.equals(qualifiedName)
321 || DomElement.ID_ATTRIBUTE.equals(qualifiedName));
322 if (mappedElement) {
323 htmlPage.removeMappedElement(this, false, false);
324 }
325
326 final HtmlAttributeChangeEvent event;
327 if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
328 event = new HtmlAttributeChangeEvent(this, qualifiedName, attribute.getValue());
329 }
330 else {
331 event = new HtmlAttributeChangeEvent(this, qualifiedName, oldAttributeValue);
332 }
333 notifyAttributeChangeListeners(event, this, oldAttributeValue, true);
334
335 final Attr result = super.setAttributeNode(attribute);
336
337 fireAttributeChangeImpl(event, htmlPage, mappedElement, oldAttributeValue);
338
339 return result;
340 }
341
342
343
344
345
346 @Override
347 public void removeAttribute(final String attributeName) {
348 final String value = getAttribute(attributeName);
349 if (ATTRIBUTE_NOT_DEFINED == value) {
350 return;
351 }
352
353 final HtmlPage htmlPage = getHtmlPageOrNull();
354
355
356 if (htmlPage == null) {
357 super.removeAttribute(attributeName);
358 return;
359 }
360
361 final boolean mapped = DomElement.NAME_ATTRIBUTE.equals(attributeName)
362 || DomElement.ID_ATTRIBUTE.equals(attributeName);
363 if (mapped) {
364 htmlPage.removeMappedElement(this, false, false);
365 }
366
367 super.removeAttribute(attributeName);
368
369 if (mapped) {
370 htmlPage.addMappedElement(this, false);
371 }
372
373 final HtmlAttributeChangeEvent event = new HtmlAttributeChangeEvent(this, attributeName, value);
374 fireHtmlAttributeRemoved(event);
375 htmlPage.fireHtmlAttributeRemoved(event);
376 }
377
378
379
380
381
382
383
384
385
386
387
388
389
390 protected void fireHtmlAttributeAdded(final HtmlAttributeChangeEvent event) {
391 final DomNode parentNode = getParentNode();
392 if (parentNode instanceof HtmlElement element) {
393 element.fireHtmlAttributeAdded(event);
394 }
395 }
396
397
398
399
400
401
402
403
404
405
406
407
408
409 protected void fireHtmlAttributeReplaced(final HtmlAttributeChangeEvent event) {
410 final DomNode parentNode = getParentNode();
411 if (parentNode instanceof HtmlElement element) {
412 element.fireHtmlAttributeReplaced(event);
413 }
414 }
415
416
417
418
419
420
421
422
423
424
425
426
427
428 protected void fireHtmlAttributeRemoved(final HtmlAttributeChangeEvent event) {
429 synchronized (attributeListeners_) {
430 for (final HtmlAttributeChangeListener listener : attributeListeners_) {
431 listener.attributeRemoved(event);
432 }
433 }
434 final DomNode parentNode = getParentNode();
435 if (parentNode instanceof HtmlElement element) {
436 element.fireHtmlAttributeRemoved(event);
437 }
438 }
439
440
441
442
443
444
445 @Override
446 public String getNodeName() {
447 final String prefix = getPrefix();
448 if (prefix != null) {
449
450 final StringBuilder name = new StringBuilder(prefix.toLowerCase(Locale.ROOT))
451 .append(':')
452 .append(getLocalName().toLowerCase(Locale.ROOT));
453 return name.toString();
454 }
455 return getLocalName().toLowerCase(Locale.ROOT);
456 }
457
458
459
460
461
462
463
464
465
466 public Short getTabIndex() {
467 final String index = getAttributeDirect("tabindex");
468 if (index == null || index.isEmpty()) {
469 return null;
470 }
471 try {
472 final long l = Long.parseLong(index);
473 if (l >= 0 && l <= Short.MAX_VALUE) {
474 return Short.valueOf((short) l);
475 }
476 return TAB_INDEX_OUT_OF_BOUNDS;
477 }
478 catch (final NumberFormatException e) {
479 return null;
480 }
481 }
482
483
484
485
486
487
488
489 public HtmlElement getEnclosingElement(final String tagName) {
490 final String tagNameLC = tagName.toLowerCase(Locale.ROOT);
491
492 for (DomNode currentNode = getParentNode(); currentNode != null; currentNode = currentNode.getParentNode()) {
493 if (currentNode instanceof HtmlElement element && currentNode.getNodeName().equals(tagNameLC)) {
494 return element;
495 }
496 }
497 return null;
498 }
499
500
501
502
503
504
505 public HtmlForm getEnclosingForm() {
506 final String formId = getAttribute("form");
507 if (ATTRIBUTE_NOT_DEFINED != formId) {
508 final Element formById = getPage().getElementById(formId);
509 if (formById instanceof HtmlForm form) {
510 return form;
511 }
512 return null;
513 }
514
515 if (owningForm_ != null) {
516 return owningForm_;
517 }
518 return (HtmlForm) getEnclosingElement("form");
519 }
520
521
522
523
524
525
526 public HtmlForm getEnclosingFormOrDie() {
527 final HtmlForm form = getEnclosingForm();
528 if (form == null) {
529 throw new IllegalStateException("Element is not contained within a form: " + this);
530 }
531 return form;
532 }
533
534
535
536
537
538
539
540 public void type(final String text) throws IOException {
541 for (final char ch : text.toCharArray()) {
542 type(ch);
543 }
544 }
545
546
547
548
549
550
551
552
553
554
555
556 public Page type(final char c) throws IOException {
557 return type(c, true);
558 }
559
560
561
562
563
564
565
566
567
568
569
570
571 private Page type(final char c, final boolean lastType)
572 throws IOException {
573 return typeChar(c, lastType, true, true);
574 }
575
576
577
578
579
580
581
582
583
584
585
586 private Page typeChar(final char c, final boolean lastType, final boolean fireDown, final boolean fireUp)
587 throws IOException {
588 if (isDisabledElementAndDisabled()) {
589 return getPage();
590 }
591
592
593 final HtmlPage page = (HtmlPage) getPage();
594 page.getWebClient().setCurrentWindow(page.getEnclosingWindow());
595
596 if (page.getFocusedElement() != this) {
597 focus();
598 }
599 final WebClient webClient = page.getWebClient();
600
601
602 final boolean isShiftNeeded = fireDown && fireUp && KeyboardEvent.isShiftNeeded(c, shiftPressed_);
603 final boolean shift = shiftPressed_ || isShiftNeeded;
604
605 final Event shiftDown;
606 final ScriptResult shiftDownResult;
607 if (isShiftNeeded) {
608 shiftDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, KeyboardEvent.DOM_VK_SHIFT,
609 true, ctrlPressed_, altPressed_);
610 shiftDownResult = fireEvent(shiftDown);
611 }
612 else {
613 shiftDown = null;
614 shiftDownResult = null;
615 }
616
617 if (fireDown) {
618 final String textBefore = getTextForInputEvent();
619
620 final Event keyDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, c,
621 shift, ctrlPressed_, altPressed_, metaPressed_);
622 final ScriptResult keyDownResult = fireEvent(keyDown);
623
624 if (!keyDown.isAborted(keyDownResult)) {
625
626
627 boolean keyPressAborted = false;
628 if (!isTypingSuppressedByModifiers()) {
629 final Event keyPress = new KeyboardEvent(this, Event.TYPE_KEY_PRESS, c,
630 shift, ctrlPressed_, altPressed_, metaPressed_);
631 final ScriptResult keyPressResult = fireEvent(keyPress);
632 keyPressAborted = keyPress.isAborted(keyPressResult);
633 }
634
635 if ((shiftDown == null || !shiftDown.isAborted(shiftDownResult))
636 && !keyPressAborted) {
637 doType(c, lastType);
638 }
639 }
640
641 if (isTextChanged(textBefore)) {
642 fireEvent(createInputEvent(c));
643 }
644 }
645
646 HtmlElement eventSource = this;
647 if (!isAttachedToPage()) {
648 eventSource = page.getBody();
649 }
650
651 if (fireUp && eventSource != null) {
652 final Event keyUp = new KeyboardEvent(this, Event.TYPE_KEY_UP, c,
653 shift, ctrlPressed_, altPressed_, metaPressed_);
654 eventSource.fireEvent(keyUp);
655
656 if (isShiftNeeded) {
657 final Event shiftUp = new KeyboardEvent(this, Event.TYPE_KEY_UP,
658 KeyboardEvent.DOM_VK_SHIFT,
659 false, ctrlPressed_, altPressed_);
660 eventSource.fireEvent(shiftUp);
661 }
662 }
663
664 final HtmlForm form = getEnclosingForm();
665 if (fireDown && form != null && c == '\n' && isSubmittableByEnter()) {
666 for (final DomElement descendant : form.getDomElementDescendants()) {
667 if (descendant instanceof HtmlSubmitInput) {
668 return descendant.click();
669 }
670 }
671
672 form.submit((SubmittableElement) this);
673
674 if (webClient.isJavaScriptEnabled()) {
675 webClient.getJavaScriptEngine().processPostponedActions();
676 }
677 }
678
679 return webClient.getCurrentWindow().getEnclosedPage();
680 }
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696 public Page type(final int keyCode) throws IOException {
697 return type(keyCode, Keyboard.DEFAULT_LOCATION, true, true, true, true);
698 }
699
700
701
702
703
704
705
706
707
708
709
710
711 public Page type(final Keyboard keyboard) throws IOException {
712 final List<Keyboard.KeyAction> keys = keyboard.getKeys();
713
714 if (keyboard.isStartAtEnd()) {
715 if (this instanceof SelectableTextInput textInput) {
716 textInput.setSelectionStart(textInput.getText().length());
717 }
718 else {
719 final DomText domText = getDoTypeNode();
720 if (domText != null) {
721 domText.moveSelectionToEnd();
722 }
723 }
724 }
725
726 final boolean[] pressedModifiers = keyboard.getPressedModifiers();
727 if (pressedModifiers != null) {
728 shiftPressed_ = pressedModifiers[0];
729 ctrlPressed_ = pressedModifiers[1];
730 altPressed_ = pressedModifiers[2];
731 metaPressed_ = pressedModifiers[3];
732 }
733
734 return type(keys);
735 }
736
737
738
739
740
741
742
743
744
745
746 private Page type(final List<Keyboard.KeyAction> keys) throws IOException {
747 Page page = null;
748
749 final int size = keys.size();
750 int i = 0;
751 for (final Keyboard.KeyAction keyAction : keys) {
752 i++;
753 final boolean lastType = i == size;
754
755 if (keyAction instanceof Keyboard.TypedChar typedChar) {
756 page = type(typedChar.ch(), lastType);
757 }
758 else if (keyAction instanceof Keyboard.CharKeyAction charKeyAction) {
759 page = typeChar(charKeyAction.ch(), lastType, charKeyAction.down(), !charKeyAction.down());
760 }
761 else if (keyAction instanceof Keyboard.KeyCodeKeyAction keyCodeKeyAction) {
762 final int key = keyCodeKeyAction.keyCode();
763 final boolean down = keyCodeKeyAction.down();
764 updateModifiers(key, down);
765 page = type(key, keyCodeKeyAction.location(), down, down, !down, lastType);
766 }
767 else if (keyAction instanceof Keyboard.KeyCodeAction keyCodeAction) {
768 final int key = keyCodeAction.keyCode();
769 final boolean pressed = keyCodeAction.pressed();
770
771 if (updateModifiers(key, pressed)) {
772 page = type(key, Keyboard.DEFAULT_LOCATION, pressed, false, !pressed, lastType);
773 }
774 else if (pressed) {
775 page = type(key, Keyboard.DEFAULT_LOCATION, true, true, true, lastType);
776 }
777 else {
778 page = type(key, Keyboard.DEFAULT_LOCATION, false, false, true, lastType);
779 }
780 }
781
782
783 if (i < size && isTabKeyDown(keyAction) && getPage() instanceof HtmlPage htmlPage) {
784 final DomElement focusedElement = htmlPage.getFocusedElement();
785 if (focusedElement == null) {
786
787 return page;
788 }
789 if (focusedElement instanceof HtmlElement focused && focused != this) {
790 focused.shiftPressed_ = shiftPressed_;
791 focused.ctrlPressed_ = ctrlPressed_;
792 focused.altPressed_ = altPressed_;
793 focused.metaPressed_ = metaPressed_;
794 return focused.type(keys.subList(i, size));
795 }
796 }
797 }
798
799 return page;
800 }
801
802 private static boolean isTabKeyDown(final Keyboard.KeyAction keyAction) {
803 if (keyAction instanceof Keyboard.KeyCodeAction keyCodeAction) {
804 return keyCodeAction.keyCode() == KeyboardEvent.DOM_VK_TAB && keyCodeAction.pressed();
805 }
806 if (keyAction instanceof Keyboard.KeyCodeKeyAction keyCodeKeyAction) {
807 return keyCodeKeyAction.keyCode() == KeyboardEvent.DOM_VK_TAB && keyCodeKeyAction.down();
808 }
809 return false;
810 }
811
812
813
814
815
816
817
818
819
820
821 private HtmlElement moveFocusByTab(final HtmlPage page) {
822 final List<HtmlElement> tabbableElements = page.getTabbableElements();
823 final int index = tabbableElements.indexOf(this);
824 if (index != -1 && index == (shiftPressed_ ? 0 : tabbableElements.size() - 1)) {
825 page.setFocusedElement(null);
826 return null;
827 }
828
829 final HtmlElement focused = shiftPressed_ ? page.tabToPreviousElement() : page.tabToNextElement();
830 if (focused instanceof HtmlInput && focused instanceof SelectableTextInput textInput) {
831 textInput.setSelectionStart(0);
832 textInput.setSelectionEnd(textInput.getText().length());
833 }
834 return focused;
835 }
836
837
838
839
840
841
842
843 boolean isTypingSuppressedByModifiers() {
844 return ctrlPressed_
845 || (metaPressed_ && getPage().getWebClient().getBrowserVersion()
846 .hasFeature(KEYBOARD_EVENT_META_NO_KEYPRESS));
847 }
848
849
850
851
852
853
854
855
856 private boolean updateModifiers(final int keyCode, final boolean pressed) {
857 switch (keyCode) {
858 case KeyboardEvent.DOM_VK_SHIFT -> shiftPressed_ = pressed;
859 case KeyboardEvent.DOM_VK_CONTROL -> ctrlPressed_ = pressed;
860 case KeyboardEvent.DOM_VK_ALT -> altPressed_ = pressed;
861 case KeyboardEvent.DOM_VK_META, KeyboardEvent.DOM_VK_WIN -> metaPressed_ = pressed;
862 default -> {
863 return false;
864 }
865 }
866 return true;
867 }
868
869 private Page type(final int keyCode, final int location,
870 final boolean fireKeyDown, final boolean fireKeyPress, final boolean fireKeyUp,
871 final boolean lastType) throws IOException {
872 if (isDisabledElementAndDisabled()) {
873 return getPage();
874 }
875
876 final HtmlPage page = (HtmlPage) getPage();
877 if (page.getFocusedElement() != this) {
878 focus();
879 }
880
881 final String textBefore = getTextForInputEvent();
882
883 final Event keyDown;
884 final ScriptResult keyDownResult;
885 if (fireKeyDown) {
886 keyDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, keyCode, location,
887 shiftPressed_, ctrlPressed_, altPressed_, metaPressed_);
888 keyDownResult = fireEvent(keyDown);
889 }
890 else {
891 keyDown = null;
892 keyDownResult = null;
893 }
894
895 final Event keyPress;
896 final ScriptResult keyPressResult;
897 if (fireKeyPress && KeyboardEvent.isCharacterKey(keyCode) && !isTypingSuppressedByModifiers()) {
898 keyPress = new KeyboardEvent(this, Event.TYPE_KEY_PRESS, keyCode, location,
899 shiftPressed_, ctrlPressed_, altPressed_, metaPressed_);
900
901 keyPressResult = fireEvent(keyPress);
902 }
903 else {
904 keyPress = null;
905 keyPressResult = null;
906 }
907
908
909 HtmlElement keyUpTarget = this;
910 if (keyDown != null && !keyDown.isAborted(keyDownResult)
911 && (keyPress == null || !keyPress.isAborted(keyPressResult))) {
912 if (keyCode == KeyboardEvent.DOM_VK_TAB) {
913 final HtmlElement focused = moveFocusByTab(page);
914 if (focused != null) {
915 keyUpTarget = focused;
916 }
917 else if (page.getBody() != null) {
918 keyUpTarget = page.getBody();
919 }
920 }
921 else {
922 doType(keyCode, lastType);
923 }
924 }
925
926 if (isTextChanged(textBefore)) {
927 fireEvent(createInputEvent(keyCode));
928 }
929
930 if (fireKeyUp) {
931 final Event keyUp = new KeyboardEvent(keyUpTarget, Event.TYPE_KEY_UP, keyCode, location,
932 shiftPressed_, ctrlPressed_, altPressed_, metaPressed_);
933 keyUpTarget.fireEvent(keyUp);
934 }
935
936 return page.getWebClient().getCurrentWindow().getEnclosedPage();
937 }
938
939
940
941
942
943
944
945 private InputEvent createInputEvent(final char c) {
946 final String inputType;
947 String data = null;
948 if (c == '\b') {
949 inputType = "deleteContentBackward";
950 }
951 else if (c == '\r' || c == '\n') {
952 inputType = "insertLineBreak";
953 }
954 else if (ctrlPressed_ && (c == 'x' || c == 'X')) {
955 inputType = "deleteByCut";
956 }
957 else if (ctrlPressed_ && (c == 'v' || c == 'V')) {
958 inputType = "insertFromPaste";
959 final ClipboardHandler clipboardHandler = getPage().getWebClient().getClipboardHandler();
960 if (clipboardHandler != null) {
961 data = clipboardHandler.getClipboardContent();
962 }
963 }
964 else {
965 inputType = "insertText";
966 data = String.valueOf(c);
967 }
968 return new InputEvent(this, Event.TYPE_INPUT, inputType, data);
969 }
970
971
972
973
974
975
976
977 private InputEvent createInputEvent(final int keyCode) {
978 final String inputType;
979 String data = null;
980 if (keyCode == KeyboardEvent.DOM_VK_BACK_SPACE) {
981 inputType = ctrlPressed_ ? "deleteWordBackward" : "deleteContentBackward";
982 }
983 else if (keyCode == KeyboardEvent.DOM_VK_DELETE) {
984 inputType = ctrlPressed_ ? "deleteWordForward" : "deleteContentForward";
985 }
986 else if (keyCode == KeyboardEvent.DOM_VK_RETURN) {
987 inputType = "insertLineBreak";
988 }
989 else {
990 inputType = "insertText";
991 final int charCode = KeyboardEvent.getCharCode(keyCode);
992 if (charCode != 0) {
993 data = String.valueOf((char) charCode);
994 }
995 }
996 return new InputEvent(this, Event.TYPE_INPUT, inputType, data);
997 }
998
999
1000
1001
1002
1003
1004
1005 private String getTextForInputEvent() {
1006 if (this instanceof SelectableTextInput textInput) {
1007 return textInput.getText();
1008 }
1009 return null;
1010 }
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020 private boolean isTextChanged(final String textBefore) {
1021 return textBefore != null && !textBefore.equals(getTextForInputEvent());
1022 }
1023
1024
1025
1026
1027
1028
1029 protected void doType(final char c, final boolean lastType) {
1030 final DomText domText = getDoTypeNode();
1031 if (domText != null) {
1032 domText.doType(c, this, lastType);
1033 }
1034 }
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046 protected void doType(final int keyCode, final boolean lastType) throws IOException {
1047 final DomText domText = getDoTypeNode();
1048 if (domText != null) {
1049 domText.doType(keyCode, this, lastType);
1050 }
1051 }
1052
1053
1054
1055
1056
1057 private DomText getDoTypeNode() {
1058 final HTMLElement scriptElement = getScriptableObject();
1059 if (scriptElement.isIsContentEditable()
1060 || "on".equals(((Document) scriptElement.getOwnerDocument()).getDesignMode())) {
1061
1062 DomNode node = this;
1063 while (node.getLastChild() != null) {
1064 node = node.getLastChild();
1065 }
1066
1067 if (node instanceof DomText text) {
1068 return text;
1069 }
1070
1071 final DomText domText = new DomText(getPage(), "");
1072 appendChild(domText);
1073 return domText;
1074 }
1075 return null;
1076 }
1077
1078
1079
1080
1081
1082
1083 protected void typeDone(final String newValue, final boolean notifyAttributeChangeListeners) {
1084
1085 }
1086
1087
1088
1089
1090
1091
1092 protected boolean acceptChar(final char c) {
1093
1094
1095 return (c < '\uE000' || c > '\uF8FF')
1096 && (c == ' ' || c == '\t' || c == '\u3000' || c == '\u2006' || !Character.isWhitespace(c));
1097 }
1098
1099
1100
1101
1102
1103
1104 protected boolean isSubmittableByEnter() {
1105 return false;
1106 }
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119 public final <E extends HtmlElement> E getOneHtmlElementByAttribute(final String elementName,
1120 final String attributeName,
1121 final String attributeValue) throws ElementNotFoundException {
1122
1123 WebAssert.notNull("elementName", elementName);
1124 WebAssert.notNull("attributeName", attributeName);
1125 WebAssert.notNull("attributeValue", attributeValue);
1126
1127 final List<E> list = getElementsByAttribute(elementName, attributeName, attributeValue);
1128
1129 if (list.isEmpty()) {
1130 throw new ElementNotFoundException(elementName, attributeName, attributeValue);
1131 }
1132
1133 return list.get(0);
1134 }
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145 @SuppressWarnings("unchecked")
1146 public final <E extends HtmlElement> List<E> getElementsByAttribute(
1147 final String elementName,
1148 final String attributeName,
1149 final String attributeValue) {
1150
1151 final List<E> list = new ArrayList<>();
1152 final String lowerCaseTagName = elementName.toLowerCase(Locale.ROOT);
1153
1154 for (final HtmlElement next : getHtmlElementDescendants()) {
1155 if (next.getTagName().equals(lowerCaseTagName)) {
1156 final String attValue = next.getAttribute(attributeName);
1157 if (attValue.equals(attributeValue)) {
1158 list.add((E) next);
1159 }
1160 }
1161 }
1162 return list;
1163 }
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173 public final HtmlElement appendChildIfNoneExists(final String tagName) {
1174 final HtmlElement child;
1175 final List<HtmlElement> children = getStaticElementsByTagName(tagName);
1176 if (children.isEmpty()) {
1177
1178 child = (HtmlElement) ((HtmlPage) getPage()).createElement(tagName);
1179 appendChild(child);
1180 }
1181 else {
1182
1183 child = children.get(0);
1184 }
1185 return child;
1186 }
1187
1188
1189
1190
1191
1192
1193
1194 public final void removeChild(final String tagName, final int i) {
1195 final List<HtmlElement> children = getStaticElementsByTagName(tagName);
1196 if (i >= 0 && i < children.size()) {
1197 children.get(i).remove();
1198 }
1199 }
1200
1201
1202
1203
1204
1205
1206
1207
1208 public final boolean hasEventHandlers(final String eventName) {
1209 if (getPage().getWebClient().isJavaScriptEngineEnabled()) {
1210 final HtmlUnitScriptable jsObj = getScriptableObject();
1211 if (jsObj instanceof EventTarget target) {
1212 return target.hasEventHandlers(eventName);
1213 }
1214 }
1215 return false;
1216 }
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226 public void addHtmlAttributeChangeListener(final HtmlAttributeChangeListener listener) {
1227 WebAssert.notNull("listener", listener);
1228 synchronized (attributeListeners_) {
1229 attributeListeners_.add(listener);
1230 }
1231 }
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241 public void removeHtmlAttributeChangeListener(final HtmlAttributeChangeListener listener) {
1242 WebAssert.notNull("listener", listener);
1243 synchronized (attributeListeners_) {
1244 attributeListeners_.remove(listener);
1245 }
1246 }
1247
1248
1249
1250
1251 @Override
1252 protected void checkChildHierarchy(final Node childNode) throws DOMException {
1253 if (!((childNode instanceof Element) || (childNode instanceof Text)
1254 || (childNode instanceof Comment) || (childNode instanceof ProcessingInstruction)
1255 || (childNode instanceof CDATASection) || (childNode instanceof EntityReference))) {
1256 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
1257 "The Element may not have a child of this type: " + childNode.getNodeType());
1258 }
1259 super.checkChildHierarchy(childNode);
1260 }
1261
1262
1263
1264
1265
1266
1267
1268 public void setOwningForm(final HtmlForm form) {
1269 owningForm_ = form;
1270 }
1271
1272
1273
1274
1275
1276 @Override
1277 protected boolean isAttributeCaseSensitive() {
1278 return false;
1279 }
1280
1281
1282
1283
1284
1285
1286 @Override
1287 protected boolean isEmptyXmlTagExpanded() {
1288 return Html.XHTML_NAMESPACE.equals(getNamespaceURI())
1289 && !isVoidElement(getLowercaseName());
1290 }
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300 public static boolean isVoidElement(final String localName) {
1301 return VOID_ELEMENTS.contains(localName);
1302 }
1303
1304
1305
1306
1307
1308
1309
1310
1311 public final String getLangAttribute() {
1312 return getAttributeDirect("lang");
1313 }
1314
1315
1316
1317
1318
1319
1320
1321
1322 public final String getXmlLangAttribute() {
1323 return getAttribute("xml:lang");
1324 }
1325
1326
1327
1328
1329
1330
1331
1332
1333 public final String getTextDirectionAttribute() {
1334 return getAttributeDirect("dir");
1335 }
1336
1337
1338
1339
1340
1341
1342
1343
1344 public final String getOnClickAttribute() {
1345 return getAttributeDirect("onclick");
1346 }
1347
1348
1349
1350
1351
1352
1353
1354
1355 public final String getOnDblClickAttribute() {
1356 return getAttributeDirect("ondblclick");
1357 }
1358
1359
1360
1361
1362
1363
1364
1365
1366 public final String getOnMouseDownAttribute() {
1367 return getAttributeDirect("onmousedown");
1368 }
1369
1370
1371
1372
1373
1374
1375
1376
1377 public final String getOnMouseUpAttribute() {
1378 return getAttributeDirect("onmouseup");
1379 }
1380
1381
1382
1383
1384
1385
1386
1387
1388 public final String getOnMouseOverAttribute() {
1389 return getAttributeDirect("onmouseover");
1390 }
1391
1392
1393
1394
1395
1396
1397
1398
1399 public final String getOnMouseMoveAttribute() {
1400 return getAttributeDirect("onmousemove");
1401 }
1402
1403
1404
1405
1406
1407
1408
1409
1410 public final String getOnMouseOutAttribute() {
1411 return getAttributeDirect("onmouseout");
1412 }
1413
1414
1415
1416
1417
1418
1419
1420
1421 public final String getOnKeyPressAttribute() {
1422 return getAttributeDirect("onkeypress");
1423 }
1424
1425
1426
1427
1428
1429
1430
1431
1432 public final String getOnKeyDownAttribute() {
1433 return getAttributeDirect("onkeydown");
1434 }
1435
1436
1437
1438
1439
1440
1441
1442
1443 public final String getOnKeyUpAttribute() {
1444 return getAttributeDirect("onkeyup");
1445 }
1446
1447
1448
1449
1450 @Override
1451 public String getCanonicalXPath() {
1452 final DomNode parent = getParentNode();
1453 if (parent.getNodeType() == DOCUMENT_NODE) {
1454 return "/" + getNodeName();
1455 }
1456 return parent.getCanonicalXPath() + '/' + getXPathToken();
1457 }
1458
1459
1460
1461
1462 private String getXPathToken() {
1463 final DomNode parent = getParentNode();
1464 int total = 0;
1465 int nodeIndex = 0;
1466 for (final DomNode child : parent.getChildren()) {
1467 if (child.getNodeType() == ELEMENT_NODE && child.getNodeName().equals(getNodeName())) {
1468 total++;
1469 }
1470 if (child == this) {
1471 nodeIndex = total;
1472 }
1473 }
1474
1475 if (nodeIndex == 1 && total == 1) {
1476 return getNodeName();
1477 }
1478 return getNodeName() + '[' + nodeIndex + ']';
1479 }
1480
1481
1482
1483
1484
1485
1486 public String getHidden() {
1487 return getAttributeDirect(ATTRIBUTE_HIDDEN);
1488 }
1489
1490
1491
1492
1493
1494
1495 public boolean isHidden() {
1496 return ATTRIBUTE_NOT_DEFINED != getAttributeDirect(ATTRIBUTE_HIDDEN);
1497 }
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507 public void setHidden(final String hidden) {
1508 if ("until-found".equalsIgnoreCase(hidden)) {
1509 setAttribute(ATTRIBUTE_HIDDEN, "until-found");
1510 return;
1511 }
1512
1513 if (StringUtils.isEmptyString(hidden)) {
1514 removeAttribute(ATTRIBUTE_HIDDEN);
1515 return;
1516 }
1517
1518 setAttribute(ATTRIBUTE_HIDDEN, "");
1519 }
1520
1521
1522
1523
1524
1525 public void setHidden(final boolean hidden) {
1526 if (hidden) {
1527 setAttribute(ATTRIBUTE_HIDDEN, "");
1528 return;
1529 }
1530
1531 removeAttribute(ATTRIBUTE_HIDDEN);
1532 }
1533
1534
1535
1536
1537
1538 @Override
1539 public boolean isDisplayed() {
1540
1541 if (isHidden() && !getPage().getWebClient().getOptions().isCssEnabled()) {
1542 return false;
1543 }
1544 return super.isDisplayed();
1545 }
1546
1547
1548
1549
1550
1551
1552
1553
1554 public DisplayStyle getDefaultStyleDisplay() {
1555 return DisplayStyle.BLOCK;
1556 }
1557
1558
1559
1560
1561
1562
1563
1564 protected final String getSrcAttributeNormalized() {
1565 final String attrib = getAttributeDirect(SRC_ATTRIBUTE);
1566 if (ATTRIBUTE_NOT_DEFINED == attrib) {
1567 return attrib;
1568 }
1569
1570 return StringUtils.replaceChars(attrib, "\r\n", "");
1571 }
1572
1573
1574
1575
1576
1577
1578
1579 @Override
1580 protected void detach() {
1581 final SgmlPage page = getPage();
1582 if (!page.getWebClient().isJavaScriptEngineEnabled()) {
1583 super.detach();
1584 return;
1585 }
1586
1587 final HtmlUnitScriptable document = page.getScriptableObject();
1588
1589 if (document instanceof HTMLDocument doc) {
1590 final Object activeElement = doc.getActiveElement();
1591
1592 if (activeElement == getScriptableObject()) {
1593 if (hasFeature(HTMLELEMENT_REMOVE_ACTIVE_TRIGGERS_BLUR_EVENT)) {
1594 ((HtmlPage) page).setFocusedElement(null);
1595 }
1596 else {
1597 ((HtmlPage) page).setElementWithFocus(null);
1598 }
1599 }
1600 else {
1601 for (final DomNode child : getChildNodes()) {
1602 if (activeElement == child.getScriptableObject()) {
1603 if (hasFeature(HTMLELEMENT_REMOVE_ACTIVE_TRIGGERS_BLUR_EVENT)) {
1604 ((HtmlPage) page).setFocusedElement(null);
1605 }
1606 else {
1607 ((HtmlPage) page).setElementWithFocus(null);
1608 }
1609
1610 break;
1611 }
1612 }
1613 }
1614 }
1615 super.detach();
1616 }
1617
1618
1619
1620
1621 @Override
1622 public boolean handles(final Event event) {
1623 if (Event.TYPE_BLUR.equals(event.getType()) || Event.TYPE_FOCUS.equals(event.getType())) {
1624 return this instanceof SubmittableElement || getTabIndex() != null;
1625 }
1626
1627 if (isDisabledElementAndDisabled()) {
1628 return false;
1629 }
1630 return super.handles(event);
1631 }
1632
1633
1634
1635
1636
1637 protected boolean isShiftPressed() {
1638 return shiftPressed_;
1639 }
1640
1641
1642
1643
1644
1645 public boolean isCtrlPressed() {
1646 return ctrlPressed_;
1647 }
1648
1649
1650
1651
1652
1653 public boolean isAltPressed() {
1654 return altPressed_;
1655 }
1656
1657
1658
1659
1660
1661 public boolean isMetaPressed() {
1662 return metaPressed_;
1663 }
1664
1665
1666
1667
1668
1669 public boolean isValid() {
1670 return !isRequiredSupported()
1671 || ATTRIBUTE_NOT_DEFINED == getAttributeDirect(ATTRIBUTE_REQUIRED)
1672 || !getAttributeDirect(VALUE_ATTRIBUTE).isEmpty();
1673 }
1674
1675
1676
1677
1678
1679 protected boolean isRequiredSupported() {
1680 return false;
1681 }
1682
1683
1684
1685
1686
1687
1688 public boolean isRequired() {
1689 return isRequiredSupported() && hasAttribute(ATTRIBUTE_REQUIRED);
1690 }
1691
1692
1693
1694
1695
1696
1697 public boolean isOptional() {
1698 return isRequiredSupported() && !hasAttribute(ATTRIBUTE_REQUIRED);
1699 }
1700
1701
1702
1703
1704
1705 public void setRequired(final boolean required) {
1706 if (isRequiredSupported()) {
1707 if (required) {
1708 setAttribute(ATTRIBUTE_REQUIRED, ATTRIBUTE_REQUIRED);
1709 }
1710 else {
1711 removeAttribute(ATTRIBUTE_REQUIRED);
1712 }
1713 }
1714 }
1715
1716
1717
1718
1719
1720
1721
1722 public HtmlElement getOffsetParentInternal(final boolean returnNullIfFixed) {
1723 if (getParentNode() == null) {
1724 return null;
1725 }
1726
1727 final WebWindow webWindow = getPage().getEnclosingWindow();
1728 final ComputedCssStyleDeclaration style = webWindow.getComputedStyle(this, null);
1729 final String position = style.getPositionWithInheritance();
1730
1731 if (returnNullIfFixed && FIXED.equals(position)) {
1732 return null;
1733 }
1734
1735 final boolean staticPos = STATIC.equals(position);
1736
1737 DomNode currentElement = this;
1738 while (currentElement != null) {
1739
1740 final DomNode parentNode = currentElement.getParentNode();
1741 if (parentNode instanceof HtmlBody
1742 || (staticPos && parentNode instanceof HtmlTableDataCell)
1743 || (staticPos && parentNode instanceof HtmlTable)) {
1744 return (HtmlElement) parentNode;
1745 }
1746
1747 if (parentNode instanceof HtmlElement element) {
1748 final ComputedCssStyleDeclaration parentStyle =
1749 webWindow.getComputedStyle(element, null);
1750 final String parentPosition = parentStyle.getPositionWithInheritance();
1751 if (!STATIC.equals(parentPosition)) {
1752 return element;
1753 }
1754 }
1755
1756 currentElement = currentElement.getParentNode();
1757 }
1758
1759 return null;
1760 }
1761
1762
1763
1764
1765
1766
1767
1768 public int getOffsetTop() {
1769 if (this instanceof HtmlBody) {
1770 return 0;
1771 }
1772
1773 int top = 0;
1774
1775
1776 final WebWindow webWindow = getPage().getEnclosingWindow();
1777 ComputedCssStyleDeclaration style = webWindow.getComputedStyle(this, null);
1778 top += style.getTop(true, false, false);
1779
1780
1781 final String position = style.getPositionWithInheritance();
1782 if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
1783 return top;
1784 }
1785
1786 final HtmlElement offsetParent = getOffsetParentInternal(false);
1787
1788
1789 DomNode parentNode = getParentNode();
1790 while (parentNode != null && parentNode != offsetParent) {
1791 if (parentNode instanceof HtmlElement element) {
1792 style = webWindow.getComputedStyle(element, null);
1793 top += style.getTop(false, true, true);
1794 }
1795 parentNode = parentNode.getParentNode();
1796 }
1797
1798 if (offsetParent != null) {
1799 style = webWindow.getComputedStyle(this, null);
1800 final boolean thisElementHasTopMargin = style.getMarginTopValue() != 0;
1801
1802 style = webWindow.getComputedStyle(offsetParent, null);
1803 if (!thisElementHasTopMargin) {
1804 top += style.getMarginTopValue();
1805 }
1806 top += style.getPaddingTopValue();
1807 }
1808
1809 return top;
1810 }
1811
1812
1813
1814
1815
1816
1817
1818 public int getOffsetLeft() {
1819 if (this instanceof HtmlBody) {
1820 return 0;
1821 }
1822
1823 int left = 0;
1824
1825
1826 final WebWindow webWindow = getPage().getEnclosingWindow();
1827 ComputedCssStyleDeclaration style = webWindow.getComputedStyle(this, null);
1828 left += style.getLeft(true, false, false);
1829
1830
1831 final String position = style.getPositionWithInheritance();
1832 if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
1833 return left;
1834 }
1835
1836 final HtmlElement offsetParent = getOffsetParentInternal(false);
1837
1838 DomNode parentNode = getParentNode();
1839 while (parentNode != null && parentNode != offsetParent) {
1840 if (parentNode instanceof HtmlElement element) {
1841 style = webWindow.getComputedStyle(element, null);
1842 left += style.getLeft(true, true, true);
1843 }
1844 parentNode = parentNode.getParentNode();
1845 }
1846
1847 if (offsetParent != null) {
1848 style = webWindow.getComputedStyle(offsetParent, null);
1849 left += style.getMarginLeftValue();
1850 left += style.getPaddingLeftValue();
1851 }
1852
1853 return left;
1854 }
1855
1856
1857
1858
1859
1860 public int getPosX() {
1861 int cumulativeOffset = 0;
1862 final WebWindow webWindow = getPage().getEnclosingWindow();
1863
1864 HtmlElement element = this;
1865 while (element != null) {
1866 cumulativeOffset += element.getOffsetLeft();
1867 if (element != this) {
1868 final ComputedCssStyleDeclaration style =
1869 webWindow.getComputedStyle(element, null);
1870 cumulativeOffset += style.getBorderLeftValue();
1871 }
1872 element = element.getOffsetParentInternal(false);
1873 }
1874
1875 return cumulativeOffset;
1876 }
1877
1878
1879
1880
1881
1882 public int getPosY() {
1883 int cumulativeOffset = 0;
1884 final WebWindow webWindow = getPage().getEnclosingWindow();
1885
1886 HtmlElement element = this;
1887 while (element != null) {
1888 cumulativeOffset += element.getOffsetTop();
1889 if (element != this) {
1890 final ComputedCssStyleDeclaration style =
1891 webWindow.getComputedStyle(element, null);
1892 cumulativeOffset += style.getBorderTopValue();
1893 }
1894 element = element.getOffsetParentInternal(false);
1895 }
1896
1897 return cumulativeOffset;
1898 }
1899
1900
1901
1902
1903 @Override
1904 public DomNode cloneNode(final boolean deep) {
1905 final HtmlElement newNode = (HtmlElement) super.cloneNode(deep);
1906 if (!deep) {
1907 synchronized (attributeListeners_) {
1908 newNode.attributeListeners_.clear();
1909 newNode.attributeListeners_.addAll(attributeListeners_);
1910 }
1911 }
1912
1913 return newNode;
1914 }
1915 }