summaryrefslogtreecommitdiffstats
path: root/library/entry.tcl
blob: 6243d26199ef1ee18cbc2a83a33d923ecf2fd5d4 (plain)
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
# entry.tcl --
#
# This file defines the default bindings for Tk entry widgets and provides
# procedures that help in implementing those bindings.
#
# Copyright (c) 1992-1994 The Regents of the University of California.
# Copyright (c) 1994-1997 Sun Microsystems, Inc.
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#

#-------------------------------------------------------------------------
# Elements of tk::Priv that are used in this file:
#
# afterId -		If non-null, it means that auto-scanning is underway
#			and it gives the "after" id for the next auto-scan
#			command to be executed.
# mouseMoved -		Non-zero means the mouse has moved a significant
#			amount since the button went down (so, for example,
#			start dragging out a selection).
# pressX -		X-coordinate at which the mouse button was pressed.
# selectMode -		The style of selection currently underway:
#			char, word, or line.
# x, y -		Last known mouse coordinates for scanning
#			and auto-scanning.
# data -		Used for Cut and Copy
#-------------------------------------------------------------------------

#-------------------------------------------------------------------------
# The code below creates the default class bindings for entries.
#-------------------------------------------------------------------------
bind Entry <<Cut>> {
    if {![catch {tk::EntryGetSelection %W} tk::Priv(data)]} {
	clipboard clear -displayof %W
	clipboard append -displayof %W $tk::Priv(data)
	%W delete sel.first sel.last
	unset tk::Priv(data)
    }
}
bind Entry <<Copy>> {
    if {![catch {tk::EntryGetSelection %W} tk::Priv(data)]} {
	clipboard clear -displayof %W
	clipboard append -displayof %W $tk::Priv(data)
	unset tk::Priv(data)
    }
}
bind Entry <<Paste>> {
    catch {
	if {[tk windowingsystem] ne "x11"} {
	    catch {
		%W delete sel.first sel.last
	    }
	}
	%W insert insert [::tk::GetSelection %W CLIPBOARD]
	tk::EntrySeeInsert %W
    }
}
bind Entry <<Clear>> {
    # ignore if there is no selection
    catch { %W delete sel.first sel.last }
}
bind Entry <<PasteSelection>> {
    if {$tk_strictMotif || ![info exists tk::Priv(mouseMoved)]
	|| !$tk::Priv(mouseMoved)} {
	tk::EntryPaste %W %x
    }
}

bind Entry <<TraverseIn>> {
    %W selection range 0 end
    %W icursor end
}

# Standard Motif bindings:

bind Entry <1> {
    tk::EntryButton1 %W %x
    %W selection clear
}
bind Entry <B1-Motion> {
    set tk::Priv(x) %x
    tk::EntryMouseSelect %W %x
}
bind Entry <Double-1> {
    set tk::Priv(selectMode) word
    tk::EntryMouseSelect %W %x
    catch {%W icursor sel.last}
}
bind Entry <Triple-1> {
    set tk::Priv(selectMode) line
    tk::EntryMouseSelect %W %x
    catch {%W icursor sel.last}
}
bind Entry <Shift-1> {
    set tk::Priv(selectMode) char
    %W selection adjust @%x
}
bind Entry <Double-Shift-1>	{
    set tk::Priv(selectMode) word
    tk::EntryMouseSelect %W %x
}
bind Entry <Triple-Shift-1>	{
    set tk::Priv(selectMode) line
    tk::EntryMouseSelect %W %x
}
bind Entry <B1-Leave> {
    set tk::Priv(x) %x
    tk::EntryAutoScan %W
}
bind Entry <B1-Enter> {
    tk::CancelRepeat
}
bind Entry <ButtonRelease-1> {
    tk::CancelRepeat
}
bind Entry <Control-1> {
    %W icursor @%x
}

bind Entry <<PrevChar>> {
    tk::EntrySetCursor %W [expr {[%W index insert] - 1}]
}
bind Entry <<NextChar>> {
    tk::EntrySetCursor %W [expr {[%W index insert] + 1}]
}
bind Entry <<SelectPrevChar>> {
    tk::EntryKeySelect %W [expr {[%W index insert] - 1}]
    tk::EntrySeeInsert %W
}
bind Entry <<SelectNextChar>> {
    tk::EntryKeySelect %W [expr {[%W index insert] + 1}]
    tk::EntrySeeInsert %W
}
bind Entry <<PrevWord>> {
    tk::EntrySetCursor %W [tk::EntryPreviousWord %W insert]
}
bind Entry <<NextWord>> {
    tk::EntrySetCursor %W [tk::EntryNextWord %W insert]
}
bind Entry <<SelectPrevWord>> {
    tk::EntryKeySelect %W [tk::EntryPreviousWord %W insert]
    tk::EntrySeeInsert %W
}
bind Entry <<SelectNextWord>> {
    tk::EntryKeySelect %W [tk::EntryNextWord %W insert]
    tk::EntrySeeInsert %W
}
bind Entry <<LineStart>> {
    tk::EntrySetCursor %W 0
}
bind Entry <<SelectLineStart>> {
    tk::EntryKeySelect %W 0
    tk::EntrySeeInsert %W
}
bind Entry <<LineEnd>> {
    tk::EntrySetCursor %W end
}
bind Entry <<SelectLineEnd>> {
    tk::EntryKeySelect %W end
    tk::EntrySeeInsert %W
}

bind Entry <Delete> {
    if {[%W selection present]} {
	%W delete sel.first sel.last
    } else {
	%W delete insert
    }
}
bind Entry <BackSpace> {
    tk::EntryBackspace %W
}

bind Entry <Control-space> {
    %W selection from insert
}
bind Entry <Select> {
    %W selection from insert
}
bind Entry <Control-Shift-space> {
    %W selection adjust insert
}
bind Entry <Shift-Select> {
    %W selection adjust insert
}
bind Entry <<SelectAll>> {
    %W selection range 0 end
}
bind Entry <<SelectNone>> {
    %W selection clear
}
bind Entry <KeyPress> {
    tk::CancelRepeat
    tk::EntryInsert %W %A
}

# Ignore all Alt, Meta, and Control keypresses unless explicitly bound.
# Otherwise, if a widget binding for one of these is defined, the
# <KeyPress> class binding will also fire and insert the character,
# which is wrong.  Ditto for Escape, Return, and Tab.

