[PATCH 4/4] editor: more intuitive cursor positioning

Philipp Brüschweiler blei42 at gmail.com
Tue Oct 2 02:06:54 PDT 2012


Compute the nearest glyph edge instead of taking the one to the
left of the cursor.

Also fixes a segfault when trying to compute the position for an empty
buffer.
---
 clients/editor.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)

diff --git a/clients/editor.c b/clients/editor.c
index 7e6845f..7446a2b 100644
--- a/clients/editor.c
+++ b/clients/editor.c
@@ -153,18 +153,26 @@ text_layout_xy_to_index(struct text_layout *layout, double x, double y)
 {
 	cairo_text_extents_t extents;
 	int i;
+	double d;
+
+	if (layout->num_glyphs == 0)
+		return 0;
 
 	cairo_scaled_font_glyph_extents(layout->font,
 					layout->glyphs, layout->num_glyphs,
 					&extents);
 
-	for (i = 1; i < layout->num_glyphs; i++) {
-		if (layout->glyphs[i].x >= x) {
-			return i - 1;
-		}
+	if (x < 0)
+		return 0;
+
+	for (i = 0; i < layout->num_glyphs - 1; ++i) {
+		d = layout->glyphs[i + 1].x - layout->glyphs[i].x;
+		if (x < layout->glyphs[i].x + d/2)
+			return i;
 	}
 
-	if (x >= layout->glyphs[layout->num_glyphs - 1].x && x < extents.width)
+	d = extents.width - layout->glyphs[layout->num_glyphs - 1].x;
+	if (x < layout->glyphs[layout->num_glyphs - 1].x + d/2)
 		return layout->num_glyphs - 1;
 
 	return layout->num_glyphs;
-- 
1.7.12.2



More information about the wayland-devel mailing list