UI 教程:总览与第一个应用

这套教程介绍如何用 Scoop 自带的 UI 库编写原生桌面应用。本篇是第一篇:先说明 UI 由哪些库组成,再写出第一个可交互的窗口。读完全套教程后,你应该能用现成控件搭出表单、列表、弹层和多窗口应用,也能在需要时自己绘制控件。

阅读前请先掌握语言基础中的变量、函数、类和 lambda。下一篇:布局与文字。

教程目录

篇目 章节 内容
总览与第一个应用 1–2 库的分层、运行环境、Counter
布局与文字 3–4 row/column/stack、frame、约束、Label 与排版
状态与数据流 5 State、Props、Binding、Store、key、线程规则
输入与表单 6–8 文本输入、选择类控件、字段与校验
焦点、键盘与滚动 9–10 Tab 与快捷键、ScrollArea、虚拟列表
弹层与导航 11–12 Popover、Dialog、菜单、Toast、Tabs、侧栏
数据展示 13 卡片、表格、树、日历、图表、会话组件
主题与样式 14–15 主题预设与定制、局部样式和效果
自绘元素 16–18 Element、Canvas、焦点、SkSL 着色器、自定义弹层与容器
桌面集成与异步 19–21 应用根、多窗口、原生菜单与窗框、全屏、后台任务
测试 UI 22 状态测试与窗口测试
综合项目 23 从零写一个带表格、确认和撤销的数据应用
触摸、手势与无障碍 24 轻扫翻页、捏合与旋转、键盘等价操作、读屏器与自绘控件

1. 认识 Scoop UI

1.1 几个库各管什么

Scoop UI 由几个普通的库 Cone 组成,应用按需依赖:

Cone 作用
scoop.ui 声明式 UI 框架,提供组件、状态、挂载、布局协议、输入、焦点、弹层与滚动。组件可登记触摸手势,并为自绘元素提供无障碍语义。
scoop.ui.style 公共样式与主题协议:颜色、边框、圆角、阴影等 Style,以及主题的 tokens 和部件绘制。
scoop.ui.style.macos、.material、.fluent、.shadcn 四套主题预设,分别提供 macosTheme、materialTheme、fluentTheme、shadcnTheme。
scoop.ui.component 基础控件库:Label、Button、Input、Checkbox、布局容器、滚动、列表、弹层、菜单、表格、树等。
scoop.ui.component.tray 系统托盘组件,单独成库,不需要托盘的应用不必引入。
scoop.window 原生窗口、触点与触控板手势事件,以及系统读屏器使用的无障碍接口。

框架与控件是分开的:scoop.ui.component 只使用 scoop.ui 的公开接口来实现控件。所以你自己写的控件和库里的控件地位相同,可以用同一套状态、焦点和主题机制,自绘元素一篇会讲怎么做。

所有界面都由 Scoop 自己通过 Skia 绘制(macOS 用 Metal,Windows 用 D3D12,Linux 用 EGL/GLES),窗口、菜单、文件对话框和托盘等桌面能力则使用系统的原生实现。

1.2 几个核心概念

这种模型和 React、Jetpack Compose、SwiftUI 相似,但组件是保留身份的 class,状态就放在组件的字段里。

1.3 运行环境

UI 库由工具链的 GUI 组件提供。在 Apple Silicon 上可用 scoop-install component add gui --target aarch64-apple-darwin 添加,其他桌面目标换成对应的 target。手势与无障碍示例需要包含这批新接口的 GUI 库。安装步骤见快速开始。

教程中的示例都在 macOS 上编译验证过。快捷键在 macOS 上用 ⌘,在 Linux 和 Windows 上用 Ctrl,框架统称为 Primary。

2. 第一个应用:Counter

2.1 最小程序

把下面的程序保存为 ui-counter.scoop,也可以下载同一份源码:

//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
import scoop.ui.*
import scoop.ui.component.button
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.macos.macosTheme

class Counter(scope: ComponentScope): Component(scope) {
    private var count: Int by state(0)
    public override fun render(): View =
        button(f"Count: ${count}", { count += 1 })
}

fun main() {
    val source = ThemeSource(macosTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Counter", { scope -> Counter(scope) })
    }
}

运行:

scoop run ui-counter.scoop --release

Counter 窗口:整个窗口是一个蓝色按钮,点击三次后显示 Count: 3

第一次编译要链接图形相关的库,需要几十秒。之后会打开一个标题为 Counter 的窗口,整个窗口是一个按钮,每点一次,文字 Count: 0 中的数字加一。关闭窗口后程序退出。

逐段说明:

2.2 为什么按钮铺满了窗口

窗口根组件接收的是紧约束:宽高都必须正好等于窗口大小。按钮直接作为根,只能填满整个窗口。要让内容按自身大小显示并居中,需要在外面套一层容器。下一节的 frame 会把紧约束放宽为“最大不超过窗口”,并默认在两个方向上居中。布局约束的完整说明见第 3 章。

2.3 用布局和多个控件改写

保存为 ui-counter-layout.scoop(下载):

//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.graphics.text:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
import scoop.graphics.Paint
import scoop.graphics.text.TextAlignment
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.currentThemeSource
import scoop.ui.style.read
import scoop.ui.style.shadcn.shadcnTheme

class Counter(scope: ComponentScope): Component(scope) {
    // Captured once at construction; the mount factory runs inside context(source).
    private val theme = currentThemeSource()
    private val count = state(0)

    public override fun render(): View {
        val count = this.count
        val content =
            column {
                spacing = 16.0
                alignment = CrossAlignment.Center
                // Text fills the bounded width, so center the paragraph itself.
                typography("Counter", TypographyRole.H3) {
                    settings { alignment = TextAlignment.Center }
                }
                label(f"Clicked ${count.value} times") {
                    settings { alignment = TextAlignment.Center }
                }
                row {
                    spacing = 8.0
                    button("-1", { count.value -= 1 }) {
                        variant = ButtonVariant.Outline
                        enabled = count.value > 0
                    }
                    button("+1", { count.value += 1 })
                    button("Reset", { count.value = 0 }) { variant = ButtonVariant.Ghost }
                }
            }
        // Read the theme with this window's display preferences.
        val pageColor = this.theme.read(scope).tokens.palette.background.background
        return frame(content) { style { background(Some(Paint(pageColor))) } }
    }
}

fun main() {
    val source = ThemeSource(shadcnTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Counter", { scope -> Counter(scope) })
    }
}

scoop run ui-counter-layout.scoop --release

改写后的 Counter:窗口中央是标题、Clicked 3 times 和 -1、+1、Reset 三个按钮

窗口中央显示标题 Counter、一行计数文字和三个按钮,背景为主题的页面底色。计数为 0 时,-1 按钮呈禁用状态;点一次 +1 后变为可用。这次换成了 shadcn 主题:依赖头和 import 改为 scoop.ui.style.shadcn,控件代码不用改。

这个版本有四处变化:

  1. builder 写法:column { ... }、row { ... } 用接收者 lambda 收集子项。在块中直接调用 typography、label、button,就会依次添加子项;spacing、alignment 等属性用来配置容器本身。控件的可选配置也写在尾随块里,例如 button("-1", onClick) { variant = ButtonVariant.Outline }。
  2. State 作为字段:private val count = state(0) 直接保存 State<Int>,通过 count.value 读写。render 开头的 val count = this.count 把它取到局部变量。
  3. 窗口底色。 组件构造时用 currentThemeSource() 取得主题来源,在 render 中从 theme.read(scope) 取出 tokens.palette.background.background 作为根 frame 的背景。切换主题或窗口的高对比度等偏好发生变化时,背景会随之更新。
  4. 文字居中:column 的 alignment = CrossAlignment.Center 让较窄的子项(例如按钮行)居中。但 Label 和 Typography 在有界宽度下会按可用宽度排版,宽度撑满整列,文字默认靠段落起始边。要让文字本身居中,需要通过 settings { alignment = TextAlignment.Center } 设置段落对齐。

第 2 点是必须的。builder 块中有自己的接收者(column 和 row 的块接收者是 LinearBuilder),Scoop 不允许在这样的块中隐式使用外层接收者(这里是 Counter 组件的成员)。直接写 label(f"${count.value}") 会得到:

error[E0716]: implicit use of an outer receiver is not allowed
help[H0402]: use `this@label` or an explicit object reference

所以要先用 val count = this.count(或 val model = this.model)取出局部变量,再在块中使用。第一个版本没有这个问题:button(text, onClick) 的回调是普通 lambda,不带接收者,可以直接访问组件成员。

E0716 标识接收者规则错误,help[H0402] 是附属的修改建议。编号的读法和工具链版本说明见编译器诊断。

2.4 练一练

常见错误与继续阅读

现象 原因与处理
编译时报找不到 scoop.ui... 单文件程序漏写了 //! dep:,或依赖头没放在最前面
报找不到 Paint、ShortcutScope 等类型 单文件依赖不会传递:直接 import 了哪个 Cone(如 scoop.graphics、scoop.surface、scoop.window),就要为它写 //! dep:
builder 块中报 argument must be of type View, found Unit 块中的 label、button、frame 等是“追加一个子项”的成员函数,返回 Unit;要把控件作为参数传给 frame(...)、tooltip(...) 等,先在块外创建 View,详见第 3 章
控件报缺少主题来源 挂载入口外层没有 context(source) { ... }
builder 块中报 implicit use of an outer receiver 先把组件成员取到局部变量,再在块中使用
控件铺满整个窗口 根是紧约束,外面套 frame 或其他容器
窗口是黑底,文字看不清 窗口不自动铺底色;用主题 palette 的 background 给根 frame 设置背景
column 设了居中,文字仍靠左 Label 撑满可用宽度;用段落 settings { alignment = TextAlignment.Center }
在 render() 中修改 State 不允许。render 只能读取状态,修改应放在回调或生命周期中,见状态与数据流

下一篇布局与文字介绍容器、约束与文字排版。各库的完整 API 可以在 API 文档中查找;实现必须遵守的完整规则见 Scoop 仓库的 UI 规范。