File: grid.go

package info (click to toggle)
golang-github-gcla-gowid 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,456 kB
  • sloc: makefile: 4
file content (455 lines) | stat: -rw-r--r-- 11,780 bytes parent folder | download
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
// Copyright 2019-2022 Graham Clark. All rights reserved.  Use of this source
// code is governed by the MIT license that can be found in the LICENSE
// file.

// Package grid allows widgets to be arranged in rows and columns.
package grid

import (
	"errors"
	"fmt"
	"strings"

	"github.com/gcla/gowid"
	"github.com/gcla/gowid/gwutil"
	"github.com/gcla/gowid/vim"
	"github.com/gcla/gowid/widgets/columns"
	"github.com/gcla/gowid/widgets/hpadding"
	"github.com/gcla/gowid/widgets/pile"
	"github.com/gcla/gowid/widgets/text"
	"github.com/gcla/gowid/widgets/vpadding"
	tcell "github.com/gdamore/tcell/v2"
)

//======================================================================

type IGrid interface {
	gowid.IFindNextSelectable
	gowid.IFocus
	SubWidgets() []gowid.IWidget
	GenerateWidgets(size gowid.IRenderSize, attrs gowid.IRenderContext) (pile.IWidget, int)
	Width() int
	HSep() int
	VSep() int
	HAlign() gowid.IHAlignment
	Wrap() bool
	KeyIsUp(*tcell.EventKey) bool
	KeyIsDown(*tcell.EventKey) bool
	KeyIsLeft(*tcell.EventKey) bool
	KeyIsRight(*tcell.EventKey) bool
}

type IWidget interface {
	gowid.IWidget
	IGrid
}

type Width struct{}
type Align struct{}
type VSepCB struct{}
type HSepCB struct{}

// align sets the alignment of the group within the leftover space in the row.
type Widget struct {
	widgets []gowid.IWidget
	width   int
	hSep    int
	vSep    int
	align   gowid.IHAlignment
	focus   int // -1 means nothing selectable
	wrap    bool
	options Options
	*gowid.Callbacks
	gowid.SubWidgetsCallbacks
	gowid.FocusCallbacks
}

type Options struct {
	StartPos  int
	Wrap      bool
	DownKeys  []vim.KeyPress
	UpKeys    []vim.KeyPress
	LeftKeys  []vim.KeyPress
	RightKeys []vim.KeyPress
}

func New(widgets []gowid.IWidget, width int, hSep int, vSep int, align gowid.IHAlignment, opts ...Options) *Widget {
	var opt Options
	if len(opts) > 0 {
		opt = opts[0]
	} else {
		opt = Options{
			StartPos: -1,
		}
	}
	if opt.DownKeys == nil {
		opt.DownKeys = vim.AllDownKeys
	}
	if opt.UpKeys == nil {
		opt.UpKeys = vim.AllUpKeys
	}
	if opt.LeftKeys == nil {
		opt.LeftKeys = vim.AllLeftKeys
	}
	if opt.RightKeys == nil {
		opt.RightKeys = vim.AllRightKeys
	}
	res := &Widget{
		widgets: widgets,
		width:   width,
		hSep:    hSep,
		vSep:    vSep,
		align:   align,
		focus:   -1,
		options: opt,
	}
	res.SubWidgetsCallbacks = gowid.SubWidgetsCallbacks{CB: &res.Callbacks}
	res.FocusCallbacks = gowid.FocusCallbacks{CB: &res.Callbacks}
	if opt.StartPos >= 0 {
		res.focus = gwutil.Min(opt.StartPos, len(widgets)-1)
	} else {
		res.focus, _ = res.FindNextSelectable(1, res.Wrap())
	}

	var _ gowid.IWidget = res
	var _ gowid.ICompositeMultiple = res
	var _ IWidget = res

	return res
}

