-
Notifications
You must be signed in to change notification settings - Fork 2
/
tk.go
6260 lines (5860 loc) · 220 KB
/
tk.go
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
// Copyright 2024 The tk9.0-go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tk9_0 // import "modernc.org/tk9.0"
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"encoding/base64"
"errors"
"fmt"
"image/png"
"io/fs"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/mat/besticon/v3/ico"
"golang.org/x/net/html"
)
const (
// ThemeEnvVar, if non-blank and containing a valid built-in theme
// name, is used to set the default application theme. Calling
// StyleThemeUse() will override the default.
ThemeEnvVar = "TK9_THEME"
// ScaleEnvVar, if a valid (floating point) number, sets the TkScaling
// value at package initialization to NativeScaling*TK9_SCALE.
ScaleEnvVar = "TK9_SCALE"
gnuplotTimeout = time.Minute //TODO do not let the UI freeze
goarch = runtime.GOARCH
goos = runtime.GOOS
libVersion = "tk9.0.0"
tcl_eval_direct = 0x40000
tcl_ok = 0
tcl_error = 1
tcl_return = 2
tcl_break = 3
tcl_continue = 4
disconnectButtonTooltip = "Disconnect the application"
exitButtonTooltip = "Quit the application"
)
// NativeScaling is the value returned by TKScaling in package initialization before it is possibly
// changed using the [ScaleEnvVar] value.
var NativeScaling float64
// App is the main/root application window.
var App = &Window{}
//TODO? ErrorMsg
// Error modes
const (
// Errors will panic with a stack trace.
PanicOnError = iota
// Errors will be recorded into the Error variable using errors.Join
CollectErrors
)
// ErrorMode selects the action taken on errors.
var ErrorMode int
// Error records errors when [CollectErrors] is true.
var Error error
var (
_ Opt = (*MenuItem)(nil)
_ Widget = (*Window)(nil)
//go:embed embed/gotk.png
icon []byte
//go:embed embed/tklib/tooltip/tooltip.tcl
tooltip []byte
autocenterDisabled bool
appWithdrawn bool
appIconified bool
appDeiconified bool
cleanupDirs []string
exitHandler Opt
finished atomic.Int32
forcedX = -1
forcedY = -1
handlers = map[int32]*eventHandler{}
id atomic.Int32
initialized bool
isBuilder = os.Getenv("MODERNC_BUILDER") != ""
isVNC = os.Getenv("TK9_VNC") == "1"
wmTitle string
// https://pdos.csail.mit.edu/archive/rover/RoverDoc/escape_shell_table.html
//
// The following characters are dissallowed or have special meanings in Tcl and
// so are escaped:
//
// &;`'"|*?~<>^()[]{}$\
badChars = [...]bool{
' ': true,
'"': true,
'$': true,
'&': true,
'(': true,
')': true,
'*': true,
';': true,
'<': true,
'>': true,
'?': true,
'[': true,
'\'': true,
'\\': true,
'\n': true,
'\r': true,
'\t': true,
']': true,
'^': true,
'`': true,
'{': true,
'|': true,
'}': true,
'~': true,
}
//TODO remove the associated tcl var on window destroy event both from the
//interp and this map.
textVariables = map[*Window]string{} // : tclName
variables = map[*Window]*VariableOpt{}
windowIndex = map[string]*Window{}
)
func commonLazyInit() {
eval(string(tooltip))
}
func checkSig(dir string, sig map[string]string) (r bool) {
if dmesgs {
dmesg("checkSig(%q, %q)", dir, sig)
}
if err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
base := filepath.Base(path)
sum := sig[base]
if sum == "" {
return nil
}
b, err := os.ReadFile(path)
if err != nil {
return err
}
if g, e := fmt.Sprintf("%0x", sha256.Sum256(b)), sum; g != e {
return fmt.Errorf("check failed: %s %s != %s", path, g, e)
}
delete(sig, base)
return nil
}); err != nil || len(sig) != 0 {
if dmesgs {
dmesg("checkSig(%q) failed: %v", dir, err)
}
return false
}
return true
}
// Returns a single Tcl string, no braces, except {} if returned for s == "".
func tclSafeString(s string) string {
if s == "" {
return "{}"
}
const badString = "&;`'\"|*?~<>^()[]{}$\\\n\r\t "
if strings.ContainsAny(s, badString) {
var b strings.Builder
for _, c := range s {
switch {
case int(c) < len(badChars) && badChars[c]:
fmt.Fprintf(&b, "\\x%02x", c)
default:
b.WriteRune(c)
}
}
s = b.String()
}
return s
}
// Same as tclSafeStrings but does not escape <>.
func tclSafeStringBind(s string) string {
if s == "" {
return "{}"
}
const badString = "&;`'\"|*?~^()[]{}$\\\n\r\t "
if strings.ContainsAny(s, badString) {
var b strings.Builder
for _, c := range s {
switch {
case int(c) < len(badChars) && badChars[c]:
fmt.Fprintf(&b, "\\x%02x", c)
default:
b.WriteRune(c)
}
}
s = b.String()
}
return s
}
// Returns a space separated list of safe Tcl strings.
func tclSafeList(list ...any) string {
var a []string
for _, v := range list {
a = append(a, tclSafeString(fmt.Sprint(v)))
}
return strings.Join(a, " ")
}
// Returns a space separated list of safe Tcl strings.
func tclSafeStrings(s ...string) string {
var a []string
for _, v := range s {
a = append(a, tclSafeString(v))
}
return strings.Join(a, " ")
}
// Returns a Tcl string that is safe inside {...}
func tclSafeInBraces(s string) string {
const badString = "}\\\n\r\t "
if strings.ContainsAny(s, badString) {
var b strings.Builder
for _, c := range s {
switch {
case int(c) < len(badMLChars) && badMLChars[c]:
fmt.Fprintf(&b, "\\x%02x", c)
default:
b.WriteRune(c)
}
}
s = b.String()
}
return s
}
func setDefaults() {
windowIndex[""] = App
windowIndex["."] = App
if goos == "windows" {
wmWithdraw(App)
}
exitHandler = Command(func() {
Destroy(App)
for _, v := range Themes {
v.Deactivate(nil)
v.Finalize(nil)
}
})
evalErr("option add *tearOff 0") // https://tkdocs.com/tutorial/menus.html
NativeScaling = TkScaling()
if s := os.Getenv(ScaleEnvVar); s != "" {
if k, err := strconv.ParseFloat(s, 64); err == nil {
TkScaling(min(max(k, 0.5), 5) * NativeScaling)
}
}
if nm := os.Getenv(ThemeEnvVar); nm != "" {
StyleThemeUse(nm)
}
App.IconPhoto(NewPhoto(Data(icon)))
wmTitle = filepath.Base(os.Args[0])
wmTitle = strings.TrimSuffix(wmTitle, ".exe")
App.WmTitle(wmTitle)
x, y := -1, -1
if os.Getenv("TK9_DEMO") == "1" {
for i := 1; i < len(os.Args); i++ {
s := os.Args[i]
if !strings.HasPrefix(s, "+") {
continue
}
a := strings.Split(s[1:], "+")
if len(a) != 2 {
continue
}
var err error
if x, err = strconv.Atoi(a[0]); err != nil || x < 0 {
x = -1
break
}
if y, err = strconv.Atoi(a[1]); err != nil || y < 0 {
y = -1
}
break
}
}
App.Configure(Padx("4m"), Pady("3m"))
if x >= 0 && y >= 0 {
forcedX, forcedY = x, y
}
}
// Window represents a Tk window/widget. It implements common widget methods.
//
// Window implements Opt. When a Window instance is used as an Opt, it provides
// its path name.
type Window struct {
fpath string
}
func (w *Window) isWidget() {}
// Widget is implemented by every *Window
//
// Widget implements Opt. When a Widget instance is used as an Opt, it provides
// its path name.
type Widget interface {
isWidget()
optionString(*Window) string
}
// String implements fmt.Stringer.
func (w *Window) String() (r string) {
if r = w.fpath; r == "" {
r = "."
}
return r
}
func (w *Window) optionString(_ *Window) string {
return w.String()
}
func (w *Window) split(options []Opt) (opts []Opt, tvs []textVarOpt, vs []*VariableOpt) {
for _, v := range options {
switch x := v.(type) {
case textVarOpt:
tvs = append(tvs, x)
case *VariableOpt:
vs = append(vs, x)
default:
opts = append(opts, x)
}
}
return opts, tvs, vs
}
func (w *Window) newChild0(nm string) (rw *Window) {
rw = &Window{fpath: fmt.Sprintf("%s.%s%v", w, nm, id.Add(1))}
windowIndex[rw.fpath] = rw
return rw
}
func (w *Window) newChild(nm string, options ...Opt) (rw *Window) {
class := strings.Replace(nm, "ttk_", "ttk::", 1)
nm = strings.Replace(nm, "ttk::", "t", 1)
if c := nm[len(nm)-1]; c >= '0' && c <= '9' {
nm += "_"
}
path := fmt.Sprintf("%s.%s%v", w, nm, id.Add(1))
options, tvs, vs := w.split(options)
rw = &Window{}
code := fmt.Sprintf("%s %s %s", class, path, winCollect(rw, options...))
var err error
if rw.fpath, err = eval(code); err != nil {
fail(fmt.Errorf("code=%s -> r=%s err=%v", code, rw.fpath, err))
}
if len(tvs) != 0 {
rw.Configure(tvs[len(tvs)-1])
}
if len(vs) != 0 {
rw.Configure(vs[len(vs)-1])
}
windowIndex[rw.fpath] = rw
return rw
}
func evalErr(code string) (r string) {
r, err := eval(code)
if err != nil {
fail(fmt.Errorf("code=%s -> r=%s err=%v", code, r, err))
}
return r
}
func fail(err error) {
switch ErrorMode {
default:
fallthrough
case PanicOnError:
if dmesgs {
dmesg("PANIC %v", err)
}
panic(err)
case CollectErrors:
Error = errors.Join(Error, err)
}
}
func winCollect(w *Window, options ...Opt) string {
var a []string
for _, v := range options {
a = append(a, v.optionString(w))
}
return strings.Join(a, " ")
}
func collectAny(options ...any) string {
var a []string
for _, v := range options {
switch x := v.(type) {
case Opt:
a = append(a, x.optionString(nil))
default:
a = append(a, tclSafeString(fmt.Sprint(x)))
}
}
return strings.Join(a, " ")
}
func collect(options ...Opt) string {
var a []string
for _, v := range options {
a = append(a, v.optionString(nil))
}
return strings.Join(a, " ")
}
// Opts is a list of options. It implements Opt.
type Opts []Opt
func (o Opts) optionString(w *Window) string {
return winCollect(w, []Opt(o)...)
}
// Opt represents an optional argument.
type Opt interface {
optionString(w *Window) string
}
type rawOption string
func (s rawOption) optionString(w *Window) string {
return string(s)
}
type stringOption string
func (s stringOption) optionString(w *Window) string {
return tclSafeString(string(s))
}
// EventHandler is the type used by call backs.
type EventHandler func(*Event)
// Event communicates information with an event handler. All handlers can use the Err field. Simple
// handlers, like in
//
// Button(..., Command(func(e *Event) {...}))
//
// can use the 'W' field, if applicable. All other fields are valid only in
// handlers bound using [Bind].
type Event struct {
// Event handlers should set Err on failure.
Err error
// Result can be optionally set by the handler. The field is returned by
// certain methods, for example [TCheckbuttonWidget.Invoke].
Result string
// Event source, if any. This field is set when the event handler was
// created.
W *Window
returnCode int // One of tcl_ok .. tcl_continue
// The window to which the event was reported (the window field from
// the event). Valid for all event types. This field is set when the
// event is handled.
EventWindow *Window
// The keysym corresponding to the event, substituted as a textual string.
// Valid only for Key and KeyRelease events.
Keysym string
// The number of the last client request processed by the server (the serial
// field from the event). Valid for all event types.
Serial int64
args []string
}
// Called from eventDispatcher. Arg1 is handler id, optionally followed by a
// list of Bind substitution values.
func newEvent(arg1 string) (id int, e *Event, err error) {
e = &Event{returnCode: tcl_ok}
a := strings.Fields(arg1)
if len(a) == 0 {
return -1, e, fmt.Errorf("internal error: missing handler ID")
}
if id, err = strconv.Atoi(a[0]); err != nil {
return id, e, fmt.Errorf("newEvent: parsing event ID %q: %v", a[0], err)
}
for i, v := range a[1:] {
switch i {
case 0: // %#
if e.Serial, err = strconv.ParseInt(v, 10, 64); err != nil {
return id, e, fmt.Errorf("newEvent: parsing event serial %q: %v", v, err)
}
case 1: // %W
e.EventWindow = windowIndex[v]
case 2: // %K
e.Keysym = v
}
}
return id, e, nil
}
// SetReturnCodeOK sets return code of 'e' to TCL_OK.
func (e *Event) SetReturnCodeOK() {
e.returnCode = tcl_ok
}
// SetReturnCodeError sets return code of 'e' to TCL_ERROR.
func (e *Event) SetReturnCodeError() {
e.returnCode = tcl_error
}
// SetReturnCodeReturn sets return code of 'e' to TCL_RETURN.
func (e *Event) SetReturnCodeReturn() {
e.returnCode = tcl_return
}
// SetReturnCodeBreak sets return code of 'e' to TCL_BREAK.
func (e *Event) SetReturnCodeBreak() {
e.returnCode = tcl_break
}
// SetReturnCodeContinue sets return code of 'e' to TCL_CONTINUE.
func (e *Event) SetReturnCodeContinue() {
e.returnCode = tcl_continue
}
// ScrollSet communicates events to scrollbars. Example:
//
// var scroll *TScrollbarWidget
// // tcl: text .text -yscrollcommand ".scroll set"
// t := Text(..., Yscrollcommand(func(e *Event) { e.ScrollSet(scroll) }))
func (e *Event) ScrollSet(w Widget) {
if len(e.args) > 1 {
evalErr(fmt.Sprintf("%s set %s %s", w, e.args[0], e.args[1]))
}
}
// Xview communicates events to views. Example:
//
// var scroll *TScrollbarWidget
// t := Text(...)
// // tcl: ttk::scrollbar .scroll -command ".text xview"
// scroll = TScrollbar(Command(func(e *Event) { e.Xview(t)}))
func (e *Event) Xview(w Widget) {
if len(e.args) > 1 {
evalErr(fmt.Sprintf("%s xview %s", w, strings.Join(e.args, " ")))
}
}
// Yview communicates events to views. Example:
//
// var scroll *TScrollbarWidget
// t := Text(...)
// // tcl: ttk::scrollbar .scroll -command ".text yview"
// scroll = TScrollbar(Command(func(e *Event) { e.Yview(t)}))
func (e *Event) Yview(w Widget) {
if len(e.args) > 1 {
evalErr(fmt.Sprintf("%s yview %s", w, strings.Join(e.args, " ")))
}
}
type eventHandler struct {
callback func(*Event)
id int32
tcl string
w *Window
lateBind bool
}
func newEventHandler(option string, handler any) (r *eventHandler) {
var callback func(*Event)
switch x := handler.(type) {
case EventHandler:
callback = x
case func(*Event):
callback = x
case func():
callback = func(*Event) { x() }
default:
fail(fmt.Errorf("registering event handler: unsupported handler type: %T", handler))
return nil
}
r = &eventHandler{
callback: callback,
id: id.Add(1),
tcl: option,
}
handlers[r.id] = r
return r
}
func (e *eventHandler) optionString(w *Window) string {
if e == nil {
return ""
}
e.w = w
switch {
case e.lateBind:
return fmt.Sprintf("%s {eventDispatcher {%v %%# %%W %%K}}", e.tcl, e.id)
default:
return fmt.Sprintf("%s {eventDispatcher %v}", e.tcl, e.id)
}
}
func optionString(v any) string {
switch x := v.(type) {
case time.Duration:
return fmt.Sprint(int64((x + time.Millisecond/2) / time.Millisecond))
case []byte:
return base64.StdEncoding.EncodeToString(x)
case []FileType:
var a []string
for _, v := range x {
a = append(a, fmt.Sprintf("{%s {%s} %s}", tclSafeString(v.TypeName), tclSafeStrings(v.Extensions...), v.MacType))
}
return fmt.Sprintf("{%s}", strings.Join(a, " "))
default:
return tclSafeString(fmt.Sprint(v))
}
}
// bind — Arrange for X events to invoke functions
//
// # Description
//
// Bind tag options...
//
// The bind command associates commands with X events. If all three
// arguments are specified, bind will arrange for script (a Tcl script called
// the “binding script”) to be evaluated whenever the event(s) given by
// sequence occur in the window(s) identified by tag. If script is prefixed
// with a “+”, then it is appended to any existing binding for sequence;
// otherwise script replaces any existing binding. If script is an empty string
// then the current binding for sequence is destroyed, leaving sequence
// unbound. In all of the cases where a script argument is provided, bind
// returns an empty string.
//
// If sequence is specified without a script, then the script currently bound
// to sequence is returned, or an empty string is returned if there is no
// binding for sequence. If neither sequence nor script is specified, then the
// return value is a list whose elements are all the sequences for which there
// exist bindings for tag.
//
// The tag argument determines which window(s) the binding applies to. If tag
// begins with a dot, as in .a.b.c, then it must be the path name for a window;
// otherwise it may be an arbitrary string. Each window has an associated list
// of tags, and a binding applies to a particular window if its tag is among
// those specified for the window. Although the bindtags command may be used to
// assign an arbitrary set of binding tags to a window, the default binding
// tags provide the following behavior:
//
// - If a tag is the name of an internal window the binding applies to that
// window.
// - If the tag is the name of a class of widgets, such as Button, the
// binding applies to all widgets in that class.
// - If the tag is the name of a toplevel window the binding applies to the
// toplevel window and all its internal windows.
// - If tag has the value all, the binding applies to all windows in the
// application.
//
// Example usage in _examples/events.go.
//
// Additional information might be available at the [Tcl/Tk bind] page.
//
// [Tcl/Tk bind]: https://www.tcl.tk/man/tcl9.0/TkCmd/bind.html
func Bind(options ...any) {
a := []string{"bind"}
var w *Window
for _, v := range options {
switch x := v.(type) {
case *Window:
if w == nil {
w = x
}
a = append(a, x.String())
case *eventHandler:
x.tcl = ""
x.lateBind = true
a = append(a, x.optionString(w))
default:
a = append(a, tclSafeStringBind(fmt.Sprint(x)))
}
}
evalErr(strings.Join(a, " "))
}
// Img represents a Tk image.
type Img struct {
name string
}
// image — Create and manipulate images
//
// # Description
//
// Deletes 'm!. If there are
// instances of the image displayed in widgets, the image will not actually
// be deleted until all of the instances are released. However, the association
// between the instances and the image manager will be dropped. Existing
// instances will retain their sizes but redisplay as empty areas. If a deleted
// image is recreated with another call to image create, the existing instances
// will use the new image.
func (m *Img) Delete() {
evalErr(fmt.Sprintf("image delete %s", m))
}
// String implements fmt.Stringer.
func (m *Img) String() string {
return m.optionString(nil)
}
func (m *Img) optionString(_ *Window) string {
if m != nil {
return m.name
}
return "img0" // does not exist
}
// Bitmap — Images that display two colors
//
// # Description
//
// A bitmap is an image whose pixels can display either of two colors or be
// transparent. A bitmap image is defined by four things: a background color, a
// foreground color, and two bitmaps, called the source and the mask. Each of
// the bitmaps specifies 0/1 values for a rectangular array of pixels, and the
// two bitmaps must have the same dimensions. For pixels where the mask is
// zero, the image displays nothing, producing a transparent effect. For other
// pixels, the image displays the foreground color if the source data is one
// and the background color if the source data is zero.
//
// Additional information might be available at the [Tcl/Tk bitmap] page.
//
// - [Background] color
//
// Specifies a background color for the image in any of the standard ways
// accepted by Tk. If this option is set to an empty string then the background
// pixels will be transparent. This effect is achieved by using the source
// bitmap as the mask bitmap, ignoring any -maskdata or -maskfile options.
//
// - [Data] string
//
// Specifies the contents of the source bitmap as a string. The string must
// adhere to X11 bitmap format (e.g., as generated by the bitmap program). If
// both the -data and -file options are specified, the -data option takes
// precedence.
//
// - [File] name
//
// name gives the name of a file whose contents define the source bitmap. The
// file must adhere to X11 bitmap format (e.g., as generated by the bitmap
// program).
//
// - [Foreground] color
//
// Specifies a foreground color for the image in any of the standard ways
// accepted by Tk.
//
// - [Maskdata] string
//
// Specifies the contents of the mask as a string. The string must adhere to
// X11 bitmap format (e.g., as generated by the bitmap program). If both the
// -maskdata and -maskfile options are specified, the -maskdata option takes
// precedence.
//
// - [Maskfile] name
//
// name gives the name of a file whose contents define the mask. The file must
// adhere to X11 bitmap format (e.g., as generated by the bitmap program).
//
// [Tcl/Tk bitmap]: https://www.tcl.tk/man/tcl9.0/TkCmd/bitmap.html
func NewBitmap(options ...Opt) *Img {
nm := fmt.Sprintf("bmp%v", id.Add(1))
code := fmt.Sprintf("image create bitmap %s %s", nm, collect(options...))
r, err := eval(code)
if err != nil {
fail(fmt.Errorf("code=%s -> r=%s err=%v", code, r, err))
return nil
}
return &Img{name: nm}
}
// Photo — Full-color images
//
// A photo is an image whose pixels can display any color with a varying degree
// of transparency (the alpha channel). A photo image is stored internally in
// full color (32 bits per pixel), and is displayed using dithering if
// necessary. Image data for a photo image can be obtained from a file or a
// string, or it can be supplied from C code through a procedural interface. At
// present, only PNG, GIF, PPM/PGM, and (read-only) SVG formats are supported,
// but an interface exists to allow additional image file formats to be added
// easily. A photo image is (semi)transparent if the image data it was obtained
// from had transparency information. In regions where no image data has been
// supplied, it is fully transparent. Transparency may also be modified with
// the transparency set subcommand.
//
// - [Data] string
//
// Specifies the contents of the image as a string. The string should contain
// binary data or, for some formats, base64-encoded data (this is currently
// guaranteed to be supported for PNG and GIF images). The format of the string
// must be one of those for which there is an image file format handler that
// will accept string data. If both the -data and -file options are specified,
// the -file option takes precedence.
//
// - [Format] format-name
//
// Specifies the name of the file format for the data specified with the -data
// or -file option.
//
// - [File] name
//
// name gives the name of a file that is to be read to supply data for the
// photo image. The file format must be one of those for which there is an
// image file format handler that can read data.
//
// - [Gamma] value
//
// Specifies that the colors allocated for displaying this image in a window
// should be corrected for a non-linear display with the specified gamma
// exponent value. (The intensity produced by most CRT displays is a power
// function of the input value, to a good approximation; gamma is the exponent
// and is typically around 2). The value specified must be greater than zero.
// The default value is one (no correction). In general, values greater than
// one will make the image lighter, and values less than one will make it
// darker.
//
// - [Height] number
//
// Specifies the height of the image, in pixels. This option is useful
// primarily in situations where the user wishes to build up the contents of
// the image piece by piece. A value of zero (the default) allows the image to
// expand or shrink vertically to fit the data stored in it.
//
// - [Palette] palette-spec
//
// Specifies the resolution of the color cube to be allocated for displaying
// this image, and thus the number of colors used from the colormaps of the
// windows where it is displayed. The palette-spec string may be either a
// single decimal number, specifying the number of shades of gray to use, or
// three decimal numbers separated by slashes (/), specifying the number of
// shades of red, green and blue to use, respectively. If the first form (a
// single number) is used, the image will be displayed in monochrome (i.e.,
// grayscale).
//
// - [Width] number
//
// Specifies the width of the image, in pixels. This option is useful primarily
// in situations where the user wishes to build up the contents of the image
// piece by piece. A value of zero (the default) allows the image to expand or
// shrink horizontally to fit the data stored in it.
//
// Additional information might be available at the [Tcl/Tk photo] page.
//
// [Tcl/Tk photo]: https://www.tcl.tk/man/tcl9.0/TkCmd/photo.html
func NewPhoto(options ...Opt) *Img {
nm := fmt.Sprintf("img%v", id.Add(1))
code := fmt.Sprintf("image create photo %s %s", nm, collect(options...))
r, err := eval(code)
if err != nil {
fail(fmt.Errorf("code=%s -> r=%s err=%v", code, r, err))
return nil
}
return &Img{name: nm}
}
// Width — Get the configured option value.
//
// Additional information might be available at the [Tcl/Tk photo] page.
//
// [Tcl/Tk photo]: https://www.tcl.tk/man/tcl9.0/TkCmd/photo.html
func (m *Img) Width() string {
return evalErr(fmt.Sprintf(`image width %s`, m))
}
// Height — Get the configured option value.
//
// Additional information might be available at the [Tcl/Tk photo] page.
//
// [Tcl/Tk photo]: https://www.tcl.tk/man/tcl9.0/TkCmd/photo.html
func (m *Img) Height() string {
return evalErr(fmt.Sprintf(`image height %s`, m))
}
// // Returns photo data.
// //
// // Additional information might be available at the [Tcl/Tk photo] page.
// //
// // [Tcl/Tk photo]: https://www.tcl.tk/man/tcl9.0/TkCmd/photo.html
// func (m *Img) Data(options ...Opt) []byte {
// s := evalErr(fmt.Sprintf("%s data %s", collect(options...)))
// panic(todo("%q", s))
// }
// photo — Full-color images
//
// Copies a region from the image called sourceImage (which must be a photo
// image) to the image called imageName, possibly with pixel zooming and/or
// subsampling. If no options are specified, this command copies the whole of
// sourceImage into imageName, starting at coordinates (0,0) in imageName.
//
// The following options may be specified:
//
// - [From] x1 y1 x2 y2
//
// Specifies a rectangular sub-region of the source image to be copied. (x1,y1)
// and (x2,y2) specify diagonally opposite corners of the rectangle. If x2 and
// y2 are not specified, the default value is the bottom-right corner of the
// source image. The pixels copied will include the left and top edges of the
// specified rectangle but not the bottom or right edges. If the -from option
// is not given, the default is the whole source image.
//
// - [To] x1 y1 x2 y2
//
// Specifies a rectangular sub-region of the destination image to be affected.
// (x1,y1) and (x2,y2) specify diagonally opposite corners of the rectangle. If
// x2 and y2 are not specified, the default value is (x1,y1) plus the size of
// the source region (after subsampling and zooming, if specified). If x2 and
// y2 are specified, the source region will be replicated if necessary to fill
// the destination region in a tiled fashion.
//
// The function returns 'm'.
//
// Additional information might be available at the [Tcl/Tk photo] page.
//
// [Tcl/Tk photo]: https://www.tcl.tk/man/tcl9.0/TkCmd/photo.html
func (m *Img) Copy(src *Img, options ...Opt) (r *Img) {
evalErr(fmt.Sprintf("%s copy %s %s", m, src, collect(options...)))
return m
}
// From option.
//
// Known uses:
// - [Img.Copy]
// - [Scale] (widget specific)
// - [Spinbox] (widget specific)
// - [TScale] (widget specific)
// - [TSpinbox] (widget specific)
func From(val ...any) Opt {
return rawOption(fmt.Sprintf(`-from %s`, collectAny(val...)))
}
// To option.
//
// Known uses:
// - [Img.Copy]
// - [Scale] (widget specific)
// - [Spinbox] (widget specific)
// - [TScale] (widget specific)
// - [TSpinbox] (widget specific)
func To(val ...any) Opt {
return rawOption(fmt.Sprintf(`-to %s`, collectAny(val...)))
}