package ui import ( "strconv" "github.com/gdamore/tcell/v2" "rickub.com/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 }