File tree Expand file tree Collapse file tree 2 files changed +37
-12
lines changed Expand file tree Collapse file tree 2 files changed +37
-12
lines changed Original file line number Diff line number Diff line change @@ -279,6 +279,41 @@ def _get_multialignment(self):
279
279
else :
280
280
return self ._horizontalalignment
281
281
282
+ def _char_index_at (self , x ):
283
+ """
284
+ Calculates the index nearer to x, we accumulate
285
+ the width of each character contained in the text
286
+ and find the index at which the distance between the
287
+ click position and the accumulated sum is minimal.
288
+ This works only on single line texts.
289
+ """
290
+
291
+ if (not hasattr (self , "_saved_fontproperties" ) or
292
+ str (self ._fontproperties ) != self ._saved_fontproperties ):
293
+
294
+ self ._saved_fontproperties = str (self ._fontproperties )
295
+ self ._chars_size = dict () # to cache results
296
+
297
+ text = self ._text
298
+
299
+ if len (text ) == 0 :
300
+ return 0
301
+
302
+ else :
303
+ for char in set (text ):
304
+ if char not in self ._chars_size :
305
+ self .set_text (char )
306
+ bb = self .get_window_extent ()
307
+ self ._chars_size [char ] = bb .x1 - bb .x0
308
+
309
+
10000
self .set_text (text )
310
+ bb = self .get_window_extent ()
311
+
312
+ size_accum = np .cumsum ([0 ] + [self ._chars_size [x ] for x in text ])
313
+
314
+ std_x = x - bb .x0
315
+ return (np .abs (size_accum - std_x )).argmin ()
316
+
282
317
def get_rotation (self ):
283
318
"""Return the text angle in degrees between 0 and 360."""
284
319
if self .get_transform_rotates_text ():
Original file line number Diff line number Diff line change @@ -1315,17 +1315,6 @@ def stop_typing(self):
1315
1315
# call it once we've already done our cleanup.
1316
1316
self ._observers .process ('submit' , self .text )
1317
1317
1318
- def position_cursor (self , x ):
1319
- # now, we have to figure out where the cursor goes.
1320
- # approximate it based on assuming all characters the same length
1321
- if len (self .text ) == 0 :
1322
- self .cursor_index = 0
1323
- else :
1324
- bb = self .text_disp .get_window_extent ()
1325
- ratio = np .clip ((x - bb .x0 ) / bb .width , 0 , 1 )
1326
- self .cursor_index = int (len (self .text ) * ratio )
1327
- self ._rendercursor ()
1328
-
1329
1318
def _click (self , event ):
1330
1319
if self .ignore (event ):
1331
1320
return
@@ -1338,7 +1327,8 @@ def _click(self, event):
1338
1327
event .canvas .grab_mouse (self .ax )
1339
1328
if not self .capturekeystrokes :
1340
1329
self .begin_typing (event .x )
1341
- self .position_cursor (event .x )
1330
+ self .cursor_index = self .text_disp ._char_index_at (event .x )
1331
+ self ._rendercursor ()
1342
1332
1343
1333
def _resize (self , event ):
1344
1334
self .stop_typing ()
You can’t perform that action at this time.
0 commit comments