bind Entry <Alt-KeyPress> {# nothing}
bind Entry <Meta-KeyPress> {# nothing}
bind Entry <Control-KeyPress> {# nothing}
bind Entry <Escape> {# nothing}
bind Entry <Return> {# nothing}
bind Entry <KP_Enter> {# nothing}
bind Entry <Tab> {# nothing}
bind Entry <Prior> {# nothing}
bind Entry <Next> {# nothing}
if {[tk windowingsystem] eq "aqua"} {
    bind Entry <Command-KeyPress> {# nothing}
}
# Tk-on-Cocoa generates characters for these two keys. [Bug 2971663]
bind Entry <<NextLine>> {# nothing}
bind Entry <<PrevLine>> {# nothing}

# On Windows, paste is done using Shift-Insert.  Shift-Insert already
# generates the <<Paste>> event, so we don't need to do anything here.
if {[tk windowingsystem] ne "win32"} {
    bind Entry <Insert> {
	catch {tk::EntryInsert %W [::tk::GetSelection %W PRIMARY]}
    }
}

# Additional emacs-like bindings:

bind Entry <Control-d> {
    if {!$tk_strictMotif} {
	%W delete insert
    }
}
bind Entry <Control-h> {
    if {!$tk_strictMotif} {
	tk::EntryBackspace %W
    }
}
bind Entry <Control-k> {
    if {!$tk_strictMotif} {
	%W delete insert end
    }
}
bind Entry <Control-t> {
    if {!$tk_strictMotif} {
	tk::EntryTranspose %W
    }
}
bind Entry <Meta-b> {
    if {!$tk_strictMotif} {
	tk::EntrySetCursor %W [tk::EntryPreviousWord %W insert]
    }
}
bind Entry <Meta-d> {
    if {!$tk_strictMotif} {
	%W delete insert [tk::EntryNextWord %W insert]
    }
}
bind Entry <Meta-f> {
    if {!$tk_strictMotif} {
	tk::EntrySetCursor %W [tk::EntryNextWord %W insert]
    }
}
bind Entry <Meta-BackSpace> {
    if {!$tk_strictMotif} {
	%W delete [tk::EntryPreviousWord %W insert] insert
    }
}
bind Entry <Meta-Delete> {
    if {!$tk_strictMotif} {
	%W delete [tk::EntryPreviousWord %W insert] insert
    }
}

# A few additional bindings of my own.

bind Entry <2> {
    if {!$tk_strictMotif} {
	::tk::EntryScanMark %W %x
    }
}
bind Entry <B2-Motion> {
    if {!$tk_strictMotif} {
	::tk::EntryScanDrag %W %x
    }
}

# ::tk::EntryClosestGap --
# Given x and y coordinates, this procedure finds the closest boundary
# between characters to the given coordinates and returns the index
# of the character just after the boundary.
#
# Arguments:
# w -		The entry window.
# x -		X-coordinate within the window.

proc ::tk::EntryClosestGap {w x} {
    set pos [$w index @$x]
    set bbox [$w bbox $pos]
    if {($x - [lindex $bbox 0]) < ([lindex $bbox 2]/2)} {
	return $pos
    }
    incr pos
}

# ::tk::EntryButton1 --
# This procedure is invoked to handle button-1 presses in entry
# widgets.  It moves the insertion cursor, sets the selection anchor,
# and claims the input focus.
#
# Arguments:
# w -		The entry window in which the button was pressed.
# x -		The x-coordinate of the button press.

proc ::tk::EntryButton1 {w x} {
    variable ::tk::Priv

    set Priv(selectMode) char
    set Priv(mouseMoved) 0
    set Priv(pressX) $x
    $w icursor [EntryClosestGap $w $x]
    $w selection from insert
    if {"disabled" ne [$w cget -state]} {
	focus $w
    }
}

# ::tk::EntryMouseSelect --
# This procedure is invoked when dragging out a selection with
# the mouse.  Depending on the selection mode (character, word,
# line) it selects in different-sized units.  This procedure
# ignores mouse motions initially until the mouse has moved from
# one character to another or until there have been multiple clicks.
#
# Arguments:
# w -		The entry window in which the button was pressed.
# x -		The x-coordinate of the mouse.

proc ::tk::EntryMouseSelect {w x} {
    variable ::tk::Priv

    set cur [EntryClosestGap $w $x]
    set anchor [$w index anchor]
    if {($cur != $anchor) || (abs($Priv(pressX) - $x) >= 3)} {
	set Priv(mouseMoved) 1
    }
    switch $Priv(selectMode) {
	char {
	    if {$Priv(mouseMoved)} {
		if {$cur < $anchor} {
		    $w selection range $cur $anchor
		} elseif {$cur > $anchor} {
		    $w selection range $anchor $cur
		} else {
		    $w selection clear
		}
	    }
	}
	word {
	    if {$cur < $anchor} {
		set before [tcl_wordBreakBefore [$w get] $cur]
		set after [tcl_wordBreakAfter [$w get] [expr {$anchor-1}]]
	    } elseif {$cur > $anchor} {
		set before [tcl_wordBreakBefore [$w get] $anchor]
		set after [tcl_wordBreakAfter [$w get] [expr {$cur - 1}]]
	    } else {
		if {[$w index @$Priv(pressX)] < $anchor} {
		      incr anchor -1
		}
		set before [tcl_wordBreakBefore [$w get] $anchor]
		set after [tcl_wordBreakAfter [$w get] $anchor]
	    }
	    if {$before < 0} {
		set before 0
	    }
	    if {$after < 0} {
		set after end
	    }
	    $w selection range $before $after
	}
	line {
	    $w selection range 0 end
	}
    }
    if {$Priv(mouseMoved)} {
        $w icursor $cur
    }
    update idletasks
}

# ::tk::EntryPaste --
# This procedure sets the insertion cursor to the current mouse position,
# pastes the selection there, and sets the focus to the window.
#
# Arguments:
# w -		The entry window.
# x -		X position of the mouse.

proc ::tk::EntryPaste {w x} {
    $w icursor [EntryClosestGap $w $x]
    catch {$w insert insert [::tk::GetSelection $w PRIMARY]}
    if {"disabled" ne [$w cget -state]} {
	focus $w
    }
}

# ::tk::EntryAutoScan --
# This procedure is invoked when the mouse leaves an entry window
# with button 1 down.  It scrolls the window left or right,
# depending on where the mouse is, and reschedules itself as an
# "after" command so that the window continues to scroll until the
# mouse moves back into the window or the mouse button is released.
#
# Arguments:
# w -		The entry window.

proc ::tk::EntryAutoScan {w} {
    variable ::tk::Priv
    set x $Priv(x)
    if {![winfo exists $w]} {
	return
    }
    if {$x >= [winfo width $w]} {
	$w xview scroll 2 units
	EntryMouseSelect $w $x
    } elseif {$x < 0} {
	$w xview scroll -2 units
	EntryMouseSelect $w $x
    }
    set Priv(afterId) [after 50 [list tk::EntryAutoScan $w]]
}

# ::tk::EntryKeySelect --
# This procedure is invoked when stroking out selections using the
# keyboard.  It moves the cursor to a new position, then extends
# the selection to that position.
#
# Arguments:
# w -		The entry window.
# new -		A new position for the insertion cursor (the cursor hasn't
#		actually been moved to this position yet).

proc ::tk::EntryKeySelect {w new} {
    if {![$w selection present]} {
	$w selection from insert
	$w selection to $new
    } else {
	$w selection adjust $new
    }
    $w icursor $new
}

# ::tk::EntryInsert --
# Insert a string into an entry at the point of the insertion cursor.
# If there is a selection in the entry, and it covers the point of the
# insertion cursor, then delete the selection before inserting.
#
# Arguments:
# w -		The entry window in which to insert the string
# s -		The string to insert (usually just a single character)

proc ::tk::EntryInsert {w s} {
    if {$s eq ""} {
	return
    }
    catch {
	set insert [$w index insert]
	if {([$w index sel.first] <= $insert)
		&& ([$w index sel.last] >= $insert)} {
	    $w delete sel.first sel.last
	}
    }
    $w insert insert $s
    EntrySeeInsert $w
}

# ::tk::EntryBackspace --
# Backspace over the character just before the insertion cursor.
# If backspacing would move the cursor off the left edge of the
# window, reposition the cursor at about the middle of the window.
#
# Arguments:
# w -		The entry window in which to backspace.

proc ::tk::EntryBackspace w {
    if {[$w selection present]} {
	$w delete sel.first sel.last
    } else {
	set x [expr {[$w index insert] - 1}]
	if {$x >= 0} {
	    $w delete $x
	}
	if {[$w index @0] >= [$w index insert]} {
	    set range [$w xview]
	    set left [lindex $range 0]
	    set right [lindex $range 1]
	    $w xview moveto [expr {$left - ($right - $left)/2.0}]
	}
    }
}

# ::tk::EntrySeeInsert --
# Make sure that the insertion cursor is visible in the entry window.
# If not, adjust the view so that it is.
#
# Arguments:
# w -		The entry window.

proc ::tk::EntrySeeInsert w {
    set c [$w index insert]
    if {($c < [$w index @0]) || ($c > [$w index @[winfo width $w]])} {
	$w xview $c
    }
}

# ::tk::EntrySetCursor -
# Move the insertion cursor to a given position in an entry.  Also
# clears the selection, if there is one in the entry, and makes sure
# that the insertion cursor is visible.
#
# Arguments:
# w -		The entry window.
# pos -		The desired new position for the cursor in the window.

proc ::tk::EntrySetCursor {w pos} {
    $w icursor $pos
    $w selection clear
    EntrySeeInsert $w
}

# ::tk::EntryTranspose -
# This procedure implements the "transpose" function for entry widgets.
# It tranposes the characters on either side of the insertion cursor,
# unless the cursor is at the end of the line.  In this case it
# transposes the two characters to the left of the cursor.  In either
# case, the cursor ends up to the right of the transposed characters.
#
# Arguments:
# w -		The entry window.

proc ::tk::EntryTranspose w {
    set i [$w index insert]
    if {$i < [$w index end]} {
	incr i
    }
    set first [expr {$i-2}]
    if {$first < 0} {
	return
    }
    set data [$w get]
    set new [string index $data [expr {$i-1}]][string index $data $first]
    $w delete $first $i
    $w insert insert $new
    EntrySeeInsert $w
}

# ::tk::EntryNextWord --
# Returns the index of the next word position after a given position in the
# entry.  The next word is platform dependent and may be either the next
# end-of-word position or the next start-of-word position after the next
# end-of-word position.
#
# Arguments:
# w -		The entry window in which the cursor is to move.
# start -	Position at which to start search.

if {[tk windowingsystem] eq "win32"}  {
    proc ::tk::EntryNextWord {w start} {
	set pos [tcl_endOfWord [$w get] [$w index $start]]
	if {$pos >= 0} {
	    set pos [tcl_startOfNextWord [$w get] $pos]
	}
	if {$pos < 0} {
	    return end
	}
	return $pos
    }
} else {
    proc ::tk::EntryNextWord {w start} {
	set pos [tcl_endOfWord [$w get] [$w index $start]]
	if {$pos < 0} {
	    return end
	}
	return $pos
    }
}

# ::tk::EntryPreviousWord --
#
# Returns the index of the previous word position before a given
# position in the entry.
#
# Arguments:
# w -		The entry window in which the cursor is to move.
# start -	Position at which to start search.

proc ::tk::EntryPreviousWord {w start} {
    set pos [tcl_startOfPreviousWord [$w get] [$w index $start]]
    if {$pos < 0} {
	return 0
    }
    return $pos
}

# ::tk::EntryScanMark --
#
# Marks the start of a possible scan drag operation
#
# Arguments:
# w -	The entry window from which the text to get
# x -	x location on screen

proc ::tk::EntryScanMark {w x} {
    $w scan mark $x
    set ::tk::Priv(x) $x
    set ::tk::Priv(y) 0 ; # not used
    set ::tk::Priv(mouseMoved) 0
}

# ::tk::EntryScanDrag --
#
# Marks the start of a possible scan drag operation
#
# Arguments:
# w -	The entry window from which the text to get
# x -	x location on screen

proc ::tk::EntryScanDrag {w x} {
    # Make sure these exist, as some weird situations can trigger the
    # motion binding without the initial press.  [Bug #220269]
    if {![info exists ::tk::Priv(x)]} { set ::tk::Priv(x) $x }
    # allow for a delta
    if {abs($x-$::tk::Priv(x)) > 2} {
	set ::tk::Priv(mouseMoved) 1
    }
    $w scan dragto $x
}

# ::tk::EntryGetSelection --
#
# Returns the selected text of the entry with respect to the -show option.
#
# Arguments:
# w -         The entry window from which the text to get

proc ::tk::EntryGetSelection {w} {
    set entryString [string range [$w get] [$w index sel.first] \
	    [expr {[$w index sel.last] - 1}]]
    if {[$w cget -show] ne ""} {
	return [string repeat [string index [$w cget -show] 0] \
		[string length $entryString]]
    }
    return $entryString
}
> * all entries are 0. */ char *fontMap[FONTMAP_PAGES]; /* Two-level sparse table used to determine * quickly if the specified character exists. * As characters are encountered, more pages * in this table are dynamically added. The * contents of each page is a bitmask * consisting of FONTMAP_BITSPERPAGE bits, * representing whether this font can be used * to display the given character at the * corresponding bit position. The high bits * of the character are used to pick which * page of the table is used. */ } FontFamily; /* * The following structure encapsulates an individual screen font. A font * object is made up of however many SubFonts are necessary to display a * stream of multilingual characters. */ typedef struct SubFont { char **fontMap; /* Pointer to font map from the FontFamily, * cached here to save a dereference. */ FontFamily *familyPtr; /* The FontFamily for this SubFont. */ } SubFont; /* * The following structure represents Macintosh's implementation of a font * object. */ #define SUBFONT_SPACE 3 typedef struct MacFont { TkFont font; /* Stuff used by generic font package. Must * be first in structure. */ SubFont staticSubFonts[SUBFONT_SPACE]; /* Builtin space for a limited number of * SubFonts. */ int numSubFonts; /* Length of following array. */ SubFont *subFontArray; /* Array of SubFonts that have been loaded * in order to draw/measure all the characters * encountered by this font so far. All fonts * start off with one SubFont initialized by * AllocFont() from the original set of font * attributes. Usually points to * staticSubFonts, but may point to malloced * space if there are lots of SubFonts. */ short size; /* Font size in pixels, constructed from * font attributes. */ short style; /* Style bits, constructed from font * attributes. */ } MacFont; /* * The following structure is used to map between the UTF-8 name for a font and * the name that the Macintosh uses to refer to the font, in order to determine * if a font exists. The Macintosh names for fonts are stored in the encoding * of the font itself. */ typedef struct FontNameMap { Tk_Uid utfName; /* The name of the font in UTF-8. */ StringPtr nativeName; /* The name of the font in the font's encoding. */ short faceNum; /* Unique face number for this font. */ } FontNameMap; /* * The list of font families that are currently loaded. As screen fonts * are loaded, this list grows to hold information about what characters * exist in each font family. */ static FontFamily *fontFamilyList = NULL; /* * Information cached about the system at startup time. */ static FontNameMap *gFontNameMap = NULL; static GWorldPtr gWorld = NULL; /* * Procedures used only in this file. */ static FontFamily * AllocFontFamily(CONST MacFont *fontPtr, int family); static SubFont * CanUseFallback(MacFont *fontPtr, CONST char *fallbackName, int ch); static SubFont * CanUseFallbackWithAliases(MacFont *fontPtr, char *faceName, int ch, Tcl_DString *nameTriedPtr); static SubFont * FindSubFontForChar(MacFont *fontPtr, int ch); static void FontMapInsert(SubFont *subFontPtr, int ch); static void FontMapLoadPage(SubFont *subFontPtr, int row); static int FontMapLookup(SubFont *subFontPtr, int ch); static void FreeFontFamily(FontFamily *familyPtr); static void InitFont(Tk_Window tkwin, int family, int size, int style, MacFont *fontPtr); static void InitSubFont(CONST MacFont *fontPtr, int family, SubFont *subFontPtr); static void MultiFontDrawText(MacFont *fontPtr, CONST char *source, int numBytes, int x, int y); static void ReleaseFont(MacFont *fontPtr); static void ReleaseSubFont(SubFont *subFontPtr); static int SeenName(CONST char *name, Tcl_DString *dsPtr); static char * BreakLine(FontFamily *familyPtr, int flags, CONST char *source, int numBytes, int *widthPtr); static int GetFamilyNum(CONST char *faceName, short *familyPtr); static int GetFamilyOrAliasNum(CONST char *faceName, short *familyPtr); static Tcl_Encoding GetFontEncoding(int faceNum, int allowSymbol, int *isSymbolPtr); static Tk_Uid GetUtfFaceName(StringPtr faceNameStr); /* *------------------------------------------------------------------------- * * TkpFontPkgInit -- * * This procedure is called when an application is created. It * initializes all the structures that are used by the * platform-dependant code on a per application basis. * * Results: * None. * * Side effects: * See comments below. * *------------------------------------------------------------------------- */ void TkpFontPkgInit(mainPtr) TkMainInfo *mainPtr; /* The application being created. */ { MenuHandle fontMenu; FontNameMap *tmpFontNameMap, *newFontNameMap, *mapPtr; int i, j, numFonts, fontMapOffset, isSymbol; Str255 nativeName; Tcl_DString ds; Tcl_Encoding encoding; Tcl_Encoding *encodings; if (gWorld == NULL) { /* * Do the following one time only. */ Rect rect = {0, 0, 1, 1}; SetFractEnable(0); /* * Used for saving and restoring state while drawing and measuring. */ if (NewGWorld(&gWorld, 0, &rect, NULL, NULL, 0) != noErr) { panic("TkpFontPkgInit: NewGWorld failed"); } /* * The name of each font is stored in the encoding of that font. * How would we translate a name from UTF-8 into the native encoding * of the font unless we knew the encoding of that font? We can't. * So, precompute the UTF-8 and native names of all fonts on the * system. The when the user asks for font by its UTF-8 name, we * lookup the name in that table and really ask for the font by its * native name. Any unknown UTF-8 names will be mapped to the system * font. */ fontMenu = NewMenu('FT', "\px"); AppendResMenu(fontMenu, 'FONT'); numFonts = CountMItems(fontMenu); tmpFontNameMap = (FontNameMap *) ckalloc(sizeof(FontNameMap) * numFonts); encodings = (Tcl_Encoding *) ckalloc(sizeof(Tcl_Encoding) * numFonts); mapPtr = tmpFontNameMap; for (i = 0; i < numFonts; i++) { GetMenuItemText(fontMenu, i + 1, nativeName); GetFNum(nativeName, &mapPtr->faceNum); encodings[i] = GetFontEncoding(mapPtr->faceNum, 0, &isSymbol); Tcl_ExternalToUtfDString(encodings[i], StrBody(nativeName), StrLength(nativeName), &ds); mapPtr->utfName = Tk_GetUid(Tcl_DStringValue(&ds)); mapPtr->nativeName = (StringPtr) ckalloc(StrLength(nativeName) + 1); memcpy(mapPtr->nativeName, nativeName, StrLength(nativeName) + 1); Tcl_DStringFree(&ds); mapPtr++; } DisposeMenu(fontMenu); /* * Reorder FontNameMap so fonts with the preferred encodings are at * the front of the list. The relative order of fonts that all have * the same encoding is preserved. Fonts with unknown encodings get * stuck at the end. */ newFontNameMap = (FontNameMap *) ckalloc(sizeof(FontNameMap) * (numFonts + 1)); fontMapOffset = 0; for (i = 0; encodingList[i] != NULL; i++) { encoding = Tcl_GetEncoding(NULL, encodingList[i]); if (encoding == NULL) { continue; } for (j = 0; j < numFonts; j++) { if (encodings[j] == encoding) { newFontNameMap[fontMapOffset] = tmpFontNameMap[j]; fontMapOffset++; Tcl_FreeEncoding(encodings[j]); tmpFontNameMap[j].utfName = NULL; } } Tcl_FreeEncoding(encoding); } for (i = 0; i < numFonts; i++) { if (tmpFontNameMap[i].utfName != NULL) { newFontNameMap[fontMapOffset] = tmpFontNameMap[i]; fontMapOffset++; Tcl_FreeEncoding(encodings[i]); } } if (fontMapOffset != numFonts) { panic("TkpFontPkgInit: unexpected number of fonts"); } mapPtr = &newFontNameMap[numFonts]; mapPtr->utfName = NULL; mapPtr->nativeName = NULL; mapPtr->faceNum = 0; ckfree((char *) tmpFontNameMap); ckfree((char *) encodings); gFontNameMap = newFontNameMap; } } /* *--------------------------------------------------------------------------- * * TkpGetNativeFont -- * * Map a platform-specific native font name to a TkFont. * * Results: * The return value is a pointer to a TkFont that represents the * native font. If a native font by the given name could not be * found, the return value is NULL. * * Every call to this procedure returns a new TkFont structure, * even if the name has already been seen before. The caller should * call TkpDeleteFont() when the font is no longer needed. * * The caller is responsible for initializing the memory associated * with the generic TkFont when this function returns and releasing * the contents of the generics TkFont before calling TkpDeleteFont(). * * Side effects: * None. * *--------------------------------------------------------------------------- */ TkFont * TkpGetNativeFont( Tk_Window tkwin, /* For display where font will be used. */ CONST char *name) /* Platform-specific font name. */ { short family; MacFont *fontPtr; if (strcmp(name, "system") == 0) { family = GetSysFont(); } else if (strcmp(name, "application") == 0) { family = GetAppFont(); } else { return NULL; } fontPtr = (MacFont *) ckalloc(sizeof(MacFont)); InitFont(tkwin, family, 0, 0, fontPtr); return (TkFont *) fontPtr; } /* *--------------------------------------------------------------------------- * * TkpGetFontFromAttributes -- * * Given a desired set of attributes for a font, find a font with * the closest matching attributes. * * Results: * The return value is a pointer to a TkFont that represents the * font with the desired attributes. If a font with the desired * attributes could not be constructed, some other font will be * substituted automatically. * * Every call to this procedure returns a new TkFont structure, * even if the specified attributes have already been seen before. * The caller should call TkpDeleteFont() to free the platform- * specific data when the font is no longer needed. * * The caller is responsible for initializing the memory associated * with the generic TkFont when this function returns and releasing * the contents of the generic TkFont before calling TkpDeleteFont(). * * Side effects: * None. * *--------------------------------------------------------------------------- */ TkFont * TkpGetFontFromAttributes( TkFont *tkFontPtr, /* If non-NULL, store the information in * this existing TkFont structure, rather than * allocating a new structure to hold the * font; the existing contents of the font * will be released. If NULL, a new TkFont * structure is allocated. */ Tk_Window tkwin, /* For display where font will be used. */ CONST TkFontAttributes *faPtr) /* Set of attributes to match. */ { short faceNum, style; int i, j; char *faceName, *fallback; char ***fallbacks; MacFont *fontPtr; /* * Algorithm to get the closest font to the one requested. * * try fontname * try all aliases for fontname * foreach fallback for fontname * try the fallback * try all aliases for the fallback */ faceNum = 0; faceName = faPtr->family; if (faceName != NULL) { if (GetFamilyOrAliasNum(faceName, &faceNum) != 0) { goto found; } fallbacks = TkFontGetFallbacks(); for (i = 0; fallbacks[i] != NULL; i++) { for (j = 0; (fallback = fallbacks[i][j]) != NULL; j++) { if (strcasecmp(faceName, fallback) == 0) { for (j = 0; (fallback = fallbacks[i][j]) != NULL; j++) { if (GetFamilyOrAliasNum(fallback, &faceNum)) { goto found; } } } break; } } } found: style = 0; if (faPtr->weight != TK_FW_NORMAL) { style |= bold; } if (faPtr->slant != TK_FS_ROMAN) { style |= italic; } if (faPtr->underline) { style |= underline; } if (tkFontPtr == NULL) { fontPtr = (MacFont *) ckalloc(sizeof(MacFont)); } else { fontPtr = (MacFont *) tkFontPtr; ReleaseFont(fontPtr); } InitFont(tkwin, faceNum, faPtr->size, style, fontPtr); return (TkFont *) fontPtr; } /* *--------------------------------------------------------------------------- * * TkpDeleteFont -- * * Called to release a font allocated by TkpGetNativeFont() or * TkpGetFontFromAttributes(). The caller should have already * released the fields of the TkFont that are used exclusively by * the generic TkFont code. * * Results: * None. * * Side effects: * TkFont is deallocated. * *--------------------------------------------------------------------------- */ void TkpDeleteFont( TkFont *tkFontPtr) /* Token of font to be deleted. */ { MacFont *fontPtr; fontPtr = (MacFont *) tkFontPtr; ReleaseFont(fontPtr); } /* *--------------------------------------------------------------------------- * * TkpGetFontFamilies -- * * Return information about the font families that are available * on the display of the given window. * * Results: * Modifies interp's result object to hold a list of all the available * font families. * * Side effects: * None. * *--------------------------------------------------------------------------- */ void TkpGetFontFamilies( Tcl_Interp *interp, /* Interp to hold result. */ Tk_Window tkwin) /* For display to query. */ { FontNameMap *mapPtr; Tcl_Obj *resultPtr, *strPtr; resultPtr = Tcl_GetObjResult(interp); for (mapPtr = gFontNameMap; mapPtr->utfName != NULL; mapPtr++) { strPtr = Tcl_NewStringObj(mapPtr->utfName, -1); Tcl_ListObjAppendElement(NULL, resultPtr, strPtr); } } /* *------------------------------------------------------------------------- * * TkpGetSubFonts -- * * A function used by the testing package for querying the actual * screen fonts that make up a font object. * * Results: * Modifies interp's result object to hold a list containing the * names of the screen fonts that make up the given font object. * * Side effects: * None. * *------------------------------------------------------------------------- */ void TkpGetSubFonts(interp, tkfont) Tcl_Interp *interp; /* Interp to hold result. */ Tk_Font tkfont; /* Font object to query. */ { int i; Tcl_Obj *resultPtr, *strPtr; MacFont *fontPtr; FontFamily *familyPtr; Str255 nativeName; resultPtr = Tcl_GetObjResult(interp); fontPtr = (MacFont *) tkfont; for (i = 0; i < fontPtr->numSubFonts; i++) { familyPtr = fontPtr->subFontArray[i].familyPtr; GetFontName(familyPtr->faceNum, nativeName); strPtr = Tcl_NewStringObj(GetUtfFaceName(nativeName), -1); Tcl_ListObjAppendElement(NULL, resultPtr, strPtr); } } /* *--------------------------------------------------------------------------- * * Tk_MeasureChars -- * * Determine the number of characters from the string that will fit * in the given horizontal span. The measurement is done under the * assumption that Tk_DrawChars() will be used to actually display * the characters. * * Results: * The return value is the number of bytes from source that * fit into the span that extends from 0 to maxLength. *lengthPtr is * filled with the x-coordinate of the right edge of the last * character that did fit. * * Side effects: * None. * *--------------------------------------------------------------------------- */ int Tk_MeasureChars( Tk_Font tkfont, /* Font in which characters will be drawn. */ CONST char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. */ int numBytes, /* Maximum number of bytes to consider * from source string. */ int maxLength, /* If >= 0, maxLength specifies the longest * permissible line length; don't consider any * character that would cross this * x-position. If < 0, then line length is * unbounded and the flags argument is * ignored. */ int flags, /* Various flag bits OR-ed together: * TK_PARTIAL_OK means include the last char * which only partially fit on this line. * TK_WHOLE_WORDS means stop on a word * boundary, if possible. * TK_AT_LEAST_ONE means return at least one * character even if no characters fit. */ int *lengthPtr) /* Filled with x-location just after the * terminating character. */ { MacFont *fontPtr; FontFamily *lastFamilyPtr; CGrafPtr saveWorld; GDHandle saveDevice; int curX, curByte; /* * According to "Inside Macintosh: Text", the Macintosh may * automatically substitute * ligatures or context-sensitive presentation forms when * measuring/displaying text within a font run. We cannot safely * measure individual characters and add up the widths w/o errors. * However, if we convert a range of text from UTF-8 to, say, * Shift-JIS, and get the offset into the Shift-JIS string as to * where a word or line break would occur, then can we map that * number back to UTF-8? */ fontPtr = (MacFont *) tkfont; GetGWorld(&saveWorld, &saveDevice); SetGWorld(gWorld, NULL); TextSize(fontPtr->size); TextFace(fontPtr->style); lastFamilyPtr = fontPtr->subFontArray[0].familyPtr; if (numBytes == 0) { curX = 0; curByte = 0; } else if (maxLength < 0) { CONST char *p, *end, *next; Tcl_UniChar ch; FontFamily *thisFamilyPtr; Tcl_DString runString; /* * A three step process: * 1. Find a contiguous range of characters that can all be * represented by a single screen font. * 2. Convert those chars to the encoding of that font. * 3. Measure converted chars. */ curX = 0; end = source + numBytes; for (p = source; p < end; ) { next = p + Tcl_UtfToUniChar(p, &ch); thisFamilyPtr = FindSubFontForChar(fontPtr, ch)->familyPtr; if (thisFamilyPtr != lastFamilyPtr) { TextFont(lastFamilyPtr->faceNum); Tcl_UtfToExternalDString(lastFamilyPtr->encoding, source, p - source, &runString); curX += TextWidth(Tcl_DStringValue(&runString), 0, Tcl_DStringLength(&runString)); Tcl_DStringFree(&runString); lastFamilyPtr = thisFamilyPtr; source = p; } p = next; } TextFont(lastFamilyPtr->faceNum); Tcl_UtfToExternalDString(lastFamilyPtr->encoding, source, p - source, &runString); curX += TextWidth(Tcl_DStringValue(&runString), 0, Tcl_DStringLength(&runString)); Tcl_DStringFree(&runString); curByte = numBytes; } else { CONST char *p, *end, *next, *sourceOrig; int widthLeft; FontFamily *thisFamilyPtr; Tcl_UniChar ch; char *rest; /* * How many chars will fit in the space allotted? */ if (maxLength > 32767) { maxLength = 32767; } widthLeft = maxLength; sourceOrig = source; end = source + numBytes; for (p = source; p < end; p = next) { next = p + Tcl_UtfToUniChar(p, &ch); thisFamilyPtr = FindSubFontForChar(fontPtr, ch)->familyPtr; if (thisFamilyPtr != lastFamilyPtr) { if (p > source) { rest = BreakLine(lastFamilyPtr, flags, source, p - source, &widthLeft); flags &= ~TK_AT_LEAST_ONE; if (rest != NULL) { p = source; break; } } lastFamilyPtr = thisFamilyPtr; source = p; } } if (p > source) { rest = BreakLine(lastFamilyPtr, flags, source, p - source, &widthLeft); } if (rest == NULL) { curByte = numBytes; } else { curByte = rest - sourceOrig; } curX = maxLength - widthLeft; } SetGWorld(saveWorld, saveDevice); *lengthPtr = curX; return curByte; } /* *--------------------------------------------------------------------------- * * BreakLine -- * * Determine where the given line of text should be broken so that it * fits in the specified range. Before calling this function, the * font values and graphics port must be set. * * Results: * The return value is NULL if the specified range is larger that the * space the text needs, and *widthLeftPtr is filled with how much * space is left in the range after measuring the whole text buffer. * Otherwise, the return value is a pointer into the text buffer that * indicates where the line should be broken (up to, but not including * that character), and *widthLeftPtr is filled with how much space is * left in the range after measuring up to that character. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static char * BreakLine( FontFamily *familyPtr, /* FontFamily that describes the font values * that are already selected into the graphics * port. */ int flags, /* Various flag bits OR-ed together: * TK_PARTIAL_OK means include the last char * which only partially fit on this line. * TK_WHOLE_WORDS means stop on a word * boundary, if possible. * TK_AT_LEAST_ONE means return at least one * character even if no characters fit. */ CONST char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. */ int numBytes, /* Maximum number of bytes to consider * from source string. */ int *widthLeftPtr) /* On input, specifies size of range into * which characters from source buffer should * be fit. On output, filled with how much * space is left after fitting as many * characters as possible into the range. * Result may be negative if TK_AT_LEAST_ONE * was specified in the flags argument. */ { Fixed pixelWidth, widthLeft; StyledLineBreakCode breakCode; Tcl_DString runString; long textOffset; Boolean leadingEdge; Point point; int charOffset, thisCharWasDoubleByte; char *p, *end, *typeTable; TextFont(familyPtr->faceNum); Tcl_UtfToExternalDString(familyPtr->encoding, source, numBytes, &runString); pixelWidth = Int2Fixed(*widthLeftPtr) + 1; if (flags & TK_WHOLE_WORDS) { textOffset = (flags & TK_AT_LEAST_ONE); widthLeft = pixelWidth; breakCode = StyledLineBreak(Tcl_DStringValue(&runString), Tcl_DStringLength(&runString), 0, Tcl_DStringLength(&runString), 0, &widthLeft, &textOffset); if (breakCode != smBreakOverflow) { /* * StyledLineBreak includes all the space characters at the end of * line that we want to suppress. */ textOffset = VisibleLength(Tcl_DStringValue(&runString), textOffset); goto getoffset; } } else { point.v = 1; point.h = 1; textOffset = PixelToChar(Tcl_DStringValue(&runString), Tcl_DStringLength(&runString), 0, pixelWidth, &leadingEdge, &widthLeft, smOnlyStyleRun, point, point); if (Fixed2Int(widthLeft) < 0) { goto getoffset; } } *widthLeftPtr = Fixed2Int(widthLeft); Tcl_DStringFree(&runString); return NULL; /* * The conversion routine that converts UTF-8 to the target encoding * must map one UTF-8 character to exactly one encoding-specific * character, so that the following algorithm works: * * 1. Get byte offset of where line should be broken. * 2. Get char offset corresponding to that byte offset. * 3. Map that char offset to byte offset in UTF-8 string. */ getoffset: thisCharWasDoubleByte = 0; if (familyPtr->isMultiByteFont == 0) { charOffset = textOffset; } else { charOffset = 0; typeTable = familyPtr->typeTable; p = Tcl_DStringValue(&runString); end = p + textOffset; thisCharWasDoubleByte = typeTable[*((unsigned char *) p)]; for ( ; p < end; p++) { thisCharWasDoubleByte = typeTable[*((unsigned char *) p)]; p += thisCharWasDoubleByte; charOffset++; } } if ((flags & TK_WHOLE_WORDS) == 0) { if ((flags & TK_PARTIAL_OK) && (leadingEdge != 0)) { textOffset += thisCharWasDoubleByte; textOffset++; charOffset++; } else if (((flags & TK_PARTIAL_OK) == 0) && (leadingEdge == 0)) { textOffset -= thisCharWasDoubleByte; textOffset--; charOffset--; } } if ((textOffset == 0) && (Tcl_DStringLength(&runString) > 0) && (flags & TK_AT_LEAST_ONE)) { p = Tcl_DStringValue(&runString); textOffset += familyPtr->typeTable[*((unsigned char *) p)]; textOffset++; charOffset++; } *widthLeftPtr = Fixed2Int(pixelWidth) - TextWidth(Tcl_DStringValue(&runString), 0, textOffset); Tcl_DStringFree(&runString); return Tcl_UtfAtIndex(source, charOffset); } /* *--------------------------------------------------------------------------- * * Tk_DrawChars -- * * Draw a string of characters on the screen. * * Results: * None. * * Side effects: * Information gets drawn on the screen. * *--------------------------------------------------------------------------- */ void Tk_DrawChars( Display *display, /* Display on which to draw. */ Drawable drawable, /* Window or pixmap in which to draw. */ GC gc, /* Graphics context for drawing characters. */ Tk_Font tkfont, /* Font in which characters will be drawn; * must be the same as font used in GC. */ CONST char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) * should be stripped out of the string that * is passed to this function. If they are * not stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ int x, int y) /* Coordinates at which to place origin of * string when drawing. */ { MacFont *fontPtr; MacDrawable *macWin; RGBColor macColor, origColor; GWorldPtr destPort; CGrafPtr saveWorld; GDHandle saveDevice; short txFont, txFace, txSize; BitMapPtr stippleMap; fontPtr = (MacFont *) tkfont; macWin = (MacDrawable *) drawable; destPort = TkMacGetDrawablePort(drawable); GetGWorld(&saveWorld, &saveDevice); SetGWorld(destPort, NULL); TkMacSetUpClippingRgn(drawable); TkMacSetUpGraphicsPort(gc); txFont = tcl_macQdPtr->thePort->txFont; txFace = tcl_macQdPtr->thePort->txFace; txSize = tcl_macQdPtr->thePort->txSize; GetForeColor(&origColor); if ((gc->fill_style == FillStippled || gc->fill_style == FillOpaqueStippled) && gc->stipple != None) { Pixmap pixmap; GWorldPtr bufferPort; stippleMap = TkMacMakeStippleMap(drawable, gc->stipple); pixmap = Tk_GetPixmap(display, drawable, stippleMap->bounds.right, stippleMap->bounds.bottom, 0); bufferPort = TkMacGetDrawablePort(pixmap); SetGWorld(bufferPort, NULL); if (TkSetMacColor(gc->foreground, &macColor) == true) { RGBForeColor(&macColor); } ShowPen(); FillRect(&stippleMap->bounds, &tcl_macQdPtr->white); MultiFontDrawText(fontPtr, source, numBytes, 0, 0); SetGWorld(destPort, NULL); CopyDeepMask(&((GrafPtr) bufferPort)->portBits, stippleMap, &((GrafPtr) destPort)->portBits, &stippleMap->bounds, &stippleMap->bounds, &((GrafPtr) destPort)->portRect, srcOr, NULL); /* TODO: this doesn't work quite right - it does a blend. you can't * draw white text when you have a stipple. */ Tk_FreePixmap(display, pixmap); ckfree(stippleMap->baseAddr); ckfree((char *)stippleMap); } else { if (TkSetMacColor(gc->foreground, &macColor) == true) { RGBForeColor(&macColor); } ShowPen(); MultiFontDrawText(fontPtr, source, numBytes, macWin->xOff + x, macWin->yOff + y); } TextFont(txFont); TextSize(txSize); TextFace(txFace); RGBForeColor(&origColor); SetGWorld(saveWorld, saveDevice); } /* *------------------------------------------------------------------------- * * MultiFontDrawText -- * * Helper function for Tk_DrawChars. Draws characters, using the * various screen fonts in fontPtr to draw multilingual characters. * Note: No bidirectional support. * * Results: * None. * * Side effects: * Information gets drawn on the screen. * Contents of fontPtr may be modified if more subfonts were loaded * in order to draw all the multilingual characters in the given * string. * *------------------------------------------------------------------------- */ static void MultiFontDrawText( MacFont *fontPtr, /* Contains set of fonts to use when drawing * following string. */ CONST char *source, /* Potentially multilingual UTF-8 string. */ int numBytes, /* Length of string in bytes. */ int x, int y) /* Coordinates at which to place origin * * of string when drawing. */ { FontFamily *lastFamilyPtr, *thisFamilyPtr; Tcl_DString runString; CONST char *p, *end, *next; Tcl_UniChar ch; TextSize(fontPtr->size); TextFace(fontPtr->style); lastFamilyPtr = fontPtr->subFontArray[0].familyPtr; end = source + numBytes; for (p = source; p < end; ) { next = p + Tcl_UtfToUniChar(p, &ch); thisFamilyPtr = FindSubFontForChar(fontPtr, ch)->familyPtr; if (thisFamilyPtr != lastFamilyPtr) { if (p > source) { TextFont(lastFamilyPtr->faceNum); Tcl_UtfToExternalDString(lastFamilyPtr->encoding, source, p - source, &runString); MoveTo((short) x, (short) y); DrawText(Tcl_DStringValue(&runString), 0, Tcl_DStringLength(&runString)); x += TextWidth(Tcl_DStringValue(&runString), 0, Tcl_DStringLength(&runString)); Tcl_DStringFree(&runString); source = p; } lastFamilyPtr = thisFamilyPtr; } p = next; } if (p > source) { TextFont(thisFamilyPtr->faceNum); Tcl_UtfToExternalDString(lastFamilyPtr->encoding, source, p - source, &runString); MoveTo((short) x, (short) y); DrawText(Tcl_DStringValue(&runString), 0, Tcl_DStringLength(&runString)); Tcl_DStringFree(&runString); } } /* *--------------------------------------------------------------------------- * * TkMacIsCharacterMissing -- * * Given a tkFont and a character determines whether the character has * a glyph defined in the font or not. Note that this is potentially * not compatible with Mac OS 8 as it looks at the font handle * structure directly. Looks into the character array of the font * handle to determine whether the glyph is defined or not. * * Results: * Returns a 1 if the character is missing, a 0 if it is not. * * Side effects: * None. * *--------------------------------------------------------------------------- */ int TkMacIsCharacterMissing( Tk_Font tkfont, /* The font we are looking in. */ unsigned int searchChar) /* The character we are looking for. */ { MacFont *fontPtr = (MacFont *) tkfont; FMInput fm; FontRec **fontRecHandle; fm.family = fontPtr->subFontArray[0].familyPtr->faceNum; fm.size = fontPtr->size; fm.face = fontPtr->style; fm.needBits = 0; fm.device = 0; fm.numer.h = fm.numer.v = fm.denom.h = fm.denom.v = 1; #if !defined(UNIVERSAL_INTERFACES_VERSION) || (UNIVERSAL_INTERFACES_VERSION < 0x0300) fontRecHandle = (FontRec **) FMSwapFont(&fm)->fontResult; #else fontRecHandle = (FontRec **) FMSwapFont(&fm)->fontHandle; #endif return *(short *) ((long) &(*fontRecHandle)->owTLoc + ((long)((*fontRecHandle)->owTLoc + searchChar - (*fontRecHandle)->firstChar) * sizeof(short))) == -1; } /* *--------------------------------------------------------------------------- * * InitFont -- * * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). * Initializes the memory for a MacFont that wraps the platform-specific * data. * * The caller is responsible for initializing the fields of the * TkFont that are used exclusively by the generic TkFont code, and * for releasing those fields before calling TkpDeleteFont(). * * Results: * Fills the MacFont structure. * * Side effects: * Memory allocated. * *--------------------------------------------------------------------------- */ static void InitFont( Tk_Window tkwin, /* For display where font will be used. */ int faceNum, /* Macintosh font number. */ int size, /* Point size for Macintosh font. */ int style, /* Macintosh style bits. */ MacFont *fontPtr) /* Filled with information constructed from * the above arguments. */ { Str255 nativeName; FontInfo fi; TkFontAttributes *faPtr; TkFontMetrics *fmPtr; CGrafPtr saveWorld; GDHandle saveDevice; short pixels; if (size == 0) { size = -GetDefFontSize(); } pixels = (short) TkFontGetPixels(tkwin, size); GetGWorld(&saveWorld, &saveDevice); SetGWorld(gWorld, NULL); TextFont(faceNum); TextSize(pixels); TextFace(style); GetFontInfo(&fi); GetFontName(faceNum, nativeName); fontPtr->font.fid = (Font) fontPtr; faPtr = &fontPtr->font.fa; faPtr->family = GetUtfFaceName(nativeName); faPtr->size = TkFontGetPoints(tkwin, size); faPtr->weight = (style & bold) ? TK_FW_BOLD : TK_FW_NORMAL; faPtr->slant = (style & italic) ? TK_FS_ITALIC : TK_FS_ROMAN; faPtr->underline = ((style & underline) != 0); faPtr->overstrike = 0; fmPtr = &fontPtr->font.fm; fmPtr->ascent = fi.ascent; fmPtr->descent = fi.descent; fmPtr->maxWidth = fi.widMax; fmPtr->fixed = (CharWidth('i') == CharWidth('w')); fontPtr->size = pixels; fontPtr->style = (short) style; fontPtr->numSubFonts = 1; fontPtr->subFontArray = fontPtr->staticSubFonts; InitSubFont(fontPtr, faceNum, &fontPtr->subFontArray[0]); SetGWorld(saveWorld, saveDevice); } /* *------------------------------------------------------------------------- * * ReleaseFont -- * * Called to release the Macintosh-specific contents of a TkFont. * The caller is responsible for freeing the memory used by the * font itself. * * Results: * None. * * Side effects: * Memory is freed. * *--------------------------------------------------------------------------- */ static void ReleaseFont( MacFont *fontPtr) /* The font to delete. */ { int i; for (i = 0; i < fontPtr->numSubFonts; i++) { ReleaseSubFont(&fontPtr->subFontArray[i]); } if (fontPtr->subFontArray != fontPtr->staticSubFonts) { ckfree((char *) fontPtr->subFontArray); } } /* *------------------------------------------------------------------------- * * InitSubFont -- * * Wrap a screen font and load the FontFamily that represents * it. Used to prepare a SubFont so that characters can be mapped * from UTF-8 to the charset of the font. * * Results: * The subFontPtr is filled with information about the font. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void InitSubFont( CONST MacFont *fontPtr, /* Font object in which the SubFont will be * used. */ int faceNum, /* The font number. */ SubFont *subFontPtr) /* Filled with SubFont constructed from * above attributes. */ { subFontPtr->familyPtr = AllocFontFamily(fontPtr, faceNum); subFontPtr->fontMap = subFontPtr->familyPtr->fontMap; } /* *------------------------------------------------------------------------- * * ReleaseSubFont -- * * Called to release the contents of a SubFont. The caller is * responsible for freeing the memory used by the SubFont itself. * * Results: * None. * * Side effects: * Memory and resources are freed. * *--------------------------------------------------------------------------- */ static void ReleaseSubFont( SubFont *subFontPtr) /* The SubFont to delete. */ { FreeFontFamily(subFontPtr->familyPtr); } /* *------------------------------------------------------------------------- * * AllocFontFamily -- * * Find the FontFamily structure associated with the given font * family. The information should be stored by the caller in a * SubFont and used when determining if that SubFont supports a * character. * * Results: * A pointer to a FontFamily. The reference count in the FontFamily * is automatically incremented. When the SubFont is released, the * reference count is decremented. When no SubFont is using this * FontFamily, it may be deleted. * * Side effects: * A new FontFamily structure will be allocated if this font family * has not been seen. * *------------------------------------------------------------------------- */ static FontFamily * AllocFontFamily( CONST MacFont *fontPtr, /* Font object in which the FontFamily will * be used. */ int faceNum) /* The font number. */ { FontFamily *familyPtr; int i; familyPtr = fontFamilyList; for (; familyPtr != NULL; familyPtr = familyPtr->nextPtr) { if (familyPtr->faceNum == faceNum) { familyPtr->refCount++; return familyPtr; } } familyPtr = (FontFamily *) ckalloc(sizeof(FontFamily)); memset(familyPtr, 0, sizeof(FontFamily)); familyPtr->nextPtr = fontFamilyList; fontFamilyList = familyPtr; /* * Set key for this FontFamily. */ familyPtr->faceNum = faceNum; /* * An initial refCount of 2 means that FontFamily information will * persist even when the SubFont that loaded the FontFamily is released. * Change it to 1 to cause FontFamilies to be unloaded when not in use. */ familyPtr->refCount = 2; familyPtr->encoding = GetFontEncoding(faceNum, 1, &familyPtr->isSymbolFont); familyPtr->isMultiByteFont = 0; FillParseTable(familyPtr->typeTable, FontToScript(faceNum)); for (i = 0; i < 256; i++) { if (familyPtr->typeTable[i] != 0) { familyPtr->isMultiByteFont = 1; break; } } return familyPtr; } /* *------------------------------------------------------------------------- * * FreeFontFamily -- * * Called to free a FontFamily when the SubFont is finished using it. * Frees the contents of the FontFamily and the memory used by the * FontFamily itself. * * Results: * None. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void FreeFontFamily( FontFamily *familyPtr) /* The FontFamily to delete. */ { FontFamily **familyPtrPtr; int i; if (familyPtr == NULL) { return; } familyPtr->refCount--; if (familyPtr->refCount > 0) { return; } Tcl_FreeEncoding(familyPtr->encoding); for (i = 0; i < FONTMAP_PAGES; i++) { if (familyPtr->fontMap[i] != NULL) { ckfree((char *) familyPtr->fontMap[i]); } } /* * Delete from list. */ for (familyPtrPtr = &fontFamilyList; ; ) { if (*familyPtrPtr == familyPtr) { *familyPtrPtr = familyPtr->nextPtr; break; } familyPtrPtr = &(*familyPtrPtr)->nextPtr; } ckfree((char *) familyPtr); } /* *------------------------------------------------------------------------- * * FindSubFontForChar -- * * Determine which physical screen font is necessary to use to * display the given character. If the font object does not have * a screen font that can display the character, another screen font * may be loaded into the font object, following a set of preferred * fallback rules. * * Results: * The return value is the SubFont to use to display the given * character. * * Side effects: * The contents of fontPtr are modified to cache the results * of the lookup and remember any SubFonts that were dynamically * loaded. * *------------------------------------------------------------------------- */ static SubFont * FindSubFontForChar( MacFont *fontPtr, /* The font object with which the character * will be displayed. */ int ch) /* The Unicode character to be displayed. */ { int i, j, k; char *fallbackName; char **aliases; SubFont *subFontPtr; FontNameMap *mapPtr; Tcl_DString faceNames; char ***fontFallbacks; char **anyFallbacks; if (FontMapLookup(&fontPtr->subFontArray[0], ch)) { return &fontPtr->subFontArray[0]; } for (i = 1; i < fontPtr->numSubFonts; i++) { if (FontMapLookup(&fontPtr->subFontArray[i], ch)) { return &fontPtr->subFontArray[i]; } } /* * Keep track of all face names that we check, so we don't check some * name multiple times if it can be reached by multiple paths. */ Tcl_DStringInit(&faceNames); aliases = TkFontGetAliasList(fontPtr->font.fa.family); subFontPtr = NULL; fontFallbacks = TkFontGetFallbacks(); for (i = 0; fontFallbacks[i] != NULL; i++) { for (j = 0; fontFallbacks[i][j] != NULL; j++) { fallbackName = fontFallbacks[i][j]; if (strcasecmp(fallbackName, fontPtr->font.fa.family) == 0) { /* * If the base font has a fallback... */ goto tryfallbacks; } else if (aliases != NULL) { /* * Or if an alias for the base font has a fallback... */ for (k = 0; aliases[k] != NULL; k++) { if (strcasecmp(aliases[k], fallbackName) == 0) { goto tryfallbacks; } } } } continue; /* * ...then see if we can use one of the fallbacks, or an * alias for one of the fallbacks. */ tryfallbacks: for (j = 0; fontFallbacks[i][j] != NULL; j++) { fallbackName = fontFallbacks[i][j]; subFontPtr = CanUseFallbackWithAliases(fontPtr, fallbackName, ch, &faceNames); if (subFontPtr != NULL) { goto end; } } } /* * See if we can use something from the global fallback list. */ anyFallbacks = TkFontGetGlobalClass(); for (i = 0; anyFallbacks[i] != NULL; i++) { fallbackName = anyFallbacks[i]; subFontPtr = CanUseFallbackWithAliases(fontPtr, fallbackName, ch, &faceNames); if (subFontPtr != NULL) { goto end; } } /* * Try all face names available in the whole system until we * find one that can be used. */ for (mapPtr = gFontNameMap; mapPtr->utfName != NULL; mapPtr++) { fallbackName = mapPtr->utfName; if (SeenName(fallbackName, &faceNames) == 0) { subFontPtr = CanUseFallback(fontPtr, fallbackName, ch); if (subFontPtr != NULL) { goto end; } } } end: Tcl_DStringFree(&faceNames); if (subFontPtr == NULL) { /* * No font can display this character. We will use the base font * and have it display the "unknown" character. */ subFontPtr = &fontPtr->subFontArray[0]; FontMapInsert(subFontPtr, ch); } return subFontPtr; } /* *------------------------------------------------------------------------- * * FontMapLookup -- * * See if the screen font can display the given character. * * Results: * The return value is 0 if the screen font cannot display the * character, non-zero otherwise. * * Side effects: * New pages are added to the font mapping cache whenever the * character belongs to a page that hasn't been seen before. * When a page is loaded, information about all the characters on * that page is stored, not just for the single character in * question. * *------------------------------------------------------------------------- */ static int FontMapLookup( SubFont *subFontPtr, /* Contains font mapping cache to be queried * and possibly updated. */ int ch) /* Character to be tested. */ { int row, bitOffset; row = ch >> FONTMAP_SHIFT; if (subFontPtr->fontMap[row] == NULL) { FontMapLoadPage(subFontPtr, row); } bitOffset = ch & (FONTMAP_BITSPERPAGE - 1); return (subFontPtr->fontMap[row][bitOffset >> 3] >> (bitOffset & 7)) & 1; } /* *------------------------------------------------------------------------- * * FontMapInsert -- * * Tell the font mapping cache that the given screen font should be * used to display the specified character. This is called when no * font on the system can be be found that can display that * character; we lie to the font and tell it that it can display * the character, otherwise we would end up re-searching the entire * fallback hierarchy every time that character was seen. * * Results: * None. * * Side effects: * New pages are added to the font mapping cache whenever the * character belongs to a page that hasn't been seen before. * When a page is loaded, information about all the characters on * that page is stored, not just for the single character in * question. * *------------------------------------------------------------------------- */ static void FontMapInsert( SubFont *subFontPtr, /* Contains font mapping cache to be * updated. */ int ch) /* Character to be added to cache. */ { int row, bitOffset; row = ch >> FONTMAP_SHIFT; if (subFontPtr->fontMap[row] == NULL) { FontMapLoadPage(subFontPtr, row); } bitOffset = ch & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } /* *------------------------------------------------------------------------- * * FontMapLoadPage -- * * Load information about all the characters on a given page. * This information consists of one bit per character that indicates * whether the associated HFONT can (1) or cannot (0) display the * characters on the page. * * Results: * None. * * Side effects: * Mempry allocated. * *------------------------------------------------------------------------- */ static void FontMapLoadPage( SubFont *subFontPtr, /* Contains font mapping cache to be * updated. */ int row) /* Index of the page to be loaded into * the cache. */ { FMInput fm; FontRec *fontRecPtr; short *widths; int i, end, bitOffset, isMultiByteFont; char src[TCL_UTF_MAX]; unsigned char buf[16]; int srcRead, dstWrote; Tcl_Encoding encoding; Handle fHandle; short theID; ResType theType; Str255 theName; subFontPtr->fontMap[row] = (char *) ckalloc(FONTMAP_BITSPERPAGE / 8); memset(subFontPtr->fontMap[row], 0, FONTMAP_BITSPERPAGE / 8); encoding = subFontPtr->familyPtr->encoding; fm.family = subFontPtr->familyPtr->faceNum; fm.size = 12; fm.face = 0; fm.needBits = 0; fm.device = 0; fm.numer.h = 1; fm.numer.v = 1; fm.denom.h = 1; fm.denom.v = 1; #if !defined(UNIVERSAL_INTERFACES_VERSION) || (UNIVERSAL_INTERFACES_VERSION < 0x0300) fHandle = FMSwapFont(&fm)->fontHandle; #else fHandle = FMSwapFont(&fm)->fontHandle; #endif GetResInfo(fHandle, &theID, &theType, theName); isMultiByteFont = subFontPtr->familyPtr->isMultiByteFont; if( theType=='sfnt' ) { /* * Found an outline font which has very complex font record. * Let's just assume *ALL* the characters are allowed. */ end = (row + 1) << FONTMAP_SHIFT; for (i = row << FONTMAP_SHIFT; i < end; i++) { if (Tcl_UtfToExternal(NULL, encoding, src, Tcl_UniCharToUtf(i, src), TCL_ENCODING_STOPONERROR, NULL, (char *) buf, sizeof(buf), &srcRead, &dstWrote, NULL) == TCL_OK) { bitOffset = i & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } } } else { /* * Found an old bitmap font which has a well-defined record. * We can check the width table to see which characters exist.