func (w *Widget) String() string {
	cols := make([]string, len(w.widgets))
	for i := 0; i < len(cols); i++ {
		cols[i] = fmt.Sprintf("%v", w.widgets[i])
	}
	return fmt.Sprintf("grid[%s]", strings.Join(cols, ","))
}

func (w *Widget) Width() int {
	return w.width
}

func (w *Widget) SetWidth(i int, app gowid.IApp) {
	w.width = i
	gowid.RunWidgetCallbacks(w.Callbacks, Width{}, app, w)
}

func (w *Widget) HSep() int {
	return w.hSep
}

func (w *Widget) SetHSep(i int, app gowid.IApp) {
	w.hSep = i
	gowid.RunWidgetCallbacks(w.Callbacks, HSepCB{}, app, w)
}

func (w *Widget) VSep() int {
	return w.vSep
}

func (w *Widget) SetVSep(i int, app gowid.IApp) {
	w.vSep = i
	gowid.RunWidgetCallbacks(w.Callbacks, VSepCB{}, app, w)
}

func (w *Widget) HAlign() gowid.IHAlignment {
	return w.align
}

func (w *Widget) SetHAlign(i gowid.IHAlignment, app gowid.IApp) {
	w.align = i
	gowid.RunWidgetCallbacks(w.Callbacks, Align{}, app, w)
}

func (w *Widget) SubWidgets() []gowid.IWidget {
	return gowid.CopyWidgets(w.widgets)
}

func (w *Widget) SetSubWidgets(widgets []gowid.IWidget, app gowid.IApp) {
	w.widgets = widgets
	gowid.RunWidgetCallbacks(w.Callbacks, gowid.SubWidgetsCB{}, app, w)
}

// Tries to set at required index, will choose first selectable from there
func (w *Widget) SetFocus(app gowid.IApp, i int) {
	old := w.focus
	w.focus = gwutil.Min(gwutil.Max(i, 0), len(w.widgets)-1)
	if old != w.focus {
		gowid.RunWidgetCallbacks(w.Callbacks, gowid.FocusCB{}, app, w)
	}
}

func (w *Widget) Wrap() bool {
	return w.options.Wrap
}

// Tries to set at required index, will choose first selectable from there
func (w *Widget) Focus() int {
	return w.focus
}

func (w *Widget) Selectable() bool {
	for _, widget := range w.widgets {
		if widget.Selectable() {
			return true
		}
	}
	return false
}

func (w *Widget) FindNextSelectable(dir gowid.Direction, wrap bool) (int, bool) {
	return gowid.FindNextSelectableWidget(w.widgets, w.focus, dir, wrap)
}

func (w *Widget) UserInput(ev interface{}, size gowid.IRenderSize, focus gowid.Selector, app gowid.IApp) bool {
	return UserInput(w, ev, size, focus, app)
}

func (w *Widget) GenerateWidgets(size gowid.IRenderSize, attrs gowid.IRenderContext) (pile.IWidget, int) {
	return GenerateWidgets(w, size, attrs)
}

func (w *Widget) RenderSize(size gowid.IRenderSize, focus gowid.Selector, app gowid.IApp) gowid.IRenderBox {
	return gowid.CalculateRenderSizeFallback(w, size, focus, app)
}

func (w *Widget) Render(size gowid.IRenderSize, focus gowid.Selector, app gowid.IApp) gowid.ICanvas {
	return Render(w, size, focus, app)
}

func (w *Widget) KeyIsUp(evk *tcell.EventKey) bool {
	return vim.KeyIn(evk, w.options.UpKeys)
}

func (w *Widget) KeyIsDown(evk *tcell.EventKey) bool {
	return vim.KeyIn(evk, w.options.DownKeys)
}

func (w *Widget) KeyIsLeft(evk *tcell.EventKey) bool {
	return vim.KeyIn(evk, w.options.LeftKeys)
}

func (w *Widget) KeyIsRight(evk *tcell.EventKey) bool {
	return vim.KeyIn(evk, w.options.RightKeys)
}

