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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
|
/*
* Copyright (C) 2004, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "SelectionController.h"
#include "CString.h"
#include "DeleteSelectionCommand.h"
#include "Document.h"
#include "Editor.h"
#include "Element.h"
#include "EventHandler.h"
#include "EventNames.h"
#include "ExceptionCode.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "Page.h"
#include "Range.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "TextIterator.h"
#include "TypingCommand.h"
#include "htmlediting.h"
#include "visible_units.h"
#include <stdio.h>
#define EDIT_DEBUG 0
namespace WebCore {
using namespace EventNames;
using namespace HTMLNames;
const int NoXPosForVerticalArrowNavigation = INT_MIN;
SelectionController::SelectionController(Frame* frame, bool isDragCaretController)
: m_needsLayout(true)
, m_lastChangeWasHorizontalExtension(false)
, m_frame(frame)
, m_isDragCaretController(isDragCaretController)
, m_isCaretBlinkingSuspended(false)
, m_xPosForVerticalArrowNavigation(NoXPosForVerticalArrowNavigation)
, m_focused(false)
{
}
void SelectionController::moveTo(const VisiblePosition &pos, bool userTriggered)
{
setSelection(Selection(pos.deepEquivalent(), pos.deepEquivalent(), pos.affinity()), true, true, userTriggered);
}
void SelectionController::moveTo(const VisiblePosition &base, const VisiblePosition &extent, bool userTriggered)
{
setSelection(Selection(base.deepEquivalent(), extent.deepEquivalent(), base.affinity()), true, true, userTriggered);
}
void SelectionController::moveTo(const Position &pos, EAffinity affinity, bool userTriggered)
{
setSelection(Selection(pos, affinity), true, true, userTriggered);
}
void SelectionController::moveTo(const Range *r, EAffinity affinity, bool userTriggered)
{
setSelection(Selection(startPosition(r), endPosition(r), affinity), true, true, userTriggered);
}
void SelectionController::moveTo(const Position &base, const Position &extent, EAffinity affinity, bool userTriggered)
{
setSelection(Selection(base, extent, affinity), true, true, userTriggered);
}
void SelectionController::setSelection(const Selection& s, bool closeTyping, bool clearTypingStyle, bool userTriggered)
{
if (m_isDragCaretController) {
invalidateCaretRect();
m_sel = s;
m_needsLayout = true;
invalidateCaretRect();
return;
}
if (!m_frame) {
m_sel = s;
return;
}
if (s.base().node() && s.base().node()->document() != m_frame->document()) {
s.base().node()->document()->frame()->selectionController()->setSelection(s, closeTyping, clearTypingStyle, userTriggered);
return;
}
if (closeTyping)
TypingCommand::closeTyping(m_frame->editor()->lastEditCommand());
if (clearTypingStyle) {
m_frame->clearTypingStyle();
m_frame->editor()->setRemovedAnchor(0);
}
if (m_sel == s)
return;
Selection oldSelection = m_sel;
m_sel = s;
m_needsLayout = true;
if (!s.isNone())
m_frame->setFocusedNodeIfNeeded();
m_frame->selectionLayoutChanged();
// Always clear the x position used for vertical arrow navigation.
// It will be restored by the vertical arrow navigation code if necessary.
m_xPosForVerticalArrowNavigation = NoXPosForVerticalArrowNavigation;
selectFrameElementInParentIfFullySelected();
m_frame->notifyRendererOfSelectionChange(userTriggered);
m_frame->respondToChangedSelection(oldSelection, closeTyping);
if (userTriggered)
m_frame->revealCaret(RenderLayer::gAlignToEdgeIfNeeded);
notifyAccessibilityForSelectionChange();
}
static bool removingNodeRemovesPosition(Node* node, const Position& position)
{
if (!position.node())
return false;
if (position.node() == node)
return true;
if (!node->isElementNode())
return false;
Element* element = static_cast<Element*>(node);
return element->contains(position.node()) || element->contains(position.node()->shadowAncestorNode());
}
void SelectionController::nodeWillBeRemoved(Node *node)
{
if (isNone())
return;
// There can't be a selection inside a fragment, so if a fragment's node is being removed,
// the selection in the document that created the fragment needs no adjustment.
if (node && highestAncestor(node)->nodeType() == Node::DOCUMENT_FRAGMENT_NODE)
return;
bool baseRemoved = removingNodeRemovesPosition(node, m_sel.base());
bool extentRemoved = removingNodeRemovesPosition(node, m_sel.extent());
bool startRemoved = removingNodeRemovesPosition(node, m_sel.start());
bool endRemoved = removingNodeRemovesPosition(node, m_sel.end());
bool clearRenderTreeSelection = false;
bool clearDOMTreeSelection = false;
if (startRemoved || endRemoved) {
// FIXME: When endpoints are removed, we should just alter the selection, instead of blowing it away.
clearRenderTreeSelection = true;
clearDOMTreeSelection = true;
} else if (baseRemoved || extentRemoved) {
// The base and/or extent are about to be removed, but the start and end aren't.
// Change the base and extent to the start and end, but don't re-validate the
// selection, since doing so could move the start and end into the node
// that is about to be removed.
if (m_sel.isBaseFirst())
m_sel.setWithoutValidation(m_sel.start(), m_sel.end());
else
m_sel.setWithoutValidation(m_sel.end(), m_sel.start());
// FIXME: This could be more efficient if we had an isNodeInRange function on Ranges.
} else if (Range::compareBoundaryPoints(m_sel.start(), Position(node, 0)) == -1 &&
Range::compareBoundaryPoints(m_sel.end(), Position(node, 0)) == 1) {
// If we did nothing here, when this node's renderer was destroyed, the rect that it
// occupied would be invalidated, but, selection gaps that change as a result of
// the removal wouldn't be invalidated.
// FIXME: Don't do so much unnecessary invalidation.
clearRenderTreeSelection = true;
}
if (clearRenderTreeSelection) {
RefPtr<Document> document = m_sel.start().node()->document();
document->updateRendering();
if (RenderView* view = static_cast<RenderView*>(document->renderer()))
view->clearSelection();
}
if (clearDOMTreeSelection)
setSelection(Selection(), false, false);
}
void SelectionController::willBeModified(EAlteration alter, EDirection direction)
{
switch (alter) {
case MOVE:
m_lastChangeWasHorizontalExtension = false;
break;
case EXTEND:
if (!m_lastChangeWasHorizontalExtension) {
m_lastChangeWasHorizontalExtension = true;
Position start = m_sel.start();
Position end = m_sel.end();
switch (direction) {
// FIXME: right for bidi?
case RIGHT:
case FORWARD:
m_sel.setBase(start);
m_sel.setExtent(end);
break;
case LEFT:
case BACKWARD:
m_sel.setBase(end);
m_sel.setExtent(start);
break;
}
}
break;
}
}
VisiblePosition SelectionController::modifyExtendingRightForward(TextGranularity granularity)
{
VisiblePosition pos(m_sel.extent(), m_sel.affinity());
switch (granularity) {
case CharacterGranularity:
pos = pos.next(true);
break;
case WordGranularity:
pos = nextWordPosition(pos);
break;
case SentenceGranularity:
pos = nextSentencePosition(pos);
break;
case LineGranularity:
pos = nextLinePosition(pos, xPosForVerticalArrowNavigation(EXTENT));
break;
case ParagraphGranularity:
pos = nextParagraphPosition(pos, xPosForVerticalArrowNavigation(EXTENT));
break;
case SentenceBoundary:
pos = endOfSentence(VisiblePosition(m_sel.end(), m_sel.affinity()));
break;
case LineBoundary:
pos = endOfLine(VisiblePosition(m_sel.end(), m_sel.affinity()));
break;
case ParagraphBoundary:
pos = endOfParagraph(VisiblePosition(m_sel.end(), m_sel.affinity()));
break;
case DocumentBoundary:
pos = VisiblePosition(m_sel.end(), m_sel.affinity());
if (isEditablePosition(pos.deepEquivalent()))
pos = endOfEditableContent(pos);
else
pos = endOfDocument(pos);
break;
}
return pos;
}
VisiblePosition SelectionController::modifyMovingRight(TextGranularity granularity)
{
VisiblePosition pos;
switch (granularity) {
case CharacterGranularity:
if (isRange())
pos = VisiblePosition(m_sel.end(), m_sel.affinity());
else
pos = VisiblePosition(m_sel.extent(), m_sel.affinity()).right(true);
break;
case WordGranularity:
case SentenceGranularity:
case LineGranularity:
case ParagraphGranularity:
case SentenceBoundary:
case LineBoundary:
case ParagraphBoundary:
case DocumentBoundary:
// FIXME: Implement all of the above.
pos = modifyMovingForward(granularity);
break;
}
return pos;
}
VisiblePosition SelectionController::modifyMovingForward(TextGranularity granularity)
{
VisiblePosition pos;
// FIXME: Stay in editable content for the less common granularities.
switch (granularity) {
case CharacterGranularity:
if (isRange())
pos = VisiblePosition(m_sel.end(), m_sel.affinity());
else
pos = VisiblePosition(m_sel.extent(), m_sel.affinity()).next(true);
break;
case WordGranularity:
pos = nextWordPosition(VisiblePosition(m_sel.extent(), m_sel.affinity()));
break;
case SentenceGranularity:
pos = nextSentencePosition(VisiblePosition(m_sel.extent(), m_sel.affinity()));
break;
case LineGranularity: {
// down-arrowing from a range selection that ends at the start of a line needs
// to leave the selection at that line start (no need to call nextLinePosition!)
pos = VisiblePosition(m_sel.end(), m_sel.affinity());
if (!isRange() || !isStartOfLine(pos))
pos = nextLinePosition(pos, xPosForVerticalArrowNavigation(START));
break;
}
case ParagraphGranularity:
pos = nextParagraphPosition(VisiblePosition(m_sel.end(), m_sel.affinity()), xPosForVerticalArrowNavigation(START));
break;
case SentenceBoundary:
pos = endOfSentence(VisiblePosition(m_sel.end(), m_sel.affinity()));
break;
case LineBoundary:
pos = endOfLine(VisiblePosition(m_sel.end(), m_sel.affinity()));
break;
case ParagraphBoundary:
pos = endOfParagraph(VisiblePosition(m_sel.end(), m_sel.affinity()));
break;
case DocumentBoundary:
pos = VisiblePosition(m_sel.end(), m_sel.affinity());
if (isEditablePosition(pos.deepEquivalent()))
pos = endOfEditableContent(pos);
else
pos = endOfDocument(pos);
break;
}
return pos;
}
VisiblePosition SelectionController::modifyExtendingLeftBackward(TextGranularity granularity)
{
VisiblePosition pos(m_sel.extent(), m_sel.affinity());
// Extending a selection backward by word or character from just after a table selects
// the table. This "makes sense" from the user perspective, esp. when deleting.
// It was done here instead of in VisiblePosition because we want VPs to iterate
// over everything.
switch (granularity) {
case CharacterGranularity:
pos = pos.previous(true);
break;
case WordGranularity:
pos = previousWordPosition(pos);
break;
case SentenceGranularity:
pos = previousSentencePosition(pos);
break;
case LineGranularity:
pos = previousLinePosition(pos, xPosForVerticalArrowNavigation(EXTENT));
break;
case ParagraphGranularity:
pos = previousParagraphPosition(pos, xPosForVerticalArrowNavigation(EXTENT));
break;
case SentenceBoundary:
pos = startOfSentence(VisiblePosition(m_sel.start(), m_sel.affinity()));
break;
case LineBoundary:
pos = startOfLine(VisiblePosition(m_sel.start(), m_sel.affinity()));
break;
case ParagraphBoundary:
pos = startOfParagraph(VisiblePosition(m_sel.start(), m_sel.affinity()));
break;
case DocumentBoundary:
pos = VisiblePosition(m_sel.start(), m_sel.affinity());
if (isEditablePosition(pos.deepEquivalent()))
pos = startOfEditableContent(pos);
else
pos = startOfDocument(pos);
break;
}
return pos;
}
VisiblePosition SelectionController::modifyMovingLeft(TextGranularity granularity)
{
VisiblePosition pos;
switch (granularity) {
case CharacterGranularity:
if (isRange())
pos = VisiblePosition(m_sel.start(), m_sel.affinity());
else
pos = VisiblePosition(m_sel.extent(), m_sel.affinity()).left(true);
break;
case WordGranularity:
case SentenceGranularity:
case LineGranularity:
case ParagraphGranularity:
case SentenceBoundary:
case LineBoundary:
case ParagraphBoundary:
case DocumentBoundary:
// FIXME: Implement all of the above.
pos = modifyMovingBackward(granularity);
break;
}
return pos;
}
VisiblePosition SelectionController::modifyMovingBackward(TextGranularity granularity)
{
VisiblePosition pos;
switch (granularity) {
case CharacterGranularity:
if (isRange())
pos = VisiblePosition(m_sel.start(), m_sel.affinity());
else
pos = VisiblePosition(m_sel.extent(), m_sel.affinity()).previous(true);
break;
case WordGranularity:
pos = previousWordPosition(VisiblePosition(m_sel.extent(), m_sel.affinity()));
break;
case SentenceGranularity:
pos = previousSentencePosition(VisiblePosition(m_sel.extent(), m_sel.affinity()));
break;
case LineGranularity:
pos = previousLinePosition(VisiblePosition(m_sel.start(), m_sel.affinity()), xPosForVerticalArrowNavigation(START));
break;
case ParagraphGranularity:
pos = previousParagraphPosition(VisiblePosition(m_sel.start(), m_sel.affinity()), xPosForVerticalArrowNavigation(START));
break;
case SentenceBoundary:
pos = startOfSentence(VisiblePosition(m_sel.start(), m_sel.affinity()));
break;
case LineBoundary:
pos = startOfLine(VisiblePosition(m_sel.start(), m_sel.affinity()));
break;
case ParagraphBoundary:
pos = startOfParagraph(VisiblePosition(m_sel.start(), m_sel.affinity()));
break;
case DocumentBoundary:
pos = VisiblePosition(m_sel.start(), m_sel.affinity());
if (isEditablePosition(pos.deepEquivalent()))
pos = startOfEditableContent(pos);
else
pos = startOfDocument(pos);
break;
}
return pos;
}
bool SelectionController::modify(EAlteration alter, EDirection dir, TextGranularity granularity, bool userTriggered)
{
if (userTriggered) {
SelectionController trialSelectionController;
trialSelectionController.setLastChangeWasHorizontalExtension(m_lastChangeWasHorizontalExtension);
trialSelectionController.setSelection(m_sel);
trialSelectionController.modify(alter, dir, granularity, false);
bool change = m_frame->shouldChangeSelection(trialSelectionController.selection());
if (!change)
return false;
}
if (m_frame)
m_frame->setSelectionGranularity(granularity);
willBeModified(alter, dir);
VisiblePosition pos;
switch (dir) {
case RIGHT:
if (alter == MOVE)
pos = modifyMovingRight(granularity);
else
pos = modifyExtendingRightForward(granularity);
break;
case FORWARD:
if (alter == EXTEND)
pos = modifyExtendingRightForward(granularity);
else
pos = modifyMovingForward(granularity);
break;
case LEFT:
if (alter == MOVE)
pos = modifyMovingLeft(granularity);
else
pos = modifyExtendingLeftBackward(granularity);
break;
case BACKWARD:
if (alter == EXTEND)
pos = modifyExtendingLeftBackward(granularity);
else
pos = modifyMovingBackward(granularity);
break;
}
if (pos.isNull())
return false;
// Some of the above operations set an xPosForVerticalArrowNavigation.
// Setting a selection will clear it, so save it to possibly restore later.
// Note: the START position type is arbitrary because it is unused, it would be
// the requested position type if there were no xPosForVerticalArrowNavigation set.
int x = xPosForVerticalArrowNavigation(START);
switch (alter) {
case MOVE:
moveTo(pos, userTriggered);
break;
case EXTEND:
setExtent(pos, userTriggered);
break;
}
if (granularity == LineGranularity || granularity == ParagraphGranularity)
m_xPosForVerticalArrowNavigation = x;
if (userTriggered) {
// User modified selection change also sets the granularity back to character.
// NOTE: The one exception is that we need to keep word granularity to
// preserve smart delete behavior when extending by word (e.g. double-click),
// then shift-option-right arrow, then delete needs to smart delete, per TextEdit.
if (!(alter == EXTEND && granularity == WordGranularity && m_frame->selectionGranularity() == WordGranularity))
m_frame->setSelectionGranularity(CharacterGranularity);
}
setNeedsLayout();
return true;
}
// FIXME: Maybe baseline would be better?
static bool caretY(const VisiblePosition &c, int &y)
{
IntRect rect = c.caretRect();
if (rect.isEmpty())
return false;
y = rect.y() + rect.height() / 2;
return true;
}
bool SelectionController::modify(EAlteration alter, int verticalDistance, bool userTriggered)
{
if (verticalDistance == 0)
return false;
if (userTriggered) {
SelectionController trialSelectionController;
trialSelectionController.setSelection(m_sel);
trialSelectionController.modify(alter, verticalDistance, false);
bool change = m_frame->shouldChangeSelection(trialSelectionController.selection());
if (!change)
return false;
}
bool up = verticalDistance < 0;
if (up)
verticalDistance = -verticalDistance;
willBeModified(alter, up ? BACKWARD : FORWARD);
VisiblePosition pos;
int xPos = 0;
switch (alter) {
case MOVE:
pos = VisiblePosition(up ? m_sel.start() : m_sel.end(), m_sel.affinity());
xPos = xPosForVerticalArrowNavigation(up ? START : END);
m_sel.setAffinity(up ? UPSTREAM : DOWNSTREAM);
break;
case EXTEND:
pos = VisiblePosition(m_sel.extent(), m_sel.affinity());
xPos = xPosForVerticalArrowNavigation(EXTENT);
m_sel.setAffinity(DOWNSTREAM);
break;
}
int startY;
if (!caretY(pos, startY))
return false;
if (up)
startY = -startY;
int lastY = startY;
VisiblePosition result;
VisiblePosition next;
for (VisiblePosition p = pos; ; p = next) {
next = (up ? previousLinePosition : nextLinePosition)(p, xPos);
if (next.isNull() || next == p)
break;
int nextY;
if (!caretY(next, nextY))
break;
if (up)
nextY = -nextY;
if (nextY - startY > verticalDistance)
break;
if (nextY >= lastY) {
lastY = nextY;
result = next;
}
}
if (result.isNull())
return false;
switch (alter) {
case MOVE:
moveTo(result, userTriggered);
break;
case EXTEND:
setExtent(result, userTriggered);
break;
}
if (userTriggered)
m_frame->setSelectionGranularity(CharacterGranularity);
return true;
}
bool SelectionController::expandUsingGranularity(TextGranularity granularity)
{
if (isNone())
return false;
m_sel.expandUsingGranularity(granularity);
m_needsLayout = true;
return true;
}
int SelectionController::xPosForVerticalArrowNavigation(EPositionType type)
{
int x = 0;
if (isNone())
return x;
Position pos;
switch (type) {
case START:
pos = m_sel.start();
break;
case END:
pos = m_sel.end();
break;
case BASE:
pos = m_sel.base();
break;
case EXTENT:
pos = m_sel.extent();
break;
}
Frame *frame = pos.node()->document()->frame();
if (!frame)
return x;
if (m_xPosForVerticalArrowNavigation == NoXPosForVerticalArrowNavigation) {
VisiblePosition visiblePosition(pos, m_sel.affinity());
// VisiblePosition creation can fail here if a node containing the selection becomes visibility:hidden
// after the selection is created and before this function is called.
x = visiblePosition.isNotNull() ? visiblePosition.caretRect().x() : 0;
m_xPosForVerticalArrowNavigation = x;
}
else
x = m_xPosForVerticalArrowNavigation;
return x;
}
void SelectionController::clear()
{
setSelection(Selection());
}
void SelectionController::setBase(const VisiblePosition &pos, bool userTriggered)
{
setSelection(Selection(pos.deepEquivalent(), m_sel.extent(), pos.affinity()), true, true, userTriggered);
}
void SelectionController::setExtent(const VisiblePosition &pos, bool userTriggered)
{
setSelection(Selection(m_sel.base(), pos.deepEquivalent(), pos.affinity()), true, true, userTriggered);
}
void SelectionController::setBase(const Position &pos, EAffinity affinity, bool userTriggered)
{
setSelection(Selection(pos, m_sel.extent(), affinity), true, true, userTriggered);
}
void SelectionController::setExtent(const Position &pos, EAffinity affinity, bool userTriggered)
{
setSelection(Selection(m_sel.base(), pos, affinity), true, true, userTriggered);
}
void SelectionController::setNeedsLayout(bool flag)
{
m_needsLayout = flag;
}
void SelectionController::layout()
{
if (isNone() || !m_sel.start().node()->inDocument() || !m_sel.end().node()->inDocument()) {
m_caretRect = IntRect();
m_caretPositionOnLayout = IntPoint();
return;
}
m_sel.start().node()->document()->updateRendering();
m_caretRect = IntRect();
m_caretPositionOnLayout = IntPoint();
if (isCaret()) {
VisiblePosition pos(m_sel.start(), m_sel.affinity());
if (pos.isNotNull()) {
ASSERT(pos.deepEquivalent().node()->renderer());
m_caretRect = pos.caretRect();
int x, y;
pos.deepEquivalent().node()->renderer()->absolutePositionForContent(x, y);
m_caretPositionOnLayout = IntPoint(x, y);
}
}
m_needsLayout = false;
}
IntRect SelectionController::caretRect() const
{
if (m_needsLayout)
const_cast<SelectionController *>(this)->layout();
IntRect caret = m_caretRect;
if (m_sel.start().node() && m_sel.start().node()->renderer()) {
int x, y;
m_sel.start().node()->renderer()->absolutePositionForContent(x, y);
caret.move(IntPoint(x, y) - m_caretPositionOnLayout);
}
return caret;
}
static IntRect repaintRectForCaret(IntRect caret)
{
if (caret.isEmpty())
return IntRect();
// Ensure that the dirty rect intersects the block that paints the caret even in the case where
// the caret itself is just outside the block. See <https://bugs.webkit.org/show_bug.cgi?id=19086>.
caret.inflateX(1);
return caret;
}
IntRect SelectionController::caretRepaintRect() const
{
return repaintRectForCaret(caretRect());
}
bool SelectionController::recomputeCaretRect()
{
if (!m_frame || !m_frame->document())
return false;
FrameView* v = m_frame->document()->view();
if (!v)
return false;
if (!m_needsLayout)
return false;
IntRect oldRect = m_caretRect;
m_needsLayout = true;
IntRect newRect = caretRect();
if (oldRect == newRect)
return false;
v->updateContents(repaintRectForCaret(oldRect), false);
v->updateContents(repaintRectForCaret(newRect), false);
return true;
}
void SelectionController::invalidateCaretRect()
{
if (!isCaret())
return;
FrameView* v = m_sel.start().node()->document()->view();
if (!v)
return;
bool caretRectChanged = recomputeCaretRect();
// EDIT FIXME: This is an unfortunate hack.
// Basically, we can't trust this layout position since we
// can't guarantee that the check to see if we are in unrendered
// content will work at this point. We may have to wait for
// a layout and re-render of the document to happen. So, resetting this
// flag will cause another caret layout to happen the first time
// that we try to paint the caret after this call. That one will work since
// it happens after the document has accounted for any editing
// changes which may have been done.
// And, we need to leave this layout here so the caret moves right
// away after clicking.
m_needsLayout = true;
if (!caretRectChanged)
v->updateContents(caretRepaintRect(), false);
}
void SelectionController::paintCaret(GraphicsContext *p, const IntRect &rect)
{
if (! m_sel.isCaret())
return;
if (m_needsLayout)
layout();
IntRect caret = intersection(caretRect(), rect);
if (!caret.isEmpty()) {
Color caretColor = Color::black;
Element* element = rootEditableElement();
if (element && element->renderer())
caretColor = element->renderer()->style()->color();
p->fillRect(caret, caretColor);
}
}
void SelectionController::debugRenderer(RenderObject *r, bool selected) const
{
if (r->node()->isElementNode()) {
Element *element = static_cast<Element *>(r->node());
fprintf(stderr, "%s%s\n", selected ? "==> " : " ", element->localName().string().utf8().data());
}
else if (r->isText()) {
RenderText* textRenderer = static_cast<RenderText*>(r);
if (textRenderer->textLength() == 0 || !textRenderer->firstTextBox()) {
fprintf(stderr, "%s#text (empty)\n", selected ? "==> " : " ");
return;
}
static const int max = 36;
String text = textRenderer->text();
int textLength = text.length();
if (selected) {
int offset = 0;
if (r->node() == m_sel.start().node())
offset = m_sel.start().offset();
else if (r->node() == m_sel.end().node())
offset = m_sel.end().offset();
int pos;
InlineTextBox *box = textRenderer->findNextInlineTextBox(offset, pos);
text = text.substring(box->m_start, box->m_len);
String show;
int mid = max / 2;
int caret = 0;
// text is shorter than max
if (textLength < max) {
show = text;
caret = pos;
}
// too few characters to left
else if (pos - mid < 0) {
show = text.left(max - 3) + "...";
caret = pos;
}
// enough characters on each side
else if (pos - mid >= 0 && pos + mid <= textLength) {
show = "..." + text.substring(pos - mid + 3, max - 6) + "...";
caret = mid;
}
// too few characters on right
else {
show = "..." + text.right(max - 3);
caret = pos - (textLength - show.length());
}
show.replace('\n', ' ');
show.replace('\r', ' ');
fprintf(stderr, "==> #text : \"%s\" at offset %d\n", show.utf8().data(), pos);
fprintf(stderr, " ");
for (int i = 0; i < caret; i++)
fprintf(stderr, " ");
fprintf(stderr, "^\n");
}
else {
if ((int)text.length() > max)
text = text.left(max - 3) + "...";
else
text = text.left(max);
fprintf(stderr, " #text : \"%s\"\n", text.utf8().data());
}
}
}
bool SelectionController::contains(const IntPoint& point)
{
Document* document = m_frame->document();
// Treat a collapsed selection like no selection.
if (!isRange())
return false;
if (!document->renderer())
return false;
HitTestRequest request(true, true);
HitTestResult result(point);
document->renderer()->layer()->hitTest(request, result);
Node* innerNode = result.innerNode();
if (!innerNode || !innerNode->renderer())
return false;
VisiblePosition visiblePos(innerNode->renderer()->positionForPoint(result.localPoint()));
if (visiblePos.isNull())
return false;
if (m_sel.visibleStart().isNull() || m_sel.visibleEnd().isNull())
return false;
Position start(m_sel.visibleStart().deepEquivalent());
Position end(m_sel.visibleEnd().deepEquivalent());
Position p(visiblePos.deepEquivalent());
return comparePositions(start, p) <= 0 && comparePositions(p, end) <= 0;
}
// Workaround for the fact that it's hard to delete a frame.
// Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
// Can't do this implicitly as part of every setSelection call because in some contexts it might not be good
// for the focus to move to another frame. So instead we call it from places where we are selecting with the
// mouse or the keyboard after setting the selection.
void SelectionController::selectFrameElementInParentIfFullySelected()
{
// Find the parent frame; if there is none, then we have nothing to do.
Frame* parent = m_frame->tree()->parent();
if (!parent)
return;
Page* page = m_frame->page();
if (!page)
return;
// Check if the selection contains the entire frame contents; if not, then there is nothing to do.
if (!isRange())
return;
if (!isStartOfDocument(selection().visibleStart()))
return;
if (!isEndOfDocument(selection().visibleEnd()))
return;
// Get to the <iframe> or <frame> (or even <object>) element in the parent frame.
Document* doc = m_frame->document();
if (!doc)
return;
Element* ownerElement = doc->ownerElement();
if (!ownerElement)
return;
Node* ownerElementParent = ownerElement->parentNode();
if (!ownerElementParent)
return;
// This method's purpose is it to make it easier to select iframes (in order to delete them). Don't do anything if the iframe isn't deletable.
if (!ownerElementParent->isContentEditable())
return;
// Create compute positions before and after the element.
unsigned ownerElementNodeIndex = ownerElement->nodeIndex();
VisiblePosition beforeOwnerElement(VisiblePosition(ownerElementParent, ownerElementNodeIndex, SEL_DEFAULT_AFFINITY));
VisiblePosition afterOwnerElement(VisiblePosition(ownerElementParent, ownerElementNodeIndex + 1, VP_UPSTREAM_IF_POSSIBLE));
// Focus on the parent frame, and then select from before this element to after.
Selection newSelection(beforeOwnerElement, afterOwnerElement);
if (parent->shouldChangeSelection(newSelection)) {
page->focusController()->setFocusedFrame(parent);
parent->selectionController()->setSelection(newSelection);
}
}
void SelectionController::selectAll()
{
Document* document = m_frame->document();
if (!document)
return;
if (document->focusedNode() && document->focusedNode()->canSelectAll()) {
document->focusedNode()->selectAll();
return;
}
Node* root = isContentEditable() ? highestEditableRoot(m_sel.start()) : document->documentElement();
if (!root)
return;
Selection newSelection(Selection::selectionFromContentsOfNode(root));
if (m_frame->shouldChangeSelection(newSelection))
setSelection(newSelection);
selectFrameElementInParentIfFullySelected();
m_frame->notifyRendererOfSelectionChange(true);
}
bool SelectionController::setSelectedRange(Range* range, EAffinity affinity, bool closeTyping)
{
if (!range)
return false;
ExceptionCode ec = 0;
Node* startContainer = range->startContainer(ec);
if (ec)
return false;
Node* endContainer = range->endContainer(ec);
if (ec)
return false;
ASSERT(startContainer);
ASSERT(endContainer);
ASSERT(startContainer->document() == endContainer->document());
m_frame->document()->updateLayoutIgnorePendingStylesheets();
// Non-collapsed ranges are not allowed to start at the end of a line that is wrapped,
// they start at the beginning of the next line instead
bool collapsed = range->collapsed(ec);
if (ec)
return false;
int startOffset = range->startOffset(ec);
if (ec)
return false;
int endOffset = range->endOffset(ec);
if (ec)
return false;
// FIXME: Can we provide extentAffinity?
VisiblePosition visibleStart(startContainer, startOffset, collapsed ? affinity : DOWNSTREAM);
VisiblePosition visibleEnd(endContainer, endOffset, SEL_DEFAULT_AFFINITY);
setSelection(Selection(visibleStart, visibleEnd), closeTyping);
return true;
}
bool SelectionController::isInPasswordField() const
{
Node* startNode = start().node();
if (!startNode)
return false;
startNode = startNode->shadowAncestorNode();
if (!startNode)
return false;
if (!startNode->hasTagName(inputTag))
return false;
return static_cast<HTMLInputElement*>(startNode)->inputType() == HTMLInputElement::PASSWORD;
}
bool SelectionController::isInsideNode() const
{
Node* startNode = start().node();
if (!startNode)
return false;
return !isTableElement(startNode) && !editingIgnoresContent(startNode);
}
void SelectionController::focusedOrActiveStateChanged()
{
bool activeAndFocused = isFocusedAndActive();
// Because RenderObject::selectionBackgroundColor() and
// RenderObject::selectionForegroundColor() check if the frame is active,
// we have to update places those colors were painted.
if (m_frame->view())
m_frame->view()->updateContents(enclosingIntRect(m_frame->selectionRect()));
// Caret appears in the active frame.
if (activeAndFocused)
m_frame->setSelectionFromNone();
m_frame->setCaretVisible(activeAndFocused);
// Update for caps lock state
m_frame->eventHandler()->capsLockStateMayHaveChanged();
// Because CSSStyleSelector::checkOneSelector() and
// RenderTheme::isFocused() check if the frame is active, we have to
// update style and theme state that depended on those.
if (Node* node = m_frame->document()->focusedNode()) {
node->setChanged();
if (RenderObject* renderer = node->renderer())
if (renderer && renderer->style()->hasAppearance())
theme()->stateChanged(renderer, FocusState);
}
// Secure keyboard entry is set by the active frame.
if (m_frame->document()->useSecureKeyboardEntryWhenActive())
m_frame->setUseSecureKeyboardEntry(activeAndFocused);
}
void SelectionController::pageActivationChanged()
{
focusedOrActiveStateChanged();
}
void SelectionController::setFocused(bool flag)
{
if (m_focused == flag)
return;
m_focused = flag;
focusedOrActiveStateChanged();
if (Document* doc = m_frame->document())
doc->dispatchWindowEvent(flag ? focusEvent : blurEvent, false, false);
}
bool SelectionController::isFocusedAndActive() const
{
return m_focused && m_frame->page() && m_frame->page()->focusController()->isActive();
}
#ifndef NDEBUG
void SelectionController::formatForDebugger(char* buffer, unsigned length) const
{
m_sel.formatForDebugger(buffer, length);
}
void SelectionController::showTreeForThis() const
{
m_sel.showTreeForThis();
}
#endif
}
#ifndef NDEBUG
void showTree(const WebCore::SelectionController& sel)
{
sel.showTreeForThis();
}
void showTree(const WebCore::SelectionController* sel)
{
if (sel)
sel->showTreeForThis();
}
#endif
|