File: display-text.lisp

package info (click to toggle)
clue 20011230
  • links: PTS
  • area: main
  • in suites: woody
  • size: 6,112 kB
  • ctags: 2,646
  • sloc: lisp: 31,991; makefile: 40; sh: 24
file content (1481 lines) | stat: -rw-r--r-- 54,494 bytes parent folder | download | duplicates (4)
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
;;; -*- Mode:Lisp; Package:CLIO-OPEN; Base:10; Lowercase:T; Syntax:Common-Lisp -*-


;;;----------------------------------------------------------------------------------+
;;;                                                                                  |
;;;                          TEXAS INSTRUMENTS INCORPORATED                          |
;;;                                  P.O. BOX 149149                                 |
;;;                             AUSTIN, TEXAS 78714-9149                             |
;;;                                                                                  |
;;;             Copyright (C) 1990, 1990 Texas Instruments Incorporated.             |
;;;                                                                                  |
;;; Permission is granted to any individual or institution to use, copy, modify, and |
;;; distribute this software, provided that  this complete copyright and  permission |
;;; notice is maintained, intact, in all copies and supporting documentation.        |
;;;                                                                                  |
;;; Texas Instruments Incorporated provides this software "as is" without express or |
;;; implied warranty.                                                                |
;;;                                                                                  |
;;;----------------------------------------------------------------------------------+

(in-package "CLIO-OPEN")

(export '(
	  *default-display-text-font*
	  display-text
	  display-text-alignment
	  display-text-copy
	  display-text-field
	  display-text-font
	  display-text-selection 
	  display-text-source
	  edit-text-mark
	  edit-text-point
	  make-display-text
	  make-display-text-field
	  )
	'clio-open)

;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                select-text                                 |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defcontact select-text ()
  ((point :type     text-mark
	  :initform nil
	  :initarg  :point
	  :reader   edit-text-point)		       ; setf defined below
   
   (mark  :type     text-mark
	  :initarg  :mark
	  :initform -1				       ; a value representing "undefined"
	  :reader   edit-text-mark))		       ; setf defined below 
  
  (:resources point mark)

  (:documentation "Text that may be selected interactively."))



;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                            Selection Handling                              |
;;;                                                                            |
;;;----------------------------------------------------------------------------+


(defgeneric (setf text-selection-displayed-p) (boolean text &optional exposed-x exposed-y exposed-width exposed-height)
  (:documentation "Turn on/off the display of the current TEXT selection."))

(defmethod (setf text-selection-displayed-p) (boolean (text select-text) &optional
					      exposed-x exposed-y exposed-width exposed-height)
  (declare (ignore boolean))
  (multiple-value-bind (from to) (text-selection-range text)
    (when from
      (text-change-highlight text from to exposed-x exposed-y exposed-width exposed-height))))

(defun text-selection-range (text)
  (with-slots (point mark buffer) (the select-text text)
    (multiple-value-bind (start end equal-p) (mark-range buffer point mark)
      (unless equal-p
	(values start end)))))