//''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

func Render(w IWidget, size gowid.IRenderSize, focus gowid.Selector, app gowid.IApp) gowid.ICanvas {
	pile, _ := w.GenerateWidgets(size, app)
	res := pile.Render(size, focus, app)
	return res
}

// Scroll sequentially through the widgets on mouse scroll events or key up/down
func UserInput(w IGrid, ev interface{}, size gowid.IRenderSize, focus gowid.Selector, app gowid.IApp) bool {
	subfocus := w.Focus()
	if !focus.Focus {
		subfocus = -1
	}

	forChild := false

	var gen pile.IWidget
	var cols int

	scrollDown := false
	scrollUp := false
	scrollRight := false
	scrollLeft := false

	if evm, ok := ev.(*tcell.EventMouse); ok {
		// If it's a scroll event, then handle it in the grid, not by delegating to the
		// construction of piles and columns
		if evm.Buttons()&(tcell.WheelDown|tcell.WheelUp|tcell.WheelLeft|tcell.WheelRight) == 0 {
			gen, cols = w.GenerateWidgets(size, app)
			forChild = gowid.UserInputIfSelectable(gen, ev, size, focus, app)
			if evm.Buttons() == tcell.Button1 && forChild {
				pileidx := gen.Focus()
				if pileidx != -1 {
					// if ForChild, then it can't be any of the in between text widgets used to pad
					// things, so don't worry about checking the casts
					rowx, _ := gen.SubWidgets()[pileidx].(*gowid.ContainerWidget)
					rowy, _ := rowx.SubWidget().(*hpadding.Widget)
					row, _ := rowy.IWidget.(*columns.Widget)
					colidx := row.Focus()
					w.SetFocus(app, (((pileidx+1)/2)*cols)+((colidx+1)/2))
				}
			}
		}
	} else {
		if subfocus != -1 {
			forChild = gowid.UserInputIfSelectable(w.SubWidgets()[w.Focus()], ev, size, focus, app)
		}
	}

	if forChild {
		return true
	} else {
		newfocus := -1

		if evk, ok := ev.(*tcell.EventKey); ok {
			switch {
			case w.KeyIsRight(evk):
				next, ok := w.FindNextSelectable(1, w.Wrap())
				if ok {
					w.SetFocus(app, next)
					return true
				}
			case w.KeyIsLeft(evk):
				next, ok := w.FindNextSelectable(-1, w.Wrap())
				if ok {
					w.SetFocus(app, next)
					return true
				}
			case w.KeyIsDown(evk):
				scrollDown = true
			case w.KeyIsUp(evk):
				scrollUp = true
			}
		} else if ev2, ok := ev.(*tcell.EventMouse); ok {
			switch ev2.Buttons() {
			case tcell.WheelDown:
				scrollDown = true
			case tcell.WheelUp:
				scrollUp = true
			case tcell.WheelRight:
				scrollRight = true
			case tcell.WheelLeft:
				scrollLeft = true
			}
		}

		if scrollDown || scrollUp || scrollRight || scrollLeft {
			if gen == nil {
				_, cols = w.GenerateWidgets(size, app)
			}

			if scrollDown {
				for i := w.Focus() + cols; i < len(w.SubWidgets()); i += cols {
					if w.SubWidgets()[i].Selectable() {
						newfocus = i
						break
					}
				}
			}
			if scrollUp {
				for i := w.Focus() - cols; i >= 0; i -= cols {
					if w.SubWidgets()[i].Selectable() {
						newfocus = i
						break
					}
				}
			}
			if scrollRight {
				i := ((w.Focus() / cols) * cols) + gwutil.Min(w.Focus()+1, cols-1)
				j := ((w.Focus() / cols) * cols) + (cols - 1)
				for ; i <= j; i++ {
					if w.SubWidgets()[i].Selectable() {
						newfocus = i
						break
					}
				}
			}
			if scrollLeft {
				i := ((w.Focus() / cols) * cols) + gwutil.Max((w.Focus()%cols)-1, 0)
				j := ((w.Focus() / cols) * cols)
				for ; i >= j; i-- {
					if w.SubWidgets()[i].Selectable() {
						newfocus = i
						break
					}
				}
			}
			if newfocus != -1 {
				w.SetFocus(app, newfocus)
				return true
			}
		}

		return false
	}
}

// Can't support RenderFixed{} because I need to know how many columns so I can roll over widgets
// to the next line.
//
func GenerateWidgets(w IGrid, size gowid.IRenderSize, attrs gowid.IRenderContext) (pile.IWidget, int) {
	focusIdx := w.Focus()
	cols2, isColumns := size.(gowid.IColumns)
	if !isColumns {
		panic(errors.New("GridFlow widget must not be rendered in Fixed mode."))
	}
	cols := cols2.Columns()

	// TODO - what about when cols < vsep?
	numInRow := (cols - w.HSep()) / (w.Width() + w.HSep())
	wWidth := numInRow * w.Width()
	if numInRow > 0 {
		wWidth += (numInRow - 1) * w.HSep()
	}

	pileWidgets := make([]gowid.IContainerWidget, 0)

	curInRow := 0
	hSepWidget := &gowid.ContainerWidget{text.New(gwutil.StringOfLength(' ', w.HSep())), gowid.RenderWithUnits{U: w.HSep()}}
	hBlankWidget := &gowid.ContainerWidget{text.New(gwutil.StringOfLength(' ', w.Width())), gowid.RenderWithUnits{U: w.Width()}}
	vBlank := text.New("")
	vBlankWidget := vpadding.New(vBlank, gowid.VAlignTop{}, gowid.RenderWithUnits{U: w.VSep()})
	curRow := make([]gowid.IContainerWidget, 0)

	todo := 0
	rowFocusIdx := -1
	pileFocusIdx := -1
	var fakeApp gowid.IApp
	if len(w.SubWidgets()) > 0 {
		todo = (((len(w.SubWidgets()) - 1) / numInRow) + 1) * numInRow
	}
	firstRow := true
	for i := 0; i < todo; i++ {
		if i >= len(w.SubWidgets()) {
			curRow = append(curRow, hBlankWidget)
		} else {
			if i == focusIdx {
				rowFocusIdx = len(curRow)
			}
			curRow = append(curRow, &gowid.ContainerWidget{w.SubWidgets()[i], gowid.RenderWithUnits{U: w.Width()}})
		}
		curInRow += 1
		if curInRow == numInRow {
			cols := columns.New(curRow)
			alignedColumns := hpadding.New(cols, w.HAlign(), gowid.RenderWithUnits{U: wWidth})
			if !firstRow {
				pileWidgets = append(pileWidgets, &gowid.ContainerWidget{vBlankWidget, gowid.RenderFlow{}})
			}
			pileWidgets = append(pileWidgets, &gowid.ContainerWidget{alignedColumns, gowid.RenderFlow{}})
			if rowFocusIdx != -1 {
				// TODO: wrong wrong wrong
				// It's not necessarily an IApp e.g. when called from Render - but it's ok because I haven't set
				// any callbacks
				cols.SetFocus(fakeApp, rowFocusIdx)
				rowFocusIdx = -1
				pileFocusIdx = len(pileWidgets) - 1
			}
			firstRow = false
			curInRow = 0
			curRow = make([]gowid.IContainerWidget, 0)
		} else {
			curRow = append(curRow, hSepWidget)
		}
	}

	pile := pile.New(pileWidgets)
	if pileFocusIdx != -1 {
		pile.SetFocus(fakeApp, pileFocusIdx)
	}

	return pile, numInRow
}

//======================================================================
// Local Variables:
// mode: Go
// fill-column: 110
// End: