gui

package
v0.0.0-...-904f9c7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package gui provides a cross-platform GUI widget toolkit for Go.

It includes 35+ widgets (Button, Label, Edit, CheckBox, Table, Dialog, etc.), a docking window system, theme support (light/dark), and a complete event model.

Platform backends:

  • Windows: Win32 API (native)
  • macOS/Linux: GLFW + OpenGL

Basic usage:

form := gui.NewForm()
form.SetTitle("My App")

btn := gui.NewButton1("Click Me", nil)
btn.SetParent(form)
btn.SetBounds(10, 10, 100, 30)
btn.Action().BindFunc0(func() { fmt.Println("clicked!") })

form.AttachWindow(gui.WtForm)
form.Show()
core.EventLoop()

Index

Constants

View Source
const (
	CikKeyword  = 0
	CikType     = 1
	CikFunction = 2
	CikVariable = 3
)

CompletionItemKind classifies the kind of completion suggestion.

View Source
const (
	SymFunc   = 0
	SymType   = 1
	SymVar    = 2
	SymConst  = 3
	SymMethod = 4
)
View Source
const (
	KeyBackSpace = 0x08

	KeyTab      = 0x09
	KeyEnter    = 0x0D
	KeyShift    = 0x10
	KeyCtrl     = 0x11
	KeyMenu     = 0x12
	KeyPause    = 0x13
	KeyCapsLock = 0x14
	KeyEsc      = 0x1B
	KeySpace    = 0x20

	KeyPageUp   = 0x21
	KeyPageDown = 0x22
	KeyEnd      = 0x23
	KeyHome     = 0x24

	KeyLeft  = 0x25
	KeyUp    = 0x26
	KeyRight = 0x27
	KeyDown  = 0x28

	KeyPrint       = 0x2A
	KeyPrintScreen = 0x2C

	KeyInsert = 0x2D
	KeyDelete = 0x2E

	KeyLWin = 0x5B
	KeyRWin = 0x5C

	KeyNumPad0 = 0x60
	KeyNumPad1 = 0x61
	KeyNumPad2 = 0x62
	KeyNumPad3 = 0x63
	KeyNumPad4 = 0x64
	KeyNumPad5 = 0x65
	KeyNumPad6 = 0x66
	KeyNumPad7 = 0x67
	KeyNumPad8 = 0x68
	KeyNumPad9 = 0x69

	KeyMultiply = 0x6A
	KeyAdd      = 0x6B
	KeySubtract = 0x6D
	KeyDivide   = 0x6F
	KeyDecimal  = 0x6E

	KeyF1  = 0x70
	KeyF2  = 0x71
	KeyF3  = 0x72
	KeyF4  = 0x73
	KeyF5  = 0x74
	KeyF6  = 0x75
	KeyF7  = 0x76
	KeyF8  = 0x77
	KeyF9  = 0x78
	KeyF10 = 0x79
	KeyF11 = 0x7A
	KeyF12 = 0x7B
	KeyF13 = 0x7C
	KeyF14 = 0x7D
	KeyF15 = 0x7E
	KeyF16 = 0x7F

	KeyNumLock    = 0x90
	KeyScrollLock = 0x91

	KeyLShift = 0xA0
	KeyRShift = 0xA1
	KeyLCtrl  = 0xA2
	KeyRCtrl  = 0xA3
	KeyLMenu  = 0xA4
	KeyRMenu  = 0xA5
)
View Source
const (
	ModAction uint8 = 1 << iota // platform "action" modifier (Cmd / Ctrl)
	ModShift
	ModAlt
)

Shortcut modifier flags. Pack into a uint8 for the registry key so ModAction|ModShift addresses Ctrl+Shift+S on Linux/Windows and Cmd+Shift+S on macOS through one entry.

View Source
const (
	TWC_CONTENT  = 0
	TWC_EXPANDER = 1
	TWC_ICON     = 2
	TWC_CHECK    = 3
)
View Source
const (
	TVC_UNCHECKED = 0
	TVC_CHECKED   = 1
	TVC_PARTIAL   = 2
)

复选框的三种状态. TVC_PARTIAL是根据子节点推导出来的中间态, 不接受外部设置.

View Source
const (
	DefultLineEnd = "\r\n"
)

Variables

View Source
var Clipboard clipBoard

Clipboard is the global clipboard object

View Source
var GlobalPerfStats = &PerfStats{lastTime: time.Now()}

GlobalPerfStats is the shared stats singleton. Code elsewhere references it rather than instantiating a new PerfStats — F12 toggles this one.

Functions

func AddToolViewSubMenu

func AddToolViewSubMenu(parentMenu *Menu) (*Menu, *Button)

func AllValid

func AllValid(edits ...*Edit) bool

AllValid reports whether every supplied Edit currently satisfies its validator (see Edit.IsValid). A submit handler calls it to gate a form: keep OK disabled until AllValid(fields...) is true. Nil entries are skipped so callers may pass a sparse slice; zero edits → true.

func AnimationTick

func AnimationTick()

AnimationTick advances all active animations by one frame. Call once per frame from the event loop.

func AppIcon

func AppIcon() paint.Icon

func AttachContextMenu

func AttachContextMenu(widget IWidget, builder func(menu *Menu, x, y float64))

AttachContextMenu attaches a right-click context menu builder to any widget. The builder function is called when the widget receives a right-click event, and is responsible for populating the menu items.

Usage:

gui.AttachContextMenu(myWidget, func(m *Menu, x, y float64) {
    m.AddButton1("Copy", nil).Action().BindFunc0(func() { ... })
    m.AddButton1("Paste", nil).Action().BindFunc0(func() { ... })
})

func BindCheckBox

func BindCheckBox(cb *CheckBox, binding *Binding)

BindCheckBox connects a binding to a CheckBox (two-way).

func BindEdit

func BindEdit(edit *Edit, binding *Binding)

BindEdit connects a binding to an Edit widget (two-way).

func BindLabel

func BindLabel(label *Label, binding *Binding)

BindLabel connects a binding to a Label widget (one-way: binding -> label).

func BindProgressBar

func BindProgressBar(pb *ProgressBar, binding *Binding)

BindProgressBar connects a binding to a ProgressBar (one-way: binding -> progress bar).

func BindSlider

func BindSlider(slider *Slider, binding *Binding)

BindSlider connects a binding to a Slider (two-way).

func BindSpinBox

func BindSpinBox(sp *SpinBox, binding *Binding)

BindSpinBox connects a binding to a SpinBox (two-way).

func BindTag

func BindTag(t *core.Tag, setter func(interface{})) func()

BindTag wraps t and drives setter with every new sample (WrapTag then BindTagValue). setter is primed with the current value immediately and receives the raw payload as interface{} — coerce with TagFloat / TagBool / TagString. The returned func unsubscribes and is idempotent.

setter may fire from the tag's poll goroutine: the host MUST marshal any widget mutation onto the UI thread via gui.Post (see tagbinding.go header).

func BindTagAnimated

func BindTagAnimated(t *core.Tag, setFloat func(float64), dur time.Duration) func()

BindTagAnimated subscribes to t and, on every new sample, EASES the displayed float from its current value to the tag's new Float() over dur, calling setFloat on each animation tick. This is the tag-changed -> animate-property glue: a Tank level or Gauge needle sweeps smoothly to the new setpoint instead of jumping. A sample that arrives mid-ease re-targets from wherever the needle currently is (the previous animation is stopped first), so setFloat never sees two animations fighting over the same widget.

Threading. The tag's subscriber fires on whatever goroutine calls Publish / SetValue — typically a background driver-poll goroutine, NOT the UI thread. Animations touch widget state, which is main-thread-only, so the subscriber marshals the animation setup onto the UI thread via gui.Post; the per-tick setFloat then runs on the UI thread too, because AnimationTick is driven from the event loop. The eased-from value and the live *Animation are therefore only ever read/written inside the posted closure and the OnUpdate tick — both on the UI thread — so they need no lock.

The returned func unsubscribes and is idempotent.

func BindTagEnabled

func BindTagEnabled(tag BindableTag, setEnabled func(bool)) func()

BindTagEnabled subscribes to tag and drives a boolean enabled setter from each sample's truthiness (TagBool). It primes with the current value immediately. The returned func unsubscribes; it is idempotent.

setEnabled may fire from a poll goroutine: the host MUST marshal the widget mutation onto the UI thread via gui.Post (see file header).

func BindTagValue

func BindTagValue(tag BindableTag, setter func(interface{})) func()

BindTagValue subscribes setter to tag and drives it with every new sample. It also invokes setter once with the current value immediately (in addition to any prime the tag itself performs on Subscribe), so a freshly-bound widget paints live data at once. The returned func unsubscribes; it is idempotent.

setter receives the raw tag payload as interface{} — use TagFloat / TagBool / TagString to coerce. The setter may fire from a poll goroutine: the host MUST marshal any widget mutation onto the UI thread via gui.Post (see file header).

func BindTagVisibility

func BindTagVisibility(tag BindableTag, setVisible func(bool)) func()

BindTagVisibility subscribes to tag and drives a boolean visibility setter from each sample's truthiness (TagBool). It primes with the current value immediately. The returned func unsubscribes; it is idempotent.

setVisible may fire from a poll goroutine: the host MUST marshal the widget mutation onto the UI thread via gui.Post (see file header).

func CheckToolTip

func CheckToolTip(xg, yg float64)

CheckToolTip is intended to be called from a mouse idle/stop handler. It checks whether the widget under the mouse has a tooltip and shows it. xg, yg are global (screen) coordinates of the mouse cursor.

func Color

func Color(decls map[string]string, key string) (paint.Color, bool)

Color reads decls[key] as a paint.Color. Hex literals (#RGB, #RGBA, #RRGGBB, #RRGGBBAA) and CSS/中文 named colors are supported, delegating to paint.ParseColor. ok is false for an absent key, a malformed hex literal, or an unrecognised name.

func Confirm

func Confirm(parent IWidget, title, message string) bool

Confirm displays a confirmation dialog with Yes/No buttons. Returns true if the user clicked Yes.

func CountWidgets

func CountWidgets(iw IWidget) int

CountWidgets walks the widget tree rooted at iw and returns the total count (including iw itself). Used by the perf overlay to display a live widget count.

func DbgExportGuiGv

func DbgExportGuiGv(open bool, a ...interface{})

func DesktopArea

func DesktopArea() (x, y, w, h float64)

func DetachContextMenu

func DetachContextMenu(widget IWidget)

DetachContextMenu removes a previously attached context menu builder.

func DockPath

func DockPath(dock IBrick) (ret []int)

获取当前的路径, 以'1','2','3','4'表示上下左右 注: 和普通的二叉树结点路径不同

func DrawWidgetAll

func DrawWidgetAll(ic IWidget, g paint.Painter, tx, ty, cx1, cy1, cw1, ch1 float64)

func EaseInBack

func EaseInBack(t float64) float64

EaseInBack 回退缓入

func EaseInBounce

func EaseInBounce(t float64) float64

EaseInBounce 弹跳缓入

func EaseInCubic

func EaseInCubic(t float64) float64

EaseInCubic 三次缓入

func EaseInElastic

func EaseInElastic(t float64) float64

EaseInElastic 弹性缓入

func EaseInOutBack

func EaseInOutBack(t float64) float64

EaseInOutBack 回退缓入缓出

func EaseInOutCubic

func EaseInOutCubic(t float64) float64

EaseInOutCubic 三次缓入缓出

func EaseInOutQuad

func EaseInOutQuad(t float64) float64

EaseInOutQuad 二次缓入缓出

func EaseInQuad

func EaseInQuad(t float64) float64

EaseInQuad 二次缓入

func EaseLinear

func EaseLinear(t float64) float64

EaseLinear 线性

func EaseOutBack

func EaseOutBack(t float64) float64

EaseOutBack 回退缓出

func EaseOutBounce

func EaseOutBounce(t float64) float64

EaseOutBounce 弹跳缓出

func EaseOutCubic

func EaseOutCubic(t float64) float64

EaseOutCubic 三次缓出

func EaseOutElastic

func EaseOutElastic(t float64) float64

EaseOutElastic 弹性缓出

func EaseOutQuad

func EaseOutQuad(t float64) float64

EaseOutQuad 二次缓出

func EllipsisText

func EllipsisText(s string, maxCharCount int) string

func Float

func Float(decls map[string]string, key string) (float64, bool)

Float reads decls[key] as a float64. A single optional trailing unit token such as "px" or "%" is tolerated (e.g. "12px" -> 12). ok is false for an absent key or an unparseable value.

func GetDbgText

func GetDbgText(o interface{}) string

func GetToolTip

func GetToolTip(w IWidget) string

GetToolTip returns the tooltip text for a widget, or "".

func GitDiff

func GitDiff(filePath string) map[int]GitLineStatus

GitDiff runs "git diff" on the given file and returns per-line status. Lines are 1-based (matching editor display). Returns an empty map if git is not available, the file is not tracked, or parsing fails.

func HasActiveAnimations

func HasActiveAnimations() bool

HasActiveAnimations returns true if any animations or groups are currently running. MainLoop polls this to choose between the 1/60 animation tick and the idle wait, and forces every visible window dirty while it holds — so it has to measure running state, not how many entries happen to be registered. Counting registrations let a single paused (or merely lingering) entry pin the loop at 60fps for the life of the process.

func HideConsoleWindow

func HideConsoleWindow()

func HideToolTip

func HideToolTip()

HideToolTip hides and destroys the current tooltip if any.

func InputNumber

func InputNumber(parent IWidget, title, prompt string, defaultValue float64) (float64, bool)

InputNumber displays a number input dialog with the given title, prompt, and default value. Returns the entered number and true if OK was clicked, or 0 and false if cancelled.

func InputText

func InputText(parent IWidget, title, prompt, defaultValue string) (string, bool)

InputText displays a text input dialog with the given title, prompt, and default value. Returns the entered text and true if OK was clicked, or empty string and false if cancelled.

func Int

func Int(decls map[string]string, key string) (int, bool)

Int reads decls[key] as an int, tolerating the same optional trailing unit as Float. A fractional value (e.g. "1.5") is rejected. ok is false for an absent key or an unparseable value.

func IsKeyDown

func IsKeyDown(key int) bool

func IsMouseLeftDown

func IsMouseLeftDown() bool

func IsMouseRightDown

func IsMouseRightDown() bool

func IsToolTipVisible

func IsToolTipVisible() bool

IsToolTipVisible returns true if a tooltip is currently shown.

func KeyState

func KeyState(key int) (down, checked bool)

func LayoutPopup

func LayoutPopup(popup IWidget, xref, yref, wref, href float64, vertical bool, overlap float64)

func LayoutPopup1

func LayoutPopup1(popup IWidget, xref, yref float64)

func LoadIcon

func LoadIcon(name string) paint.Icon

func LoadSession

func LoadSession(doc *core.TDoc) error

func LoadSessionFile

func LoadSessionFile(path string) error

func MainLoop

func MainLoop()

MainLoop runs the GLFW event loop.

Frame-pacing strategy:

  • SwapInterval(1) is enabled per-window in create(), so SwapBuffers blocks until the next display retrace. On ProMotion / 120Hz / 144Hz displays this adapts to the panel's actual refresh rate instead of a hard 60fps.
  • When the UI is idle (no animations, no live perf overlay) we use a long wait timeout so timers still fire (idle timer = 47ms) and the loop can react to off-thread wake-ups, but the CPU stays asleep most of the time.
  • When animations are running or the perf overlay is live we use the classic ~16ms tick so redraws happen smoothly.

func MemStats

func MemStats() string

MemStats returns a one-line human-readable summary of the current process memory state (live allocation, lifetime allocation, OS-reserved, GC count, goroutine count). Useful for inline logging or perf overlays.

func MemStatsDetailed

func MemStatsDetailed() string

MemStatsDetailed returns a multi-line dump with additional fields useful when chasing leaks: heap objects, mspan/mcache, GC pause stats.

func MmToPixel

func MmToPixel(mmLen float64) (pixelLen float64)

func MmToPixelZ

func MmToPixelZ(mmLen float64) (pixelLen float64)

func MousePosition

func MousePosition() (x, y float64)

func OnMouseMoveToolTip

func OnMouseMoveToolTip()

OnMouseMoveToolTip should be called when the mouse moves to hide the tooltip.

func OpenFileDialog

func OpenFileDialog() string

OpenFileDialog opens a native file dialog and returns the selected file path

func PickThresholdColor

func PickThresholdColor(ranges []ColorRange, value float64) (paint.Color, bool)

PickThresholdColor returns the color of the first ColorRange whose closed interval [Min, Max] contains value, and ok=true. If value falls below every range or above every range (or ranges is empty) it returns ok=false and the zero Color, so callers can leave the widget's color unchanged rather than blank it. Ranges are scanned in order, so overlapping bands resolve to the first match.

func PixelToMm

func PixelToMm(pixelLen float64) (mmLen float64)

func Post

func Post(fn func())

Post enqueues fn to run on the main (event-loop) thread on the next iteration. Safe to call from any goroutine. Use this for every GUI mutation that originates off the main thread (dlv/LSP callbacks, etc).

func PromptSaveClose

func PromptSaveClose(parent IWidget, a interface{}) bool

func PumpTimersForTest

func PumpTimersForTest()

PumpTimersForTest fires every timer that is due, on the calling goroutine, without an event loop.

The two backends time differently — GLFW polls timerMap from the frame loop, Win32 arms a real WM_TIMER and fires from the message pump — so neither mechanism is reachable from a test process, and every test of a debounced behaviour ended up calling the work function directly. That leaves the path from "timer armed" to "work actually ran" driven by nothing: a Start() with the wrong delay, a Stop() in the wrong place or a callback that never re-arms is invisible until a user sees a stale view.

This is the seam. It does not advance real time — it declares every armed timer due and runs it, which is what a test wants: waiting out a 200ms debounce in a unit test buys nothing but 200ms. A test arms the behaviour it is exercising, calls this, and asserts on the effect rather than on the arming.

func QuitLoop

func QuitLoop()

func RegisterShortcut

func RegisterShortcut(mods uint8, key int, fn func())

RegisterShortcut binds (mods, key) to fn. Subsequent registrations for the same (mods, key) overwrite — silkide-style apps only need the last binding to take effect when reconfiguring at runtime.

Pass nil fn to unregister. The fn runs on the GLFW event-loop goroutine, same as widget OnKeyDown.

Modifiers are abstracted across platforms: ModAction is Cmd on macOS, Ctrl elsewhere. Shortcuts that use raw KeyCtrl / KeyLWin directly should still go through widget-level OnKeyDown.

func RegisterToolView

func RegisterToolView(info ToolViewDef) error

注册工具视图

func RenameInFile

func RenameInFile(text, oldName, newName string) string

RenameInFile renames all occurrences of oldName to newName in the given text. It only renames whole-word matches (not substrings), where word boundaries are defined by Go identifier rules.

func RenameSymbol

func RenameSymbol(src, oldName, newName string) (string, error)

RenameSymbol returns src with every occurrence of identifier oldName (declarations and uses alike) replaced by newName, using go/parser + go/ast so that comments, string literals, and import paths are left untouched.

Validation:

  • newName must be a valid Go identifier (see isGoIdent); otherwise an error is returned and src is unchanged.
  • oldName == newName is a no-op and returns src, nil.
  • If src does not parse, the original src is returned along with the parse error so the caller can surface it (no panic).
  • If newName already exists as a top-level declaration in src and differs from oldName, the rename is rejected to avoid silently shadowing or duplicating package-level symbols.

Known limitation (name-based, not scope-aware): this rewrites EVERY identifier whose Name == oldName in the file. It does not distinguish between two unrelated local variables in different functions that happen to share a name, nor between a field selector and a same-named variable. A fully scope-aware rename (using go/types) is intentionally out of scope here and would be a separate, larger change; tests below pin the current behaviour so any future upgrade surfaces as a deliberate breaking change.

func RenameSymbolCount

func RenameSymbolCount(src, oldName, newName string) (int, string, error)

RenameSymbolCount is the companion of RenameSymbol that also returns how many identifiers were rewritten (useful for "renamed N occurrences" status messages in an editor). Validation and limitations are identical.

func SaveFileDialog

func SaveFileDialog() string

SaveFileDialog opens a native save dialog and returns the selected file path

func SaveForm

func SaveForm(form *Form, filename string) error

SaveForm writes a Form's current widget hierarchy to a .silkui file using the same TDoc dialect that GedScene.SaveDesign produces, so files written here round-trip cleanly through LoadForm and through the visual designer.

The output format is intentionally compatible with existing .cml designs: each widget node stores its factory name as the node value, its bounds under the "bounds" attribute (as a geom.Rect), and its children in a "children" sub-node.

If the supplied filename has no extension, the default .silkui extension is appended automatically.

func SaveSession

func SaveSession() (*core.TDoc, error)

func SaveSessionFile

func SaveSessionFile(path string) error

func ScreenDpi

func ScreenDpi() float64

func ScreenDpmm

func ScreenDpmm() float64

func SetAppIcon

func SetAppIcon(icon paint.Icon)

func SetCursor

func SetCursor(p *Cursor)

func SetDefaultFrame

func SetDefaultFrame(p *Frame)

指定默认框架 打开文档, 显示视图时, 如果没有指定框架, 则放到默认框架中

func SetThemeMode

func SetThemeMode(mode ThemeMode)

SetThemeMode switches between light and dark themes.

func SetToolTip

func SetToolTip(w IWidget, text string)

SetToolTip associates tooltip text with a widget. Pass an empty string to remove the tooltip.

func SetUIWakeup

func SetUIWakeup(fn func())

SetUIWakeup installs the wakeup hook (called once by the window layer).

func ShortcutHandler

func ShortcutHandler(mods uint8, key int) func()

ShortcutHandler returns the fn bound to (mods, key), or nil when the combination is unbound. The registry is otherwise only reachable through a real key event — which needs a window and the modifier physically held — so this is how a caller confirms which action a key actually carries.

func ShowConfirmDialog

func ShowConfirmDialog(parent IWidget, title, message string) bool

ShowConfirmDialog displays a confirmation dialog with Yes/No buttons. Returns true if the user clicked Yes.

func ShowConsoleWindow

func ShowConsoleWindow()

func ShowContextMenu

func ShowContextMenu(widget IWidget, x, y float64, builder func(menu *Menu))

ShowContextMenu creates a popup menu at the given widget-local coordinates, calls the builder to populate it, then shows it as a popup.

func ShowInputBox

func ShowInputBox(parent IWidget, icon paint.Icon, title, label, defText string) (string, bool)

ShowInputBox displays a styled input dialog.

func ShowInputDialog

func ShowInputDialog(parent IWidget, title, prompt, defaultVal string) (string, bool)

ShowInputDialog displays an input dialog with a text field. Returns the entered text and true if the user clicked OK, or empty string and false if cancelled.

func ShowMessageBox

func ShowMessageBox(iw IWidget, ico paint.Icon, title, content string, btns []string) string

ShowMessageBox displays a styled message box dialog.

func ShowToast

func ShowToast(parent IWidget, message string, durationMs uint32, level ToastLevel)

ShowToast displays a temporary toast notification message at the top center of the parent widget's window. The toast auto-dismisses after the given number of milliseconds.

func ShowToolTip

func ShowToolTip(xg, yg float64, text string)

ShowToolTip displays a tooltip at global coordinates (xg, yg).

func SortActions

func SortActions(a []IAction)

func StartCPUProfile

func StartCPUProfile(filename string) error

StartCPUProfile begins recording a Go pprof CPU profile to filename. Call StopCPUProfile() to stop and flush the profile to disk. Calling StartCPUProfile while a profile is already running returns an error from runtime/pprof.

func StopCPUProfile

func StopCPUProfile()

StopCPUProfile stops the current CPU profile and flushes any buffered data. Safe to call when no profile is active (no-op).

func SymbolKindColor

func SymbolKindColor(kind int) paint.Color

SymbolKindColor returns the color for a symbol kind label (exported).

func SymbolKindLabel

func SymbolKindLabel(kind int) string

SymbolKindLabel returns a short display label for a symbol kind (exported).

func TagBool

func TagBool(v interface{}) bool

TagBool coerces a raw tag payload to bool: a bool directly, otherwise any nonzero numeric. A whole scada.Value is accepted structurally via its Bool() method.

func TagFloat

func TagFloat(v interface{}) float64

TagFloat coerces a raw tag payload to float64 for the common cases (float64/float32, int/int64/int32, bool -> 1/0). A whole scada.Value is accepted structurally via its Float() method. Anything else yields 0.

func TagString

func TagString(v interface{}) string

TagString coerces a raw tag payload to string: a string directly, nil to "", a fmt.Stringer (including a whole scada.Value) via String(), otherwise fmt.Sprint.

func Theme

func Theme() *defaultTheme

GUI风格(待改进)

func ThemeRev

func ThemeRev() uint64

ThemeRev returns the current theme revision counter. Caches that depend on theme-derived values should capture this and re-validate by comparison.

func ThresholdColorBinding

func ThresholdColorBinding(tag BindableTag, ranges []ColorRange, setColor func(paint.Color)) func()

ThresholdColorBinding subscribes to tag, coerces each sample to float64, and calls setColor with the matching band's color (see PickThresholdColor). It primes setColor with the current value immediately. When a sample falls outside every range setColor is NOT called, leaving the last color in place. The returned func unsubscribes; it is idempotent.

setColor may fire from a poll goroutine: the host MUST marshal the widget repaint onto the UI thread via gui.Post (see file header).

func TryContextMenu

func TryContextMenu(widget IWidget, x, y float64) bool

TryContextMenu attempts to show a context menu for the given widget. It first checks for a registered builder, then checks if the widget implements IContextMenuProvider. Returns true if a menu was shown.

func TypeOf

func TypeOf(i interface{}) reflect.Type

此函数功能同reflect.TypeOf, 放在这里是为了便于使用

func WriteHeapProfile

func WriteHeapProfile(filename string) error

WriteHeapProfile triggers a GC and writes the current heap profile to filename. Use for one-shot allocation snapshots.

Types

type Accordion

type Accordion struct {
	Widget
	// contains filtered or unexported fields
}

Accordion 手风琴/折叠面板控件

func NewAccordion

func NewAccordion() *Accordion

func (*Accordion) AddSection

func (this *Accordion) AddSection(title string, content IWidget)

func (*Accordion) Draw

func (this *Accordion) Draw(g paint.Painter)

func (*Accordion) EnumProperties

func (this *Accordion) EnumProperties(list core.IPropertyList)

func (*Accordion) Init

func (this *Accordion) Init(self IWidget)

Init carries the geometry and the sentinels, not NewAccordion: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A zero headerH makes every header a zero-height strip — hitTestHeader then matches nothing and no section can ever be opened by a click.

func (*Accordion) Layout

func (this *Accordion) Layout()

func (*Accordion) MultiExpand

func (this *Accordion) MultiExpand() bool

func (*Accordion) OnKeyDown

func (this *Accordion) OnKeyDown(key int, repeat bool)

OnKeyDown 实现 IEventKeyDown, 给折叠面板加键盘导航(对标 Qt QAccordion 风格): Up/Down 移动当前 header, Home/End 跳到首/末区段, 回车/空格 切换当前区段的 展开/折叠 — 走与点击相同的 ToggleSection, 因此单展开/多展开语义与回调都一致. 仅在控件持有焦点时被调用(OnLeftDown 里 SetFocus 后才能收到键盘事件).

func (*Accordion) OnLeftDown

func (this *Accordion) OnLeftDown(x, y float64)

func (*Accordion) OnMouseEnter

func (this *Accordion) OnMouseEnter()

func (*Accordion) OnMouseLeave

func (this *Accordion) OnMouseLeave()

func (*Accordion) OnMouseMove

func (this *Accordion) OnMouseMove(x, y float64)

func (*Accordion) SectionCount

func (this *Accordion) SectionCount() int

func (*Accordion) SetMultiExpand

func (this *Accordion) SetMultiExpand(b bool)

func (*Accordion) SigExpand

func (this *Accordion) SigExpand(fn func(int, bool))

func (*Accordion) SizeHints

func (this *Accordion) SizeHints() SizeHints

func (*Accordion) ToggleSection

func (this *Accordion) ToggleSection(idx int)

type AccordionSection

type AccordionSection struct {
	Title    string
	Content  IWidget
	Expanded bool
}

AccordionSection 折叠面板的单个区段

type Action

type Action struct {
	// contains filtered or unexported fields
}

Action 是按钮/菜单等命令的抽象

func NewAction

func NewAction() *Action

func NewAction1

func NewAction1(txt string, icon paint.Icon) *Action

func (*Action) BindAction

func (this *Action) BindAction(a IAction)

func (*Action) BindFunc

func (this *Action) BindFunc(fn func(IAction, interface{}))

func (*Action) BindFunc0

func (this *Action) BindFunc0(fn func())

func (*Action) BindFunc1

func (this *Action) BindFunc1(fn func(IAction))

func (*Action) Extra

func (this *Action) Extra() interface{}

func (*Action) Icon

func (this *Action) Icon() paint.Icon

func (*Action) IsChecked

func (this *Action) IsChecked() bool

func (*Action) IsEnabled

func (this *Action) IsEnabled() bool

func (*Action) MTime

func (this *Action) MTime() time.Time

func (*Action) ObjName

func (this *Action) ObjName() string

func (*Action) Rev

func (this *Action) Rev() uint64

Rev is the change counter for cache keys. Bound actions fold both sides in: either one advancing changes the sum, which is all a key needs.

func (*Action) SetChecked

func (this *Action) SetChecked(b bool)

func (*Action) SetEnabled

func (this *Action) SetEnabled(b bool)

func (*Action) SetExtra

func (this *Action) SetExtra(a interface{})

func (*Action) SetIcon

func (this *Action) SetIcon(icon paint.Icon)

func (*Action) SetObjName

func (this *Action) SetObjName(objname string)

func (*Action) SetText

func (this *Action) SetText(text string)

func (*Action) Text

func (this *Action) Text() string

Text returns the action's display text, or the empty string when no text has been set. Earlier versions returned the literal "<EMPTY>" placeholder for empty text — that propagated through Button.Text(), which made Button.IsTextVisible report true for icon-only buttons, which in turn made ToolBar.layoutHorizontal lay out icon-only buttons using the wide text-aware formula (~105 px each instead of 36 px). The result was icon buttons spread far apart on the silkide toolbar. Returning "" lets the icon-only branches fire correctly throughout the widget stack.

func (*Action) Trigger

func (this *Action) Trigger(sender interface{})

type AlarmPanel

type AlarmPanel struct {
	Widget
	// contains filtered or unexported fields
}

AlarmPanel is a live operator alarm list for SCADA / 组态 screens: a scrollable list of a core.AlarmDB's active alarms, one row per tag, showing the severity (colour + label), tag, value, "active since" time and an ACK affordance. The host feeds an already-ordered snapshot via SetAlarms (or wires a live AlarmDB with BindAlarmDB); the panel does not re-sort, so the db's unacked-first / most-severe-first / oldest-first ordering shows through.

It is deliberately UI-only: acknowledging is not done here. A click on a row's ACK affordance fires SigAckRequested(tag); the host calls db.Ack(tag), which raises a transition the bound panel then re-reads. This keeps the panel a pure view and leaves the ack lifecycle in the (thread-safe) db.

func NewAlarmPanel

func NewAlarmPanel() *AlarmPanel

NewAlarmPanel creates an empty alarm panel.

func (*AlarmPanel) Alarms

func (this *AlarmPanel) Alarms() []core.AlarmState

Alarms returns a defensive copy of the displayed alarms in display order.

func (*AlarmPanel) BindAlarmDB

func (this *AlarmPanel) BindAlarmDB(db *core.AlarmDB) func()

BindAlarmDB wires the panel to db as a live view: it seeds the panel with db.Active() and subscribes for every future transition. AlarmDB subscribers fire on whatever goroutine drove the transition (a driver-poll goroutine, not the UI thread), so the callback marshals the refresh onto the event-loop thread via Post before touching the panel — mirroring the tag bindings. The returned func unsubscribes and is idempotent (it wraps the db's CancelFunc).

func (*AlarmPanel) Draw

func (this *AlarmPanel) Draw(g paint.Painter)

Draw renders a count header followed by one row per active alarm.

func (*AlarmPanel) Init

func (this *AlarmPanel) Init(self IWidget)

func (*AlarmPanel) OnLeftDown

func (this *AlarmPanel) OnLeftDown(x, y float64)

OnLeftDown fires SigAckRequested when the click lands in an unacked row's ACK column. Clicks elsewhere on a row, on the header, or past the last row are ignored.

func (*AlarmPanel) OnMouseWheel

func (this *AlarmPanel) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the row list vertically.

func (*AlarmPanel) SetAlarms

func (this *AlarmPanel) SetAlarms(in []core.AlarmState)

SetAlarms replaces the displayed alarm list with a defensive copy of in. AlarmState is a value type, so the shallow copy fully isolates the panel from later mutation of the caller's slice. The caller is expected to pass an already-ordered snapshot (typically AlarmDB.Active()); the panel renders it verbatim. The scroll offset is clamped to the new content rather than reset, so a live refresh does not yank the operator's view back to the top.

func (*AlarmPanel) SigAckRequested

func (this *AlarmPanel) SigAckRequested(fn func(tag string))

SigAckRequested registers the callback fired when the operator clicks a row's ACK affordance. It receives the alarm's tag; the host acknowledges by calling db.Ack(tag). Already-acked rows do not fire.

func (*AlarmPanel) SizeHints

func (this *AlarmPanel) SizeHints() SizeHints

type Alert

type Alert struct {
	Widget
	// contains filtered or unexported fields
}

Alert 内联提示横幅控件,在布局中常驻显示一条带级别和图标的状态信息。 与 Toast 不同:Toast 是浮层、定时自动消失;Alert 固定在布局里作为状态提示, 可选标题、可选关闭按钮。

func NewAlert

func NewAlert(level AlertLevel, message string) *Alert

NewAlert creates an inline message banner at the given level with the supplied message text. Title and the close button are off by default.

func (*Alert) Draw

func (this *Alert) Draw(g paint.Painter)

func (*Alert) EnumProperties

func (this *Alert) EnumProperties(list core.IPropertyList)

func (*Alert) IsCloseable

func (this *Alert) IsCloseable() bool

func (*Alert) Level

func (this *Alert) Level() AlertLevel

func (*Alert) Message

func (this *Alert) Message() string

func (*Alert) OnLeftDown

func (this *Alert) OnLeftDown(x, y float64)

func (*Alert) SetCloseable

func (this *Alert) SetCloseable(b bool)

func (*Alert) SetLevel

func (this *Alert) SetLevel(l AlertLevel)

func (*Alert) SetMessage

func (this *Alert) SetMessage(s string)

func (*Alert) SetTitle

func (this *Alert) SetTitle(s string)

func (*Alert) SigClose

func (this *Alert) SigClose(fn func())

SigClose sets the callback fired when the user clicks the × button. The alert hides itself before the callback runs.

func (*Alert) SizeHints

func (this *Alert) SizeHints() SizeHints

func (*Alert) Title

func (this *Alert) Title() string

type AlertLevel

type AlertLevel int

AlertLevel represents the severity level of an Alert banner. It mirrors the four-level scheme used by Toast (info / success / warning / error) so the visual language stays consistent across transient and inline messages.

const (
	AlertInfo    AlertLevel = iota // Blue
	AlertSuccess                   // Green
	AlertWarning                   // Amber
	AlertError                     // Red
)

type Anchor

type Anchor struct {
	Flags        AnchorFlag
	LeftOffset   float64
	RightOffset  float64
	TopOffset    float64
	BottomOffset float64
}

type AnchorFlag

type AnchorFlag int
const (
	AnchorLef    AnchorFlag = 1
	AnchorRight  AnchorFlag = 2
	AnchorTop    AnchorFlag = 4
	AnchorBottom AnchorFlag = 8
)

type AnimGroupMode

type AnimGroupMode int

AnimationGroup 动画组,可并行或串行运行多个动画

const (
	AnimParallel   AnimGroupMode = iota // 并行
	AnimSequential                      // 串行
)

type Animation

type Animation struct {
	// contains filtered or unexported fields
}

Animation 属性动画,支持任意浮点值从 A 到 B 的过渡

func FadeIn

func FadeIn(widget IWidget, duration time.Duration) *Animation

FadeIn 创建淡入动画

func FadeOut

func FadeOut(widget IWidget, duration time.Duration) *Animation

FadeOut 创建淡出动画

func NewAnimation

func NewAnimation(from, to float64, duration time.Duration) *Animation

NewAnimation creates a property animation that transitions a float64 value from 'from' to 'to' over the given duration. Uses EaseOutCubic by default.

func Pulse

func Pulse(widget IWidget, scale float64, duration time.Duration) *Animation

Pulse 创建脉冲动画 (循环缩放)

func ScaleUp

func ScaleUp(widget IWidget, duration time.Duration) *Animation

ScaleUp 创建缩放动画

func Shake

func Shake(widget IWidget, amplitude float64, duration time.Duration) *Animation

Shake 创建抖动动画

func (*Animation) OnDone

func (a *Animation) OnDone(fn func()) *Animation

OnDone registers a callback invoked when the animation completes.

func (*Animation) OnUpdate

func (a *Animation) OnUpdate(fn func(float64)) *Animation

OnUpdate registers a callback invoked on each animation tick with the current interpolated value.

func (*Animation) Pause

func (a *Animation) Pause()

Pause suspends a running animation, preserving its current progress.

func (*Animation) Resume

func (a *Animation) Resume()

Resume continues a paused animation from where it left off.

func (*Animation) SetEase

func (a *Animation) SetEase(fn EaseFunc) *Animation

SetEase sets the easing function used to interpolate the animation progress.

func (*Animation) SetLoop

func (a *Animation) SetLoop(b bool) *Animation

SetLoop enables or disables continuous looping of the animation.

func (*Animation) SetReverse

func (a *Animation) SetReverse(b bool) *Animation

SetReverse enables ping-pong mode, swapping from/to on each loop iteration.

func (*Animation) Start

func (a *Animation) Start()

Start begins the animation, registering it with the global animation manager.

func (*Animation) State

func (a *Animation) State() AnimationState

State returns the current animation state (idle, running, paused, or done).

func (*Animation) Stop

func (a *Animation) Stop()

Stop terminates the animation immediately and unregisters it. Marking it AnimDone is not enough on its own: the manager only evicts on Tick, and the loop only Ticks while something is still moving, so a stopped animation could otherwise stay registered — holding its onUpdate closure, and the widget that closure captured — forever.

func (*Animation) Value

func (a *Animation) Value() float64

Value returns the current interpolated animation value.

type AnimationGroup

type AnimationGroup struct {
	// contains filtered or unexported fields
}

func NewAnimationGroup

func NewAnimationGroup(mode AnimGroupMode) *AnimationGroup

NewAnimationGroup creates a group that runs multiple animations in parallel or sequentially.

func SlideIn

func SlideIn(widget IWidget, fromX, fromY, toX, toY float64, duration time.Duration) *AnimationGroup

SlideIn 创建滑入动画 (从 offset 滑到 target)

func (*AnimationGroup) Add

Add appends an animation to the group.

func (*AnimationGroup) OnDone

func (g *AnimationGroup) OnDone(fn func()) *AnimationGroup

OnDone registers a callback invoked when all animations in the group complete.

func (*AnimationGroup) Start

func (g *AnimationGroup) Start()

Start begins all animations in the group according to its mode (parallel or sequential).

type AnimationState

type AnimationState int

AnimationState 动画状态

const (
	AnimIdle AnimationState = iota
	AnimRunning
	AnimPaused
	AnimDone
)

type Avatar

type Avatar struct {
	Widget
	// contains filtered or unexported fields
}

Avatar 头像控件,显示图片或文字首字母

func NewAvatar

func NewAvatar() *Avatar

func (*Avatar) AvatarSize

func (this *Avatar) AvatarSize() float64

func (*Avatar) Draw

func (this *Avatar) Draw(g paint.Painter)

func (*Avatar) EnumProperties

func (this *Avatar) EnumProperties(list core.IPropertyList)

func (*Avatar) Init

func (this *Avatar) Init(self IWidget)

Init carries the defaults, not NewAvatar: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A zero size makes SizeHints 0x0 and collapses the avatar to a point.

func (*Avatar) Pixmap

func (this *Avatar) Pixmap() paint.Pixmap

func (*Avatar) SetAvatarSize

func (this *Avatar) SetAvatarSize(s float64)

func (*Avatar) SetBgColor

func (this *Avatar) SetBgColor(c paint.Color)

func (*Avatar) SetPixmap

func (this *Avatar) SetPixmap(pm paint.Pixmap)

func (*Avatar) SetShape

func (this *Avatar) SetShape(s AvatarShape)

func (*Avatar) SetText

func (this *Avatar) SetText(s string)

func (*Avatar) Shape

func (this *Avatar) Shape() AvatarShape

func (*Avatar) SizeHints

func (this *Avatar) SizeHints() SizeHints

func (*Avatar) Text

func (this *Avatar) Text() string

type AvatarShape

type AvatarShape int

AvatarShape 头像形状

const (
	AvatarCircle AvatarShape = iota
	AvatarSquare
)

type Badge

type Badge struct {
	Widget
	// contains filtered or unexported fields
}

Badge 徽标控件,显示数字或小红点

func NewBadge

func NewBadge() *Badge

func (*Badge) AddWidget

func (this *Badge) AddWidget(iw IWidget)

func (*Badge) Content

func (this *Badge) Content() IWidget

func (*Badge) Count

func (this *Badge) Count() int

func (*Badge) Draw

func (this *Badge) Draw(g paint.Painter)

Draw paints nothing. The framework's order is Draw, then the children, then DrawOverlay, and Layout hands the content child the whole widget rect — a marker drawn here disappears the moment the content paints anything opaque over that corner. Overriding Draw is still required: Widget.Draw puts a debug error cross on any widget that doesn't.

func (*Badge) DrawOverlay

func (this *Badge) DrawOverlay(g paint.Painter)

DrawOverlay paints the count pill / dot above the content child.

func (*Badge) EnumProperties

func (this *Badge) EnumProperties(list core.IPropertyList)

func (*Badge) Init

func (this *Badge) Init(self IWidget)

Init carries the defaults, not NewBadge: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A zero maxCount also turns every count into "0+".

func (*Badge) IsDot

func (this *Badge) IsDot() bool

func (*Badge) Layout

func (this *Badge) Layout()

func (*Badge) MaxCount

func (this *Badge) MaxCount() int

func (*Badge) SetColor

func (this *Badge) SetColor(c paint.Color)

func (*Badge) SetContent

func (this *Badge) SetContent(w IWidget)

func (*Badge) SetCount

func (this *Badge) SetCount(n int)

func (*Badge) SetDot

func (this *Badge) SetDot(b bool)

func (*Badge) SetMaxCount

func (this *Badge) SetMaxCount(n int)

func (*Badge) SizeHints

func (this *Badge) SizeHints() SizeHints

type BarChart

type BarChart struct {
	Widget
	// contains filtered or unexported fields
}

BarChart renders vertical or horizontal bars.

func NewBarChart

func NewBarChart() *BarChart

NewBarChart creates a ready-to-use BarChart widget.

func (*BarChart) AddBar

func (this *BarChart) AddBar(label string, value float64, color paint.Color)

AddBar appends a bar.

func (*BarChart) AutoScale

func (this *BarChart) AutoScale() bool

AutoScale reports whether auto-scaling is active.

func (*BarChart) ClearBars

func (this *BarChart) ClearBars()

ClearBars removes all bars.

func (*BarChart) Draw

func (this *BarChart) Draw(g paint.Painter)

Draw renders the bar chart.

func (*BarChart) EnumProperties

func (this *BarChart) EnumProperties(list core.IPropertyList)

EnumProperties exposes inspectable properties.

func (*BarChart) Horizontal

func (this *BarChart) Horizontal() bool

Horizontal reports bar orientation.

func (*BarChart) Init

func (this *BarChart) Init(self IWidget)

Init carries the scale and the display defaults, not NewBarChart: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Left in the constructor, maxValue comes up as 0 with auto-scaling off, so AddBar never reseeds it and Draw divides by the maxV == 0 fallback of 1 — every bar is drawn its own value in pixels tall and paints straight over the rest of the form.

func (*BarChart) SetAutoScale

func (this *BarChart) SetAutoScale(b bool)

SetAutoScale enables or disables auto scaling of the value axis.

func (*BarChart) SetHorizontal

func (this *BarChart) SetHorizontal(b bool)

SetHorizontal switches between vertical and horizontal bars.

func (*BarChart) SetMaxValue

func (this *BarChart) SetMaxValue(v float64)

SetMaxValue manually sets the maximum value axis.

func (*BarChart) SetShowValues

func (this *BarChart) SetShowValues(b bool)

SetShowValues controls value label drawing.

func (*BarChart) SetTitle

func (this *BarChart) SetTitle(s string)

SetTitle sets the chart title.

func (*BarChart) ShowValues

func (this *BarChart) ShowValues() bool

ShowValues reports whether value labels are drawn.

func (*BarChart) SizeHints

func (this *BarChart) SizeHints() SizeHints

SizeHints returns the preferred size.

func (*BarChart) Title

func (this *BarChart) Title() string

Title returns the current title.

type BarChartItem

type BarChartItem struct {
	Label string
	Value float64
	Color paint.Color
}

BarChartItem represents a single bar.

type BindableTag

type BindableTag interface {
	// Subscribe registers fn for every future sample and returns an
	// idempotent unsubscribe func.
	Subscribe(func(interface{})) func()
	// Value returns the latest sample.
	Value() interface{}
}

BindableTag is the structural contract a real-time tag satisfies. Defined locally so gui need not import the (UI-agnostic, parallel) tag package. See the file header for the seam and the scada->gui bridge that adapts the concrete tag onto it.

func WrapTag

func WrapTag(t *core.Tag) BindableTag

WrapTag adapts a concrete *core.Tag to gui.BindableTag so it can drive the binding helpers in tagbinding.go (BindTagValue / ThresholdColorBinding / ...).

type Binding

type Binding struct {
	// contains filtered or unexported fields
}

Binding represents a connection between a data source and a widget property. It holds a value and notifies registered watchers when the value changes.

func NewBinding

func NewBinding(initial interface{}) *Binding

NewBinding creates a new data binding with an initial value.

func (*Binding) Get

func (b *Binding) Get() interface{}

Get returns the current value.

func (*Binding) GetBool

func (b *Binding) GetBool() bool

GetBool returns the value as bool.

func (*Binding) GetFloat

func (b *Binding) GetFloat() float64

GetFloat returns the value as float64.

func (*Binding) GetInt

func (b *Binding) GetInt() int

GetInt returns the value as int.

func (*Binding) GetString

func (b *Binding) GetString() string

GetString returns the value as string.

func (*Binding) Set

func (b *Binding) Set(v interface{})

Set updates the value and notifies all watchers. It guards against recursive calls caused by two-way bindings.

func (*Binding) Watch

func (b *Binding) Watch(fn func(interface{}))

Watch adds a callback that fires when the value changes.

type Breadcrumb struct {
	Widget
	// contains filtered or unexported fields
}

Breadcrumb 面包屑导航控件

func NewBreadcrumb

func NewBreadcrumb() *Breadcrumb
func (this *Breadcrumb) AddItem(text string, data interface{})
func (this *Breadcrumb) Draw(g paint.Painter)
func (this *Breadcrumb) EnumProperties(list core.IPropertyList)
func (this *Breadcrumb) Init(self IWidget)

Init carries the separator and the hover sentinel, not NewBreadcrumb: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. An empty separator draws the trail as "home docs" with nothing between the items.

func (this *Breadcrumb) Items() []BreadcrumbItem
func (this *Breadcrumb) OnLeftDown(x, y float64)
func (this *Breadcrumb) OnMouseEnter()
func (this *Breadcrumb) OnMouseLeave()
func (this *Breadcrumb) OnMouseMove(x, y float64)
func (this *Breadcrumb) Separator() string
func (this *Breadcrumb) SetItems(items []BreadcrumbItem)
func (this *Breadcrumb) SetSeparator(s string)
func (this *Breadcrumb) SigClick(fn func(int, BreadcrumbItem))
func (this *Breadcrumb) SizeHints() SizeHints
type BreadcrumbItem struct {
	Text string
	Data interface{}
}

BreadcrumbItem 面包屑项

type Brick

type Brick struct {
	// contains filtered or unexported fields
}

Brick是Frame里的分格方块 (原为Tile, 但Tile和Title容易搞混)

func (*Brick) Bounds

func (this *Brick) Bounds() (x, y, w, h float64)

func (*Brick) Bounds1

func (this *Brick) Bounds1() geom.Rect

func (*Brick) ContainMainDock

func (this *Brick) ContainMainDock() bool

func (*Brick) Detach

func (_this *Brick) Detach()

func (*Brick) DropRect

func (this *Brick) DropRect(split float64, left, vert, merge bool) (xd, yd, wd, hd float64)

func (*Brick) DropSplitHint

func (this *Brick) DropSplitHint(xp, yp float64) (split float64, left, vert, merge bool)

假设在xp,yp位置drop一个dock, 判断是否分割, 以及分割的方向和位置

func (*Brick) ExportGv

func (this *Brick) ExportGv(g *gv.Graph)

func (*Brick) FindSplitter

func (this *Brick) FindSplitter(x, y float64) IBrick

func (*Brick) Frame

func (this *Brick) Frame() *Frame

func (*Brick) IsLeftVisible

func (this *Brick) IsLeftVisible() bool

func (*Brick) IsRightVisible

func (this *Brick) IsRightVisible() bool

func (*Brick) IsVertical

func (this *Brick) IsVertical() bool

func (*Brick) IsVisible

func (this *Brick) IsVisible() bool

func (*Brick) Layout

func (this *Brick) Layout()

func (*Brick) Left

func (this *Brick) Left() IBrick

func (*Brick) LeftContainMainDock

func (this *Brick) LeftContainMainDock() bool

func (*Brick) LoadTDoc

func (this *Brick) LoadTDoc(doc *core.TDoc)

func (*Brick) ParentBrick

func (this *Brick) ParentBrick() IBrick

func (*Brick) Right

func (this *Brick) Right() IBrick

func (*Brick) RightContainMainDock

func (this *Brick) RightContainMainDock() bool

func (*Brick) SaveTDoc

func (this *Brick) SaveTDoc() *core.TDoc

func (*Brick) SelfBrick

func (this *Brick) SelfBrick() IBrick

func (*Brick) SetBounds

func (this *Brick) SetBounds(x, y, w, h float64)

func (*Brick) SetBounds1

func (this *Brick) SetBounds1(rc geom.Rect)

func (*Brick) SetLeft

func (this *Brick) SetLeft(t IBrick)

func (*Brick) SetRight

func (this *Brick) SetRight(t IBrick)

func (*Brick) SetSplit

func (this *Brick) SetSplit(split float64)

func (*Brick) SetSplitPoint

func (this *Brick) SetSplitPoint(x, y float64)

func (*Brick) SetVertical

func (this *Brick) SetVertical(vert bool)

func (*Brick) Sibling

func (_this *Brick) Sibling() IBrick

func (*Brick) SizeHints

func (this *Brick) SizeHints() SizeHints

func (*Brick) Split

func (_this *Brick) Split(t IBrick, split float64, left, vert bool)

func (*Brick) SplitNewDock

func (this *Brick) SplitNewDock(left, vert bool) IDock

type Button

type Button struct {
	Widget
	// contains filtered or unexported fields
}

按钮, 含普通按钮, 菜单项, 下拉按钮等

func NewActionButton

func NewActionButton(a IAction) *Button

func NewButton

func NewButton() *Button

func NewButton1

func NewButton1(s string, icon paint.Icon) *Button

func (*Button) Action

func (this *Button) Action() IAction

func (*Button) Draw

func (this *Button) Draw(g paint.Painter)

func (*Button) EnumProperties

func (this *Button) EnumProperties(list core.IPropertyList)

func (*Button) ExportGv

func (this *Button) ExportGv(g *gv.Graph)

func (*Button) HideSubPopup

func (this *Button) HideSubPopup()

func (*Button) Icon

func (this *Button) Icon() paint.Icon

func (*Button) IconName

func (this *Button) IconName() string

func (*Button) IsChecked

func (this *Button) IsChecked() bool

func (*Button) IsDefault

func (this *Button) IsDefault() bool

func (*Button) IsEnabled

func (this *Button) IsEnabled() bool

func (*Button) IsIconVisible

func (this *Button) IsIconVisible() bool

func (*Button) IsInPopupMenu

func (this *Button) IsInPopupMenu() bool

func (*Button) IsPushed

func (this *Button) IsPushed() bool

func (*Button) IsSubPopupVisible

func (this *Button) IsSubPopupVisible() bool

func (*Button) IsTextVisible

func (this *Button) IsTextVisible() bool

func (*Button) OnIdle

func (this *Button) OnIdle()

func (*Button) OnKeyDown

func (this *Button) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown so a focused button can be activated from the keyboard: Enter or Space run the same path as a mouse click (emit -> Action.Trigger / sub-popup toggle). Implementing this interface also opts the button into the Tab focus chain (see focus.go AutoFocus). Guarded on IsEnabled — which for a Button also implies a non-nil action — so a disabled button ignores keys and emit() never dereferences a nil action.

func (*Button) OnLeftDown

func (this *Button) OnLeftDown(x, y float64)

func (*Button) OnLeftUp

func (this *Button) OnLeftUp(x, y float64)

func (*Button) OnMouseEnter

func (this *Button) OnMouseEnter()

func (*Button) OnMouseLeave

func (this *Button) OnMouseLeave()

func (*Button) OnMouseStop

func (this *Button) OnMouseStop(x, y float64)

func (*Button) OwnerMenu

func (this *Button) OwnerMenu() IMenu

func (*Button) SetAction

func (this *Button) SetAction(a IAction)

func (*Button) SetDefault

func (this *Button) SetDefault(b bool)

SetDefault marks this button as the default one — the button Enter activates in a dialog. The theme rings it like a focused button so the Enter target is visible before focus ever reaches it. Keeping exactly one button flagged is the dialog's job, see Dialog.markDefaultButton.

func (*Button) SetIcon

func (this *Button) SetIcon(icon paint.Icon)

func (*Button) SetIconName

func (this *Button) SetIconName(name string)

SetIconName loads the icon by resource name (LoadIcon resolves it under core.ResourceDir()) and remembers the name, which is what makes an icon settable from the designer's property sheet: the name persists into the design file and comes back out as generated code. "" clears both.

func (*Button) SetSubPopup

func (this *Button) SetSubPopup(iw IWidget)

func (*Button) SetSubPopupCallback

func (this *Button) SetSubPopupCallback(fn func(IButton))

func (*Button) SetText

func (this *Button) SetText(text string)

func (*Button) SetTextVisible

func (this *Button) SetTextVisible(b bool)

func (*Button) ShowSubPopup

func (this *Button) ShowSubPopup()

func (*Button) SizeHints

func (this *Button) SizeHints() SizeHints

func (*Button) SubPopup

func (this *Button) SubPopup() IWidget

func (*Button) Text

func (this *Button) Text() string

type ButtonBox

type ButtonBox struct {
	Menu
	// contains filtered or unexported fields
}

按钮框, 即对话框里的"确定/取消"等标准按钮, 也可加入自定义按钮

func NewButtonBox

func NewButtonBox() *ButtonBox

func (*ButtonBox) ButtonsSpec

func (this *ButtonBox) ButtonsSpec() string

func (*ButtonBox) EnumProperties

func (this *ButtonBox) EnumProperties(list core.IPropertyList)

func (*ButtonBox) Init

func (this *ButtonBox) Init(iw IWidget)

func (*ButtonBox) SetButtons

func (this *ButtonBox) SetButtons(btns []string)

func (*ButtonBox) SetButtonsSpec

func (this *ButtonBox) SetButtonsSpec(s string)

SetButtonsSpec is SetButtons as one editable string: the button names separated by commas ("@ok,@cancel"), which is the form a designer types into a property sheet and the form a design file stores. Names are trimmed and blanks dropped, and the normalized spelling is what ButtonsSpec reports back, so " @ok , " and "@ok" are the same box.

func (*ButtonBox) SigSubmit

func (this *ButtonBox) SigSubmit(fn func(string))

type CalcPanel

type CalcPanel struct {
	Widget
	// contains filtered or unexported fields
}

CalcPanel is a decoupled 公式 (formula/calc) operator panel: a scrollable list of host-supplied FormulaRows, each shown as "Output = Expr" with a status cell, plus a footer with 新增(Add) / 删除(Remove) actions. It holds nothing but plain view-model data fed through SetFormulas and emits the operator's intent through the Sig* callbacks: Add asks the host to create a formula, Remove carries the selected row's Output. The host wires those back to the calc store; the panel never imports it, so gui stays light and this file is GL-free unit-testable (only Draw touches the painter).

func NewCalcPanel

func NewCalcPanel() *CalcPanel

NewCalcPanel creates an empty formula panel with no selection.

func (*CalcPanel) Draw

func (this *CalcPanel) Draw(g paint.Painter)

Draw renders a title/count header, the scrollable formula list with the selected row highlighted and a per-row status cell, and the footer action-button row. All colours come from the active Theme() (only the status warning accent is fixed) so the panel reads correctly in the dark IDE theme.

func (*CalcPanel) Formulas

func (this *CalcPanel) Formulas() []FormulaRow

Formulas returns a defensive copy of the displayed formulas in order.

func (*CalcPanel) Init

func (this *CalcPanel) Init(self IWidget)

func (*CalcPanel) OnLeftDown

func (this *CalcPanel) OnLeftDown(x, y float64)

OnLeftDown routes a click: a hit in the footer band fires the matching action (Add unconditionally with empty strings, Remove on the selected row's Output); a hit in the list body selects that row. Clicks on the header or past the last row are ignored.

func (*CalcPanel) OnMouseWheel

func (this *CalcPanel) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the formula list vertically.

func (*CalcPanel) Selected

func (this *CalcPanel) Selected() int

Selected returns the index of the currently selected row, or -1 when no row is selected (or the selection has fallen out of range).

func (*CalcPanel) SetFormulas

func (this *CalcPanel) SetFormulas(in []FormulaRow)

SetFormulas replaces the displayed formulas with a defensive copy of in. FormulaRow is a value type (all strings), so the shallow copy fully isolates the panel from later mutation of the caller's slice. The selection is reset (a new list invalidates any prior index), and the scroll offset is clamped to the new content rather than reset.

func (*CalcPanel) SigAdd

func (this *CalcPanel) SigAdd(fn func(output, expr string))

SigAdd registers the callback fired when the operator clicks 新增(Add). For v1 it passes empty output/expr — the host opens its own input to fill them in.

func (*CalcPanel) SigRemove

func (this *CalcPanel) SigRemove(fn func(output string))

SigRemove registers the callback fired when the operator clicks 删除(Remove). It receives the selected row's Output; it does not fire when nothing is selected.

func (*CalcPanel) SizeHints

func (this *CalcPanel) SizeHints() SizeHints

type Calendar

type Calendar struct {
	Widget
	// contains filtered or unexported fields
}

Calendar is a month-grid date picker — an always-visible calendar like Qt's QCalendarWidget. A header row shows the displayed month/year with prev/next-month arrows; below it a weekday header row, then up to six week-rows of day cells (weeks as rows, weekdays as the seven columns). Today gets an accent ring, the selected day a filled accent background with contrasting text, and days spilling in from the adjacent months (to square off the grid) render dimmed. Clicking a day selects it and fires SigDateSelected.

Usage:

cal := gui.NewCalendar()
cal.SigDateSelected(func(d time.Time) { label.SetText(d.Format("2006-01-02")) })

Calendar is distinct from DatePicker: DatePicker is a compact text field that opens a transient popup calendar, whereas Calendar is the full grid laid out inline as a first-class widget.

The week starts on Monday (columns: Mon..Sun) to match DatePicker's popup and the project's ISO dayOfWeek helper. The header reads in the zh-CN form "2026年6月" to match the designer's Chinese UI.

func NewCalendar

func NewCalendar() *Calendar

NewCalendar creates a Calendar showing the current month with today selected.

func (*Calendar) DisplayedMonth

func (this *Calendar) DisplayedMonth() time.Time

DisplayedMonth returns the first day of the month the grid is showing. A zero month — where a factory-built Calendar starts, since Init stays clock- free — resolves to the current month, so the header, the grid and the hit test all read "now" instead of January of year 1.

func (*Calendar) Draw

func (this *Calendar) Draw(g paint.Painter)

func (*Calendar) EnumProperties

func (this *Calendar) EnumProperties(list core.IPropertyList)

func (*Calendar) Init

func (this *Calendar) Init(self IWidget)

Init carries the hover sentinels, not NewCalendar: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor, and a zero hoverRow/hoverCol paints the top-left day cell hovered before the mouse has ever entered the widget.

The displayed month is deliberately left at its zero value here rather than stamped from time.Now(): DisplayedMonth resolves a zero month to the current one, which keeps Init free of the clock while a factory-built calendar still opens on today's month.

func (*Calendar) NextMonth

func (this *Calendar) NextMonth()

NextMonth advances the displayed month by one, rolling Dec→Jan and bumping the year.

func (*Calendar) OnLeftDown

func (this *Calendar) OnLeftDown(x, y float64)

func (*Calendar) OnMouseLeave

func (this *Calendar) OnMouseLeave()

func (*Calendar) OnMouseMove

func (this *Calendar) OnMouseMove(x, y float64)

func (*Calendar) PrevMonth

func (this *Calendar) PrevMonth()

PrevMonth steps the displayed month back by one, rolling Jan→Dec and dropping the year.

func (*Calendar) SelectedDate

func (this *Calendar) SelectedDate() time.Time

SelectedDate returns the currently selected date (at midnight, local).

func (*Calendar) SetSelectedDate

func (this *Calendar) SetSelectedDate(d time.Time)

SetSelectedDate selects d (truncated to its day) and scrolls the grid to the month containing it. It does not fire SigDateSelected — the callback is reserved for user clicks, so programmatic selection stays quiet. Selecting the already-selected day is a cheap no-op.

func (*Calendar) ShowMonth

func (this *Calendar) ShowMonth(year int, month time.Month)

ShowMonth scrolls the grid to the given year/month without changing the selection.

func (*Calendar) SigDateSelected

func (this *Calendar) SigDateSelected(fn func(time.Time))

SigDateSelected registers the callback fired when the user clicks a day cell. Receives the selected date at midnight, local.

func (*Calendar) SizeHints

func (this *Calendar) SizeHints() SizeHints

type Card

type Card struct {
	Widget
	// contains filtered or unexported fields
}

Card 卡片容器控件,带圆角边框和可选标题

func NewCard

func NewCard(title string) *Card

func (*Card) AddWidget

func (this *Card) AddWidget(iw IWidget)

func (*Card) Content

func (this *Card) Content() IWidget

func (*Card) Draw

func (this *Card) Draw(g paint.Painter)

func (*Card) EnumProperties

func (this *Card) EnumProperties(list core.IPropertyList)

func (*Card) HasShadow

func (this *Card) HasShadow() bool

func (*Card) Layout

func (this *Card) Layout()

func (*Card) Padding

func (this *Card) Padding() float64

func (*Card) Radius

func (this *Card) Radius() float64

func (*Card) SetContent

func (this *Card) SetContent(w IWidget)

func (*Card) SetPadding

func (this *Card) SetPadding(v float64)

func (*Card) SetRadius

func (this *Card) SetRadius(v float64)

func (*Card) SetShadow

func (this *Card) SetShadow(b bool)

func (*Card) SetTitle

func (this *Card) SetTitle(s string)

func (*Card) SizeHints

func (this *Card) SizeHints() SizeHints

func (*Card) Title

func (this *Card) Title() string

type CheckBox

type CheckBox struct {
	Widget
	// contains filtered or unexported fields
}

勾选框, 多选框

func NewCheckBox

func NewCheckBox() *CheckBox

func (*CheckBox) Draw

func (this *CheckBox) Draw(g paint.Painter)

func (*CheckBox) EnumProperties

func (this *CheckBox) EnumProperties(list core.IPropertyList)

func (*CheckBox) Icon

func (this *CheckBox) Icon() paint.Icon

func (*CheckBox) IsChecked

func (this *CheckBox) IsChecked() bool

func (*CheckBox) IsEnabled

func (this *CheckBox) IsEnabled() bool

func (*CheckBox) IsPushed

func (this *CheckBox) IsPushed() bool

func (*CheckBox) OnKeyDown

func (this *CheckBox) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown, giving the check box Qt QCheckBox style keyboard control while it holds focus: Space (and Enter, for convenience) toggles the checked state. The widget is not tri-state, so this is a plain toggle. It routes through Toggle so the change callback fires exactly as a click does. Guarded on IsEnabled so a disabled box ignores keys.

func (*CheckBox) OnLeftDown

func (this *CheckBox) OnLeftDown(x, y float64)

func (*CheckBox) OnLeftUp

func (this *CheckBox) OnLeftUp(x, y float64)

func (*CheckBox) OnMouseEnter

func (this *CheckBox) OnMouseEnter()

func (*CheckBox) OnMouseLeave

func (this *CheckBox) OnMouseLeave()

func (*CheckBox) SetChecked

func (this *CheckBox) SetChecked(b bool)

func (*CheckBox) SetEnabled

func (this *CheckBox) SetEnabled(b bool)

func (*CheckBox) SetText

func (this *CheckBox) SetText(text string)

func (*CheckBox) SigCheck

func (this *CheckBox) SigCheck(fn func(bool))

func (*CheckBox) SizeHints

func (this *CheckBox) SizeHints() SizeHints

func (*CheckBox) Text

func (this *CheckBox) Text() string

func (*CheckBox) Toggle

func (this *CheckBox) Toggle()

type CodeEditor

type CodeEditor struct {
	Widget
	// contains filtered or unexported fields
}

CodeEditor is a syntax-highlighted code editing widget with line numbers, cursor, and basic editing support, designed for Go source code.

func NewCodeEditor

func NewCodeEditor() *CodeEditor

NewCodeEditor creates a new code editor widget.

func (*CodeEditor) AddCursorAtLine

func (this *CodeEditor) AddCursorAtLine(line, col int)

AddCursorAtLine adds a secondary caret at (line, col). The primary cursor remains at (cursorLine, cursorCol). Duplicate positions are ignored.

func (*CodeEditor) BlameAnnotations

func (this *CodeEditor) BlameAnnotations() map[int]string

BlameAnnotations returns a copy of the current blame set, so mutating the result does not affect the editor's internal state.

func (*CodeEditor) BlameVisible

func (this *CodeEditor) BlameVisible() bool

BlameVisible reports whether the annotate (blame) column is currently shown.

func (*CodeEditor) Breakpoints

func (this *CodeEditor) Breakpoints() []int

Breakpoints returns the lines (0-based) that currently have a breakpoint, sorted ascending.

func (*CodeEditor) CaretGlobalXY

func (this *CodeEditor) CaretGlobalXY() (float64, float64)

CaretGlobalXY returns the primary caret's position in GLOBAL screen coordinates: the caret's left x and the bottom of its line, ready to anchor an LSP hover / signature-help popup just below the caret. The local position is viewport-clamped (see caretLocalXY), so the anchor stays inside the editor even when the caret is scrolled out of view.

func (*CodeEditor) ClearAdditionalCursors

func (this *CodeEditor) ClearAdditionalCursors()

ClearAdditionalCursors removes all secondary carets, returning to single-cursor mode.

func (*CodeEditor) ClearBlame

func (this *CodeEditor) ClearBlame()

ClearBlame drops all blame annotations and hides the annotate column. The gutter / text layout returns to its blame-off geometry. Triggers a repaint.

func (*CodeEditor) ClearBreakpoints

func (this *CodeEditor) ClearBreakpoints()

ClearBreakpoints removes all breakpoints.

func (*CodeEditor) ClearCoverage

func (this *CodeEditor) ClearCoverage()

ClearCoverage drops any coverage data. The stripe becomes invisible.

func (*CodeEditor) ClearDiffMarkers

func (this *CodeEditor) ClearDiffMarkers()

ClearDiffMarkers drops all diff markers. The gutter bars become invisible.

func (*CodeEditor) ClearErrors

func (this *CodeEditor) ClearErrors()

ClearErrors removes all error markers.

func (*CodeEditor) ClearExternalCompletions

func (this *CodeEditor) ClearExternalCompletions()

ClearExternalCompletions drops all injected candidates, returning the popup to its built-in sources.

func (*CodeEditor) ClearOccurrenceHighlights

func (this *CodeEditor) ClearOccurrenceHighlights()

ClearOccurrenceHighlights removes any host-fed occurrence highlights.

func (*CodeEditor) CompletionVisible

func (this *CodeEditor) CompletionVisible() bool

CompletionVisible reports whether the completion popup is currently shown. The LSP host uses it to decide whether to REFRESH an open popup with server items vs. force-open one (which would hijack Enter/arrows after a newline, paste, or programmatic edit).

func (*CodeEditor) Cursor

func (this *CodeEditor) Cursor() *Cursor

func (*CodeEditor) CursorCol

func (this *CodeEditor) CursorCol() int

CursorCol returns the current 0-based cursor column (rune index within the line). LSP callers need it to build a textDocument position for completion / go-to-definition requests.

func (*CodeEditor) CursorLine

func (this *CodeEditor) CursorLine() int

CursorLine returns the current 0-based cursor line index.

func (*CodeEditor) CursorUTF16Col

func (this *CodeEditor) CursorUTF16Col() int

CursorUTF16Col returns the caret column as a UTF-16 code-unit offset within its line — the encoding LSP mandates for a Position's `character` field. It parallels CursorCol, which stays a rune index for internal editing: the two agree for ASCII / BMP text but diverge once a non-BMP rune (emoji, a CJK-extension glyph) precedes the caret, where each such rune counts as two UTF-16 units. LSP callers MUST send this, not CursorCol, as the character offset or completion / hover / definition / rename resolve at the wrong column.

func (*CodeEditor) DedentSelection

func (this *CodeEditor) DedentSelection()

DedentSelection removes one indent unit (one tab or up to 4 spaces) from the start of every line spanned by the active selection. Lines with no leading whitespace are skipped.

func (*CodeEditor) DeleteSelection

func (this *CodeEditor) DeleteSelection()

DeleteSelection removes the selected text and places cursor at start.

func (*CodeEditor) DiffMarkers

func (this *CodeEditor) DiffMarkers() map[int]DiffMarkerKind

DiffMarkers returns a copy of the current marker set, so mutating the result does not affect the editor's internal state.

func (*CodeEditor) Draw

func (this *CodeEditor) Draw(g paint.Painter)

func (*CodeEditor) DuplicateLines

func (this *CodeEditor) DuplicateLines()

DuplicateLines copies the current line (or each line of a multi-line selection) below itself. With no selection it reuses duplicateLine (the Cmd+D empty-selection fallback); a selection duplicates the whole block as one undoable full-text edit and re-selects the copy. Routed through rebuildText.

func (*CodeEditor) EnumProperties

func (this *CodeEditor) EnumProperties(list core.IPropertyList)

func (*CodeEditor) ErrorAtLine

func (this *CodeEditor) ErrorAtLine(line int) string

ErrorAtLine returns the error message for a line, or empty string if none.

func (*CodeEditor) FilePath

func (this *CodeEditor) FilePath() string

FilePath returns the file path this editor is editing.

func (*CodeEditor) FindLineContaining

func (this *CodeEditor) FindLineContaining(substr string) int

FindLineContaining returns the first line number containing substr, or -1.

func (*CodeEditor) FoldAll

func (this *CodeEditor) FoldAll()

FoldAll collapses every foldable region.

func (*CodeEditor) FoldRegions

func (this *CodeEditor) FoldRegions() []foldRegion

FoldRegions returns the foldable brace regions for the current text, ordered by start line. The brace scan (O(all lines)) is memoized in foldRegionsCache and reused until a text change invalidates it, since it is called several times per Draw and depends only on line content.

func (*CodeEditor) FormatCode

func (this *CodeEditor) FormatCode()

FormatCode runs gofmt on the current editor text with a timeout to prevent UI freezes. If formatting succeeds, the text is replaced with the formatted output. If it fails or times out, the text remains unchanged.

func (*CodeEditor) GitLineStatuses

func (this *CodeEditor) GitLineStatuses() map[int]GitLineStatus

GitStatus returns the git line status map (1-based line numbers).

func (*CodeEditor) GoToDefinitionAtCursor

func (this *CodeEditor) GoToDefinitionAtCursor()

GoToDefinitionAtCursor jumps to the definition of the identifier at the caret using the AST-based FindDefinition resolver. When the target lives in the current file (or no file path is set) the editor scrolls to it directly; when it lives in a sibling .go file it is delegated to the cross-file navigation callback the host editor wires up. No-op when no identifier is under the cursor or no definition can be resolved.

func (*CodeEditor) HasCoverage

func (this *CodeEditor) HasCoverage() bool

HasCoverage reports whether a coverage map is currently installed.

func (*CodeEditor) HasSelection

func (this *CodeEditor) HasSelection() bool

HasSelection returns true if text is selected.

func (*CodeEditor) HighlightReferencesAtCursor

func (this *CodeEditor) HighlightReferencesAtCursor()

HighlightReferencesAtCursor finds every occurrence of the identifier at the caret in the current buffer (AST-based FindReferences) and routes them through the find bar's findMatches overlay so they are highlighted in place. The user dismisses the highlight with Esc the same way they dismiss a normal find (the find bar's Esc handler already clears findMatches).

func (*CodeEditor) IndentSelection

func (this *CodeEditor) IndentSelection()

IndentSelection inserts one indent unit at the start of every line spanned by the active selection. With no selection it is a no-op (single-caret Tab goes through OnTextInput("\t") in OnKeyDown).

func (*CodeEditor) Init

func (this *CodeEditor) Init(iw IWidget)

func (*CodeEditor) IsFolded

func (this *CodeEditor) IsFolded(startLine int) bool

IsFolded reports whether the region starting at the given line is collapsed.

func (*CodeEditor) IsWordWrap

func (this *CodeEditor) IsWordWrap() bool

IsWordWrap returns whether word wrap is enabled.

func (*CodeEditor) JoinLines

func (this *CodeEditor) JoinLines()

JoinLines merges the current line with the next (or every line of a multi-line selection) into one, collapsing each break to a single space. A no-op on the last line. Recorded as one undoable full-text edit routed through rebuildText.

func (*CodeEditor) Layout

func (this *CodeEditor) Layout()

func (*CodeEditor) LineCovered

func (this *CodeEditor) LineCovered(line int) (covered bool, has bool)

LineCovered queries a single line. The second return value indicates whether the line has any coverage entry at all (so callers can distinguish "covered = false" from "no data").

func (*CodeEditor) Lines

func (this *CodeEditor) Lines() []string

Lines returns the current editor lines.

func (*CodeEditor) NavGoBack

func (this *CodeEditor) NavGoBack()

NavGoBack navigates to the previous position in the navigation stack.

func (*CodeEditor) NavGoForward

func (this *CodeEditor) NavGoForward()

NavGoForward navigates to the next position in the navigation stack.

func (*CodeEditor) NextBookmark

func (this *CodeEditor) NextBookmark()

NextBookmark moves the cursor to the next bookmark after the current line.

func (*CodeEditor) OnKeyDown

func (this *CodeEditor) OnKeyDown(key int, repeat bool)

func (*CodeEditor) OnLeftDown

func (this *CodeEditor) OnLeftDown(x, y float64)

func (*CodeEditor) OnLeftUp

func (this *CodeEditor) OnLeftUp(x, y float64)

func (*CodeEditor) OnMouseLeave

func (this *CodeEditor) OnMouseLeave()

OnMouseLeave clears hover link state when the cursor leaves the editor.

func (*CodeEditor) OnMouseMove

func (this *CodeEditor) OnMouseMove(x, y float64)

func (*CodeEditor) OnMouseWheel

func (this *CodeEditor) OnMouseWheel(x, y, z float64)

func (*CodeEditor) OnRightDown

func (this *CodeEditor) OnRightDown(x, y float64)

OnRightDown opens the editor's context menu at the click point. Following Qt Creator, the caret is first moved to the click position so the subsequent Rename / Go to Definition / Find References act on the word the user actually right-clicked, not wherever the caret happened to be.

func (*CodeEditor) OnTextInput

func (this *CodeEditor) OnTextInput(s string)

func (*CodeEditor) ParseSymbols

func (this *CodeEditor) ParseSymbols() []CodeSymbol

ParseSymbols scans the current editor content and returns all top-level function, type, variable, and constant declarations found by simple line-by-line pattern matching.

func (*CodeEditor) PrevBookmark

func (this *CodeEditor) PrevBookmark()

PrevBookmark moves the cursor to the previous bookmark before the current line.

func (*CodeEditor) RefreshGitStatus

func (this *CodeEditor) RefreshGitStatus()

RefreshGitStatus re-runs git diff and updates the gutter markers.

func (*CodeEditor) RenameSymbolAtCursor

func (this *CodeEditor) RenameSymbolAtCursor(newName string) (string, int, error)

--- AST Rename at Cursor (host-driven, F2) ---

RenameSymbolAtCursor renames the Go identifier under the cursor across the current buffer using code_refactor.go::RenameSymbolCount. The host (silkide) wires F2 to this method via an input dialog — the editor itself does NOT bind a key; this matches the existing host-driven design of go-to-definition and find-references.

On success, the buffer is replaced, the changed callback fires, the cursor snaps to the same byte offset (clamped), and (oldName, count, nil) is returned. On any failure (empty word at cursor, parse error, invalid newName, name collision) the buffer is left untouched and an error is returned alongside (oldName, 0).

func (*CodeEditor) ReplaceAllText

func (this *CodeEditor) ReplaceAllText(s string)

ReplaceAllText swaps the whole buffer for s while PRESERVING undo history, the caret, and scroll — unlike SetText, which resets all three. Used by LSP format / rename / code-action application so a single Cmd+Z reverts the change. Records one kind-3 (full-text-replace) undo entry, fires SigChanged so the host re-syncs gopls, and no-ops when s equals the current text.

func (*CodeEditor) ReplaceSelection

func (this *CodeEditor) ReplaceSelection(text string)

ReplaceSelection replaces selected text with new text.

func (*CodeEditor) ScrollToLine

func (this *CodeEditor) ScrollToLine(line int)

ScrollToLine scrolls the editor so that the given line is visible.

func (*CodeEditor) ScrollToLineCol

func (this *CodeEditor) ScrollToLineCol(line, col int)

ScrollToLineCol is ScrollToLine that also lands the caret on col (clamped to the line). Used by LSP go-to-definition so F12 puts the cursor on the symbol, not just its line. col < 0 behaves like ScrollToLine (col 0).

func (*CodeEditor) ScrollY

func (this *CodeEditor) ScrollY() float64

ScrollY returns the current vertical scroll position.

func (*CodeEditor) SelectedText

func (this *CodeEditor) SelectedText() string

SelectedText returns the currently selected text.

func (*CodeEditor) SetBlameAnnotations

func (this *CodeEditor) SetBlameAnnotations(m map[int]string)

SetBlameAnnotations installs the per-line blame column and switches the annotate view on. Keys are 0-based line numbers; values are the host-computed annotation string (conventionally "shorthash author"). The map is copied so the host may mutate its own copy afterwards. Passing nil installs an empty set but still turns the view on (a blank column); use ClearBlame to hide it. Triggers a repaint.

func (*CodeEditor) SetBreakpoint

func (this *CodeEditor) SetBreakpoint(line int, on bool)

SetBreakpoint enables or disables the breakpoint on a line.

func (*CodeEditor) SetCoverage

func (this *CodeEditor) SetCoverage(cov map[int]bool)

SetCoverage installs a coverage map. The argument is copied so the host is free to mutate its own copy afterwards. Passing nil clears coverage (same effect as ClearCoverage).

func (*CodeEditor) SetDiffFromLines

func (this *CodeEditor) SetDiffFromLines(added, modified, removed []int)

SetDiffFromLines builds the marker set from three line lists (0-based) and installs it. added → DiffMarkerAdded, modified → DiffMarkerModified, removed → DiffMarkerRemoved. Overlap precedence is Removed > Modified > Added: a line listed in more than one bucket takes the highest-precedence kind, applied by writing Added first, then Modified, then Removed last so it wins. Triggers a repaint via SetDiffMarkers.

func (*CodeEditor) SetDiffMarkers

func (this *CodeEditor) SetDiffMarkers(markers map[int]DiffMarkerKind)

SetDiffMarkers replaces the whole marker set. The argument is copied so the host is free to mutate its own copy afterwards; entries with kind DiffMarkerNone are dropped so the set stays minimal. Passing nil clears the markers (same effect as ClearDiffMarkers). Triggers a repaint.

func (*CodeEditor) SetErrors

func (this *CodeEditor) SetErrors(errors map[int]string)

SetErrors sets compile error markers on specific lines. The map keys are 0-based line numbers, values are error messages.

func (*CodeEditor) SetExternalCompletions

func (this *CodeEditor) SetExternalCompletions(items []ExternalCompletion)

SetExternalCompletions replaces the injected candidate set. Pass the items a host fetched from its provider; they are merged into the popup on the next (re)build and persist until replaced or cleared. A nil/empty slice is equivalent to ClearExternalCompletions.

func (*CodeEditor) SetFilePath

func (this *CodeEditor) SetFilePath(path string)

SetFilePath stores the file path this editor is editing and refreshes git status.

func (*CodeEditor) SetFont

func (this *CodeEditor) SetFont(f paint.Font)

SetFont sets the editor's monospace font.

func (*CodeEditor) SetNavigateCallback

func (this *CodeEditor) SetNavigateCallback(fn func(string, int))

SetNavigateCallback sets the callback for cross-file navigation. The callback receives the target file path and line number.

func (*CodeEditor) SetOccurrenceHighlights

func (this *CodeEditor) SetOccurrenceHighlights(ranges []HighlightRange)

SetOccurrenceHighlights renders the given ranges as a subtle same-symbol background wash (e.g. from LSP textDocument/documentHighlight). Kept separate from the find bar so the two don't clobber each other. nil / empty clears.

func (*CodeEditor) SetScrollY

func (this *CodeEditor) SetScrollY(y float64)

SetScrollY sets the vertical scroll position.

func (*CodeEditor) SetShowMinimap

func (this *CodeEditor) SetShowMinimap(on bool)

SetShowMinimap toggles the minimap display.

func (*CodeEditor) SetSnippets

func (this *CodeEditor) SetSnippets(s *SnippetSet)

SetSnippets installs a SnippetSet used by Tab to expand triggers. Passing nil disables the new-style expansion path; the legacy goSnippets table still fires from tryExpandSnippet.

func (*CodeEditor) SetText

func (this *CodeEditor) SetText(s string)

SetText replaces the entire editor content.

func (*CodeEditor) SetWordWrap

func (this *CodeEditor) SetWordWrap(on bool)

SetWordWrap toggles word wrap mode.

func (*CodeEditor) SigBreakpointToggled

func (this *CodeEditor) SigBreakpointToggled(fn func(line int, on bool))

SigBreakpointToggled registers the callback fired after ToggleBreakpoint has flipped a line — the gutter click and F9 both land there. line is 0-based (editor convention) and on is the state the line ended up in; the host (silkide) pushes it at the running debugger. Mirrors the SigTestRunRequested / SigChanged idiom.

func (*CodeEditor) SigChanged

func (this *CodeEditor) SigChanged(fn func(string))

SigChanged registers a callback invoked when text changes.

func (*CodeEditor) SigChangedFn

func (this *CodeEditor) SigChangedFn() func(string)

SigChangedFn returns the currently registered change callback, or nil.

func (*CodeEditor) SigHoverRequested

func (this *CodeEditor) SigHoverRequested(fn func(line, col int, gx, gy float64))

SigHoverRequested registers the host hook fired when the mouse settles over an identifier in the text area. The editor reports (line, col) plus a global anchor (gx, gy); the host runs the async LSP Hover RPC and shows the result (e.g. via ShowToolTip). The editor does NOT fetch or display hover text — it only signals where the user is hovering. The callback fires once per identifier (see hoverReqLine/hoverReqCol) and never while the completion popup is visible. Passing nil disables the signal (no-op).

func (*CodeEditor) SigSignatureRequested

func (this *CodeEditor) SigSignatureRequested(fn func(line, col int))

SigSignatureRequested registers the host hook fired when the user types a signature trigger ("(" or ","). The editor passes the cursor (line, col) AFTER the insert; the host runs the async LSP SignatureHelp RPC and shows the result. Typing ")" dismisses any shown help (the editor calls HideToolTip on ")"); Esc dismissal is left to the host. Passing nil disables the signal (no-op).

func (*CodeEditor) SigTestRunRequested

func (this *CodeEditor) SigTestRunRequested(fn func(name string))

SigTestRunRequested registers the callback fired when the user clicks the run-test ▶ gutter marker beside a Go test function. The argument is the function name (e.g. "TestFoo"); the host runs `go test -run ^Name$`. Mirrors the SigWidgetClicked / SigChanged idiom.

func (*CodeEditor) SigWidgetClicked

func (this *CodeEditor) SigWidgetClicked(fn func(string))

SigWidgetClicked registers a callback for widget-name clicks.

func (*CodeEditor) SizeHints

func (this *CodeEditor) SizeHints() SizeHints

func (*CodeEditor) Snippets

func (this *CodeEditor) Snippets() *SnippetSet

Snippets returns the active SnippetSet (may be nil if cleared via SetSnippets).

func (*CodeEditor) Text

func (this *CodeEditor) Text() string

Text returns the full editor content.

func (*CodeEditor) ToggleBookmark

func (this *CodeEditor) ToggleBookmark()

ToggleBookmark toggles a bookmark on the current cursor line.

func (*CodeEditor) ToggleBreakpoint

func (this *CodeEditor) ToggleBreakpoint(line int)

ToggleBreakpoint flips the breakpoint state of a line.

func (*CodeEditor) ToggleFold

func (this *CodeEditor) ToggleFold(startLine int)

ToggleFold collapses or expands the foldable region that starts at the given line. A line that is not the start of a foldable region is ignored.

func (*CodeEditor) ToggleLineComment

func (this *CodeEditor) ToggleLineComment()

ToggleLineComment toggles "// " line comments on the current line, or on every line spanned by the active selection (Cmd/Ctrl+/). It delegates the transform to the pure toggleComment helper, then fires the changed callback and repaints.

func (*CodeEditor) TriggerCompletion

func (this *CodeEditor) TriggerCompletion()

TriggerCompletion programmatically opens the completion popup at the current cursor, merging in any external candidates. A host calls this after fetching provider results (e.g. an LSP completion response) and injecting them via SetExternalCompletions.

func (*CodeEditor) TrimTrailingWhitespace

func (this *CodeEditor) TrimTrailingWhitespace()

TrimTrailingWhitespace strips trailing spaces/tabs from every line. The caret column is clamped to its (possibly shorter) line. Callable by the host and recorded as one undoable full-text edit routed through rebuildText.

func (*CodeEditor) UnfoldAll

func (this *CodeEditor) UnfoldAll()

UnfoldAll expands every collapsed region.

type CodeSymbol

type CodeSymbol struct {
	Name     string
	Kind     int    // 0=func, 1=type, 2=var, 3=const, 4=method
	Line     int    // 0-based line index
	Detail   string // e.g., "func(x int) string" or "type struct"
	Receiver string // for methods: receiver type name
}

CodeSymbol represents a parsed symbol declaration in Go source code.

type ColorPicker

type ColorPicker struct {
	Widget
	// contains filtered or unexported fields
}

ColorPicker is a color selection widget that displays the current color as a swatch with its hex value, followed by an inline palette of common colors the user can click (or arrow-key onto) to pick. The palette can be replaced with SetPalette to override the defaults; the active swatch (matching the current Color()) gets a ring highlight.

func NewColorPicker

func NewColorPicker() *ColorPicker

NewColorPicker creates a new ColorPicker with a default blue color and the built-in palette returned by defaultColorPalette().

func (*ColorPicker) Color

func (this *ColorPicker) Color() paint.Color

Color returns the currently selected color.

func (*ColorPicker) Draw

func (this *ColorPicker) Draw(g paint.Painter)

func (*ColorPicker) EnumProperties

func (this *ColorPicker) EnumProperties(list core.IPropertyList)

func (*ColorPicker) Init

func (this *ColorPicker) Init(self IWidget)

Init carries the default colour and palette, not NewColorPicker: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. An empty palette draws no swatches, so there is nothing for a click or an arrow key to land on.

func (*ColorPicker) OnKeyDown

func (this *ColorPicker) OnKeyDown(key int, repeat bool)

OnKeyDown navigates the inline palette by arrow keys. Left/Right step by one swatch (single-row layout — Up/Down behave the same as Left/Right so keyboards without horizontal arrow muscle memory still work). Home/End jump to the first/last swatch. Enter/Space commit the focused swatch.

func (*ColorPicker) OnLeftDown

func (this *ColorPicker) OnLeftDown(x, y float64)

func (*ColorPicker) OnLeftUp

func (this *ColorPicker) OnLeftUp(x, y float64)

func (*ColorPicker) OnMouseEnter

func (this *ColorPicker) OnMouseEnter()

func (*ColorPicker) OnMouseLeave

func (this *ColorPicker) OnMouseLeave()

func (*ColorPicker) Palette

func (this *ColorPicker) Palette() []paint.Color

Palette returns the current inline palette.

func (*ColorPicker) SetColor

func (this *ColorPicker) SetColor(c paint.Color)

SetColor sets the selected color. The change callback (if any) fires only when the new color differs from the existing one.

func (*ColorPicker) SetPalette

func (this *ColorPicker) SetPalette(p []paint.Color)

SetPalette replaces the inline palette. A nil or empty slice restores the built-in default palette. The keyboard-active index is re-anchored to the currently selected color, or to 0 if no match exists.

func (*ColorPicker) SigColorChanged

func (this *ColorPicker) SigColorChanged(fn func(paint.Color))

SigColorChanged sets the callback for when the color changes.

func (*ColorPicker) SizeHints

func (this *ColorPicker) SizeHints() SizeHints

type ColorRange

type ColorRange struct {
	Min, Max float64
	Color    paint.Color
}

ColorRange maps a numeric interval [Min, Max] to a color. Used to paint alarm bands (LoLo/Lo/normal/Hi/HiHi) from a tag's engineering value.

type ColorScheme

type ColorScheme struct {
	// 主要颜色
	Primary      paint.Color // 主色调
	PrimaryLight paint.Color // 主色调浅色
	PrimaryDark  paint.Color // 主色调深色
	Secondary    paint.Color // 辅助色
	Accent       paint.Color // 强调色

	// 背景色
	Background paint.Color // 主背景
	Surface    paint.Color // 表面/卡片背景
	SurfaceAlt paint.Color // 交替表面色

	// 文字色
	TextPrimary   paint.Color // 主要文字
	TextSecondary paint.Color // 辅助文字
	TextDisabled  paint.Color // 禁用文字
	TextOnPrimary paint.Color // 主色上的文字(通常白色)

	// 边框与分割
	Border      paint.Color // 边框色
	Divider     paint.Color // 分割线
	BorderFocus paint.Color // 获焦边框

	// 功能色
	Success paint.Color // 成功/正确
	Warning paint.Color // 警告
	Error   paint.Color // 错误/危险
	Info    paint.Color // 信息

	// 交互状态
	Hover    paint.Color // 悬停
	Pressed  paint.Color // 按下
	Selected paint.Color // 选中
	Disabled paint.Color // 禁用背景

	// 特殊
	Shadow  paint.Color // 阴影色
	Overlay paint.Color // 遮罩层
}

ColorScheme 配色方案

func BlueColorScheme

func BlueColorScheme() ColorScheme

BlueColorScheme 蓝色主题配色

func DarkColorScheme

func DarkColorScheme() ColorScheme

DarkColorScheme 深色主题配色

func GetColorScheme

func GetColorScheme(variant StyleVariant) ColorScheme

GetColorScheme 获取预设配色方案

func GreenColorScheme

func GreenColorScheme() ColorScheme

GreenColorScheme 绿色主题配色

func LightColorScheme

func LightColorScheme() ColorScheme

LightColorScheme 浅色主题配色

func PurpleColorScheme

func PurpleColorScheme() ColorScheme

PurpleColorScheme 紫色主题配色

type ComboBox

type ComboBox struct {
	Widget
	// contains filtered or unexported fields
}

组合下拉框

func NewComboBox

func NewComboBox() *ComboBox

func (*ComboBox) ActiveIndex

func (this *ComboBox) ActiveIndex() int

func (*ComboBox) ActiveItem

func (this *ComboBox) ActiveItem() ListItem

func (*ComboBox) Append

func (this *ComboBox) Append(a ListItem)

func (*ComboBox) Clear

func (this *ComboBox) Clear()

func (*ComboBox) ClientRect

func (this *ComboBox) ClientRect() geom.Rect

func (*ComboBox) Count

func (this *ComboBox) Count() int

func (*ComboBox) Draw

func (this *ComboBox) Draw(g paint.Painter)

func (*ComboBox) EditWidget

func (this *ComboBox) EditWidget() IEdit

func (*ComboBox) EnumProperties

func (this *ComboBox) EnumProperties(list core.IPropertyList)

func (*ComboBox) HasFocus

func (this *ComboBox) HasFocus() bool

func (*ComboBox) HideSubPopup

func (this *ComboBox) HideSubPopup()

func (*ComboBox) Init

func (this *ComboBox) Init(iw IWidget)

func (*ComboBox) Insert

func (this *ComboBox) Insert(idx int, a ListItem)

func (*ComboBox) IsEditable

func (this *ComboBox) IsEditable() bool

func (*ComboBox) IsHover

func (this *ComboBox) IsHover() bool

func (*ComboBox) IsSubPopupVisible

func (this *ComboBox) IsSubPopupVisible() bool

func (*ComboBox) Item

func (this *ComboBox) Item(idx int) ListItem

func (*ComboBox) ItemList

func (this *ComboBox) ItemList() (ret []ListItem)

func (*ComboBox) Layout

func (this *ComboBox) Layout()

func (*ComboBox) OnKeyDown

func (this *ComboBox) OnKeyDown(key int, repeat bool)

OnKeyDown implements Qt QComboBox keyboard navigation. When the dropdown is open Up/Down move the highlighted row and Enter commits it; when closed they change the current selection directly. Esc closes without changing selection, Home/End jump to the first/last item, and a printable character performs a single-character type-ahead jump to the next matching item.

func (*ComboBox) OnLeftDown

func (this *ComboBox) OnLeftDown(x, y float64)

func (*ComboBox) OnLeftUp

func (this *ComboBox) OnLeftUp(x, y float64)

func (*ComboBox) OnMouseEnter

func (this *ComboBox) OnMouseEnter()

func (*ComboBox) OnMouseLeave

func (this *ComboBox) OnMouseLeave()

func (*ComboBox) Remove

func (this *ComboBox) Remove(idx int) ListItem

func (*ComboBox) RemoveLast

func (this *ComboBox) RemoveLast() ListItem

func (*ComboBox) SetEditWidget

func (this *ComboBox) SetEditWidget(edit IEdit)

func (*ComboBox) SetItem

func (this *ComboBox) SetItem(idx int, item ListItem)

func (*ComboBox) ShowSubPopup

func (this *ComboBox) ShowSubPopup()

func (*ComboBox) SigSelectionChanged

func (this *ComboBox) SigSelectionChanged(fn func(o interface{}, idx int))

func (*ComboBox) SigSubmit

func (this *ComboBox) SigSubmit(fn func(o interface{}))

func (*ComboBox) SubPopup

func (this *ComboBox) SubPopup() *comboPopup

func (*ComboBox) ToggleSubPopup

func (this *ComboBox) ToggleSubPopup()

type Completer

type Completer struct {
	// Source produces the candidate list dynamically. When nil, the
	// pre-baked Candidates slice is used. Either may be set; if both
	// are set, Source wins.
	Source CompletionSource

	// Candidates is a pre-baked candidate list. Compatible with the
	// dominant case (a fixed dictionary, recent-values list, etc.).
	Candidates []string
	// contains filtered or unexported fields
}

Completer ranks candidates against a typed prefix and exposes the matches as Suggestions(). Mirrors QCompleter at the data layer; UI integration (popup display, keyboard navigation) is handled by the host widget — Edit reaches into Completer.Suggestions() to render its own completion popup.

Default settings: MatchStartsWith with case-insensitive comparison. Override via SetMode / SetCaseSensitive when constructing.

func NewCompleter

func NewCompleter(candidates ...string) *Completer

NewCompleter builds a Completer over a static candidate list with the default settings (StartsWith + case-insensitive + dedupe). Callers needing a dynamic source can ignore the candidates argument and assign Source after construction.

func (*Completer) Filter

func (c *Completer) Filter(prefix string) []string

Filter recomputes suggestions for the given typed prefix and stores the result on the Completer. Returns the same slice that Suggestions would return — convenient for callers that want the values inline.

The input order in the result is: (1) candidates whose match starts at position 0, (2) candidates whose match is later in the string, then (3) alphabetical. This puts "best matches" first without a dedicated relevance score, which is fine for the dominant UI use case.

func (*Completer) IsCaseSensitive

func (c *Completer) IsCaseSensitive() bool

IsCaseSensitive reports the current case-sensitivity setting.

func (*Completer) Mode

func (c *Completer) Mode() MatchMode

Mode returns the current match mode.

func (*Completer) SetCaseSensitive

func (c *Completer) SetCaseSensitive(b bool)

SetCaseSensitive toggles case sensitivity.

func (*Completer) SetDedupe

func (c *Completer) SetDedupe(b bool)

SetDedupe toggles duplicate-removal in the suggestion list.

func (*Completer) SetMaxSuggestions

func (c *Completer) SetMaxSuggestions(n int)

SetMaxSuggestions caps the result list length. n=0 means no cap.

func (*Completer) SetMode

func (c *Completer) SetMode(m MatchMode)

SetMode changes the matcher.

func (*Completer) Suggestions

func (c *Completer) Suggestions() []string

Suggestions returns the most recent Filter result. Empty when no Filter has run, or when no candidate matched.

type CompletionItem

type CompletionItem struct {
	Text   string
	Kind   int // CikKeyword, CikType, CikFunction, CikVariable
	Detail string
}

CompletionItem represents a single auto-completion suggestion.

func RankCompletions

func RankCompletions(items []CompletionItem, query string) []CompletionItem

RankCompletions filters items by fuzzyMatch against query and returns a new slice sorted by descending score; ties are broken by ascending candidate length, then by original input order (stable sort). An empty query returns a copy of items with their original ordering preserved.

type CompletionPopup

type CompletionPopup struct {
	// contains filtered or unexported fields
}

CompletionPopup manages the auto-completion dropdown for a CodeEditor.

func NewCompletionPopup

func NewCompletionPopup(editor *CodeEditor) *CompletionPopup

NewCompletionPopup creates a new completion popup for the given editor.

func (*CompletionPopup) Accept

func (this *CompletionPopup) Accept(editor *CodeEditor)

Accept inserts the selected completion into the editor.

func (*CompletionPopup) Dismiss

func (this *CompletionPopup) Dismiss()

Dismiss hides the completion popup.

func (*CompletionPopup) SelectNext

func (this *CompletionPopup) SelectNext()

SelectNext moves selection down.

func (*CompletionPopup) SelectPrev

func (this *CompletionPopup) SelectPrev()

SelectPrev moves selection up.

func (*CompletionPopup) Show

func (this *CompletionPopup) Show(prefix string, editor *CodeEditor)

Show opens the completion popup with the given prefix, filtering candidates.

type CompletionSource

type CompletionSource interface {
	CandidateAt(prefix string) []string
}

CompletionSource is the optional dynamic-data interface for a Completer. When the candidate set is computed at filter time (e.g. filesystem paths, database queries, language symbols) the host implements CompletionSource and assigns it to the Completer; the pre-baked Candidates slice is consulted only when Source is nil.

CandidateAt(prefix) returns the full candidate list given the current input. It is the implementation's responsibility to cache / debounce expensive lookups; the Completer does not memoise.

type CompoundCommand

type CompoundCommand struct {
	// contains filtered or unexported fields
}

func NewCompoundCommand

func NewCompoundCommand() *CompoundCommand

func (*CompoundCommand) Append

func (this *CompoundCommand) Append(a ICommand)

func (*CompoundCommand) Redo

func (this *CompoundCommand) Redo()

func (*CompoundCommand) SetText

func (this *CompoundCommand) SetText(s string)

func (*CompoundCommand) Text

func (this *CompoundCommand) Text() string

func (*CompoundCommand) Undo

func (this *CompoundCommand) Undo()

type CompoundEdit

type CompoundEdit struct {
	// Edits is ordered bottom-up (last position first). Applying them in this
	// order keeps every later entry's coordinates valid, because an edit can
	// only shift text that comes after it.
	Edits []SelectionEdit
	// Description labels the batch for the undo stack, e.g.
	// "column replace at 4 cursors".
	Description string
}

CompoundEdit is a whole multi-cursor edit: Edits in the order they must be applied, plus one Description so the batch collapses into a single undo step.

type Conner

type Conner int
const (
	TopLeft Conner = iota
	TopRight
	BottomLeft
	BottomRight
)

type Cursor

type Cursor struct {
	// contains filtered or unexported fields
}

Cursor wraps a GLFW cursor

func DefaultCursor

func DefaultCursor() *Cursor

DefaultCursor returns the default arrow cursor

func GenerateDropCursors

func GenerateDropCursors(content paint.Pixmap) (curs []*Cursor)

GenerateDropCursors generates a set of DnD cursors with the given content thumbnail

func LoadCursor

func LoadCursor(name string) *Cursor

LoadCursor loads a named cursor, using cache

func NewCursorFromData

func NewCursorFromData(data CursorData) (*Cursor, error)

NewCursorFromData creates a cursor from cursor data

func NewCursorFromIcon

func NewCursorFromIcon(icon paint.Icon, sz, hotX, hotY int) (*Cursor, error)

NewCursorFromIcon creates a cursor from an icon

func SetOverrideCursor

func SetOverrideCursor(c *Cursor) (old *Cursor)

SetOverrideCursor sets a global override cursor

type CursorData

type CursorData struct {
	paint.Pixmap
	HotX, HotY int
}

CursorData holds cursor image data

func LoadCursorData

func LoadCursorData(name string) (data CursorData, err error)

LoadCursorData loads cursor data from a file

type DatePicker

type DatePicker struct {
	Widget
	// contains filtered or unexported fields
}

DatePicker is a date selection widget that shows the current date as text. Clicking it opens a dropdown calendar popup for selecting a day.

func NewDatePicker

func NewDatePicker() *DatePicker

NewDatePicker creates a new DatePicker initialized to today's date.

func (*DatePicker) Day

func (this *DatePicker) Day() int

Day returns the currently selected day (1-31).

func (*DatePicker) Draw

func (this *DatePicker) Draw(g paint.Painter)

func (*DatePicker) EnumProperties

func (this *DatePicker) EnumProperties(list core.IPropertyList)

func (*DatePicker) Format

func (this *DatePicker) Format() string

Format returns the display format string.

func (*DatePicker) Init

func (this *DatePicker) Init(self IWidget)

Init carries the display format, not NewDatePicker: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor.

The date itself is deliberately left at its zero value here rather than stamped from time.Now(): Year/Month/Day resolve an unset date to today, so Init stays free of the clock while a factory-built picker still shows a real date instead of 0000-00-00.

func (*DatePicker) Month

func (this *DatePicker) Month() int

Month returns the currently selected month (1-12).

func (*DatePicker) OnLeftDown

func (this *DatePicker) OnLeftDown(x, y float64)

func (*DatePicker) OnLeftUp

func (this *DatePicker) OnLeftUp(x, y float64)

func (*DatePicker) OnMouseEnter

func (this *DatePicker) OnMouseEnter()

func (*DatePicker) OnMouseLeave

func (this *DatePicker) OnMouseLeave()

func (*DatePicker) SetDate

func (this *DatePicker) SetDate(year, month, day int)

SetDate sets the date value.

func (*DatePicker) SetFormat

func (this *DatePicker) SetFormat(f string)

SetFormat sets the display format string.

func (*DatePicker) SigDateChanged

func (this *DatePicker) SigDateChanged(fn func(year, month, day int))

SigDateChanged sets the callback for when the date changes.

func (*DatePicker) SizeHints

func (this *DatePicker) SizeHints() SizeHints

func (*DatePicker) Year

func (this *DatePicker) Year() int

Year returns the currently selected year.

type Dialog

type Dialog struct {
	Form
	// contains filtered or unexported fields
}

Dialog is a modal window widget built on top of Form. It provides a content area and a bottom button bar for user interaction.

func NewDialog

func NewDialog(title string, parent IWidget) *Dialog

NewDialog creates a new Dialog with the given title and parent widget.

func (*Dialog) AddButton

func (this *Dialog) AddButton(text string, result DialogResult) *Button

AddButton adds a button with the given text and associated DialogResult. Returns the created Button for further customization.

func (*Dialog) Content

func (this *Dialog) Content() IWidget

Content returns the current content widget.

func (*Dialog) Draw

func (this *Dialog) Draw(g paint.Painter)

Draw renders a modern dialog background with clean separation.

func (*Dialog) EnumProperties

func (this *Dialog) EnumProperties(list core.IPropertyList)

func (*Dialog) Init

func (this *Dialog) Init(iw IWidget)

Init carries the state every dialog needs regardless of how it was built. A reflect-built dialog (designer palette, form loader) only ever gets Init, and without this AddButton dies on a nil resultMap and a nil button bar, while cancelResult left at 0 makes Esc return DialogOK instead of rejecting.

func (*Dialog) Layout

func (this *Dialog) Layout()

Layout arranges the content area on top and the button bar at the bottom.

func (*Dialog) OnKeyDown

func (this *Dialog) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown so the dialog itself handles Enter/Esc (Qt QDialog behavior). Enter/Return activates the default button; Esc cancels/rejects. Key events route here only when no child widget holds focus (window_glfw dispatches to focusWidget first), so a focused multi-line editor keeps its own Enter — the dialog only catches these as the focus fallback.

func (*Dialog) Result

func (this *Dialog) Result() DialogResult

Result returns the dialog result after ShowModal has returned.

func (*Dialog) SetCancelResult

func (this *Dialog) SetCancelResult(r DialogResult)

SetCancelResult overrides the result returned when Esc closes the dialog (DialogCancel by default), mirroring Qt's reject role.

func (*Dialog) SetContent

func (this *Dialog) SetContent(w IWidget)

SetContent sets the main content widget displayed in the dialog body.

func (*Dialog) SetDefaultButton

func (this *Dialog) SetDefaultButton(btn *Button)

SetDefaultButton marks btn (one returned from AddButton) as the dialog's default button — the one Enter/Return activates. Passing nil clears it and reverts to the implicit heuristic (see defaultButton). Matches Qt QPushButton::setDefault on a QDialog's button.

func (*Dialog) ShowModal

func (this *Dialog) ShowModal() DialogResult

ShowModal displays the dialog modally and returns the result.

func (*Dialog) SizeHints

func (this *Dialog) SizeHints() SizeHints

SizeHints returns the preferred size for the dialog.

type DialogResult

type DialogResult int

DialogResult represents the result of a dialog action

const (
	DialogOK DialogResult = iota
	DialogCancel
	DialogYes
	DialogNo
)

func ShowMessageDialog

func ShowMessageDialog(parent IWidget, title, message string) DialogResult

ShowMessageDialog displays a simple message dialog with an OK button.

type DiffHunkAction

type DiffHunkAction int

DiffHunkAction names the clickable affordances on a hunk header row.

const (
	DiffHunkActionNone   DiffHunkAction = iota // click landed outside both zones
	DiffHunkActionStage                        // "stage this hunk"
	DiffHunkActionRevert                       // "revert this hunk"
)

type DiffMarkerKind

type DiffMarkerKind int

DiffMarkerKind is the VCS diff state of a single line.

const (
	DiffMarkerNone     DiffMarkerKind = iota // no marker — draw nothing
	DiffMarkerAdded                          // green bar — new line
	DiffMarkerModified                       // blue bar — changed line
	DiffMarkerRemoved                        // red triangle — line(s) removed AFTER this line
)

type DiffPatchFile

type DiffPatchFile struct {
	OldPath string
	NewPath string
	OldText string
	Hunks   []DiffPatchHunk
}

DiffPatchFile is one file's patch plus the original content it applies to. OldText is what lets the view show the WHOLE file: the unchanged gaps between hunks come from it. With OldText empty the view degrades to the changed neighbourhoods only (still with header rows and hunk actions), which is all a patch without its original file can show.

func NewDiffPatchFile

func NewDiffPatchFile(f core.FilePatch, original string) DiffPatchFile

NewDiffPatchFile converts a parsed core.FilePatch plus the original file content into the plain struct SetPatchFile takes. Hosts that already speak core.ParsePatchSet get the whole-file view in two calls.

type DiffPatchHunk

type DiffPatchHunk struct {
	Header   string
	OldStart int
	OldLines int
	NewStart int
	NewLines int
	Lines    []DiffPatchLine
}

DiffPatchHunk is one hunk of a file patch. Header is the pre-rendered "@@ -a,b +c,d @@" text for the header row; when empty the view renders one from the four range fields. OldStart is 1-based and is what positions the hunk against OldText so the unchanged gaps land in the right place.

type DiffPatchLine

type DiffPatchLine struct {
	Kind DiffPatchLineKind
	Text string
}

DiffPatchLine is one line of a hunk body, without the +/-/space marker.

type DiffPatchLineKind

type DiffPatchLineKind int

DiffPatchLineKind classifies one line of a hunk body handed to SetPatchFile. It mirrors core.PatchLineKind but is declared here so the widget stays independent of the patch parser: any host that can produce context/added/deleted lines can drive the view.

const (
	DiffPatchContext DiffPatchLineKind = iota // unchanged, on both sides
	DiffPatchAdded                            // only in the new file
	DiffPatchDeleted                          // only in the old file
)

type DiffRow

type DiffRow struct {
	OldLine string
	NewLine string
	Status  DiffRowStatus
}

DiffRow is one row in the rendered diff: oldLine renders on the left and newLine renders on the right. For DiffRemoved newLine is empty; for DiffAdded oldLine is empty; for DiffSame and DiffModified both fields are populated. The status drives the per-row background tint.

type DiffRowStatus

type DiffRowStatus int

DiffRowStatus classifies a single row in the side-by-side diff view. The first four states cover every (left, right) line-pairing we emit: matched lines on both sides, a line that exists only on the left (removed), one that exists only on the right (added), or a row where both sides hold a line but they differ (modified). DiffHunkHeader is the fifth and only appears in patch mode (SetPatchFile): a full-width "@@ ... @@" separator that carries the per-hunk stage/revert actions instead of a left/right line pair.

const (
	DiffSame       DiffRowStatus = iota // both sides hold the same line
	DiffRemoved                         // old has a line, new does not (left only)
	DiffAdded                           // new has a line, old does not (right only)
	DiffModified                        // both sides hold a line but they differ
	DiffHunkHeader                      // patch mode: "@@ ... @@" separator row
)

type DiffView

type DiffView struct {
	Widget
	// contains filtered or unexported fields
}

DiffView is a two-column line-by-line text diff viewer (Qt Creator's "Side-by-Side Diff", simplified). The left column shows the old text, the right column shows the new text, with matching lines neutral, lines only in the old tinted red on the left, lines only in the new tinted green on the right, and rows where both sides differ tinted on both sides. A vertical divider sits in the middle and a single shared scroll offset keeps the two columns aligned.

Usage:

dv := gui.NewDiffView()
dv.SetTexts(oldSrc, newSrc)

The diff is line-based and computed via a simple LCS pass — the helper lineDiff is exported package-locally so it can be unit-tested without any widget/GL state.

func NewDiffView

func NewDiffView() *DiffView

NewDiffView creates an empty diff viewer. Callers populate it with SetTexts (or SetOldText/SetNewText) once the two sides are known.

func (*DiffView) ActivateHunkAction

func (this *DiffView) ActivateHunkAction(row int, x float64) bool

ActivateHunkAction fires the stage/revert callback for a click at (row, x) and reports whether the click hit an action zone. A hit consumes the click even with no callback registered, so the header row never doubles as a change-row selection.

func (*DiffView) ActiveChangeRow

func (this *DiffView) ActiveChangeRow() int

ActiveChangeRow returns the index of the row the n/p navigation last landed on (or -1 if none / never used). Hosts that want to drive the view themselves can read this back after SetActiveChangeRow.

func (*DiffView) DiffRows

func (this *DiffView) DiffRows() []DiffRow

DiffRows returns the computed row list. Exposed for tests and host code that wants to render its own summary on top of the same diff data.

func (*DiffView) Draw

func (this *DiffView) Draw(g paint.Painter)

Draw paints the two columns, the centre divider, and per-row tints.

func (*DiffView) EnumProperties

func (this *DiffView) EnumProperties(list core.IPropertyList)

EnumProperties exposes the two texts to the property sheet so the designer can preview the widget with sample content.

func (*DiffView) HunkActionAt

func (this *DiffView) HunkActionAt(row int, x float64) (hunkIndex int, action DiffHunkAction)

HunkActionAt hit-tests a click at column x on `row`. It returns the hunk index and which action zone was hit; a row that is not a hunk header yields (-1, DiffHunkActionNone), and a header row clicked outside both zones yields (hunkIndex, DiffHunkActionNone). Pure geometry against the widget size, so it is testable without any render state.

func (*DiffView) HunkCount

func (this *DiffView) HunkCount() int

HunkCount is the number of hunks currently on screen.

func (*DiffView) HunkHeaderRows

func (this *DiffView) HunkHeaderRows() []int

HunkHeaderRows returns a copy of the row index of each hunk's header row, in hunk order. Hosts use it to scroll a hunk into view.

func (*DiffView) HunkIndexAtRow

func (this *DiffView) HunkIndexAtRow(row int) int

HunkIndexAtRow maps a row index to the hunk it belongs to — header row and body rows alike — or -1 for an unchanged gap row, an out-of-range row, or any row in plain two-text mode.

func (*DiffView) Init

func (this *DiffView) Init(self IWidget)

Init carries the gutter default and the active-row sentinel, not NewDiffView: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A factory viewer would otherwise open with the line-number gutter suppressed.

func (*DiffView) IsPatchMode

func (this *DiffView) IsPatchMode() bool

IsPatchMode reports whether the rows came from SetPatchFile.

func (*DiffView) JumpToNextChange

func (this *DiffView) JumpToNextChange()

JumpToNextChange advances activeChangeRow to the next non-Same row, or no-ops if there isn't one. Wraps NextChangeRow(activeChangeRow) so a fresh view (activeChangeRow == -1) lands on the first change.

func (*DiffView) JumpToPrevChange

func (this *DiffView) JumpToPrevChange()

JumpToPrevChange is the symmetric helper for the previous change. From activeChangeRow == -1 the search starts past the end of the row list, so a fresh "press p" lands on the last change.

func (*DiffView) NewText

func (this *DiffView) NewText() string

NewText returns the right-side text.

func (*DiffView) NextChangeRow

func (this *DiffView) NextChangeRow(from int) int

NextChangeRow returns the index of the next non-Same row strictly after `from`, or -1 if no such row exists. `from < 0` searches from row 0 inclusive (i.e. "find the first change from the top"). The search does NOT wrap around — past-the-last-change yields -1 so JumpToNextChange stops at the bottom rather than cycling.

func (*DiffView) OldText

func (this *DiffView) OldText() string

OldText returns the left-side text.

func (*DiffView) OnKeyDown

func (this *DiffView) OnKeyDown(key int, repeat bool)

OnKeyDown wires n/p to JumpToNextChange / JumpToPrevChange. Letter keys arrive as uppercase ASCII (see keyboard_glfw.go's A-Z mapping), which is the same convention ComboBox's type-ahead relies on.

func (*DiffView) OnLeftDown

func (this *DiffView) OnLeftDown(x, y float64)

OnLeftDown grabs focus so subsequent wheel and key events route here, and sets the active change row to whatever row the click landed on when that row is a change. Clicks on Same rows just take focus without disturbing the navigation cursor — landing the cursor on a non-change row would be surprising relative to the n/p behaviour. In patch mode a click inside a hunk header's action zone fires the stage/revert callback and consumes the click instead.

func (*DiffView) OnMouseWheel

func (this *DiffView) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls both columns together. We measure the line height from the theme font so the step matches the rendered row size.

func (*DiffView) PatchFile

func (this *DiffView) PatchFile() DiffPatchFile

PatchFile returns the patch last handed to SetPatchFile (zero value when the view is in plain two-text mode).

func (*DiffView) PrevChangeRow

func (this *DiffView) PrevChangeRow(from int) int

PrevChangeRow returns the index of the previous non-Same row strictly before `from`, or -1 if none. `from > len(rows)` searches from the end (i.e. "find the last change from the bottom"). Like NextChangeRow, the search does NOT wrap around — past-the-first yields -1.

func (*DiffView) SetActiveChangeRow

func (this *DiffView) SetActiveChangeRow(row int)

SetActiveChangeRow marks `row` as the active change row and scrolls it into view. Passing -1 (or any out-of-range index) clears the active row without scrolling. The scroll machinery is the same scrollY/lh model OnMouseWheel uses, so the marker stays aligned with the per-row tints.

func (*DiffView) SetNewText

func (this *DiffView) SetNewText(s string)

SetNewText replaces only the right side. Symmetric to SetOldText.

func (*DiffView) SetOldText

func (this *DiffView) SetOldText(s string)

SetOldText replaces only the left side. The diff is recomputed against the current right side so the user sees the new comparison immediately.

func (*DiffView) SetPatchFile

func (this *DiffView) SetPatchFile(f DiffPatchFile)

SetPatchFile shows one file's patch as a whole-file side-by-side diff: the unchanged gaps between hunks are reconstructed from f.OldText, each hunk is introduced by a header row carrying the stage/revert actions, and the two columns end up holding the complete old and new file text (readable back through OldText/NewText).

This is the multi-hunk, gap-aware counterpart to SetTexts. Calling either SetTexts setter afterwards returns the view to plain two-text mode.

func (*DiffView) SetShowGutter

func (this *DiffView) SetShowGutter(b bool)

SetShowGutter toggles the per-side line-number gutter. With the gutter off the diff text expands into the reclaimed space; with it on each column reserves diffGutterWidth px on the left for the line numbers.

func (*DiffView) SetTexts

func (this *DiffView) SetTexts(oldText, newText string)

SetTexts replaces both sides of the diff and recomputes the row list in one shot, then invalidates the widget. Use this when both sides change together to avoid an intermediate render with mismatched content.

func (*DiffView) ShowGutter

func (this *DiffView) ShowGutter() bool

ShowGutter reports whether the per-side line-number gutter is rendered.

func (*DiffView) SigRevertHunk

func (this *DiffView) SigRevertHunk(fn func(hunkIndex int))

SigRevertHunk is the symmetric hook for the revert affordance.

func (*DiffView) SigStageHunk

func (this *DiffView) SigStageHunk(fn func(hunkIndex int))

SigStageHunk registers the callback fired when the user clicks a hunk header's stage affordance. The argument is the hunk index, which indexes straight into the hunk slice the host built the DiffPatchFile from (and therefore into core.FilePatch.Hunks / ApplySelected).

func (*DiffView) SizeHints

func (this *DiffView) SizeHints() SizeHints

SizeHints returns the default footprint for a diff viewer: wide enough to hold two reasonable columns of monospaced text and tall enough for several lines without scrolling.

type DigitalDisplay

type DigitalDisplay struct {
	Widget
	// contains filtered or unexported fields
}

DigitalDisplay renders a numeric value in a 7-segment LCD style. Value is formatted through Format (a Printf verb such as "%.1f"). When limits are enabled the segment color changes below Lo or at/above Hi.

func NewDigitalDisplay

func NewDigitalDisplay() *DigitalDisplay

NewDigitalDisplay creates a green-on-black readout showing 0.

func (*DigitalDisplay) Color

func (this *DigitalDisplay) Color() paint.Color

Color returns the normal (lit) segment color.

func (*DigitalDisplay) Draw

func (this *DigitalDisplay) Draw(g paint.Painter)

func (*DigitalDisplay) EnumProperties

func (this *DigitalDisplay) EnumProperties(list core.IPropertyList)

func (*DigitalDisplay) Format

func (this *DigitalDisplay) Format() string

Format returns the current format verb.

func (*DigitalDisplay) Hi

func (this *DigitalDisplay) Hi() float64

Hi returns the high threshold.

func (*DigitalDisplay) Init

func (this *DigitalDisplay) Init(self IWidget)

Init carries the format verb and the segment colours (see the file note on factory construction).

func (*DigitalDisplay) Lo

func (this *DigitalDisplay) Lo() float64

Lo returns the low threshold.

func (*DigitalDisplay) SetColor

func (this *DigitalDisplay) SetColor(c paint.Color)

SetColor sets the normal (lit) segment color.

func (*DigitalDisplay) SetFormat

func (this *DigitalDisplay) SetFormat(f string)

SetFormat sets the Printf format verb used to render the value.

func (*DigitalDisplay) SetLimits

func (this *DigitalDisplay) SetLimits(lo, hi float64)

SetLimits enables lo/hi color changes at the given thresholds.

func (*DigitalDisplay) SetTagName

func (this *DigitalDisplay) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*DigitalDisplay) SetUnit

func (this *DigitalDisplay) SetUnit(s string)

SetUnit sets the trailing unit string (e.g. "°C", "bar").

func (*DigitalDisplay) SetValue

func (this *DigitalDisplay) SetValue(v float64)

SetValue sets the displayed value.

func (*DigitalDisplay) SizeHints

func (this *DigitalDisplay) SizeHints() SizeHints

func (*DigitalDisplay) TagName

func (this *DigitalDisplay) TagName() string

TagName returns the design-time tag name.

func (*DigitalDisplay) Text

func (this *DigitalDisplay) Text() string

Text returns the formatted value string (without the unit).

func (*DigitalDisplay) Unit

func (this *DigitalDisplay) Unit() string

Unit returns the trailing unit string.

func (*DigitalDisplay) Value

func (this *DigitalDisplay) Value() float64

Value returns the displayed value.

type DndAction

type DndAction int
const (
	// 忽略拖放动作
	DndIgnore DndAction = 0
	// 复制
	DndCopy DndAction = 1
	// 移动
	DndMove DndAction = 2
	// 链接
	DndLink DndAction = 4
)

type Dock

type Dock struct {
	Widget
	Brick
	// contains filtered or unexported fields
}

Dock是Frame里的"子框架", 用作视图的容器

func NewDock

func NewDock() *Dock

func (*Dock) ActiveIndex

func (this *Dock) ActiveIndex() int

func (*Dock) ActiveView

func (this *Dock) ActiveView() IWidget

func (*Dock) AddView

func (this *Dock) AddView(iw IWidget)

func (*Dock) AllViews

func (this *Dock) AllViews() (ret []IWidget)

func (*Dock) Bounds

func (this *Dock) Bounds() (x, y, w, h float64)

func (*Dock) Bounds1

func (this *Dock) Bounds1() geom.Rect

func (*Dock) Close

func (this *Dock) Close()

func (*Dock) CloseAllViews

func (this *Dock) CloseAllViews()

func (*Dock) CloseDocViews

func (this *Dock) CloseDocViews()

func (*Dock) CloseIndex

func (this *Dock) CloseIndex(idx int) bool

关闭视图 除了移除以外, 还调用视图的Close接口

func (*Dock) CloseView

func (this *Dock) CloseView(iw IWidget) bool

func (*Dock) ContainMainDock

func (this *Dock) ContainMainDock() bool

func (*Dock) Detach

func (this *Dock) Detach()

func (*Dock) DetachIfEmpty

func (this *Dock) DetachIfEmpty() bool

func (*Dock) Draw

func (this *Dock) Draw(g paint.Painter)

func (*Dock) DrawOverlay

func (this *Dock) DrawOverlay(g paint.Painter)

func (*Dock) ExportGv

func (this *Dock) ExportGv(g *gv.Graph)

func (*Dock) Frame

func (this *Dock) Frame() *Frame

func (*Dock) IndexOfView

func (this *Dock) IndexOfView(iw IWidget) int

func (*Dock) Init

func (this *Dock) Init(self IWidget)

func (*Dock) InsertView

func (this *Dock) InsertView(idx int, iw IWidget)

func (*Dock) IsMainDock

func (this *Dock) IsMainDock() bool

func (*Dock) IsVisible

func (this *Dock) IsVisible() bool

func (*Dock) Layout

func (this *Dock) Layout()

func (*Dock) LoadTDoc

func (this *Dock) LoadTDoc(doc *core.TDoc)

func (*Dock) OnDragEnter

func (this *Dock) OnDragEnter(x, y float64, dnd IDndContext)

func (*Dock) OnDragLeave

func (this *Dock) OnDragLeave()

func (*Dock) OnDragMove

func (this *Dock) OnDragMove(x, y float64, dnd IDndContext)

func (*Dock) OnDrop

func (this *Dock) OnDrop(x, y float64, dnd IDndContext)

func (*Dock) OnIdle

func (this *Dock) OnIdle()

func (*Dock) PromptSaveCloseIndex

func (this *Dock) PromptSaveCloseIndex(idx int) bool

func (*Dock) PromptSaveCloseView

func (this *Dock) PromptSaveCloseView(iw IWidget) bool

func (*Dock) RemoveIndex

func (this *Dock) RemoveIndex(idx int) IWidget

从Dock上移除视图 注: 所有关闭/移除视图的操作, 最终都调用此接口来执行

func (*Dock) RemoveView

func (this *Dock) RemoveView(iw IWidget)

func (*Dock) SaveTDoc

func (this *Dock) SaveTDoc() *core.TDoc

func (*Dock) SelfBrick

func (this *Dock) SelfBrick() IBrick

func (*Dock) SetActiveIndex

func (this *Dock) SetActiveIndex(idx int)

func (*Dock) SetBounds

func (this *Dock) SetBounds(x, y, w, h float64)

func (*Dock) SetBounds1

func (this *Dock) SetBounds1(rc geom.Rect)

func (*Dock) SetTabChangedCallback

func (this *Dock) SetTabChangedCallback(cb func(int))

SetTabChangedCallback registers a callback invoked when the active tab changes. The callback receives the new active tab index.

func (*Dock) SizeHints

func (this *Dock) SizeHints() SizeHints

func (*Dock) ViewAtIndex

func (this *Dock) ViewAtIndex(idx int) IWidget

func (*Dock) ViewCount

func (this *Dock) ViewCount() int

type DoubleValidator

type DoubleValidator struct {
	Bottom   float64
	Top      float64
	Decimals int // -1 = unlimited
}

DoubleValidator constrains input to a floating-point value in [Bottom, Top] with at most Decimals fractional digits. Decimals == 0 means integer-only; -1 (the zero value) means unlimited fractional digits.

func NewDoubleValidator

func NewDoubleValidator(bottom, top float64, decimals int) *DoubleValidator

NewDoubleValidator: decimals = -1 for unlimited, 0 for integer, N for at most N digits past the decimal point.

func (*DoubleValidator) Fixup

func (v *DoubleValidator) Fixup(input string) string

Fixup clamps the input into the range and rounds to Decimals if set. Empty / sign-only inputs are returned unchanged.

func (*DoubleValidator) Validate

func (v *DoubleValidator) Validate(input string) State

Validate. The state machine matches IntValidator's intermediate rules (signs, empty), with an additional "trailing decimal point" carve-out: "3." is Intermediate (the user is mid-typing) even though strconv rejects it.

type DropdownButton struct {
	Widget
	// contains filtered or unexported fields
}

DropdownButton is a button that opens a dropdown menu when clicked.

func NewDropdownButton

func NewDropdownButton() *DropdownButton
func (this *DropdownButton) AddItem(text string, icon paint.Icon, data interface{})
func (this *DropdownButton) Draw(g paint.Painter)
func (this *DropdownButton) EnumProperties(list core.IPropertyList)
func (this *DropdownButton) Init(iw IWidget)

Init carries the selection sentinel, not NewDropdownButton: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. At selected 0 the button reports the first item as chosen before the menu has ever been opened, while its caption still shows the "Select" placeholder.

func (this *DropdownButton) Items() []DropdownItem
func (this *DropdownButton) OnLeftDown(x, y float64)
func (this *DropdownButton) OnLeftUp(x, y float64)
func (this *DropdownButton) OnMouseEnter()
func (this *DropdownButton) OnMouseLeave()
func (this *DropdownButton) Selected() int
func (this *DropdownButton) SetItems(items []DropdownItem)
func (this *DropdownButton) SetSelected(idx int)
func (this *DropdownButton) SetText(s string)
func (this *DropdownButton) SigSelect(fn func(int, string))
func (this *DropdownButton) SizeHints() SizeHints
func (this *DropdownButton) Text() string
type DropdownItem struct {
	Text string
	Icon paint.Icon
	Data interface{}
}

DropdownItem represents an item in the dropdown menu.

type EaseFunc

type EaseFunc func(t float64) float64

EaseFunc 缓动函数类型

type Edit

type Edit struct {
	ScrollArea
	TextBlock
	// contains filtered or unexported fields
}

文本编辑框

func NewEdit

func NewEdit() *Edit

func (*Edit) AcceptCompletion

func (this *Edit) AcceptCompletion(idx int) bool

AcceptCompletion replaces the active prefix with the suggestion at idx in the current Suggestions list. No-op when idx is out of range or no completer is installed. Returns true on a successful replace.

After replacement, completionPrefixStart moves to the position immediately after the inserted candidate, so a subsequent keystroke starts a fresh completion against whatever the user types next.

func (*Edit) AlwaysDrawSelection

func (this *Edit) AlwaysDrawSelection() bool

func (*Edit) CaretPos

func (this *Edit) CaretPos() (pos int)

func (*Edit) CaretRowCol

func (this *Edit) CaretRowCol() (row, col int)

func (*Edit) Completer

func (this *Edit) Completer() *Completer

Completer returns the installed Completer, or nil.

func (*Edit) CompletionPrefix

func (this *Edit) CompletionPrefix() string

CompletionPrefix returns the substring currently being completed — from completionPrefixStart to the caret position. Hosts call this to highlight the prefix in their popup or to compute completion bounds.

func (*Edit) Copy

func (this *Edit) Copy()

func (*Edit) Cursor

func (this *Edit) Cursor() *Cursor

func (*Edit) DeleteSelection

func (this *Edit) DeleteSelection()

func (*Edit) Draw

func (this *Edit) Draw(g paint.Painter)

func (*Edit) EnumProperties

func (this *Edit) EnumProperties(list core.IPropertyList)

func (*Edit) HasAcceptableInput

func (this *Edit) HasAcceptableInput() bool

HasAcceptableInput reports whether the current text is in the Acceptable state per the installed validator. Returns true when no validator is installed (free-form text is always "acceptable"). Mirrors QLineEdit::hasAcceptableInput; hosts use it to enable / disable Submit actions when the user's input is mid-edit (Intermediate).

func (*Edit) Init

func (this *Edit) Init(iw IWidget)

func (*Edit) IsReadOnly

func (this *Edit) IsReadOnly() bool

func (*Edit) IsValid

func (this *Edit) IsValid() bool

IsValid reports whether the current text satisfies the installed validator. True when no validator is installed (free-form text is always valid) or the text is Acceptable; false for Intermediate / Invalid. Reads the cached result — O(1), no re-validation. A form gates its Submit button on this via AllValid.

func (*Edit) Layout

func (this *Edit) Layout()

func (*Edit) MaxLength

func (this *Edit) MaxLength() int

MaxLength returns the configured rune cap, or 0 when the buffer is unlimited (the default).

func (*Edit) NoFrame

func (this *Edit) NoFrame() bool

func (*Edit) OnDragEnter

func (this *Edit) OnDragEnter(x, y float64, dnd IDndContext)

func (*Edit) OnDragMove

func (this *Edit) OnDragMove(x, y float64, dnd IDndContext)

func (*Edit) OnDrop

func (this *Edit) OnDrop(x, y float64, dnd IDndContext)

func (*Edit) OnKeyDown

func (this *Edit) OnKeyDown(key int, repeat bool)

func (*Edit) OnLeftDown

func (this *Edit) OnLeftDown(x, y float64)

func (*Edit) OnLeftUp

func (this *Edit) OnLeftUp(x, y float64)

func (*Edit) OnMouseEnter

func (this *Edit) OnMouseEnter()

func (*Edit) OnMouseLeave

func (this *Edit) OnMouseLeave()

func (*Edit) OnMouseMove

func (this *Edit) OnMouseMove(x, y float64)

func (*Edit) OnMouseStop

func (this *Edit) OnMouseStop(x, y float64)

func (*Edit) OnMouseWheel

func (this *Edit) OnMouseWheel(x, y, z float64)

func (*Edit) OnTextInput

func (this *Edit) OnTextInput(s string)

func (*Edit) Padding

func (this *Edit) Padding() Padding

func (*Edit) Replace

func (this *Edit) Replace(begin, end int, s string) (caret int, old string)

func (*Edit) ScrollToCaret

func (this *Edit) ScrollToCaret()

func (*Edit) Select

func (this *Edit) Select(begin, end int)

func (*Edit) SelectAll

func (this *Edit) SelectAll()

func (*Edit) Selection

func (this *Edit) Selection() (begin, end int)

func (*Edit) SelectionText

func (this *Edit) SelectionText() string

func (*Edit) SetAlwaysShowSelection

func (this *Edit) SetAlwaysShowSelection(b bool)

func (*Edit) SetCaretPos

func (this *Edit) SetCaretPos(pos int)

func (*Edit) SetCaretRowCol

func (this *Edit) SetCaretRowCol(row, col int)

func (*Edit) SetCompleter

func (this *Edit) SetCompleter(c *Completer)

SetCompleter installs (or clears, when nil) the input completer. Subsequent text edits trigger Filter; hosts read Suggestions() and call AcceptCompletion(idx) when the user picks a candidate.

Switching completers does not retroactively re-filter — the next keystroke or an explicit refreshCompleter call updates the list.

func (*Edit) SetCompletionPrefixStart

func (this *Edit) SetCompletionPrefixStart(start int)

SetCompletionPrefixStart pins the byte offset where the active completion prefix begins. Defaults to 0 (whole text). Hosts that implement word-by-word completion (e.g. a code editor where each new identifier resets the prefix start) call this on whitespace / boundary keystrokes.

func (*Edit) SetFont

func (this *Edit) SetFont(font paint.Font)

func (*Edit) SetMaxLength

func (this *Edit) SetMaxLength(n int)

SetMaxLength sets the rune cap. n <= 0 clears any existing cap. When n is positive and the current buffer already exceeds n, the buffer is truncated to n runes and the change callback fires — an explicit API call is a deliberate limit reset, not a stray keystroke we should silently swallow.

func (*Edit) SetMultiLine

func (this *Edit) SetMultiLine(b bool)

func (*Edit) SetNoFrame

func (this *Edit) SetNoFrame(b bool)

func (*Edit) SetPadding

func (this *Edit) SetPadding(m Padding)

func (*Edit) SetReadOnly

func (this *Edit) SetReadOnly(b bool)

func (*Edit) SetSelection

func (this *Edit) SetSelection(begin, end int)

func (*Edit) SetText

func (this *Edit) SetText(s string)

func (*Edit) SetValidator

func (this *Edit) SetValidator(v Validator)

SetValidator installs (or clears, when nil) the input validator. The new validator is applied to existing text only when ValidatorFixup is called explicitly — switching validators mid-flight does not retroactively reject the current value, matching Qt's behaviour.

func (*Edit) SetWrap

func (this *Edit) SetWrap(b bool)

func (*Edit) SigSubmit

func (this *Edit) SigSubmit(fn func(interface{}, string))

func (*Edit) SigTextChanged

func (this *Edit) SigTextChanged(fn func(interface{}, string))

func (*Edit) SigTextEdited

func (this *Edit) SigTextEdited(fn func(interface{}, string))

func (*Edit) SigVerify

func (this *Edit) SigVerify(fn func(interface{}, string) bool)

func (*Edit) SizeHints

func (this *Edit) SizeHints() SizeHints

func (*Edit) Submit

func (this *Edit) Submit() bool

func (*Edit) ValidationError

func (this *Edit) ValidationError() string

ValidationError returns the human-readable reason the field is invalid, or "" when the field is valid or has no validator. Populated from the validator's ErrorMessage when it implements ErrorMessager, else a generic "invalid input". Hosts render it beside the field or via ShowToolTip.

func (*Edit) Validator

func (this *Edit) Validator() Validator

Validator returns the currently installed validator, or nil when no validator is gating input.

func (*Edit) ValidatorFixup

func (this *Edit) ValidatorFixup()

ValidatorFixup applies the installed validator's Fixupper, if any, to the current text. Typically called on lose-focus so a partial "12" auto-completes to "12.00" when DoubleValidator{Decimals: 2} is installed. Safe to call when no validator or no Fixupper is set — the text is left unchanged.

func (*Edit) ViewportSize

func (this *Edit) ViewportSize() (w, h float64)

type EditableTableModel

type EditableTableModel interface {
	SetCellText(row, col int, text string)
}

EditableTableModel is an optional capability for models that accept cell writes. Table's in-place editor commits through SetCellText, so a model that does not implement this interface stays read-only even when cell editing is enabled on the widget.

type EditorCursor

type EditorCursor struct {
	Line int
	Col  int

	AnchorLine int
	AnchorCol  int

	DesiredCol int
}

EditorCursor is one caret plus the selection anchor that belongs to it. The selection spans anchor..caret in either direction; an anchor equal to the caret means "no selection" (the same rule CodeEditor uses for hasSelection).

DesiredCol is the sticky column vertical motion aims for. Moving down onto a short line clamps Col to that line's length but leaves DesiredCol alone, so continuing onto a longer line restores the original column. A negative DesiredCol means "unset": treat Col as the sticky column.

func NewEditorCursor

func NewEditorCursor(line, col int) EditorCursor

NewEditorCursor returns a collapsed cursor at (line, col) whose sticky column is col.

func (*EditorCursor) Collapse

func (c *EditorCursor) Collapse()

Collapse drops the selection by moving the anchor onto the caret.

func (EditorCursor) HasSelection

func (c EditorCursor) HasSelection() bool

HasSelection reports whether the cursor covers a non-empty range.

func (EditorCursor) Range

func (c EditorCursor) Range() (startLine, startCol, endLine, endCol int)

Range returns the cursor's selection normalized so start <= end. A collapsed cursor returns its caret position twice (a zero-width range).

func (EditorCursor) StickyCol

func (c EditorCursor) StickyCol() int

StickyCol returns the column vertical motion should aim for: DesiredCol when it is set, otherwise the current Col.

type ErrorMessager

type ErrorMessager interface {
	// ErrorMessage returns the reason input is not Acceptable, or "" when
	// input is in fact Acceptable. Edit calls it only for non-Acceptable
	// input.
	ErrorMessage(input string) string
}

--- ErrorMessager ---------------------------------------------------

ErrorMessager is the optional companion to Validator (sibling of Fixupper): it supplies a human-readable reason when Validate returns a non-Acceptable state. Edit detects it via type assertion and stores the message in Edit.ValidationError() so a form can tell the user *why* a field is rejected. Classify-only validators (Int / Double / RegExp) omit it; Edit then falls back to a generic message.

type EventLogPanel

type EventLogPanel struct {
	Widget
	// contains filtered or unexported fields
}

EventLogPanel is a read-only 事件记录 viewer for operator screens: a scrollable list of host-supplied EventRows with a top filter bar of kind tabs. It holds nothing but plain view-model data fed through SetEvents/SetKindFilter and emits the operator's filter intent through SigFilter; the host wires that back (typically by calling SetKindFilter with the emitted kind) and re-feeds rows. This mirrors AlarmPanel's pure-view posture: no backend import, no I/O, and a pure hit-test / scroll-clamp surface that unit tests exercise without a window.

func NewEventLogPanel

func NewEventLogPanel() *EventLogPanel

NewEventLogPanel creates an empty event-log panel.

func (*EventLogPanel) Draw

func (this *EventLogPanel) Draw(g paint.Painter)

Draw renders a count header, a kind-filter bar, then one row per visible event. All backgrounds and text use Theme() semantic colours so the panel reads correctly in the dark IDE theme; only the per-kind accents are fixed.

func (*EventLogPanel) Events

func (this *EventLogPanel) Events() []EventRow

Events returns a defensive copy of the full event list in host order.

func (*EventLogPanel) Init

func (this *EventLogPanel) Init(self IWidget)

func (*EventLogPanel) KindFilter

func (this *EventLogPanel) KindFilter() string

KindFilter returns the active kind filter ("" for all).

func (*EventLogPanel) OnLeftDown

func (this *EventLogPanel) OnLeftDown(x, y float64)

OnLeftDown routes a click in the filter bar to the kind tab under the cursor, firing SigFilter with that tab's mapped kind ("all" -> ""). Clicks on the header, on a row, or on empty filter-bar space are ignored.

func (*EventLogPanel) OnMouseWheel

func (this *EventLogPanel) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the visible row list vertically.

func (*EventLogPanel) SetEvents

func (this *EventLogPanel) SetEvents(in []EventRow)

SetEvents replaces the event list with a defensive copy of in. EventRow is a value type (all strings), so the shallow copy fully isolates the panel from later mutation of the caller's slice. The current kind filter is re-applied to the new list and the scroll offset is clamped to the new content rather than reset, so a live refresh does not yank the operator's view back to the top.

func (*EventLogPanel) SetKindFilter

func (this *EventLogPanel) SetKindFilter(kind string)

SetKindFilter narrows the visible list to rows whose Kind equals kind; the empty string shows every kind. It re-derives the cached visible set and clamps the scroll offset to the (usually shorter) filtered content.

func (*EventLogPanel) SigFilter

func (this *EventLogPanel) SigFilter(fn func(kind string))

SigFilter registers the callback fired when the operator clicks a kind tab. It receives the kind to filter on, already mapped so the "all" tab emits "" — the same argument SetKindFilter expects, so the host can wire the two directly.

func (*EventLogPanel) SizeHints

func (this *EventLogPanel) SizeHints() SizeHints

type EventRow

type EventRow struct {
	Time    string // host-formatted timestamp, e.g. "15:04:05"
	Kind    string // event class the filter groups on: "alarm"/"login"/"write"/"system"/…
	Source  string // originating tag / user / subsystem
	Message string // human-readable detail
}

EventRow is one plain, already-formatted 事件记录 (event-log) entry. The host owns all formatting: it turns a backend event (package eventlog) into these four display strings before handing a slice to the panel. The panel never parses Time or classifies Kind — it only groups by the Kind string, colours the cell, and renders the row. Keeping the row a bag of strings is what lets the panel stay decoupled from the eventlog backend and GL-free testable.

type ExternalCompletion

type ExternalCompletion struct {
	Label  string // shown in the list
	Detail string // right-aligned hint (type/signature)
	Insert string // text inserted on accept (defaults to Label if empty)
}

ExternalCompletion is a completion candidate supplied by an external provider (e.g. an LSP server). The host converts its protocol items into this shape; the editor merges them with its built-in candidates in the same popup.

type FindMatch

type FindMatch struct {
	Start int
	End   int
	Line  int
	Col   int
}

FindMatch is one search hit. Start/End are byte offsets into the searched text (half-open, so text[Start:End] is the matched span). Line is the 0-based line the match starts on and Col the 0-based *rune* column within that line, matching the editor's cursorLine/cursorCol convention.

type FindModel

type FindModel struct {
	Options FindOptions
}

FindModel searches and rewrites text according to Options. It holds no document and no cursor: every method takes the text and the caret it should work from, so the same model can be pointed at any buffer and nothing can go stale behind the caller's back.

func NewFindModel

func NewFindModel(opt FindOptions) *FindModel

NewFindModel returns a model configured with opt.

func (*FindModel) Next

func (this *FindModel) Next(text string, sel FindRange, caret int) (FindMatch, bool, error)

Next returns the first match starting strictly after caret, wrapping around to the first match when caret sits at or past the last one. ok is false only when there is nothing to find. The comparison is strict so a zero-width match sitting on the caret cannot pin the cursor to itself.

func (*FindModel) Prev

func (this *FindModel) Prev(text string, sel FindRange, caret int) (FindMatch, bool, error)

Prev returns the last match starting strictly before caret, wrapping around to the last match when caret sits at or before the first one.

func (*FindModel) ReplaceAll

func (this *FindModel) ReplaceAll(text, repl string, sel FindRange) (string, []FindRange, error)

ReplaceAll replaces every match in one pass and returns the new text plus the span each replacement occupies in it. The returned ranges are offsets into the *new* text, so they stay correct when the replacement is longer or shorter than what it replaced. Matches are non-overlapping and ascending, so the rewrite is a single left-to-right splice: nothing written can be matched again and no offset drifts.

func (*FindModel) ReplaceOne

func (this *FindModel) ReplaceOne(text, repl string, sel FindRange, caret int) (string, []FindRange, error)

ReplaceOne replaces the first match starting at or after caret — the match a find bar has highlighted when the user hits Replace — wrapping around to the first match when caret is past the last one. It returns the new text and the span the replacement now occupies *in that new text*, so the caller can put its caret at the end of what it just wrote. applied holds at most one range and is nil when nothing matched.

func (*FindModel) Search

func (this *FindModel) Search(text string, sel FindRange) ([]FindMatch, error)

Search returns every match in text, ordered by offset and non-overlapping. sel is the caller's selection and is only consulted when Options.InSelection is set, in which case only matches fully inside the selection are kept — a match straddling a selection edge is dropped, and an empty selection finds nothing.

An empty Query yields no matches (never one hit per position). An invalid regular expression yields an error and no matches; a literal query can never fail to compile because it is quoted.

Zero-width patterns ("a*", "^", "\b") terminate: the scan advances one rune past an empty match instead of retrying at the same offset, and an empty match abutting the previous match is dropped. Matching runs against the whole text rather than a re-sliced tail, so ^, $ and \b see their real neighbours; ^/$ are per-line (the pattern is compiled with (?m)), which is what a find bar user expects from "^func".

type FindOptions

type FindOptions struct {
	Query         string
	Regex         bool
	CaseSensitive bool
	WholeWord     bool
	InSelection   bool
	PreserveCase  bool
}

FindOptions is one configuration of the find bar. The zero value is a case-insensitive literal search over the whole text, which is what the find bar starts out as.

Regex reads Query as a regular expression (Go RE2 syntax) instead of a literal. CaseSensitive turns off case folding for both modes. WholeWord keeps only matches bounded by non-word runes (Unicode aware, see findWordBounded). InSelection scopes the search to the caller's selection. PreserveCase affects the Replace* methods only: the replacement takes on the case pattern of the text it overwrites.

type FindRange

type FindRange struct {
	Start int
	End   int
}

FindRange is a half-open byte span [Start,End) of some text: the caller's selection on input, an applied replacement on output.

type Fixupper

type Fixupper interface {
	Fixup(input string) string
}

Fixupper is the optional companion to Validator: a chance to normalise input on lose-focus (or whenever the host calls Fixup). Typical fixups:

  • trimming whitespace
  • upper / lower casing
  • clamping a numeric value into the validator's range

Implement on the same struct as Validator when the validator naturally produces a canonical form; Edit detects the interface via type assertion and applies it transparently.

type FlexWrap

type FlexWrap struct {
	Widget
	// contains filtered or unexported fields
}

FlexWrap is a CSS-Flexbox-like wrap container. Children flow left-to-right using their SizeHints widths/heights and wrap to the next line when the available width is exceeded. Useful for tag clouds, chip groups, and any pile-of-pills UI.

func NewFlexWrap

func NewFlexWrap() *FlexWrap

NewFlexWrap returns a FlexWrap with sensible defaults: 4px spacing in both directions and zero padding.

func (*FlexWrap) AddWidget

func (this *FlexWrap) AddWidget(iw IWidget)

AddWidget appends a child. Layout is recomputed lazily on the next Layout() call (or eagerly via relayout()). The child's parent is set to this FlexWrap.

func (*FlexWrap) Draw

func (this *FlexWrap) Draw(g paint.Painter)

Draw — no FlexWrap-specific painting. Children are painted by the framework after this method returns.

func (*FlexWrap) EnumProperties

func (this *FlexWrap) EnumProperties(list core.IPropertyList)

func (*FlexWrap) Layout

func (this *FlexWrap) Layout()

Layout flows visible children left-to-right, wrapping to a new line when a child would overflow the available width. Each child is sized to its SizeHints.Width/Height (clamped to MinWidth/MaxWidth where set). Reuses the shared layoutScratch pool to avoid allocations on the hot path.

func (*FlexWrap) RowGap

func (this *FlexWrap) RowGap() float64

func (*FlexWrap) SetPadding

func (this *FlexWrap) SetPadding(p Padding)

func (*FlexWrap) SetRowGap

func (this *FlexWrap) SetRowGap(g float64)

func (*FlexWrap) SetSpacing

func (this *FlexWrap) SetSpacing(s float64)

func (*FlexWrap) SizeHints

func (this *FlexWrap) SizeHints() SizeHints

SizeHints reports the natural size of the FlexWrap given its current width. Width: longest packed row, capped at the configured width if any. Height: total stacked row heights + row gaps + vertical padding. If no width is set yet, returns the sum of intrinsic widths as a single row.

func (*FlexWrap) Spacing

func (this *FlexWrap) Spacing() float64

type FocusPolicy

type FocusPolicy int

FocusPolicy 描述一个控件参与 Tab 焦点链的方式.

const (
	// AutoFocus 是零值: 按启发式判定 —— 控件可见、可用且实现了
	// IEventKeyDown 时即可被 Tab 聚焦. 未显式设置策略的控件都是此值.
	AutoFocus FocusPolicy = iota

	// NoFocus 显式把控件排除出 Tab 焦点链, 即便它实现了 IEventKeyDown.
	NoFocus

	// TabFocus 显式声明控件可被 Tab 聚焦, 即便它没有实现 IEventKeyDown.
	TabFocus
)

type FoldKind

type FoldKind string

FoldKind classifies what a fold region encloses.

const (
	FoldKindBlock   FoldKind = "block"   // a { ... } brace block
	FoldKindImport  FoldKind = "import"  // an import ( ... ) group
	FoldKindComment FoldKind = "comment" // a run of whole-line comments
)

type Form

type Form struct {
	Widget
	// contains filtered or unexported fields
}

表单 用界面编辑器编辑界面时的容器, 控件要放在表单上 程序里加载上来后, 可作为对话框显示, 也可嵌到其他控件中

func LoadForm

func LoadForm(filename string) (*Form, error)

LoadForm loads a UI design from a .silkui file (or any legacy design file produced by the Silk designer: .cml / .silk / .form) and returns a live Form widget that can be shown immediately.

This entry point does NOT require the ged package, so any Go app can consume a designer-produced layout using just silk/core + silk/gui.

Example:

form, err := gui.LoadForm("main.silkui")
if err != nil { log.Fatal(err) }
form.SetParent(mainFrame)
form.Show()

func LoadFormFromDoc

func LoadFormFromDoc(doc *core.TDoc) (*Form, error)

LoadFormFromDoc creates a Form from an already-parsed TDoc. Useful when the design was loaded from an embedded resource or generated on the fly.

The accepted document shape matches the output of ged.GedScene.SaveDesign:

root: val="form", WriteAttr("bounds", Rect), WriteAttr("title", string)
  "children":
    child: val=<factoryName>, WriteAttr("bounds", Rect), [WriteAttr("name", string)]
      ... nested children ...

For forward compatibility, a few modern attribute keys are also accepted:

  • root-level "form_title" / "form_w" / "form_h"
  • per-widget "factory" (string) / "x" "y" "w" "h" (float, mm)
  • per-widget "text" / "checked"
  • nested children under a "widget"-keyed sub-node

func NewForm

func NewForm() *Form

func (*Form) Draw

func (this *Form) Draw(g paint.Painter)

func (*Form) EnumProperties

func (this *Form) EnumProperties(list core.IPropertyList)

func (*Form) Icon

func (this *Form) Icon() paint.Icon

func (*Form) LoadGui

func (this *Form) LoadGui(doc *core.TDoc) error

func (*Form) SetIcon

func (this *Form) SetIcon(icon paint.Icon)

func (*Form) SetTitle

func (this *Form) SetTitle(s string)

func (*Form) Title

func (this *Form) Title() string

type FormLayout

type FormLayout struct {
	Widget
	// contains filtered or unexported fields
}

FormLayout is a two-column layout with labels on the left and widgets on the right (similar to QFormLayout).

func NewFormLayout

func NewFormLayout() *FormLayout

func (*FormLayout) AddRow

func (this *FormLayout) AddRow(labelText string, w IWidget)

AddRow adds a label+widget pair to the form. A Label is created internally for the label text, with right alignment.

func (*FormLayout) Draw

func (this *FormLayout) Draw(g paint.Painter)

func (*FormLayout) EnumProperties

func (this *FormLayout) EnumProperties(list core.IPropertyList)

func (*FormLayout) Init

func (this *FormLayout) Init(self IWidget)

Init carries the label column width, not NewFormLayout: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A zero labelWidth starts the field column at x=0, so every field paints on top of its own label.

func (*FormLayout) LabelWidth

func (this *FormLayout) LabelWidth() float64

func (*FormLayout) Layout

func (this *FormLayout) Layout()

func (*FormLayout) RowHeight

func (this *FormLayout) RowHeight() float64

func (*FormLayout) SetLabelWidth

func (this *FormLayout) SetLabelWidth(w float64)

func (*FormLayout) SetPadding

func (this *FormLayout) SetPadding(p Padding)

func (*FormLayout) SetRowHeight

func (this *FormLayout) SetRowHeight(h float64)

func (*FormLayout) SetSpacing

func (this *FormLayout) SetSpacing(s float64)

func (*FormLayout) SizeHints

func (this *FormLayout) SizeHints() SizeHints

func (*FormLayout) Spacing

func (this *FormLayout) Spacing() float64

type FormRow

type FormRow struct {
	// contains filtered or unexported fields
}

FormRow represents a label+widget pair in the form layout.

type FormulaRow

type FormulaRow struct {
	Output string // target tag / cell the formula writes, e.g. "TIC-101.SP"
	Expr   string // formula source, e.g. "A + B * 2"
	Status string // host-formatted result: "ok", or an error like "div by zero"
}

FormulaRow is one plain, already-formatted row for CalcPanel. The host owns all evaluation: it turns a backend formula (package calc) into these three display strings before handing a slice to the panel. Output is the target the formula writes, Expr the formula source, and Status a host-formatted result — "ok" for a clean evaluation or an error message otherwise. Keeping the row a bag of strings is what lets the panel stay decoupled from the calc backend (it never imports it) and GL-free testable.

type Frame

type Frame struct {
	Widget
	// contains filtered or unexported fields
}

Frame是程序的主框架窗口, 程序可以有一个或多个主框架

func AllFrames

func AllFrames() (list []*Frame)

func DefaultFrame

func DefaultFrame() *Frame

获取默认框架, 如果未制定则返回最先创建的框架 打开文档, 显示视图时, 如果没有指定框架, 则应放到此框架中 如果默认框架已经关闭, 则系统将任意选一个框架作为替补 建议应用层把主框架设为默认框架 建议应用层在关闭默认框架时退出程序

func FindFrameByUuid

func FindFrameByUuid(uuid core.Uuid) *Frame

func FindOwnerFrame

func FindOwnerFrame(iw IWidget) *Frame

func LoadFrameSession

func LoadFrameSession(doc *core.TDoc) (*Frame, error)

加载框架布局 如果对应框架已经存在, 则在原有框架上加载 如果对应框架不存在, 则创建一个新的框架, 再加载

func NewFrame

func NewFrame() *Frame

创建框架Widget 此函数为了和其他Widget保持相同编码风格, 仅创建框架本身 如需同时创建框架窗口请用NewFrameWindow

func NewFrameWindow

func NewFrameWindow() *Frame

创建空的框架窗口, 初始Uuid为零, 窗口为不可见状态

func (*Frame) ActiveDock

func (this *Frame) ActiveDock() IDock

func (*Frame) ActiveView

func (this *Frame) ActiveView() (IWidget, IDock)

func (*Frame) AllDocks

func (this *Frame) AllDocks() (ret []IDock)

func (*Frame) AllViews

func (this *Frame) AllViews() (ret []IWidget)

func (*Frame) CanClose

func (this *Frame) CanClose() bool

CanClose reports whether a window-manager close may proceed. True when no callback is installed, so a frame that never opted in closes as before.

func (*Frame) Close

func (this *Frame) Close()

func (*Frame) CloseAllViews

func (this *Frame) CloseAllViews()

func (*Frame) CloseDocViews

func (this *Frame) CloseDocViews()

func (*Frame) CloseToolView

func (this *Frame) CloseToolView(id string) bool

func (*Frame) CurrentDocView

func (this *Frame) CurrentDocView() (IWidget, IDock)

func (*Frame) DirtyList

func (this *Frame) DirtyList() (list []string)

func (*Frame) Draw

func (this *Frame) Draw(g paint.Painter)

func (*Frame) DrawOverlay

func (this *Frame) DrawOverlay(g paint.Painter)

func (*Frame) ExportGv

func (this *Frame) ExportGv(g *gv.Graph)

func (*Frame) HideToolView

func (this *Frame) HideToolView(id string)

func (*Frame) Init

func (this *Frame) Init(iw IWidget)

func (*Frame) IsToolView

func (this *Frame) IsToolView(iw IWidget) bool

判断一个已打开的视图是否本框架的工具视图

func (*Frame) IsToolViewVisible

func (this *Frame) IsToolViewVisible(id string) bool

func (*Frame) Layout

func (this *Frame) Layout()

func (*Frame) LeftSidebar

func (this *Frame) LeftSidebar() IWidget

LeftSidebar returns the frame's left sidebar widget, or nil if none.

func (*Frame) LoadSession

func (this *Frame) LoadSession(doc *core.TDoc) error

把框架布局加载到当前框架

func (*Frame) MainDock

func (this *Frame) MainDock() IDock

查找主停靠区 主停靠区在没有视图停靠时也不自动关闭, 通常用来停靠文档视图 正常情况下框架有0至1个主停靠区

func (*Frame) MainMenu

func (this *Frame) MainMenu() *Menu

func (*Frame) OnDragEnter

func (this *Frame) OnDragEnter(x, y float64, dnd IDndContext)

func (*Frame) OnDragLeave

func (this *Frame) OnDragLeave()

func (*Frame) OnDragMove

func (this *Frame) OnDragMove(x, y float64, dnd IDndContext)

func (*Frame) OnDrop

func (this *Frame) OnDrop(x, y float64, dnd IDndContext)

func (*Frame) OnIdle

func (this *Frame) OnIdle()

func (*Frame) OnLeftDown

func (this *Frame) OnLeftDown(x, y float64)

func (*Frame) OnLeftUp

func (this *Frame) OnLeftUp(x, y float64)

func (*Frame) OnMouseMove

func (this *Frame) OnMouseMove(x, y float64)

func (*Frame) PromptSaveCloseView

func (this *Frame) PromptSaveCloseView(view IWidget) bool

此函数正确找到Dock, 然后通过Dock关闭视图

func (*Frame) RootBrick

func (this *Frame) RootBrick() IBrick

func (*Frame) Save

func (this *Frame) Save() bool

func (*Frame) SaveSession

func (this *Frame) SaveSession() (doc *core.TDoc, err error)

保存当前框架布局 注: uuid为零时也保存

func (*Frame) SetActiveDock

func (this *Frame) SetActiveDock(dock IDock)

func (*Frame) SetCanCloseCallback

func (this *Frame) SetCanCloseCallback(fn func(*Frame) bool)

SetCanCloseCallback installs a veto for a close asked for by the window manager (the title bar's close button). Returning false leaves the window standing exactly as it was.

This is the only hook that can still say no: Close() runs CloseAllViews before the closing/closed callbacks get a word in, so an application that has to ask "unsaved work — really quit?" would be asking it after the views it was protecting are already gone.

func (*Frame) SetClosedCallback

func (this *Frame) SetClosedCallback(fn func(*Frame))

func (*Frame) SetClosingCallback

func (this *Frame) SetClosingCallback(fn func(*Frame))

func (*Frame) SetLeftSidebar

func (this *Frame) SetLeftSidebar(w IWidget)

SetLeftSidebar sets a fixed-width widget on the left edge of the frame, between the toolbar and the dock area. Used for mode selectors.

func (*Frame) SetStatusBar

func (this *Frame) SetStatusBar(sb *StatusBar)

SetStatusBar sets the status bar at the bottom of the frame.

func (*Frame) SetTitle

func (this *Frame) SetTitle(s string)

func (*Frame) SetToolBar

func (this *Frame) SetToolBar(tb *ToolBar)

SetToolBar sets an optional toolbar below the menu bar.

func (*Frame) SetUuid

func (this *Frame) SetUuid(a core.Uuid) error

func (*Frame) SetUuidStr

func (this *Frame) SetUuidStr(s string) error

func (*Frame) ShowToolView

func (this *Frame) ShowToolView(id string) bool

func (*Frame) StatusBar

func (this *Frame) StatusBar() *StatusBar

StatusBar returns the frame's status bar, or nil if none.

func (*Frame) SuggestDocDock

func (this *Frame) SuggestDocDock() IDock

查找用于停靠文档视图的停靠区

func (*Frame) SuggestToolDock

func (this *Frame) SuggestToolDock() IDock

查找用于停靠工具视图的停靠区

func (*Frame) Title

func (this *Frame) Title() string

func (*Frame) ToolBar

func (this *Frame) ToolBar() *ToolBar

ToolBar returns the frame's toolbar, or nil if none.

func (*Frame) ToolViewActions

func (this *Frame) ToolViewActions() (list []IAction)

func (*Frame) ToolViewById

func (this *Frame) ToolViewById(id string) IWidget

查找已打开的工具视图

func (*Frame) Uuid

func (this *Frame) Uuid() core.Uuid

type Gauge

type Gauge struct {
	Widget
	// contains filtered or unexported fields
}

Gauge renders a semi-circular meter with a needle.

func NewGauge

func NewGauge() *Gauge

NewGauge creates a ready-to-use Gauge widget.

func (*Gauge) AddZone

func (this *Gauge) AddZone(start, end float64, color paint.Color)

AddZone adds a colored arc region.

func (*Gauge) ClearZones

func (this *Gauge) ClearZones()

ClearZones removes all zones.

func (*Gauge) Draw

func (this *Gauge) Draw(g paint.Painter)

Draw renders the gauge.

func (*Gauge) EnumProperties

func (this *Gauge) EnumProperties(list core.IPropertyList)

EnumProperties exposes inspectable properties.

func (*Gauge) Init

func (this *Gauge) Init(self IWidget)

Init carries the range and the background, not NewGauge: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A range left in the constructor comes up as 0..0, which clamps every SetValue to 0, pins the needle at the left stop and prints a scale of all zeroes.

func (*Gauge) Max

func (this *Gauge) Max() float64

Max returns the range maximum.

func (*Gauge) Min

func (this *Gauge) Min() float64

Min returns the range minimum.

func (*Gauge) SetMax

func (this *Gauge) SetMax(v float64)

SetMax sets the range maximum.

func (*Gauge) SetMin

func (this *Gauge) SetMin(v float64)

SetMin sets the range minimum.

func (*Gauge) SetRange

func (this *Gauge) SetRange(min, max float64)

SetRange sets the minimum and maximum values.

func (*Gauge) SetTitle

func (this *Gauge) SetTitle(s string)

SetTitle sets the gauge title.

func (*Gauge) SetUnit

func (this *Gauge) SetUnit(s string)

SetUnit sets the value unit string.

func (*Gauge) SetValue

func (this *Gauge) SetValue(v float64)

SetValue sets the needle position.

func (*Gauge) SizeHints

func (this *Gauge) SizeHints() SizeHints

SizeHints returns the preferred size.

func (*Gauge) Title

func (this *Gauge) Title() string

Title returns the current title.

func (*Gauge) Unit

func (this *Gauge) Unit() string

Unit returns the current unit.

func (*Gauge) Value

func (this *Gauge) Value() float64

Value returns the current value.

type GaugeZone

type GaugeZone struct {
	Start, End float64
	Color      paint.Color
}

GaugeZone defines a colored arc region on a Gauge.

type GitLineStatus

type GitLineStatus int

GitLineStatus indicates the git modification state of a single line.

const (
	GitUnchanged GitLineStatus = iota
	GitAdded                   // green bar — new line not in HEAD
	GitModified                // blue bar — changed line
	GitDeleted                 // red triangle — line(s) deleted after this position
)

type GridCell

type GridCell struct {
	// contains filtered or unexported fields
}

GridCell represents a widget placed in the grid at a specific row/column with optional span.

type GridLayout

type GridLayout struct {
	Widget
	// contains filtered or unexported fields
}

GridLayout is a layout container that arranges children in a grid (similar to QGridLayout).

func NewGridLayout

func NewGridLayout() *GridLayout

func (*GridLayout) AddWidget

func (this *GridLayout) AddWidget(w IWidget, row, col int)

AddWidget places a widget at the given row and column with span of 1x1.

func (*GridLayout) AddWidgetSpan

func (this *GridLayout) AddWidgetSpan(w IWidget, row, col, rowSpan, colSpan int)

AddWidgetSpan places a widget at the given row and column with the specified row/col span.

func (*GridLayout) Draw

func (this *GridLayout) Draw(g paint.Painter)

func (*GridLayout) EnumProperties

func (this *GridLayout) EnumProperties(list core.IPropertyList)

func (*GridLayout) Layout

func (this *GridLayout) Layout()

func (*GridLayout) SetColumnWidth

func (this *GridLayout) SetColumnWidth(col int, width float64)

SetColumnWidth sets a fixed width for a column. Pass 0 for flexible sizing.

func (*GridLayout) SetPadding

func (this *GridLayout) SetPadding(p Padding)

func (*GridLayout) SetRowHeight

func (this *GridLayout) SetRowHeight(row int, height float64)

SetRowHeight sets a fixed height for a row. Pass 0 for flexible sizing.

func (*GridLayout) SetSpacing

func (this *GridLayout) SetSpacing(s float64)

func (*GridLayout) SizeHints

func (this *GridLayout) SizeHints() SizeHints

func (*GridLayout) Spacing

func (this *GridLayout) Spacing() float64

type GroupBox

type GroupBox struct {
	Widget
	// contains filtered or unexported fields
}

GroupBox is a container widget with a titled border, equivalent to QGroupBox in Qt.

func NewGroupBox

func NewGroupBox(title string) *GroupBox

func (*GroupBox) AddWidget

func (this *GroupBox) AddWidget(iw IWidget)

func (*GroupBox) Content

func (this *GroupBox) Content() IWidget

func (*GroupBox) Draw

func (this *GroupBox) Draw(g paint.Painter)

func (*GroupBox) EnumProperties

func (this *GroupBox) EnumProperties(list core.IPropertyList)

func (*GroupBox) Init

func (this *GroupBox) Init(self IWidget)

func (*GroupBox) IsCheckable

func (this *GroupBox) IsCheckable() bool

func (*GroupBox) IsChecked

func (this *GroupBox) IsChecked() bool

func (*GroupBox) Layout

func (this *GroupBox) Layout()

func (*GroupBox) OnLeftDown

func (this *GroupBox) OnLeftDown(x, y float64)

OnLeftDown toggles the group when checkable and the press lands on the title row (the check box indicator or the title text beside it). It is a no-op when not checkable, so a plain group keeps its previous behaviour of having no click handling. Toggling fires SigToggled and takes focus, like a check box.

func (*GroupBox) SetCheckable

func (this *GroupBox) SetCheckable(b bool)

SetCheckable turns the title check box on or off. Switching into checkable mode applies the current checked state to the content so the enabled state is consistent from the start; switching out re-enables the content.

func (*GroupBox) SetChecked

func (this *GroupBox) SetChecked(b bool)

SetChecked sets the checked state. It only does work (propagating enabled state, firing SigToggled, repainting) when the value actually changes, so a redundant set is a no-op and never re-fires the callback.

func (*GroupBox) SetContent

func (this *GroupBox) SetContent(w IWidget)

func (*GroupBox) SetTitle

func (this *GroupBox) SetTitle(s string)

func (*GroupBox) SigToggled

func (this *GroupBox) SigToggled(fn func(bool))

SigToggled registers a callback fired whenever the checked state changes (QGroupBox::toggled). The new state is passed to the callback.

func (*GroupBox) SizeHints

func (this *GroupBox) SizeHints() SizeHints

func (*GroupBox) Title

func (this *GroupBox) Title() string

type GuiModel

type GuiModel struct {
	// contains filtered or unexported fields
}

////////////////////////////////////////////

func (*GuiModel) BeginReset

func (this *GuiModel) BeginReset()

func (*GuiModel) EndReset

func (this *GuiModel) EndReset()

func (*GuiModel) HasChildren

func (this *GuiModel) HasChildren(mi ModelIndex) bool

func (*GuiModel) Init

func (this *GuiModel) Init(self IGuiModel)

type GuiView

type GuiView struct {
	ScrollArea
	// contains filtered or unexported fields
}

/////////////////////////////////////////// 模型-视图机制的视图, 此为抽象基类

func (*GuiView) Close

func (this *GuiView) Close()

func (*GuiView) ContextMenuCallback

func (this *GuiView) ContextMenuCallback() func(w IWidget, x, y float64)

func (*GuiView) Init

func (this *GuiView) Init(iw IWidget)

func (*GuiView) OnBeginReset

func (this *GuiView) OnBeginReset()

func (*GuiView) OnEndReset

func (this *GuiView) OnEndReset()

func (*GuiView) OnRightUp

func (this *GuiView) OnRightUp(x, y float64)

func (*GuiView) SetContextMenuCallback

func (this *GuiView) SetContextMenuCallback(fn func(w IWidget, x, y float64))

type HBox

type HBox struct {
	Widget
	// contains filtered or unexported fields
}

HBox is a layout container that stacks children horizontally. Supports stretch weights, alignment, minimum sizes, and hidden-widget skipping.

func NewHBox

func NewHBox() *HBox

func (*HBox) AddWidget

func (this *HBox) AddWidget(iw IWidget)

func (*HBox) Draw

func (this *HBox) Draw(g paint.Painter)

func (*HBox) EnumProperties

func (this *HBox) EnumProperties(list core.IPropertyList)

func (*HBox) Layout

func (this *HBox) Layout()

func (*HBox) SetPadding

func (this *HBox) SetPadding(p Padding)

func (*HBox) SetSpacing

func (this *HBox) SetSpacing(s float64)

func (*HBox) SetVAlign

func (this *HBox) SetVAlign(a VertAlign)

func (*HBox) SizeHints

func (this *HBox) SizeHints() SizeHints

func (*HBox) Spacing

func (this *HBox) Spacing() float64

func (*HBox) VAlign

func (this *HBox) VAlign() VertAlign

type HeaderView

type HeaderView struct {
	GuiView
	// contains filtered or unexported fields
}

表头视图

func NewHeaderView

func NewHeaderView() *HeaderView

func (*HeaderView) AutoSectionSize

func (this *HeaderView) AutoSectionSize(visualIndex int)

func (*HeaderView) Draw

func (this *HeaderView) Draw(g paint.Painter)

func (*HeaderView) IniPath

func (this *HeaderView) IniPath() string

func (*HeaderView) Init

func (this *HeaderView) Init(iw IWidget)

func (*HeaderView) Layout

func (this *HeaderView) Layout()

func (*HeaderView) LogicIndexAt

func (this *HeaderView) LogicIndexAt(pos float64) int

func (*HeaderView) LogicSection

func (this *HeaderView) LogicSection(sid int) HeaderViewSection

LogicSection returns the section whose LogicIndex matches sid. If no section matches (e.g. a stale or out-of-range logic index) it returns the zero-value HeaderViewSection sentinel instead of panicking, so a bad index can never crash the host application. A zero-value result has Size == 0 and Hidden == false; callers that must distinguish a real match can compare the returned LogicIndex against the requested sid.

func (*HeaderView) Model

func (this *HeaderView) Model() IGuiModel

func (*HeaderView) OnBeginReset

func (this *HeaderView) OnBeginReset()

func (*HeaderView) OnEndReset

func (this *HeaderView) OnEndReset()

func (*HeaderView) ScrollOffset

func (this *HeaderView) ScrollOffset() (offset float64)

func (*HeaderView) SectionCount

func (this *HeaderView) SectionCount() int

func (*HeaderView) SetIniPath

func (this *HeaderView) SetIniPath(path string)

func (*HeaderView) SetModel

func (this *HeaderView) SetModel(m IGuiModel)

func (*HeaderView) SetScrollOffset

func (this *HeaderView) SetScrollOffset(offset float64)

func (*HeaderView) TotalSectionSize

func (this *HeaderView) TotalSectionSize() (sz float64)

func (*HeaderView) VisualSection

func (this *HeaderView) VisualSection(vid int) HeaderViewSection

type HeaderViewSection

type HeaderViewSection struct {
	Offset      float64
	Size        float64
	LogicIndex  int // 和Model里的列号对应
	VisualIndex int // 用户看到的列序号, 隐藏的也编号
	Hidden      bool
}

表头视图的一节

type HighlightRange

type HighlightRange struct {
	Line     int
	StartCol int // UTF-16 code-unit column, 0-based
	EndCol   int // UTF-16 code-unit column, 0-based, exclusive
}

HighlightRange is a host-fed occurrence-highlight range in LSP coordinates: 0-based Line, 0-based UTF-16 StartCol / EndCol (EndCol exclusive). The editor converts the UTF-16 columns to rune columns internally.

type HorzAlign

type HorzAlign int
const (
	HA_LEFT HorzAlign = iota
	HA_CENTER
	HA_RIGHT
)

type IAction

type IAction interface {
	//core.ICallback
	Text() string
	SetText(text string)
	Icon() paint.Icon
	SetIcon(icon paint.Icon)
	ObjName() string
	SetObjName(objname string)
	IsEnabled() bool
	SetEnabled(b bool)
	IsChecked() bool
	SetChecked(b bool)
	MTime() time.Time
	Rev() uint64
	Trigger(sender interface{})

	BindFunc(fn func(IAction, interface{}))
	BindFunc0(fn func())
	BindFunc1(fn func(IAction))

	BindAction(a IAction)

	SetExtra(a interface{})
	Extra() interface{}
}

Action 是按钮/菜单等命令的抽象

type IBrick

type IBrick interface {
	SelfBrick() IBrick
	LeftContainMainDock() bool
	RightContainMainDock() bool
	ContainMainDock() bool
	IsLeftVisible() bool
	IsRightVisible() bool
	IsVisible() bool
	SetBounds(x, y, w, h float64)
	Bounds() (x, y, w, h float64)
	Layout()
	DropRect(split float64, left, vert, merge bool) (xd, yd, wd, hd float64)
	DropSplitHint(xp, yp float64) (split float64, left, vert, merge bool)

	SetSplit(split float64)
	SetVertical(vert bool)
	IsVertical() bool
	Left() IBrick
	SetLeft(t IBrick)
	Right() IBrick
	SetRight(t IBrick)

	ParentBrick() IBrick

	Frame() *Frame

	Split(t IBrick, split float64, left, vert bool)
	SplitNewDock(left, vert bool) IDock

	Sibling() IBrick
	FindSplitter(x, y float64) IBrick
	SetSplitPoint(x, y float64)

	SaveTDoc() *core.TDoc
	LoadTDoc(doc *core.TDoc)
	// contains filtered or unexported methods
}

Brick是Frame里的分格方块 (原为Tile, 但Tile和Title容易搞混)

type IButton

type IButton interface {
	HideSubPopup()
	ShowSubPopup()
	IsInPopupMenu() bool

	SetTextVisible(bool)
	SubPopup() IWidget
	// contains filtered or unexported methods
}

type ICommand

type ICommand interface {
	Redo()
	Undo()
	Text() string
}

type IContextMenuProvider

type IContextMenuProvider interface {
	BuildContextMenu(menu *Menu, x, y float64)
}

IContextMenuProvider — any widget can implement this interface to provide a context menu when right-clicked.

type IDndContext

type IDndContext interface {
	// 可能的动作
	PosibleActions() DndAction
	// 当前动作
	Action() DndAction
	// 设置当前动作
	SetAction(act DndAction)
	// 来源
	// 来自程序内部时, 一般是某个控件
	// 来自程序外部时为nil
	From() interface{}
	// 数据的格式
	Formats() (formats []string)
	// 检测是否有指定格式的数据
	HasFormat(format string) bool
	// 获取指定格式的数据
	Data(format string) (data interface{})
}

拖放事件的上下文参数

type IDock

type IDock interface {
	IWidget
	IsMainDock() bool
	RemoveIndex(int) IWidget
	DetachIfEmpty() bool
	ViewCount() int
	AddView(iw IWidget)
	InsertView(idx int, iw IWidget)
	Frame() *Frame
	AllViews() []IWidget
	Close()

	CloseDocViews()
	CloseAllViews()

	PromptSaveCloseIndex(idx int) bool
	PromptSaveCloseView(iw IWidget) bool
	CloseIndex(idx int) bool
	CloseView(iw IWidget) bool

	ActiveIndex() int
	ActiveView() IWidget

	Layout()
}

Dock是Frame里的"子框架", 用作视图的容器

func FallowDockPath

func FallowDockPath(root IBrick, path []int) IDock

func FindOwnerDock

func FindOwnerDock(iw IWidget) IDock

type IDrawOverlay

type IDrawOverlay interface {
	DrawOverlay(cc paint.Painter)
}

type IEdit

type IEdit interface {
	IWidget
	SetText(s string)
	Text() string
	SelectAll()
}

文本编辑框

type IEventFocusChanged

type IEventFocusChanged interface {
	OnFocusChanged(newFocusWidget, oldFocusWidget IWidget)
}

type IEventHide

type IEventHide interface {
	OnHide()
}

type IEventKeyDown

type IEventKeyDown interface {
	OnKeyDown(key int, repeat bool)
}

type IEventKeyUp

type IEventKeyUp interface {
	OnKeyUp(key int)
}

type IEventLeftDown

type IEventLeftDown interface {
	OnLeftDown(x, y float64)
}

type IEventLeftUp

type IEventLeftUp interface {
	OnLeftUp(x, y float64)
}

type IEventMiddleDown

type IEventMiddleDown interface {
	OnMiddleDown(x, y float64)
}

type IEventMiddleUp

type IEventMiddleUp interface {
	OnMiddleUp(x, y float64)
}

type IEventMouseEnter

type IEventMouseEnter interface {
	OnMouseEnter()
}

type IEventMouseLeave

type IEventMouseLeave interface {
	OnMouseLeave()
}

type IEventMouseMove

type IEventMouseMove interface {
	OnMouseMove(x, y float64)
}

type IEventMouseStop

type IEventMouseStop interface {
	OnMouseStop(x, y float64)
}

type IEventMouseWheel

type IEventMouseWheel interface {
	OnMouseWheel(x, y, z float64)
}

type IEventRightDown

type IEventRightDown interface {
	OnRightDown(x, y float64)
}

type IEventRightUp

type IEventRightUp interface {
	OnRightUp(x, y float64)
}

type IEventShow

type IEventShow interface {
	OnShow()
}

type IEventTextInput

type IEventTextInput interface {
	OnTextInput(s string)
}

type IGuiModel

type IGuiModel interface {
	Index(row, col int, parent ModelIndex) ModelIndex
	Data(idx ModelIndex, role ItemDataRole) interface{}
	HeaderData(section int, vertical bool, role ItemDataRole) interface{}
	Parent(idx ModelIndex) ModelIndex
	RowCount(parent ModelIndex) int
	ColCount() int // 列数必须统一, 和parent无关
	Flags(idx ModelIndex) ItemFlags
	HasChildren(mi ModelIndex) bool
}

////////////////////////////////////////// 模型-视图机制的模型, 此为抽象基类

type IHeightForWidth

type IHeightForWidth interface {
	HeightForWidth(float64) float64
}

type IIcon

type IIcon interface {
	// 表示对象的内容的字符串
	Icon() paint.Icon
}

type ILayout

type ILayout interface {
	Layout()
}

type IMenu

type IMenu interface {
	HideAllSubs()
}

type IOnDragLeave

type IOnDragLeave interface {
	OnDragLeave()
}

type IOnDrop

type IOnDrop interface {
	OnDragEnter(x, y float64, dnd IDndContext)
	OnDragMove(x, y float64, dnd IDndContext)
	OnDrop(x, y float64, dnd IDndContext)
}

type IOnHorzScroll

type IOnHorzScroll interface {
	OnHorzScroll(sender IWidget)
}

type IOnVertScroll

type IOnVertScroll interface {
	OnVertScroll(sender IWidget)
}

type ISaveLoadSession

type ISaveLoadSession interface {
	SaveSession() (doc *core.TDoc, err error)
	LoadSession(doc *core.TDoc) error
}

type IString

type IString interface {
	// 表示对象的内容的字符串
	String() string
}

type IText

type IText interface {
	// 表示对象的内容的字符串
	Text() string
}

type ITitle

type ITitle interface {
	// 用来显示的标题
	Title() string
}

type IUndoStack

type IUndoStack interface {
	// 命令压栈并执行
	Push(cmd ICommand)

	// 能否撤销
	CanUndo() bool

	// 撤销
	Undo()

	// 描述当前撤销操作的文本, 例如"撤销某操作"
	UndoText() string

	// 能否恢复
	CanRedo() bool

	// 恢复
	Redo()

	// 描述当前重做操作的文本, 例如"恢复某操作"
	RedoText() string

	// 堆栈里的全部命令的数目, 含撤销和恢复
	Count() int

	// 当前命令的索引, 指向下一步Push或Redo的命令
	Current() int

	// 获取指定位置的命令
	// 此方法只供查询命令的信息, 请不要在外部执行获取到的命令, 否则将发生混乱
	Command(index int) ICommand

	// 把当前位置设置为"清洁"状态, 表示文档在当前位置已保存
	SetClean()

	// 判断当前位置是否"清洁"状态
	IsClean() bool

	// Undo方法对应的Action
	UndoAction() IAction

	// Redo方法对应的Action
	RedoAction() IAction

	// 清除所有命令, 并重置Clean和Current位置
	Clear()
}

支持撤销/恢复的命令堆栈

type IWantsTab

type IWantsTab interface {
	WantsTab(shift bool) bool
}

IWantsTab lets a focused widget claim Tab before the window spends it on focus traversal.

The window layer owns Tab because no ordinary widget wants it. A design canvas does: Tab there walks the widgets being designed, which is the only way to reach one without a mouse. Without this seam the canvas never sees the key — the window moves focus to the next panel and the canvas loses it, so the next Tab walks further away.

Returning true means "I handled it"; the window then leaves focus alone.

type IWidget

type IWidget interface {

	// (控件)对象本身
	Self() IWidget

	// 裸的(内层)控件指针
	NakedWidget() *Widget

	// 和本Widget配对的窗口, 可能为空
	Window() *Window

	// 附加到窗口上
	AttachWindow(wt WindowType)

	// 附加到窗口上, 但延迟到第一次显示时才创建窗口
	// 因为创建窗口通常较慢, 所以此方法可能有助于提高创建效率
	LazyAttachWindow(wt WindowType)

	// 和窗口分离
	DetachWindow()

	// 是否已经附加到一个WtPopup窗口上
	// 注: 即使是延迟附加, 这个方法也会返回true
	IsPopup() bool

	// 本Widget所在的窗口,
	// 此窗口可能是直接和本Widget绑定, 也可能是和某祖先Widget绑定
	// 因为Widget只能显示在窗口里, 所以当Widget可见时, 此函数返回值一定是有效的窗口
	OwnerWindow() *Window

	// 父控件
	Parent() IWidget

	// 设置父控件
	SetParent(parent IWidget)

	// 根控件
	RootWidget() IWidget

	// 绘图接口
	Draw(g paint.Painter)

	// 获取X坐标
	X() float64
	// 获取Y坐标
	Y() float64
	// 获取宽度
	Width() float64
	// 获取高度
	Height() float64

	Pos() (x, y float64)
	SetPos(x, y float64)
	Size() (width, height float64)
	SetSize(width, height float64)

	Bounds() (x, y, width, height float64)
	SetBounds(x, y, width, height float64)
	Bounds1() (rect geom.Rect)
	SetBounds1(rect geom.Rect)

	UpdateRect(x, y, width, height float64)
	Update()

	// 鼠标是否在控件内部
	IsHover() bool

	MapToWindow(x, y float64) (x1, y1 float64)
	MapFromWindow(x, y float64) (x1, y1 float64)
	MapToGlobal(x, y float64) (x1, y1 float64)
	MapFromGlobal(x, y float64) (x1, y1 float64)

	FindWidgetAt(x, y float64) IWidget

	SetVisible(bool)
	IsVisible() bool
	IsAllAncentorsVisible() bool

	SetEnabled(bool)
	IsEnabled() bool

	// 显示控件, 相当于SetVisible(true)
	Show()

	// 隐藏控件, 相当于SetVisible(false)
	Hide()

	HasFocus() bool
	SetFocus()

	SetRedrawParent(b bool)
	IsRedrawParent() bool

	Cursor() *Cursor

	SizeHints() SizeHints

	PushCapture()
	PopCapture()
	HasCapture() bool

	Detach()

	Children() []IWidget

	DoDragDrop(content paint.Pixmap, availableActions DndAction, data ...interface{}) DndAction

	ExtraData() interface{}
	SetExtraData(a interface{})
}

func FindWidgetGlobal

func FindWidgetGlobal(xg, yg float64) IWidget

func FindWidgetUnderMouse

func FindWidgetUnderMouse() IWidget

type IWidgetEvent

type IWidgetEvent interface {
	OnMove()
	OnResize()
}

type IWidthForHeight

type IWidthForHeight interface {
	WidthForHeight(float64) float64
}

type IconText

type IconText struct {
	Ico paint.Icon
	Txt string
}

func (IconText) Icon

func (v IconText) Icon() paint.Icon

func (IconText) String

func (v IconText) String() string

func (IconText) Text

func (v IconText) Text() string

type ImageScaleMode

type ImageScaleMode int

ImageScaleMode 图片缩放模式

const (
	ImageContain ImageScaleMode = iota // 保持比例,完整显示
	ImageCover                         // 保持比例,填满区域
	ImageStretch                       // 拉伸填满
	ImageCenter                        // 原始大小居中显示
)

type ImageView

type ImageView struct {
	Widget
	// contains filtered or unexported fields
}

ImageView 图片显示控件

func NewImageView

func NewImageView() *ImageView

func (*ImageView) Draw

func (this *ImageView) Draw(g paint.Painter)

func (*ImageView) EnumProperties

func (this *ImageView) EnumProperties(list core.IPropertyList)

func (*ImageView) Pixmap

func (this *ImageView) Pixmap() paint.Pixmap

func (*ImageView) ScaleMode

func (this *ImageView) ScaleMode() ImageScaleMode

func (*ImageView) SetBgColor

func (this *ImageView) SetBgColor(c paint.Color)

func (*ImageView) SetPixmap

func (this *ImageView) SetPixmap(pm paint.Pixmap)

func (*ImageView) SetScaleMode

func (this *ImageView) SetScaleMode(mode ImageScaleMode)

func (*ImageView) SizeHints

func (this *ImageView) SizeHints() SizeHints

type Indicator

type Indicator struct {
	Widget
	// contains filtered or unexported fields
}

Indicator is a round status lamp that glows in On color when on and shows a dim Off color when off. Blink is a stored flag a caller may drive from the animation engine to toggle On for an alarm.

func NewIndicator

func NewIndicator() *Indicator

NewIndicator creates an off green lamp.

func (*Indicator) Color

func (this *Indicator) Color() paint.Color

Color returns the on (lit) color.

func (*Indicator) Draw

func (this *Indicator) Draw(g paint.Painter)

func (*Indicator) EnumProperties

func (this *Indicator) EnumProperties(list core.IPropertyList)

func (*Indicator) Init

func (this *Indicator) Init(self IWidget)

Init carries the lit / unlit colours (see the file note on factory construction).

func (this *Indicator) IsBlink() bool

IsBlink reports the blink flag.

func (*Indicator) IsOn

func (this *Indicator) IsOn() bool

IsOn reports the lamp state.

func (*Indicator) OffColor

func (this *Indicator) OffColor() paint.Color

OffColor returns the unlit color.

func (this *Indicator) SetBlink(b bool)

SetBlink stores the blink flag (driven externally by the animation engine).

func (*Indicator) SetColor

func (this *Indicator) SetColor(c paint.Color)

SetColor sets the on (lit) color.

func (*Indicator) SetOffColor

func (this *Indicator) SetOffColor(c paint.Color)

SetOffColor sets the unlit color.

func (*Indicator) SetOn

func (this *Indicator) SetOn(b bool)

SetOn turns the lamp on or off.

func (*Indicator) SetTagName

func (this *Indicator) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*Indicator) SizeHints

func (this *Indicator) SizeHints() SizeHints

func (*Indicator) TagName

func (this *Indicator) TagName() string

TagName returns the design-time tag name.

type InputBox

type InputBox struct {
	Form
	// contains filtered or unexported fields
}

InputBox is a styled dialog for text input with a prompt label.

func NewInputBox

func NewInputBox() *InputBox

func (*InputBox) Draw

func (this *InputBox) Draw(g paint.Painter)

func (*InputBox) Init

func (this *InputBox) Init(iw IWidget)

func (*InputBox) Layout

func (this *InputBox) Layout()

func (*InputBox) SetIcon

func (this *InputBox) SetIcon(ico paint.Icon)

func (*InputBox) SetLabel

func (this *InputBox) SetLabel(s string)

func (*InputBox) SetMessage

func (this *InputBox) SetMessage(s string)

func (*InputBox) SetTitle

func (this *InputBox) SetTitle(s string)

func (*InputBox) ShowModal

func (this *InputBox) ShowModal() bool

func (*InputBox) Title

func (this *InputBox) Title() string

type IntValidator

type IntValidator struct {
	Bottom int64
	Top    int64
}

IntValidator constrains input to integers in the inclusive range [Bottom, Top]. Bottom <= Top is the host's responsibility — a swapped pair degenerates to "no value is acceptable", which is observable but not a panic.

func NewIntValidator

func NewIntValidator(bottom, top int64) *IntValidator

NewIntValidator constructs a validator over the given range. Bottom and Top are inclusive, matching QIntValidator.

func (*IntValidator) Fixup

func (v *IntValidator) Fixup(input string) string

Fixup clamps the input into the validator's range. An unparseable input is left unchanged (Validate would already have returned Invalid). Whitespace is trimmed unconditionally — the canonical form has no spaces.

func (*IntValidator) Validate

func (v *IntValidator) Validate(input string) State

Validate classifies input. The state machine:

""        → Intermediate (user just emptied the field)
"-" "+"   → Intermediate (typed sign, no digits yet)
"abc"     → Invalid     (non-numeric)
"42"      → Acceptable  if Bottom <= 42 <= Top
          → Intermediate if 42 outside but a longer prefix could land in range
          → Invalid     if even with appended digits it can't reach the range

The Intermediate-vs-Invalid distinction outside the range is a deliberate simplification: we only check whether the absolute-value is below |Top|, which catches the common "user typed first digit of a multi-digit value" case without expensive search.

type ItemDataRole

type ItemDataRole int
const (
	//The general purpose roles (and the associated types) are:
	DisplayRole    ItemDataRole = 0  //The key data to be rendered in the form of text. (string)
	DecorationRole ItemDataRole = 1  //The data to be rendered as a decoration in the form of an icon. (QColor, QIcon or QPixmap)
	EditRole       ItemDataRole = 2  //The data in a form suitable for editing in an editor. (string)
	ToolTipRole    ItemDataRole = 3  //The data displayed in the item's tooltip. (string)
	StatusTipRole  ItemDataRole = 4  //The data displayed in the status bar. (string)
	WhatsThisRole  ItemDataRole = 5  //The data displayed for the item in "What's This?" mode. (string)
	SizeHintRole   ItemDataRole = 13 //The size hint for the item that will be supplied to views. (QSize)

	//Roles describing appearance and meta data (with associated types):
	FontRole             ItemDataRole = 6  //The font used for items rendered with the default delegate. (QFont)
	TextAlignmentRole    ItemDataRole = 7  //The alignment of the text for items rendered with the default delegate. (AlignmentFlag)
	BackgroundRole       ItemDataRole = 8  //The background brush used for items rendered with the default delegate. (QBrush)
	ForegroundRole       ItemDataRole = 9  //The foreground brush (text color, typically) used for items rendered with the default delegate. (QBrush)
	CheckStateRole       ItemDataRole = 10 //This role is used to obtain the checked state of an item. (CheckState)
	InitialSortOrderRole ItemDataRole = 14 //This role is used to obtain the initial sort order of a header view section. (SortOrder). This role was introduced in Qt 4.8.

	//Accessibility roles (with associated types):
	AccessibleTextRole        ItemDataRole = 11 //The text to be used by accessibility extensions and plugins, such as screen readers. (string)
	AccessibleDescriptionRole ItemDataRole = 12 //A description of the item for accessibility purposes. (string)

	//User roles:
	UserRole ItemDataRole = 32 //The first role that can be used for application-specific purposes.
)

type ItemFlags

type ItemFlags int
const (
	NoItemFlags         ItemFlags = 0  //	It does not have any properties set.
	ItemIsSelectable    ItemFlags = 1  //It can be selected.
	ItemIsEditable      ItemFlags = 2  //It can be edited.
	ItemIsDragEnabled   ItemFlags = 4  //It can be dragged.
	ItemIsDropEnabled   ItemFlags = 8  //It can be used as a drop target.
	ItemIsUserCheckable ItemFlags = 16 //It can be checked or unchecked by the user.
	ItemIsEnabled       ItemFlags = 32 //The user can interact with the item.
	ItemIsTristate      ItemFlags = 64 //The item is checkable with three separate states.
)

type Label

type Label struct {
	Widget
	// contains filtered or unexported fields
}

Label is a non-editable text display widget.

func NewLabel

func NewLabel(text string) *Label

func (*Label) Align

func (this *Label) Align() TextAlign

func (*Label) Draw

func (this *Label) Draw(g paint.Painter)

func (*Label) EnumProperties

func (this *Label) EnumProperties(list core.IPropertyList)

func (*Label) SetAlign

func (this *Label) SetAlign(a TextAlign)

func (*Label) SetFont

func (this *Label) SetFont(f paint.Font)

func (*Label) SetText

func (this *Label) SetText(s string)

func (*Label) SetTextColor

func (this *Label) SetTextColor(c paint.Color)

func (*Label) SetWrap

func (this *Label) SetWrap(b bool)

func (*Label) SizeHints

func (this *Label) SizeHints() SizeHints

func (*Label) Text

func (this *Label) Text() string

func (*Label) Wrap

func (this *Label) Wrap() bool

type LabelSeparator

type LabelSeparator struct {
	Widget
	// contains filtered or unexported fields
}

LabelSeparator is an enhanced separator with optional label text (e.g. "-- OR --").

func NewLabelSeparator

func NewLabelSeparator(text string) *LabelSeparator

func (*LabelSeparator) Draw

func (this *LabelSeparator) Draw(g paint.Painter)

func (*LabelSeparator) EnumProperties

func (this *LabelSeparator) EnumProperties(list core.IPropertyList)

func (*LabelSeparator) IsVertical

func (this *LabelSeparator) IsVertical() bool

func (*LabelSeparator) SetText

func (this *LabelSeparator) SetText(s string)

func (*LabelSeparator) SetVertical

func (this *LabelSeparator) SetVertical(b bool)

func (*LabelSeparator) SizeHints

func (this *LabelSeparator) SizeHints() SizeHints

func (*LabelSeparator) Text

func (this *LabelSeparator) Text() string

type LengthValidator

type LengthValidator struct {
	Min int
	Max int // <= 0 means unbounded
}

--- LengthValidator ------------------------------------------------

LengthValidator constrains input to a rune-count range [Min, Max]. Below Min is Intermediate (keep typing to reach the minimum); within range is Acceptable; above Max is Invalid (a hard cap like maxlength — the extra keystroke is dropped, since appending can only make it longer). Max <= 0 means no upper bound.

func (*LengthValidator) ErrorMessage

func (v *LengthValidator) ErrorMessage(input string) string

ErrorMessage explains a below-Min or above-Max count, "" when in range.

func (*LengthValidator) Validate

func (v *LengthValidator) Validate(input string) State

Validate classifies by rune count: below Min is Intermediate, above Max is Invalid, otherwise Acceptable.

type LineChart

type LineChart struct {
	Widget
	// contains filtered or unexported fields
}

LineChart renders one or more data series as connected line segments inside a coordinate grid.

func NewLineChart

func NewLineChart() *LineChart

NewLineChart creates a ready-to-use LineChart widget.

func (*LineChart) AddSample

func (this *LineChart) AddSample(seriesName string, t time.Time, v float64)

AddSample appends one (time, value) sample to a rolling series, dropping the oldest sample once the ring is full. The series is auto-enabled for rolling (default capacity) if AddSample is called before EnableRolling.

func (*LineChart) AddSeries

func (this *LineChart) AddSeries(name string, color paint.Color, data []float64)

AddSeries appends a named data series.

func (*LineChart) AutoScale

func (this *LineChart) AutoScale() bool

AutoScale reports whether auto-scaling is active.

func (*LineChart) ClearSeries

func (this *LineChart) ClearSeries()

ClearSeries removes all series.

func (*LineChart) Draw

func (this *LineChart) Draw(g paint.Painter)

Draw renders the chart.

func (*LineChart) EnableRolling

func (this *LineChart) EnableRolling(seriesName string, capacity int)

EnableRolling turns a series into a live rolling trend backed by a ring buffer holding the most recent capacity (time, value) samples. If the named series does not exist yet it is created with a default palette color, so a tag-bound chart can EnableRolling then AddSample without a prior AddSeries.

func (*LineChart) EnumProperties

func (this *LineChart) EnumProperties(list core.IPropertyList)

EnumProperties exposes inspectable properties.

func (*LineChart) GPUAccelerated

func (this *LineChart) GPUAccelerated() bool

GPUAccelerated reports whether the GL series fast-path is enabled.

func (*LineChart) SetAutoScale

func (this *LineChart) SetAutoScale(b bool)

SetAutoScale enables or disables automatic Y range computation.

func (*LineChart) SetGPUAccelerated

func (this *LineChart) SetGPUAccelerated(b bool)

SetGPUAccelerated toggles the GL fast-path for data series. When on (and the host window supports it), the frame/grid/axes/labels still render via Cairo but the data polylines are drawn as native GL line strips after the texture blit — cheaper for high-rate rolling trends. Off (the default) draws the series with Cairo, byte-identically to the original path.

func (*LineChart) SetShowGrid

func (this *LineChart) SetShowGrid(b bool)

SetShowGrid controls grid line drawing.

func (*LineChart) SetShowLegend

func (this *LineChart) SetShowLegend(b bool)

SetShowLegend controls legend drawing.

func (*LineChart) SetTimeWindow

func (this *LineChart) SetTimeWindow(d time.Duration)

SetTimeWindow sets the visible X span for rolling series (newest sample at the right edge). A zero or negative duration shows the whole buffer.

func (*LineChart) SetTitle

func (this *LineChart) SetTitle(s string)

SetTitle sets the chart title rendered at the top.

func (*LineChart) SetYRange

func (this *LineChart) SetYRange(min, max float64)

SetYRange sets an explicit Y range (disables auto-scale).

func (*LineChart) ShowGrid

func (this *LineChart) ShowGrid() bool

ShowGrid reports whether the grid is drawn.

func (*LineChart) ShowLegend

func (this *LineChart) ShowLegend() bool

ShowLegend reports whether the legend is drawn.

func (*LineChart) SizeHints

func (this *LineChart) SizeHints() SizeHints

SizeHints returns the preferred size.

func (*LineChart) TimeWindow

func (this *LineChart) TimeWindow() time.Duration

TimeWindow returns the current visible X span (0 = full buffer).

func (*LineChart) Title

func (this *LineChart) Title() string

Title returns the current chart title.

type LineChartSeries

type LineChartSeries struct {
	Name   string
	Color  paint.Color
	Points []float64 // Y values; X is the index
	// contains filtered or unexported fields
}

LineChartSeries holds one data series for a LineChart.

A series is either STATIC (Points, X = index — the original behaviour) or ROLLING (a fixed-capacity ring buffer of timeSamples fed via AddSample, X = time). Rolling fields are zero-valued and ignored for static series, so the static path is unchanged.

type Link struct {
	Widget
	// contains filtered or unexported fields
}

Link is a hyperlink label widget.

func NewLink(text, url string) *Link

func (*Link) Color

func (this *Link) Color() paint.Color

func (*Link) Draw

func (this *Link) Draw(g paint.Painter)

func (*Link) EnumProperties

func (this *Link) EnumProperties(list core.IPropertyList)

func (*Link) Init

func (this *Link) Init(self IWidget)

Init carries the colour, not NewLink: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Draw paints the text with this.color, so a zero colour draws it fully transparent.

func (*Link) OnLeftDown

func (this *Link) OnLeftDown(x, y float64)

func (*Link) OnMouseEnter

func (this *Link) OnMouseEnter()

func (*Link) OnMouseLeave

func (this *Link) OnMouseLeave()

func (*Link) SetColor

func (this *Link) SetColor(c paint.Color)

func (*Link) SetText

func (this *Link) SetText(s string)

func (*Link) SetURL

func (this *Link) SetURL(s string)

func (*Link) SigClick

func (this *Link) SigClick(fn func(string))

func (*Link) SizeHints

func (this *Link) SizeHints() SizeHints

func (*Link) Text

func (this *Link) Text() string

func (*Link) URL

func (this *Link) URL() string

type ListItem

type ListItem struct {
	Text    string
	Icon    paint.Icon
	Checked bool
	Data    interface{}
}

列表控件里的一项

type ListWidget

type ListWidget struct {
	ScrollArea
	// contains filtered or unexported fields
}

列表控件(不使用model-view架构)

func NewListWidget

func NewListWidget() *ListWidget

func (*ListWidget) ActiveIndex

func (this *ListWidget) ActiveIndex() int

func (*ListWidget) ActiveItem

func (this *ListWidget) ActiveItem() ListItem

func (*ListWidget) Append

func (this *ListWidget) Append(a ListItem)

func (*ListWidget) Clear

func (this *ListWidget) Clear()

Clear drops every item, and the selection with them: ActiveIndex goes back to -1. Draw only highlights a row that is the active one, so a caller that repopulates the list right after has to re-select (SetActiveIndex) or the list comes back with nothing highlighted.

func (*ListWidget) Count

func (this *ListWidget) Count() int

func (*ListWidget) Draw

func (this *ListWidget) Draw(g paint.Painter)

func (*ListWidget) EnumProperties

func (this *ListWidget) EnumProperties(list core.IPropertyList)

func (*ListWidget) Font

func (this *ListWidget) Font() paint.Font

func (*ListWidget) HitTest

func (this *ListWidget) HitTest(x, y float64) (row, col int)

func (*ListWidget) Icon

func (this *ListWidget) Icon() paint.Icon

func (*ListWidget) IconSize

func (this *ListWidget) IconSize() float64

func (*ListWidget) Init

func (this *ListWidget) Init(iw IWidget)

func (*ListWidget) Insert

func (this *ListWidget) Insert(idx int, a ListItem)

func (*ListWidget) IsCheckBoxVisible

func (this *ListWidget) IsCheckBoxVisible() bool

func (*ListWidget) IsHoverVisible

func (this *ListWidget) IsHoverVisible() bool

func (*ListWidget) IsIconVisible

func (this *ListWidget) IsIconVisible() bool

func (*ListWidget) IsSelectionVisible

func (this *ListWidget) IsSelectionVisible() bool

func (*ListWidget) Item

func (this *ListWidget) Item(idx int) ListItem

func (*ListWidget) ItemList

func (this *ListWidget) ItemList() (ret []ListItem)

func (*ListWidget) Layout

func (this *ListWidget) Layout()

Layout creates/updates the vertical scrollbar when the item list exceeds the visible viewport, and hides it when all items fit.

func (*ListWidget) OnKeyDown

func (this *ListWidget) OnKeyDown(key int, repeat bool)

键盘导航 (仿Qt QListWidget):

上/下          : 当前/选中项上移/下移一行, 到头/到尾时夹住
Home/End       : 跳到第一/最后一项
PageUp/PageDown: 按一个视口页的行数上移/下移
回车/空格      : 激活当前项 (走与点击相同的提交回调)

仅在控件持有焦点时被调用(OnLeftDown里SetFocus后才能收到键盘事件).

func (*ListWidget) OnLeftDown

func (this *ListWidget) OnLeftDown(x, y float64)

func (*ListWidget) OnLeftUp

func (this *ListWidget) OnLeftUp(x, y float64)

func (*ListWidget) OnMouseMove

func (this *ListWidget) OnMouseMove(x, y float64)

func (*ListWidget) OnMouseWheel

func (this *ListWidget) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the list by 3 rows per wheel notch.

func (*ListWidget) Padding

func (this *ListWidget) Padding() (left, right, top, bottom float64)

func (*ListWidget) Remove

func (this *ListWidget) Remove(idx int) ListItem

func (*ListWidget) RemoveLast

func (this *ListWidget) RemoveLast() ListItem

func (*ListWidget) RowHeight

func (this *ListWidget) RowHeight() float64

func (*ListWidget) SetActiveIndex

func (this *ListWidget) SetActiveIndex(idx int)

SetActiveIndex moves the selection to idx from outside the widget, through the same seam the keyboard navigation uses: idx is clamped into range (an empty list stays at "nothing selected"), the selection-changed callback fires only when the row actually moves, and the row is scrolled into view. A host that rebuilds its items with Clear + Append needs this afterwards — Clear resets the selection to -1.

func (*ListWidget) SetCheckBoxVisible

func (this *ListWidget) SetCheckBoxVisible(b bool)

func (*ListWidget) SetDragStartCallback

func (this *ListWidget) SetDragStartCallback(fn func(idx []int) ([]interface{}, DndAction))

func (*ListWidget) SetFont

func (this *ListWidget) SetFont(font paint.Font)

func (*ListWidget) SetHoverVisible

func (this *ListWidget) SetHoverVisible(b bool)

func (*ListWidget) SetIcon

func (this *ListWidget) SetIcon(icon paint.Icon)

func (*ListWidget) SetIconSize

func (this *ListWidget) SetIconSize(sz float64)

func (*ListWidget) SetIconVisible

func (this *ListWidget) SetIconVisible(b bool)

func (*ListWidget) SetItem

func (this *ListWidget) SetItem(idx int, item ListItem)

func (*ListWidget) SetPadding

func (this *ListWidget) SetPadding(left, right, top, bottom float64)

func (*ListWidget) SetRowHeight

func (this *ListWidget) SetRowHeight(rh float64)

func (*ListWidget) SetSelectionVisible

func (this *ListWidget) SetSelectionVisible(b bool)

func (*ListWidget) SetTitle

func (this *ListWidget) SetTitle(s string)

func (*ListWidget) SigCheckChanged

func (this *ListWidget) SigCheckChanged(fn func(o interface{}, idx int))

func (*ListWidget) SigSelectionChanged

func (this *ListWidget) SigSelectionChanged(fn func(o interface{}, idx []int))

func (*ListWidget) SigSubmit

func (this *ListWidget) SigSubmit(fn func(o interface{}))

func (*ListWidget) SizeHints

func (this *ListWidget) SizeHints() SizeHints

func (*ListWidget) Submit

func (this *ListWidget) Submit()

func (*ListWidget) Title

func (this *ListWidget) Title() string

type Margin

type Margin struct {
	L, R, T, B float64
}

func (Margin) Apply

func (m Margin) Apply(x, y, w, h float64) (x1, y1, w1, h1 float64)

type MatchMode

type MatchMode int

MatchMode picks how Completer.Filter compares the user's typed prefix against each candidate. Mirrors QCompleter's three-way mode set: dominant for code-completion (StartsWith), dominant for fuzzy search (Contains), and a fallback that lets every candidate through with no substring constraint at all (Anywhere — useful for "show recent values regardless of typing").

const (
	// MatchStartsWith accepts candidates whose first characters are the
	// typed prefix. The default, matching QCompleter::PopupCompletion's
	// default and the dominant interactive UX.
	MatchStartsWith MatchMode = iota

	// MatchContains accepts candidates that contain the typed prefix
	// anywhere. Useful for path / symbol search where the user remembers
	// part of the middle of the name.
	MatchContains

	// MatchAnywhere accepts every candidate regardless of the typed
	// prefix. Best for "recent values" or "command history" where the
	// candidate set itself is the filter.
	MatchAnywhere
)

func (MatchMode) String

func (m MatchMode) String() string

String aids debug + property panels.

type Menu struct {
	Widget

	VerticalT
	// contains filtered or unexported fields
}

菜单, 用来装载菜单按钮 可用作弹出菜单和传统的菜单栏 注: Menu是菜单项的容器, 不是菜单项

func BuildMenu

func BuildMenu(actions []IAction, cfgFilePath string) *Menu

func NewMenu

func NewMenu(popup bool) *Menu

新建菜单

func NewMenuBar

func NewMenuBar() *Menu

新建传统菜单栏形式的菜单

func NewPopupMenu

func NewPopupMenu() *Menu

新建弹出菜单

func (this *Menu) AddActionButton(a IAction) *Button
func (this *Menu) AddButton() *Button
func (this *Menu) AddButton1(text string, icon paint.Icon) *Button
func (this *Menu) AddSeparator() *Separator
func (this *Menu) AddSubMenu(text string, icon paint.Icon, sub *Menu) (*Menu, *Button)
func (this *Menu) AddWidget(iw IWidget)
func (this *Menu) Clear()
func (this *Menu) Draw(g paint.Painter)
func (this *Menu) HideAllSubs()
func (this *Menu) Init(iw IWidget)

Init 携带高亮哨兵, 而不是 NewMenu: 设计器和 .tdoc 加载器都经由 core 工厂 建控件, 工厂只反射调用 Init, 看不到构造函数. 这一步同时覆盖 ButtonBox —— 它内嵌 Menu 却从不走 NewMenu, highlight 为 0 时首项被当成"已键盘高亮", 回车会在任何方向键按下之前就触发它, 向下键也会跳过它.

func (this *Menu) Items() []IWidget
func (this *Menu) Layout()
func (this *Menu) OnHide()
func (this *Menu) OnIdle()
func (this *Menu) OnKeyDown(key int, repeat bool)

OnKeyDown 实现弹出菜单的键盘导航(对标 Qt QMenu):

  • 上/下: 在可选项之间移动高亮, 跳过分隔线与禁用项, 越界回绕;
  • Home/End: 跳到第一个/最后一个可选项;
  • 回车/空格: 触发高亮项, 走与鼠标点击相同的 emit 路径;
  • Esc: 关闭整条弹出菜单链;
  • 右: 若高亮项有子菜单则打开并高亮其首个可选项;
  • 左: 关闭当前子菜单, 返回父菜单.

仅弹出菜单处理按键; 菜单栏(非 popup)不参与键盘导航.

func (this *Menu) OnLeftDown(x, y float64)
func (this *Menu) OnMouseMove(x, y float64)
func (this *Menu) OnMouseStop(x, y float64)
func (this *Menu) OnShow()
func (this *Menu) RemoveWidget(iw IWidget)
func (this *Menu) ShowAsPopup(xg, yg float64, autoClose bool)

在全局坐标(xg, yg)显示为弹出菜单 注: 无论菜单的Parent()是否为nil, 都是全局坐标

func (this *Menu) SizeHints() SizeHints

type MessageBox

type MessageBox struct {
	Form
	// contains filtered or unexported fields
}

MessageBox is a styled modal message dialog.

func NewMessageBox

func NewMessageBox() *MessageBox

NewMessageBox creates a new MessageBox instance.

func (*MessageBox) Draw

func (this *MessageBox) Draw(g paint.Painter)

func (*MessageBox) Init

func (this *MessageBox) Init(iw IWidget)

func (*MessageBox) Layout

func (this *MessageBox) Layout()

func (*MessageBox) SetButtons

func (this *MessageBox) SetButtons(btns []string)

func (*MessageBox) SetMessage

func (this *MessageBox) SetMessage(s string)

func (*MessageBox) ShowModal

func (this *MessageBox) ShowModal() string

type ModelIndex

type ModelIndex struct {
	Row   int
	Col   int
	Param interface{}
	Model IGuiModel
}

模型-视图机制的数据索引 一个索引对应表格中的一个单元格

func (ModelIndex) Child

func (v ModelIndex) Child(row, col int) ModelIndex

func (ModelIndex) Flags

func (v ModelIndex) Flags() ItemFlags

func (ModelIndex) IsNil

func (v ModelIndex) IsNil() bool

func (ModelIndex) Parent

func (v ModelIndex) Parent() ModelIndex

func (ModelIndex) SameCol

func (v ModelIndex) SameCol(row int) ModelIndex

func (ModelIndex) SameRow

func (v ModelIndex) SameRow(col int) ModelIndex

func (ModelIndex) Sibling

func (v ModelIndex) Sibling(row, col int) ModelIndex
type NavPosition struct {
	FilePath string
	Line     int
	Column   int
	ScrollY  float64
}

NavPosition records a cursor position for back/forward navigation.

type NavigationStack struct {
	// contains filtered or unexported fields
}

NavigationStack provides back/forward navigation history.

func (ns *NavigationStack) CanGoBack() bool

CanGoBack returns true if there is a previous position in history.

func (ns *NavigationStack) CanGoForward() bool

CanGoForward returns true if there is a next position in history.

func (ns *NavigationStack) GoBack() (NavPosition, bool)

GoBack moves to the previous position and returns it.

func (ns *NavigationStack) GoForward() (NavPosition, bool)

GoForward moves to the next position and returns it.

func (ns *NavigationStack) Push(pos NavPosition)

Push adds a new position to the stack, discarding any forward history.

type NavigationTarget struct {
	FilePath string
	Line     int
	Column   int
	Name     string
	Kind     string // "func", "type", "var", "const", "method", "param", "local"
}

NavigationTarget represents a found definition location.

func FindDefinition

func FindDefinition(word string, currentFile string, currentContent string) *NavigationTarget

FindDefinition searches for the definition of an identifier. First searches the current file content, then other .go files in the same directory, then walks up to find a gui/ package directory.

Resolution within a single file is AST-based (go/parser): it understands func/type/var/const declarations, methods, and function-local declarations (params, named results, and short variable declarations). If the source fails to parse (e.g. mid-edit), it falls back to a tolerant line scanner so navigation keeps working on partial code.

type NotificationItem

type NotificationItem struct {
	Title   string
	Message string
	Level   NotificationLevel
	Time    string
	Read    bool
}

NotificationItem represents a single notification entry.

type NotificationLevel

type NotificationLevel int

NotificationLevel represents the severity level of a notification.

const (
	NotifyInfo NotificationLevel = iota
	NotifySuccess
	NotifyWarning
	NotifyError
)

type NotificationPanel

type NotificationPanel struct {
	Widget
	// contains filtered or unexported fields
}

NotificationPanel displays a scrollable list of notification cards.

func NewNotificationPanel

func NewNotificationPanel() *NotificationPanel

func (*NotificationPanel) AddNotification

func (this *NotificationPanel) AddNotification(item NotificationItem)

func (*NotificationPanel) ClearAll

func (this *NotificationPanel) ClearAll()

func (*NotificationPanel) Count

func (this *NotificationPanel) Count() int

func (*NotificationPanel) Draw

func (this *NotificationPanel) Draw(g paint.Painter)

func (*NotificationPanel) EnumProperties

func (this *NotificationPanel) EnumProperties(list core.IPropertyList)

func (*NotificationPanel) Init

func (this *NotificationPanel) Init(iw IWidget)

Init carries the hover sentinel, not NewNotificationPanel: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. At hoverIdx 0 the first card paints the hover background before the mouse has entered the panel.

func (*NotificationPanel) Items

func (this *NotificationPanel) Items() []NotificationItem

func (*NotificationPanel) OnLeftDown

func (this *NotificationPanel) OnLeftDown(x, y float64)

func (*NotificationPanel) OnMouseEnter

func (this *NotificationPanel) OnMouseEnter()

func (*NotificationPanel) OnMouseLeave

func (this *NotificationPanel) OnMouseLeave()

func (*NotificationPanel) OnMouseMove

func (this *NotificationPanel) OnMouseMove(x, y float64)

func (*NotificationPanel) OnMouseWheel

func (this *NotificationPanel) OnMouseWheel(x, y, z float64)

func (*NotificationPanel) RemoveNotification

func (this *NotificationPanel) RemoveNotification(idx int)

func (*NotificationPanel) SigClick

func (this *NotificationPanel) SigClick(fn func(int))

func (*NotificationPanel) SizeHints

func (this *NotificationPanel) SizeHints() SizeHints

type NumberInput

type NumberInput struct {
	Widget
	// contains filtered or unexported fields
}

NumberInput 数值输入控件,支持浮点数,带上下调节按钮

func NewNumberInput

func NewNumberInput() *NumberInput

func (*NumberInput) Decimals

func (this *NumberInput) Decimals() int

func (*NumberInput) Draw

func (this *NumberInput) Draw(g paint.Painter)

func (*NumberInput) EnumProperties

func (this *NumberInput) EnumProperties(list core.IPropertyList)

func (*NumberInput) Init

func (this *NumberInput) Init(self IWidget)

Init installs the defaults. They belong here and not in NewNumberInput because the designer palette and the form loader build widgets through core.New, which only calls Init: with max and step left at zero every SetValue clamps to 0 and the field cannot be moved by any click or key.

func (*NumberInput) Max

func (this *NumberInput) Max() float64

func (*NumberInput) Min

func (this *NumberInput) Min() float64

func (*NumberInput) OnFocusIn

func (this *NumberInput) OnFocusIn()

func (*NumberInput) OnFocusOut

func (this *NumberInput) OnFocusOut()

func (*NumberInput) OnKeyDown

func (this *NumberInput) OnKeyDown(key int, repeat bool)

func (*NumberInput) OnLeftDown

func (this *NumberInput) OnLeftDown(x, y float64)

func (*NumberInput) OnMouseEnter

func (this *NumberInput) OnMouseEnter()

func (*NumberInput) OnMouseLeave

func (this *NumberInput) OnMouseLeave()

func (*NumberInput) OnMouseMove

func (this *NumberInput) OnMouseMove(x, y float64)

func (*NumberInput) OnTextInput

func (this *NumberInput) OnTextInput(s string)

OnTextInput implements IEventTextInput. While editing, it appends the digits / dot / minus of the committed text and drops any other rune, preserving the numeric-only filter of the old per-char handler.

func (*NumberInput) SetDecimals

func (this *NumberInput) SetDecimals(n int)

SetDecimals changes the displayed precision and re-seats the current value on the new grid, so Value() keeps agreeing with the text on screen.

func (*NumberInput) SetMax

func (this *NumberInput) SetMax(v float64)

func (*NumberInput) SetMin

func (this *NumberInput) SetMin(v float64)

func (*NumberInput) SetRange

func (this *NumberInput) SetRange(min, max float64)

func (*NumberInput) SetStep

func (this *NumberInput) SetStep(v float64)

func (*NumberInput) SetValue

func (this *NumberInput) SetValue(v float64)

func (*NumberInput) SigValueChanged

func (this *NumberInput) SigValueChanged(fn func(float64))

func (*NumberInput) SizeHints

func (this *NumberInput) SizeHints() SizeHints

func (*NumberInput) Step

func (this *NumberInput) Step() float64

func (*NumberInput) StepDown

func (this *NumberInput) StepDown()

func (*NumberInput) StepUp

func (this *NumberInput) StepUp()

func (*NumberInput) Value

func (this *NumberInput) Value() float64

type Orientation

type Orientation int
const (
	East Orientation = iota
	West
	North
	South
)

func (Orientation) IsHorizontal

func (o Orientation) IsHorizontal() bool

func (Orientation) IsVertical

func (o Orientation) IsVertical() bool

type OutlineSymbol

type OutlineSymbol struct {
	Name     string
	Kind     string // "func", "type", "var", "const", "method"
	Receiver string // method receiver type, empty for plain funcs
	Line     int    // 0-based
	Column   int    // 0-based
}

OutlineSymbol describes a top-level declaration for an outline / symbol list.

func OutlineSymbols

func OutlineSymbols(content string) []OutlineSymbol

OutlineSymbols returns the top-level functions, methods, types, vars and consts declared in content, in source order, using the Go AST. It returns nil if the source does not parse.

type Padding

type Padding struct {
	L, R, T, B float64
}

边距

func (Padding) Apply

func (m Padding) Apply(x, y, w, h float64) (x1, y1, w1, h1 float64)

func (Padding) Apply1

func (m Padding) Apply1(rc geom.Rect) geom.Rect

type Pagination

type Pagination struct {
	Widget
	// contains filtered or unexported fields
}

Pagination is a page-navigation control: a row of square cells holding a previous-arrow, page numbers (with "…" gaps collapsed for large page counts), and a next-arrow. The active page is highlighted in the theme accent colour; the prev/next arrows grey out at the first / last page.

Usage:

pg := gui.NewPagination()
pg.SetTotalPages(20)
pg.SetCurrentPage(1)
pg.SigChange(func(page int) { table.LoadPage(page) })

The page model is 1-based throughout — SetCurrentPage(1) is the first page, matching how users think about pagination and how the numbers render.

func NewPagination

func NewPagination() *Pagination

NewPagination creates a pager with sensible defaults: 1 total page, current page 1, one sibling each side of the current page, and one boundary page pinned at each end. Callers set the real total via SetTotalPages once the data size is known.

func (*Pagination) BoundaryCount

func (this *Pagination) BoundaryCount() int

BoundaryCount returns how many pages are pinned at each end.

func (*Pagination) CurrentPage

func (this *Pagination) CurrentPage() int

CurrentPage returns the active (1-based) page.

func (*Pagination) Draw

func (this *Pagination) Draw(g paint.Painter)

func (*Pagination) EnumProperties

func (this *Pagination) EnumProperties(list core.IPropertyList)

func (*Pagination) Init

func (this *Pagination) Init(self IWidget)

Init carries the page-model defaults, not NewPagination: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A factory pager left at zero counts renders no page numbers at all, and keeps rendering only the current page after SetTotalPages — sibling and boundary both being 0 collapse every run.

func (*Pagination) OnLeftDown

func (this *Pagination) OnLeftDown(x, y float64)

func (*Pagination) OnMouseLeave

func (this *Pagination) OnMouseLeave()

func (*Pagination) OnMouseMove

func (this *Pagination) OnMouseMove(x, y float64)

func (*Pagination) SetBoundaryCount

func (this *Pagination) SetBoundaryCount(n int)

SetBoundaryCount sets how many pages stay pinned at the start and end (the "1 …" and "… 20" anchors). Default 1.

func (*Pagination) SetCurrentPage

func (this *Pagination) SetCurrentPage(page int)

SetCurrentPage moves the active page, clamped to [1, total]. Fires the SigChange callback only when the page actually changes, so a redundant SetCurrentPage(current) is a cheap no-op.

func (*Pagination) SetSiblingCount

func (this *Pagination) SetSiblingCount(n int)

SetSiblingCount sets how many pages show either side of the current page. 0 shows only the current page between the ellipses; the default 1 gives the familiar "4 [5] 6" cluster.

func (*Pagination) SetTotalPages

func (this *Pagination) SetTotalPages(n int)

SetTotalPages sets the page count. Values < 1 clamp to 0 (an empty control). If the current page now exceeds the new total it snaps to the last page so the highlight never points past the end.

func (*Pagination) SiblingCount

func (this *Pagination) SiblingCount() int

SiblingCount returns how many pages flank the current one.

func (*Pagination) SigChange

func (this *Pagination) SigChange(fn func(page int))

SigChange registers the page-change callback. Receives the new 1-based page number.

func (*Pagination) SizeHints

func (this *Pagination) SizeHints() SizeHints

func (*Pagination) TotalPages

func (this *Pagination) TotalPages() int

TotalPages returns the configured page count.

type ParseError

type ParseError struct {
	Errors []string
}

ParseError aggregates the per-rule failures encountered while parsing. It implements error so callers can treat it as a normal error value while still inspecting the individual problems via Errors.

func (*ParseError) Error

func (e *ParseError) Error() string

type PathEdit

type PathEdit struct {
	Widget
	// contains filtered or unexported fields
}

PathEdit is a single-line text input paired with a fixed-width browse button on the right. Clicking the button pops the framework file/folder dialog (per Mode) and writes the picked path back into the field; typing into the field works the same as a plain Edit.

Usage:

pe := gui.NewPathEdit()
pe.SetMode(gui.PathFolder)
pe.SigPathChanged(func(p string) { config.OutputDir = p })

func NewPathEdit

func NewPathEdit() *PathEdit

NewPathEdit creates an empty path picker in PathFile mode wired to the framework's real file dialog. Tests that need to drive the browse-button decision without spawning the native dialog assign their own openFn via the (unexported) setter or by direct write — see pathedit_test.go.

func (*PathEdit) Cursor

func (this *PathEdit) Cursor() *Cursor

Cursor shows an I-beam over the text region and the default arrow over the button. Matches Edit's iBeam over its body.

func (*PathEdit) Draw

func (this *PathEdit) Draw(g paint.Painter)

Draw paints the text field on the left and the "..." browse button on the right. Uses the theme's edit frame so the input matches a stock gui.Edit; the button shares Theme().FormDarkColor for its background to read as a flat affordance against the white field.

func (*PathEdit) EnumProperties

func (this *PathEdit) EnumProperties(list core.IPropertyList)

EnumProperties exposes the path/placeholder/readonly knobs to the designer's property sheet. Mode is intentionally omitted — picking "file vs folder" is wiring code, not visual styling.

func (*PathEdit) Init

func (this *PathEdit) Init(self IWidget)

Init installs the defaults. They belong here and not in NewPathEdit because the designer palette and the form loader build widgets through core.New, which only calls Init — a nil openFn leaves the browse button dead.

func (*PathEdit) IsReadOnly

func (this *PathEdit) IsReadOnly() bool

IsReadOnly reports whether the field is read-only. A read-only PathEdit still pops the dialog on a button click — read-only here means the user can't type characters into the field, mirroring QLineEdit's setReadOnly.

func (*PathEdit) Mode

func (this *PathEdit) Mode() PathMode

Mode returns the configured PathMode.

func (*PathEdit) OnKeyDown

func (this *PathEdit) OnKeyDown(key int, repeat bool)

OnKeyDown handles Backspace; other keys fall through. Kept minimal because the dialog is the primary input path — anyone needing full editing should compose a real gui.Edit beside this widget.

func (*PathEdit) OnLeftDown

func (this *PathEdit) OnLeftDown(x, y float64)

OnLeftDown routes the click: a hit in the button region opens the dialog and writes any picked path back via SetText (which fires SigPathChanged on a real change). A hit in the text region just grabs focus so the user can type.

func (*PathEdit) OnMouseEnter

func (this *PathEdit) OnMouseEnter()

OnMouseEnter / OnMouseLeave keep the hover paint in sync.

func (*PathEdit) OnMouseLeave

func (this *PathEdit) OnMouseLeave()

func (*PathEdit) OnTextInput

func (this *PathEdit) OnTextInput(s string)

OnTextInput accepts typed characters and appends them to the field, matching QLineEdit's behaviour. No-op when read-only.

func (*PathEdit) Placeholder

func (this *PathEdit) Placeholder() string

Placeholder returns the current placeholder string.

func (*PathEdit) SetMode

func (this *PathEdit) SetMode(m PathMode)

SetMode switches the dialog flavor the browse button will pop. Defaults to PathFile.

func (*PathEdit) SetOpenFn

func (this *PathEdit) SetOpenFn(fn func(mode PathMode) (string, bool))

SetOpenFn replaces the dialog-opening function. Used by tests to stub out the real native dialog (which needs a window + event loop) and observe whether the browse-button decision was reached. Passing nil restores the default real-dialog driver.

func (*PathEdit) SetPlaceholder

func (this *PathEdit) SetPlaceholder(s string)

SetPlaceholder sets the grey hint string drawn when Text() is empty.

func (*PathEdit) SetReadOnly

func (this *PathEdit) SetReadOnly(b bool)

SetReadOnly toggles read-only typing. The browse button stays live because picking via dialog is the intended workflow when the user shouldn't free-form-type a path.

func (*PathEdit) SetText

func (this *PathEdit) SetText(s string)

SetText writes the path string. Fires SigPathChanged only when the value actually changes, so a redundant SetText(current) is a cheap no-op (matches Pagination.SetCurrentPage's semantics).

func (*PathEdit) SigPathChanged

func (this *PathEdit) SigPathChanged(fn func(string))

SigPathChanged registers the path-change callback. Fired by SetText (whether triggered by the dialog or by a programmatic caller) only on a real change.

func (*PathEdit) SizeHints

func (this *PathEdit) SizeHints() SizeHints

SizeHints reports a sensible default 200x28; the widget grows horizontally so it tracks layout width and the text region absorbs the slack to the left of the fixed-width button.

func (*PathEdit) Text

func (this *PathEdit) Text() string

Text returns the current path string.

type PathMode

type PathMode int

PathMode picks which dialog the browse button opens. The three values map onto the OpenFileDialog / SaveFileDialog primitives the framework already ships; folder-pick reuses OpenFileDialog and keeps the parent directory of the picked file since the GLFW build of the framework has no native folder picker.

const (
	PathFile PathMode = iota
	PathFolder
	PathSaveFile
)

type PerfStats

type PerfStats struct {
	// contains filtered or unexported fields
}

PerfStats is the process-wide sampler for paint / layout / frame timing. It's designed to be toggled on-demand with F12: when invisible, the per-frame accounting is still cheap (a few atomics) but the overlay does no drawing.

func (*PerfStats) Draw

func (s *PerfStats) Draw(g paint.Painter, w, h float64)

Draw paints the overlay in the top-right corner of the surface. When the overlay is hidden, this is a no-op. Colors are hard-coded (dark bg with green monospaced text) so the overlay is legible regardless of theme.

func (*PerfStats) IsVisible

func (s *PerfStats) IsVisible() bool

IsVisible reports whether the overlay is currently shown.

func (*PerfStats) RecordFrame

func (s *PerfStats) RecordFrame()

RecordFrame should be called once per frame from the main loop. When the 1-second window elapses, the accumulated frame count becomes the reported FPS and the window resets. Safe to call even when the overlay is hidden.

func (*PerfStats) RecordLayout

func (s *PerfStats) RecordLayout(d time.Duration)

RecordLayout records a layout-pass duration into the rolling average.

func (*PerfStats) RecordPaint

func (s *PerfStats) RecordPaint(d time.Duration)

RecordPaint folds a paint duration into the rolling average. Call this once per frame, wrapping the widget-tree draw pass.

func (*PerfStats) SetVisible

func (s *PerfStats) SetVisible(v bool)

SetVisible sets the overlay visibility explicitly. Useful for tests.

func (*PerfStats) SetWidgetCount

func (s *PerfStats) SetWidgetCount(n int)

SetWidgetCount publishes the most recent widget count (computed during the last paint pass).

func (*PerfStats) Toggle

func (s *PerfStats) Toggle()

Toggle flips the overlay on or off and forces a repaint.

type PieChart

type PieChart struct {
	Widget
	// contains filtered or unexported fields
}

PieChart renders data as a circular pie.

func NewPieChart

func NewPieChart() *PieChart

NewPieChart creates a ready-to-use PieChart widget.

func (*PieChart) AddSlice

func (this *PieChart) AddSlice(label string, value float64, color paint.Color)

AddSlice appends a sector.

func (*PieChart) ClearSlices

func (this *PieChart) ClearSlices()

ClearSlices removes all sectors.

func (*PieChart) Draw

func (this *PieChart) Draw(g paint.Painter)

Draw renders the pie chart.

func (*PieChart) EnumProperties

func (this *PieChart) EnumProperties(list core.IPropertyList)

EnumProperties exposes inspectable properties.

func (*PieChart) SetShowLabels

func (this *PieChart) SetShowLabels(b bool)

SetShowLabels controls label drawing.

func (*PieChart) SetShowPercent

func (this *PieChart) SetShowPercent(b bool)

SetShowPercent controls percentage display.

func (*PieChart) SetTitle

func (this *PieChart) SetTitle(s string)

SetTitle sets the chart title.

func (*PieChart) ShowLabels

func (this *PieChart) ShowLabels() bool

ShowLabels reports whether labels are drawn.

func (*PieChart) ShowPercent

func (this *PieChart) ShowPercent() bool

ShowPercent reports whether percentages are shown.

func (*PieChart) SizeHints

func (this *PieChart) SizeHints() SizeHints

SizeHints returns the preferred size.

func (*PieChart) Title

func (this *PieChart) Title() string

Title returns the current title.

type PieSlice

type PieSlice struct {
	Label string
	Value float64
	Color paint.Color
}

PieSlice represents one sector of a PieChart.

type Pipe

type Pipe struct {
	Widget
	// contains filtered or unexported fields
}

Pipe draws a straight pipe segment. When Active it is filled with FlowColor and overlaid with flow dashes; when inactive it is drawn in a neutral gray.

func NewPipe

func NewPipe() *Pipe

NewPipe creates an inactive horizontal pipe.

func (*Pipe) Draw

func (this *Pipe) Draw(g paint.Painter)

func (*Pipe) EnumProperties

func (this *Pipe) EnumProperties(list core.IPropertyList)

func (*Pipe) FlowColor

func (this *Pipe) FlowColor() paint.Color

FlowColor returns the active-flow color.

func (*Pipe) Init

func (this *Pipe) Init(self IWidget)

Init carries the flow / idle colours (see the file note on factory construction).

func (*Pipe) IsActive

func (this *Pipe) IsActive() bool

IsActive reports whether flow is active.

func (*Pipe) IsVertical

func (this *Pipe) IsVertical() bool

IsVertical reports the pipe orientation.

func (*Pipe) SetActive

func (this *Pipe) SetActive(b bool)

SetActive toggles flow on the pipe.

func (*Pipe) SetFlowColor

func (this *Pipe) SetFlowColor(c paint.Color)

SetFlowColor sets the color used when flow is active.

func (*Pipe) SetTagName

func (this *Pipe) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*Pipe) SetVertical

func (this *Pipe) SetVertical(b bool)

SetVertical sets the pipe orientation (true = vertical).

func (*Pipe) SizeHints

func (this *Pipe) SizeHints() SizeHints

func (*Pipe) TagName

func (this *Pipe) TagName() string

TagName returns the design-time tag name.

type Placeholder

type Placeholder struct {
	Widget
	// contains filtered or unexported fields
}

Placeholder is an empty state widget showing an icon, title, and subtitle.

func NewPlaceholder

func NewPlaceholder(title string) *Placeholder

func (*Placeholder) Draw

func (this *Placeholder) Draw(g paint.Painter)

func (*Placeholder) EnumProperties

func (this *Placeholder) EnumProperties(list core.IPropertyList)

func (*Placeholder) Icon

func (this *Placeholder) Icon() paint.Icon

func (*Placeholder) SetIcon

func (this *Placeholder) SetIcon(ico paint.Icon)

func (*Placeholder) SetSubtitle

func (this *Placeholder) SetSubtitle(s string)

func (*Placeholder) SetTitle

func (this *Placeholder) SetTitle(s string)

func (*Placeholder) SizeHints

func (this *Placeholder) SizeHints() SizeHints

func (*Placeholder) Subtitle

func (this *Placeholder) Subtitle() string

func (*Placeholder) Title

func (this *Placeholder) Title() string

type ProgressBar

type ProgressBar struct {
	Widget
	// contains filtered or unexported fields
}

ProgressBar displays a value between 0.0 and 1.0 as a filled bar.

In indeterminate ("busy") mode the value is ignored and the bar instead shows a small chunk sliding back and forth across the track to signal ongoing work of unknown duration (cf. Qt's QProgressBar indeterminate state). A looping heartbeat Animation keeps HasActiveAnimations() true so the window event loop keeps redrawing while busy — the same idiom Spinner uses.

func NewProgressBar

func NewProgressBar() *ProgressBar

func (*ProgressBar) BarColor

func (this *ProgressBar) BarColor() paint.Color

func (*ProgressBar) Draw

func (this *ProgressBar) Draw(g paint.Painter)

func (*ProgressBar) EnumProperties

func (this *ProgressBar) EnumProperties(list core.IPropertyList)

func (*ProgressBar) Init

func (this *ProgressBar) Init(self IWidget)

Init carries the defaults, not NewProgressBar: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Colours left in the constructor paint a transparent fill over a transparent track.

func (*ProgressBar) IsIndeterminate

func (this *ProgressBar) IsIndeterminate() bool

IsIndeterminate reports whether the bar is in busy mode.

func (*ProgressBar) IsShowText

func (this *ProgressBar) IsShowText() bool

func (*ProgressBar) SetBarColor

func (this *ProgressBar) SetBarColor(c paint.Color)

func (*ProgressBar) SetBgColor

func (this *ProgressBar) SetBgColor(c paint.Color)

func (*ProgressBar) SetIndeterminate

func (this *ProgressBar) SetIndeterminate(on bool)

SetIndeterminate toggles "busy" mode. When turning on, it records the phase start time and arms a looping heartbeat Animation so HasActiveAnimations() reports true and the window keeps ticking; turning off stops the heartbeat so the event loop can idle. The value path is untouched — flipping back to determinate resumes the previous fill exactly.

func (*ProgressBar) SetShowText

func (this *ProgressBar) SetShowText(b bool)

func (*ProgressBar) SetValue

func (this *ProgressBar) SetValue(v float64)

func (*ProgressBar) SizeHints

func (this *ProgressBar) SizeHints() SizeHints

func (*ProgressBar) Value

func (this *ProgressBar) Value() float64

type Pump

type Pump struct {
	Widget
	// contains filtered or unexported fields
}

Pump draws a circular pump body with an impeller mark. It is green while running, gray while stopped, and red on fault (fault takes precedence).

func NewPump

func NewPump() *Pump

NewPump creates a stopped pump.

func (*Pump) Draw

func (this *Pump) Draw(g paint.Painter)

func (*Pump) EnumProperties

func (this *Pump) EnumProperties(list core.IPropertyList)

func (*Pump) IsFault

func (this *Pump) IsFault() bool

IsFault reports the fault state.

func (*Pump) IsRunning

func (this *Pump) IsRunning() bool

IsRunning reports the running state.

func (*Pump) SetFault

func (this *Pump) SetFault(b bool)

SetFault sets the fault state (overrides running when drawn).

func (*Pump) SetRunning

func (this *Pump) SetRunning(b bool)

SetRunning sets the running state.

func (*Pump) SetTagName

func (this *Pump) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*Pump) SizeHints

func (this *Pump) SizeHints() SizeHints

func (*Pump) TagName

func (this *Pump) TagName() string

TagName returns the design-time tag name.

type RadioButton

type RadioButton struct {
	Widget
	// contains filtered or unexported fields
}

RadioButton is a mutually-exclusive toggle within a RadioGroup

func NewRadioButton

func NewRadioButton(text string, group *RadioGroup) *RadioButton

func (*RadioButton) Draw

func (this *RadioButton) Draw(g paint.Painter)

func (*RadioButton) EnumProperties

func (this *RadioButton) EnumProperties(list core.IPropertyList)

func (*RadioButton) IsChecked

func (this *RadioButton) IsChecked() bool

func (*RadioButton) OnKeyDown

func (this *RadioButton) OnKeyDown(key int, repeat bool)

OnKeyDown implements Qt QRadioButton keyboard behaviour. Space selects this radio (firing the exclusive-select path so siblings deselect and callbacks fire). Within a group the arrow keys move the selection AND focus to the previous (Up/Left) or next (Down/Right) enabled radio, wrapping at the ends.

func (*RadioButton) OnLeftDown

func (this *RadioButton) OnLeftDown(x, y float64)

func (*RadioButton) OnMouseEnter

func (this *RadioButton) OnMouseEnter()

func (*RadioButton) OnMouseLeave

func (this *RadioButton) OnMouseLeave()

func (*RadioButton) SetChangedCallback

func (this *RadioButton) SetChangedCallback(cb func(interface{}, bool))

func (*RadioButton) SetChecked

func (this *RadioButton) SetChecked(b bool)

func (*RadioButton) SetText

func (this *RadioButton) SetText(s string)

func (*RadioButton) SizeHints

func (this *RadioButton) SizeHints() SizeHints

func (*RadioButton) Text

func (this *RadioButton) Text() string

type RadioGroup

type RadioGroup struct {
	// contains filtered or unexported fields
}

RadioGroup manages mutual exclusion among RadioButtons

func NewRadioGroup

func NewRadioGroup() *RadioGroup

func (*RadioGroup) SelectedIndex

func (g *RadioGroup) SelectedIndex() int

SelectedIndex returns the index of the currently selected button, or -1

type Rating

type Rating struct {
	Widget
	// contains filtered or unexported fields
}

Rating is a star rating control that displays filled/empty circles and allows the user to select a rating by clicking.

func NewRating

func NewRating() *Rating

NewRating creates a new Rating widget with a default of 5 stars.

func (*Rating) Draw

func (this *Rating) Draw(g paint.Painter)

func (*Rating) EnumProperties

func (this *Rating) EnumProperties(list core.IPropertyList)

func (*Rating) Init

func (this *Rating) Init(self IWidget)

Init carries the defaults, not NewRating: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. At zero stars the draw loop never runs and SetValue clamps everything to 0; at hoverValue 0 the "is hovered" test (hoverValue >= 0) is true before the mouse has arrived.

func (*Rating) IsReadOnly

func (this *Rating) IsReadOnly() bool

IsReadOnly returns whether the control is read-only.

func (*Rating) MaxStars

func (this *Rating) MaxStars() int

MaxStars returns the maximum number of stars.

func (*Rating) OnLeftDown

func (this *Rating) OnLeftDown(x, y float64)

func (*Rating) OnMouseEnter

func (this *Rating) OnMouseEnter()

func (*Rating) OnMouseLeave

func (this *Rating) OnMouseLeave()

func (*Rating) OnMouseMove

func (this *Rating) OnMouseMove(x, y float64)

func (*Rating) SetMaxStars

func (this *Rating) SetMaxStars(n int)

SetMaxStars sets the maximum number of stars.

func (*Rating) SetReadOnly

func (this *Rating) SetReadOnly(b bool)

SetReadOnly sets the read-only state.

func (*Rating) SetValue

func (this *Rating) SetValue(v int)

SetValue sets the current rating.

func (*Rating) SigRatingChanged

func (this *Rating) SigRatingChanged(fn func(int))

SigRatingChanged sets the callback for when the rating changes.

func (*Rating) SizeHints

func (this *Rating) SizeHints() SizeHints

func (*Rating) Value

func (this *Rating) Value() int

Value returns the current rating (0 to maxStars).

type RecipePanel

type RecipePanel struct {
	Widget
	// contains filtered or unexported fields
}

RecipePanel is a 配方 (recipe) operator panel for SCADA / 组态 screens: a scrollable list of named recipes with a selectable row and a footer row of action buttons — 应用(Apply), 抓取(Capture), 保存(Save), 加载(Load).

It is deliberately decoupled from the backend recipe package. The panel holds only a plain []string of recipe names fed via SetRecipes, and the operator's intent leaves through the Sig* callbacks: Apply/Capture carry the currently selected recipe name, Save/Load carry nothing. The host wires those callbacks to the recipe store; the panel never imports it, so gui stays light and this file is GL-free unit-testable (only Draw touches the painter).

func NewRecipePanel

func NewRecipePanel() *RecipePanel

NewRecipePanel creates an empty recipe panel with no selection.

func (*RecipePanel) Draw

func (this *RecipePanel) Draw(g paint.Painter)

Draw renders a title/count header, the scrollable recipe list with the selected row highlighted, and the footer action-button row. All colours come from the active Theme() so the panel reads correctly in the dark IDE theme.

func (*RecipePanel) Init

func (this *RecipePanel) Init(self IWidget)

func (*RecipePanel) OnLeftDown

func (this *RecipePanel) OnLeftDown(x, y float64)

OnLeftDown routes a click: a hit in the footer band fires the matching action (Apply/Capture on the selected recipe, Save/Load unconditionally); a hit in the list body selects that row. Clicks on the header or past the last row are ignored.

func (*RecipePanel) OnMouseWheel

func (this *RecipePanel) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the recipe list vertically.

func (*RecipePanel) Recipes

func (this *RecipePanel) Recipes() []string

Recipes returns a defensive copy of the displayed recipe names in order.

func (*RecipePanel) Selected

func (this *RecipePanel) Selected() string

Selected returns the name of the currently selected recipe, or "" when no row is selected (or the selection has fallen out of range).

func (*RecipePanel) SetRecipes

func (this *RecipePanel) SetRecipes(in []string)

SetRecipes replaces the displayed recipe list with a defensive copy of in. The selection is reset (a new list invalidates any prior index), and the scroll offset is clamped to the new content rather than reset.

func (*RecipePanel) SigApply

func (this *RecipePanel) SigApply(fn func(name string))

SigApply registers the callback fired when the operator clicks 应用(Apply). It receives the selected recipe name; it does not fire when nothing is selected.

func (*RecipePanel) SigCapture

func (this *RecipePanel) SigCapture(fn func(name string))

SigCapture registers the callback fired when the operator clicks 抓取(Capture). It receives the selected recipe name; it does not fire when nothing is selected.

func (*RecipePanel) SigLoad

func (this *RecipePanel) SigLoad(fn func())

SigLoad registers the callback fired when the operator clicks 加载(Load).

func (*RecipePanel) SigSave

func (this *RecipePanel) SigSave(fn func())

SigSave registers the callback fired when the operator clicks 保存(Save).

func (*RecipePanel) SizeHints

func (this *RecipePanel) SizeHints() SizeHints

type ReferenceMatch

type ReferenceMatch struct {
	Line   int // 0-based
	Column int // 0-based
}

ReferenceMatch is a single use site of an identifier within a file.

func FindReferences

func FindReferences(word, content string) []ReferenceMatch

FindReferences returns every position in content where an identifier named word appears (declarations and uses alike), using the Go AST.

Resolution is name-based and scoped to this single file: cross-package resolution and shadowing analysis are out of scope. The source is parsed with go/parser; if it does not parse, an empty slice is returned.

type RegExpValidator

type RegExpValidator struct {
	// contains filtered or unexported fields
}

RegExpValidator validates input against a Go regexp. Construction with an invalid pattern returns nil + the parse error so callers can report rather than rendering with a panic.

func NewRegExpValidator

func NewRegExpValidator(pattern string) (*RegExpValidator, error)

NewRegExpValidator compiles pattern. Returns (nil, err) on a bad pattern; callers should surface the error to the developer rather than silently fall through to "always Invalid".

func (*RegExpValidator) Validate

func (v *RegExpValidator) Validate(input string) State

Validate. The classifier:

full match (^pattern$)     → Acceptable
prefix of a matching string → Intermediate
otherwise                   → Invalid

"Prefix of a matching string" is determined by checking whether the underlying regex engine can match the input as the start of a string when the pattern is run as unanchored. This catches the common UI patterns (phone numbers, IPs, dates, emails) without a hand-rolled partial matcher.

Method: take the loc returned by FindStringIndex on the unanchored pattern. If the regex matches starting at position 0 AND the match reaches the end of input, the input is a viable prefix. We further approximate by appending probe completions and trying again — this covers cases where the pattern includes non-greedy quantifiers that FindStringIndex could otherwise consume only zero chars.

type ReportView

type ReportView struct {
	Widget
	// contains filtered or unexported fields
}

ReportView is a read-only 报表 (report) table viewer for operator screens: a bold column-header row over a vertically scrollable body of data rows with alternating (zebra) backgrounds. It is deliberately backend-free — it holds a plain view-model (a []string header and a [][]string body) fed via SetTable and never imports the report/query packages that produce those tables. Column widths are derived from the content; wide cells are clipped (v1 has no horizontal scroll).

The only user intent it emits is export: the toolbar carries "导出CSV" and "导出HTML" buttons that fire SigExport with "csv" / "html". The host owns the actual serialization and file writing; the panel stays a pure view.

func NewReportView

func NewReportView() *ReportView

NewReportView creates an empty report view.

func (*ReportView) Draw

func (this *ReportView) Draw(g paint.Painter)

Draw renders a toolbar (title + export buttons), a bold column-header row and the scrollable, zebra-striped data rows, all in the active Theme() colours so the panel reads correctly in the dark IDE theme.

func (*ReportView) Headers

func (this *ReportView) Headers() []string

Headers returns a defensive copy of the column headers.

func (*ReportView) Init

func (this *ReportView) Init(self IWidget)

func (*ReportView) OnLeftDown

func (this *ReportView) OnLeftDown(x, y float64)

OnLeftDown fires SigExport when a toolbar export button is clicked. Clicks in the data body (or that miss the buttons) are ignored beyond taking focus.

func (*ReportView) OnMouseWheel

func (this *ReportView) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the data rows vertically.

func (*ReportView) RowCount

func (this *ReportView) RowCount() int

RowCount returns the number of data rows (headers excluded).

func (*ReportView) SetTable

func (this *ReportView) SetTable(headers []string, rows [][]string)

SetTable replaces the displayed table with a defensive deep copy of headers and rows. The inner row slices are copied too, so later mutation of the caller's data cannot reach the panel. The scroll offset is clamped to the new content rather than reset, so a refresh does not yank the operator's view back to the top.

func (*ReportView) SigExport

func (this *ReportView) SigExport(fn func(format string))

SigExport registers the callback fired when the operator clicks an export button. It receives the requested format: "csv" or "html".

func (*ReportView) SizeHints

func (this *ReportView) SizeHints() SizeHints

type RequiredValidator

type RequiredValidator struct {
	// Message overrides the default "this field is required" text returned
	// by ErrorMessage. Leave empty for the default.
	Message string
}

--- RequiredValidator ----------------------------------------------

RequiredValidator rejects empty (whitespace-only) input. It deliberately never returns Invalid: an empty value must stay typable and programmatically settable so the user can clear the field and a form reset works. Empty is therefore Intermediate ("allowed in the buffer but not submittable"); non-empty is Acceptable. A required field is thus a submit-gate plus red-border affordance, not a keystroke filter.

func (*RequiredValidator) ErrorMessage

func (v *RequiredValidator) ErrorMessage(input string) string

ErrorMessage returns the required-field message for empty input, or "" once the field carries a value.

func (*RequiredValidator) Validate

func (v *RequiredValidator) Validate(input string) State

Validate: whitespace-only input is Intermediate, anything else is Acceptable.

type Rule

type Rule struct {
	Selector     Selector
	Declarations map[string]string // property name -> raw value string
}

Rule is one parsed `selector { ... }` block.

type ScatterPlot

type ScatterPlot struct {
	Widget
	// contains filtered or unexported fields
}

ScatterPlot renders one or more series as scattered dots.

func NewScatterPlot

func NewScatterPlot() *ScatterPlot

NewScatterPlot creates a ready-to-use ScatterPlot widget.

func (*ScatterPlot) AddSeries

func (this *ScatterPlot) AddSeries(name string, color paint.Color, points []ScatterPoint)

AddSeries appends a scatter series.

func (*ScatterPlot) AddSeriesWithSize

func (this *ScatterPlot) AddSeriesWithSize(name string, color paint.Color, points []ScatterPoint, size float64)

AddSeriesWithSize appends a scatter series with a custom dot radius.

func (*ScatterPlot) AutoScale

func (this *ScatterPlot) AutoScale() bool

AutoScale reports whether auto-scaling is active.

func (*ScatterPlot) ClearSeries

func (this *ScatterPlot) ClearSeries()

ClearSeries removes all series.

func (*ScatterPlot) Draw

func (this *ScatterPlot) Draw(g paint.Painter)

Draw renders the scatter plot.

func (*ScatterPlot) EnumProperties

func (this *ScatterPlot) EnumProperties(list core.IPropertyList)

EnumProperties exposes inspectable properties.

func (*ScatterPlot) SetAutoScale

func (this *ScatterPlot) SetAutoScale(b bool)

SetAutoScale enables or disables automatic axis range computation.

func (*ScatterPlot) SetRange

func (this *ScatterPlot) SetRange(minX, maxX, minY, maxY float64)

SetRange sets explicit axis ranges (disables auto-scale).

func (*ScatterPlot) SetShowGrid

func (this *ScatterPlot) SetShowGrid(b bool)

SetShowGrid controls grid line drawing.

func (*ScatterPlot) SetShowLegend

func (this *ScatterPlot) SetShowLegend(b bool)

SetShowLegend controls legend drawing.

func (*ScatterPlot) SetTitle

func (this *ScatterPlot) SetTitle(s string)

SetTitle sets the chart title.

func (*ScatterPlot) ShowGrid

func (this *ScatterPlot) ShowGrid() bool

ShowGrid reports whether the grid is drawn.

func (*ScatterPlot) ShowLegend

func (this *ScatterPlot) ShowLegend() bool

ShowLegend reports whether the legend is drawn.

func (*ScatterPlot) SizeHints

func (this *ScatterPlot) SizeHints() SizeHints

SizeHints returns the preferred size.

func (*ScatterPlot) Title

func (this *ScatterPlot) Title() string

Title returns the current title.

type ScatterPoint

type ScatterPoint struct {
	X, Y float64
}

ScatterPoint holds one (X, Y) data point.

type ScatterSeries

type ScatterSeries struct {
	Name   string
	Color  paint.Color
	Points []ScatterPoint
	Size   float64 // dot radius (default 3)
}

ScatterSeries holds a named set of scatter points.

type ScrollArea

type ScrollArea struct {
	Widget
	// contains filtered or unexported fields
}

滚动区域 注: 滚动区域提供滚动条和相应接口, 不自动滚动客户区坐标

程序代码中, 要根据滚动位置, 另行偏移客户区坐标和平移绘图对象
由于偏移操作可定制, 所以滚动单位可以不是像素

func NewScrollArea

func NewScrollArea() *ScrollArea

func (*ScrollArea) EnumProperties

func (this *ScrollArea) EnumProperties(list core.IPropertyList)

func (*ScrollArea) HorzScrollBar

func (this *ScrollArea) HorzScrollBar() *ScrollBar

func (*ScrollArea) Layout

func (this *ScrollArea) Layout()

func (*ScrollArea) OnHorzScroll

func (this *ScrollArea) OnHorzScroll(sender IWidget)

func (*ScrollArea) OnVertScroll

func (this *ScrollArea) OnVertScroll(sender IWidget)

func (*ScrollArea) ScrollPos

func (this *ScrollArea) ScrollPos() (x, y float64)

func (*ScrollArea) ScrollX

func (this *ScrollArea) ScrollX() float64

func (*ScrollArea) ScrollY

func (this *ScrollArea) ScrollY() float64

func (*ScrollArea) SetScrollX

func (this *ScrollArea) SetScrollX(sx float64)

func (*ScrollArea) SetScrollY

func (this *ScrollArea) SetScrollY(sy float64)

func (*ScrollArea) VertScrollBar

func (this *ScrollArea) VertScrollBar() *ScrollBar

func (*ScrollArea) ViewportSizePx

func (this *ScrollArea) ViewportSizePx() (width, height float64)

type ScrollBar

type ScrollBar struct {
	Widget
	// contains filtered or unexported fields
}

滚动条

func NewScrollBar

func NewScrollBar() *ScrollBar

func (*ScrollBar) ActivePart

func (this *ScrollBar) ActivePart() (part int, pushed bool)

func (*ScrollBar) Delta

func (this *ScrollBar) Delta() (small, large float64)

func (*ScrollBar) Draw

func (this *ScrollBar) Draw(g paint.Painter)

func (*ScrollBar) IsAutoHide

func (this *ScrollBar) IsAutoHide() bool

func (*ScrollBar) IsValid

func (this *ScrollBar) IsValid() bool

func (*ScrollBar) IsVertical

func (this *ScrollBar) IsVertical() bool

func (*ScrollBar) LargeBakward

func (this *ScrollBar) LargeBakward()

func (*ScrollBar) LargeForward

func (this *ScrollBar) LargeForward()

func (*ScrollBar) OnLeftDown

func (this *ScrollBar) OnLeftDown(x, y float64)

func (*ScrollBar) OnLeftUp

func (this *ScrollBar) OnLeftUp(x, y float64)

func (*ScrollBar) OnMouseEnter

func (this *ScrollBar) OnMouseEnter()

func (*ScrollBar) OnMouseLeave

func (this *ScrollBar) OnMouseLeave()

func (*ScrollBar) OnMouseMove

func (this *ScrollBar) OnMouseMove(x, y float64)

func (*ScrollBar) PointToPart

func (this *ScrollBar) PointToPart(x, y float64) int

func (*ScrollBar) PointToValue

func (this *ScrollBar) PointToValue(x, y float64) float64

func (*ScrollBar) Range

func (this *ScrollBar) Range() (min, max float64)

func (*ScrollBar) SetAutoHide

func (this *ScrollBar) SetAutoHide(b bool)

func (*ScrollBar) SetChangedCallback

func (this *ScrollBar) SetChangedCallback(fn func(IWidget))

func (*ScrollBar) SetDelta

func (this *ScrollBar) SetDelta(small, large float64)

func (*ScrollBar) SetRange

func (this *ScrollBar) SetRange(min, max float64)

func (*ScrollBar) SetValue

func (this *ScrollBar) SetValue(v float64)

func (*ScrollBar) SetVertical

func (this *ScrollBar) SetVertical(vert bool)

func (*ScrollBar) SizeHints

func (this *ScrollBar) SizeHints() (hints SizeHints)

func (*ScrollBar) SmallBakward

func (this *ScrollBar) SmallBakward()

func (*ScrollBar) SmallForward

func (this *ScrollBar) SmallForward()

func (*ScrollBar) TrackRect

func (this *ScrollBar) TrackRect() (x, y, w, h float64)

func (*ScrollBar) Value

func (this *ScrollBar) Value() (value float64)

type ScrollPart

type ScrollPart int
const (
	SCROLL_SMALL_DEC ScrollPart = iota
	SCROLL_SMALL_INC
	SCROLL_LARGE_DEC
	SCROLL_LARGE_INC
	SCROLL_TRACK_BAR
)
type SearchBox struct {
	Widget
	// contains filtered or unexported fields
}

SearchBox 搜索框控件,带搜索图标和清除按钮

func NewSearchBox

func NewSearchBox() *SearchBox

func (*SearchBox) Clear

func (this *SearchBox) Clear()

func (*SearchBox) Draw

func (this *SearchBox) Draw(g paint.Painter)

func (*SearchBox) EnumProperties

func (this *SearchBox) EnumProperties(list core.IPropertyList)

func (*SearchBox) OnFocusIn

func (this *SearchBox) OnFocusIn()

func (*SearchBox) OnFocusOut

func (this *SearchBox) OnFocusOut()

func (*SearchBox) OnKeyDown

func (this *SearchBox) OnKeyDown(key int, repeat bool)

func (*SearchBox) OnLeftDown

func (this *SearchBox) OnLeftDown(x, y float64)

func (*SearchBox) OnMouseEnter

func (this *SearchBox) OnMouseEnter()

func (*SearchBox) OnMouseLeave

func (this *SearchBox) OnMouseLeave()

func (*SearchBox) OnMouseMove

func (this *SearchBox) OnMouseMove(x, y float64)

func (*SearchBox) OnTextInput

func (this *SearchBox) OnTextInput(s string)

OnTextInput implements IEventTextInput: the window routes committed text here (already stripped of control chars by onChar). Each rune is inserted at the caret and advances it, matching the old per-char handler.

func (*SearchBox) Placeholder

func (this *SearchBox) Placeholder() string

func (*SearchBox) SetPlaceholder

func (this *SearchBox) SetPlaceholder(s string)

func (*SearchBox) SetText

func (this *SearchBox) SetText(s string)

func (*SearchBox) SigSearch

func (this *SearchBox) SigSearch(fn func(string))

func (*SearchBox) SigTextChanged

func (this *SearchBox) SigTextChanged(fn func(string))

func (*SearchBox) SizeHints

func (this *SearchBox) SizeHints() SizeHints

func (*SearchBox) Text

func (this *SearchBox) Text() string

type SelectionEdit

type SelectionEdit struct {
	StartLine int
	StartCol  int
	EndLine   int
	EndCol    int
	Text      string
}

SelectionEdit is one buffer replacement: the normalized range [(StartLine,StartCol) .. (EndLine,EndCol)) and the text that replaces it. A zero-width range is a plain insertion at that position.

func (SelectionEdit) Empty

func (e SelectionEdit) Empty() bool

Empty reports whether the edit's range is zero-width (a pure insertion).

type SelectionLines

type SelectionLines []string

SelectionLines adapts a plain []string buffer (CodeEditor.lines) to SelectionMetrics.

func (SelectionLines) LineCount

func (s SelectionLines) LineCount() int

LineCount returns the line count, reporting 1 for an empty slice because an empty buffer still holds one empty line.

func (SelectionLines) LineRunes

func (s SelectionLines) LineRunes(line int) int

LineRunes returns the rune length of line, or 0 when line is out of range.

type SelectionMetrics

type SelectionMetrics interface {
	// LineCount returns the number of lines; always >= 1 for a valid buffer.
	LineCount() int
	// LineRunes returns the rune length of line, or 0 when line is out of range.
	LineRunes(line int) int
}

SelectionMetrics supplies the buffer geometry the engine needs to clamp cursors: how many lines exist and how many runes each line holds. CodeEditor satisfies it via SelectionLines(this.lines).

type SelectionSet

type SelectionSet struct {
	// contains filtered or unexported fields
}

SelectionSet is a primary cursor plus any number of secondary cursors, each with its own selection. It keeps itself normalized: cursors stay clamped to the buffer, secondary cursors stay ordered top-down, and cursors whose ranges overlap or touch are merged into one.

column records that the current set came from AddCursorsForColumnBlock, i.e. it is a rectangular (block) selection rather than a scatter of carets. It only affects the undo description CollectEdits produces.

func NewSelectionSet

func NewSelectionSet(m SelectionMetrics, line, col int) *SelectionSet

NewSelectionSet returns a single-cursor set at (line, col), clamped to m. A nil m behaves as a one-line empty buffer.

func (*SelectionSet) AddCursor

func (s *SelectionSet) AddCursor(line, col int)

AddCursor adds a secondary caret at (line, col) with no selection. A caret that lands on another cursor, or inside another cursor's selection, is merged away by Normalize, so adding the same position twice is a no-op.

func (*SelectionSet) AddCursorsForColumnBlock

func (s *SelectionSet) AddCursorsForColumnBlock(l1, c1, l2, c2 int)

AddCursorsForColumnBlock replaces the set with the rectangular block spanned by the corners (l1,c1) and (l2,c2): one cursor per line of the block, each selecting the block's column span. Ragged lines clamp — a line shorter than the block's left column collapses to an empty range at its end — so a block over uneven text still yields exactly one cursor per line.

Every caret sits at the block's right column with its anchor at the left one, regardless of drag direction, and every cursor's sticky column is the block's (unclamped) right column so moving the block vertically keeps its shape. The primary lands on l2, the line where the drag ended. ColumnMode reports true afterwards.

func (*SelectionSet) AddSelection

func (s *SelectionSet) AddSelection(anchorLine, anchorCol, line, col int)

AddSelection adds a secondary cursor selecting anchor..caret, with its caret at (line, col) so a following MoveAll extends from the right end. Used for "select next occurrence", where every match gets its own range.

func (*SelectionSet) ClearSecondary

func (s *SelectionSet) ClearSecondary()

ClearSecondary drops every secondary cursor and leaves column mode, keeping the primary cursor and its selection. This is the Esc path back to single-cursor editing.

func (*SelectionSet) CollectEdits

func (s *SelectionSet) CollectEdits(replacement string) CompoundEdit

CollectEdits turns the set into the replacement of every cursor's range with replacement, in safe apply order. Collapsed cursors yield zero-width insertions, so typing a character and replacing three selections both come out as one CompoundEdit.

func (*SelectionSet) ColumnMode

func (s *SelectionSet) ColumnMode() bool

ColumnMode reports whether the set is a rectangular block selection.

func (*SelectionSet) Count

func (s *SelectionSet) Count() int

Count returns the number of cursors, always at least 1.

func (*SelectionSet) Cursors

func (s *SelectionSet) Cursors() []EditorCursor

Cursors returns every cursor (primary included) ordered top-down by range start — the order to walk for rendering.

func (*SelectionSet) HasSelection

func (s *SelectionSet) HasSelection() bool

HasSelection reports whether any cursor covers a non-empty range.

func (*SelectionSet) MoveAll

func (s *SelectionSet) MoveAll(dLine, dCol int, extend bool)

MoveAll moves every cursor by (dLine, dCol) and re-normalizes the set.

Horizontal motion steps across line boundaries the way Left/Right does and resets each cursor's sticky column to where it landed. Vertical motion aims at the sticky column, clamping only the resulting Col so DesiredCol survives a short line. When both deltas are non-zero the horizontal step runs first.

extend=true keeps each cursor's anchor, growing (or shrinking) its own selection; extend=false collapses every cursor onto its new caret.

func (*SelectionSet) Normalize

func (s *SelectionSet) Normalize()

Normalize clamps every cursor to the buffer, orders the set top-down and merges cursors whose ranges overlap or touch (which is also how duplicate carets are deduped). The primary cursor survives every merge it takes part in, keeping its own drag direction. Normalize is idempotent.

func (*SelectionSet) Primary

func (s *SelectionSet) Primary() EditorCursor

Primary returns the primary cursor — the one that owns the visible caret and that keyboard-driven motion reports back to the editor.

func (*SelectionSet) Secondary

func (s *SelectionSet) Secondary() []EditorCursor

Secondary returns a copy of the secondary cursors, ordered top-down.

func (*SelectionSet) SetMetrics

func (s *SelectionSet) SetMetrics(m SelectionMetrics)

SetMetrics swaps the buffer geometry (call it after the text changed) and re-clamps every cursor to the new bounds.

func (*SelectionSet) SetPrimary

func (s *SelectionSet) SetPrimary(c EditorCursor)

SetPrimary replaces the primary cursor, then re-normalizes the set.

type Selector

type Selector struct {
	Type  string // widget type name, or "*" for the universal selector
	ID    string // optional widget id (without the leading '#'); "" if none
	State string // optional pseudo-class state (without the leading ':'); "" if none
}

Selector identifies which widgets a Rule applies to.

func (Selector) String

func (s Selector) String() string

String renders the selector back into its QSS-lite source form.

type Separator

type Separator struct {
	Widget
}

分隔线 通常用来分隔两个相邻菜单按钮 分隔线表现形式是一条线, 宽度大于高度时是横线, 反之是竖线

func NewSeparator

func NewSeparator() *Separator

func (*Separator) Draw

func (this *Separator) Draw(cc paint.Painter)

func (*Separator) SizeHints

func (this *Separator) SizeHints() SizeHints

type SetpointBox

type SetpointBox struct {
	NumberInput
	// contains filtered or unexported fields
}

SetpointBox 设定值输入框: 操作员改写工艺设定值并回写到 tag 的控件。

It embeds NumberInput, so the value, the [min,max] clamp, the keyboard editing and the step buttons are the ones the operator already knows. What it adds is the write direction the rest of the 组态 widgets do not have: a commit callback fired on Enter and on blur, which scada.BindScreen routes to core.Tag.SetValue.

SetValue deliberately does NOT commit. The tag->widget refresh drives SetValue on every sample, so committing from there would write each displayed value straight back to the tag.

func NewSetpointBox

func NewSetpointBox() *SetpointBox

NewSetpointBox creates a setpoint field with the NumberInput defaults (range 0..100, step 1, 2 decimals) and no tag.

func (*SetpointBox) Commit

func (this *SetpointBox) Commit()

Commit hands the current value to the commit callback, if one is installed.

func (*SetpointBox) EnumProperties

func (this *SetpointBox) EnumProperties(list core.IPropertyList)

func (*SetpointBox) OnFocusOut

func (this *SetpointBox) OnFocusOut()

OnFocusOut commits what the operator left in the field, after NumberInput's own blur handling has committed any open edit into Value().

func (*SetpointBox) OnKeyDown

func (this *SetpointBox) OnKeyDown(key int, repeat bool)

OnKeyDown lets the embedded NumberInput handle the key first — Enter there closes an open edit session and parses the typed text into Value() — then commits, so what is written is the value the operator is reading.

func (*SetpointBox) SetTagName

func (this *SetpointBox) SetTagName(s string)

SetTagName sets the design-time tag name that this widget reads and writes.

func (*SetpointBox) SigCommit

func (this *SetpointBox) SigCommit(fn func(float64))

SigCommit installs the operator-confirm callback — the one place a value leaves this widget. Pass nil to detach it.

func (*SetpointBox) TagName

func (this *SetpointBox) TagName() string

TagName returns the design-time tag name.

type SimpleTableModel

type SimpleTableModel struct {
	// contains filtered or unexported fields
}

SimpleTableModel is a basic in-memory TableModel implementation.

func NewSimpleTableModel

func NewSimpleTableModel(headers []string) *SimpleTableModel

NewSimpleTableModel creates a new SimpleTableModel with the given column headers.

func (*SimpleTableModel) AddRow

func (m *SimpleTableModel) AddRow(cells ...string)

AddRow appends a new row of cell values.

func (*SimpleTableModel) CellText

func (m *SimpleTableModel) CellText(row, col int) string

func (*SimpleTableModel) ColumnCount

func (m *SimpleTableModel) ColumnCount() int

func (*SimpleTableModel) ColumnWidth

func (m *SimpleTableModel) ColumnWidth(col int) float64

func (*SimpleTableModel) HeaderText

func (m *SimpleTableModel) HeaderText(col int) string

func (*SimpleTableModel) RemoveRow

func (m *SimpleTableModel) RemoveRow(row int)

RemoveRow removes the row at the given index.

func (*SimpleTableModel) RestoreOrder

func (m *SimpleTableModel) RestoreOrder()

RestoreOrder reverts the rows to the original insertion order captured before the first sort.

func (*SimpleTableModel) RowCount

func (m *SimpleTableModel) RowCount() int

func (*SimpleTableModel) RowData

func (m *SimpleTableModel) RowData(row int) []string

RowData returns a copy of the cells at the given row.

func (*SimpleTableModel) SetCellText

func (m *SimpleTableModel) SetCellText(row, col int, text string)

SetCellText writes a single cell, ignoring out-of-range indices. It makes SimpleTableModel satisfy EditableTableModel so Table's inline editor can commit into it.

func (*SimpleTableModel) SetColumnWidth

func (m *SimpleTableModel) SetColumnWidth(col int, width float64)

SetColumnWidth sets the width of a specific column.

func (*SimpleTableModel) SetRow

func (m *SimpleTableModel) SetRow(row int, cells ...string)

SetRow replaces the cell values at the given row index.

func (*SimpleTableModel) SortByColumn

func (m *SimpleTableModel) SortByColumn(col int, ascending bool)

SortByColumn reorders the rows by the given column. Numeric columns are compared as numbers, others case-insensitively as strings. The first sort captures the insertion order so RestoreOrder can revert to it.

type SizeHints

type SizeHints struct {
	Width, Height       float64
	MinWidth, MinHeight float64 // 最小尺寸约束
	MaxWidth, MaxHeight float64 // 最大尺寸约束 (0=无限制)
	Stretch             int     // 拉伸权重 (0=不拉伸/使用固定尺寸, >0=按权重分配剩余空间)
	Policy              SizePolicy
}

type SizePolicy

type SizePolicy int
const (
	ExpandHorizontal SizePolicy = 0x0001
	ExpandVertical   SizePolicy = 0x0002
	GrowHorizontal   SizePolicy = 0x0004
	GrowVertical     SizePolicy = 0x0008
	ShrinkHorizontal SizePolicy = 0x0010
	ShrinkVertical   SizePolicy = 0x0020
)

type Slider

type Slider struct {
	Widget
	// contains filtered or unexported fields
}

Slider provides a draggable control for selecting a value within a range

func NewSlider

func NewSlider(min, max float64) *Slider

func (*Slider) Draw

func (this *Slider) Draw(g paint.Painter)

func (*Slider) EnumProperties

func (this *Slider) EnumProperties(list core.IPropertyList)

func (*Slider) Init

func (this *Slider) Init(self IWidget)

Init installs a default range. NewSlider takes its bounds as arguments, but the designer palette and the form loader build widgets through core.New, which only calls Init — a min == max == 0 slider clamps every SetValue to 0 and cannot be dragged anywhere.

func (*Slider) IsVertical

func (this *Slider) IsVertical() bool

func (*Slider) Max

func (this *Slider) Max() float64

func (*Slider) Min

func (this *Slider) Min() float64

func (*Slider) OnKeyDown

func (this *Slider) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown, giving the slider Qt QSlider style keyboard navigation while it holds focus. The same key mapping is used for both orientations: Up/Right increase, Down/Left decrease.

func (*Slider) OnLeftDown

func (this *Slider) OnLeftDown(x, y float64)

func (*Slider) OnLeftUp

func (this *Slider) OnLeftUp(x, y float64)

func (*Slider) OnMouseEnter

func (this *Slider) OnMouseEnter()

func (*Slider) OnMouseLeave

func (this *Slider) OnMouseLeave()

func (*Slider) OnMouseMove

func (this *Slider) OnMouseMove(x, y float64)

func (*Slider) PageStep

func (this *Slider) PageStep() float64

PageStep returns the larger step used by PageUp/PageDown. When unset it defaults to 1/10 of the range.

func (*Slider) Range

func (this *Slider) Range() (min, max float64)

func (*Slider) SetMax

func (this *Slider) SetMax(v float64)

func (*Slider) SetMin

func (this *Slider) SetMin(v float64)

func (*Slider) SetPageStep

func (this *Slider) SetPageStep(s float64)

func (*Slider) SetRange

func (this *Slider) SetRange(min, max float64)

func (*Slider) SetStep

func (this *Slider) SetStep(s float64)

func (*Slider) SetTickInterval

func (this *Slider) SetTickInterval(v float64)

func (*Slider) SetValue

func (this *Slider) SetValue(v float64)

func (*Slider) SetValueChangedCallback

func (this *Slider) SetValueChangedCallback(cb func(interface{}, float64))

func (*Slider) SetVertical

func (this *Slider) SetVertical(b bool)

func (*Slider) SizeHints

func (this *Slider) SizeHints() SizeHints

func (*Slider) Step

func (this *Slider) Step() float64

Step returns the single-step size used by the arrow keys. When unset it defaults to 1/100 of the range, mirroring Qt's QAbstractSlider.

func (*Slider) TickInterval

func (this *Slider) TickInterval() float64

TickInterval is the spacing between tick marks drawn along the track. A value of 0 disables tick marks.

func (*Slider) Value

func (this *Slider) Value() float64

type Snippet

type Snippet struct {
	Trigger string // e.g. "iferr"
	Title   string // human label, e.g. "if err != nil"
	Body    string // template body; may contain "$0" cursor mark
}

Snippet is a single trigger-to-body template.

Body may contain a single "$0" mark indicating the final cursor position after expansion. The mark is stripped from the inserted text.

type SnippetSet

type SnippetSet struct {
	// contains filtered or unexported fields
}

SnippetSet is an ordered, lookup-friendly bundle of Snippets.

func NewGoSnippetSet

func NewGoSnippetSet() *SnippetSet

NewGoSnippetSet returns the default Go snippet set.

func (*SnippetSet) ByTrigger

func (this *SnippetSet) ByTrigger(trigger string) *Snippet

ByTrigger returns the snippet for trigger, or nil if none.

func (*SnippetSet) Expand

func (this *SnippetSet) Expand(buffer string, cursor int, trigger string) (string, int, bool)

Expand attempts to expand the trigger ending at cursor in buffer.

Preconditions for expansion (all required):

  • The last len([]rune(trigger)) runes before cursor equal trigger.
  • The rune immediately left of the trigger is either start-of-buffer, a newline, or a non-identifier character (so "xiferr" doesn't match "iferr").
  • SnippetSet has a snippet registered for trigger.

On match, the trigger text is removed and the snippet body is inserted in its place. The leading whitespace of the current line is captured and prefixed to every body line AFTER the first, so the expansion lines up with the trigger column. The "$0" cursor mark, if present, is stripped from the inserted text and newCursor is positioned where it sat; otherwise newCursor lands at the end of the inserted body.

Returns ok=false (and unchanged buffer/cursor) when no snippet matches.

func (*SnippetSet) Triggers

func (this *SnippetSet) Triggers() []string

Triggers returns the trigger strings in registration order.

type SortableTableModel

type SortableTableModel interface {
	SortByColumn(col int, ascending bool)
	RestoreOrder()
}

SortableTableModel is an optional capability for models that support click-to-sort on column headers. SortByColumn reorders the rows by the given column; RestoreOrder reverts to the original insertion order.

type Space

type Space struct {
	Widget
	// contains filtered or unexported fields
}

空格 此控件除占用空白区域以外, 没有其他作用 可以设置为带有弹性, 如果布局器支持, 有弹性表现为看不见的弹簧, 占用尽可能多的空间

func NewSpace

func NewSpace(vertical, expand bool) *Space

func (*Space) Draw

func (this *Space) Draw(cc paint.Painter)

func (*Space) EnumProperties

func (this *Space) EnumProperties(list core.IPropertyList)

func (*Space) IsExpand

func (this *Space) IsExpand() bool

func (*Space) IsVertical

func (this *Space) IsVertical() bool

func (*Space) MinSize

func (this *Space) MinSize() float64

func (*Space) SetExpand

func (this *Space) SetExpand(b bool)

func (*Space) SetMinSize

func (this *Space) SetMinSize(min float64)

func (*Space) SetVertical

func (this *Space) SetVertical(b bool)

SetVertical switches the axis the space occupies. Both flags feed SizeHints, which the parent layout has already read, so the parent is re-laid out — a spring flipped in the designer that keeps its old orientation on screen looks like the setter did nothing.

func (*Space) SizeHints

func (this *Space) SizeHints() SizeHints

type SpinBox

type SpinBox struct {
	Widget
	// contains filtered or unexported fields
}

SpinBox is a numeric input widget with up/down buttons, equivalent to QSpinBox in Qt.

func NewSpinBox

func NewSpinBox() *SpinBox

func (*SpinBox) Draw

func (this *SpinBox) Draw(g paint.Painter)

func (*SpinBox) EnumProperties

func (this *SpinBox) EnumProperties(list core.IPropertyList)

func (*SpinBox) Init

func (this *SpinBox) Init(self IWidget)

func (*SpinBox) Max

func (this *SpinBox) Max() int

func (*SpinBox) Min

func (this *SpinBox) Min() int

func (*SpinBox) OnKeyDown

func (this *SpinBox) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown, giving the spin box Qt QSpinBox style keyboard navigation while it holds focus: Up/Down step by step, PageUp/ PageDown by the larger page step, and Home/End jump to min/max. The spin box always has a bounded [min, max] range, so Home/End are always meaningful. All paths route through SetValue, so clamping and the change callback behave exactly as the up/down buttons do (callback fires only on a real change).

func (*SpinBox) OnLeftDown

func (this *SpinBox) OnLeftDown(x, y float64)

func (*SpinBox) OnLeftUp

func (this *SpinBox) OnLeftUp(x, y float64)

func (*SpinBox) OnMouseEnter

func (this *SpinBox) OnMouseEnter()

func (*SpinBox) OnMouseLeave

func (this *SpinBox) OnMouseLeave()

func (*SpinBox) OnMouseMove

func (this *SpinBox) OnMouseMove(x, y float64)

func (*SpinBox) OnMouseWheel

func (this *SpinBox) OnMouseWheel(x, y, z float64)

func (*SpinBox) PageStep

func (this *SpinBox) PageStep() int

PageStep returns the larger step used by PageUp/PageDown. When unset it defaults to 10*step, mirroring QSpinBox's page jump.

func (*SpinBox) SetMax

func (this *SpinBox) SetMax(v int)

func (*SpinBox) SetMin

func (this *SpinBox) SetMin(v int)

func (*SpinBox) SetPageStep

func (this *SpinBox) SetPageStep(s int)

func (*SpinBox) SetRange

func (this *SpinBox) SetRange(min, max int)

func (*SpinBox) SetStep

func (this *SpinBox) SetStep(s int)

func (*SpinBox) SetSuffix

func (this *SpinBox) SetSuffix(s string)

func (*SpinBox) SetValue

func (this *SpinBox) SetValue(v int)

func (*SpinBox) SetValueChangedCallback

func (this *SpinBox) SetValueChangedCallback(cb func(interface{}, int))

func (*SpinBox) SizeHints

func (this *SpinBox) SizeHints() SizeHints

func (*SpinBox) Step

func (this *SpinBox) Step() int

func (*SpinBox) Suffix

func (this *SpinBox) Suffix() string

func (*SpinBox) Value

func (this *SpinBox) Value() int

type Spinner

type Spinner struct {
	Widget
	// contains filtered or unexported fields
}

Spinner is an animated busy indicator: eight dots arranged on a circle, with the "current" dot at full alpha and trailing dots fading toward transparent. The pattern rotates once per CycleDuration so the user perceives the widget as alive.

Usage:

sp := gui.NewSpinner()
sp.SetSize(24, 24)
sp.SetParent(parent)
// later, when the long-running op finishes:
sp.SetBusy(false)

Spinners draw nothing while !busy, so it's safe to leave one in the layout permanently and just toggle SetBusy(true/false) when an operation runs.

Internally a single looping Animation drives redraws — its onUpdate is a no-op, but its presence makes gui.HasActiveAnimations() report true so the window event loop keeps ticking. That heartbeat exists only while the spinner could actually be seen (busy, attached, visible); see canDrive. The phase that Draw uses is computed straight from time.Since(startTime), so the visual is independent of the animation tick rate (it stays smooth even if AnimationTick lands on irregular intervals).

func NewSpinner

func NewSpinner() *Spinner

NewSpinner creates a spinner with sensible defaults: theme accent colour, 8 dots, 1-second rotation cycle. The widget starts in the busy state so adding it to a layout immediately animates — call SetBusy(false) afterwards if you want to start hidden.

No heartbeat is armed here. A spinner that has not been parented cannot be on screen, and arming at construction meant every spinner ever built — including ones dropped without being used — registered a looping Animation that nothing could ever evict. SetParent arms it.

func (*Spinner) Color

func (this *Spinner) Color() paint.Color

Color returns the configured dot colour.

func (*Spinner) CycleDuration

func (this *Spinner) CycleDuration() time.Duration

CycleDuration returns the rotation period.

func (*Spinner) Detach

func (this *Spinner) Detach()

Detach must route through Spinner.SetParent; Widget.Detach calls the embedded Widget.SetParent directly and would skip the heartbeat.

func (*Spinner) DotCount

func (this *Spinner) DotCount() int

DotCount returns the current dot count.

func (*Spinner) Draw

func (this *Spinner) Draw(g paint.Painter)

Draw paints the eight-dot rotating pattern when busy; renders nothing when not busy so a stopped spinner leaves no visual residue. The phase is computed straight from elapsed time so the rotation rate stays constant regardless of how often AnimationTick fires.

func (*Spinner) EnumProperties

func (this *Spinner) EnumProperties(list core.IPropertyList)

EnumProperties exposes the user-tunable properties for the designer's property sheet. Cycle duration is left out because the property sheet doesn't render time.Duration cleanly yet.

func (*Spinner) Init

func (this *Spinner) Init(self IWidget)

Init carries the defaults, not NewSpinner: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Draw bails below 3 dots, so a factory spinner left at zero could not render even once SetBusy(true) armed it.

The busy flag and the phase origin belong here too — a factory spinner that starts !busy draws nothing at all. Arming the heartbeat does not: Init runs for every reflect-built widget, including throwaway instances the designer never shows, and each startAnim would leave a looping Animation behind. The heartbeat is started by NewSpinner and by SetBusy(true) instead.

func (*Spinner) IsBusy

func (this *Spinner) IsBusy() bool

IsBusy reports whether the spinner is currently animating.

func (*Spinner) OnHide

func (this *Spinner) OnHide()

func (*Spinner) OnShow

func (this *Spinner) OnShow()

OnShow / OnHide are the widget tree's visibility seam (see Widget.setVisible). A hidden spinner paints nothing, so it must not keep the event loop at the animation tick either — hiding one used to cost more CPU than showing it, because the loop kept ticking and dirtying windows for a widget that drew nothing.

SetVisible does not repaint on its own, and the heartbeat we just dropped is what used to dirty the window on the next frame, so the vacated rect is invalidated here — same as Menu.OnHide.

func (*Spinner) SetBusy

func (this *Spinner) SetBusy(b bool)

SetBusy toggles the animation. true starts the rotation and resets the phase so the spinner doesn't appear to jump when reactivated; false stops the underlying Animation so the window event loop can idle when nothing else needs ticking.

A factory-built spinner starts busy but unarmed (Init sets the flag, not the heartbeat), so SetBusy(true) still has work to do there even though the flag already reads true.

func (*Spinner) SetColor

func (this *Spinner) SetColor(c paint.Color)

SetColor overrides the dot colour. Defaults to the theme accent so most callers shouldn't need this — it exists for spinners on non-default surface colours (e.g. dark dialogs) where the theme accent provides poor contrast.

func (*Spinner) SetCycleDuration

func (this *Spinner) SetCycleDuration(d time.Duration)

SetCycleDuration sets how long one full rotation takes. Default 1 second; smaller values look more urgent, larger values calmer. Negative or zero falls back to 1 second so Draw never divides by zero when computing phase.

func (*Spinner) SetDotCount

func (this *Spinner) SetDotCount(n int)

SetDotCount changes the number of dots on the circle. 8 is the default — fewer dots look chunkier, more dots look smoother. Below 3 the visual collapses to a single travelling dot.

func (*Spinner) SetParent

func (this *Spinner) SetParent(parent IWidget)

SetParent arms or drops the heartbeat along with the attachment. A spinner only earns the 60fps tick once it is in a widget tree, and loses it the moment it is detached — so reparenting away, or dropping the last reference to a spinner that was never attached, leaves nothing registered with animManager.

func (*Spinner) SizeHints

func (this *Spinner) SizeHints() SizeHints

SizeHints reports a default 24×24 with growth disabled — spinners are usually small icons next to a label, not stretched across a container. Callers that want a bigger spinner SetSize after add.

type Splitter

type Splitter struct {
	Widget
	// contains filtered or unexported fields
}

Splitter is a layout container that splits space between children with draggable handles (similar to QSplitter).

func NewSplitter

func NewSplitter(vertical bool) *Splitter

func (*Splitter) AddWidget

func (this *Splitter) AddWidget(w IWidget)

AddWidget adds a pane (child) to the splitter.

func (*Splitter) Cursor

func (this *Splitter) Cursor() *Cursor

func (*Splitter) Draw

func (this *Splitter) Draw(g paint.Painter)

func (*Splitter) EnumProperties

func (this *Splitter) EnumProperties(list core.IPropertyList)

func (*Splitter) HandleSize

func (this *Splitter) HandleSize() float64

func (*Splitter) Init

func (this *Splitter) Init(iw IWidget)

Init carries the defaults the factory path depends on. A reflect-built splitter (designer palette, form loader) only ever gets Init, and dragging left at 0 makes the first bare mouse move take the drag branch: it indexes sizes[0]/sizes[1] on a splitter that may have neither pane, and silently resizes one that does. handleSize belongs here too -- a 0 handle is a zero-width grab target no mouse position can hit.

func (*Splitter) Layout

func (this *Splitter) Layout()

func (*Splitter) OnLeftDown

func (this *Splitter) OnLeftDown(x, y float64)

func (*Splitter) OnLeftUp

func (this *Splitter) OnLeftUp(x, y float64)

func (*Splitter) OnMouseLeave

func (this *Splitter) OnMouseLeave()

func (*Splitter) OnMouseMove

func (this *Splitter) OnMouseMove(x, y float64)

func (*Splitter) SetHandleSize

func (this *Splitter) SetHandleSize(s float64)

func (*Splitter) SetSizes

func (this *Splitter) SetSizes(sizes []float64)

SetSizes sets the proportional sizes for each child pane.

func (*Splitter) SetVertical

func (this *Splitter) SetVertical(b bool)

func (*Splitter) SizeHints

func (this *Splitter) SizeHints() SizeHints

func (*Splitter) Sizes

func (this *Splitter) Sizes() []float64

Sizes returns the current proportional sizes.

func (*Splitter) Vertical

func (this *Splitter) Vertical() bool

type StackedWidget

type StackedWidget struct {
	Widget
	// contains filtered or unexported fields
}

StackedWidget shows one page at a time from a stack of child widgets, equivalent to QStackedWidget in Qt.

func NewStackedWidget

func NewStackedWidget() *StackedWidget

func (*StackedWidget) AddPage

func (this *StackedWidget) AddPage(w IWidget)

func (*StackedWidget) Count

func (this *StackedWidget) Count() int

func (*StackedWidget) CurrentIndex

func (this *StackedWidget) CurrentIndex() int

func (*StackedWidget) CurrentPage

func (this *StackedWidget) CurrentPage() IWidget

func (*StackedWidget) Draw

func (this *StackedWidget) Draw(g paint.Painter)

func (*StackedWidget) Init

func (this *StackedWidget) Init(self IWidget)

func (*StackedWidget) Layout

func (this *StackedWidget) Layout()

func (*StackedWidget) MovePage

func (this *StackedWidget) MovePage(from, to int)

MovePage reorders the pages in place, the way a tab strip does when a tab is dragged to a new position. It only renumbers: no page is reparented, hidden or shown, so whatever was on screen stays on screen.

func (*StackedWidget) Page

func (this *StackedWidget) Page(idx int) IWidget

func (*StackedWidget) RemovePage

func (this *StackedWidget) RemovePage(idx int)

func (*StackedWidget) SetCurrentIndex

func (this *StackedWidget) SetCurrentIndex(idx int)

func (*StackedWidget) SizeHints

func (this *StackedWidget) SizeHints() SizeHints

type StatRow

type StatRow struct {
	Tag   string
	Count int
	Min   float64
	Max   float64
	Avg   float64
	Last  float64
}

StatRow is one plain view-model row for a per-tag statistics table: the tag name plus its running count and min/max/avg/last aggregates. It is a value type carrying no backend references, so the host can compute it from whatever stats source it likes (typically package stats) and hand the panel a flat snapshot. Copying a StatRow fully isolates it.

type State

type State int

State is the result of a Validator's classification of an input string. Mirrors Qt's QValidator::State three-value enum, which is the canonical shape for input validators that need to distinguish "not valid yet, but the user might still finish typing" from "definitively wrong".

Edit / SpinBox / NumberInput call Validator.Validate on each keypress and react per state:

  • Invalid → reject the change, current text stays
  • Intermediate → accept the change, but disable Submit / OK actions
  • Acceptable → accept and treat as final
const (
	// Invalid means the input cannot become valid no matter what the user
	// types next. Edit reverts to the previous accepted text.
	Invalid State = iota

	// Intermediate means the input is incomplete but could become valid
	// after additional keystrokes. Edit accepts the change but the host
	// should refuse to commit (e.g. greyed-out OK button).
	Intermediate

	// Acceptable means the input fully satisfies the validator. Safe to
	// commit / submit.
	Acceptable
)

func (State) String

func (s State) String() string

String aids debug and error logs. Mirrors the Qt naming.

type StatsPanel

type StatsPanel struct {
	Widget
	// contains filtered or unexported fields
}

StatsPanel is a live per-tag 统计 (statistics) table for SCADA / 组态 screens: a scrollable list showing, per tag, the sample Count and the Min / Max / Avg / Last aggregates, plus a per-row 清零 (clear) affordance. It is deliberately UI-only and holds nothing but plain StatRow view-model data fed via SetStats; it does not import or know about the backend stats engine. The host computes a snapshot, calls SetStats, and wires SigReset to clear a tag's aggregates.

Resetting is not done here. A click on a row's 清零 cell fires SigReset(tag); the host clears that tag in its stats store and pushes a fresh snapshot back. This keeps the panel a pure, GL-free-testable view.

func NewStatsPanel

func NewStatsPanel() *StatsPanel

NewStatsPanel creates an empty statistics panel.

func (*StatsPanel) Draw

func (this *StatsPanel) Draw(g paint.Painter)

Draw renders a title band, a column-header band, then one scrollable row per tag. All colours come from Theme() semantic fields so the panel reads correctly in the dark IDE theme; zebra striping is a low-alpha TextColor tint that stays visible in both light and dark modes (ViewBGColor == FormColor in dark mode, so a FormColor stripe would vanish).

func (*StatsPanel) Init

func (this *StatsPanel) Init(self IWidget)

func (*StatsPanel) OnLeftDown

func (this *StatsPanel) OnLeftDown(x, y float64)

OnLeftDown fires SigReset when the click lands in a row's right-anchored 清零 column. Clicks elsewhere on a row, on either header band, or past the last row are ignored.

func (*StatsPanel) OnMouseWheel

func (this *StatsPanel) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the row list vertically.

func (*StatsPanel) RowCount

func (this *StatsPanel) RowCount() int

RowCount returns the number of rows currently displayed.

func (*StatsPanel) SetStats

func (this *StatsPanel) SetStats(in []StatRow)

SetStats replaces the displayed rows with a defensive copy of in. StatRow is a value type, so the shallow copy fully isolates the panel from later mutation of the caller's slice. The panel renders the rows verbatim in the order given (the host decides the ordering). The scroll offset is clamped to the new content rather than reset, so a live refresh does not yank the operator's view back to the top.

func (*StatsPanel) SigReset

func (this *StatsPanel) SigReset(fn func(tag string))

SigReset registers the callback fired when the operator clicks a row's 清零 affordance. It receives the row's tag; the host clears that tag's statistics and pushes a refreshed snapshot back via SetStats.

func (*StatsPanel) SizeHints

func (this *StatsPanel) SizeHints() SizeHints

func (*StatsPanel) Stats

func (this *StatsPanel) Stats() []StatRow

Stats returns a defensive copy of the displayed rows in display order.

type StatusBar

type StatusBar struct {
	Widget
	// contains filtered or unexported fields
}

StatusBar is a horizontal bar at the bottom of a frame showing a message and optional permanent widgets on the right. Similar to QStatusBar.

func NewStatusBar

func NewStatusBar() *StatusBar

func (*StatusBar) AddIconLabel

func (this *StatusBar) AddIconLabel(icon string, text string) *StatusIconLabel

AddIconLabel creates a StatusIconLabel (icon + text) and adds it as a permanent widget on the right, returning it so the caller can update it later via SetText / SetIcon. icon is an icon resource name (e.g. "git-branch").

func (*StatusBar) AddPermanentWidget

func (this *StatusBar) AddPermanentWidget(iw IWidget)

AddPermanentWidget adds a widget to the right side of the status bar (e.g. a progress bar, label, or indicator).

func (*StatusBar) ClearMessage

func (this *StatusBar) ClearMessage()

ClearMessage clears the status message.

func (*StatusBar) Draw

func (this *StatusBar) Draw(g paint.Painter)

func (*StatusBar) EnumProperties

func (this *StatusBar) EnumProperties(list core.IPropertyList)

func (*StatusBar) Layout

func (this *StatusBar) Layout()

Layout positions the permanent widgets on the right side.

func (*StatusBar) Message

func (this *StatusBar) Message() string

Message returns the current status message.

func (*StatusBar) OnIdle

func (this *StatusBar) OnIdle()

func (*StatusBar) PermanentWidgets

func (this *StatusBar) PermanentWidgets() []IWidget

PermanentWidgets returns the list of permanent widgets.

func (*StatusBar) RemovePermanentWidget

func (this *StatusBar) RemovePermanentWidget(iw IWidget)

RemovePermanentWidget removes a permanent widget.

func (*StatusBar) SetMessage

func (this *StatusBar) SetMessage(text string)

SetMessage sets the permanent status message.

func (*StatusBar) ShowMessage

func (this *StatusBar) ShowMessage(text string)

ShowMessage displays a temporary status message (no timeout for now).

func (*StatusBar) ShowMessageFor

func (this *StatusBar) ShowMessageFor(text string, timeoutMs uint32)

ShowMessageFor displays a transient status message that is automatically cleared after timeoutMs milliseconds (like QStatusBar.showMessage with a timeout). A pending timer from an earlier timed message is replaced.

func (*StatusBar) SizeHints

func (this *StatusBar) SizeHints() SizeHints

type StatusIconLabel

type StatusIconLabel struct {
	Widget
	// contains filtered or unexported fields
}

StatusIconLabel is a compact status-bar cell that draws a small icon followed by a short text, both vertically centered. It is a permanent widget like any other (add it with AddPermanentWidget or the AddIconLabel helper), letting callers show IDE-style indicators — a branch glyph + branch name, an error or warning glyph + count — in place of a plain text label. An empty icon name draws text only; empty text draws the icon only.

func NewStatusIconLabel

func NewStatusIconLabel(icon string, text string) *StatusIconLabel

NewStatusIconLabel creates an icon+text status cell. icon is an icon resource name (e.g. "git-branch", "error", "warning"); text is the label after it.

func (*StatusIconLabel) Draw

func (this *StatusIconLabel) Draw(g paint.Painter)

Draw renders the icon on the left and the text after it, both vertically centered. Colors come from the theme so the cell tracks light/dark mode.

func (*StatusIconLabel) Icon

func (this *StatusIconLabel) Icon() string

Icon returns the cell's icon resource name.

func (*StatusIconLabel) SetIcon

func (this *StatusIconLabel) SetIcon(name string)

SetIcon changes the icon resource name and re-lays out the parent bar (the cell's width depends on whether an icon is present).

func (*StatusIconLabel) SetText

func (this *StatusIconLabel) SetText(text string)

SetText changes the label text and re-lays out the parent bar, since the cell's width tracks the text width.

func (*StatusIconLabel) SizeHints

func (this *StatusIconLabel) SizeHints() SizeHints

SizeHints reports the cell's natural size: icon + gap + text wide, and tall enough for the taller of the font line and the icon.

func (*StatusIconLabel) Text

func (this *StatusIconLabel) Text() string

Text returns the cell's text.

type StyleSheet

type StyleSheet struct {
	Rules []Rule
}

StyleSheet is an ordered collection of parsed rules.

func ParseStyleSheet

func ParseStyleSheet(src string) (*StyleSheet, error)

ParseStyleSheet parses QSS-lite source into a StyleSheet.

Well-formed rules are always collected. If any rule is malformed, the bad rules are skipped and a *ParseError is returned alongside the partially populated sheet (the sheet is never nil). The parser never panics.

func (*StyleSheet) Lookup

func (ss *StyleSheet) Lookup(widgetType, id, state string) map[string]string

Lookup merges every rule matching (widgetType, id, state) into a single property map, ordered by ascending specificity so more specific rules win:

  1. universal type, stateless ("*")
  2. concrete type, stateless (Type)
  3. universal type + state ("*:state")
  4. concrete type + state (Type:state)
  5. id, stateless (#id / Type#id)
  6. id + state (#id:state / Type#id:state)

Within the same specificity tier, later rules in source order override earlier ones. Passing "" for id or state simply means those tiers do not match. The returned map is always non-nil and safe to mutate.

type StyleVariant

type StyleVariant int

StyleVariant 风格变体枚举

const (
	StyleDefault StyleVariant = iota
	StyleLight                // 浅色主题
	StyleDark                 // 深色主题
	StyleBlue                 // 蓝色主题
	StyleGreen                // 绿色主题
	StylePurple               // 紫色主题
	StyleCustom               // 自定义
)

type SwitchGroup

type SwitchGroup struct {
	Widget
	// contains filtered or unexported fields
}

SwitchGroup is a group of toggle buttons where only one can be active (segmented control).

func NewSwitchGroup

func NewSwitchGroup() *SwitchGroup

func (*SwitchGroup) Draw

func (this *SwitchGroup) Draw(g paint.Painter)

func (*SwitchGroup) EnumProperties

func (this *SwitchGroup) EnumProperties(list core.IPropertyList)

func (*SwitchGroup) Items

func (this *SwitchGroup) Items() []string

func (*SwitchGroup) OnLeftDown

func (this *SwitchGroup) OnLeftDown(x, y float64)

func (*SwitchGroup) OnMouseEnter

func (this *SwitchGroup) OnMouseEnter()

func (*SwitchGroup) OnMouseLeave

func (this *SwitchGroup) OnMouseLeave()

func (*SwitchGroup) Selected

func (this *SwitchGroup) Selected() int

func (*SwitchGroup) SelectedText

func (this *SwitchGroup) SelectedText() string

func (*SwitchGroup) SetItems

func (this *SwitchGroup) SetItems(items []string)

func (*SwitchGroup) SetSelected

func (this *SwitchGroup) SetSelected(idx int)

func (*SwitchGroup) SigChange

func (this *SwitchGroup) SigChange(fn func(int, string))

func (*SwitchGroup) SizeHints

func (this *SwitchGroup) SizeHints() SizeHints

type SymbolPopup

type SymbolPopup struct {
	// contains filtered or unexported fields
}

SymbolPopup provides a "Go to Symbol" overlay for quick navigation.

func NewSymbolPopup

func NewSymbolPopup() *SymbolPopup

NewSymbolPopup creates a new symbol navigation popup.

func (*SymbolPopup) Accept

func (this *SymbolPopup) Accept(editor *CodeEditor)

Accept jumps to the selected symbol and closes the popup.

func (*SymbolPopup) Dismiss

func (this *SymbolPopup) Dismiss()

Dismiss closes the symbol popup.

func (*SymbolPopup) OnBackspace

func (this *SymbolPopup) OnBackspace()

OnBackspace handles backspace in the symbol filter field.

func (*SymbolPopup) OnTextInput

func (this *SymbolPopup) OnTextInput(s string)

OnTextInput handles typing in the symbol filter field.

func (*SymbolPopup) SelectNext

func (this *SymbolPopup) SelectNext()

SelectNext moves selection down.

func (*SymbolPopup) SelectPrev

func (this *SymbolPopup) SelectPrev()

SelectPrev moves selection up.

func (*SymbolPopup) Show

func (this *SymbolPopup) Show(editor *CodeEditor)

Show opens the symbol popup, parsing symbols from the editor.

type SyntaxFoldRegion

type SyntaxFoldRegion struct {
	StartLine int
	EndLine   int
	Kind      FoldKind
}

SyntaxFoldRegion is a foldable span of source lines. Both bounds are 0-based and inclusive, and only multi-line spans are produced (EndLine > StartLine).

func ScanGoFoldRegions

func ScanGoFoldRegions(src string) []SyntaxFoldRegion

ScanGoFoldRegions tokenizes src with go/scanner and returns every foldable region, ordered by StartLine with the outer region first on a tie:

  • FoldKindBlock — a matched '{' ... '}' pair spanning more than one line. Because the input is tokenized, braces inside string literals, raw strings, rune literals and comments do not count, and a '{' that is not the last thing on its line still opens a block.
  • FoldKindImport — an "import ( ... )" group spanning more than one line.
  • FoldKindComment — a run of comments on consecutive lines, each starting its own line. A comment trailing code neither starts nor extends a run; a blank line ends one. A single /* ... */ comment spanning lines is a run of its own.

Malformed input is tolerated: scan errors are swallowed and whatever regions were closed before and after the bad token are still returned. Unbalanced openers are dropped, stray closers are ignored.

func ScanGoFoldRegionsLines

func ScanGoFoldRegionsLines(lines []string) []SyntaxFoldRegion

ScanGoFoldRegionsLines is ScanGoFoldRegions over an editor line buffer. It carries the same pathological-input guard as computeFoldRegions: at or above maxFoldComputeLines it returns nil, so a giant buffer loses folding rather than paying for a full tokenization on every Draw.

type TabBar

type TabBar struct {
	Widget
	// contains filtered or unexported fields
}

标签页 (注: 目前只在Dock中使用, 未准备好用在别处)

func NewTabBar

func NewTabBar() *TabBar

func (*TabBar) ActiveTab

func (this *TabBar) ActiveTab() int

func (*TabBar) AddTab

func (this *TabBar) AddTab(data interface{}, activate bool)

func (*TabBar) CloseTab

func (this *TabBar) CloseTab(idx int) bool

func (*TabBar) Count

func (this *TabBar) Count() int

func (*TabBar) Data

func (this *TabBar) Data(idx int) interface{}

func (*TabBar) Draw

func (this *TabBar) Draw(g paint.Painter)

func (*TabBar) DropIndex

func (this *TabBar) DropIndex(x, y float64) (index int)

func (*TabBar) HitTest

func (this *TabBar) HitTest(x, y float64) (index int, hoverCloseBtn bool)

func (*TabBar) Init

func (this *TabBar) Init(self IWidget)

func (*TabBar) InsertTab

func (this *TabBar) InsertTab(idx int, data interface{}, activate bool)

func (*TabBar) IsEmpty

func (this *TabBar) IsEmpty() bool

func (*TabBar) Layout

func (this *TabBar) Layout()

func (*TabBar) OnDragEnter

func (this *TabBar) OnDragEnter(x, y float64, dnd IDndContext)

func (*TabBar) OnDragLeave

func (this *TabBar) OnDragLeave()

func (*TabBar) OnDragMove

func (this *TabBar) OnDragMove(x, y float64, dnd IDndContext)

func (*TabBar) OnDrop

func (this *TabBar) OnDrop(x, y float64, dnd IDndContext)

func (*TabBar) OnIdle

func (this *TabBar) OnIdle()

func (*TabBar) OnLeftDown

func (this *TabBar) OnLeftDown(x, y float64)

func (*TabBar) OnLeftUp

func (this *TabBar) OnLeftUp(x, y float64)

func (*TabBar) OnMiddleDown

func (this *TabBar) OnMiddleDown(x, y float64)

OnMiddleDown/OnMiddleUp give the strip the close-on-middle-click every IDE has. The press only arms a candidate; the release must land on the same tab, so a middle press that slides off the tab is abandoned like a button press.

func (*TabBar) OnMiddleUp

func (this *TabBar) OnMiddleUp(x, y float64)

func (*TabBar) OnMouseLeave

func (this *TabBar) OnMouseLeave()

func (*TabBar) OnMouseMove

func (this *TabBar) OnMouseMove(x, y float64)

func (*TabBar) RemoveTab

func (this *TabBar) RemoveTab(idx int) interface{}

func (*TabBar) SetActivateCallback

func (this *TabBar) SetActivateCallback(callback func(tb *TabBar, idx int))

func (*TabBar) SetActiveTab

func (this *TabBar) SetActiveTab(idx int)

func (*TabBar) SetCloseCallback

func (this *TabBar) SetCloseCallback(callback func(tb *TabBar, idx int) bool)

func (*TabBar) SetDeactivateCallback

func (this *TabBar) SetDeactivateCallback(callback func(tb *TabBar, idx int))

func (*TabBar) SetDndCallback

func (this *TabBar) SetDndCallback(cbDragStart func(tb *TabBar, idx int) interface{},
	cbDragMove func(tb *TabBar, dnd IDndContext),
	cbDrop func(tb *TabBar, idx int, dnd IDndContext))

func (*TabBar) SetMoveCallback

func (this *TabBar) SetMoveCallback(callback func(tb *TabBar, from, to int))

SetMoveCallback registers a listener for a drag reorder of the strip itself. A container that keeps its own list in tab order (TabWidget's pages) has to apply the same move, otherwise the strip and the list disagree after a drag. Dock needs none: a Dock tab's data is the view it shows, so moving the tab moves the view with it.

func (*TabBar) SizeHints

func (this *TabBar) SizeHints() SizeHints

type TabWidget

type TabWidget struct {
	Widget
	// contains filtered or unexported fields
}

TabWidget combines a TabBar with a StackedWidget to provide a tabbed page container, equivalent to QTabWidget in Qt.

func NewTabWidget

func NewTabWidget() *TabWidget

func (*TabWidget) AddTab

func (this *TabWidget) AddTab(w IWidget, title string, icon paint.Icon)

func (*TabWidget) Count

func (this *TabWidget) Count() int

func (*TabWidget) CurrentIndex

func (this *TabWidget) CurrentIndex() int

func (*TabWidget) Draw

func (this *TabWidget) Draw(g paint.Painter)

func (*TabWidget) Init

func (this *TabWidget) Init(self IWidget)

func (*TabWidget) Layout

func (this *TabWidget) Layout()

func (*TabWidget) OnKeyDown

func (this *TabWidget) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown, giving the TabWidget Qt QTabWidget style keyboard tab switching while it (or its tab strip) holds focus:

  • Ctrl+PageDown / Ctrl+Tab -> next tab (wraps to first)
  • Ctrl+PageUp / Ctrl+Shift+Tab -> previous tab (wraps to last)
  • Left/Up (previous), Right/Down (next) when focused, no Ctrl required

All moves wrap and are no-ops with fewer than two tabs. Note: focus is only reached when the TabWidget itself holds focus; the tab strip's click path lives in TabBar (a sibling file) and does not call SetFocus, so clicking a tab does not by itself arm these shortcuts.

func (*TabWidget) RemoveTab

func (this *TabWidget) RemoveTab(idx int)

func (*TabWidget) SetCurrentChangedCallback

func (this *TabWidget) SetCurrentChangedCallback(cb func(interface{}, int))

func (*TabWidget) SetCurrentIndex

func (this *TabWidget) SetCurrentIndex(idx int)

func (*TabWidget) SizeHints

func (this *TabWidget) SizeHints() SizeHints

func (*TabWidget) Stack

func (this *TabWidget) Stack() *StackedWidget

func (*TabWidget) TabBar

func (this *TabWidget) TabBar() *TabBar

type Table

type Table struct {
	Widget
	// contains filtered or unexported fields
}

Table is a tabular data display widget with a fixed header row, scrollable body, row selection, and alternating row backgrounds.

func NewTable

func NewTable() *Table

NewTable creates a new Table widget.

func (*Table) CurrentRow

func (this *Table) CurrentRow() int

CurrentRow returns the index of the current row, or -1 if none. The table's current row and selected row are the same concept, so this mirrors SelectedRow; both keyboard navigation and clicks move it.

func (*Table) Draw

func (this *Table) Draw(g paint.Painter)

Draw renders the table: header row, data rows with alternating backgrounds, and selection highlight.

func (*Table) EnumProperties

func (this *Table) EnumProperties(list core.IPropertyList)

func (*Table) HeaderHeight

func (this *Table) HeaderHeight() float64

HeaderHeight returns the height of the header row.

func (*Table) Init

func (this *Table) Init(iw IWidget)

Init builds the scroll area and seeds the "nothing selected / nothing hovered" sentinels. All of it lives here rather than in NewTable because the factory (core.RegisterFactory above) constructs a Table by reflection and calls Init and nothing else: a table the designer drops on the canvas skips NewTable entirely, so setup left there gave it a nil scrollArea — Layout dereferenced it on the first SetBounds and panicked — and every sentinel at row/column 0 instead of -1.

func (*Table) IsCellsEditable

func (this *Table) IsCellsEditable() bool

IsCellsEditable reports whether in-place cell editing is enabled.

func (*Table) Layout

func (this *Table) Layout()

Layout arranges the header, scroll area, and scroll bars.

func (*Table) Model

func (this *Table) Model() TableModel

Model returns the current TableModel.

func (*Table) OnKeyDown

func (this *Table) OnKeyDown(key int, repeat bool)

OnKeyDown provides Qt QTableView-style row navigation (it coexists with the header click-to-sort and column-resize handling, which are mouse-only):

Up/Down       : move the current row by one, clamped to the ends
PageUp/PageDown: move by a viewport page of rows
Home/End      : jump to the first/last row
Enter/Space   : activate the current row (fires SigRowActivated)

func (*Table) OnLeftDown

func (this *Table) OnLeftDown(x, y float64)

OnLeftDown handles mouse clicks for row selection.

func (*Table) OnLeftUp

func (this *Table) OnLeftUp(x, y float64)

OnLeftUp ends a column resize drag.

func (*Table) OnMouseLeave

func (this *Table) OnMouseLeave()

OnMouseLeave clears the resize cursor affordance when not actively dragging.

func (*Table) OnMouseMove

func (this *Table) OnMouseMove(x, y float64)

OnMouseMove drives an in-progress column resize and, when idle, shows a horizontal-resize cursor while hovering a header boundary.

func (*Table) OnMouseWheel

func (this *Table) OnMouseWheel(x, y, z float64)

OnMouseWheel handles mouse wheel scrolling.

func (*Table) OnRightDown

func (this *Table) OnRightDown(x, y float64)

OnRightDown handles right-click events for context menu support. It determines which row and column were clicked, selects that row, and fires the context menu callback.

func (*Table) RowHeight

func (this *Table) RowHeight() float64

RowHeight returns the height of each data row.

func (*Table) SelectedRow

func (this *Table) SelectedRow() int

SelectedRow returns the index of the currently selected row, or -1 if none.

func (*Table) SelectedRows

func (this *Table) SelectedRows() []int

SelectedRows returns every selected row index in ascending order. With no multi-selection active it returns just the current row (or an empty slice when nothing is selected), so single-select callers get a sensible result.

func (*Table) SetCellsEditable

func (this *Table) SetCellsEditable(b bool)

SetCellsEditable toggles in-place cell editing. It defaults to false, so a table stays read-only (and byte-for-byte unchanged) unless a host opts in. Turning editing off cancels any editor currently open.

func (*Table) SetContextMenuCallback

func (this *Table) SetContextMenuCallback(fn func(table *Table, row, col int, menu *Menu))

SetContextMenuCallback sets a callback that is invoked when the user right-clicks on the table. The callback receives the table, the row and column indices under the click, and a Menu to populate.

Pass nil to remove the callback.

func (*Table) SetCurrentRow

func (this *Table) SetCurrentRow(row int)

SetCurrentRow sets the current row, clamped to the valid range. It is an alias for SetSelectedRow so the navigation API reads consistently.

func (*Table) SetHeaderHeight

func (this *Table) SetHeaderHeight(h float64)

SetHeaderHeight sets the height of the header row.

func (*Table) SetModel

func (this *Table) SetModel(m TableModel)

SetModel sets the TableModel that provides data for this table.

func (*Table) SetRowHeight

func (this *Table) SetRowHeight(rh float64)

SetRowHeight sets the row height for data rows.

func (*Table) SetSelectedRow

func (this *Table) SetSelectedRow(row int)

SetSelectedRow sets the selected row index.

func (*Table) SetSelectionChangedCallback

func (this *Table) SetSelectionChangedCallback(cb func(interface{}, int))

SetSelectionChangedCallback sets a callback invoked when the selected row changes.

func (*Table) SigCellEdited

func (this *Table) SigCellEdited(fn func(row, col int, newText string))

SigCellEdited sets the callback fired after a cell edit commits, with the edited row, column and the new text. Fires even when the model does not implement EditableTableModel, so a host can persist the value itself.

func (*Table) SigRowActivated

func (this *Table) SigRowActivated(fn func(interface{}, int))

SigRowActivated sets the callback invoked when the current row is activated (Enter or Space). The argument is the activated row index.

func (*Table) SigSortChanged

func (this *Table) SigSortChanged(fn func(col int, ascending bool))

SigSortChanged sets the callback invoked when the sort column or direction changes. col is the sorted column, or -1 when the table returns to its original unsorted order.

func (*Table) SizeHints

func (this *Table) SizeHints() SizeHints

SizeHints returns the preferred size for the table.

func (*Table) SortAscending

func (this *Table) SortAscending() bool

SortAscending reports the direction of the current sort.

func (*Table) SortColumn

func (this *Table) SortColumn() int

SortColumn returns the currently sorted column index, or -1 when unsorted.

type TableModel

type TableModel interface {
	RowCount() int
	ColumnCount() int
	CellText(row, col int) string
	HeaderText(col int) string
	ColumnWidth(col int) float64
}

TableModel is the data interface for Table widgets.

type Tag

type Tag struct {
	Widget
	// contains filtered or unexported fields
}

Tag 标签控件,用于显示标签/状态/分类

func NewTag

func NewTag(text string) *Tag

func (*Tag) Color

func (this *Tag) Color() paint.Color

func (*Tag) Draw

func (this *Tag) Draw(g paint.Painter)

func (*Tag) EnumProperties

func (this *Tag) EnumProperties(list core.IPropertyList)

func (*Tag) Init

func (this *Tag) Init(self IWidget)

Init carries the visual defaults, not NewTag: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Colours left in NewTag render a transparent tag.

func (*Tag) IsCloseable

func (this *Tag) IsCloseable() bool

func (*Tag) OnLeftDown

func (this *Tag) OnLeftDown(x, y float64)

func (*Tag) OnMouseEnter

func (this *Tag) OnMouseEnter()

func (*Tag) OnMouseLeave

func (this *Tag) OnMouseLeave()

func (*Tag) OnMouseMove

func (this *Tag) OnMouseMove(x, y float64)

func (*Tag) SetCloseable

func (this *Tag) SetCloseable(b bool)

func (*Tag) SetColor

func (this *Tag) SetColor(c paint.Color)

func (*Tag) SetText

func (this *Tag) SetText(s string)

func (*Tag) SetTextColor

func (this *Tag) SetTextColor(c paint.Color)

func (*Tag) SigClose

func (this *Tag) SigClose(fn func())

func (*Tag) SizeHints

func (this *Tag) SizeHints() SizeHints

func (*Tag) Text

func (this *Tag) Text() string

type Tank

type Tank struct {
	Widget
	// contains filtered or unexported fields
}

Tank draws a vertical vessel whose liquid fills bottom-up by Level (0..1). Min/Max define the engineering range used only for the optional value label.

func NewTank

func NewTank() *Tank

NewTank creates a Tank filled to 0 with a default blue liquid.

func (*Tank) Color

func (this *Tank) Color() paint.Color

Color returns the liquid color.

func (*Tank) Draw

func (this *Tank) Draw(g paint.Painter)

func (*Tank) EngValue

func (this *Tank) EngValue() float64

EngValue maps the current level onto the engineering range.

func (*Tank) EnumProperties

func (this *Tank) EnumProperties(list core.IPropertyList)

func (*Tank) Init

func (this *Tank) Init(self IWidget)

Init carries the engineering range and the display defaults, not NewTank: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Left there, the range comes up as 0..0 so EngValue() reads 0 at every level, the label is off and the liquid is drawn in a fully transparent color.

func (*Tank) Level

func (this *Tank) Level() float64

Level returns the current fill fraction.

func (*Tank) Max

func (this *Tank) Max() float64

Max returns the engineering maximum.

func (*Tank) Min

func (this *Tank) Min() float64

Min returns the engineering minimum.

func (*Tank) SetColor

func (this *Tank) SetColor(c paint.Color)

SetColor sets the liquid color.

func (*Tank) SetLevel

func (this *Tank) SetLevel(v float64)

SetLevel sets the fill fraction, clamped to [0,1].

func (*Tank) SetMax

func (this *Tank) SetMax(v float64)

SetMax sets the engineering maximum.

func (*Tank) SetMin

func (this *Tank) SetMin(v float64)

SetMin sets the engineering minimum.

func (*Tank) SetRange

func (this *Tank) SetRange(min, max float64)

SetRange sets the engineering min/max used for the value label.

func (*Tank) SetShowLabel

func (this *Tank) SetShowLabel(b bool)

SetShowLabel toggles the percent/value label.

func (*Tank) SetTagName

func (this *Tank) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*Tank) ShowLabel

func (this *Tank) ShowLabel() bool

ShowLabel reports whether the value label is drawn.

func (*Tank) SizeHints

func (this *Tank) SizeHints() SizeHints

func (*Tank) TagName

func (this *Tank) TagName() string

TagName returns the design-time tag name.

type TextAlign

type TextAlign int
const (
	AlignLeft TextAlign = iota
	AlignCenter
	AlignRight
)

type TextArea

type TextArea struct {
	Widget
	// contains filtered or unexported fields
}

TextArea is a multi-line plain-text input — the QPlainTextEdit slot in the toolkit. It is the middle widget in the trio:

  • Edit (single line) for one-line inputs (name, email).
  • TextArea (this file) for paragraphs of plain text — description, notes, comments. NO syntax highlighting, NO line numbers, NO undo/redo, NO completer; just typing, navigation, selection, scroll.
  • CodeEditor for source code (syntax highlighting, gutter, find/ replace, multi-cursor, etc).

The caret and selection model mirrors Edit's — a single anchor + cursor pair, Shift+nav extends selection, Ctrl+A selects all — but the storage is a slice of lines so Enter genuinely inserts a newline instead of dispatching Submit. Lines are stored as plain strings; the public API treats Text() / SetText() as the canonical form, joined with "\n".

func NewTextArea

func NewTextArea() *TextArea

NewTextArea creates an empty TextArea with one (empty) line and the caret at the start.

func (*TextArea) Cursor

func (this *TextArea) Cursor() *Cursor

func (*TextArea) Draw

func (this *TextArea) Draw(g paint.Painter)

func (*TextArea) EnumProperties

func (this *TextArea) EnumProperties(list core.IPropertyList)

func (*TextArea) Init

func (this *TextArea) Init(iw IWidget)

func (*TextArea) IsReadOnly

func (this *TextArea) IsReadOnly() bool

IsReadOnly reports whether typing-driven mutations are blocked.

func (*TextArea) LineCount

func (this *TextArea) LineCount() int

LineCount returns the number of logical lines (always >= 1).

func (*TextArea) OnKeyDown

func (this *TextArea) OnKeyDown(key int, repeat bool)

func (*TextArea) OnLeftDown

func (this *TextArea) OnLeftDown(x, y float64)

func (*TextArea) OnMouseWheel

func (this *TextArea) OnMouseWheel(x, y, z float64)

func (*TextArea) OnTextInput

func (this *TextArea) OnTextInput(s string)

func (*TextArea) Placeholder

func (this *TextArea) Placeholder() string

Placeholder returns the configured hint text.

func (*TextArea) SelectAll

func (this *TextArea) SelectAll()

SelectAll selects the entire buffer; the caret lands at the end.

func (*TextArea) SetPlaceholder

func (this *TextArea) SetPlaceholder(s string)

SetPlaceholder sets the muted hint text drawn when the buffer is empty and unfocused. Empty by default.

func (*TextArea) SetReadOnly

func (this *TextArea) SetReadOnly(b bool)

SetReadOnly toggles the read-only flag. A read-only TextArea still accepts focus, scroll and selection so the user can copy text; only mutations (typing, Backspace, Delete, paste, Enter) are dropped.

func (*TextArea) SetText

func (this *TextArea) SetText(s string)

SetText replaces the entire buffer. The caret moves to the end and the selection collapses, matching QPlainTextEdit semantics. Fires SigTextChanged if installed. A subsequent Layout/Update is not strictly required — the next Draw picks up the new lines.

func (*TextArea) SigTextChanged

func (this *TextArea) SigTextChanged(fn func(interface{}, string))

SigTextChanged registers the callback fired on every mutation that changes Text(). Matches Edit.SigTextChanged: (sender, newText).

func (*TextArea) SizeHints

func (this *TextArea) SizeHints() SizeHints

func (*TextArea) Text

func (this *TextArea) Text() string

Text returns the full buffer joined with "\n". Mirrors QPlainTextEdit :: toPlainText.

type TextBlock

type TextBlock struct {
	// contains filtered or unexported fields
}

抽象的多行文本块 支持自动折行等操作

func (*TextBlock) Font

func (this *TextBlock) Font() paint.Font

func (*TextBlock) Layout

func (this *TextBlock) Layout(w float64)

func (*TextBlock) MultiLine

func (this *TextBlock) MultiLine() bool

func (*TextBlock) PointToPos

func (this *TextBlock) PointToPos(x, y float64) int

func (*TextBlock) PosToPoint

func (this *TextBlock) PosToPoint(pos int) (x, y float64)

func (*TextBlock) PosToRowCol

func (this *TextBlock) PosToRowCol(pos int) (r, c int)

func (*TextBlock) Replace

func (this *TextBlock) Replace(begin, end int, s string) (caret int, old string)

func (*TextBlock) RowColToPos

func (this *TextBlock) RowColToPos(r, c int) (pos int)

func (*TextBlock) RowHeight

func (this *TextBlock) RowHeight() float64

func (*TextBlock) RunesCount

func (this *TextBlock) RunesCount() int

func (*TextBlock) SetFont

func (this *TextBlock) SetFont(font paint.Font)

func (*TextBlock) SetMultiLine

func (this *TextBlock) SetMultiLine(b bool)

func (*TextBlock) SetText

func (this *TextBlock) SetText(s string)

func (*TextBlock) SetWrap

func (this *TextBlock) SetWrap(b bool)

func (*TextBlock) SoftRowsCount

func (this *TextBlock) SoftRowsCount() int

func (*TextBlock) String

func (this *TextBlock) String() string

func (*TextBlock) Text

func (this *TextBlock) Text() string

func (*TextBlock) Warp

func (this *TextBlock) Warp() bool

type TextStyle

type TextStyle struct {
	// contains filtered or unexported fields
}

文本格式, 支持高级文本编辑(未使用)

func CachedTextStyle

func CachedTextStyle(font paint.Font, color paint.Color) *TextStyle

func (*TextStyle) Access

func (p *TextStyle) Access()

type ThemeMode

type ThemeMode int

ThemeMode represents the current color scheme.

const (
	ThemeLight ThemeMode = iota
	ThemeDark
)

func CurrentThemeMode

func CurrentThemeMode() ThemeMode

CurrentThemeMode returns the active theme mode.

type Thermometer

type Thermometer struct {
	Widget
	// contains filtered or unexported fields
}

Thermometer draws a bulb and a column whose fill height maps Value across [Min,Max].

func NewThermometer

func NewThermometer() *Thermometer

NewThermometer creates a 0..100 thermometer reading Min.

func (*Thermometer) Color

func (this *Thermometer) Color() paint.Color

Color returns the mercury color.

func (*Thermometer) Draw

func (this *Thermometer) Draw(g paint.Painter)

func (*Thermometer) EnumProperties

func (this *Thermometer) EnumProperties(list core.IPropertyList)

func (*Thermometer) Fraction

func (this *Thermometer) Fraction() float64

Fraction returns the fill fraction of the current value over the range.

func (*Thermometer) Init

func (this *Thermometer) Init(self IWidget)

Init carries the range and the mercury color, not NewThermometer: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A 0..0 range clamps every SetValue to 0 and makes Fraction() return 0, so the column never fills.

func (*Thermometer) Max

func (this *Thermometer) Max() float64

Max returns the range maximum.

func (*Thermometer) Min

func (this *Thermometer) Min() float64

Min returns the range minimum.

func (*Thermometer) SetColor

func (this *Thermometer) SetColor(c paint.Color)

SetColor sets the mercury color.

func (*Thermometer) SetMax

func (this *Thermometer) SetMax(v float64)

SetMax sets the range maximum.

func (*Thermometer) SetMin

func (this *Thermometer) SetMin(v float64)

SetMin sets the range minimum.

func (*Thermometer) SetRange

func (this *Thermometer) SetRange(min, max float64)

SetRange sets the engineering range.

func (*Thermometer) SetTagName

func (this *Thermometer) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*Thermometer) SetValue

func (this *Thermometer) SetValue(v float64)

SetValue sets the temperature reading, clamped to [Min,Max].

func (*Thermometer) SizeHints

func (this *Thermometer) SizeHints() SizeHints

func (*Thermometer) TagName

func (this *Thermometer) TagName() string

TagName returns the design-time tag name.

func (*Thermometer) Value

func (this *Thermometer) Value() float64

Value returns the temperature reading.

type TimePicker

type TimePicker struct {
	Widget
	// contains filtered or unexported fields
}

TimePicker is a compact hours:minutes (optionally :seconds) time selector with per-field up/down steppers, modelled on Qt's QTimeEdit. The value is three plain ints (hour 0-23, minute 0-59, second 0-59) rather than a full time.Time, since only the clock part matters here.

Each field renders as a small box reading "HH" / "MM" (/ "SS") with a pair of stepper arrows on its right edge. The currently focused field gets an accent ring. Interaction mirrors QTimeEdit:

  • Clicking a field focuses it; clicking that field's up/down arrow steps it by one with wraparound.
  • Up/Down step the focused field; Left/Right move focus between fields.
  • The mouse wheel steps whichever field sits under the cursor.

Wraparound rule: each field wraps within its own range and does NOT carry into the next field (minute 59→00 leaves the hour untouched), matching the simplest QTimeEdit-style per-section spin.

Usage:

tp := gui.NewTimePicker()
tp.SigTimeChanged(func(h, m, s int) { label.SetText(fmt.Sprintf("%02d:%02d", h, m)) })

TimePicker pairs with Calendar/DatePicker to cover the clock side of a date-time selection.

func NewTimePicker

func NewTimePicker() *TimePicker

NewTimePicker creates a TimePicker initialised to the current local wall-clock time (hours:minutes), with the seconds field hidden. The hour field starts focused.

func (*TimePicker) Draw

func (this *TimePicker) Draw(g paint.Painter)

func (*TimePicker) EnumProperties

func (this *TimePicker) EnumProperties(list core.IPropertyList)

func (*TimePicker) Hour

func (this *TimePicker) Hour() int

Hour returns the selected hour (0-23).

func (*TimePicker) Init

func (this *TimePicker) Init(self IWidget)

func (*TimePicker) Minute

func (this *TimePicker) Minute() int

Minute returns the selected minute (0-59).

func (*TimePicker) OnKeyDown

func (this *TimePicker) OnKeyDown(key int, repeat bool)

OnKeyDown gives QTimeEdit-style keyboard control while focused: Up/Down step the focused field with wraparound, Left/Right move focus between fields.

func (*TimePicker) OnLeftDown

func (this *TimePicker) OnLeftDown(x, y float64)

func (*TimePicker) OnMouseLeave

func (this *TimePicker) OnMouseLeave()

func (*TimePicker) OnMouseMove

func (this *TimePicker) OnMouseMove(x, y float64)

func (*TimePicker) OnMouseWheel

func (this *TimePicker) OnMouseWheel(x, y, z float64)

func (*TimePicker) Second

func (this *TimePicker) Second() int

Second returns the selected second (0-59).

func (*TimePicker) SetShowSeconds

func (this *TimePicker) SetShowSeconds(show bool)

SetShowSeconds toggles the seconds field. Hiding it keeps the stored second value; it simply stops rendering and stops being a focus target. When the seconds field is hidden while focused, focus falls back to the minute.

func (*TimePicker) SetTime

func (this *TimePicker) SetTime(h, m, s int)

SetTime sets the time, normalising each field into its valid range by wrapping (euclidean modulo): SetTime(25, 70, 0) becomes 01:10:00. Negative values wrap too, so SetTime(-1, 0, 0) is 23:00:00. Fires SigTimeChanged only when the normalised value actually differs from the current one.

func (*TimePicker) ShowSeconds

func (this *TimePicker) ShowSeconds() bool

ShowSeconds reports whether the seconds field is shown.

func (*TimePicker) SigTimeChanged

func (this *TimePicker) SigTimeChanged(fn func(h, m, s int))

SigTimeChanged registers the callback fired when the time changes through a real edit (stepper click, wheel, or key). Programmatic SetTime that lands on a different value fires it too; a no-op SetTime does not.

func (*TimePicker) SizeHints

func (this *TimePicker) SizeHints() SizeHints

type Timeline

type Timeline struct {
	Widget
	// contains filtered or unexported fields
}

Timeline displays a vertical or horizontal sequence of steps/events.

func NewTimeline

func NewTimeline() *Timeline

func (*Timeline) AddItem

func (this *Timeline) AddItem(title, subtitle string, status int)

func (*Timeline) Draw

func (this *Timeline) Draw(g paint.Painter)

func (*Timeline) EnumProperties

func (this *Timeline) EnumProperties(list core.IPropertyList)

func (*Timeline) Init

func (this *Timeline) Init(self IWidget)

Init carries the orientation, not NewTimeline: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A factory timeline would otherwise lay its steps out horizontally while its SizeHints ask for a tall vertical box.

func (*Timeline) IsVertical

func (this *Timeline) IsVertical() bool

func (*Timeline) Items

func (this *Timeline) Items() []TimelineItem

func (*Timeline) SetItems

func (this *Timeline) SetItems(items []TimelineItem)

func (*Timeline) SetStatus

func (this *Timeline) SetStatus(idx, status int)

func (*Timeline) SetVertical

func (this *Timeline) SetVertical(b bool)

func (*Timeline) SizeHints

func (this *Timeline) SizeHints() SizeHints

type TimelineItem

type TimelineItem struct {
	Title    string
	Subtitle string
	Status   int // 0=pending, 1=active, 2=done
}

TimelineItem represents a single step/event on the timeline.

type Timer

type Timer uintptr

Timer is a low-precision timer for the UI thread

func (*Timer) Start

func (t *Timer) Start(millisecond uint32, f func()) bool

func (*Timer) Stop

func (t *Timer) Stop()

type ToastLevel

type ToastLevel int

ToastLevel represents the severity level of a toast notification.

const (
	ToastInfo    ToastLevel = iota // Blue
	ToastSuccess                   // Green
	ToastWarning                   // Amber
	ToastError                     // Red
)

type ToastManager

type ToastManager struct {
	// contains filtered or unexported fields
}

ToastManager manages active toast notifications. It is a global singleton.

func GetToastManager

func GetToastManager() *ToastManager

GetToastManager returns the global toast manager singleton.

type ToggleSwitch

type ToggleSwitch struct {
	Widget
	// contains filtered or unexported fields
}

ToggleSwitch 开关控件,iOS 风格的滑动开关

func NewToggleSwitch

func NewToggleSwitch() *ToggleSwitch

func (*ToggleSwitch) Draw

func (this *ToggleSwitch) Draw(g paint.Painter)

func (*ToggleSwitch) EnumProperties

func (this *ToggleSwitch) EnumProperties(list core.IPropertyList)

func (*ToggleSwitch) IsChecked

func (this *ToggleSwitch) IsChecked() bool

func (*ToggleSwitch) IsEnabled

func (this *ToggleSwitch) IsEnabled() bool

func (*ToggleSwitch) OnKeyDown

func (this *ToggleSwitch) OnKeyDown(key int, repeat bool)

OnKeyDown implements IEventKeyDown, giving the switch Qt-style keyboard control while it holds focus. Space (and Enter, for convenience) flips the state like a click; Left forces it OFF and Right forces it ON (the Qt switch direction convention). All paths route through Toggle so the change callback fires exactly as a click does, and the explicit Left/Right cases only toggle when the state actually changes, so re-asserting the current state is a no-op with no spurious callback. Guarded on IsEnabled so a disabled switch ignores keys.

func (*ToggleSwitch) OnLeftDown

func (this *ToggleSwitch) OnLeftDown(x, y float64)

func (*ToggleSwitch) OnLeftUp

func (this *ToggleSwitch) OnLeftUp(x, y float64)

func (*ToggleSwitch) OnMouseEnter

func (this *ToggleSwitch) OnMouseEnter()

func (*ToggleSwitch) OnMouseLeave

func (this *ToggleSwitch) OnMouseLeave()

func (*ToggleSwitch) SetChecked

func (this *ToggleSwitch) SetChecked(b bool)

func (*ToggleSwitch) SetEnabled

func (this *ToggleSwitch) SetEnabled(b bool)

func (*ToggleSwitch) SetText

func (this *ToggleSwitch) SetText(s string)

func (*ToggleSwitch) SigToggle

func (this *ToggleSwitch) SigToggle(fn func(bool))

func (*ToggleSwitch) SizeHints

func (this *ToggleSwitch) SizeHints() SizeHints

func (*ToggleSwitch) Text

func (this *ToggleSwitch) Text() string

func (*ToggleSwitch) Toggle

func (this *ToggleSwitch) Toggle()

type ToolBar

type ToolBar struct {
	Widget
	// contains filtered or unexported fields
}

ToolBar is a horizontal or vertical bar for tool buttons, separators, and arbitrary widgets. Similar to QToolBar.

func NewToolBar

func NewToolBar() *ToolBar

func (*ToolBar) AddAction

func (this *ToolBar) AddAction(text string, icon paint.Icon, callback func()) *Button

AddAction creates a tool button and appends it to the toolbar.

func (*ToolBar) AddActionButton

func (this *ToolBar) AddActionButton(a IAction) *Button

AddActionButton adds an existing action as a tool button.

func (*ToolBar) AddSeparator

func (this *ToolBar) AddSeparator() *Separator

AddSeparator inserts a visual separator into the toolbar.

func (*ToolBar) AddWidget

func (this *ToolBar) AddWidget(iw IWidget)

AddWidget appends any widget (e.g. ComboBox, Edit) to the toolbar.

func (*ToolBar) Draw

func (this *ToolBar) Draw(g paint.Painter)

func (*ToolBar) EnumProperties

func (this *ToolBar) EnumProperties(list core.IPropertyList)

func (*ToolBar) IconSize

func (this *ToolBar) IconSize() int

func (*ToolBar) Init

func (this *ToolBar) Init(self IWidget)

Init carries the icon size and spacing, not NewToolBar: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Icon buttons are sized from iconSize, so a factory toolbar shrinks them to the button margins alone.

func (*ToolBar) IsVertical

func (this *ToolBar) IsVertical() bool

func (*ToolBar) Items

func (this *ToolBar) Items() []IWidget

Items returns all items in the toolbar.

func (*ToolBar) Layout

func (this *ToolBar) Layout()

Layout arranges children horizontally or vertically.

func (*ToolBar) OnIdle

func (this *ToolBar) OnIdle()

func (*ToolBar) Orientation

func (this *ToolBar) Orientation() int

func (*ToolBar) OverflowItems

func (this *ToolBar) OverflowItems() []IWidget

OverflowItems returns the items the last horizontal layout could not fit, in their original order. They are hidden and reachable through the chevron.

func (*ToolBar) RemoveWidget

func (this *ToolBar) RemoveWidget(iw IWidget)

RemoveWidget removes a widget from the toolbar.

func (*ToolBar) SetIconSize

func (this *ToolBar) SetIconSize(size int)

func (*ToolBar) SetOrientation

func (this *ToolBar) SetOrientation(o int)

func (*ToolBar) SetSpacing

func (this *ToolBar) SetSpacing(s float64)

func (*ToolBar) SizeHints

func (this *ToolBar) SizeHints() SizeHints

func (*ToolBar) Spacing

func (this *ToolBar) Spacing() float64

type ToolViewDef

type ToolViewDef struct {
	// 视图的标识
	// 应和对象工厂名相同, 底层根据此字段调用对象工厂创建对象
	Id string
	// 视图的名称
	Name string
	// 视图的图标
	Icon string
	// 视图的描述
	Desc string
}

工具视图定义

func GetToolViewDef

func GetToolViewDef(typ string) (ToolViewDef, bool)

type TreeView

type TreeView struct {
	GuiView
	// contains filtered or unexported fields
}

支持模型-视图机制的树形视图

func NewTreeView

func NewTreeView() *TreeView

func (*TreeView) CheckState

func (this *TreeView) CheckState(mi ModelIndex) int

CheckState 返回一行的勾选状态: TVC_CHECKED / TVC_PARTIAL / TVC_UNCHECKED.

func (*TreeView) CheckedIndexes

func (this *TreeView) CheckedIndexes() []ModelIndex

CheckedIndexes 按可见顺序返回所有完全勾选的行的模型索引, 部分勾选的不算.

func (*TreeView) Close

func (this *TreeView) Close()

func (*TreeView) ColCount

func (this *TreeView) ColCount() int

func (*TreeView) Collapse

func (this *TreeView) Collapse(mi ModelIndex)

func (*TreeView) CurrentIndex

func (this *TreeView) CurrentIndex() ModelIndex

CurrentIndex 返回当前行第0列的模型索引, 无当前行时返回空索引.

func (*TreeView) CurrentRow

func (this *TreeView) CurrentRow() int

CurrentRow 返回当前行在可见行列表里的下标, -1表示无当前行.

func (*TreeView) Draw

func (this *TreeView) Draw(g paint.Painter)

func (*TreeView) EnumProperties

func (this *TreeView) EnumProperties(list core.IPropertyList)

func (*TreeView) Expand

func (this *TreeView) Expand(mi ModelIndex)

func (*TreeView) ExpandAll

func (this *TreeView) ExpandAll(depth int)

func (*TreeView) Icon

func (this *TreeView) Icon() paint.Icon

func (*TreeView) Init

func (this *TreeView) Init(iw IWidget)

func (*TreeView) IsCheckBoxVisible

func (this *TreeView) IsCheckBoxVisible() bool

IsCheckBoxVisible 第0列是否显示复选框.

func (*TreeView) Layout

func (this *TreeView) Layout()

func (*TreeView) MapFromScrolled

func (this *TreeView) MapFromScrolled(x, y float64) (x1, y1 float64)

func (*TreeView) MapToScrolled

func (this *TreeView) MapToScrolled(x, y float64) (x1, y1 float64)

func (*TreeView) Model

func (this *TreeView) Model() IGuiModel

func (*TreeView) OnBeginReset

func (this *TreeView) OnBeginReset()

func (*TreeView) OnEndReset

func (this *TreeView) OnEndReset()

func (*TreeView) OnHorzScroll

func (this *TreeView) OnHorzScroll(sender IWidget)

func (*TreeView) OnKeyDown

func (this *TreeView) OnKeyDown(key int, repeat bool)

键盘导航 (仿Qt QTreeView):

上/下   : 在可见行间上移/下移当前行, 到头/到尾时夹住
右       : 折叠且有子节点 -> 展开; 已展开 -> 移到第一个子节点; 无子节点 -> 无操作
左       : 已展开 -> 折叠; 否则 -> 移到父节点(若有)
回车     : 激活当前行
空格     : 显示复选框且当前行可勾选时翻转勾选, 否则激活当前行
Home/End : 跳到第一/最后一个可见行

func (*TreeView) OnLeftDown

func (this *TreeView) OnLeftDown(x, y float64)

func (*TreeView) OnMouseWheel

func (this *TreeView) OnMouseWheel(x, y, z float64)

func (*TreeView) RootIndent

func (this *TreeView) RootIndent() (indent bool)

func (*TreeView) RowCount

func (this *TreeView) RowCount() int

func (*TreeView) ScrollPosPx

func (this *TreeView) ScrollPosPx() (x, y float64)

func (*TreeView) ScrollXPx

func (this *TreeView) ScrollXPx() float64

func (*TreeView) ScrollYPx

func (this *TreeView) ScrollYPx() float64

func (*TreeView) SetActivatedCallback

func (this *TreeView) SetActivatedCallback(cb func(o interface{}, mi ModelIndex))

SetActivatedCallback 设置当前行被激活(回车/空格/点击内容区)时的回调.

func (*TreeView) SetCheckBoxVisible

func (this *TreeView) SetCheckBoxVisible(b bool)

SetCheckBoxVisible 显示/隐藏第0列的复选框. 复选框带占的是列内已有的位置, 不改变列宽和滚动条, 所以重画即可.

func (*TreeView) SetCheckState

func (this *TreeView) SetCheckState(mi ModelIndex, state int)

SetCheckState 勾选/取消勾选一行: 整棵子树跟着变, 再自下而上重算各级父节点. TVC_PARTIAL是推导出来的中间态, 传进来时什么也不做. 这是程序接口, 不受ItemIsUserCheckable限制 -- 那个标志只挡鼠标和空格.

func (*TreeView) SetCurrentRow

func (this *TreeView) SetCurrentRow(r int)

SetCurrentRow 以可见行下标设置当前行.

func (*TreeView) SetIcon

func (this *TreeView) SetIcon(icon paint.Icon)

func (*TreeView) SetModel

func (this *TreeView) SetModel(m IGuiModel)

func (*TreeView) SetRootIndent

func (this *TreeView) SetRootIndent(indent bool)

func (*TreeView) SetTitle

func (this *TreeView) SetTitle(s string)

func (*TreeView) Title

func (this *TreeView) Title() string

func (*TreeView) VisibleColRange

func (this *TreeView) VisibleColRange() (col0, col1 int)

[row0, row1)

func (*TreeView) VisibleRowRange

func (this *TreeView) VisibleRowRange() (row0, row1 int)

[row0, row1)

type TreeViewRow

type TreeViewRow struct {
	// contains filtered or unexported fields
}

type TrendPanel

type TrendPanel struct {
	Widget
	// contains filtered or unexported fields
}

TrendPanel is a historical-trend playback control bar sitting above a live LineChart, for SCADA / 组态 trend screens. The panel OWNS the chart: it creates a *LineChart, parents it, and lays it out in the area below the control bar. The host feeds samples through Chart() (Chart().EnableRolling / Chart().AddSample) and reacts to the operator's playback intents through the Sig* callbacks.

It is deliberately backend-free. The panel holds only plain view-model state (playing / live flags and the selected range index) and never imports the historian / playback packages that actually seek, buffer or replay samples. A click on a control mutates the local flag and fires the matching Sig callback; the host wires that intent to its historian/playback backend and drives the chart. This keeps gui light and the panel GL-free testable.

func NewTrendPanel

func NewTrendPanel() *TrendPanel

NewTrendPanel creates a trend panel with an owned, ready-to-feed LineChart.

func (*TrendPanel) Chart

func (this *TrendPanel) Chart() *LineChart

Chart returns the owned LineChart so the host can feed it samples via the chart's existing EnableRolling / AddSample API.

func (*TrendPanel) Draw

func (this *TrendPanel) Draw(g paint.Painter)

Draw paints the control bar (buttons + active states) using theme colours; the owned LineChart draws itself as a child.

func (*TrendPanel) Init

func (this *TrendPanel) Init(self IWidget)

func (*TrendPanel) IsLive

func (this *TrendPanel) IsLive() bool

IsLive reports whether the panel is in live (实时) mode; false is history (历史).

func (*TrendPanel) IsPlaying

func (this *TrendPanel) IsPlaying() bool

IsPlaying reports whether the panel is in the playing state.

func (*TrendPanel) Layout

func (this *TrendPanel) Layout()

Layout keeps the chart filling the panel below the control bar. Called on every resize via Widget.OnResize -> ILayout.

func (*TrendPanel) OnLeftDown

func (this *TrendPanel) OnLeftDown(x, y float64)

OnLeftDown routes a click to the control under it: play/pause update the playing flag, the mode toggle flips live, a range label selects a window. Each fires its matching Sig callback with the current intent. Clicks below the control bar fall on the chart, which handles its own input.

func (*TrendPanel) SigModeChanged

func (this *TrendPanel) SigModeChanged(fn func(live bool))

SigModeChanged registers the callback fired when the operator toggles the 实时/历史 mode. It receives the new live state.

func (*TrendPanel) SigPause

func (this *TrendPanel) SigPause(fn func())

SigPause registers the callback fired when the operator clicks 暂停.

func (*TrendPanel) SigPlay

func (this *TrendPanel) SigPlay(fn func())

SigPlay registers the callback fired when the operator clicks 播放.

func (*TrendPanel) SigRange

func (this *TrendPanel) SigRange(fn func(d time.Duration))

SigRange registers the callback fired when the operator picks a time range. It receives the chosen trailing window duration.

func (*TrendPanel) SizeHints

func (this *TrendPanel) SizeHints() SizeHints

type UndoStack

type UndoStack struct {
	// contains filtered or unexported fields
}

支持撤销恢复的命令堆栈

func NewUndoStack

func NewUndoStack(name string) *UndoStack

func (*UndoStack) CanRedo

func (this *UndoStack) CanRedo() bool

func (*UndoStack) CanUndo

func (this *UndoStack) CanUndo() bool

func (*UndoStack) Clear

func (this *UndoStack) Clear()

func (*UndoStack) Command

func (this *UndoStack) Command(index int) ICommand

func (*UndoStack) Count

func (this *UndoStack) Count() int

func (*UndoStack) Current

func (this *UndoStack) Current() int

func (*UndoStack) IsClean

func (this *UndoStack) IsClean() bool

func (*UndoStack) Push

func (this *UndoStack) Push(cmd ICommand)

func (*UndoStack) Redo

func (this *UndoStack) Redo()

func (*UndoStack) RedoAction

func (this *UndoStack) RedoAction() IAction

func (*UndoStack) RedoText

func (this *UndoStack) RedoText() string

func (*UndoStack) SetClean

func (this *UndoStack) SetClean()

func (*UndoStack) Undo

func (this *UndoStack) Undo()

func (*UndoStack) UndoAction

func (this *UndoStack) UndoAction() IAction

func (*UndoStack) UndoText

func (this *UndoStack) UndoText() string

type VBox

type VBox struct {
	Widget
	// contains filtered or unexported fields
}

VBox is a layout container that stacks children vertically. Supports stretch weights, alignment, minimum sizes, and hidden-widget skipping.

func NewVBox

func NewVBox() *VBox

func (*VBox) AddWidget

func (this *VBox) AddWidget(iw IWidget)

func (*VBox) Draw

func (this *VBox) Draw(g paint.Painter)

func (*VBox) EnumProperties

func (this *VBox) EnumProperties(list core.IPropertyList)

func (*VBox) HAlign

func (this *VBox) HAlign() TextAlign

func (*VBox) Layout

func (this *VBox) Layout()

func (*VBox) SetHAlign

func (this *VBox) SetHAlign(a TextAlign)

func (*VBox) SetPadding

func (this *VBox) SetPadding(p Padding)

func (*VBox) SetSpacing

func (this *VBox) SetSpacing(s float64)

func (*VBox) SizeHints

func (this *VBox) SizeHints() SizeHints

func (*VBox) Spacing

func (this *VBox) Spacing() float64

type Validator

type Validator interface {
	Validate(input string) State
}

Validator classifies an input string into one of the three states above. Implementations are stateless w.r.t. the input — Validate must not mutate the receiver based on the call. This lets a single Validator instance be safely shared by multiple Edit widgets, mirroring Qt's expectation.

type ValidatorFunc

type ValidatorFunc func(input string) error

--- ValidatorFunc --------------------------------------------------

ValidatorFunc adapts an ordinary func(string) error into a Validator so callers can express one-off rules ("must contain @", "must equal the confirm-password field") without declaring a type. A nil error is Acceptable; a non-nil error is Intermediate — NOT Invalid — so a partial value the user is still typing is never keystroke-dropped: the func only gates submission and drives the error border. The error's text becomes the ValidationError message.

func (ValidatorFunc) ErrorMessage

func (f ValidatorFunc) ErrorMessage(input string) string

ErrorMessage runs the wrapped func and returns its error text, or "" when the func is satisfied.

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(input string) State

Validate runs the wrapped func: nil error → Acceptable, else Intermediate.

type ValueBar

type ValueBar struct {
	Widget
	// contains filtered or unexported fields
}

ValueBar draws a vertical bar filled to Value over [Min,Max]. The fill color is chosen from the LoLo / Lo / Hi / HiHi alarm bands the value falls into.

func NewValueBar

func NewValueBar() *ValueBar

NewValueBar creates a 0..100 bar reading 0.

func (*ValueBar) Draw

func (this *ValueBar) Draw(g paint.Painter)

func (*ValueBar) EnumProperties

func (this *ValueBar) EnumProperties(list core.IPropertyList)

func (*ValueBar) Fraction

func (this *ValueBar) Fraction() float64

Fraction returns the fill fraction of the current value over the range.

func (*ValueBar) Hi

func (this *ValueBar) Hi() float64

Hi returns the high limit.

func (*ValueBar) HiHi

func (this *ValueBar) HiHi() float64

HiHi returns the high-high limit.

func (*ValueBar) Init

func (this *ValueBar) Init(self IWidget)

Init carries the range and the band colors, not NewValueBar: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. A 0..0 range clamps every SetValue to 0 and makes Fraction() return 0, so the bar never leaves the floor and the alarm bands are drawn in a fully transparent color.

func (*ValueBar) Lo

func (this *ValueBar) Lo() float64

Lo returns the low limit.

func (*ValueBar) LoLo

func (this *ValueBar) LoLo() float64

LoLo returns the low-low limit.

func (*ValueBar) Max

func (this *ValueBar) Max() float64

Max returns the range maximum.

func (*ValueBar) Min

func (this *ValueBar) Min() float64

Min returns the range minimum.

func (*ValueBar) SetLimits

func (this *ValueBar) SetLimits(loLo, lo, hi, hiHi float64)

SetLimits enables the LoLo/Lo/Hi/HiHi alarm bands.

func (*ValueBar) SetMax

func (this *ValueBar) SetMax(v float64)

SetMax sets the range maximum.

func (*ValueBar) SetMin

func (this *ValueBar) SetMin(v float64)

SetMin sets the range minimum.

func (*ValueBar) SetRange

func (this *ValueBar) SetRange(min, max float64)

SetRange sets the engineering range.

func (*ValueBar) SetTagName

func (this *ValueBar) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*ValueBar) SetValue

func (this *ValueBar) SetValue(v float64)

SetValue sets the bar value, clamped to [Min,Max].

func (*ValueBar) SizeHints

func (this *ValueBar) SizeHints() SizeHints

func (*ValueBar) TagName

func (this *ValueBar) TagName() string

TagName returns the design-time tag name.

func (*ValueBar) Value

func (this *ValueBar) Value() float64

Value returns the bar value.

type Valve

type Valve struct {
	Widget
	// contains filtered or unexported fields
}

Valve draws the classic bow-tie valve symbol, colored by open/closed state.

func NewValve

func NewValve() *Valve

NewValve creates a closed valve.

func (*Valve) ClosedColor

func (this *Valve) ClosedColor() paint.Color

ClosedColor returns the closed-state color.

func (*Valve) Draw

func (this *Valve) Draw(g paint.Painter)

func (*Valve) EnumProperties

func (this *Valve) EnumProperties(list core.IPropertyList)

func (*Valve) Init

func (this *Valve) Init(self IWidget)

Init carries the open / closed colours (see the file note on factory construction).

func (*Valve) OpenColor

func (this *Valve) OpenColor() paint.Color

OpenColor returns the open-state color.

func (*Valve) SetClosedColor

func (this *Valve) SetClosedColor(c paint.Color)

SetClosedColor sets the closed-state color.

func (*Valve) SetOpenColor

func (this *Valve) SetOpenColor(c paint.Color)

SetOpenColor sets the open-state color.

func (*Valve) SetState

func (this *Valve) SetState(open bool)

SetState sets the valve open (true) or closed (false).

func (*Valve) SetTagName

func (this *Valve) SetTagName(s string)

SetTagName sets the design-time tag name that drives this widget.

func (*Valve) SizeHints

func (this *Valve) SizeHints() SizeHints

func (*Valve) State

func (this *Valve) State() bool

State reports whether the valve is open.

func (*Valve) TagName

func (this *Valve) TagName() string

TagName returns the design-time tag name.

func (*Valve) Toggle

func (this *Valve) Toggle()

Toggle flips the valve state.

type VertAlign

type VertAlign int
const (
	VA_TOP VertAlign = iota
	VA_CENTER
	VA_BOTTOM
)

type Vertical

type Vertical interface {
	IsVertical() bool
	SetVertical(b bool)
}

type VerticalT

type VerticalT bool

func (VerticalT) IsVertical

func (v VerticalT) IsVertical() bool

func (*VerticalT) SetVertical

func (v *VerticalT) SetVertical(b bool)

type VirtualList

type VirtualList struct {
	Widget
	// contains filtered or unexported fields
}

VirtualList is a virtualized scrolling list — only the rows currently inside the visible viewport are drawn, regardless of itemCount. This keeps draw cost O(viewport_height / itemHeight) instead of O(itemCount), making the widget usable for millions of rows where ListWidget would stall.

Rows have a fixed itemHeight. Drawing of each row is delegated to a caller- provided drawItemFn, so the widget itself is data-source-agnostic.

func NewVirtualList

func NewVirtualList() *VirtualList

NewVirtualList returns a VirtualList with itemHeight=28 and no items. Call SetItemCount, SetItemHeight, and SetItemDrawer to configure it.

func (*VirtualList) Draw

func (this *VirtualList) Draw(g paint.Painter)

func (*VirtualList) EnumProperties

func (this *VirtualList) EnumProperties(list core.IPropertyList)

func (*VirtualList) Init

func (this *VirtualList) Init(self IWidget)

Init carries the row height and the sentinels, not NewVirtualList: the designer and the .tdoc loader build widgets through the core factory, which reflects on Init and never sees the constructor. Draw and hitTest both bail out on itemHeight <= 0, so a factory list stays permanently blank however many items it is given.

func (*VirtualList) ItemCount

func (this *VirtualList) ItemCount() int

ItemCount returns the configured item count.

func (*VirtualList) ItemHeight

func (this *VirtualList) ItemHeight() float64

ItemHeight returns the per-row height in pixels.

func (*VirtualList) OnLeftDown

func (this *VirtualList) OnLeftDown(x, y float64)

func (*VirtualList) OnMouseLeave

func (this *VirtualList) OnMouseLeave()

func (*VirtualList) OnMouseMove

func (this *VirtualList) OnMouseMove(x, y float64)

func (*VirtualList) OnMouseWheel

func (this *VirtualList) OnMouseWheel(x, y, z float64)

OnMouseWheel scrolls the list. z is the wheel delta in notches (positive = up). Each notch moves defaultWheelScrollLines rows.

func (*VirtualList) ScrollY

func (this *VirtualList) ScrollY() float64

ScrollY returns the current scroll offset (pixels from top).

func (*VirtualList) SelectedIndex

func (this *VirtualList) SelectedIndex() int

SelectedIndex returns the current selection, or -1 if none.

func (*VirtualList) SetBackgroundColor

func (this *VirtualList) SetBackgroundColor(c paint.Color)

SetBackgroundColor sets the optional background fill. Pass a zero-alpha color to disable.

func (*VirtualList) SetHoverColor

func (this *VirtualList) SetHoverColor(c paint.Color)

SetHoverColor sets the highlight color drawn under the hover row.

func (*VirtualList) SetItemCount

func (this *VirtualList) SetItemCount(n int)

SetItemCount sets the number of rows. Negative values are clamped to 0. The view is invalidated and scroll position is clamped.

func (*VirtualList) SetItemDrawer

func (this *VirtualList) SetItemDrawer(fn func(g paint.Painter, index int, x, y, w, h float64))

SetItemDrawer installs the function that paints a single row. The function receives a painter with origin at (0, 0) of the widget and the absolute row rectangle in widget-local coordinates.

func (*VirtualList) SetItemHeight

func (this *VirtualList) SetItemHeight(h float64)

SetItemHeight sets the per-row height. Values <= 0 are ignored.

func (*VirtualList) SetScrollY

func (this *VirtualList) SetScrollY(y float64)

SetScrollY scrolls the view to the given pixel offset, clamped to the valid range.

func (*VirtualList) SetSelectedColor

func (this *VirtualList) SetSelectedColor(c paint.Color)

SetSelectedColor sets the highlight color drawn under the selected row.

func (*VirtualList) SetSelectedIndex

func (this *VirtualList) SetSelectedIndex(i int)

SetSelectedIndex selects a row programmatically. Out-of-range values clear the selection.

func (*VirtualList) SigItemClick

func (this *VirtualList) SigItemClick(fn func(int))

SigItemClick registers the click callback. The index is in [0, itemCount).

func (*VirtualList) SizeHints

func (this *VirtualList) SizeHints() SizeHints

SizeHints returns a virtual size: width is a default 200, height is the total content height (itemCount * itemHeight). This is an O(1) computation so it's safe to call extremely frequently.

type VisualRow

type VisualRow struct {
	Line     int
	StartCol int
	EndCol   int
}

VisualRow is one on-screen row of a wrapped view: the source runes [StartCol, EndCol) of source line Line. The rows of a line partition that line exactly — no rune is dropped and none is duplicated — which is what makes SourceToVisual/VisualToSource lossless.

type Widget

type Widget struct {
	// contains filtered or unexported fields
}

func (*Widget) AttachWindow

func (this *Widget) AttachWindow(wt WindowType)

func (*Widget) Bounds

func (this *Widget) Bounds() (x, y, width, height float64)

func (*Widget) Bounds1

func (this *Widget) Bounds1() (rect geom.Rect)

func (*Widget) CheckAllAncestors

func (this *Widget) CheckAllAncestors(checkFunc func(IWidget) bool) bool

func (*Widget) CheckAnyAncestor

func (this *Widget) CheckAnyAncestor(checkFunc func(IWidget) bool) bool

func (*Widget) Children

func (this *Widget) Children() []IWidget

func (*Widget) Cursor

func (this *Widget) Cursor() *Cursor

func (*Widget) Detach

func (this *Widget) Detach()

func (*Widget) DetachWindow

func (this *Widget) DetachWindow()

func (*Widget) DoDragDrop

func (this *Widget) DoDragDrop(content paint.Pixmap, availableActions DndAction, data ...interface{}) DndAction

func (*Widget) Draw

func (this *Widget) Draw(g paint.Painter)

func (*Widget) ExportGv

func (this *Widget) ExportGv(g *gv.Graph)

func (*Widget) ExtraData

func (this *Widget) ExtraData() interface{}

func (*Widget) FindWidgetAt

func (this *Widget) FindWidgetAt(x, y float64) IWidget

func (*Widget) FocusPolicy

func (this *Widget) FocusPolicy() FocusPolicy

FocusPolicy 返回控件的 Tab 焦点策略. 零值 (AutoFocus) 表示按启发式判定: 控件可见、可用且实现了 IEventKeyDown 时即可被 Tab 聚焦. 见 focus.go.

func (*Widget) HasCapture

func (this *Widget) HasCapture() bool

func (*Widget) HasFocus

func (this *Widget) HasFocus() bool

func (*Widget) Height

func (this *Widget) Height() float64

func (*Widget) Hide

func (this *Widget) Hide()

func (*Widget) Init

func (this *Widget) Init(o IWidget)

func (*Widget) InvalidateLayout

func (this *Widget) InvalidateLayout()

InvalidateLayout requests a layout recalculation on this widget. If this widget implements ILayout, its Layout() is called immediately, then Update() is called to trigger a repaint.

func (*Widget) InvalidateParentLayout

func (this *Widget) InvalidateParentLayout()

InvalidateParentLayout requests the parent container to recalculate layout. This should be called when a child's size hints change.

func (*Widget) IsAllAncentorsVisible

func (this *Widget) IsAllAncentorsVisible() bool

func (*Widget) IsEnabled

func (this *Widget) IsEnabled() bool

func (*Widget) IsHover

func (this *Widget) IsHover() bool

func (*Widget) IsPopup

func (this *Widget) IsPopup() bool

func (*Widget) IsRedrawParent

func (this *Widget) IsRedrawParent() bool

func (*Widget) IsVisible

func (this *Widget) IsVisible() bool

func (*Widget) LazyAttachWindow

func (this *Widget) LazyAttachWindow(wt WindowType)

func (*Widget) MapFromGlobal

func (this *Widget) MapFromGlobal(x, y float64) (x1, y1 float64)

func (*Widget) MapFromWindow

func (this *Widget) MapFromWindow(x, y float64) (x1, y1 float64)

func (*Widget) MapToGlobal

func (this *Widget) MapToGlobal(x, y float64) (x1, y1 float64)

func (*Widget) MapToWindow

func (this *Widget) MapToWindow(x, y float64) (x1, y1 float64)

func (*Widget) NakedWidget

func (this *Widget) NakedWidget() *Widget

func (*Widget) OnFocusChanged

func (this *Widget) OnFocusChanged(newFocusWidget, oldFocusWidget IWidget)

func (*Widget) OnMove

func (this *Widget) OnMove()

func (*Widget) OnResize

func (this *Widget) OnResize()

func (*Widget) OwnerWindow

func (this *Widget) OwnerWindow() *Window

func (*Widget) Parent

func (this *Widget) Parent() IWidget

func (*Widget) PopCapture

func (this *Widget) PopCapture()

func (*Widget) Pos

func (this *Widget) Pos() (x, y float64)

func (*Widget) PushCapture

func (this *Widget) PushCapture()

func (*Widget) RootWidget

func (this *Widget) RootWidget() IWidget

func (*Widget) Self

func (this *Widget) Self() IWidget

func (*Widget) SetBounds

func (this *Widget) SetBounds(x, y, width, height float64)

func (*Widget) SetBounds1

func (this *Widget) SetBounds1(rect geom.Rect)

func (*Widget) SetEnabled

func (this *Widget) SetEnabled(b bool)

func (*Widget) SetExtraData

func (this *Widget) SetExtraData(a interface{})

func (*Widget) SetFocus

func (this *Widget) SetFocus()

func (*Widget) SetFocusPolicy

func (this *Widget) SetFocusPolicy(p FocusPolicy)

SetFocusPolicy 设置控件的 Tab 焦点策略. 例如纯展示控件可设为 NoFocus 以 排除出焦点链.

func (*Widget) SetHeight

func (this *Widget) SetHeight(h float64)

func (*Widget) SetParent

func (this *Widget) SetParent(parent IWidget)

func (*Widget) SetPos

func (this *Widget) SetPos(x, y float64)

func (*Widget) SetRedrawParent

func (this *Widget) SetRedrawParent(b bool)

func (*Widget) SetSize

func (this *Widget) SetSize(width, height float64)

func (*Widget) SetVisible

func (this *Widget) SetVisible(b bool)

func (*Widget) SetWidth

func (this *Widget) SetWidth(w float64)

func (*Widget) SetX

func (this *Widget) SetX(x float64)

func (*Widget) SetY

func (this *Widget) SetY(y float64)

func (*Widget) Show

func (this *Widget) Show()

func (*Widget) Size

func (this *Widget) Size() (width, height float64)

func (*Widget) SizeHints

func (this *Widget) SizeHints() SizeHints

func (*Widget) Update

func (this *Widget) Update()

func (*Widget) UpdateRect

func (this *Widget) UpdateRect(x, y, width, height float64)

func (*Widget) Width

func (this *Widget) Width() float64

func (*Widget) Window

func (this *Widget) Window() *Window

func (*Widget) WindowWidget

func (this *Widget) WindowWidget() IWidget

func (*Widget) X

func (this *Widget) X() float64

func (*Widget) Y

func (this *Widget) Y() float64

type WidgetStyle

type WidgetStyle struct {
	// 圆角
	BorderRadius float64

	// 内边距
	PaddingTop    float64
	PaddingRight  float64
	PaddingBottom float64
	PaddingLeft   float64

	// 字体大小覆盖 (0 = 使用主题默认)
	FontSize float64

	// 颜色覆盖 (A=0 表示不覆盖,使用主题)
	BackgroundColor paint.Color
	TextColor       paint.Color
	BorderColor     paint.Color

	// 阴影
	ShadowOffsetX float64
	ShadowOffsetY float64
	ShadowBlur    float64
	ShadowColor   paint.Color
}

WidgetStyle 控件级别的样式覆盖

func ButtonStyleDanger

func ButtonStyleDanger(scheme ColorScheme) WidgetStyle

ButtonStyleDanger returns a danger/destructive button style with error-colored background.

func ButtonStylePrimary

func ButtonStylePrimary(scheme ColorScheme) WidgetStyle

ButtonStyle 按钮样式预设

func ButtonStyleSecondary

func ButtonStyleSecondary(scheme ColorScheme) WidgetStyle

ButtonStyleSecondary returns a secondary button style with surface background and text-primary color.

func ButtonStyleSuccess

func ButtonStyleSuccess(scheme ColorScheme) WidgetStyle

ButtonStyleSuccess returns a success button style with green background.

func CardStyleDefault

func CardStyleDefault(scheme ColorScheme) WidgetStyle

CardStyle 卡片样式预设

func CardStyleElevated

func CardStyleElevated(scheme ColorScheme) WidgetStyle

CardStyleElevated returns an elevated card style with larger radius and no border, just shadow.

func InputStyleDefault

func InputStyleDefault(scheme ColorScheme) WidgetStyle

InputStyle 输入框样式预设 InputStyleDefault returns the default input field style with surface background and standard border.

func TagStyleError

func TagStyleError(scheme ColorScheme) WidgetStyle

TagStyleError returns a tag style with error-colored (red) background.

func TagStyleOutlined

func TagStyleOutlined(scheme ColorScheme) WidgetStyle

TagStyleOutlined returns a tag style with transparent background and primary-colored border.

func TagStylePrimary

func TagStylePrimary(scheme ColorScheme) WidgetStyle

TagStyle 标签样式预设

func TagStyleSuccess

func TagStyleSuccess(scheme ColorScheme) WidgetStyle

TagStyleSuccess returns a tag style with success-colored (green) background.

func TagStyleWarning

func TagStyleWarning(scheme ColorScheme) WidgetStyle

TagStyleWarning returns a tag style with warning-colored (amber) background.

type WinId

type WinId uintptr

func AnyWindowId

func AnyWindowId() (ret WinId)

type Window

type Window struct {
	// contains filtered or unexported fields
}

func AllWindows

func AllWindows() (list []*Window)

func FindTopWindow

func FindTopWindow(xg, yg float64) *Window

func (*Window) Bounds

func (this *Window) Bounds() (x, y, width, height float64)

func (*Window) Close

func (this *Window) Close()

func (*Window) DirtyList

func (this *Window) DirtyList() []string

func (*Window) DoDragDrop

func (this *Window) DoDragDrop(from interface{},
	content paint.Pixmap,
	availableActions DndAction,
	data ...interface{}) DndAction

DoDragDrop implements an interactive drag-and-drop loop for GLFW. It polls GLFW events and tracks the mouse to deliver drag enter/move/leave/drop events to widgets that implement IOnDrop, matching the Windows COM-based behavior.

func (*Window) EndModal

func (this *Window) EndModal(retParam interface{})

func (*Window) EnsureInDesktopArea

func (this *Window) EnsureInDesktopArea()

func (*Window) ExportGv

func (this *Window) ExportGv(g *gv.Graph)

func (*Window) FrameBounds

func (this *Window) FrameBounds() (x, y, w, h float64)

func (*Window) FrameBounds1

func (this *Window) FrameBounds1() geom.Rect

func (*Window) FrameMargin

func (this *Window) FrameMargin() (ret Padding)

func (*Window) IsActive

func (this *Window) IsActive() bool

func (*Window) IsEnabled

func (this *Window) IsEnabled() bool

func (*Window) IsMaximized

func (this *Window) IsMaximized() bool

func (*Window) IsMinimized

func (this *Window) IsMinimized() bool

func (*Window) IsValid

func (this *Window) IsValid() bool

func (*Window) IsVisible

func (this *Window) IsVisible() bool

func (*Window) MarkDirtyRect

func (this *Window) MarkDirtyRect(x, y, w, h float64)

MarkDirtyRect grows the pending dirty area by the given logical rect. Coalesces consecutive calls into a single bounding rect — there is at most one accumulated region per frame. If MarkFullDirty was called this frame the call is a no-op (the whole window is already going to repaint).

Coordinates are widget-local (the same coordinate system widget Bounds() uses). The paint pass converts to physical pixels via the content scale.

func (*Window) MarkFullDirty

func (this *Window) MarkFullDirty()

MarkFullDirty marks the entire window for redraw, discarding any accumulated partial dirty rect. Used when a global change (theme, resize, scroll) invalidates everything.

func (*Window) MoveToCenter

func (this *Window) MoveToCenter()

func (*Window) NakedWindow

func (this *Window) NakedWindow() *Window

func (*Window) Native

func (this *Window) Native() WinId

func (*Window) OnDestroy

func (this *Window) OnDestroy()

func (*Window) OnIdle

func (this *Window) OnIdle()

func (*Window) ParentWindow

func (this *Window) ParentWindow() *Window

func (*Window) Placement

func (this *Window) Placement() (ret WindowPlace)

func (*Window) Save

func (this *Window) Save() bool

func (*Window) SetBounds

func (this *Window) SetBounds(x, y, width, height float64)

func (*Window) SetCloseOnHide

func (this *Window) SetCloseOnHide(b bool)

func (*Window) SetEnabled

func (this *Window) SetEnabled(b bool)

func (*Window) SetFrameBounds

func (this *Window) SetFrameBounds(x, y, w, h float64)

func (*Window) SetFrameBounds1

func (this *Window) SetFrameBounds1(rect geom.Rect)

func (*Window) SetIcon

func (this *Window) SetIcon(icon paint.Icon)

func (*Window) SetMaximized

func (this *Window) SetMaximized(b bool)

func (*Window) SetMinimized

func (this *Window) SetMinimized(b bool)

func (*Window) SetPlacement

func (this *Window) SetPlacement(a WindowPlace)

func (*Window) SetPos

func (this *Window) SetPos(x, y float64)

func (*Window) SetSize

func (this *Window) SetSize(w, h float64)

func (*Window) SetTitle

func (this *Window) SetTitle(s string)

func (*Window) SetVisible

func (this *Window) SetVisible(b bool)

func (*Window) ShowModal

func (this *Window) ShowModal(cbOnShow func()) (retParam interface{})

func (*Window) Title

func (this *Window) Title() string

func (*Window) Update

func (this *Window) Update()

func (*Window) UpdateRect

func (this *Window) UpdateRect(x, y, width, height float64)

func (*Window) Widget

func (this *Window) Widget() IWidget

func (*Window) WindowType

func (this *Window) WindowType() WindowType

type WindowPlace

type WindowPlace struct {
	Monitor     string
	FrameBounds geom.Rect
	Maximized   bool
	Minimized   bool
	FullScreen  bool
}

type WindowType

type WindowType int
const (
	WtInherit WindowType = iota
	WtForm
	WtPopup
	WtChild
)

func (WindowType) String

func (wt WindowType) String() string

type WrapLayout

type WrapLayout struct {
	// contains filtered or unexported fields
}

WrapLayout is the wrap of a whole buffer: source lines in, visual rows out. Build cost is O(total runes) and the result is immutable, so rebuild it when the text or the wrap width changes. The layout keeps a reference to the lines slice it was given rather than copying it; feeding it a slice that is mutated afterwards yields stale rows (RowText degrades gracefully, it never panics).

func NewWrapLayout

func NewWrapLayout(lines []string, maxWidth float64, widthOf WrapWidthFunc) *WrapLayout

NewWrapLayout wraps lines so that no row exceeds maxWidth, measuring runes with widthOf (nil = one column per rune). A maxWidth <= 0 disables wrapping: every source line becomes exactly one visual row, which is the "wrap off" layout and lets a caller use the same mapping in both modes.

func (*WrapLayout) LineCount

func (this *WrapLayout) LineCount() int

LineCount is the number of source lines the layout was built from.

func (*WrapLayout) Row

func (this *WrapLayout) Row(i int) (VisualRow, bool)

Row returns the row at index i, or false when i is out of range.

func (*WrapLayout) RowCount

func (this *WrapLayout) RowCount() int

RowCount is the number of visual rows in the layout — the scrollable height of the wrapped view, in rows.

func (*WrapLayout) RowText

func (this *WrapLayout) RowText(row int) string

RowText returns the slice of source text drawn on a visual row, or "" when the row index is out of range.

func (*WrapLayout) RowsForLine

func (this *WrapLayout) RowsForLine(line int) (first, count int)

RowsForLine returns the index of a source line's first visual row and the number of rows it occupies. count is 0 when line is out of range.

func (*WrapLayout) SourceToVisual

func (this *WrapLayout) SourceToVisual(line, col int) (row, rowCol int)

SourceToVisual maps a source position — line index plus rune offset — to the visual row and the rune offset within that row. Out-of-range inputs are clamped into the buffer. A position that falls exactly on a wrap boundary is reported on the continuation row at offset 0, which is where a caret moving forward through the wrap lands.

func (*WrapLayout) VisualToSource

func (this *WrapLayout) VisualToSource(row, rowCol int) (line, col int)

VisualToSource maps a visual row plus a rune offset within it back to the source line and rune offset it stands for. Out-of-range inputs are clamped — an offset past the end of the row clamps to the row's end — so VisualToSource(SourceToVisual(line, col)) == (line, col) for every in-range source position.

type WrapWidthFunc

type WrapWidthFunc func(r rune) float64

WrapWidthFunc reports the display width of one rune, in the same unit as the max width handed to NewWrapLayout. Passing nil selects unitRuneWidth, which returns 1 for every rune — the max width is then a plain column count. A caller holding a real font can pass a metric-based function later without touching the wrap algorithm; a tab is just another rune to this function.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL