Caret moves after clicked char if closer to its right rect boundary.

Bug: chromium:832293
Change-Id: Idd240010a5ec99b836d9cb90c4c2aa3027ff5f67
Reviewed-on: https://pdfium-review.googlesource.com/31013
Commit-Queue: Henrique Nakashima <hnakashima@chromium.org>
Reviewed-by: dsinclair <dsinclair@chromium.org>
Reviewed-by: Ryan Harrison <rharrison@chromium.org>
diff --git a/xfa/fde/cfde_texteditengine.cpp b/xfa/fde/cfde_texteditengine.cpp
index a423ba6..fd5b101 100644
--- a/xfa/fde/cfde_texteditengine.cpp
+++ b/xfa/fde/cfde_texteditengine.cpp
@@ -899,8 +899,6 @@
 
   size_t start_it_idx = start_it->nStart;
   for (; start_it <= end_it; ++start_it) {
-    // We need to handle clicking off the end of the line. Using Contains()
-    // would constrain the detection to the text on the line.
     bool piece_contains_point_vertically =
         (point.y >= start_it->rtPiece.top &&
          point.y < start_it->rtPiece.bottom());
@@ -913,7 +911,14 @@
           (point.x >= rects[i].left && point.x < rects[i].right());
       if (!character_contains_point_horizontally)
         continue;
-      size_t pos = start_it->nStart + i;
+
+      // When clicking on the left half of a character, the cursor should be
+      // moved before it. If the click was on the right half of that character,
+      // move the cursor after it.
+      bool closer_to_left =
+          (point.x - rects[i].left < rects[i].right() - point.x);
+      int caret_pos = (closer_to_left ? i : i + 1);
+      size_t pos = start_it->nStart + caret_pos;
       if (pos >= text_length_)
         return text_length_;
 
diff --git a/xfa/fde/cfde_texteditengine_unittest.cpp b/xfa/fde/cfde_texteditengine_unittest.cpp
index e279f8e..7ae001a 100644
--- a/xfa/fde/cfde_texteditengine_unittest.cpp
+++ b/xfa/fde/cfde_texteditengine_unittest.cpp
@@ -416,6 +416,7 @@
   EXPECT_EQ(0U, engine()->GetIndexForPoint({0.0f, 0.0f}));
   EXPECT_EQ(11U, engine()->GetIndexForPoint({999999.0f, 9999999.0f}));
   EXPECT_EQ(11U, engine()->GetIndexForPoint({999999.0f, 0.0f}));
+  EXPECT_EQ(1U, engine()->GetIndexForPoint({5.0f, 5.0f}));
   EXPECT_EQ(1U, engine()->GetIndexForPoint({10.0f, 5.0f}));
 }
 
@@ -427,7 +428,8 @@
   EXPECT_EQ(0U, engine()->GetIndexForPoint({0.0f, 0.0f}));
   EXPECT_EQ(87U, engine()->GetIndexForPoint({999999.0f, 9999999.0f}));
   EXPECT_EQ(12U, engine()->GetIndexForPoint({999999.0f, 0.0f}));
-  EXPECT_EQ(1U, engine()->GetIndexForPoint({10.0f, 5.0f}));
+  EXPECT_EQ(1U, engine()->GetIndexForPoint({5.0f, 5.0f}));
+  EXPECT_EQ(2U, engine()->GetIndexForPoint({10.0f, 5.0f}));
 }
 
 TEST_F(CFDE_TextEditEngineTest, BoundsForWordAt) {