/
imgrid.go
1288 lines (1174 loc) · 35.2 KB
/
imgrid.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 (c) 2020, The gide / GoKi 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 imgrid
import (
"fmt"
"image"
"sort"
"github.com/goki/gi/gi"
"github.com/goki/gi/gist"
"github.com/goki/gi/oswin"
"github.com/goki/gi/oswin/dnd"
"github.com/goki/gi/oswin/key"
"github.com/goki/gi/oswin/mimedata"
"github.com/goki/gi/oswin/mouse"
"github.com/goki/gi/units"
"github.com/goki/ki/ints"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/ki/sliceclone"
"github.com/goki/mat32"
"github.com/goki/pi/filecat"
)
// ImgGrid shows a list of images in a grid.
// The outer layout contains the inner grid and a scrollbar
type ImgGrid struct {
gi.Frame
// maximum size for images -- geom set to square of this size
ImageMax float32 `desc:"maximum size for images -- geom set to square of this size"`
// list of image files to display
Images []string `desc:"list of image files to display"`
// function for displaying context menu for item at given index -- if not set then a basic standard one is used
CtxtMenuFunc func(m *gi.Menu, idx int) `desc:"function for displaying context menu for item at given index -- if not set then a basic standard one is used"`
// if true, drag-n-drop and paste actions actually result in insertion -- otherwise they just drive signals to be managed externally
InsertOk bool `desc:"if true, drag-n-drop and paste actions actually result in insertion -- otherwise they just drive signals to be managed externally"`
// last selected item
SelectedIdx int `desc:"last selected item"`
// editing-mode select rows mode
SelectMode bool `copy:"-" desc:"editing-mode select rows mode"`
// list of currently-selected file indexes
SelectedIdxs map[int]struct{} `copy:"-" desc:"list of currently-selected file indexes"`
// list of currently-dragged indexes
DraggedIdxs []int `copy:"-" desc:"list of currently-dragged indexes"`
// signal for image events -- selection events occur via WidgetSig
ImageSig ki.Signal `copy:"-" json:"-" xml:"-" desc:"signal for image events -- selection events occur via WidgetSig"`
// number of columns and rows to display -- computed from avail room
Size image.Point `desc:"number of columns and rows to display -- computed from avail room"`
// current copy / paste idx
CurIdx int `copy:"-" json:"-" xml:"-" desc:"current copy / paste idx"`
}
var KiT_ImgGrid = kit.Types.AddType(&ImgGrid{}, ImgGridProps)
// AddNewImgGrid adds a new imggrid to given parent node, with given name.
func AddNewImgGrid(parent ki.Ki, name string) *ImgGrid {
return parent.AddNewChild(KiT_ImgGrid, name).(*ImgGrid)
}
// SetImages sets the current image files to view (makes a copy of slice),
// and does a config rebuild. If reset, then reset selections, else not
func (ig *ImgGrid) SetImages(files []string, reset bool) {
ig.Images = sliceclone.String(files)
ig.Config(reset)
}
func (ig *ImgGrid) NumImages() int {
return len(ig.Images)
}
// Config configures the grid
func (ig *ImgGrid) Config(reset bool) {
updt := ig.UpdateStart()
defer ig.UpdateEnd(updt)
ig.SetFullReRender()
ig.SetCanFocus()
if reset {
ig.ResetSelectedIdxs()
ig.SelectedIdx = 0
}
if !ig.HasChildren() {
ig.Lay = gi.LayoutHoriz
gi.AddNewLayout(ig, "grid", gi.LayoutGrid)
sbb := gi.AddNewScrollBar(ig, "sb")
sbb.Defaults()
sbb.SliderSig.Connect(ig.This(), func(recv, send ki.Ki, sig int64, data any) {
igg := recv.(*ImgGrid)
if sig == int64(gi.SliderValueChanged) {
igg.Update()
}
})
}
gr := ig.Grid()
sb := ig.ScrollBar()
if ig.Size.X == 0 {
ig.Size.X = 4
ig.Size.Y = 4
}
if ig.ImageMax == 0 {
ig.ImageMax = 200
}
gr.SetProp("columns", ig.Size.X)
gr.Lay = gi.LayoutGrid
gr.SetStretchMax()
gr.SetProp("spacing", gi.StdDialogVSpaceUnits)
ng := ig.Size.X * ig.Size.Y
if ng != gr.NumChildren() {
gr.SetNChildren(ng, gi.KiT_Bitmap, "b_")
}
sb.Min = 0
sb.Tracking = true
sb.Dim = mat32.Y
if reset {
sb.Value = 0
}
sb.SetFixedWidth(units.NewPx(gist.ScrollBarWidthDefault))
sb.SetStretchMaxHeight()
ig.SetScrollMax()
ig.Update()
}
func (ig *ImgGrid) SetScrollMax() int {
sb := ig.ScrollBar()
nf := ig.NumImages()
nr := int(mat32.Ceil(float32(nf)/float32(ig.Size.X))) + 1
nr = ints.MaxInt(nr, ig.Size.Y)
sb.Max = float32(nr)
sb.ThumbVal = float32(ig.Size.Y)
sb.Value = mat32.Min(sb.Max-1, sb.Value)
return nr
}
// Grid returns the actual grid layout
func (ig *ImgGrid) Grid() *gi.Layout {
return ig.Child(0).(*gi.Layout)
}
// ScrollBar returns the scrollbar
func (ig *ImgGrid) ScrollBar() *gi.ScrollBar {
return ig.Child(1).(*gi.ScrollBar)
}
// BitmapAtIdx returns the gi.Bitmap at given index
func (ig *ImgGrid) BitmapAtIdx(idx int) *gi.Bitmap {
si := ig.StartIdx()
idx = idx - si
ni := ig.Size.X * ig.Size.Y
if idx < 0 || idx >= ni {
return nil
}
gr := ig.Grid()
return gr.Child(idx).(*gi.Bitmap)
}
// ImageDeleteAt deletes image at given index
func (ig *ImgGrid) ImageDeleteAt(idx int) {
// img := ig.Images[idx]
if idx < len(ig.Images) {
ig.Images = append(ig.Images[:idx], ig.Images[idx+1:]...)
ig.ImageSig.Emit(ig.This(), int64(ImgGridDeleted), idx)
}
}
// ImageInsertAt inserts image(s) at given index
func (ig *ImgGrid) ImageInsertAt(idx int, files []string) {
ni := len(files)
nt := append(ig.Images, files...) // first append to end
copy(nt[idx+ni:], nt[idx:]) // move stuff to end
copy(nt[idx:], files) // copy into position
ig.Images = nt
ig.ImageSig.Emit(ig.This(), int64(ImgGridInserted), idx)
}
// ImgGridSignals are signals that sliceview can send, mostly for editing
// mode. Selection events are sent on WidgetSig WidgetSelected signals in
// both modes.
type ImgGridSignals int
const (
// ImgGridDoubleClicked emitted during inactive mode when item
// double-clicked -- can be used for accepting dialog.
ImgGridDoubleClicked ImgGridSignals = iota
// ImgGridInserted emitted when a new item is inserted -- data is index of new item
ImgGridInserted
// ImgGridDeleted emitted when an item is deleted -- data is index of item deleted
ImgGridDeleted
ImgGridSignalsN
)
//go:generate stringer -type=ImgGridSignals
// LayoutGrid updates the grid size based on allocated size
// if returns true, then needs a new iteration
func (ig *ImgGrid) LayoutGrid(iter int) bool {
if iter > 0 {
return false
}
sb := ig.ScrollBar()
gr := ig.Grid()
alc := ig.LayState.Alloc.Size.ToPoint()
if alc.X == 0 || alc.Y == 0 {
return false
}
alc.X -= int(sb.Sty.Layout.Width.Dots)
gsz := alc.Div(int(ig.ImageMax))
gsz.X = ints.MaxInt(2, gsz.X)
gsz.Y = ints.MaxInt(2, gsz.Y)
if ig.Size == gsz {
return false
}
ig.Size = gsz
gr.SetProp("columns", ig.Size.X)
ig.SetScrollMax()
ig.Update()
return true
}
func (ig *ImgGrid) Layout2D(parBBox image.Rectangle, iter int) bool {
redo := ig.LayoutGrid(iter)
ig.Frame.Layout2D(parBBox, iter)
return redo
}
// Update updates the display for current scrollbar position, rendering the images
func (ig *ImgGrid) Update() {
updt := ig.UpdateStart()
defer ig.UpdateEnd(updt)
gr := ig.Grid()
nf := ig.NumImages()
ig.SetScrollMax()
ng := ig.Size.X * ig.Size.Y
if ng != gr.NumChildren() {
gr.SetNChildren(ng, gi.KiT_Bitmap, "b_")
}
bimg := image.NewNRGBA(image.Rect(0, 0, 50, 50))
si := ig.StartIdx()
idx := si
bi := 0
for y := 0; y < ig.Size.Y; y++ {
for x := 0; x < ig.Size.X; x++ {
bm := gr.Child(bi).(*gi.Bitmap)
if idx < nf {
f := ig.Images[idx]
if f != "" {
bm.OpenImage(gi.FileName(f), 0, 0)
} else {
bm.SetImage(bimg, 0, 0)
}
} else {
bm.SetImage(bimg, 0, 0)
}
bm.SetProp("width", units.NewValue(float32(ig.ImageMax), units.Dot))
bm.SetProp("height", units.NewValue(float32(ig.ImageMax), units.Dot))
bi++
idx++
}
}
}
func (ig *ImgGrid) RenderSelected() {
gr := ig.Grid()
st := &ig.Sty
rs := &ig.Viewport.Render
pc := &rs.Paint
rs.Lock()
pc.StrokeStyle.SetColor(&st.Border.Color)
pc.StrokeStyle.Width = st.Border.Width
pc.FillStyle.SetColor(nil)
wd := pc.StrokeStyle.Width.Dots
si := ig.StartIdx()
idx := si
bi := 0
for y := 0; y < ig.Size.Y; y++ {
for x := 0; x < ig.Size.X; x++ {
bm := gr.Child(bi).(*gi.Bitmap)
if _, sel := ig.SelectedIdxs[idx]; sel {
pos := bm.LayState.Alloc.Pos.SubScalar(wd)
sz := bm.LayState.Alloc.Size.AddScalar(2.0 * wd)
// fmt.Printf("sel: %d wd: %v pos: %v sz: %v\n", idx, wd, pos, sz)
pc.DrawRectangle(rs, pos.X, pos.Y, sz.X, sz.Y)
pc.FillStrokeClear(rs)
}
bi++
idx++
}
}
rs.Unlock()
}
func (ig *ImgGrid) Render2D() {
if ig.FullReRenderIfNeeded() {
return
}
if ig.PushBounds() {
ig.FrameStdRender()
ig.RenderSelected()
ig.This().(gi.Node2D).ConnectEvents2D()
if ig.ScrollsOff {
ig.ManageOverflow()
}
ig.RenderScrolls()
ig.Render2DChildren()
ig.PopBounds()
} else {
ig.SetScrollsOff()
ig.DisconnectAllEvents(gi.AllPris) // uses both Low and Hi
}
}
func (ig *ImgGrid) ConnectEvents2D() {
ig.ImgGridEvents()
}
func (ig *ImgGrid) ImgGridEvents() {
gr := ig.Grid()
// LowPri to allow other focal widgets to capture
ig.ConnectEvent(oswin.MouseScrollEvent, gi.LowPri, func(recv, send ki.Ki, sig int64, d any) {
me := d.(*mouse.ScrollEvent)
igg := recv.Embed(KiT_ImgGrid).(*ImgGrid)
me.SetProcessed()
sbb := igg.ScrollBar()
cur := float32(sbb.Pos)
sbb.SliderMove(cur, cur+float32(me.NonZeroDelta(false))) // preferY
})
ig.ConnectEvent(oswin.MouseEvent, gi.LowRawPri, func(recv, send ki.Ki, sig int64, d any) {
me := d.(*mouse.Event)
igg := recv.Embed(KiT_ImgGrid).(*ImgGrid)
switch {
case me.Button == mouse.Left && me.Action == mouse.DoubleClick:
si := igg.SelectedIdx
igg.UnselectAllIdxs()
igg.SelectIdx(si)
igg.ImageSig.Emit(igg.This(), int64(ImgGridDoubleClicked), si)
me.SetProcessed()
case me.Button == mouse.Left && me.Action == mouse.Release:
idx, ok := igg.IdxFromPos(me.Pos())
if !ok {
return
}
me.SetProcessed()
igg.GrabFocus()
igg.SelectIdxAction(idx+ig.StartIdx(), me.SelectMode())
case me.Button == mouse.Right && me.Action == mouse.Release:
igg.ItemCtxtMenu(igg.SelectedIdx)
me.SetProcessed()
}
})
ig.ConnectEvent(oswin.KeyChordEvent, gi.HiPri, func(recv, send ki.Ki, sig int64, d any) {
igg := recv.Embed(KiT_ImgGrid).(*ImgGrid)
kt := d.(*key.ChordEvent)
igg.KeyInputActive(kt)
})
ig.ConnectEvent(oswin.DNDEvent, gi.RegPri, func(recv, send ki.Ki, sig int64, d any) {
de := d.(*dnd.Event)
igg := recv.Embed(KiT_ImgGrid).(*ImgGrid)
switch de.Action {
case dnd.Start:
igg.DragNDropStart()
case dnd.DropOnTarget:
igg.DragNDropTarget(de)
// case dnd.DropFmSource: // don't do this -- only targets!
// igg.DragNDropSource(de)
}
})
gr.ConnectEvent(oswin.DNDFocusEvent, gi.RegPri, func(recv, send ki.Ki, sig int64, d any) {
de := d.(*dnd.FocusEvent)
sgg := recv.Embed(gi.KiT_Layout).(*gi.Layout)
switch de.Action {
case dnd.Enter:
sgg.Viewport.Win.DNDSetCursor(de.Mod)
case dnd.Exit:
sgg.Viewport.Win.DNDNotCursor()
case dnd.Hover:
// nothing here?
}
})
}
/////////////////////////////////////////////////////////////////////////////
// Moving
// MoveNext moves the selection to next item, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (ig *ImgGrid) MoveNext(selMode mouse.SelectModes) int {
nf := ig.NumImages()
if ig.SelectedIdx >= nf-1 {
ig.SelectedIdx = nf - 1
return -1
}
ig.SelectedIdx++
ig.SelectIdxAction(ig.SelectedIdx, selMode)
return ig.SelectedIdx
}
// MoveNextAction moves the selection to next item, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (ig *ImgGrid) MoveNextAction(selMode mouse.SelectModes) int {
nidx := ig.MoveNext(selMode)
if nidx >= 0 {
ig.ScrollToIdx(nidx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), nidx)
}
return nidx
}
// MovePrev moves the selection to previous idx, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (ig *ImgGrid) MovePrev(selMode mouse.SelectModes) int {
if ig.SelectedIdx <= 0 {
ig.SelectedIdx = 0
return -1
}
ig.SelectedIdx--
ig.SelectIdxAction(ig.SelectedIdx, selMode)
return ig.SelectedIdx
}
// MovePrevAction moves the selection to previous idx, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (ig *ImgGrid) MovePrevAction(selMode mouse.SelectModes) int {
nidx := ig.MovePrev(selMode)
if nidx >= 0 {
ig.ScrollToIdx(nidx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), nidx)
}
return nidx
}
// MoveDown moves the selection down to next row, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (ig *ImgGrid) MoveDown(selMode mouse.SelectModes) int {
nf := ig.NumImages()
if ig.SelectedIdx >= nf-1 {
ig.SelectedIdx = nf - 1
return -1
}
if ig.SelectedIdx+ig.Size.X >= nf {
return -1
}
ig.SelectedIdx += ig.Size.X
ig.SelectIdxAction(ig.SelectedIdx, selMode)
return ig.SelectedIdx
}
// MoveDownAction moves the selection down to next row, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (ig *ImgGrid) MoveDownAction(selMode mouse.SelectModes) int {
nidx := ig.MoveDown(selMode)
if nidx >= 0 {
ig.ScrollToIdx(nidx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), nidx)
}
return nidx
}
// MoveUp moves the selection up to previous idx, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (ig *ImgGrid) MoveUp(selMode mouse.SelectModes) int {
if ig.SelectedIdx <= 0 {
ig.SelectedIdx = 0
return -1
}
if ig.SelectedIdx-ig.Size.X < 0 {
return -1
}
ig.SelectedIdx -= ig.Size.X
ig.SelectIdxAction(ig.SelectedIdx, selMode)
return ig.SelectedIdx
}
// MoveUpAction moves the selection up to previous idx, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (ig *ImgGrid) MoveUpAction(selMode mouse.SelectModes) int {
nidx := ig.MoveUp(selMode)
if nidx >= 0 {
ig.ScrollToIdx(nidx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), nidx)
}
return nidx
}
// MovePageDown moves the selection down to next page, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (ig *ImgGrid) MovePageDown(selMode mouse.SelectModes) int {
nf := ig.NumImages()
if ig.SelectedIdx >= nf-1 {
ig.SelectedIdx = nf - 1
return -1
}
np := ig.Size.X * ig.Size.Y
if ig.SelectedIdx+np >= nf {
return ig.MoveDown(selMode)
}
ig.SelectedIdx += np
ig.SelectIdxAction(ig.SelectedIdx, selMode)
return ig.SelectedIdx
}
// MovePageDownAction moves the selection down to next page, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (ig *ImgGrid) MovePageDownAction(selMode mouse.SelectModes) int {
nidx := ig.MovePageDown(selMode)
if nidx >= 0 {
ig.ScrollToIdx(nidx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), nidx)
}
return nidx
}
// MovePageUp moves the selection up to previous page, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (ig *ImgGrid) MovePageUp(selMode mouse.SelectModes) int {
if ig.SelectedIdx <= 0 {
ig.SelectedIdx = 0
return -1
}
np := ig.Size.X * ig.Size.Y
if ig.SelectedIdx-np < 0 {
return ig.MoveUp(selMode)
}
ig.SelectedIdx -= np
ig.SelectIdxAction(ig.SelectedIdx, selMode)
return ig.SelectedIdx
}
// MovePageUpAction moves the selection up to previous page, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected idx
func (ig *ImgGrid) MovePageUpAction(selMode mouse.SelectModes) int {
nidx := ig.MovePageUp(selMode)
if nidx >= 0 {
ig.ScrollToIdx(nidx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), nidx)
}
return nidx
}
//////////////////////////////////////////////////////////////////////////////
// Selection: user operates on the index labels
// StartIdx returns the index of first image visible
func (ig *ImgGrid) StartIdx() int {
sb := ig.ScrollBar()
si := int(sb.Value) * ig.Size.X
return si
}
// IsIdxVisible returns true if image index is currently visible
func (ig *ImgGrid) IsIdxVisible(idx int) bool {
si := ig.StartIdx()
sidx := si
eidx := sidx + ig.Size.X*ig.Size.Y
if idx < sidx || idx >= eidx {
return false
}
return true
}
// IdxPos returns center of window position of index label for idx (ContextMenuPos)
func (ig *ImgGrid) IdxPos(idx int) image.Point {
pos := ig.Viewport.Win.EventMgr.LastMousePos
bm := ig.BitmapAtIdx(idx)
if bm != nil {
pos = bm.ContextMenuPos()
}
return pos
}
// IdxFromPos returns the widget grid idx that contains given position, false if not found
// add StartIdx to get actual index
func (ig *ImgGrid) IdxFromPos(pos image.Point) (int, bool) {
gr := ig.Grid()
st := gr.WinBBox.Min
rp := pos.Sub(st)
if rp.X < 0 || rp.Y < 0 {
return 0, false
}
sp := gr.Spacing.Dots
x := rp.X / int(ig.ImageMax)
x = ints.MinInt(x, ig.Size.X)
y := rp.Y / int(ig.ImageMax+sp)
y = ints.MinInt(y, ig.Size.Y)
idx := y*ig.Size.X + x
return idx, true
}
// ScrollToIdx ensures that given slice idx is visible by scrolling display as needed
func (ig *ImgGrid) ScrollToIdx(idx int) bool {
sb := ig.ScrollBar()
si := ig.StartIdx()
ir := idx / ig.Size.X
np := ig.Size.X * ig.Size.Y
if idx < si {
sb.SetValueAction(float32(ir))
return true
} else if idx >= si+np {
ni := ir - (ig.Size.Y - 1)
ni = ints.MaxInt(0, ni)
sb.SetValueAction(float32(ni))
return true
}
return false
}
// SelectIdxWidgets sets the selection state of given slice index
// returns false if index is not visible
func (ig *ImgGrid) SelectIdxWidgets(idx int, sel bool) bool {
if !ig.IsIdxVisible(idx) {
return false
}
return true
}
// IdxGrabFocus grabs the focus for the first focusable widget in given idx
func (ig *ImgGrid) IdxGrabFocus(idx int) {
ig.ScrollToIdx(idx)
}
// UpdateSelectIdx updates the selection for the given index
func (ig *ImgGrid) UpdateSelectIdx(idx int, sel bool) {
selMode := mouse.SelectOne
em := ig.EventMgr2D()
if em != nil {
selMode = em.LastSelMode
}
ig.SelectIdxAction(idx, selMode)
}
// IdxIsSelected returns the selected status of given slice index
func (ig *ImgGrid) IdxIsSelected(idx int) bool {
if _, ok := ig.SelectedIdxs[idx]; ok {
return true
}
return false
}
func (ig *ImgGrid) ResetSelectedIdxs() {
ig.SelectedIdxs = make(map[int]struct{})
}
// SelectedIdxsList returns list of selected indexes, sorted either ascending or descending
func (ig *ImgGrid) SelectedIdxsList(descendingSort bool) []int {
rws := make([]int, len(ig.SelectedIdxs))
i := 0
for r, _ := range ig.SelectedIdxs {
rws[i] = r
i++
}
if descendingSort {
sort.Slice(rws, func(i, j int) bool {
return rws[i] > rws[j]
})
} else {
sort.Slice(rws, func(i, j int) bool {
return rws[i] < rws[j]
})
}
return rws
}
// SelectIdx selects given idx (if not already selected) -- updates select
// status of index label
func (ig *ImgGrid) SelectIdx(idx int) {
ig.SelectedIdxs[idx] = struct{}{}
ig.SelectIdxWidgets(idx, true)
}
// UnselectIdx unselects given idx (if selected)
func (ig *ImgGrid) UnselectIdx(idx int) {
if ig.IdxIsSelected(idx) {
delete(ig.SelectedIdxs, idx)
}
ig.SelectIdxWidgets(idx, false)
}
// UnselectAllIdxs unselects all selected idxs
func (ig *ImgGrid) UnselectAllIdxs() {
updt := ig.UpdateStart()
ig.ResetSelectedIdxs()
ig.UpdateEnd(updt)
}
// SelectAllIdxs selects all idxs
func (ig *ImgGrid) SelectAllIdxs() {
nf := ig.NumImages()
updt := ig.UpdateStart()
ig.UnselectAllIdxs()
ig.SelectedIdxs = make(map[int]struct{}, nf)
for idx := 0; idx < nf; idx++ {
ig.SelectedIdxs[idx] = struct{}{}
}
ig.UpdateEnd(updt)
}
// SelectIdxAction is called when a select action has been received (e.g., a
// mouse click) -- translates into selection updates -- gets selection mode
// from mouse event (ExtendContinuous, ExtendOne)
func (ig *ImgGrid) SelectIdxAction(idx int, mode mouse.SelectModes) {
if mode == mouse.NoSelect {
return
}
nf := ig.NumImages()
idx = ints.MinInt(idx, nf-1)
if idx < 0 {
idx = 0
}
// row := idx - sv.StartIdx // note: could be out of bounds
wupdt := ig.TopUpdateStart()
defer ig.TopUpdateEnd(wupdt)
switch mode {
case mouse.SelectOne:
if ig.IdxIsSelected(idx) {
if len(ig.SelectedIdxs) > 1 {
ig.UnselectAllIdxs()
}
ig.SelectedIdx = idx
ig.SelectIdx(idx)
ig.IdxGrabFocus(idx)
} else {
ig.UnselectAllIdxs()
ig.SelectedIdx = idx
ig.SelectIdx(idx)
ig.IdxGrabFocus(idx)
}
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), ig.SelectedIdx)
case mouse.ExtendContinuous:
if len(ig.SelectedIdxs) == 0 {
ig.SelectedIdx = idx
ig.SelectIdx(idx)
ig.IdxGrabFocus(idx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), ig.SelectedIdx)
} else {
minIdx := -1
maxIdx := 0
for r, _ := range ig.SelectedIdxs {
if minIdx < 0 {
minIdx = r
} else {
minIdx = ints.MinInt(minIdx, r)
}
maxIdx = ints.MaxInt(maxIdx, r)
}
cidx := idx
ig.SelectedIdx = idx
ig.SelectIdx(idx)
if idx < minIdx {
for cidx < minIdx {
r := ig.MoveNext(mouse.SelectQuiet) // just select
cidx = r
}
} else if idx > maxIdx {
for cidx > maxIdx {
r := ig.MovePrev(mouse.SelectQuiet) // just select
cidx = r
}
}
ig.IdxGrabFocus(idx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), ig.SelectedIdx)
}
case mouse.ExtendOne:
if ig.IdxIsSelected(idx) {
ig.UnselectIdxAction(idx)
} else {
ig.SelectedIdx = idx
ig.SelectIdx(idx)
ig.IdxGrabFocus(idx)
ig.WidgetSig.Emit(ig.This(), int64(gi.WidgetSelected), ig.SelectedIdx)
}
case mouse.Unselect:
ig.UnselectIdxAction(idx)
case mouse.SelectQuiet:
ig.SelectedIdx = idx
ig.SelectIdx(idx)
case mouse.UnselectQuiet:
ig.UnselectIdx(idx)
}
if mode != mouse.SelectQuiet && mode != mouse.UnselectQuiet {
ig.UpdateSig()
}
}
// UnselectIdxAction unselects this idx (if selected) -- and emits a signal
func (ig *ImgGrid) UnselectIdxAction(idx int) {
if ig.IdxIsSelected(idx) {
ig.UnselectIdx(idx)
}
}
//////////////////////////////////////////////////////////////////////////////
// Copy / Cut / Paste
// MimeDataIdx adds mimedata for given idx: an application/json of the struct
func (ig *ImgGrid) MimeDataIdx(md *mimedata.Mimes, idx int) {
fn := ig.Images[idx]
*md = append(*md, &mimedata.Data{Type: filecat.TextPlain, Data: []byte(fn)})
}
// FromMimeData creates a slice of file names from mime data
func (ig *ImgGrid) FromMimeData(md mimedata.Mimes) []string {
var sl []string
for _, d := range md {
if d.Type == filecat.TextPlain {
fn := string(d.Data)
sl = append(sl, fn)
}
}
return sl
}
// CopySelToMime copies selected rows to mime data
func (ig *ImgGrid) CopySelToMime() mimedata.Mimes {
nitms := len(ig.SelectedIdxs)
if nitms == 0 {
return nil
}
ixs := ig.SelectedIdxsList(false) // ascending
md := make(mimedata.Mimes, 0, nitms)
for _, i := range ixs {
ig.MimeDataIdx(&md, i)
}
return md
}
// Copy copies selected rows to clip.Board, optionally resetting the selection
// satisfies gi.Clipper interface and can be overridden by subtypes
func (ig *ImgGrid) Copy(reset bool) {
nitms := len(ig.SelectedIdxs)
if nitms == 0 {
return
}
md := ig.CopySelToMime()
if md != nil {
oswin.TheApp.ClipBoard(ig.Viewport.Win.OSWin).Write(md)
}
if reset {
ig.UnselectAllIdxs()
}
}
// CopyIdxs copies selected idxs to clip.Board, optionally resetting the selection
func (ig *ImgGrid) CopyIdxs(reset bool) {
if cpr, ok := ig.This().(gi.Clipper); ok { // should always be true, but justin case..
cpr.Copy(reset)
} else {
ig.Copy(reset)
}
}
// DeleteIdxs deletes all selected indexes
func (ig *ImgGrid) DeleteIdxs() {
if len(ig.SelectedIdxs) == 0 {
return
}
updt := ig.UpdateStart()
ixs := ig.SelectedIdxsList(true) // descending sort
for _, i := range ixs {
ig.ImageDeleteAt(i)
}
ig.UpdateEnd(updt)
}
// Cut copies selected indexes to clip.Board and deletes selected indexes
// satisfies gi.Clipper interface and can be overridden by subtypes
func (ig *ImgGrid) Cut() {
if len(ig.SelectedIdxs) == 0 {
return
}
ig.CopyIdxs(false)
ixs := ig.SelectedIdxsList(true) // descending sort
idx := ixs[0]
ig.UnselectAllIdxs()
for _, i := range ixs {
ig.ImageDeleteAt(i)
}
ig.Update()
ig.SelectIdxAction(idx, mouse.SelectOne)
}
// CutIdxs copies selected indexes to clip.Board and deletes selected indexes
func (ig *ImgGrid) CutIdxs() {
if cpr, ok := ig.This().(gi.Clipper); ok { // should always be true, but justin case..
cpr.Cut()
} else {
ig.Cut()
}
}
// Paste pastes clipboard at CurIdx
// satisfies gi.Clipper interface and can be overridden by subtypes
func (ig *ImgGrid) Paste() {
md := oswin.TheApp.ClipBoard(ig.Viewport.Win.OSWin).Read([]string{filecat.TextPlain})
if md != nil {
ig.PasteMenu(md, ig.CurIdx)
}
}
// PasteIdx pastes clipboard at given idx
func (ig *ImgGrid) PasteIdx(idx int) {
ig.CurIdx = idx
if cpr, ok := ig.This().(gi.Clipper); ok { // should always be true, but justin case..
cpr.Paste()
} else {
ig.Paste()
}
}
// MakePasteMenu makes the menu of options for paste events
func (ig *ImgGrid) MakePasteMenu(m *gi.Menu, data any, idx int) {
if len(*m) > 0 {
return
}
m.AddAction(gi.ActOpts{Label: "Assign To", Data: data}, ig.This(), func(recv, send ki.Ki, sig int64, data any) {
svv := recv.Embed(KiT_ImgGrid).(*ImgGrid)
svv.PasteAssign(data.(mimedata.Mimes), idx)
})
m.AddAction(gi.ActOpts{Label: "Insert Before", Data: data}, ig.This(), func(recv, send ki.Ki, sig int64, data any) {
svv := recv.Embed(KiT_ImgGrid).(*ImgGrid)
svv.PasteAtIdx(data.(mimedata.Mimes), idx)
})
m.AddAction(gi.ActOpts{Label: "Insert After", Data: data}, ig.This(), func(recv, send ki.Ki, sig int64, data any) {
svv := recv.Embed(KiT_ImgGrid).(*ImgGrid)
svv.PasteAtIdx(data.(mimedata.Mimes), idx+1)
})
m.AddAction(gi.ActOpts{Label: "Cancel", Data: data}, ig.This(), func(recv, send ki.Ki, sig int64, data any) {
})
}
// PasteMenu performs a paste from the clipboard using given data -- pops up
// a menu to determine what specifically to do
func (ig *ImgGrid) PasteMenu(md mimedata.Mimes, idx int) {
ig.UnselectAllIdxs()
var men gi.Menu
ig.MakePasteMenu(&men, md, idx)
pos := ig.IdxPos(idx)
gi.PopupMenu(men, pos.X, pos.Y, ig.Viewport, "svPasteMenu")
}
// PasteAssign assigns mime data (only the first one!) to this idx
func (ig *ImgGrid) PasteAssign(md mimedata.Mimes, idx int) {
sl := ig.FromMimeData(md)
if len(sl) == 0 {
return
}
updt := ig.UpdateStart()
ig.SetFullReRender()
ns := sl[0]
ig.Images[idx] = ns
ig.UpdateEnd(updt)
}
// PasteAtIdx inserts object(s) from mime data at (before) given slice index
func (ig *ImgGrid) PasteAtIdx(md mimedata.Mimes, idx int) {
sl := ig.FromMimeData(md)
if len(sl) == 0 {
return
}
ig.ImageInsertAt(idx, sl)
ig.Update()
ig.SelectIdxAction(idx, mouse.SelectOne)
}
// Duplicate copies selected items and inserts them after current selection --
// return idx of start of duplicates if successful, else -1
func (ig *ImgGrid) Duplicate() int {
nitms := len(ig.SelectedIdxs)
if nitms == 0 {
return -1
}
ixs := ig.SelectedIdxsList(true) // descending sort -- last first
pasteAt := ixs[0]
ig.CopyIdxs(true)
md := oswin.TheApp.ClipBoard(ig.Viewport.Win.OSWin).Read([]string{filecat.TextPlain})