ui

package
v0.0.1-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ui предоставляет экспериментальные компоненты Golphi.

Конструкторы готовят логические объекты без загрузки native-библиотек или обращения к display. Импорт закрепляет startup thread для будущего Run. Принятый native MVP ограничен формой и статическим деревом Edit/Button/Label. Текущий логический API также поддерживает Panel и подготовку отсоединённых поддеревьев во время Run. Общее ядро реализует транзакции и события дерева; адаптеры GTK/Win32 реализуют этот протокол. Нативная интеграция проверяется на Linux/X11 и Windows 11; результаты и границы — в docs/archive/dynamic-tree/dynamic-tree-validation.md. Подробнее см. docs/ru/reference/components.md.

Index

Constants

This section is empty.

Variables

View Source
var ErrFileDialogUnsupported = errors.New("ui: native file dialogs are not supported by this backend")

ErrFileDialogUnsupported is returned when the active backend has no file chooser.

Functions

func Post

func Post(fn func()) error

Post ставит fn в очередь UI-потока из любой goroutine. nil означает только принятие: остановка может отменить ещё не начатую задачу. Вызов не выполняет fn непосредственно, даже с UI-потока; вложенные задачи идут в конец очереди. До готовности Run, после начала остановки и для fn == nil возвращается error.

Types

type Button

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

Button — кнопка.

func NewButton

func NewButton(owner Component) *Button

NewButton создаёт кнопку с владельцем, но без визуального Parent.

func (*Button) SetOnClick

func (b *Button) SetOnClick(handler func())

SetOnClick заменяет единственный обработчик кнопки; nil отключает событие.

func (*Button) SetText

func (c *Button) SetText(text string)

SetText задаёт текст контрола.

func (*Button) Text

func (c *Button) Text() string

Text возвращает подготовленный текст контрола.

type CheckBox

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

CheckBox is a labeled checkbox. The GTK4 backend supports it.

func NewCheckBox

func NewCheckBox(owner Component) *CheckBox

NewCheckBox creates an unchecked component without a visual parent.

func (*CheckBox) Checked

func (c *CheckBox) Checked() bool

Checked returns the current checkbox value.

func (*CheckBox) SetChecked

func (c *CheckBox) SetChecked(checked bool)

SetChecked prepares the value before Run or while detached.

func (*CheckBox) SetOnChange

func (c *CheckBox) SetOnChange(handler func())

SetOnChange replaces the handler for user changes to the checkbox.

func (*CheckBox) SetText

func (c *CheckBox) SetText(text string)

SetText задаёт текст контрола.

func (*CheckBox) Text

func (c *CheckBox) Text() string

Text возвращает подготовленный текст контрола.

type ComboBox

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

ComboBox is a single-choice drop-down without editable text.

func NewComboBox

func NewComboBox(owner Component) *ComboBox

NewComboBox creates an empty list without a selection or visual parent.

func (*ComboBox) Items

func (c *ComboBox) Items() []string

Items returns a copy in display order. Labels may repeat.

func (*ComboBox) SelectedIndex

func (c *ComboBox) SelectedIndex() int

SelectedIndex returns the current zero-based selection or -1.

func (*ComboBox) SetItems

func (c *ComboBox) SetItems(items []string)

SetItems replaces the choices and clears the selection. Call it before Run or while detached.

func (*ComboBox) SetOnChange

func (c *ComboBox) SetOnChange(handler func())

SetOnChange replaces the handler for user changes to the selection.

func (*ComboBox) SetSelectedIndex

func (c *ComboBox) SetSelectedIndex(index int) error

SetSelectedIndex prepares the selection before Run or while detached. Use -1 to clear it. An invalid index leaves the previous selection intact.

type Component

type Component interface {
	Owner() Component
	Parent() Container
	Destroy()
	Destroyed() bool
	// contains filtered or unexported methods
}

Form — логическая форма и владелец контролов экспериментального MVP. Создание формы не обращается к оконной системе. Component is an experimental sealed role; third-party implementations are unsupported.

type Container

type Container interface {
	Component
	// contains filtered or unexported methods
}

Container is the experimental visual-parent role implemented by Form and Panel.

type Edit

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

Edit — однострочное поле ввода.

func NewEdit

func NewEdit(owner Component) *Edit

NewEdit создаёт логическое поле с владельцем, но без визуального Parent. Во время Run конструкторы Edit/Button/Label/Panel требуют UI-поток и не создают native-ресурсов.

func (*Edit) SetOnChange

func (e *Edit) SetOnChange(handler func())

SetOnChange заменяет обработчик реального изменения текста; nil отменяет также ещё не начатые и накопленные уведомления.

func (*Edit) SetText

func (c *Edit) SetText(text string)

SetText задаёт текст контрола.

func (*Edit) Text

func (c *Edit) Text() string

Text возвращает подготовленный текст контрола.

type FileDialogOptions

type FileDialogOptions struct {
	Title, InitialPath, FilterName string
	Patterns                       []string
}

FileDialogOptions configures a native dialog. An optional absolute InitialPath identifies a file and directory. Patterns are optional filename patterns, such as "*.json", grouped under FilterName.

type Form

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

func NewForm

func NewForm() *Form

NewForm создаёт логическую форму без native-ресурсов.

func (*Form) Destroy

func (c *Form) Destroy()

Destroy немедленно уничтожает компонент, его owned-компоненты и визуальных потомков. Повторный вызов безопасен, включая пересечения двух деревьев.

func (*Form) Destroyed

func (c *Form) Destroyed() bool

Destroyed безопасен после Destroy и возвращает логическое состояние.

func (*Form) OpenFileDialog

