Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 80 additions & 3 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2353,6 +2353,28 @@ dv.OnFileChangedOnDisk = func(side widget.DiffSide, path string, deleted bool) {
изменений), `FileChangedCommand` (`DiffFileChange`); из кода — `SetCommand`.
Полный пример — `cmd/diffdemo`.

**Свернуть сторону и сдвинуть границу (v4.4).** При длинных строках половины
ширины не хватает: сторону можно свернуть в узкую полосу, и вторая займёт всю
ширину — с подсветкой изменений, переходом по ним, правкой и сохранением.

```go
dv.SetCollapsed(widget.DiffLeft, true) // свернуть «HEAD»; вторую — разворачивает первую
dv.Collapsed(widget.DiffLeft) // true
dv.SetSplit(0.6) // доля левой стороны, когда развёрнуты обе (0.15…0.85)
dv.OnCollapsedChanged = func(side widget.DiffSide, collapsed bool) { saveLayout() }
dv.OnSplitChanged = func(ratio float64) { saveLayout() }
// dv.SetShowCollapseButtons(false) — без кнопок в шапках, если у приложения свои
```

В шапке каждой стороны — шеврон «свернуть», полоса свёрнутой стороны
разворачивается щелчком. Свёрнутой может быть только одна сторона; свернули
активную — активной становится видимая, а `SetActiveSide`/`SetCaret` на
свёрнутую её разворачивают. Коннекторы и кнопки переноса при свёрнутой стороне
не рисуются, `CopyBlock`/`CopyAll` из кода работают. Граница между развёрнутыми
сторонами тянется мышью за промежуток с коннекторами (`OnSplitChanged` — один
раз, когда её отпустят), двойной щелчок по нему возвращает 50/50. В разметке:
`CollapsedSide="None|Left|Right"`, `ShowCollapseButtons`, `Split="0.6"`.

#### MergeView — трёхстороннее слияние

Пара к `DiffView`: три стороны конфликта сверху (наше · база · их) и
Expand Down Expand Up @@ -2414,6 +2436,29 @@ git — стиль `MergeStyleMerge` или `MergeStyleDiff3` (с базой з
граница между верхом и итогом двигается перетаскиванием. `SetShowBase(false)`
убирает панель базы — остаются наше, их и итог.

**Раскладка (v4.4).** Верхние панели сворачиваются в узкие полосы — шевроном
в шапке или из кода; полоса разворачивается щелчком. Итог можно развернуть на
всю высоту (от верха остаются шапки) и наоборот — кнопками в шапке итога.

```go
mv.SetPaneCollapsed(widget.MergeBase, true) // «наше», «база», «их»; последнюю развёрнутую свернуть нельзя
mv.SetResultMaximized(true) // итог на всю высоту; SetSourcesMaximized — верх
mv.SetSplit(0.5) // доля высоты верха (0.2…0.85), снимает развёртывание
mv.OnLayoutChanged = func() { // одно событие на любое изменение раскладки
saveLayout(mv.PaneCollapsed(widget.MergeOurs), mv.Split(), mv.ResultMaximized())
}
// mv.SetShowCollapseButtons(false) — без шевронов и кнопок «на всю высоту»
```

У свёрнутой панели кнопки решения не рисуются; `Resolve`, `ResolveCurrent`,
`ResolveAll` из кода работают. Свернули активную панель — ввод уходит в итог;
`SetActiveSide` на свёрнутую её разворачивает. `SetShowBase(false)` сохраняет
прежний смысл — базы нет совсем. Двойной щелчок по разделителю возвращает долю
по умолчанию 0.58. `OnLayoutChanged` приходит и на показ базы, и на
отпускание разделителя (один раз за перетаскивание). В разметке:
`CollapsedPanes="Ours,Theirs"`, `Split="0.58"`, `ResultMaximized`,
`SourcesMaximized`, `ShowCollapseButtons`.

Программно — `Resolve`, `ResolveCurrent`, `ResolveAll`, `Resolution`,
`Unresolved`, `ConflictCount`, `NextConflict`, `PrevConflict`, `GoToConflict`,
`Result`, `ResultLines`, `Undo`, `Redo`, `SetCaret`, `InsertText`.
Expand Down Expand Up @@ -3049,11 +3094,11 @@ ctx.DrawTextSize(" px", x+widget.MeasureUIText("12", 18), base-small.Ascent, 10,

### Чёткость мелкого текста (v3.42)

По умолчанию текст растеризуется как раньше: серое сглаживание без хинтинга.
Без этого слоя текст растеризуется серым сглаживанием без хинтинга.
У мелких кеглей (12–14 px) штрихи тогда ложатся на сетку случайно, и одна и та
же буква в строке то чёткая, то размытая. Режим `TextQuality` это исправляет.
Он **выключен по умолчанию** — кадры существующих программ не меняются, —
включать его надо явно, один раз при запуске:
До v4.4 он был **выключен по умолчанию** и включался явно, один раз при
запуске (с v4.4 движок включает его сам, см. ниже):

```go
eng.SetTextQuality(engine.TextQuality{
Expand All @@ -3078,6 +3123,38 @@ Linux и в CI. Есть и короткие формы: `SetTextHinting(bool)`,
`SetTextContrast(float64)`. После включения эталонные снимки программы надо
пересобрать.

**С v4.4 слой качества включён по умолчанию** и умеет больше: движок сам
ставит `engine.DefaultTextQuality()` — хинтинг по обеим осям и контраст, без
LCD. Новое поле `HintingX` привязывает вертикальные штрихи к пиксельной сетке
по горизонтали, как хинтинг Windows: ствол «l», «Н», бока «о» шириной около
пикселя ложатся не на границу двух пикселей (два серых столбца — «мыло»), а в
один плотный столбец.

```go
// Ничего вызывать не нужно — так движок рисует по умолчанию.
eng.SetTextQuality(engine.TextQuality{}) // прежний вид текста, побайтно
eng.SetTextHintingX(false) // выключить только привязку по X
```

- Толщина штриха округляется до целого числа пикселей (вверх уже с 0,4), а
у штрихов, близких к стандартной толщине шрифта на кегле (по букве «l»), —
одинаково: буквы строки одного веса.
- Стволы с равным шагом («Ш», «ш», «m», «п») ставятся рядом с одним
округлённым шагом — просветы равные.
- Шаги глифов, кернинг и ширина строки **не меняются** — раскладка прежняя;
глиф сдвигается внутри своей ячейки меньше чем на пиксель (штрих — не
дальше полпикселя, в ряду равных стволов — до ¾ px, плюс до ¼ px к
середине ячейки при целом шаге). С `SetTextSubpixel(true)` штрихи ставятся
от точного положения пера, ошибка по строке не копится.
- Знаки вне зон («•», «·», «°», «.», «…») и шрифты без латиницы и кириллицы
(иконочные) не выравниваются: маркер в поле пароля остаётся круглым,
значки — прежними.
- Работает на путях `DrawText`/`DrawTextFont` и повёрнутого текста; текст
шейпера (сложные письменности) и SVG выравнивается только по вертикали.

Эталонные снимки программ с текстом после перехода на v4.4 надо пересобрать
(или вернуть прежний вид вызовом `SetTextQuality(engine.TextQuality{})`).

---

### Стандартные диалоги (MessageBox, ввод, прогресс, файлы)
Expand Down
87 changes: 83 additions & 4 deletions GUIDE_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2369,6 +2369,29 @@ file; the application saves it with `SaveAs`. Commands: `SaveCommand`
`DiffChangedCommand` (number of changes), `FileChangedCommand`
(`DiffFileChange`); from code — `SetCommand`. Full example — `cmd/diffdemo`.

**Collapse a side and move the boundary (v4.4).** With long lines half the
width is not enough: a side collapses into a narrow strip and the other one
takes the whole width — with change highlighting, navigation, editing and
saving.

```go
dv.SetCollapsed(widget.DiffLeft, true) // collapse "HEAD"; collapsing the other one expands this
dv.Collapsed(widget.DiffLeft) // true
dv.SetSplit(0.6) // share of the left side when both are expanded (0.15…0.85)
dv.OnCollapsedChanged = func(side widget.DiffSide, collapsed bool) { saveLayout() }
dv.OnSplitChanged = func(ratio float64) { saveLayout() }
// dv.SetShowCollapseButtons(false) — no header buttons when the app has its own
```

Each side header has a "collapse" chevron; a click on the strip of a collapsed
side expands it. Only one side can be collapsed; collapsing the active side
makes the visible one active, and `SetActiveSide`/`SetCaret` on a collapsed
side expand it. With a collapsed side the connectors and transfer buttons are
not drawn; `CopyBlock`/`CopyAll` work from code. The boundary between expanded
sides is dragged by the connector gap (`OnSplitChanged` comes once, on
release), a double click on it restores 50/50. Markup:
`CollapsedSide="None|Left|Right"`, `ShowCollapseButtons`, `Split="0.6"`.

#### MergeView — three-way merge

The counterpart to `DiffView`: three sides of the conflict on top (ours ·
Expand Down Expand Up @@ -2431,6 +2454,29 @@ menu offers every resolution, and the boundary between the top panes and the
result is draggable. `SetShowBase(false)` hides the base pane — ours, theirs
and the result remain.

**Layout (v4.4).** The top panes collapse into narrow strips — with the
chevron in the header or from code; a click on the strip expands it. The
result can take the whole height (only the top headers remain) and the other
way round — with the buttons in the result header.

```go
mv.SetPaneCollapsed(widget.MergeBase, true) // ours, base, theirs; the last expanded one cannot collapse
mv.SetResultMaximized(true) // result full height; SetSourcesMaximized — the top
mv.SetSplit(0.5) // share of height for the top (0.2…0.85), clears maximizing
mv.OnLayoutChanged = func() { // one event for any layout change
saveLayout(mv.PaneCollapsed(widget.MergeOurs), mv.Split(), mv.ResultMaximized())
}
// mv.SetShowCollapseButtons(false) — no chevrons and full-height buttons
```

A collapsed pane draws no resolve buttons; `Resolve`, `ResolveCurrent` and
`ResolveAll` work from code. Collapsing the active pane moves input to the
result; `SetActiveSide` on a collapsed pane expands it. `SetShowBase(false)`
keeps its meaning — no base at all. A double click on the splitter restores
the default 0.58. `OnLayoutChanged` also comes for showing the base and when
the splitter is released (once per drag). Markup: `CollapsedPanes="Ours,Theirs"`,
`Split="0.58"`, `ResultMaximized`, `SourcesMaximized`, `ShowCollapseButtons`.

From code — `Resolve`, `ResolveCurrent`, `ResolveAll`, `Resolution`,
`Unresolved`, `ConflictCount`, `NextConflict`, `PrevConflict`, `GoToConflict`,
`Result`, `ResultLines`, `Undo`, `Redo`, `SetCaret`, `InsertText`.
Expand Down Expand Up @@ -3069,12 +3115,12 @@ not divide by zero; a size of zero or less gives all zeros.

### Small text sharpness (v3.42)

By default text is rasterized as before: grayscale antialiasing without
Without this layer text is rasterized with grayscale antialiasing and no
hinting. At small sizes (12–14 px) stems then land on the pixel grid by
chance, so the same letter is crisp in one place of a line and blurry in
another. The `TextQuality` mode fixes that. It is **off by default** — frames
of existing programs do not change — and has to be turned on explicitly, once
at start-up:
another. The `TextQuality` mode fixes that. Before v4.4 it was **off by
default** and had to be turned on explicitly, once at start-up (since v4.4
the engine turns it on itself, see below):

```go
eng.SetTextQuality(engine.TextQuality{
Expand All @@ -3099,6 +3145,39 @@ byte-identical on Windows, Linux and in CI. Short forms exist too:
`SetTextHinting(bool)`, `SetTextContrast(float64)`. Re-record the program's
golden snapshots after turning it on.

**Since v4.4 the quality layer is on by default** and does more: the engine
starts with `engine.DefaultTextQuality()` — hinting along both axes and
contrast, no LCD. The new `HintingX` field snaps vertical stems to the pixel
grid horizontally, like Windows hinting: a stem of `l`, `H` or the side of
`o` about one pixel wide no longer lands on the border of two pixels (two
grey columns — the "blurry" look) but fills one solid column.

```go
// Nothing to call — this is how the engine draws by default.
eng.SetTextQuality(engine.TextQuality{}) // the previous look, byte for byte
eng.SetTextHintingX(false) // only the horizontal snapping off
```

- Stem widths are rounded to whole pixels (up from a 0.4 fraction), and stems
close to the font's standard width at that size (taken from `l`) get the
same width: the letters of a line have one weight.
- Stems with an equal step (`Ш`, `ш`, `m`, `п`) are placed as a row with one
rounded step — the counters are equal.
- Advances, kerning and line widths **do not change** — layout stays the
same; a glyph moves inside its cell by less than a pixel (a stem by at most
half a pixel, in a row of equal stems up to 3/4 px, plus up to 1/4 px
towards the cell centre with whole-pixel advances). With
`SetTextSubpixel(true)` stems are placed from the exact pen position, the
error does not accumulate along a line.
- Signs outside the zones (`•`, `·`, `°`, `.`, `…`) and fonts without Latin
and Cyrillic (icon fonts) are not snapped: the password bullet stays round,
icons stay as they were.
- Applies to `DrawText`/`DrawTextFont` and rotated text; shaped text
(complex scripts) and SVG text are hinted vertically only.

Programs with golden snapshots of text must re-record them after moving to
v4.4 (or restore the previous look with `SetTextQuality(engine.TextQuality{})`).

---

### Standard dialogs (MessageBox, input, progress, files)
Expand Down
Loading
Loading