turbo-editors/turbo-corepublic Fork 0
v0.9.0
Commits
Clone
git clone https://git.rickub.com/turbo-editors/turbo-core.git
git clone ssh://git@rickub.com/turbo-editors/turbo-core.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

🛟 Updated. 28d5985 · on v0.9.0 · k33g · 21h ago
window.go · 446 lines · 13.7 KBGo Blame HistoryRaw
  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
package ui

import (
	"strconv"

	"github.com/gdamore/tcell/v2"

	"codeberg.org/turbo-editors/turbo-core/theme"
)

// MinWindowWidth and MinWindowHeight are the smallest a window may be dragged
// down to: enough for a frame and one cell of content.
const (
	MinWindowWidth  = 12
	MinWindowHeight = 4
)

// Grow says which edges of the desktop a window follows when the desktop is
// resized — Turbo Vision called this a window's grow mode.
//
// A document window follows the right and bottom edges, so its top-left corner
// stays put while its far corner keeps pace with the terminal. That is what
// makes the editor fill a window you have just made larger.
type Grow uint8

// The edges a window can follow.
const (
	GrowNone   Grow = 0
	GrowRight  Grow = 1 << iota // the right edge keeps its distance from the desktop's
	GrowBottom                  // the bottom edge keeps its distance from the desktop's

	// GrowBoth is what a document window uses.
	GrowBoth = GrowRight | GrowBottom
)

// Window is a framed, movable, resizable box holding one widget.
//
// The frame carries the Turbo Vision furniture: a close box at the top left, a
// title, the window's number so that Alt-1 … Alt-9 can reach it, and a
// maximise box at the top right. The frame is drawn double when the window is
// active and single when it is not, which is how the eye finds the focused
// window even in a monochrome terminal.
type Window struct {
	Box
	title    string
	number   int
	active   bool
	closable bool
	grow     Grow
	content  Widget

	// OnClose is called when the close box is used. It returns whether the
	// window may actually go, so an editor can put a "save first?" dialog in
	// the way.
	OnClose func() bool

	// OnMaximize is called when the maximise box is used.
	//
	// A window with nobody listening draws no maximise box, because the window
	// itself cannot know what to fill: only whatever holds it does. Desktop.Add
	// sets this, so a window on a desktop always has a working one.
	OnMaximize func()

	// maximized says whether the window is currently filling its desktop, and
	// restore is where it was before it did.
	maximized bool
	restore   Rect

	drag dragState
}

// dragState remembers what a mouse drag on the frame is doing.
type dragState struct {
	mode   dragMode
	startX int
	startY int
	origin Rect
}

// dragMode is what the current mouse drag is changing.
type dragMode int

const (
	dragNone dragMode = iota
	dragMove
	dragResize
)

// NewWindow returns a window titled title, holding content.
//
//	w := ui.NewWindow("main.go", editorView)
//	w.SetBounds(ui.Rect{X: 0, Y: 1, W: 60, H: 20})
func NewWindow(title string, content Widget) *Window {
	return &Window{title: title, content: content, closable: true, grow: GrowBoth}
}

// Grow returns which desktop edges this window follows.
func (w *Window) Grow() Grow { return w.grow }

// SetGrow chooses which desktop edges this window follows. A window set to
// GrowNone keeps its size and is only moved back into view.
func (w *Window) SetGrow(grow Grow) { w.grow = grow }

// fitInto returns where the window belongs after the desktop has changed from
// one rectangle to another.
//
// The edges the window follows move by the same amount the desktop's did, so
// the gap between them is preserved. Whatever the result, the window is then
// held to the desktop's own size: one larger than the desktop that holds it
// has parts nobody can reach.
func (w *Window) fitInto(from, to Rect) Rect { return w.fitRect(w.Bounds(), from, to) }

// fitRect is fitInto for any rectangle belonging to this window, which is what
// lets the bounds a maximised window would be restored to travel with it.
func (w *Window) fitRect(bounds, from, to Rect) Rect {
	if !from.IsEmpty() {
		if w.grow&GrowRight != 0 {
			bounds.W += to.Right() - from.Right()
		}
		if w.grow&GrowBottom != 0 {
			bounds.H += to.Bottom() - from.Bottom()
		}
	}

	bounds.W = min(max(bounds.W, MinWindowWidth), to.W)
	bounds.H = min(max(bounds.H, MinWindowHeight), to.H)
	return bounds.ClampInto(to)
}

// followDesktop moves the window as the desktop changes size, taking the
// bounds it would be restored to along with it.
//
// Without the second part, maximising and then making the terminal smaller
// would leave a restore rectangle larger than the desktop — and pressing the
// box would put the window somewhere nobody could reach.
func (w *Window) followDesktop(from, to Rect) {
	if w.maximized {
		w.restore = w.fitRect(w.restore, from, to)
	}
	w.SetBounds(w.fitInto(from, to))
}

// place puts a window at a rectangle and forgets that it was maximised.
//
// A window the desktop has just laid out is no longer filling anything, so its
// box must go back to offering to maximise rather than to restore a rectangle
// that no longer means anything.
func (w *Window) place(r Rect) {
	w.maximized = false
	w.SetBounds(r)
}

// Title returns the window's title.
func (w *Window) Title() string { return w.title }

// SetTitle changes the window's title, as saving under a new name does.
func (w *Window) SetTitle(title string) { w.title = title }

// Number returns the window's position in the desktop, from one, or zero when
// it has none. It is what Alt-1 … Alt-9 select.
func (w *Window) Number() int { return w.number }

// SetNumber records the window's position in the desktop.
func (w *Window) SetNumber(n int) { w.number = n }

// Active reports whether this is the window the keyboard talks to.
func (w *Window) Active() bool { return w.active }

// SetActive marks the window as the focused one, which changes how its frame
// is drawn.
//
// A content widget that can hold the focus is told as well, so that only the
// active window draws a cursor. Without that, every open window would show one
// and none of them would mean anything.
func (w *Window) SetActive(active bool) {
	w.active = active
	if focusable, ok := w.content.(Focusable); ok {
		focusable.SetFocused(active)
	}
}

// Closable reports whether the window shows a close box.
func (w *Window) Closable() bool { return w.closable }

// SetClosable shows or hides the close box.
func (w *Window) SetClosable(closable bool) { w.closable = closable }

// Content returns the widget filling the window's interior.
func (w *Window) Content() Widget { return w.content }

// SetBounds places the window and lays its content out inside the frame.
func (w *Window) SetBounds(r Rect) {
	w.Box.SetBounds(r)
	if w.content != nil {
		w.content.SetBounds(r.Inset(1, 1))
	}
}

// InteriorBounds returns the rectangle inside the frame.
func (w *Window) InteriorBounds() Rect { return w.Bounds().Inset(1, 1) }

// Draw paints the frame, the title bar and the content.
func (w *Window) Draw(p *Painter, th *theme.Theme) {
	bounds := w.Bounds()
	if bounds.W < 2 || bounds.H < 2 {
		return
	}

	DrawShadow(p, bounds, th.Style(theme.KeyShadow))

	frame := p.Sub(bounds)
	frame.Clear(th.Style(theme.KeyWindowBody))
	DrawFrame(frame, frame.Size(), w.frameKind(), th.Style(w.frameStyleKey()))
	w.drawTitleBar(frame, th)
	w.drawNumber(frame, th)

	if w.content != nil {
		w.content.Draw(p.Sub(w.InteriorBounds()), th)
	}
}

// frameKind returns the box-drawing style for the window's current state.
func (w *Window) frameKind() FrameKind {
	if w.active {
		return FrameDouble
	}
	return FrameSingle
}

// frameStyleKey returns the theme key colouring the frame.
func (w *Window) frameStyleKey() string {
	if w.active {
		return theme.KeyWindowFrameActive
	}
	return theme.KeyWindowFrameInactive
}

// titleStyleKey returns the theme key colouring the title.
func (w *Window) titleStyleKey() string {
	if w.active {
		return theme.KeyWindowTitleActive
	}
	return theme.KeyWindowTitleInactive
}

// The two boxes on the top frame. Their widths are counted in **cells**, not
// bytes: the block characters are three bytes each and occupy one column, and
// measuring them with len() was once a real off-by-two.
const (
	// closeBoxLabel closes the window. It sits at the top left, where Turbo
	// Vision put it.
	closeBoxLabel = "[x]"
	// maximizeBoxLabel fills the desktop; restoreBoxLabel puts the window back
	// where it was. Only one is ever drawn, so the box says what pressing it
	// will do rather than what the window currently is.
	maximizeBoxLabel = "[■]"
	restoreBoxLabel  = "[▬]"

	// boxWidth is how many columns any of them takes on screen.
	boxWidth = 3
)

// numberOffset and maximizeOffset are how far from the right edge the window
// number and the maximise box are drawn.
//
// The maximise box occupies the three columns before the corner, and the
// number sits two further left, so the two never touch.
const (
	maximizeOffset = 4
	numberOffset   = 6
)

// Maximized reports whether the window is filling the area it was maximised
// into.
func (w *Window) Maximized() bool { return w.maximized }

// Maximize makes the window fill area, remembering where it was so Restore can
// put it back.
//
// Maximising an already maximised window only moves it to the new area, which
// is what keeps it filling a terminal that has been resized.
//
//	desktop := ui.NewDesktop()
//	w.Maximize(desktop.Bounds())
func (w *Window) Maximize(area Rect) {
	if !w.maximized {
		w.restore = w.Bounds()
		w.maximized = true
	}
	w.SetBounds(area)
}

// Restore puts the window back where it was before Maximize, and does nothing
// to a window that was never maximised.
func (w *Window) Restore() {
	if !w.maximized {
		return
	}
	w.maximized = false
	w.SetBounds(w.restore)
}

// maximizeBoxLabelFor returns the box to draw: the one that says what pressing
// it will do.
func (w *Window) maximizeBoxLabelFor() string {
	if w.maximized {
		return restoreBoxLabel
	}
	return maximizeBoxLabel
}