func (f *Form) OpenFileDialog(options FileDialogOptions, done func(path string, err error)) error

OpenFileDialog shows a modal chooser for one existing local file. Call on the UI thread while the form is running. done is called later on the UI thread with the selected path, an error, or ("", nil) on cancel. If the dialog fails to start or the application stops, done is not called.

func (*Form) Owner

func (c *Form) Owner() Component

Owner возвращает неизменяемого владельца или nil для корневой Form.

func (*Form) Parent

func (c *Form) Parent() Container

Parent возвращает визуальный контейнер или nil.

func (*Form) Run

func (f *Form) Run() (err error)

Run запускает единственный native UI на startup-потоке. Уничтоженная форма вызывает panic прежде любых проверок. Отклонённый вызов живой формы возвращает error без расхода допуска; прошедшая проверки попытка расходуется навсегда.

func (*Form) SaveFileDialog

func (f *Form) SaveFileDialog(options FileDialogOptions, done func(path string, err error)) error

SaveFileDialog chooses a destination, with native overwrite confirmation. It only returns a path; the caller writes the file. The callback follows OpenFileDialog's rules.

func (*Form) SetClientSize

func (f *Form) SetClientSize(width, height int)

SetClientSize задаёт размер клиентской области без оконных декораций. Размеры — положительные целые logical units; настройка разрешена до Run.

func (*Form) SetTitle

func (f *Form) SetTitle(title string)

SetTitle задаёт заголовок формы.

func (*Form) Title

func (f *Form) Title() string

Title возвращает заголовок формы.

type Label

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

Label — текстовая метка.

func NewLabel

func NewLabel(owner Component) *Label

NewLabel создаёт метку с владельцем, но без визуального Parent.

func (*Label) SetText

func (c *Label) SetText(text string)

SetText задаёт текст контрола.

func (*Label) Text

func (c *Label) Text() string

Text возвращает подготовленный текст контрола.

type ListBox

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

ListBox is a visible list with one selected item at most.

func NewListBox

func NewListBox(owner Component) *ListBox

NewListBox creates an empty list without a selection or visual parent.

func (*ListBox) Items

func (c *ListBox) Items() []string

Items returns a copy in display order. Labels may repeat.

func (*ListBox) SelectedIndex

func (c *ListBox) SelectedIndex() int

SelectedIndex returns the current zero-based selection or -1.

func (*ListBox) SetItems

func (c *ListBox) SetItems(items []string)

SetItems replaces the choices and clears the selection. Call it before Run or while detached.

func (*ListBox) SetOnChange

func (c *ListBox) SetOnChange(handler func())

SetOnChange replaces the handler for user changes to the selection.

func (*ListBox) SetSelectedIndex

func (c *ListBox) SetSelectedIndex(index int) error

SetSelectedIndex prepares the selection before Run or while detached. Use -1 to clear it. An invalid index leaves the previous selection intact.

type Memo

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

Memo is a multiline text field. It follows Edit's text notification rules.

func NewMemo

func NewMemo(owner Component) *Memo

NewMemo creates a multiline field without a visual parent.

func (*Memo) SetOnChange

func (c *Memo) SetOnChange(handler func())

SetOnChange replaces the handler for a real change to the text.

func (*Memo) SetText

func (c *Memo) SetText(text string)

SetText задаёт текст контрола.

func (*Memo) Text

func (c *Memo) Text() string

Text возвращает подготовленный текст контрола.

type OpenDialog

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

OpenDialog is a nonvisual component for choosing an existing local file.

func NewOpenDialog

func NewOpenDialog(owner *Form) *OpenDialog

NewOpenDialog creates a logical dialog owned by the form.

func (*OpenDialog) SetOptions

func (d *OpenDialog) SetOptions(options FileDialogOptions)

SetOptions replaces the options used for subsequent calls to Show.

func (*OpenDialog) Show

func (d *OpenDialog) Show(done func(path string, err error)) error

Show opens the native chooser using the rules of Form.OpenFileDialog. The completion callback is suppressed if the component is destroyed.

type Panel

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

Panel is a logical visual container without text or caption properties. Native rendering depends on backend support.

func NewPanel

func NewPanel(owner Component) *Panel

NewPanel creates a logical container with an immutable owner and no Parent.

func (*Panel) SetBounds

func (c *Panel) SetBounds(x, y, width, height int)

SetBounds задаёт фиксированное положение относительно внутренней области Parent и минимальный размер в целых logical units. Native-тема может увеличить размер. Координаты неотрицательны, минимальные размеры положительны. До Run доступен для всех контролов; после начала Run — только для живого отсоединённого поддерева (вся цепочка Parent не достигает Form), независимо от прежнего native-создания. Во время Run требуется UI-поток. Автоматического размещения и коррекции пересечений нет.

func (*Panel) SetParent

func (c *Panel) SetParent(parent Container) error

SetParent changes the visual parent synchronously. During Run it requires the UI thread and backend transaction support; the same Parent is a no-op. nil отсоединяет контрол, сохраняя его состояние. An ordinary failure preserves links and properties. Failed native restoration stops the runtime and is also reported by Run.

type SaveDialog

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

SaveDialog is a nonvisual component for choosing a destination file.

func NewSaveDialog

func NewSaveDialog(owner *Form) *SaveDialog

NewSaveDialog creates a logical dialog owned by the form.

func (*SaveDialog) SetOptions

func (d *SaveDialog) SetOptions(options FileDialogOptions)

SetOptions replaces the options used for subsequent calls to Show.

func (*SaveDialog) Show

func (d *SaveDialog) Show(done func(path string, err error)) error

Show opens the native chooser using the rules of Form.SaveFileDialog. The completion callback is suppressed if the component is destroyed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL