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
18 changes: 15 additions & 3 deletions GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -3095,14 +3095,26 @@ id := mb.ShowInput("", "Имя:", "default", validate, onResult); id.SetHint("п
pd := mb.ShowProgress("Копирование", "file.jpg", onCancel)
pd.SetDetail("34 из 120 · 61 МБ/с"); pd.SetProgress(0.28) // или SetIndeterminate(true)
mb.ShowOpenFile(widget.FileDialogOptions{Filters: ...}, func(path string, ok bool) { ... })
mb.ShowSaveFile(widget.FileDialogOptions{InitialName: "a.txt"}, ...) // компактная форма
mb.ShowSaveFile(widget.FileDialogOptions{InitialName: "a.txt"}, ...) // обзор папок
mb.ShowPickFolder(widget.FileDialogOptions{}, ...)
```

Горячие клавиши: Enter — кнопка по умолчанию, Escape/✕ — отмена, Ctrl+C в
MessageBox копирует содержимое в формате Windows (разделители `---`).
Открытый браузер файлов: панель мест (Places в опциях + домашняя/диски),
кликабельный breadcrumb-путь, колонки Имя/Размер/Изменён, фильтры.
Браузер файлов: панель мест (Places в опциях + домашняя/диски),
кликабельный breadcrumb-путь, колонки Имя/Размер/Изменён, фильтры. Щелчок по
пустому месту строки пути открывает ввод пути, как в Проводнике: Enter —
переход (путь к файлу — в его папку, имя — в поле имени), Escape и щелчок
мимо — отмена, диалог при этом остаётся открытым.

**«Сохранить как».** Раньше `ShowSaveFile` показывал компактную форму, где
можно было только подняться к родительским папкам. Теперь это тот же обзор,
что у «Открыть»: двойной щелчок по папке — вход в неё, щелчок по файлу —
его имя в поле «Имя». Имени без расширения достаётся расширение выбранного
фильтра (`conn` → `conn.rdp`); имя папки в поле — переход в неё. Если файл
уже есть, предупреждение слева от кнопок показывается сразу, а перед заменой
диалог спрашивает «Заменить его?»: «Нет» оставляет диалог открытым. Компактная
форма осталась — `FileDialogOptions{Compact: true}`; ввод пути есть и в ней.

**Свои выпадающие списки в файловом диалоге.** Состав файловых диалогов был
зашит, и добавить в них поле было нельзя. Приложению, которому нужен хотя бы
Expand Down
18 changes: 16 additions & 2 deletions GUIDE_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3116,12 +3116,26 @@ id := mb.ShowInput("", "Name:", "default", validate, onResult); id.SetHint("hint
pd := mb.ShowProgress("Copying", "file.jpg", onCancel)
pd.SetDetail("34 of 120 · 61 MB/s"); pd.SetProgress(0.28) // or SetIndeterminate(true)
mb.ShowOpenFile(widget.FileDialogOptions{Filters: ...}, func(path string, ok bool) { ... })
mb.ShowSaveFile(widget.FileDialogOptions{InitialName: "a.txt"}, ...) // compact form
mb.ShowSaveFile(widget.FileDialogOptions{InitialName: "a.txt"}, ...) // folder browser
mb.ShowPickFolder(widget.FileDialogOptions{}, ...)
```

**Save As.** `ShowSaveFile` used to show a compact form where you could only go
up to parent folders. Now it is the same browser as Open: double-click a folder
to enter it, click a file to put its name into the Name field. A name without an
extension gets the extension of the selected filter (`conn` → `conn.rdp`); a
folder name in the field enters that folder. For an existing file the warning
next to the buttons shows at once, and before replacing it the dialog asks
"Do you want to replace it?": "No" keeps the dialog open. The compact form is
still there — `FileDialogOptions{Compact: true}`; it has path input too.

A click on the empty part of the path bar opens path input, as in Explorer:
Enter goes to the path (a path to a file goes to its folder and puts the name
into the Name field), Escape or a click elsewhere cancels, and the dialog stays
open.

Hotkeys: Enter — default button, Escape/✕ — cancel, Ctrl+C in a MessageBox
copies its content in the Windows format (`---` separators). The Open
copies its content in the Windows format (`---` separators). The file
browser has a places sidebar (custom Places + home/drives), a clickable
breadcrumb path, Name/Size/Modified columns and extension filters.

Expand Down
26 changes: 25 additions & 1 deletion docs/AI_AGENT_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2866,7 +2866,9 @@ mb.ShowOpenFile(opts, func(path string, ok bool) {}) // places sidebar, breadcr
// the dialog lists the SERVER's file system:
opts.AllowedRoots = []string{"/srv/uploads"} // per dialog
widget.SetDefaultAllowedRoots("/srv/uploads") // for all new dialogs
mb.ShowSaveFile(opts, onResult) // compact form + overwrite warning
mb.ShowSaveFile(opts, onResult) // the same browser + overwrite
// confirmation; opts.Compact —
// the old compact form
mb.ShowPickFolder(opts, onResult)
```

Expand Down Expand Up @@ -10522,3 +10524,25 @@ Where window code lives now (ADR-0013):
windows, `TestX11Contract`/`TestWaylandContract` on real servers when
`DISPLAY`/`WAYLAND_DISPLAY` is set, `TestCocoaContract` builds). The capability
matrix of the backends is in `window/README.md`.

## v4.1 (unreleased, branch `develop`): Save As browses folders (RDP client Tandem)

- `ShowSaveFile` builds the same browser as `ShowOpenFile` (places, path bar, up/refresh,
list filtered by the selected filter), Save button, Name + filter row; the overwrite
warning sits on the button row. `FileDialogOptions.Compact` keeps the old compact form
(height 232); it does nothing for Open and FolderPick.
- Name field in Save (`widget/dialog/dialog_file_path.go`, `saveTarget`): relative to the
current folder or absolute; an existing folder name enters it and puts `InitialName`
back; a name without an extension gets the first extension of the selected filter.
An existing file asks `dlg.file.replace` (Yes/No message box on top): No keeps the
dialog open. A full path in the Open name field is taken as is.
- Path input in every mode: a click on the empty part of the path bar (`crumbBar.OnEdit`;
the bar keeps `crumbEditGap` = 24 px free on the right, a too long last name is
ellipsized) shows `pathInput` (a `TextInput` with the current folder selected, focus
through `internal/focusreq`). Enter goes there (`Dialog.HandleInputBinding` →
`confirm` → `commitPathEdit`; a file path goes to its folder and fills the name); a
missing path or one outside `AllowedRoots` shows `dlg.file.badpath` as the field's
validation error. Escape cancels through `Dialog.OnClosing` (the dialog stays), and so
does losing focus.
- New strings (EN, RU): `dlg.file.replace.title`, `dlg.file.replace` (`%s` — file name),
`dlg.file.badpath`.
91 changes: 71 additions & 20 deletions widget/dialog/dialog_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type FileDialogMode int

const (
FileOpen FileDialogMode = iota // выбор существующего файла
FileSave // сохранение (компактная форма с именем)
FileSave // сохранение: обзор папок, имя и тип файла
FolderPick // выбор папки
)

Expand Down Expand Up @@ -69,6 +69,10 @@ type FileDialogOptions struct {
// такой же, как без этого поля. Как приложение узнаёт выбор — см.
// FileDialogChoice и FileDialog.Choice.
Choices []FileDialogChoice
// Compact — «Сохранить как» в компактной форме: строка пути, имя и тип
// файла, без панели мест и списка. По умолчанию Save — тот же обзор, что
// у Open. В Open и FolderPick не действует.
Compact bool
}

var (
Expand Down Expand Up @@ -144,9 +148,10 @@ type fileEntry struct {
// Полностью на движке: работает в headless-режиме и показывает файловую
// систему ПРОЦЕССА (в стриминге — сервера). Темизируется и локализуется.
//
// Open/FolderPick — браузер с панелью мест, breadcrumb-путём и списком
// с колонками; Save — компактная форма (путь + имя + предупреждение),
// как в принятых дизайн-мокапах.
// Open, Save и FolderPick — браузер с панелью мест, breadcrumb-путём и
// списком с колонками; щелчок по пустому месту пути открывает его ввод.
// Компактная форма Save (путь + имя + предупреждение) — по
// FileDialogOptions.Compact.
type FileDialog struct {
eng ModalShower
dlg *Dialog
Expand All @@ -164,8 +169,11 @@ type FileDialog struct {
places *placeList // nil в компактном Save
table *fileTable // nil в компактном Save
nameIn *text.TextInput // nil в FolderPick
warnLbl *base.Label
warnLbl *base.Label // предупреждение о перезаписи (только Save)
warnIco *DialogIcon

pathIn *pathInput // ввод пути на месте строки пути (dialog_file_path.go)
pathEditing bool // идёт ввод пути
}

// ShowOpenFile показывает диалог выбора файла.
Expand Down Expand Up @@ -219,7 +227,7 @@ func (mb *MessageBox) showFileDialog(opts FileDialogOptions, onResult func(path
opts.Choices = normChoices(opts.Choices)

fd := &FileDialog{eng: mb.eng, opts: opts, onResult: onResult, roots: roots}
if opts.Mode == FileSave {
if opts.Mode == FileSave && opts.Compact {
fd.buildSaveCompact(mb, title)
} else {
fd.buildBrowser(mb, title)
Expand All @@ -231,8 +239,9 @@ func (mb *MessageBox) showFileDialog(opts FileDialogOptions, onResult func(path
return fd
}

// buildBrowser — полный браузер (Open / FolderPick), мокап dlg_fileopen:
// breadcrumb + ↑/⟳, панель мест, список с колонками, имя+фильтр, кнопки.
// buildBrowser — полный браузер (Open / Save / FolderPick), мокап
// dlg_fileopen: breadcrumb + ↑/⟳, панель мест, список с колонками,
// имя+фильтр, кнопки; у Save слева от кнопок — предупреждение о перезаписи.
func (fd *FileDialog) buildBrowser(mb *MessageBox, title string) {
const (
dlgW = 640
Expand All @@ -247,10 +256,10 @@ func (fd *FileDialog) buildBrowser(mb *MessageBox, title string) {
// extraH = 0 и dlgH остаётся прежним 460.
nameY := panelY + panelH + 12
plan := planChoices(fd.opts.Choices, dlgW-2*padX)
// В Open ряд «имя + фильтр» занят, и списки идут под ним, прибавляя
// В Open и Save ряд «имя + фильтр» занят, и списки идут под ним, прибавляя
// высоту; в FolderPick этот ряд пуст — первый ряд списков встаёт в него.
choiceY, extraH := nameY, plan.height()
if fd.opts.Mode == FileOpen {
if fd.opts.Mode != FolderPick {
choiceY += choiceRowH
} else if extraH > 0 {
extraH -= choiceRowH
Expand All @@ -264,6 +273,7 @@ func (fd *FileDialog) buildBrowser(mb *MessageBox, title string) {
fd.crumb.SetBounds(image.Rect(padX, crumbY, dlgW-padX-112, crumbY+30))
fd.crumb.OnNavigate = fd.navigate
dlg.AddChild(fd.crumb)
fd.addPathInput(dlg)

upBtn := base.NewButton("↑")
upBtn.FocusRing = true
Expand Down Expand Up @@ -292,17 +302,21 @@ func (fd *FileDialog) buildBrowser(mb *MessageBox, title string) {
fd.table.OnActivate = fd.activate
dlg.AddChild(fd.table)

// ── Имя файла + фильтр (только Open) ─────────────────────────────────
// ── Имя файла + фильтр (Open и Save) ─────────────────────────────────
var nameLbl *base.Label
var filterDD *base.Dropdown
if fd.opts.Mode == FileOpen {
if fd.opts.Mode != FolderPick {
nameLbl = base.NewLabel(base.Tr("dlg.file.name"), base.ActiveTheme().LabelText)
nameLbl.FontSize = 11
nameLbl.SetBounds(image.Rect(padX, nameY+7, padX+42, nameY+25))
dlg.AddChild(nameLbl)

fd.nameIn = text.NewTextInput("")
fd.nameIn.SetBounds(image.Rect(padX+44, nameY, padX+44+330, nameY+30))
if fd.opts.Mode == FileSave {
fd.nameIn.SetText(fd.opts.InitialName)
fd.nameIn.OnChange = func(string) { fd.updateWarning() }
}
dlg.AddChild(fd.nameIn)

filterDD = fd.newFilterDropdown()
Expand All @@ -315,11 +329,29 @@ func (fd *FileDialog) buildBrowser(mb *MessageBox, title string) {

// ── Кнопки ───────────────────────────────────────────────────────────
okKey := "dlg.open"
if fd.opts.Mode == FolderPick {
switch fd.opts.Mode {
case FolderPick:
okKey = "dlg.select"
case FileSave:
okKey = "dlg.save"
}
okBtn, cancelBtn := fd.addBottomButtons(mb, dlg, dlgW, dlgH, okKey)

// Предупреждение о перезаписи (Save) — на ряду кнопок, слева от них:
// высота диалога та же, что у Open.
if fd.opts.Mode == FileSave {
bb := okBtn.Bounds()
fd.warnIco = NewDialogIcon(SeverityWarning)
fd.warnIco.SetBounds(image.Rect(padX+2, bb.Min.Y+4, padX+24, bb.Min.Y+26))
fd.warnIco.SetVisible(false)
dlg.AddChild(fd.warnIco)

fd.warnLbl = base.NewLabel("", severityColor(SeverityWarning))
fd.warnLbl.FontSize = 10
fd.warnLbl.SetBounds(image.Rect(padX+30, bb.Min.Y+7, bb.Min.X-8, bb.Min.Y+23))
dlg.AddChild(fd.warnLbl)
}

dlg.OnLanguageChange(func() {
okBtn.SetText(base.Tr(okKey))
cancelBtn.SetText(base.Tr("dlg.cancel"))
Expand All @@ -328,6 +360,7 @@ func (fd *FileDialog) buildBrowser(mb *MessageBox, title string) {
if nameLbl != nil {
nameLbl.SetText(base.Tr("dlg.file.name"))
}
fd.updateWarning()
})
}

Expand All @@ -351,6 +384,7 @@ func (fd *FileDialog) buildSaveCompact(mb *MessageBox, title string) {
fd.crumb.SetBounds(image.Rect(padX, crumbY, dlgW-padX, crumbY+30))
fd.crumb.OnNavigate = fd.navigate
dlg.AddChild(fd.crumb)
fd.addPathInput(dlg) // без списка папок путь вводится только так

lblY := crumbY + 42
nameLbl := newMutedLabel(base.Tr("dlg.file.filename"))
Expand Down Expand Up @@ -512,6 +546,7 @@ func (fd *FileDialog) navigate(dir string) {
}
fd.cur = dir
fd.reload()
fd.updateWarning() // то же имя в другой папке может уже существовать
}

// reload перечитывает текущий каталог с учётом фильтра.
Expand Down Expand Up @@ -550,6 +585,7 @@ func (fd *FileDialog) selectEntry(idx int) {
e := fd.entries[idx]
if !e.dir && fd.nameIn != nil {
fd.nameIn.SetText(e.name)
fd.updateWarning() // SetText не зовёт OnChange
}
}

Expand Down Expand Up @@ -582,10 +618,9 @@ func (fd *FileDialog) updateWarning() {
if fd.opts.Mode != FileSave || fd.warnLbl == nil {
return
}
name := strings.TrimSpace(fd.nameIn.GetText())
warn := false
if name != "" {
if st, err := os.Stat(filepath.Join(fd.cur, name)); err == nil && !st.IsDir() {
if p, isDir, ok := fd.saveTarget(); ok && !isDir {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
warn = true
}
}
Expand All @@ -600,6 +635,12 @@ func (fd *FileDialog) updateWarning() {

// confirm подтверждает выбор согласно режиму.
func (fd *FileDialog) confirm() {
if fd.pathEditing {
// Enter в поле пути — переход по пути, а не выбор файла: Enter
// диалог получает раньше поля (HandleInputBinding).
fd.commitPathEdit()
return
}
switch fd.opts.Mode {
case FolderPick:
// Выделенная папка приоритетнее текущего каталога.
Expand All @@ -611,11 +652,21 @@ func (fd *FileDialog) confirm() {
}
fd.finish(fd.cur)
case FileSave:
name := strings.TrimSpace(fd.nameIn.GetText())
if name == "" {
p, isDir, ok := fd.saveTarget()
if !ok {
return
}
fd.finish(filepath.Join(fd.cur, name))
if isDir {
// Имя папки — вход в неё, как в Проводнике; в поле — прежнее имя.
fd.navigate(p)
fd.SetFileName(fd.opts.InitialName)
return
}
if st, err := os.Stat(p); err == nil && !st.IsDir() {
fd.confirmReplace(p)
return
}
fd.finish(p)
default: // FileOpen
name := strings.TrimSpace(fd.nameIn.GetText())
if name == "" {
Expand All @@ -627,7 +678,7 @@ func (fd *FileDialog) confirm() {
}
return
}
p := filepath.Join(fd.cur, name)
p := fd.resolvePath(name)
// Если имя оказалось папкой — входим в неё.
if st, err := os.Stat(p); err == nil && st.IsDir() {
fd.navigate(p)
Expand Down
Loading
Loading