(defgeneric display-text-copy (text)
  (:documentation "Causes the current TEXT selection to become the :CLIPBOARD selection.
Returns the selected string."))

(defmethod display-text-selection ((text select-text))
  (multiple-value-bind (start end) (text-selection-range text)
    (when start
      (display-text-source text :start start :end end))))

(defgeneric text-change-highlight (text from to &optional exposed-x exposed-y exposed-width exposed-height)
  (:documentation "Turn on/off highlighting of TEXT between the FROM and TO positions."))
  
(defgeneric (setf text-caret-displayed-p)
	    (boolean text &optional exposed-x exposed-y exposed-width exposed-height)
  (:documentation "Turn on/off the display of the TEXT caret."))




;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                 Accessors                                  |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defmacro while-changing-marks ((text &optional time) &body body)
  `(progn 
     (setf (text-caret-displayed-p ,text) nil)

     ,@body

     ;; Update :primary ownership.
     (text-own-selection ,text :primary ,time)
 
     (setf (text-caret-displayed-p ,text) t)))


(defgeneric (setf edit-text-mark) (new-mark text)
  (:documentation "Change the selection mark for the TEXT."))

(defmethod (setf edit-text-mark) (new-mark (text select-text))
  (with-slots (buffer mark display) text
    (unless (mark-equal new-mark mark)
      (while-changing-marks (text (when (processing-event-p) (with-event (time) time)))
	(text-change-highlight text new-mark mark)
	(setf mark (move-mark mark new-mark)))))
  new-mark)

(defgeneric (setf edit-text-point) (new-point text &key clear-p)
  (:documentation "Change the insert point for the TEXT. If CLEAR-P is true,
then the mark is also changed to clear the current selection."))

(defmethod (setf edit-text-point) (new-point (text select-text) &key clear-p)
  (with-slots (display buffer point mark) text
    (unless (mark-equal new-point point)
      (while-changing-marks (text (when (processing-event-p) (with-event (time) time)))
	(when clear-p (text-change-highlight text new-point mark))
	(text-change-highlight text new-point point)

	;; Update marks
	(setf point (move-mark point new-point))
	(when clear-p (setf mark (move-mark mark new-point))))))
  new-point)


(defmethod (setf display-text-source) :after (new-value (text select-text)
				       &key (start 0) end (from-start 0) from-end)
  (declare (ignore new-value start end from-start from-end)) 
  (with-slots (buffer point mark) text
    ;; Ensure valid insertion point and clear selection.
    
    ;; Note: primary method causes exposure and redisplay, so no need to update
    ;; selection highlighting here.
    (setf mark (move-mark mark (setf point (move-mark point (mark-range buffer point nil)))))))


(defmethod display-text-copy ((text select-text))
  (with-slots (point) text
    (prog1
      (clipboard-copy text)
      (setf (edit-text-mark text) point))))

(defgeneric display-text-selection (text)
  (:documentation "Returns the current TEXT selection."))



;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                          Initialization                                    |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defmethod initialize-instance :after ((text select-text) &rest initargs)
  (declare (ignore initargs))
  (with-slots (point mark) text
    (setf (edit-text-point text) point)
    (setf (edit-text-mark text) (if (eql -1 mark) point mark))))



;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                              Event Handling                                |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defevent select-text :selection-clear                       (text-selection-clear nil))
(defevent select-text :selection-request                     text-selection-request)
(defevent select-text (:button-press   :button-2)            text-adjust-selection)
(defevent select-text (:button-press   :button-1 :meta)      display-text-copy)
(defevent select-text (:button-release :button-1)            text-handle-release)
(defevent select-text (:button-press   :button-1 :none :all) text-start-selection)
(defevent select-text (:motion-notify  :button-1)            text-drag-selection)



(let ((new-mark (make-mark)))

  (defun text-start-selection (text)
    (declare (type select-text text))
    (with-slots (display mark point buffer) (the select-text text)
      (with-event (x y time)
	
	;; Undisplay either caret or current text selection.
	(setf (text-selection-displayed-p text) nil)
	(while-changing-marks (text time)
	  
	  (multiple-value-bind
	    (*current-left* *current-top* *current-width* *current-height* *current-ascent* *current-descent*)
	      (text-geometry text)
	    
	    (declare (special *current-left* *current-top*
			      *current-width* *current-height*
			      *current-ascent* *current-descent*))
	    
	    (let
	      ((new-mark            (text-point-mark text x y new-mark))
	       (*pointer-selection* t)
	       (display             (contact-display text)))
	      (declare (special *pointer-selection*))
	      
	      
	      ;; Initialize selection.
	      (setf
		mark  (move-mark mark new-mark)
		point (move-mark point new-mark))
	      
	      ;; Complete text selection interaction.
	      (catch :pointer-selection
		(loop (process-next-event display)))
	      (apply-callback
		text :point text (buffer-mark-position buffer point))))))))



  (defun text-drag-selection (text)
    (declare (special *pointer-selection*))
    (declare (type select-text text))
    
    (when (boundp '*pointer-selection*)
      (with-event (x y)
	(let ((new-mark (text-point-mark text x y new-mark)))
	  (with-slots (point) (the select-text text)
	    (text-change-highlight text point new-mark)
	    (setf point (move-mark point new-mark)))))))

  (defun text-adjust-selection (text)
    (declare (type select-text text))
    (when (text-selection-range text)
      (with-event (x y)
	(setf (edit-text-point text)
	      (text-point-mark text x y new-mark))
	(with-slots (point buffer) (the select-text text)
	  (apply-callback text :point text (buffer-mark-position buffer point)))))))


(defun text-handle-release (text)
  (declare (ignore text))
  (declare (special *pointer-selection*))
  (when (boundp '*pointer-selection*) 
    (throw :pointer-selection nil)))



;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                            Selection Ownership                             |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defun display-selection-owner (display selection)
  "Return the owner window and time of ownership for the SELECTION."
  (let ((entry (getf (getf (display-plist display) 'selections) selection)))
    (values
      (first entry)		  ; Owner window
      (second entry))))		  ; Timestamp

(defsetf display-selection-owner (display selection &optional timestamp) (owner) 
  `(setf-display-selection-owner ,display ,selection ,timestamp ,owner))

(defun setf-display-selection-owner (display selection timestamp owner)
  (assert (or (not owner) timestamp) nil
	  "Must give non-NIL timestamp for ~a to own ~s selection."
	  owner selection)
  (let ((entry (or
		 (getf (getf (display-plist display) 'selections) selection)
		 (setf
		   (getf (getf (display-plist display) 'selections) selection)
		   (list nil nil)))))
    (setf
      (first entry)  owner
      (second entry) timestamp)
    (values owner timestamp)))



(defgeneric text-selection-clear (text selection)
  (:documentation "Perform result of TEXT losing ownership of the given SELECTION."))

(defmethod text-selection-clear ((text contact) selection)
  (with-slots (display) text
    (setf (display-selection-owner display selection) nil)))

(defmethod text-selection-clear ((text contact) (selection null))
  (text-selection-clear
    text
    (with-event ((event-selection selection)) event-selection)))

(defmethod text-selection-clear :after ((text select-text) (selection (eql :primary)))
  (with-slots (point) text
    (setf (edit-text-mark text) point)))



(defun text-selection-request (text)
  (with-event (requestor selection target time property)
    (selection-notify text requestor selection target time property)))

(defun selection-notify (text requestor selection target time property)
  (declare (type select-text text)) 
  (multiple-value-bind (property-name property-value property-format transform)
      (text-convert-selection text selection property target time)
    
    (when property-name 
      ;; Store converted reply property. 
      (change-property
	requestor property-name property-value target property-format :transform transform))
    
    ;; Send :selection-notify to requestor
    (send-event requestor :selection-notify nil
		:window requestor
		:selection selection
		:target target
		:property property-name
		:time time)

    ;; Return nil if failed to convert.
    property-name))

(defgeneric text-convert-selection (text selection property target time)
  (:documentation "Convert SELECTION (if owned by TEXT), to the given
TARGET type. TIME is the time of the conversion request. PROPERTY 
is the name of the property where the converted value should be stored.

Return values are the PROPERTY to be used (nil if conversion refused),
the converted VALUE, the FORMAT of the value, and the TRANSFORM function
to be used with change-property."))

(defmethod text-convert-selection (text selection property target time)
  ;; Default method for converting a SELECTION. Since this is called when
  ;; no other method exists, it always returns NIL to indicate that the SELECTION
  ;; is not supported.
  (declare (ignore text selection target time property))
  nil)

(defmethod text-convert-selection :around (text selection (property null) target time)
  ;; This method ensures conformance with the ICCCM convention that if no
  ;; PROPERTY atom is given by the requestor, the TARGET atom is used as the
  ;; name of the property where the converted value is stored.
  (when (not (eq :multiple target))
    (call-next-method text selection target target time)))

(defmethod text-convert-selection :around ((text contact) selection property (target (eql :multiple)) time)
  (with-event (requestor)
    (with-slots (display) text
      (values
	property

	;; Value returned is list of targets, updated for failed conversions.
	(do*
	  ((conversions
	     (get-property requestor property :transform #'(lambda (atom) (atom-name display atom))))
	   (targets
	     conversions (cddr targets)))
	  
	  ((endp targets)
	   ;; Crock! Have to apply the transform here to avoid a CLX R4.2 bug in change-property.
	   (mapcar
	     ;; Protocol encodes None atoms as 0. Future version of intern-atom should do this.
	     #'(lambda (a) (if a (intern-atom display a) 0))
	     conversions))
	  
	  (let ((target (first targets)) (property (second targets)))
	    (unless (selection-notify text requestor selection target time property)
	      ;; Mark failed target
	      (setf (getf conversions target) nil))))
	
	32))))

(flet
  ((convert-text (text selection property target time)
     (declare (type select-text text))
     (with-slots (display buffer) (the select-text text)
       (multiple-value-bind (owner owner-time) (display-selection-owner display selection)
	 (when
	   (and
	     ;; Selection owned?...
	     (eq text owner)
	     
	     ;; ...and Conversion time is...
	     (or
	       ;; ... CurrentTime?
	       (not time)
	       
	       ;; Crock! Remove this test when CLX maps CurrentTime correctly to nil!!
	       (zerop time)
	       
	       ;; ... later than owner time?
	       (> time owner-time)))
	   
	   ;; Convert successfully?
	   (case target
	     
	     ((:string :text)
	      (values property
		      (text-selection-string text selection)
		      8
		      #'xlib::char->card8))
	     
	     (:timestamp
	      (values property (list owner-time) 32 nil))
	     
	     (:targets
	      (values property
		      '(:string :text :targets :timestamp) 
		      32
		      #'(lambda (a) (intern-atom display a))))))))))

  (defmethod text-convert-selection ((text select-text) (selection (eql :primary)) property target time)
    (convert-text text selection property target time))

  (defmethod text-convert-selection ((text select-text) (selection (eql :clipboard)) property target time)
    (convert-text text selection property target time)))



(defgeneric text-selection-string (text selection)
  (:documentation "Return the TEXT string for the given SELECTION."))

(defmethod text-selection-string ((text select-text) (selection (eql :primary)))
  (with-slots (buffer) text
    (multiple-value-bind (start end) (text-selection-range text)
      (if start (buffer-subseq buffer start end) ""))))




(defgeneric text-own-selection (text selection time)
  (:documentation "Assert TEXT (non)ownership of the SELECTION at the given TIME.
This function should call (setf selection-owner) with owner as TEXT or nil, 
as needed."))

(defmethod text-own-selection ((text contact) selection time)
  (with-slots (display) text
    (or
      ;; Selection already owned?
      (let ((owner (display-selection-owner display selection))) 
	(unless (or (not owner) (eq owner text))
	  ;; Yes, change owner window.
	  (text-selection-clear owner selection)
	  
	  ;; Record new owner window/time.
	  (setf (selection-owner display selection time)
		(setf (display-selection-owner display selection time) text)))
	owner)
      
      ;; Selection ownership acquired?
      (progn
	(unless time
	  ;; Ensure actual timestamp is used, as per ICCCM.
	  (with-event-mode
	    (text
	      `((:property-notify :current-time)
		,#'(lambda (c) (declare (ignore c))
			   (with-event ((event-time time)) (setf time event-time)))))
	    
	    ;; Null property change just to generate a :property-notify timestamp
	    (change-property text :current-time nil :string 8 :mode :append)
	    
	    ;; Wait for :property-notify to be processed.
	    (do () (time) (process-next-event display))))
	
	;; Ownership request successful?
	(when (eq (setf (selection-owner display selection time) text)
		  (selection-owner display selection))
	  ;; Record owner window/time.
	  (setf (display-selection-owner display selection time) text))))))


(defmethod text-own-selection ((text select-text) (selection (eql :primary)) time)
  (with-slots (display point) text
    ;; Need to own selection?
    (if (text-selection-range text)
	
	;; Yes, ownership request successful?
	(or (call-next-method)
	    ;; No, abandon selection.
	    (when (setf (edit-text-mark text) point) nil)) 
	
	;; No, abandon ownership, if necessary
	(multiple-value-bind (owner owner-time) (display-selection-owner display selection)
	  (when (eq text owner)
	    (text-selection-clear text selection)
	    (setf (selection-owner display selection owner-time) nil))))))






;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                            display-text-field                              |
;;;                                                                            |
;;;----------------------------------------------------------------------------+
 
(defparameter *default-display-text-font*
	      "-*-*-medium-r-*-*-*-*-*-*-*-*-iso8859-1")

(defparameter *default-display-text-field-font*
	      "-*-*-bold-r-*-*-*-*-*-*-*-*-iso8859-1")

(defcontact display-text-field (gravity-mixin core contact)
  ((font      :type     fontable
	      :initform *default-display-text-field-font*
	      :reader   display-text-font	       ; setf defined below
	      :initarg  :font)

   (buffer    :type     (or buffer buffer-line)
	      :initform (make-buffer-line)) 

   (compress-exposures
              :initform :on))
  
  (:resources
    (border-width :initform 0)
    font
    (source :type string :initform ""))

  (:documentation
    "Presents a single line of text for viewing."))


;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                  Accessors                                 |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defmethod (setf display-text-font) (new-value (text display-text-field))
  (with-slots (font) text
    (setf font (find-font text new-value)))

  ;; Save original fontname requested. Used again when changing scale.
  (setf (getf (window-plist text) 'fontname) new-value)

  (multiple-value-bind (width height) (preferred-size text)
    (change-geometry text :width width :height height :accept-p t))
  
  (when (realized-p text)
    ;; Delay redisplay until :exposure handling to allow other class methods
    ;; a chance to prepare for redisplay.
    (clear-area text :exposures-p t))
  
  new-value)


(defgeneric display-text-source (text &key start end)
  (:documentation "Return the source substring of TEXT given by START/END."))

(defmethod display-text-source ((text display-text-field) &key (start 0) end)
  (with-slots (buffer) text
    (buffer-subseq buffer start end)))

(defgeneric (setf display-text-source) (new-string text &key start end from-start from-end)
  (:documentation 
     "Replace the source substring of TEXT given by START/END with the
      substring of NEW-STRING given by FROM-START/FROM-END."))

(defmethod (setf display-text-source) (new-value (text display-text-field)
				       &key (start 0) end (from-start 0) from-end)
  (let ((new (string new-value)))
    (with-slots (buffer) text
      (buffer-delete buffer start end)
      (buffer-insert buffer new start :start from-start :end from-end)

      (multiple-value-bind (width height) (preferred-size text)
	(change-geometry text :width width :height height :accept-p t))
      
      (when (realized-p text)
	;; Delay redisplay until :exposure handling to allow other class methods
	;; a chance to prepare for redisplay.
	(clear-area text :exposures-p t))
      
      new-value)))


;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                Initialization                              |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defun make-display-text-field (&rest initargs)
  (apply #'make-contact 'display-text-field initargs))

(defmethod initialize-instance :after ((text display-text-field) &key source &allow-other-keys)
  (setf (display-text-font text) (slot-value text 'font))
  (setf (display-text-source text) source))


;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                   Display                                  |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defmethod display ((text display-text-field) &optional x y width height &key)
  (declare (ignore x y width height))
  (with-slots (buffer) text
    (multiple-value-bind (x y) (text-base-point text)	    
      (text-display-chars text (buffer-line-chars buffer) x y)
      
      ;; Return base position for other methods to use
      (values x y))))


(defun text-display-chars (text chars x y &key (start 0) end)
  (declare (type display-text-field text))
  (with-slots (font foreground clip-rectangle) (the display-text-field text)
    (let ((sensitive-p (sensitive-p text)))
      (using-gcontext
	(gcontext
	  :drawable   text
	  :font       font
	  :fill-style (unless sensitive-p :stippled)
	  :stipple    (unless sensitive-p (contact-image-mask text 50%gray :depth 1))
	  :foreground foreground
	  :clip-mask  clip-rectangle)
	(draw-glyphs
	  text gcontext x y chars
	  :start start :end end)))))

(defgeneric text-refresh-line (text position &key clear-p base-x base-y)
  (:documentation "Clear and redisplay one line of TEXT, beginning at the given POSITION."))

(defmethod text-refresh-line ((text display-text-field) (position integer) &key (clear-p t) base-x base-y)
  (with-slots (buffer) text
    (unless (and base-x base-y)
      (multiple-value-setq (base-x base-y) (text-base-position text position)))
    
    ;; Clear line
    (when clear-p
      (text-clear-line text base-x base-y))
      
    ;; Redisplay chars
    (text-display-chars
      text (buffer-line-chars buffer)
      base-x base-y :start position)))

(defmethod text-refresh-line ((text display-text-field) (position null) &key (clear-p t) base-x base-y)
  ;; Nothing to do!
  (declare (ignore clear-p base-x base-y)))

(defgeneric text-clear-line (text base-x base-y)
  (:documentation "Clear one line of TEXT, beginning at the given base position."))

(defmethod text-clear-line ((text display-text-field) base-x base-y)
  (with-slots (font) text
    (clear-area
      text
      :x      base-x
      :y      (- base-y (font-ascent font))
      :height (+ (font-ascent font) (font-descent font)))))

(defmethod (setf text-caret-displayed-p) (boolean (text display-text-field)
					  &optional exposed-x exposed-y exposed-width exposed-height)
  ;; No caret displayed for non-editable text.
  (declare (ignore exposed-x exposed-y exposed-width exposed-height))
  boolean)


;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                   Geometry                                 |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defgeneric display-text-extent (text)
  (:documentation "Return the width, height, ascent, and descent of the TEXT extent rectangle."))

(defmethod display-text-extent ((text display-text-field))
  (with-slots (buffer font) text
    (multiple-value-bind (text-width a d l r font-ascent font-descent)
	(text-extents font (buffer-line-chars buffer))
      (declare (ignore a d l r))      
      (values text-width (+ font-ascent font-descent) font-ascent font-descent))))

(defmethod rescale :before ((text display-text-field))
  (with-slots (font) text
    ;; Find font for new scale, using original fontname requested.
    (setf font (find-font text (getf (window-plist text) 'fontname))))
  (when (realized-p text)
    (clear-area text :exposures-p t)))

(defmethod preferred-size ((text display-text-field) &key width height border-width)
  (with-slots
    ((contact-width width) (contact-height height) (contact-border-width border-width))
    text
    (multiple-value-bind (text-width text-height) (display-text-extent text)
            
      (values
	(max text-width (or width contact-width))
	(max text-height (or height contact-height))
	(or border-width contact-border-width)))))


(defgeneric text-geometry (text)
  (:documentation
    "Return the left, top, width, height, ascent, and descent of the TEXT extent rectangle."))

(defmethod text-geometry ((text display-text-field))
  (declare (special *current-left* *current-top*
		    *current-width* *current-height*
		    *current-ascent* *current-descent*))
  (if (boundp '*current-left*)
      (values  *current-left* *current-top*
	       *current-width* *current-height*
	       *current-ascent* *current-descent*)
      (compute-text-geometry text)))

(defgeneric compute-text-geometry (text))

(defmethod compute-text-geometry ((text display-text-field)) 
  (with-slots (gravity) (the display-text-field text)
    (multiple-value-bind (width height ascent descent) (display-text-extent text)
      (multiple-value-bind (left top)
	  
	  ;; Note: use FLOOR to compute position to be consistent with repositioning
	  ;; according to bit-gravity. Needed for small exposed regions to match
	  ;; up properly when redisplayed.
	  
	  (case gravity
	    (:north-west
	     (values
	       (display-clip-x text)
	       (display-clip-y text)))
	    
	    (:north
	     (values
	       (+ (display-clip-x text) (floor (- (display-clip-width text) width) 2))
	       (display-clip-y text)))
	    
	    (:north-east
	     (values
	       (+ (display-clip-x text) (- (display-clip-width text) width))
	       (display-clip-y text)))
	    
	    (:east
	     (values
	       (+ (display-clip-x text) (- (display-clip-width text) width))
	       (+ (display-clip-y text) (floor (- (display-clip-height text) height) 2))))
	    
	    (:center
	     (values
	       (+ (display-clip-x text) (floor (- (display-clip-width text) width) 2))
	       (+ (display-clip-y text) (floor (- (display-clip-height text) height) 2))))
	    
	    (:west
	     (values
	       (display-clip-x text)
	       (+ (display-clip-y text) (floor (- (display-clip-height text) height) 2))))
	    
	    (:south-east
	     (values
	       (+ (display-clip-x text) (- (display-clip-width text) width))
	       (+ (display-clip-y text) (- (display-clip-height text) height))))
	    
	    (:south
	     (values
	       (+ (display-clip-x text) (floor (- (display-clip-width text) width) 2))
	       (+ (display-clip-y text) (- (display-clip-height text) height))))
	    
	    (:south-west
	     (values
	       (display-clip-x text)
	       (+ (display-clip-y text) (- (display-clip-height text) height)))))
	
	(values left top width height ascent descent)))))


(defun text-base-point (text)
  "Return the left baseline endpoint for the TEXT."
  (multiple-value-bind (left top w h ascent) (text-geometry text)
    (declare (ignore w h))
    (values left (+ top ascent))))

(defgeneric text-base-position (text position)
  (:documentation "Return the left baseline endpoint for the TEXT substring
beginning at the given POSITION."))

(defmethod text-base-position ((text display-text-field) (position integer))
  (with-slots (font buffer) text
    (multiple-value-bind (start-x start-y) (text-base-point text)
      (unless (zerop position)
	(incf start-x (text-width font (buffer-line-chars buffer) :end position)))
      (values start-x start-y))))

(defmethod text-base-position ((text display-text-field) (position null))
  (with-slots (buffer) text
    (text-base-position text (length (buffer-line-chars buffer)))))



(defgeneric text-point-mark (text x y &optional mark)
  (:documentation "Return the text-mark corresponding to the given X/Y point."))


(defmethod text-point-mark ((text display-text-field) x y &optional mark)
  (declare (ignore mark))
  (with-slots (buffer) text
  
    ;; Compute extent.
    (multiple-value-bind (left top width height)
	(text-geometry text) 
 
      (cond
	(;; Return first position if above or left of extent
	 (or (< x left) (< y top))
	 0)
	
	(;; Return end position if below or righ of extent
	 (or (>= x (+ left width)) (>= y (+ top height)))
	 (buffer-length buffer))
    
	(t
	 (text-point-index text nil left x))))))


(defgeneric text-point-index (text line left x)
  (:documentation "Return the index of the character in the given LINE of the TEXT
which is at the given X position. LEFT gives the left edge position of the TEXT extent 
rectangle."))

(let ((char-string (make-string 1))
      (char-index  (make-array 1 :element-type 'card8)))
  

  (defmethod text-point-index ((text display-text-field) line left x)
    (declare (ignore line))
    
    (with-slots (font buffer) text
      (do* ((index-x left)
	    (index   0)
	    (chars  (buffer-line-chars buffer))
	    (max    (length chars)))
	   
	   ((= index max) index)
	
	(setf (elt char-string 0) (elt chars index))
	(translate-default char-string 0 1 font char-index 0)
	(let ((char-width (char-width font (elt char-index 0))))
	  (when (> (+ index-x (pixel-round char-width 2)) x)
	    (return index))
	  
	  (incf index-x char-width)
	  (incf index))))))

(defgeneric text-point-line (text top ascent descent y)
  (:documentation "Return the line of the given Y position for the TEXT, given
the TOP, ASCENT, DESCENT of the TEXT extent rectangle."))


(defmethod text-point-line ((text display-text-field) top ascent descent y)
  (declare (ignore top ascent descent y))
  0)


(defgeneric text-mark-point (text mark)
  (:documentation "Return the X/Y point corresponding to the given TEXT mark."))

(defmethod text-mark-point ((text display-text-field) mark)
  ;; Compute extent.
  (multiple-value-bind (left top w h ascent) 
      (text-geometry text)
    (declare (ignore w h))
    
    (with-slots (buffer font) text
      (values
	(+ left (buffer-text-extents buffer font 0 mark))
	(+ top ascent)))))


;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                               display-text                                 |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defcontact display-text (select-text display-text-field)
  ((buffer    :type     buffer
	      :initform (make-buffer))

   (alignment :type     (member :left :center :right)
	      :initform :left
	      :initarg  :alignment
	      :accessor display-text-alignment)

   (extent-top       
              :type     integer)
   (extent-left      
              :type     integer)
   (extent-width
              :type     (integer 0 *))
   (extent-height
              :type     (integer 0 *))

   (compress-exposures
              :initform :off))
  
  (:resources
    alignment
    (font :initform  *default-display-text-font*))

  (:documentation
    "Presents multiple lines of text for viewing."))



;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                              Initialization                                |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defun make-display-text (&rest initargs)
  (apply #'make-contact 'display-text initargs))


;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                 Accessors                                  |
;;;                                                                            |
;;;----------------------------------------------------------------------------+


(defun text-extent-defined-p (text)
  (slot-boundp text 'extent-top))

(defsetf text-extent-defined-p (text) (boolean)
  (declare (ignore boolean))
  `(slot-makunbound ,text 'extent-top))

(defmethod (setf display-text-source) :after (new-value (text display-text)
							&key (start 0) end (from-start 0) from-end)
  (declare (ignore new-value start end from-start from-end))
  (setf (text-extent-defined-p text) nil))

(defmethod (setf display-gravity) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil))

(defmethod (setf display-text-font) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil))

(defmethod (setf display-text-alignment) :before (new-value (text display-text))
  (check-type new-value (member :left :center :right)
	      "one of :LEFT, :CENTER, or :RIGHT"))

(defmethod (setf display-text-alignment) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil)
  (when (realized-p text)
    ;; Delay redisplay until :exposure handling to allow other class methods
    ;; a chance to prepare for redisplay.
    (clear-area text :exposures-p t)))

(defmethod (setf display-bottom-margin) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil))

(defmethod (setf display-left-margin) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil))

(defmethod (setf display-right-margin) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil))

(defmethod (setf display-top-margin) :after (new-value (text display-text))
  (declare (ignore new-value))
  (setf (text-extent-defined-p text) nil))

;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                  Display                                   |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defmethod display ((text display-text) &optional exposed-x exposed-y exposed-width exposed-height &key)
  (with-slots (width height) text
    (text-refresh
      text 0 nil nil
      (or exposed-x 0) (or exposed-y 0)
      exposed-width exposed-height))
    
  ;; Display caret or current selection
  (setf (text-selection-displayed-p text exposed-x exposed-y exposed-width exposed-height) t)
  (setf (text-caret-displayed-p text exposed-x exposed-y exposed-width exposed-height) t))


(let ((char-string (make-string 1))
      (char-index  (make-array 1 :element-type 'card8)))
  
  (defun text-clipped-line (text line start end clip-left clip-right)
    "Clip the substring of LINE in TEXT given by START/END to the horizontal region
between CLIP-LEFT and CLIP-RIGHT. Returns the start/end indexes and the left x position
of the clipped substring."
    (declare (type display-text text))
    
    (flet
      ((actual-width (font char)
	(cond
	  ((graphic-char-p char)
	   (setf (elt char-string 0) char)
	   (translate-default char-string 0 1 font char-index 0)
	   (char-width font (elt char-index 0)))
	  (t 0))))
				   
    (with-slots (font buffer) (the display-text text)
      (let*
	((index-x (text-base-x text line))
	 (index   0)
	 
	 (chars   (buffer-line-chars (elt (buffer-lines buffer) line)))
	 (max     (length chars))
	 (end     (if end (min max end) max))

	 (start   (do (char-right)
		      ((= index end) index)
		    
		    ;; Find right edge of next char 
		    (setf char-right (+ index-x (actual-width font (elt chars index))))
		    
		    ;; Is this the first char in start/end subseq that intersects
		    ;; the clip region?
		    (when (and (>= index start) (> char-right clip-left))
		      (return index))
		    
		    ;; Setf index-x to left edge of next char
		    (incf index)
		    (setf index-x char-right)))
	 
	 (start-x index-x))

	(values
	  start
	  
	  ;; Find end of clipped substring.
	  (do ()	      
	      ;; Is this the last char in start/end subseq past that intersects
	      ;; the clip region?
	      ((or (>= index-x clip-right) (= index end)) index)
	    
	    ;; Find left edge of next char.
	    (incf index-x (actual-width font (elt chars index)))
	    (incf index))

	  start-x))))))

(defgeneric text-refresh (text start end &optional clear-p exposed-x exposed-y exposed-width exposed-height)
  (:documentation "Draw TEXT characters from START to END. By default CLEAR-P is true, in which case the displayed 
area is cleared first. If EXPOSED-X, EXPOSED-Y, EXPOSED-WIDTH, and EXPOSED-HEIGHT are given, then 
characters are refreshed only if they lie in the exposed area."))


(defmethod text-refresh ((text display-text) (start mark) (end mark)
			   &optional (clear-p t) (exposed-x 0) (exposed-y 0) exposed-width exposed-height) 
  ;; Update extent cache
  (text-geometry text)
  
  (with-slots (buffer font extent-left extent-top extent-width extent-height width height) text
    
    ;; Redisplay only text inside the exposed region.
    (multiple-value-bind (exposed-x exposed-y exposed-width exposed-height)
	(area-overlaps-p
	  exposed-x exposed-y (or exposed-width (- width exposed-x)) (or exposed-height (- height exposed-y))
	  extent-left extent-top extent-width extent-height)
      
      (when exposed-x
	(let*
	  ((ascent         (font-ascent font))
	   (descent        (font-descent font))
	   (exposed-right  (+ exposed-x exposed-width)) 
	   
	   (sli            (mark-line-index start))
	   (next-line      (max sli
				(text-point-line
				  text extent-top ascent descent
				  exposed-y)))
	   
	   (eli            (mark-line-index end))
	   (end-line       (min eli
				(text-point-line
				  text extent-top ascent descent
				  (+ exposed-y exposed-height))))
	   
	   (nlines         (1+ (- end-line next-line)))
	   (lines          (buffer-lines buffer))
	   (line-height    (+ ascent descent))
	   (base-y         (+ extent-top ascent (* next-line line-height)))) 
	  
	  
	  (dotimes (i nlines)
	    (multiple-value-bind (start end start-x)
		(text-clipped-line text next-line
				   (if (unless clear-p (= next-line sli))
				       (mark-index start)
				       0)
				   (if (unless clear-p (= next-line eli))
				       (mark-index end)
				       nil)
				   exposed-x exposed-right)
	      
	      (text-display-chars
		text (buffer-line-chars (elt lines next-line))
		start-x base-y
		:start start
		:end end)
	      (incf next-line)
	      (incf base-y line-height))))))))


(let ((start-mark (make-mark))
      (end-mark (make-mark)))

  (defmethod text-refresh ((text display-text) start end
			   &optional (clear-p t) (exposed-x 0) (exposed-y 0) exposed-width exposed-height)
    (with-slots (buffer) text
      (text-refresh
	text
	(if (or (null start) (integerp start))
	    (buffer-position-mark buffer start start-mark)
	    start)
	(if (or (null end) (integerp end))
	    (buffer-position-mark buffer end end-mark)
	    end)
	clear-p exposed-x exposed-y exposed-width exposed-height))))



(defmethod text-change-highlight ((text display-text) (from mark) (to mark)
				  &optional exposed-x exposed-y exposed-width exposed-height)
  (when (realized-p text)    
  (with-slots (font buffer foreground  clip-rectangle) text
    
    (multiple-value-bind (from to equal-p) (mark-range buffer from to)
      (unless equal-p
	(let*
	  ((lines       (buffer-lines buffer))
	   (ascent      (font-ascent font))
	   (descent     (font-descent font))
	   (line-height (+ ascent descent))
	   (fli         (mark-line-index from))
	   (tli         (mark-line-index to)))

	  (flet
	    ((draw-highlight
	      (gc)
	      ;; Draw highlight for all chars between from and to marks.
	      (do ((line fli (1+ line))
		   (y (- (text-base-y text fli ascent descent) ascent) (+ y line-height)))
		  ((> line tli))
		
		(let ((start-index (if (= line fli) (mark-index from) 0)))
		  (draw-rectangle
		    text gc
		    (text-base-x text line start-index) y
		    (text-width
		      font (buffer-line-chars (elt lines line))
		      :start start-index
		      :end (when (= line tli) (mark-index to)))
		    line-height
		    t)))))
	    
	    (using-gcontext
	      (gc :drawable   text
		  :function   boole-xor
		  :clip-mask  clip-rectangle
		  :foreground (logxor
				foreground
				(contact-current-background-pixel text)))
	      
	      (if exposed-x
		  
		  ;; Clip highlight to intersection of clip rectangle and exposed region.
		  (let
		    ((old-clip-x      (display-clip-x text))
		     (old-clip-y      (display-clip-y text))
		     (old-clip-width  (display-clip-width text))
		     (old-clip-height (display-clip-height text)))

		    (multiple-value-bind (new-clip-x new-clip-y new-clip-width new-clip-height)
			(area-overlaps-p
			  old-clip-x old-clip-y old-clip-width old-clip-height
			  exposed-x exposed-y exposed-width exposed-height)

		      (when new-clip-x
			(setf
			  (display-clip-x text)      new-clip-x
			  (display-clip-y text)      new-clip-y
			  (display-clip-width text)  new-clip-width
			  (display-clip-height text) new-clip-height)
		    
			;; Draw highlight when intersection exists.
			(with-gcontext (gc :clip-mask clip-rectangle)
			  (draw-highlight gc))
		    
			;; Restore clip rectangle
			(setf (display-clip-x text)      old-clip-x
			      (display-clip-y text)      old-clip-y
			      (display-clip-width text)  old-clip-width
			      (display-clip-height text) old-clip-height))))
		  
		  ;; Else draw highlight without additional clipping
		  (draw-highlight gc))))))))))
	  
	  
;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                 Geometry                                   |
;;;                                                                            |
;;;----------------------------------------------------------------------------+

(defmethod resize :after ((text display-text) width height border-width)
  (declare (ignore width height border-width))
  (setf (text-extent-defined-p text) nil))

(defmethod display-text-extent ((text display-text))
  (with-slots (buffer font) text
    (let ((ascent  (font-ascent font))
	  (descent (font-descent font))
	  (lines   (buffer-lines buffer)))
      (values
	(reduce #'(lambda (max-width line)
		    (max max-width (text-width font (buffer-line-chars line))))
		lines :initial-value 0)
	(* (+ ascent descent) (length lines))
	ascent
	descent))))

(defmethod text-geometry ((text display-text))
  (with-slots (font extent-top extent-left extent-width extent-height) text
    (multiple-value-bind (ascent descent)
	(if (text-extent-defined-p text)
	    (values (font-ascent font) (font-descent font))

	    ;; Update extent slots with current geometry.
	    (multiple-value-bind (left top w h a d) (compute-text-geometry text)
	      (setf extent-left   left
		    extent-top    top
		    extent-width  w
		    extent-height h)
	      (values a d)))

      (values extent-left extent-top extent-width extent-height ascent descent))))

(defmethod text-point-mark ((text display-text) x y &optional mark)
  (with-slots (font buffer extent-top extent-left extent-width extent-height) text  
    (let
      ((mark (or mark (make-mark)))
       (line (text-point-line
	       text extent-top
	       (font-ascent font) (font-descent font)
	       (max extent-top (min (1- (+ extent-top extent-height)) y)))))
      (setf (mark-buffer mark) buffer)
      (move-mark mark line (text-point-index text line (text-base-x text line) x)))))

(defun text-base-x (text line &optional (start 0))
  "Return the left edge of the START position of the LINE in the TEXT."
  (declare (type display-text text)
	   (type integer     line))

  ;; Ensure extent is defined.
  (text-geometry text)
  
  (with-slots (font buffer alignment extent-left extent-width) (the display-text text)
    (let ((chars (buffer-line-chars (elt (buffer-lines buffer) line))))
      (+ (ecase alignment
	   (:left   extent-left)
	   (:center (+ extent-left (floor (- extent-width (text-width font chars)) 2)))
	   (:right  (+ extent-left (- extent-width (text-width font chars)))))
	 
	 (if (plusp start)
	     (text-width font chars :end start)
	     0)))))

(defun text-base-y (text line &optional ascent descent)
  "Return the baseline position of the LINE in the TEXT."
  (declare (type display-text text)
	   (type integer     line))

  ;; Ensure extent is defined.
  (text-geometry text) 
  
  (with-slots (font extent-top) (the display-text text)
    (+ extent-top
       (* line (+ (or ascent (setf ascent (font-ascent font)))
		  (or descent (font-descent font))))
       ascent)))

(defmethod text-base-position ((text display-text) (position mark))
  (let ((line (mark-line-index position)))
    (values
      (text-base-x text line (mark-index position))
      (text-base-y text line))))

(let ((mark (make-mark)))
  (defmethod text-base-position ((text display-text) position)
    (with-slots (buffer) text
      (setf (mark-buffer mark) buffer)
      (text-base-position text (buffer-position-mark buffer position mark)))))



(let ((char-string (make-string 1))
      (char-index  (make-array 1 :element-type 'card8)))
  
  (defmethod text-point-index ((text display-text) line left x)
    (with-slots (font buffer) text
      (do* ((index-x left)
	    (index   0 (1+ index))
	    (chars  (buffer-line-chars (elt (buffer-lines buffer) line)))
	    (max    (let* ((max (length chars)) (last (1- max)))
		      ;; Can't point or insert after #\newline!
		      (if (and (plusp max) (eql #\newline (elt chars last))) last max))))
	   
	   ((= index max) index)
	
	(let ((char (elt chars index)))
	  (when (graphic-char-p char)
	    (setf (elt char-string 0) char)
	    (translate-default char-string 0 1 font char-index 0)
	    (let ((char-width (char-width font (elt char-index 0))))
	      (when (> (+ index-x (pixel-round char-width 2)) x)
		(return index))	  
	      (incf index-x char-width))))))))
	   
	   
	   
(defmethod text-point-line ((text display-text) top ascent descent y)
  (floor (- y top) (+ ascent descent)))

(defmethod text-mark-point ((text display-text) (mark mark))
  (with-slots (font buffer extent-top) text
    (let ((ascent (font-ascent font))
	  (line   (mark-line-index mark)))
      (values
	(text-base-x text line (mark-index mark))
	(+ extent-top (* line (+ ascent (font-descent font))) ascent)))))







;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                                 Selection                                  |
;;;                                                                            |
;;;----------------------------------------------------------------------------+


(defmethod (setf edit-text-point) :before (new-value (text display-text) &key clear-p)
  (declare (ignore new-value clear-p))
  (with-slots (point buffer) text
    ;; Allocate point if necessary.
    (unless (mark-p point) (setf point (make-mark :buffer buffer)))))


(defmethod edit-text-point :around ((text display-text))
  (with-slots (buffer) text
    (buffer-mark-position buffer (call-next-method))))

(let ((mark (make-mark)))
  (defmethod (setf edit-text-point) :around ((new-value integer) (text display-text) &key clear-p)
    (with-slots (buffer) text
      (call-next-method
	(buffer-position-mark buffer new-value mark)
	text :clear-p clear-p))
    new-value))


(defmethod (setf edit-text-mark) :before (new-value (text display-text))
  (declare (ignore new-value))
  (with-slots (mark buffer) text
    ;; Allocate mark if necessary.
    (unless (mark-p mark) (setf mark (make-mark :buffer buffer)))))

(defmethod edit-text-mark :around ((text display-text))
  (with-slots (buffer) text
    (buffer-mark-position buffer (call-next-method))))

(let ((mark (make-mark)))
  (defmethod (setf edit-text-mark) :around ((new-value integer) (text display-text))
    (with-slots (buffer) text
      (call-next-method
	(buffer-position-mark buffer new-value mark)
	text))
    new-value))



;;;----------------------------------------------------------------------------+
;;;                                                                            |
;;;                            Clipboard Handling                              |
;;;                                                                            |
;;;----------------------------------------------------------------------------+


;;; When text is copied or cut to the Clipboard, then the client becomes the owner 
;;; of the :CLIPBOARD selection.  During this time, the current :CLIPBOARD value is
;;; a string stored on the display plist.  (The current :CLIPBOARD value is unique to
;;; server; in particular, individual text contacts do not need to store this value
;;; independently.) To minimize garbage, the display-clipboard-text is an adjustable
;;; string vector which is reused.

(defmacro display-clipboard-text (display)
  `(getf (display-plist ,display) 'clipboard-text))

(defsetf display-clipboard-text setf-display-clipboard-text)
(defun setf-display-clipboard-text (display string)
  (let
    ;; Create string vector, if necessary.
    ((clipboard (or (display-clipboard-text display)
		    (make-array *minimum-buffer-line-length*
				:adjustable   t
				:fill-pointer 0
				:element-type 'buffer-character)))
     dont-care)

    ;; Delete previous contents.
    (vector-delete clipboard)

    ;; Store new contents and adjust vector, if necessary.
    (when string
      (multiple-value-setq (dont-care clipboard)
	(vector-insert clipboard 0 string 0 (length string)))
      (setf (getf (display-plist display) 'clipboard-text) clipboard)))
  string)


(defun clipboard-copy (text)
  (declare (type display-text-field text))
  
  (with-slots (buffer display) text
    (let ((time (when (processing-event-p) (with-event (time) time)))) 

      (multiple-value-bind (start end) (text-selection-range text)
	(if (and start (text-own-selection text :clipboard time))

	    (setf (display-clipboard-text display) (buffer-subseq buffer start end))
	  
	    (when start
	      (warn "~a ~a.~%~a"
		    "Cannot acquire :CLIPBOARD selection for"
		    text
		    "Text not copied to Clipboard.")))))))

(defmethod text-selection-string ((text select-text) (selection (eql :clipboard))) 
  (with-slots (display) text
    (display-clipboard-text display)))