// drawTitleBar puts the two boxes and the centred title into the top frame.
func (w *Window) drawTitleBar(p *Painter, th *theme.Theme) {
	frameStyle := th.Style(w.frameStyleKey())

	if w.closable && p.Size().W > boxWidth+4 {
		p.Text(2, 0, closeBoxLabel, frameStyle)
	}
	if w.OnMaximize != nil && p.Size().W > numberOffset+boxWidth {
		p.Text(p.Size().W-maximizeOffset, 0, w.maximizeBoxLabelFor(), frameStyle)
	}

	if w.title == "" {
		return
	}

	// The title sits in the middle of the top frame, with a space either side
	// so the box-drawing characters do not touch the letters. Five cells are
	// kept clear on the left — corner, frame, close box — and six on the right
	// for the number, the maximise box and the corner, so the title never runs
	// into any of them. TestTheTitleNeverRunsIntoTheFurniture checks the sum
	// against the offsets rather than trusting this arithmetic.
	const reservedForFurniture = 5 + numberOffset
	available := p.Size().W - reservedForFurniture
	if available < 4 {
		return
	}
	text := " " + w.title + " "
	if len([]rune(text)) > available {
		text = " " + string([]rune(w.title)[:available-3]) + "… "
	}

	x := (p.Size().W - len([]rune(text))) / 2
	p.Text(x, 0, text, th.Style(w.titleStyleKey()))
}

// drawNumber puts the window's number in the top right of the frame, where
// Turbo Vision showed it.
func (w *Window) drawNumber(p *Painter, th *theme.Theme) {
	if w.number < 1 || w.number > 9 || p.Size().W < numberOffset+boxWidth+1 {
		return
	}
	p.Text(p.Size().W-numberOffset, 0, strconv.Itoa(w.number), th.Style(w.frameStyleKey()))
}

// HandleKey passes the key to the content; the window itself has no shortcuts
// of its own, since those belong to the menu bar.
func (w *Window) HandleKey(ev *tcell.EventKey) bool {
	return w.content != nil && w.content.HandleKey(ev)
}

// HandleMouse deals with the frame — closing, moving, resizing — and passes
// anything landing on the interior to the content.
func (w *Window) HandleMouse(ev *tcell.EventMouse) bool {
	if w.drag.mode != dragNone {
		return w.continueDrag(ev)
	}
	if !w.hit(ev) {
		return false
	}

	x, y := ev.Position()
	if w.InteriorBounds().Contains(x, y) {
		return w.content != nil && w.content.HandleMouse(ev)
	}
	if ev.Buttons() != tcell.Button1 {
		return true // a click on the frame, but not one that starts anything
	}
	return w.startFrameAction(x, y)
}

// startFrameAction reacts to a press on the frame: close, resize or move.
func (w *Window) startFrameAction(x, y int) bool {
	bounds := w.Bounds()

	switch {
	case w.closable && y == bounds.Y && w.onCloseBox(x):
		w.requestClose()
	case w.OnMaximize != nil && y == bounds.Y && w.onMaximizeBox(x):
		w.OnMaximize()
	case x == bounds.Right()-1 && y == bounds.Bottom()-1:
		w.beginDrag(dragResize, x, y)
	case y == bounds.Y:
		w.beginDrag(dragMove, x, y)
	}
	return true
}

// onCloseBox reports whether a column falls on the close box.
func (w *Window) onCloseBox(x int) bool {
	start := w.Bounds().X + 2
	return x >= start && x < start+boxWidth
}

// onMaximizeBox reports whether a column falls on the maximise box.
func (w *Window) onMaximizeBox(x int) bool {
	start := w.Bounds().Right() - maximizeOffset
	return x >= start && x < start+boxWidth
}

// requestClose asks the owner to close the window, if it agreed to be asked.
func (w *Window) requestClose() {
	if w.OnClose != nil {
		w.OnClose()
	}
}

// beginDrag records where a move or resize started.
func (w *Window) beginDrag(mode dragMode, x, y int) {
	w.drag = dragState{mode: mode, startX: x, startY: y, origin: w.Bounds()}
}

// continueDrag applies the movement of an in-progress drag and ends it when
// the button comes back up.
func (w *Window) continueDrag(ev *tcell.EventMouse) bool {
	x, y := ev.Position()
	dx, dy := x-w.drag.startX, y-w.drag.startY

	if w.drag.mode == dragMove {
		w.SetBounds(w.drag.origin.Move(dx, dy))
	} else {
		w.SetBounds(w.drag.origin.WithSize(
			max(w.drag.origin.W+dx, MinWindowWidth),
			max(w.drag.origin.H+dy, MinWindowHeight),
		))
	}

	if ev.Buttons() == tcell.ButtonNone {
		w.drag = dragState{}
	}
	return true
}

// Dragging reports whether a move or resize is in progress, which the desktop
// needs in order to keep sending it events that fall outside the window.
func (w *Window) Dragging() bool { return w.drag.mode != dragNone }