summaryrefslogtreecommitdiffstats
path: root/library/demos/widget
blob: 2cf49c40cd9dc4c4238d29f714d601f826deabe5 (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
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
#!/bin/sh
# the next line restarts using wish \
exec wish "$0" "$@"

# widget --
# This script demonstrates the various widgets provided by Tk, along with many
# of the features of the Tk toolkit. This file only contains code to generate
# the main window for the application, which invokes individual
# demonstrations. The code for the actual demonstrations is contained in
# separate ".tcl" files is this directory, which are sourced by this script as
# needed.
#
# RCS: @(#) $Id: widget,v 1.32 2007/10/16 15:15:19 dkf Exp $

package require Tcl	8.5
package require Tk	8.5
package require msgcat
package require Ttk

eval destroy [winfo child .]
set tk_demoDirectory [file join [pwd] [file dirname [info script]]]
::msgcat::mcload $tk_demoDirectory
namespace import ::msgcat::mc
wm title . [mc "Widget Demonstration"]
if {[tk windowingsystem] eq "x11"} {
    # This won't work everywhere, but there's no other way in core Tk at the
    # moment to display a coloured icon.
    image create photo TclPowered \
	    -file [file join $tk_library images logo64.gif]
    wm iconwindow . [toplevel ._iconWindow]
    pack [label ._iconWindow.i -image TclPowered]
    wm iconname . [mc "tkWidgetDemo"]
}

if {"defaultFont" ni [font names]} {
    # TIP #145 defines some standard named fonts
    if {"TkDefaultFont" in [font names] && "TkFixedFont" in [font names]} {
        # FIX ME: the following tecnique of cloning the font to copy it works
        #         fine but means that if the system font is changed by Tk
        #         cannot update the copied font. font alias might be useful
        #         here -- or fix the app to use TkDefaultFont etc.
        font create mainFont   {*}[font configure TkDefaultFont]
        font create fixedFont  {*}[font configure TkFixedFont]
        font create boldFont   {*}[font configure TkDefaultFont] -weight bold
        font create titleFont  {*}[font configure TkDefaultFont] -weight bold
        font create statusFont {*}[font configure TkDefaultFont]
        font create varsFont   {*}[font configure TkDefaultFont]
    } else {
        font create mainFont   -family Helvetica -size 12
        font create fixedFont  -family Courier   -size 10
        font create boldFont   -family Helvetica -size 12 -weight bold
        font create titleFont  -family Helvetica -size 18 -weight bold
        font create statusFont -family Helvetica -size 10
        font create varsFont   -family Helvetica -size 14
    }
}

set widgetDemo 1
set font mainFont

image create photo ::img::refresh -height 16 -format GIF -data {
    R0lGODlhEAAQAPMAAMz/zCpnKdb/1z9mPypbKBtLGy9NMPL/9Or+6+P+4j1Y
    PwQKBP7//xMLFAYBCAEBASH5BAEAAAAALAAAAAAQABAAAwR0EAD3Gn0Vyw0e
    ++CncU7IIAezMA/nhUqSLJizvSdCEEjy2ZIV46AwDAoDHwPYGSoEiUJAAGJ6
    EDHBNCFINW5OqABKSFk/B9lUa94IDwIFgewFMwQDQwCZQCztTgM9Sl8SOEMG
    KSAthiaOjBMPDhQONBiXABEAOw==
}

image create photo ::img::view -height 16 -format GIF -data {
    R0lGODlhEAAQAPMAAMz/zP///8DAwICAgH9/fwAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAQABAAAwRIcMhJB7h3hM33
    KFjWdQQYap1QrCaGBmrRrS4nj5b53jOgbwXBKGACoYLDIuAoHCmZyYvR1rT5
    RMAq8LqcIYGsrjPsW1XOmFUEADs=
}

image create photo ::img::delete -height 16 -format GIF -data {
    R0lGODlhEAAOAKEAAIQAAO/n3v///////yH5BAEKAAIALAAAAAAQAA4AAAIm
    lI9pAKHbIHNoVhYhTdjlJ2AWKG2g+CldmB6rxo2uybYhbS80eRQAOw==
}

image create photo ::img::print -height 19 -format GIF -data {
    R0lGODlhGgATAPcAACEQOTEpQjEpUkIpc0IxY0I5c0oxjEo5SlJCY1JCe1JK
    UlpChFpCjFpGkFpSc1paa2NKc2NKnGNja2tapWtjc29KnHNanHNjc3NjrXNr
    jHNrnHNzc3tjpXtrtXtzhICAgIRzvYSEjIZzqox7tYyEnIyMjJSEtZSEvZSM
    lJyMtZyMvZyUlJyUrZyUvZycnKWctaWlpa2czq2lzrWtvbWtzrW1tb21xr21
    1sa9zs693s7OztbO3tbO597W1t7W7+fe7+fn5////+/n7+/v7+/v9////wAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAACH5BAEAAEEALAAAAAAaABMAQAj/AIMIHBhkg0GC
    CBMGIQEiQgseQT4oeCBBAokgRYYQ0JBixg8hRIiUUEBBYYmTByBwiCBCRYwH
    CxY8cKFw4AogRXLqLAJkQ80gCBBg3BkxZswTNGh4MGqgQQUMJRHCwMkTSE+D
    Pn8eCKBhxIMhO3ei2OHDBw6sWSlMMMoWgwwfMDZI8GBjx44NARZwEGGi5MkS
    PcIWKRGz5YgLbAco+KkQBQoJIRgjdGEVq+SaJajqtNrzMgsPCmoIzqmDgmWE
    KOBuUKAAwYabYTfs4OHjY0giGyhk4MAWRI4eKyRQqPgggYUXPH4A+XBAgwoK
    DiIsCFxjA9sFEVQQCRJCAYAFDJxiKhAxvMTonEFimrhhYinTBgWiCvxLNX3M
    DkkpsKV5OYhjBxCMYAICAigUEAA7
}

image create photo ::img::new -format GIF -data {
    R0lGODlhHgAOAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgICAgMDAwP8AAAD/
    AP//AAAA//8A/wD//////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAMwAAZgAAmQAAzAAA/wAzAAAzMwAzZgAzmQAzzAAz/wBmAABmMwBmZgBm
    mQBmzABm/wCZAACZMwCZZgCZmQCZzACZ/wDMAADMMwDMZgDMmQDMzADM/wD/
    AAD/MwD/ZgD/mQD/zAD//zMAADMAMzMAZjMAmTMAzDMA/zMzADMzMzMzZjMz
    mTMzzDMz/zNmADNmMzNmZjNmmTNmzDNm/zOZADOZMzOZZjOZmTOZzDOZ/zPM
    ADPMMzPMZjPMmTPMzDPM/zP/ADP/MzP/ZjP/mTP/zDP//2YAAGYAM2YAZmYA
    mWYAzGYA/2YzAGYzM2YzZmYzmWYzzGYz/2ZmAGZmM2ZmZmZmmWZmzGZm/2aZ
    AGaZM2aZZmaZmWaZzGaZ/2bMAGbMM2bMZmbMmWbMzGbM/2b/AGb/M2b/Zmb/
    mWb/zGb//5kAAJkAM5kAZpkAmZkAzJkA/5kzAJkzM5kzZpkzmZkzzJkz/5lm
    AJlmM5lmZplmmZlmzJlm/5mZAJmZM5mZZpmZmZmZzJmZ/5nMAJnMM5nMZpnM
    mZnMzJnM/5n/AJn/M5n/Zpn/mZn/zJn//8wAAMwAM8wAZswAmcwAzMwA/8wz
    AMwzM8wzZswzmcwzzMwz/8xmAMxmM8xmZsxmmcxmzMxm/8yZAMyZM8yZZsyZ
    mcyZzMyZ/8zMAMzMM8zMZszMmczMzMzM/8z/AMz/M8z/Zsz/mcz/zMz///8A
    AP8AM/8AZv8Amf8AzP8A//8zAP8zM/8zZv8zmf8zzP8z//9mAP9mM/9mZv9m
    mf9mzP9m//+ZAP+ZM/+ZZv+Zmf+ZzP+Z///MAP/MM//MZv/Mmf/MzP/M////
    AP//M///Zv//mf//zP///yH5BAEAABAALAAAAAAeAA4AAAiWAMMJFPhvYEGC
    /xIeDLdw4UCC+gr+i8hQn0WLEilOdAiRW0R9HidyGznyY0iQFA2CROGRG8uV
    KGK+dNnyZUOYI2eyJGmR5sqQKl3u1FnSJNGUFWmy1BnzJM2cQDsu9fk0osip
    NoMOPYrx51SkV3MS5enV502qTGV6LIu0o0mTJEOKRMkRYsaMF1NubPuQoUGD
    Ch0q7BsQADs=
}
apply {{} {
    # Fix the 'new' image's lack of transparency using a "once only" procedure
    # (really a lambda application...)
    # TODO: rework the image to have the transparent bit set
    set i ::img::new
    set t "255 0 255"
    set w [image width $i]
    set h [image height $i]

    for {set x 0} {$x < $w} {incr x} {
	for {set y 0} {$y < $h} {incr y} {
	    if {[$i get $x $y] eq $t} {
		$i trans set $x $y 1
	    }
	}
    }
}}

#----------------------------------------------------------------
# The code below create the main window, consisting of a menu bar and a text
# widget that explains how to use the program, plus lists all of the demos as
# hypertext items.
#----------------------------------------------------------------

menu .menuBar -tearoff 0

# On the Mac use the special .apple menu for the about item
if {[tk windowingsystem] eq "aqua"} {
    .menuBar add cascade -menu .menuBar.apple
    menu .menuBar.apple -tearoff 0
    .menuBar.apple add command -label [mc "About..."] -command {aboutBox}
} else {
    # This is a tk-internal procedure to make i18n easier
    ::tk::AmpMenuArgs .menuBar add cascade -label [mc "&File"] \
	    -menu .menuBar.file
    menu .menuBar.file -tearoff 0
    ::tk::AmpMenuArgs .menuBar.file add command -label [mc "&About..."] \
	    -command {aboutBox} -accelerator [mc "<F1>"]
    .menuBar.file add sep
    ::tk::AmpMenuArgs .menuBar.file add command -label [mc "&Quit"] \
	    -command {exit} -accelerator [mc "Meta-Q"]
    bind . <[mc "Meta-q"]> {exit}
    bind . <F1>     {aboutBox}
}

. configure -menu .menuBar

ttk::frame .statusBar
ttk::label .statusBar.lab -text "   " -anchor w
ttk::sizegrip .statusBar.foo
pack .statusBar.lab -side left -padx 2 -expand yes -fill both
pack .statusBar.foo -side left -padx 2
pack .statusBar -side bottom -fill x -pady 2

ttk::frame .textFrame
scrollbar .s -orient vertical -command {.t yview} -highlightthickness 0 \
    -takefocus 1 -bd 1
pack .s -in .textFrame -side right -fill y
text .t -yscrollcommand {.s set}  -wrap word  -width 70  -height 30 \
	-font mainFont  -setgrid 1  -highlightthickness 0 \
	-padx 4  -pady 2  -takefocus 0 -bd 1
pack .t -in .textFrame -expand y -fill both -padx 1
pack  .textFrame -expand yes -fill both

# Create a bunch of tags to use in the text widget, such as those for section
# titles and demo descriptions. Also define the bindings for tags.

.t tag configure title -font titleFont
.t tag configure bold  -font boldFont

# We put some "space" characters to the left and right of each demo
# description so that the descriptions are highlighted only when the mouse
# cursor is right over them (but not when the cursor is to their left or
# right).
#
.t tag configure demospace -lmargin1 1c -lmargin2 1c


if {[winfo depth .] == 1} {
    .t tag configure demo -lmargin1 1c -lmargin2 1c \
	-underline 1
    .t tag configure visited -lmargin1 1c -lmargin2 1c \
	-underline 1
    .t tag configure hot -background black -foreground white
} else {
    .t tag configure demo -lmargin1 1c -lmargin2 1c \
	-foreground blue -underline 1
    .t tag configure visited -lmargin1 1c -lmargin2 1c \
	-foreground #303080 -underline 1
    .t tag configure hot -foreground red -underline 1
}
.t tag bind demo <ButtonRelease-1> {
    invoke [.t index {@%x,%y}]
}
set lastLine ""
.t tag bind demo <Enter> {
    set lastLine [.t index {@%x,%y linestart}]
    .t tag add hot "$lastLine +1 chars" "$lastLine lineend -1 chars"
    .t config -cursor hand2
    showStatus [.t index {@%x,%y}]
}
.t tag bind demo <Leave> {
    .t tag remove hot 1.0 end
    .t config -cursor xterm
    .statusBar.lab config -text ""
}
.t tag bind demo <Motion> {
    set newLine [.t index {@%x,%y linestart}]
    if {$newLine ne $lastLine} {
	.t tag remove hot 1.0 end
	set lastLine $newLine

	set tags [.t tag names {@%x,%y}]
	set i [lsearch -glob $tags demo-*]
	if {$i >= 0} {
	    .t tag add hot "$lastLine +1 chars" "$lastLine lineend -1 chars"
	}
    }
    showStatus [.t index {@%x,%y}]
}

##############################################################################
# Create the text for the text widget.

# addFormattedText --
#
#	Add formatted text (but not hypertext) to the text widget after first
#	passing it through the message catalog to allow for localization.
#	Lines starting with @@ are formatting directives (insert title, insert
#	demo hyperlink, begin newline, or change style) and all other lines
#	are literal strings to be inserted. Blank lines are ignored.
#
proc addFormattedText {formattedText} {
    set style normal
    set isNL 1
    set demoCount 0
    set new 0
    foreach line [split [mc $formattedText] \n] {
	set line [string trim $line]
	if {$line eq ""} {
	    continue
	}
	if {[string match @@* $line]} {
	    set data [string range $line 2 end]
	    set key [lindex $data 0]
	    set values [lrange $data 1 end]
	    switch -exact -- $key {
		title {
		    .t insert end [mc $values]\n title \n normal
		}
		newline {
		    .t insert end \n $style
		    set isNL 1
		}
		subtitle {
		    .t insert end "\n" {} [mc $values] title " \n " demospace
		    set demoCount 0
		}
		demo {
		    set description [lassign $values name]
		    .t insert end "[incr demoCount]. [mc $description]." \
			    [list demo demo-$name]
		    if {$new} {
			.t image create end -image ::img::new
			set new 0
		    }
		    .t insert end " \n " demospace
		}
		new {
		    set new 1
		}
		default {
		    set style $key
		}
	    }
	    continue
	}
	if {!$isNL} {
	    .t insert end " " $style
	}
	set isNL 0
	.t insert end $line $style
    }
}

addFormattedText {
    @@title	Tk Widget Demonstrations

    This application provides a front end for several short scripts
    that demonstrate what you can do with Tk widgets.  Each of the
    numbered lines below describes a demonstration; you can click on
    it to invoke the demonstration.  Once the demonstration window
    appears, you can click the
    @@bold
    See Code
    @@normal
    button to see the Tcl/Tk code that created the demonstration.  If
    you wish, you can edit the code and click the
    @@bold
    Rerun Demo
    @@normal
    button in the code window to reinvoke the demonstration with the
    modified code.
    @@newline

    @@subtitle	Labels, buttons, checkbuttons, and radiobuttons
    @@demo label	Labels (text and bitmaps)
    @@demo unicodeout	Labels and UNICODE text
    @@demo button	Buttons
    @@demo check	Check-buttons (select any of a group)
    @@demo radio	Radio-buttons (select one of a group)
    @@demo puzzle	A 15-puzzle game made out of buttons
    @@demo icon		Iconic buttons that use bitmaps
    @@demo image1	Two labels displaying images
    @@demo image2	A simple user interface for viewing images
    @@demo labelframe	Labelled frames

    @@subtitle	Listboxes
    @@demo states	The 50 states
    @@demo colors	Colors: change the color scheme for the application
    @@demo sayings	A collection of famous and infamous sayings

    @@subtitle	Entries and Spin-boxes
    @@demo entry1	Entries without scrollbars
    @@demo entry2	Entries with scrollbars
    @@demo entry3	Validated entries and password fields
    @@demo spin		Spin-boxes
    @@demo form		Simple Rolodex-like form

    @@subtitle	Text
    @@demo text		Basic editable text
    @@demo style	Text display styles
    @@demo bind		Hypertext (tag bindings)
    @@demo twind	A text widget with embedded windows and other features
    @@demo search	A search tool built with a text widget
    @@new
    @@demo textpeer	Peering text widgets

    @@subtitle	Canvases
    @@demo items	The canvas item types
    @@demo plot		A simple 2-D plot
    @@demo ctext	Text items in canvases
    @@demo arrow	An editor for arrowheads on canvas lines
    @@demo ruler	A ruler with adjustable tab stops
    @@demo floor	A building floor plan
    @@demo cscroll	A simple scrollable canvas

    @@subtitle	Scales
    @@demo hscale	Horizontal scale
    @@demo vscale	Vertical scale

    @@subtitle	Paned Windows
    @@demo paned1	Horizontal paned window
    @@demo paned2	Vertical paned window

    @@subtitle	Menus
    @@demo menu		Menus and cascades (sub-menus)
    @@demo menubu	Menu-buttons

    @@subtitle	Common Dialogs
    @@demo msgbox	Message boxes
    @@demo filebox	File selection dialog
    @@demo clrpick	Color picker

    @@subtitle	Animation
    @@new
    @@demo anilabel	Animated labels
    @@new
    @@demo aniwave	Animated wave
    @@new
    @@demo pendulum	Pendulum simulation
    @@new
    @@demo goldberg	A celebration of Rube Goldberg

    @@subtitle	Miscellaneous
    @@demo bitmap	The built-in bitmaps
    @@demo dialog1	A dialog box with a local grab
    @@demo dialog2	A dialog box with a global grab
}

##############################################################################

.t configure -state disabled
focus .s

# addSeeDismiss --
# Add "See Code" and "Dismiss" button frame, with optional "See Vars"
#
# Arguments:
# w -		The name of the frame to use.

proc addSeeDismiss {w show {vars {}} {extra {}}} {
    ## See Code / Dismiss buttons
    ttk::frame $w
    ttk::separator $w.sep
    #ttk::frame $w.sep -height 2 -relief sunken
    grid $w.sep -columnspan 4 -row 0 -sticky ew -pady 2
    ttk::button $w.dismiss -text [mc "Dismiss"] \
	-image ::img::delete -compound left \
	-command [list destroy [winfo toplevel $w]]
    ttk::button $w.code -text [mc "See Code"] \
	-image ::img::view -compound left \
	-command [list showCode $show]
    set buttons [list x $w.code $w.dismiss]
    if {[llength $vars]} {
	ttk::button $w.vars -text [mc "See Variables"] \
	    -image ::img::view -compound left \
	    -command [concat [list showVars $w.dialog] $vars]
	set buttons [linsert $buttons 1 $w.vars]
    }
    if {$extra ne ""} {
	set buttons [linsert $buttons 1 [uplevel 1 $extra]]
    }
    grid {*}$buttons -padx 4 -pady 4
    grid columnconfigure $w 0 -weight 1
    return $w
}

# positionWindow --
# This procedure is invoked by most of the demos to position a new demo
# window.
#
# Arguments:
# w -		The name of the window to position.

proc positionWindow w {
    wm geometry $w +300+300
}

# showVars --
# Displays the values of one or more variables in a window, and updates the
# display whenever any of the variables changes.
#
# Arguments:
# w -		Name of new window to create for display.
# args -	Any number of names of variables.

proc showVars {w args} {
    catch {destroy $w}
    toplevel $w
    wm title $w [mc "Variable values"]

    set f [ttk::labelframe $w.title -text [mc "Variable values:"]]
    foreach var $args {
	ttk::label $f.n$var -text "$var:" -anchor w
	ttk::label $f.v$var -textvariable $var -anchor w
	grid $f.n$var $f.v$var -padx 2 -pady 2 -sticky w
    }
    ttk::button $w.ok -width 8 -text [mc "OK"] \
	-command [list destroy $w] -default active
    bind $w <Return> [list $w.ok invoke]
    bind $w <Escape> [list $w.ok invoke]

    grid $f -sticky news -padx 4
    grid $w.ok -sticky e -padx 4 -pady {6 4}
    grid columnconfig $f 1 -weight 1
    grid rowconfigure $f 100 -weight 1
    grid columnconfig $w 0 -weight 1
    grid rowconfigure $w 0 -weight 1
}

# invoke --
# This procedure is called when the user clicks on a demo description. It is
# responsible for invoking the demonstration.
#
# Arguments:
# index -	The index of the character that the user clicked on.

proc invoke index {
    global tk_demoDirectory
    set tags [.t tag names $index]
    set i [lsearch -glob $tags demo-*]
    if {$i < 0} {
	return
    }
    set cursor [.t cget -cursor]
    .t configure -cursor watch
    update
    set demo [string range [lindex $tags $i] 5 end]
    uplevel [list source [file join $tk_demoDirectory $demo.tcl]]
    update
    .t configure -cursor $cursor

    .t tag add visited "$index linestart +1 chars" "$index lineend -1 chars"
}

# showStatus --
#
#	Show the name of the demo program in the status bar. This procedure is
#	called when the user moves the cursor over a demo description.
#
proc showStatus index {
    set tags [.t tag names $index]
    set i [lsearch -glob $tags demo-*]
    set cursor [.t cget -cursor]
    if {$i < 0} {
	.statusBar.lab config -text " "
	set newcursor xterm
    } else {
	set demo [string range [lindex $tags $i] 5 end]
	.statusBar.lab config -text [mc "Run the \"%s\" sample program" $demo]
	set newcursor hand2
    }
    if {$cursor ne $newcursor} {
	.t config -cursor $newcursor
    }
}

# evalShowCode --
#
# Arguments:
# w -		Name of text widget containing code to eval

proc evalShowCode {w} {
    set code [$w get 1.0 end-1c]
    uplevel #0 $code
}

# showCode --
# This procedure creates a toplevel window that displays the code for a
# demonstration and allows it to be edited and reinvoked.
#
# Arguments:
# w -		The name of the demonstration's window, which can be used to
#		derive the name of the file containing its code.

proc showCode w {
    global tk_demoDirectory
    set file [string range $w 1 end].tcl
    set top .code
    if {![winfo exists $top]} {
	toplevel $top

	set t [frame $top.f]
	set text [text $t.text -font fixedFont -height 30 -wrap word -bd 1 \
		      -xscrollcommand [list $t.xscroll set] \
		      -yscrollcommand [list $t.yscroll set] \
		      -setgrid 1 -highlightthickness 0 -pady 2 -padx 3]
	scrollbar $t.xscroll -command [list $t.text xview] \
	    -highlightthickness 0 -orient horizontal -bd 1
	scrollbar $t.yscroll -command [list $t.text yview] \
	    -highlightthickness 0 -orient vertical -bd 1

	grid $t.text $t.yscroll -sticky news
	#grid $t.xscroll
	grid rowconfigure $t 0 -weight 1
	grid columnconfig $t 0 -weight 1

	set btns [frame $top.btns]

	ttk::button $btns.dismiss -text [mc "Dismiss"] \
	    -default active -command [list destroy $top] \
	    -image ::img::delete -compound left
	ttk::button $btns.print   -text [mc "Print Code"] \
	    -command [list printCode $text $file] \
	    -image ::img::print -compound left
	ttk::button $btns.rerun   -text [mc "Rerun Demo"] \
	    -command [list evalShowCode $text] \
	    -image ::img::refresh -compound left

	grid x $btns.rerun $btns.print $btns.dismiss -padx 4 -pady {6 4}
	grid columnconfigure $btns 0 -weight 1

	grid $t    -sticky news
	grid $btns -sticky ew
	grid rowconfigure $top 0 -weight 1
	grid columnconfig $top 0 -weight 1

	bind $top <Return> {
	    if {[winfo class %W] ne "Text"} { .code.btns.dismiss invoke }
	}
	bind $top <Escape> [bind $top <Return>]
    } else {
	wm deiconify $top
	raise $top
    }
    wm title $top [mc "Demo code: %s" [file join $tk_demoDirectory $file]]
    wm iconname $top $file
    set id [open [file join $tk_demoDirectory $file]]
    $top.f.text delete 1.0 end
    $top.f.text insert 1.0 [read $id]
    $top.f.text mark set insert 1.0
    close $id
}

# printCode --
# Prints the source code currently displayed in the See Code dialog. Much
# thanks to Arjen Markus for this.
#
# Arguments:
# w -		Name of text widget containing code to print
# file -		Name of the original file (implicitly for title)

proc printCode {w file} {
    set code [$w get 1.0 end-1c]

    set dir "."
    if {[info exists ::env(HOME)]} {
	set dir "$::env(HOME)"
    }
    if {[info exists ::env(TMP)]} {
	set dir $::env(TMP)
    }
    if {[info exists ::env(TEMP)]} {
	set dir $::env(TEMP)
    }

    set filename [file join $dir "tkdemo-$file"]
    set outfile [open $filename "w"]
    puts $outfile $code
    close $outfile

    switch -- $::tcl_platform(platform) {
	unix {
	    if {[catch {exec lp -c $filename} msg]} {
		tk_messageBox -title "Print spooling failure" \
			-message "Print spooling probably failed: $msg"
	    }
	}
	windows {
	    if {[catch {PrintTextWin32 $filename} msg]} {
		tk_messageBox -title "Print spooling failure" \
			-message "Print spooling probably failed: $msg"
	    }
	}
	default {
	    tk_messageBox -title "Operation not Implemented" \
		    -message "Wow! Unknown platform: $::tcl_platform(platform)"
	}
    }

    #
    # Be careful to throw away the temporary file in a gentle manner ...
    #
    if {[file exists $filename]} {
	catch {file delete $filename}
    }
}

# PrintTextWin32 --
#    Print a file under Windows using all the "intelligence" necessary
#
# Arguments:
# filename -		Name of the file
#
# Note:
# Taken from the Wiki page by Keith Vetter, "Printing text files under
# Windows".
# Note:
# Do not execute the command in the background: that way we can dispose of the
# file smoothly.
#
proc PrintTextWin32 {filename} {
    package require registry
    set app [auto_execok notepad.exe]
    set pcmd "$app /p %1"
    catch {
	set app [registry get {HKEY_CLASSES_ROOT\.txt} {}]
	set pcmd [registry get \
		{HKEY_CLASSES_ROOT\\$app\\shell\\print\\command} {}]
    }

    regsub -all {%1} $pcmd $filename pcmd
    puts $pcmd

    regsub -all {\\} $pcmd {\\\\} pcmd
    set command "[auto_execok start] /min $pcmd"
    eval exec $command
}

# aboutBox --
#
#	Pops up a message box with an "about" message
#
proc aboutBox {} {
    tk_messageBox -icon info -type ok -title [mc "About Widget Demo"] \
	-message "[mc {Tk widget demonstration application}]

[mc {Copyright (c) %s} {1996-1997 Sun Microsystems, Inc.}]
[mc {Copyright (c) %s} {1997-2000 Ajuba Solutions, Inc.}]
[mc {Copyright (c) %s} {2001-2007 Donal K. Fellows}]"
}

# Local Variables:
# mode: tcl
# End: