diff --git a/GUIDE.md b/GUIDE.md index 488c5fb..46f7ef1 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -3111,7 +3111,10 @@ MessageBox копирует содержимое в формате Windows (ра можно было только подняться к родительским папкам. Теперь это тот же обзор, что у «Открыть»: двойной щелчок по папке — вход в неё, щелчок по файлу — его имя в поле «Имя». Имени без расширения достаётся расширение выбранного -фильтра (`conn` → `conn.rdp`); имя папки в поле — переход в неё. Если файл +фильтра (`conn` → `conn.rdp`); имя папки в поле — переход в неё. Смена +фильтра, как в Windows, меняет и расширение в имени, если оно есть у +какого-нибудь фильтра списка: `cert.cer` → `cert.pem`; фильтр «все файлы» и +расширение, которое подходит новому фильтру, имя не меняют. Если файл уже есть, предупреждение слева от кнопок показывается сразу, а перед заменой диалог спрашивает «Заменить его?»: «Нет» оставляет диалог открытым. Компактная форма осталась — `FileDialogOptions{Compact: true}`; ввод пути есть и в ней. diff --git a/GUIDE_EN.md b/GUIDE_EN.md index fb4b1b9..c2c937b 100644 --- a/GUIDE_EN.md +++ b/GUIDE_EN.md @@ -3124,9 +3124,12 @@ mb.ShowPickFolder(widget.FileDialogOptions{}, ...) 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 +folder name in the field enters that folder. Changing the filter also changes +the extension in the name, as in Windows, when one of the listed filters has +that extension: `cert.cer` → `cert.pem`; the "all files" filter and an +extension the new filter accepts leave the name as it is. 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: diff --git a/docs/AI_AGENT_REFERENCE.md b/docs/AI_AGENT_REFERENCE.md index 43d408e..b1ae524 100644 --- a/docs/AI_AGENT_REFERENCE.md +++ b/docs/AI_AGENT_REFERENCE.md @@ -10546,3 +10546,13 @@ Where window code lives now (ADR-0013): does losing focus. - New strings (EN, RU): `dlg.file.replace.title`, `dlg.file.replace` (`%s` — file name), `dlg.file.badpath`. + +## v4.1.1 (unreleased, branch `develop`): Save As changes the extension with the filter + +- Changing the filter in Save (`matchNameToFilter` in `widget/dialog/dialog_file_path.go`, + browser and compact form) swaps the name's extension for the new filter's first one + when some listed filter has that extension, as Windows does (`cert.cer` → `cert.pem`). + A name without an extension, an unknown extension (`notes.v2`), one the new filter + already accepts and the "all files" filter keep the name; case doesn't matter; a path + in the field is kept. Open keeps the name. The overwrite warning follows the new name. + No API change. diff --git a/widget/dialog/dialog_file.go b/widget/dialog/dialog_file.go index 7dee1e5..f28badf 100644 --- a/widget/dialog/dialog_file.go +++ b/widget/dialog/dialog_file.go @@ -442,6 +442,7 @@ func (fd *FileDialog) newFilterDropdown() *base.Dropdown { dd.OnChange = func(i int, _ string) { fd.filter = i fd.reload() + fd.matchNameToFilter() fd.updateWarning() } return dd diff --git a/widget/dialog/dialog_file_path.go b/widget/dialog/dialog_file_path.go index 4db517a..282c873 100644 --- a/widget/dialog/dialog_file_path.go +++ b/widget/dialog/dialog_file_path.go @@ -156,18 +156,59 @@ func (fd *FileDialog) filterExt() string { return "" } for _, e := range fd.opts.Filters[fd.filter].Exts { - e = strings.TrimPrefix(strings.TrimSpace(e), "*") - if e == "" || e == "." || e == ".*" { - continue + if e = normExt(e); e != "" { + return e } - if !strings.HasPrefix(e, ".") { - e = "." + e - } - return e } return "" } +// normExt приводит расширение фильтра к виду «.rdp» («*.rdp», «rdp» — тоже); +// у «*», «.*» и пустого — "". +func normExt(e string) string { + e = strings.TrimPrefix(strings.TrimSpace(e), "*") + if e == "" || e == "." || e == ".*" { + return "" + } + if !strings.HasPrefix(e, ".") { + e = "." + e + } + return e +} + +// hasExt — есть ли расширение ext (без учёта регистра) у какого-нибудь из +// фильтров. +func hasExt(filters []FileFilter, ext string) bool { + for _, f := range filters { + for _, e := range f.Exts { + if n := normExt(e); n != "" && strings.EqualFold(n, ext) { + return true + } + } + } + return false +} + +// matchNameToFilter — смена фильтра в Save меняет расширение в поле имени на +// расширение нового фильтра, как в Windows: «cert.cer» → «cert.pem». Меняется +// только расширение, которое есть в списке фильтров; имя без расширения, с +// чужим расширением («отчёт.v2») или уже подходящее новому фильтру остаётся, +// фильтр «все файлы» имя не трогает. Предупреждение обновляет вызывающий. +func (fd *FileDialog) matchNameToFilter() { + if fd.opts.Mode != FileSave || fd.nameIn == nil { + return + } + name := strings.TrimSpace(fd.nameIn.GetText()) + ext := filepath.Ext(name) + newExt := fd.filterExt() // "" — «все файлы» или номер вне списка + // Имя без расширения отсеивает hasExt: пустого расширения у фильтров нет. + if newExt == "" || !hasExt(fd.opts.Filters, ext) || + hasExt(fd.opts.Filters[fd.filter:fd.filter+1], ext) { + return + } + fd.nameIn.SetText(strings.TrimSuffix(name, ext) + newExt) +} + // confirmReplace спрашивает, заменить ли существующий файл: «Да» — выбор // сделан, «Нет» — диалог остаётся открытым. func (fd *FileDialog) confirmReplace(p string) { diff --git a/widget/dialog/dialog_file_save_test.go b/widget/dialog/dialog_file_save_test.go index aa41ab1..462aad9 100644 --- a/widget/dialog/dialog_file_save_test.go +++ b/widget/dialog/dialog_file_save_test.go @@ -148,6 +148,96 @@ func TestFileSave_FilterExtension(t *testing.T) { } } +// certFilters — фильтры, как у сохранения сертификата в Tandem. +var certFilters = []FileFilter{ + {Label: "DER", Exts: []string{".cer"}}, + {Label: "PEM", Exts: []string{".pem", ".crt"}}, + {Label: "*"}, +} + +// pickFilter переключает список фильтров диалога стрелками, как с клавиатуры: +// OnChange списка тот же, что при выборе мышью. Других списков в этих тестах нет. +func pickFilter(t *testing.T, fd *FileDialog, keys ...base.KeyCode) { + t.Helper() + for _, c := range fd.Dialog().Children() { + if dd, ok := c.(*base.Dropdown); ok { + for _, k := range keys { + dd.OnKeyEvent(base.KeyEvent{Code: k, Pressed: true}) + } + return + } + } + t.Fatal("в диалоге нет списка фильтров") +} + +// Смена фильтра в Save меняет расширение в имени на расширение нового фильтра, +// как в Windows; имя без расширения, с чужим расширением или уже подходящее +// новому фильтру остаётся, «все файлы» имя не трогает. В обзоре и в +// компактной форме одинаково. +func TestFileSave_FilterChangesExtension(t *testing.T) { + down, up := base.KeyDown, base.KeyUp + for _, compact := range []bool{false, true} { + for _, c := range []struct { + name string + keys []base.KeyCode // от первого фильтра (DER) + want string + }{ + {"cert.cer", []base.KeyCode{down}, "cert.pem"}, + {"CERT.CER", []base.KeyCode{down}, "CERT.pem"}, + {"cert.cer", []base.KeyCode{down, up}, "cert.cer"}, + {"cert.crt", []base.KeyCode{down}, "cert.crt"}, + {"cert.cer", []base.KeyCode{down, down}, "cert.pem"}, + {"cert", []base.KeyCode{down}, "cert"}, + {"notes.v2", []base.KeyCode{down}, "notes.v2"}, + {filepath.Join("sub", "cert.cer"), []base.KeyCode{down}, filepath.Join("sub", "cert.pem")}, + } { + fd, _, _ := openSave(t, FileDialogOptions{StartDir: t.TempDir(), InitialName: c.name, + Filters: certFilters, Compact: compact}) + pickFilter(t, fd, c.keys...) + if got := fd.nameIn.GetText(); got != c.want { + t.Fatalf("Compact %v, имя %q, стрелки %v: стало %q, ожидалось %q", compact, c.name, c.keys, got, c.want) + } + } + } +} + +// Новое расширение сразу проверяется на перезапись, и сохраняется файл с ним. +func TestFileSave_FilterChangeWarnsAndSaves(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "cert.pem"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + fd, rm, res := openSave(t, FileDialogOptions{StartDir: dir, InitialName: "cert.cer", Filters: certFilters}) + if fd.warnIco.IsVisible() { + t.Fatal("предупреждение при новом имени") + } + pickFilter(t, fd, base.KeyDown) + if !fd.warnIco.IsVisible() { + t.Fatal("нет предупреждения: после смены фильтра имя совпало с cert.pem") + } + fd.confirm() + q := rm.top() + if q == nil || q == fd.Dialog() || q.DefaultAction == nil { + t.Fatal("нет вопроса о замене cert.pem") + } + q.DefaultAction() // «Да» + if want := filepath.Join(dir, "cert.pem"); !res.ok || res.path != want { + t.Fatalf("результат %+v, ожидался %q", *res, want) + } +} + +// В Open имя в поле — то, что ищут, а не то, что создают: смена фильтра его +// не меняет. +func TestFileOpen_FilterKeepsName(t *testing.T) { + fd := NewMessageBox(&recModal{}).ShowOpenFile(FileDialogOptions{StartDir: t.TempDir(), Filters: certFilters}, + func(string, bool) {}) + fd.SetFileName("cert.cer") + pickFilter(t, fd, base.KeyDown) + if got := fd.nameIn.GetText(); got != "cert.cer" { + t.Fatalf("Open: имя после смены фильтра %q", got) + } +} + // Существующий файл: сначала подтверждение; «Нет» оставляет диалог, «Да» // (Enter) — выбор. Подтверждение учитывает и расширение фильтра. func TestFileSave_ConfirmReplace(t *testing.T) {