Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Watch folders: optional file patterns, name rule, rename steps and a preview

KnifeLemon140d5cd135af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b041c5a..df256f0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,21 @@ find it, what it does and doesn't do.
was changed or deleted. Files that are no longer there are left out. The progress card that pops up after a
conversion has the same **Retry** button. Conversions from watch folders are listed and retried the same way;
a retried file stays in the watched folder, also when the folder moves originals to "originals".
+- **Watch folders: choose files and name them** (Settings → Watch folders → *More options*, all optional; empty
+ fields change nothing):
+ - *Files to convert*: patterns entered as tags. Typing `heic` adds `*.heic`, other text picks names that contain
+ it, `*` stands for any text and `?` for one character, and a regular expression goes between slashes
+ (`/^IMG_\d+/`). Extensions are suggested while typing, a broken expression is not added, and the card says how
+ many files in the folder match. Other files in the folder are left alone.
+ - *File name rule*: a name pattern for this folder in place of the preset's, with `{name}`, `{date}`, `{time}`,
+ `{index}` and `{preset}`.
+ - *Replace part of the name*: regular expressions and what to put in their place, applied in order, e.g.
+ `IMG_(\d+)` → `Photo_$1`. **Common replacements** lists ready-made ones (camera numbers, spaces, copy numbers
+ like "(2)", text in brackets, dates, symbols, text at the start or end), each with an example of what it does;
+ double-click one or press + to add it as a step and change it from there.
+ - A **preview** on every watch folder shows a converted file as it will be saved (`IMG_0412.jpg →
+ converted\Photo_0412.pdf`, using a file already in the folder when there is one), what happens when the name is
+ taken and what happens to the original.
### Documentation
diff --git a/README.ko.md b/README.ko.md
index 948b223e..0868c0c3 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -95,7 +95,9 @@ Finder에서 파일을 우클릭하면 "Filee로 변환"이 나와요. FFmpeg와
잘하는 엔진을 써요.
- **네 가지 사용 방법.** 드래그 동작, 파일 관리자 우클릭 메뉴(Windows는 보내기도), 선택한 파일 + 단축키, 메인 창 드롭 영역.
- **자동 변환 폴더.** 정해 둔 폴더에 들어온 파일을 다운로드나 복사가 끝난 뒤 변환해요. 원본은 그대로 두거나 따로 옮겨서
- 폴더를 받은편지함처럼 쓸 수 있어요.
+ 폴더를 받은편지함처럼 쓸 수 있어요. 필요하면 일부 파일만 변환하고(`*.heic`, `scan_*`, 정규식을 태그로 입력), 변환된
+ 파일에 따로 파일명 규칙을 정하고, 자주 쓰는 규칙이나 직접 만든 정규식으로 이름 일부를 바꿀 수 있어요. 결과는 미리보기로
+ 바로 보여요.
- **보이는 엔진.** 설정 → 변환 엔진에서 엔진마다 버전과 변환 범위를 보여 줘요. PC에 이미 있는 FFmpeg, calibre, Pandoc,
Ghostscript, LibreOffice는 찾아서 쓰고 따로 내려받지 않아요.
- **라이트·다크·시스템 테마**, 강조색, *애니메이션 줄이기*.
diff --git a/README.md b/README.md
index 8c9838fc..bc189d8b 100644
--- a/README.md
+++ b/README.md
@@ -98,7 +98,9 @@ Dolphin. Ubuntu 24.04 is the tested baseline; `INSTALL.txt` in the package lists
- **Four ways in.** The drag gesture, the file manager's right-click menu (and Send To on Windows), a keyboard shortcut
on the selected files, and the drop zone in the main window.
- **Watch folders.** Files that land in a folder you choose are converted once their download or copy is complete.
- Keep the originals or move them aside, so the folder works like an inbox.
+ Keep the originals or move them aside, so the folder works like an inbox. Optionally convert only some files
+ (`*.heic`, `scan_*` or a regular expression, entered as tags), give converted files their own name rule and
+ replace parts of names with ready-made or your own regular expressions, with a live preview.
- **Engines you can see.** Settings → Engines lists every engine with its version and what it converts. FFmpeg,
calibre, Pandoc, Ghostscript and LibreOffice already on your computer are found and used instead of a download.
- **Light, dark or system theme**, your accent colour and a *Reduce animations* switch.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 65c66c1f..289ea953 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -87,7 +87,7 @@ Nautilus、Nemo、Thunar 或 Dolphin 的右键菜单。测试基准为 Ubuntu 24
"合并 PDF"生成一个 PDF。
- **多步转换。** 自动找到需要多步的转换(HWP → HWPX → DOCX、EPUB → HWPX → PDF → PNG),每一步使用最擅长的引擎。
- **四种使用方式。** 拖动手势、文件管理器右键菜单(Windows 还有“发送到”)、对选中文件按快捷键、主窗口拖放区。
-- **自动转换文件夹。** 放入指定文件夹的文件会在下载或复制完成后自动转换;原文件可以保留,也可以移走,让文件夹像收件箱一样使用。
+- **自动转换文件夹。** 放入指定文件夹的文件会在下载或复制完成后自动转换;原文件可以保留,也可以移走,让文件夹像收件箱一样使用。还可以只转换部分文件(以标签输入 `*.heic`、`scan_*` 或正则表达式),为转换后的文件设置单独的文件名规则,并用常用规则或自己写的正则表达式替换名称中的文字,实时预览结果。
- **引擎一目了然。** “设置 → 转换引擎”列出每个引擎的版本和可转换内容。电脑上已有的 FFmpeg、calibre、Pandoc、Ghostscript
和 LibreOffice 会被自动找到并使用,不再另外下载。
- **浅色、深色或跟随系统**,自定义强调色,可开启“减少动画”。
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index d133badd..c49722bc 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -474,6 +474,38 @@
"watch.output": "Save converted files to",
"watch.output_placeholder": "\"converted\" inside the watched folder",
"watch.subfolders": "Include subfolders",
+ "watch.options": "More options (optional)",
+ "watch.include": "Files to convert",
+ "watch.include_placeholder": "Type an extension or a name, then Enter (e.g. heic, scan_*)",
+ "watch.include_hint": "Empty converts every file. An extension such as heic becomes *.heic; other text picks names that contain it. * stands for any text and ? for one character; put a regular expression between slashes, e.g. /^IMG_\\d+/.",
+ "watch.name": "File name rule",
+ "watch.name_placeholder": "Same as the preset: {0}",
+ "watch.name_hint": "{name} original name · {date} date · {time} time · {index} number in the batch · {preset} preset name",
+ "watch.rename": "Replace part of the name (regular expressions, applied in order)",
+ "watch.rename_find": "Find, e.g. IMG_(\\d+)",
+ "watch.rename_replace": "Replace with, e.g. Photo_$1",
+ "watch.include_matches": "{0} file(s) in the folder match now",
+ "watch.add_step": "Add a step",
+ "watch.remove_step": "Remove this step",
+ "watch.recipes": "Common replacements",
+ "watch.recipes_hint": "Double-click one (or press +) to add it as a step, then change it if you like.",
+ "watch.recipe_add": "Add as a step",
+ "watch.recipe_removes": "(removed)",
+ "watch.recipe.photo_number": "Camera file names to Photo_number",
+ "watch.recipe.drop_camera_prefix": "Remove IMG_, DSC_ or PXL_",
+ "watch.recipe.spaces": "Spaces to underscores",
+ "watch.recipe.copy_number": "Remove a copy number like (2)",
+ "watch.recipe.brackets": "Remove text in brackets",
+ "watch.recipe.leading_number": "Remove a leading number",
+ "watch.recipe.date_dashes": "Put dashes in dates",
+ "watch.recipe.symbols": "Remove symbols",
+ "watch.recipe.prefix": "Add text at the start",
+ "watch.recipe.suffix": "Add text at the end",
+ "watch.invalid_regex": "Not a valid regular expression: {0}",
+ "watch.preview": "Preview",
+ "watch.sample_file": "photo.jpg",
+ "watch.preview_keep": "The original stays where it is",
+ "watch.preview_move": "The original moves to \"originals\"",
"watch.status_off": "Off",
"watch.status_no_folder": "Choose a folder to start",
"watch.status_watching": "Watching",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 9c475d69..7dd06f96 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -474,6 +474,38 @@
"watch.output": "변환된 파일 저장 위치",
"watch.output_placeholder": "감시 폴더 안의 \"converted\" 폴더",
"watch.subfolders": "하위 폴더 포함",
+ "watch.options": "추가 옵션 (선택)",
+ "watch.include": "변환할 파일",
+ "watch.include_placeholder": "확장자나 이름을 입력하고 Enter (예: heic, scan_*)",
+ "watch.include_hint": "비워 두면 모든 파일을 변환해요. heic처럼 확장자만 쓰면 *.heic가 되고, 다른 글자는 이름에 그 글자가 들어간 파일을 골라요. * 는 아무 글자, ? 는 한 글자이고, 정규식은 /^IMG_\\d+/ 처럼 슬래시로 감싸요.",
+ "watch.name": "파일명 규칙",
+ "watch.name_placeholder": "프리셋과 같게: {0}",
+ "watch.name_hint": "{name} 원래 이름 · {date} 날짜 · {time} 시간 · {index} 순번 · {preset} 프리셋 이름",
+ "watch.rename": "이름 일부 바꾸기 (정규식, 위에서부터 차례로)",
+ "watch.rename_find": "찾을 패턴 (예: IMG_(\\d+))",
+ "watch.rename_replace": "바꿀 내용 (예: 사진_$1)",
+ "watch.include_matches": "지금 폴더에서 {0}개 파일이 해당돼요",
+ "watch.add_step": "단계 추가",
+ "watch.remove_step": "이 단계 지우기",
+ "watch.recipes": "자주 쓰는 규칙",
+ "watch.recipes_hint": "더블클릭하거나 + 를 누르면 단계로 추가돼요. 추가한 뒤 자유롭게 고칠 수 있어요.",
+ "watch.recipe_add": "단계로 추가",
+ "watch.recipe_removes": "(지우기)",
+ "watch.recipe.photo_number": "카메라 파일 이름을 Photo_번호로",
+ "watch.recipe.drop_camera_prefix": "IMG_, DSC_, PXL_ 지우기",
+ "watch.recipe.spaces": "공백을 밑줄(_)로",
+ "watch.recipe.copy_number": "(2) 같은 사본 번호 지우기",
+ "watch.recipe.brackets": "괄호와 그 안의 글자 지우기",
+ "watch.recipe.leading_number": "앞에 붙은 번호 지우기",
+ "watch.recipe.date_dashes": "날짜에 - 넣기",
+ "watch.recipe.symbols": "특수 문자 지우기",
+ "watch.recipe.prefix": "앞에 글자 붙이기",
+ "watch.recipe.suffix": "뒤에 글자 붙이기",
+ "watch.invalid_regex": "올바른 정규식이 아니에요: {0}",
+ "watch.preview": "미리보기",
+ "watch.sample_file": "사진.jpg",
+ "watch.preview_keep": "원본은 그대로 둬요",
+ "watch.preview_move": "원본은 \"originals\" 폴더로 옮겨요",
"watch.status_off": "꺼짐",
"watch.status_no_folder": "폴더를 고르면 시작해요",
"watch.status_watching": "감시 중",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index a5d07a0b..bafaa6ed 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -474,6 +474,38 @@
"watch.output": "转换后的文件保存到",
"watch.output_placeholder": "监视文件夹中的 \"converted\" 文件夹",
"watch.subfolders": "包括子文件夹",
+ "watch.options": "更多选项(可选)",
+ "watch.include": "要转换的文件",
+ "watch.include_placeholder": "输入扩展名或名称后按 Enter(例如 heic、scan_*)",
+ "watch.include_hint": "留空则转换所有文件。只写 heic 这样的扩展名会变成 *.heic,其他文字会选出名称中包含它的文件。* 代表任意文字,? 代表一个字符,正则表达式用斜杠包住,例如 /^IMG_\\d+/。",
+ "watch.name": "文件名规则",
+ "watch.name_placeholder": "与预设相同:{0}",
+ "watch.name_hint": "{name} 原文件名 · {date} 日期 · {time} 时间 · {index} 序号 · {preset} 预设名称",
+ "watch.rename": "替换名称中的文字(正则表达式,按顺序执行)",
+ "watch.rename_find": "查找,例如 IMG_(\\d+)",
+ "watch.rename_replace": "替换为,例如 照片_$1",
+ "watch.include_matches": "文件夹中目前有 {0} 个文件符合",
+ "watch.add_step": "添加一步",
+ "watch.remove_step": "删除此步",
+ "watch.recipes": "常用规则",
+ "watch.recipes_hint": "双击(或点 +)即可添加为一步,添加后可以再修改。",
+ "watch.recipe_add": "添加为一步",
+ "watch.recipe_removes": "(删除)",
+ "watch.recipe.photo_number": "相机文件名改为 Photo_编号",
+ "watch.recipe.drop_camera_prefix": "去掉 IMG_、DSC_、PXL_",
+ "watch.recipe.spaces": "空格改为下划线",
+ "watch.recipe.copy_number": "去掉 (2) 这样的副本编号",
+ "watch.recipe.brackets": "去掉括号及其中的文字",
+ "watch.recipe.leading_number": "去掉开头的编号",
+ "watch.recipe.date_dashes": "日期加上连字符",
+ "watch.recipe.symbols": "去掉特殊符号",
+ "watch.recipe.prefix": "在开头加文字",
+ "watch.recipe.suffix": "在末尾加文字",
+ "watch.invalid_regex": "不是有效的正则表达式:{0}",
+ "watch.preview": "预览",
+ "watch.sample_file": "照片.jpg",
+ "watch.preview_keep": "原文件保留在原处",
+ "watch.preview_move": "原文件移到 \"originals\" 文件夹",
"watch.status_off": "已关闭",
"watch.status_no_folder": "选择文件夹后开始",
"watch.status_watching": "正在监视",
diff --git a/src/Filee.App/Services/WatchFolderService.cs b/src/Filee.App/Services/WatchFolderService.cs
index 04621c9c..68fe22d7 100644
--- a/src/Filee.App/Services/WatchFolderService.cs
+++ b/src/Filee.App/Services/WatchFolderService.cs
@@ -74,20 +74,20 @@ public sealed class WatchFolderService(UserDataStore store, ConversionService co
private async Task<Core.Conversion.ConversionJob?> ConvertAsync(WatchRule rule, IReadOnlyList<string> files)
{
- var preset = store.Presets.FirstOrDefault(p => p.Id == rule.PresetId)?.Clone();
+ var preset = store.Presets.FirstOrDefault(p => p.Id == rule.PresetId);
if (preset is null)
{
log.LogWarning("Watch folder {Folder}: preset {Preset} no longer exists", rule.Folder, rule.PresetId);
return null;
}
- preset.Output.Location = Core.Presets.OutputLocation.CustomFolder;
- preset.Output.CustomFolder = rule.ResolvedOutputFolder;
- return await conversions.RunAsync(files, preset);
+ return await conversions.RunAsync(files, rule.Apply(preset));
}
/// <summary>Everything that needs a new watcher when it changes.</summary>
private static string Signature(WatchRule rule) =>
- string.Join('|', rule.Folder, rule.PresetId, rule.IncludeSubfolders, rule.OutputFolder, rule.Originals);
+ string.Join('|', rule.Folder, rule.PresetId, rule.IncludeSubfolders, rule.OutputFolder, rule.Originals,
+ string.Join('/', rule.Include), rule.FileNamePattern,
+ string.Join('/', rule.Renames.Select(r => $"{r.Find}>{r.Replace}")));
public async ValueTask DisposeAsync()
{
diff --git a/src/Filee.App/ViewModels/Pages/RenameRecipes.cs b/src/Filee.App/ViewModels/Pages/RenameRecipes.cs
new file mode 100644
index 00000000..4b92b00d
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/RenameRecipes.cs
@@ -0,0 +1,27 @@
+// Ready-made replacements for the names of converted files (Watch folders → More options → Replace part of the
+// name). Each one adds a step the user can edit afterwards.
+
+namespace Filee.App.ViewModels.Pages;
+
+/// <param name="TitleKey">Localization key of what it does.</param>
+/// <param name="Find">Regular expression.</param>
+/// <param name="Replace">What goes in its place; empty removes the match.</param>
+/// <param name="Example">A name it changes, shown with the result.</param>
+public sealed record RenameRecipe(string TitleKey, string Find, string Replace, string Example);
+
+public static class RenameRecipes
+{
+ public static IReadOnlyList<RenameRecipe> All { get; } =
+ [
+ new("watch.recipe.photo_number", @"^(?:IMG|DSC|PXL)_(\d+)", "Photo_$1", "IMG_0412"),
+ new("watch.recipe.drop_camera_prefix", @"^(?:IMG|DSC|PXL)_", "", "DSC_0815"),
+ new("watch.recipe.spaces", @"\s+", "_", "trip to busan"),
+ new("watch.recipe.copy_number", @"\s*\(\d+\)$", "", "report (2)"),
+ new("watch.recipe.brackets", @"\s*[\(\[][^\)\]]*[\)\]]", "", "song [remix] (live)"),
+ new("watch.recipe.leading_number", @"^\d+[\s._-]*", "", "01 - intro"),
+ new("watch.recipe.date_dashes", @"(\d{4})(\d{2})(\d{2})", "$1-$2-$3", "scan_20261011"),
+ new("watch.recipe.symbols", @"[^\w\s.-]", "", "invoice#12@acme!"),
+ new("watch.recipe.prefix", "^", "new_", "report"),
+ new("watch.recipe.suffix", "$", "_final", "report"),
+ ];
+}
diff --git a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
index 9336019d..99096937 100644
--- a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
@@ -4,8 +4,11 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
+using Filee.App.Controls;
using Filee.App.Services;
+using Filee.Core.Formats;
using Filee.Core.Localization;
+using Filee.Core.Presets;
using Filee.Core.Settings;
using Filee.Core.Watching;
@@ -65,6 +68,91 @@ public sealed partial class WatchFoldersPageViewModel : ObservableObject, IDispo
: _service.IsWatching(rule.Id) ? _loc["watch.status_watching"]
: _loc["watch.status_starting"];
+ /// <summary>
+ /// A converted file as this rule would save it, e.g. <c>scan.jpg → converted\scan.pdf</c> (a file already in the
+ /// folder when there is one), and below it what happens when the name is taken and to the original. Null when the
+ /// rule has no preset.
+ /// </summary>
+ internal (string Example, string Details)? PreviewOf(WatchRule rule)
+ {
+ if (_store.FindPreset(rule.PresetId) is not { } preset)
+ return null;
+ var folder = rule.Folder.Trim();
+ var source = SampleFile(rule) ?? Path.Combine(folder, _loc["watch.sample_file"]);
+ var extension = preset.TargetFormat switch
+ {
+ BuiltInData.SameAsSource => FormatRegistry.ExtensionOf(source),
+ FormatRegistry.Folder => "",
+ var id => FormatRegistry.FindById(id)?.PrimaryExtension ?? id,
+ };
+ var applied = rule.Apply(preset);
+ var output = OutputPathResolver.Resolve(applied.Output,
+ new OutputPathResolver.Tokens(source, _loc.DisplayName(preset), 1, DateTime.Now), extension, _ => false) ?? "";
+ var shown = folder.Length > 0 && output.StartsWith(Path.TrimEndingDirectorySeparator(folder) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
+ ? Path.GetRelativePath(folder, output)
+ : output;
+ var details = $"{_loc["presets.conflict"]}: {_loc[$"presets.conflict.{preset.Output.Conflict}"]} · "
+ + _loc[rule.Originals == AfterConversion.MoveToOriginals ? "watch.preview_move" : "watch.preview_keep"];
+ return ($"{Path.GetFileName(source)} → {shown}", details);
+ }
+
+ /// <summary>The pattern a rule without its own file name rule uses: the preset's.</summary>
+ internal string PresetNamePattern(WatchRule rule) =>
+ _store.FindPreset(rule.PresetId) is { } preset && !string.IsNullOrWhiteSpace(preset.Output.FileNamePattern)
+ ? preset.Output.FileNamePattern
+ : "{name}";
+
+ internal string Format(string key, params object[] args) => _loc.Format(key, args);
+
+ internal string Text(string key) => _loc[key];
+
+ /// <summary>Extensions starting with what is typed ("he" → *.heic, *.heif), minus the patterns already there.</summary>
+ internal static IReadOnlyList<TagSuggestion> ExtensionSuggestions(string typed, IReadOnlyCollection<string> existing)
+ {
+ var start = typed.Trim().TrimStart('*').TrimStart('.');
+ if (start.Length == 0 || start.IndexOfAny(['*', '?', '/']) >= 0)
+ return [];
+ return FormatRegistry.Known
+ .SelectMany(format => format.Extensions.Select(extension => (Extension: extension, Format: format)))
+ .Where(e => e.Extension.StartsWith(start, StringComparison.OrdinalIgnoreCase) && !e.Extension.Contains('.'))
+ .Select(e => new TagSuggestion($"*.{e.Extension}", $"*.{e.Extension}", e.Format.DisplayName))
+ .Where(s => !existing.Contains(s.Value, StringComparer.OrdinalIgnoreCase))
+ .DistinctBy(s => s.Value, StringComparer.OrdinalIgnoreCase)
+ .Take(8)
+ .ToList();
+ }
+
+ /// <summary>How many files in the folder the rule's patterns let through now; null without patterns or folder.</summary>
+ internal static int? MatchCount(WatchRule rule)
+ {
+ if (rule.Include.Count == 0 || string.IsNullOrWhiteSpace(rule.Folder) || !Directory.Exists(rule.Folder))
+ return null;
+ try
+ {
+ var option = rule.IncludeSubfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
+ return Directory.EnumerateFiles(rule.Folder, "*", option).Take(5000).Count(path => !FolderWatcher.ShouldIgnore(path, rule));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>A file in the folder this rule would convert, for the preview; null when there is none (yet).</summary>
+ private static string? SampleFile(WatchRule rule)
+ {
+ if (string.IsNullOrWhiteSpace(rule.Folder) || !Directory.Exists(rule.Folder))
+ return null;
+ try
+ {
+ return Directory.EnumerateFiles(rule.Folder).Take(200).FirstOrDefault(path => !FolderWatcher.ShouldIgnore(path, rule));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
private void OnStatusChanged(object? sender, EventArgs e)
{
foreach (var rule in Rules)
@@ -90,6 +178,14 @@ public sealed partial class WatchRuleViewModel : ObservableObject
_outputFolder = rule.OutputFolder;
_originals = page.OriginalsChoices.First(c => c.Value == rule.Originals);
_status = page.StatusOf(rule);
+ _fileNamePattern = rule.FileNamePattern;
+ foreach (var step in rule.Renames)
+ RenameSteps.Add(new RenameStepViewModel(step, this));
+ Recipes = RenameRecipes.All.Select(r => new RenameRecipeViewModel(r, page.Text(r.TitleKey), page.Text("watch.recipe_removes"), this)).ToList();
+ // Options in use stay in view; a new rule starts with them folded away.
+ _showOptions = rule.Include.Count > 0 || rule.FileNamePattern.Length > 0 || rule.Renames.Count > 0;
+ RefreshIncludeTags();
+ RefreshPreview();
}
public WatchRule Rule { get; }
@@ -104,12 +200,107 @@ public sealed partial class WatchRuleViewModel : ObservableObject
[ObservableProperty] private Choice<AfterConversion> _originals;
[ObservableProperty] private string _status;
+ // Optional settings ("More options"): empty means every file, named as the preset says.
+
+ [ObservableProperty] private bool _showOptions;
+
+ /// <summary>The "Files to convert" patterns as chips.</summary>
+ [ObservableProperty] private IReadOnlyList<TagChip> _includeTags = [];
+ [ObservableProperty] private IReadOnlyList<TagSuggestion> _includeSuggestions = [];
+ [ObservableProperty] private string _includeText = "";
+
+ /// <summary>Why the typed pattern wasn't added, or null.</summary>
+ [ObservableProperty] private string? _includeError;
+
+ /// <summary>"3 files in the folder match now", or null.</summary>
+ [ObservableProperty] private string? _includeMatches;
+
+ [ObservableProperty] private string _fileNamePattern;
+
+ /// <summary>"Same as the preset: {name}" in the empty file name box.</summary>
+ [ObservableProperty] private string _fileNamePlaceholder = "";
+
+ /// <summary>Replacements applied in order to the name.</summary>
+ public ObservableCollection<RenameStepViewModel> RenameSteps { get; } = [];
+
+ /// <summary>Ready-made replacements, each with what it does to an example name.</summary>
+ public IReadOnlyList<RenameRecipeViewModel> Recipes { get; }
+
+ [ObservableProperty] private bool _showRecipes;
+
+ /// <summary>"scan.jpg → converted\scan.pdf": a converted file as it would be saved.</summary>
+ [ObservableProperty] private string? _previewExample;
+
+ /// <summary>What happens when the name is taken, and to the original.</summary>
+ [ObservableProperty] private string? _previewDetails;
+
+ public bool HasPreview => PreviewExample is not null;
+
partial void OnEnabledChanged(bool value) => Change(r => r.Enabled = value);
partial void OnFolderChanged(string value) => Change(r => r.Folder = value.Trim());
partial void OnPresetChanged(Choice<string>? value) => Change(r => r.PresetId = value?.Value ?? "");
partial void OnIncludeSubfoldersChanged(bool value) => Change(r => r.IncludeSubfolders = value);
partial void OnOutputFolderChanged(string value) => Change(r => r.OutputFolder = value.Trim());
partial void OnOriginalsChanged(Choice<AfterConversion> value) => Change(r => r.Originals = value.Value);
+ partial void OnFileNamePatternChanged(string value) => Change(r => r.FileNamePattern = value.Trim());
+
+ partial void OnIncludeTextChanged(string value)
+ {
+ IncludeError = null;
+ IncludeSuggestions = WatchFoldersPageViewModel.ExtensionSuggestions(value, Rule.Include);
+ }
+
+ [RelayCommand]
+ private void ToggleOptions() => ShowOptions = !ShowOptions;
+
+ [RelayCommand]
+ private void ToggleRecipes() => ShowRecipes = !ShowRecipes;
+
+ /// <summary>Adds a typed pattern: "heic" becomes *.heic, plain text matches names containing it.</summary>
+ [RelayCommand]
+ private void AddInclude(string? typed)
+ {
+ var pattern = FileNameFilter.Normalize(typed);
+ if (pattern is null)
+ return;
+ if (FileNameFilter.Validate(pattern) is { } error)
+ {
+ IncludeText = typed!.Trim(); // kept, so the mistake can be fixed
+ IncludeError = _page.Format("watch.invalid_regex", error);
+ return;
+ }
+ IncludeText = "";
+ if (!Rule.Include.Contains(pattern, StringComparer.OrdinalIgnoreCase))
+ Change(r => r.Include.Add(pattern));
+ }
+
+ [RelayCommand]
+ private void RemoveInclude(TagChip? chip)
+ {
+ if (chip is not null)
+ Change(r => r.Include.RemoveAll(p => p == chip.Value));
+ }
+
+ [RelayCommand]
+ private void AddStep() => AddStep(new RenameStep());
+
+ internal void AddStep(RenameStep step)
+ {
+ Rule.Renames.Add(step);
+ RenameSteps.Add(new RenameStepViewModel(step, this));
+ StepsChanged();
+ }
+
+ internal void RemoveStep(RenameStepViewModel step)
+ {
+ Rule.Renames.Remove(step.Step);
+ RenameSteps.Remove(step);
+ StepsChanged();
+ }
+
+ internal void StepsChanged() => Change(_ => { });
+
+ internal string InvalidRegex(string error) => _page.Format("watch.invalid_regex", error);
[RelayCommand]
private void Remove() => _page.Remove(this);
@@ -121,5 +312,79 @@ public sealed partial class WatchRuleViewModel : ObservableObject
change(Rule);
_page.Save();
RefreshStatus();
+ RefreshIncludeTags();
+ RefreshPreview();
+ }
+
+ private void RefreshIncludeTags()
+ {
+ IncludeTags = Rule.Include.Select(p => new TagChip(p, p)).ToList();
+ IncludeMatches = WatchFoldersPageViewModel.MatchCount(Rule) is { } count ? _page.Format("watch.include_matches", count) : null;
+ }
+
+ private void RefreshPreview()
+ {
+ FileNamePlaceholder = _page.Format("watch.name_placeholder", _page.PresetNamePattern(Rule));
+ var preview = _page.PreviewOf(Rule);
+ PreviewExample = preview?.Example;
+ PreviewDetails = preview?.Details;
+ OnPropertyChanged(nameof(HasPreview));
+ }
+}
+
+/// <summary>One replacement in a watch folder's names: a regular expression and what goes in its place.</summary>
+public sealed partial class RenameStepViewModel : ObservableObject
+{
+ private readonly WatchRuleViewModel _rule;
+
+ public RenameStepViewModel(RenameStep step, WatchRuleViewModel rule)
+ {
+ Step = step;
+ _rule = rule;
+ _find = step.Find;
+ _replace = step.Replace;
+ Validate();
+ }
+
+ public RenameStep Step { get; }
+
+ [ObservableProperty] private string _find;
+ [ObservableProperty] private string _replace;
+
+ /// <summary>Why <see cref="Find"/> is not a valid regular expression, or null.</summary>
+ [ObservableProperty] private string? _error;
+
+ partial void OnFindChanged(string value)
+ {
+ Step.Find = value;
+ Validate();
+ _rule.StepsChanged();
+ }
+
+ partial void OnReplaceChanged(string value)
+ {
+ Step.Replace = value;
+ _rule.StepsChanged();
}
+
+ [RelayCommand]
+ private void Remove() => _rule.RemoveStep(this);
+
+ private void Validate() => Error = OutputPathResolver.RenameError(Find) is { } error ? _rule.InvalidRegex(error) : null;
+}
+
+/// <summary>A ready-made replacement in the list: what it does, its expression and an example.</summary>
+public sealed partial class RenameRecipeViewModel(RenameRecipe recipe, string title, string removes, WatchRuleViewModel rule) : ObservableObject
+{
+ public string Title { get; } = title;
+
+ /// <summary>"IMG_(\d+) → Photo_$1"; an empty replacement shows as "(removed)".</summary>
+ public string Expression { get; } = $"{recipe.Find} → {(recipe.Replace.Length == 0 ? removes : recipe.Replace)}";
+
+ /// <summary>"IMG_0412 → Photo_0412".</summary>
+ public string Example { get; } = $"{recipe.Example} → {OutputPathResolver.Rename(recipe.Example, recipe.Find, recipe.Replace)}";
+
+ /// <summary>Adds the replacement as the last step (double-click, or the + button).</summary>
+ [RelayCommand]
+ private void Add() => rule.AddStep(new RenameStep { Find = recipe.Find, Replace = recipe.Replace });
}
diff --git a/src/Filee.App/Views/Pages/WatchFoldersPage.axaml b/src/Filee.App/Views/Pages/WatchFoldersPage.axaml
index 6eeb100a..f1c24bd6 100644
--- a/src/Filee.App/Views/Pages/WatchFoldersPage.axaml
+++ b/src/Filee.App/Views/Pages/WatchFoldersPage.axaml
@@ -1,8 +1,20 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:Filee.App.ViewModels.Pages"
+ xmlns:c="using:Filee.App.Controls"
x:Class="Filee.App.Views.Pages.WatchFoldersPage"
x:DataType="vm:WatchFoldersPageViewModel">
+ <UserControl.Styles>
+ <Style Selector="Border.recipe:pointerover">
+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />
+ </Style>
+ <Style Selector="PathIcon.chevron">
+ <Setter Property="RenderTransform" Value="rotate(0deg)" />
+ </Style>
+ <Style Selector="PathIcon.chevron.open">
+ <Setter Property="RenderTransform" Value="rotate(90deg)" />
+ </Style>
+ </UserControl.Styles>
<StackPanel Spacing="18">
<TextBlock Classes="h1" Text="{DynamicResource watch.title}" />
<TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource watch.description}" />
@@ -63,6 +75,105 @@
</StackPanel>
<CheckBox Content="{DynamicResource watch.subfolders}" IsChecked="{Binding IncludeSubfolders}" />
+
+ <!-- Optional: which files, and how converted files are named. Empty fields change nothing. -->
+ <Button Classes="ghost" Command="{Binding ToggleOptionsCommand}" Padding="6,4" HorizontalAlignment="Left">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Classes="chevron" Classes.open="{Binding ShowOptions}" Width="12" Height="12" Data="{StaticResource Icon.ChevronRight}" />
+ <TextBlock Text="{DynamicResource watch.options}" />
+ </StackPanel>
+ </Button>
+ <StackPanel Spacing="12" IsVisible="{Binding ShowOptions}" Margin="8,0,0,0">
+ <StackPanel Spacing="4">
+ <TextBlock Classes="label" Text="{DynamicResource watch.include}" />
+ <!-- Only ";" separates: patterns and regular expressions may contain spaces and commas -->
+ <c:TagEditor Tags="{Binding IncludeTags}" Suggestions="{Binding IncludeSuggestions}" Text="{Binding IncludeText}"
+ AddCommand="{Binding AddIncludeCommand}" RemoveCommand="{Binding RemoveIncludeCommand}"
+ Separators=";" PlaceholderText="{DynamicResource watch.include_placeholder}" />
+ <TextBlock Classes="caption danger" Text="{Binding IncludeError}" TextWrapping="Wrap" IsVisible="{Binding IncludeError, Converter={x:Static ObjectConverters.IsNotNull}}" />
+ <TextBlock Classes="caption" Text="{Binding IncludeMatches}" TextWrapping="Wrap" IsVisible="{Binding IncludeMatches, Converter={x:Static ObjectConverters.IsNotNull}}" />
+ <TextBlock Classes="caption" Text="{DynamicResource watch.include_hint}" TextWrapping="Wrap" />
+ </StackPanel>
+ <StackPanel Spacing="4">
+ <TextBlock Classes="label" Text="{DynamicResource watch.name}" />
+ <TextBox Text="{Binding FileNamePattern}" PlaceholderText="{Binding FileNamePlaceholder}" />
+ <TextBlock Classes="caption" Text="{DynamicResource watch.name_hint}" TextWrapping="Wrap" />
+ </StackPanel>
+ <StackPanel Spacing="4">
+ <TextBlock Classes="label" Text="{DynamicResource watch.rename}" />
+ <!-- The steps, applied in order -->
+ <ItemsControl ItemsSource="{Binding RenameSteps}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="6" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:RenameStepViewModel">
+ <StackPanel Spacing="2">
+ <Grid ColumnDefinitions="*,Auto,*,Auto">
+ <TextBox Text="{Binding Find}" PlaceholderText="{DynamicResource watch.rename_find}" />
+ <TextBlock Grid.Column="1" Classes="muted" Text="→" Margin="8,0" VerticalAlignment="Center" />
+ <TextBox Grid.Column="2" Text="{Binding Replace}" PlaceholderText="{DynamicResource watch.rename_replace}" />
+ <Button Grid.Column="3" Classes="icon" Margin="6,0,0,0" Command="{Binding RemoveCommand}" ToolTip.Tip="{DynamicResource watch.remove_step}">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Close}" />
+ </Button>
+ </Grid>
+ <TextBlock Classes="caption danger" Text="{Binding Error}" TextWrapping="Wrap" IsVisible="{Binding Error, Converter={x:Static ObjectConverters.IsNotNull}}" />
+ </StackPanel>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ <StackPanel Orientation="Horizontal" Spacing="8">
+ <Button Command="{Binding AddStepCommand}" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />
+ <TextBlock Text="{DynamicResource watch.add_step}" />
+ </StackPanel>
+ </Button>
+ <Button Classes="ghost" Command="{Binding ToggleRecipesCommand}" Padding="6,4">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Classes="chevron" Classes.open="{Binding ShowRecipes}" Width="12" Height="12" Data="{StaticResource Icon.ChevronRight}" />
+ <TextBlock Text="{DynamicResource watch.recipes}" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
+
+ <!-- Ready-made replacements: what each does to an example; double-click or + adds it as a step -->
+ <StackPanel Spacing="4" IsVisible="{Binding ShowRecipes}">
+ <TextBlock Classes="caption" Text="{DynamicResource watch.recipes_hint}" TextWrapping="Wrap" />
+ <Border BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" CornerRadius="8" ClipToBounds="True">
+ <ItemsControl ItemsSource="{Binding Recipes}">
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:RenameRecipeViewModel">
+ <Border Classes="recipe" Padding="10,6" Background="Transparent" DoubleTapped="OnRecipeDoubleTapped">
+ <Grid ColumnDefinitions="*,*,Auto">
+ <StackPanel VerticalAlignment="Center">
+ <TextBlock FontWeight="SemiBold" Text="{Binding Title}" TextWrapping="Wrap" />
+ <TextBlock Classes="caption" FontFamily="Consolas, Menlo, monospace" Text="{Binding Expression}" TextWrapping="Wrap" />
+ </StackPanel>
+ <TextBlock Grid.Column="1" Classes="caption" Text="{Binding Example}" TextWrapping="Wrap" VerticalAlignment="Center" Margin="12,0" />
+ <Button Grid.Column="2" Classes="icon" Command="{Binding AddCommand}" ToolTip.Tip="{DynamicResource watch.recipe_add}" VerticalAlignment="Center">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />
+ </Button>
+ </Grid>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ </Border>
+ </StackPanel>
+ </StackPanel>
+ </StackPanel>
+
+ <!-- A converted file as it would be saved -->
+ <Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="8" Padding="12,10" IsVisible="{Binding HasPreview}">
+ <StackPanel Spacing="4">
+ <TextBlock Classes="label" Text="{DynamicResource watch.preview}" />
+ <SelectableTextBlock FontWeight="SemiBold" Text="{Binding PreviewExample}" TextWrapping="Wrap" />
+ <TextBlock Classes="caption" Text="{Binding PreviewDetails}" TextWrapping="Wrap" />
+ </StackPanel>
+ </Border>
</StackPanel>
</Border>
</DataTemplate>
diff --git a/src/Filee.App/Views/Pages/WatchFoldersPage.axaml.cs b/src/Filee.App/Views/Pages/WatchFoldersPage.axaml.cs
index 34363852..a67a06f5 100644
--- a/src/Filee.App/Views/Pages/WatchFoldersPage.axaml.cs
+++ b/src/Filee.App/Views/Pages/WatchFoldersPage.axaml.cs
@@ -1,4 +1,5 @@
using Avalonia.Controls;
+using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using Filee.App.ViewModels.Pages;
@@ -21,6 +22,13 @@ public partial class WatchFoldersPage : UserControl
rule.OutputFolder = path;
}
+ /// <summary>Double-clicking a ready-made replacement adds it as a step, like its + button.</summary>
+ private void OnRecipeDoubleTapped(object? sender, TappedEventArgs e)
+ {
+ if ((sender as Control)?.DataContext is RenameRecipeViewModel recipe)
+ recipe.AddCommand.Execute(null);
+ }
+
private async Task<string?> PickFolderAsync()
{
if (TopLevel.GetTopLevel(this) is not { } top)
diff --git a/src/Filee.Core/Presets/OutputPathResolver.cs b/src/Filee.Core/Presets/OutputPathResolver.cs
index 6741efdc..922c3fba 100644
--- a/src/Filee.Core/Presets/OutputPathResolver.cs
+++ b/src/Filee.Core/Presets/OutputPathResolver.cs
@@ -1,6 +1,7 @@
// Turns an OutputRule + source file into the concrete output path. Pure logic, unit tested.
using System.Text;
+using System.Text.RegularExpressions;
using Filee.Core.Formats;
namespace Filee.Core.Presets;
@@ -32,7 +33,7 @@ public static class OutputPathResolver
};
var sourceName = FormatRegistry.NameWithoutExtension(tokens.SourcePath);
- var name = Sanitize(ExpandPattern(rule.FileNamePattern, tokens), sourceName) + suffix;
+ var name = Sanitize(Rename(ExpandPattern(rule.FileNamePattern, tokens), rule.Renames), sourceName) + suffix;
var ext = targetExtension.TrimStart('.');
string PathFor(string baseName) => Path.Combine(dir, ext.Length == 0 ? baseName : $"{baseName}.{ext}");
var candidate = PathFor(name);
@@ -55,6 +56,44 @@ public static class OutputPathResolver
}
}
+ /// <summary>Applies <paramref name="steps"/> to <paramref name="name"/> in order.</summary>
+ public static string Rename(string name, IEnumerable<RenameStep> steps) =>
+ steps.Aggregate(name, (current, step) => Rename(current, step.Find, step.Replace));
+
+ /// <summary>
+ /// Replaces the regular expression <paramref name="find"/> in <paramref name="name"/>. A pattern that isn't valid
+ /// (see <see cref="RenameError"/>) or runs too long leaves the name as it is.
+ /// </summary>
+ public static string Rename(string name, string? find, string? replace)
+ {
+ if (string.IsNullOrEmpty(find))
+ return name;
+ try
+ {
+ return Regex.Replace(name, find, replace ?? "", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(250));
+ }
+ catch (Exception ex) when (ex is ArgumentException or RegexMatchTimeoutException)
+ {
+ return name;
+ }
+ }
+
+ /// <summary>Why <paramref name="find"/> is not a valid regular expression, or null.</summary>
+ public static string? RenameError(string? find)
+ {
+ if (string.IsNullOrEmpty(find))
+ return null;
+ try
+ {
+ _ = new Regex(find, RegexOptions.CultureInvariant);
+ return null;
+ }
+ catch (ArgumentException ex)
+ {
+ return ex.Message;
+ }
+ }
+
/// <summary>Replaces <c>{token}</c> placeholders in a file name pattern.</summary>
public static string ExpandPattern(string pattern, Tokens tokens)
{
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
index 564e8e89..65304f2e 100644
--- a/src/Filee.Core/Presets/OutputRule.cs
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -45,6 +45,9 @@ public sealed class OutputRule
/// </summary>
public string FileNamePattern { get; set; } = "{name}";
+ /// <summary>Replacements applied in order to the name made from <see cref="FileNamePattern"/>.</summary>
+ public List<RenameStep> Renames { get; set; } = [];
+
public ConflictPolicy Conflict { get; set; } = ConflictPolicy.Rename;
/// <summary>
@@ -53,5 +56,21 @@ public sealed class OutputRule
/// </summary>
public bool KeepDates { get; set; }
- public OutputRule Clone() => (OutputRule)MemberwiseClone();
+ public OutputRule Clone()
+ {
+ var clone = (OutputRule)MemberwiseClone();
+ clone.Renames = Renames.Select(r => r.Clone()).ToList();
+ return clone;
+ }
+}
+
+/// <summary>A regular expression replaced in a file name, e.g. <c>IMG_(\d+)</c> → <c>Photo_$1</c>.</summary>
+public sealed class RenameStep
+{
+ public string Find { get; set; } = "";
+
+ /// <summary>What <see cref="Find"/> is replaced with; <c>$1</c> inserts the first group.</summary>
+ public string Replace { get; set; } = "";
+
+ public RenameStep Clone() => (RenameStep)MemberwiseClone();
}
diff --git a/src/Filee.Core/Watching/FileNameFilter.cs b/src/Filee.Core/Watching/FileNameFilter.cs
new file mode 100644
index 00000000..f91f9275
--- /dev/null
+++ b/src/Filee.Core/Watching/FileNameFilter.cs
@@ -0,0 +1,118 @@
+// Which files of a watch folder are converted: patterns such as "*.heic" and "scan_*", or a regular expression
+// between slashes ("/^IMG_\d+/"). A file matching any pattern is converted; no patterns means every file.
+
+using System.Collections.Concurrent;
+using System.Text;
+using System.Text.RegularExpressions;
+using Filee.Core.Formats;
+
+namespace Filee.Core.Watching;
+
+/// <summary>A file name filter of a watch folder. An empty filter lets every file through.</summary>
+public sealed class FileNameFilter
+{
+ private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(250);
+ private static readonly ConcurrentDictionary<string, FileNameFilter> Cache = new();
+ private readonly Regex[] _patterns;
+
+ private FileNameFilter(Regex[] patterns) => _patterns = patterns;
+
+ /// <summary>Lets every file through.</summary>
+ public static FileNameFilter All { get; } = new([]);
+
+ /// <summary>
+ /// Turns what someone typed into a pattern: an extension (<c>heic</c>, <c>.heic</c>) becomes <c>*.heic</c>, text
+ /// without <c>*</c> or <c>?</c> matches names containing it (<c>scan</c> → <c>*scan*</c>), and a pattern or a
+ /// /regular expression/ stays as it is. Null for blank input.
+ /// </summary>
+ public static string? Normalize(string? typed)
+ {
+ var text = typed?.Trim();
+ if (string.IsNullOrEmpty(text))
+ return null;
+ if (IsRegex(text) || text.Contains('*') || text.Contains('?'))
+ return text;
+ var extension = text.TrimStart('.');
+ if (extension.Length > 0 && FormatRegistry.FindByExtension(extension) is not null && !extension.Contains('.'))
+ return $"*.{extension.ToLowerInvariant()}";
+ return $"*{text}*";
+ }
+
+ /// <summary>Why a pattern can't be used (a regular expression that isn't valid), or null.</summary>
+ public static string? Validate(string pattern)
+ {
+ try
+ {
+ _ = ToRegex(pattern);
+ return null;
+ }
+ catch (ArgumentException ex)
+ {
+ return ex.Message;
+ }
+ }
+
+ /// <summary>
+ /// The filter of <paramref name="patterns"/>: <c>*</c> stands for any text, <c>?</c> for one character, and a
+ /// pattern between slashes is a regular expression. Case is ignored. Patterns that aren't valid are skipped.
+ /// </summary>
+ public static FileNameFilter Of(IReadOnlyCollection<string>? patterns)
+ {
+ if (patterns is null || patterns.Count == 0)
+ return All;
+ return Cache.GetOrAdd(string.Join('\n', patterns), _ =>
+ {
+ var regexes = new List<Regex>();
+ foreach (var pattern in patterns)
+ {
+ try
+ {
+ regexes.Add(ToRegex(pattern));
+ }
+ catch (ArgumentException)
+ {
+ // checked when the pattern was added; one edited by hand in settings.json is left out
+ }
+ }
+ return regexes.Count == 0 ? All : new FileNameFilter([.. regexes]);
+ });
+ }
+
+ /// <summary>True when the file name (without folder) matches one of the patterns.</summary>
+ public bool Matches(string fileName)
+ {
+ if (_patterns.Length == 0)
+ return true;
+ foreach (var pattern in _patterns)
+ {
+ try
+ {
+ if (pattern.IsMatch(fileName))
+ return true;
+ }
+ catch (RegexMatchTimeoutException)
+ {
+ // a pattern that takes this long on one name is treated as no match
+ }
+ }
+ return false;
+ }
+
+ private static bool IsRegex(string pattern) => pattern.Length > 2 && pattern.StartsWith('/') && pattern.EndsWith('/');
+
+ private static Regex ToRegex(string pattern) =>
+ new(IsRegex(pattern) ? pattern[1..^1] : FromWildcards(pattern), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, Timeout);
+
+ private static string FromWildcards(string pattern)
+ {
+ var regex = new StringBuilder("^");
+ foreach (var c in pattern.Trim())
+ regex.Append(c switch
+ {
+ '*' => ".*",
+ '?' => ".",
+ _ => Regex.Escape(c.ToString()),
+ });
+ return regex.Append('$').ToString();
+ }
+}
diff --git a/src/Filee.Core/Watching/FolderWatcher.cs b/src/Filee.Core/Watching/FolderWatcher.cs
index 2ef23c4d..20de9630 100644
--- a/src/Filee.Core/Watching/FolderWatcher.cs
+++ b/src/Filee.Core/Watching/FolderWatcher.cs
@@ -176,7 +176,7 @@ public sealed class FolderWatcher : IAsyncDisposable
}
/// <summary>True for files a watch folder never converts: temporary, hidden or system files, unknown formats,
- /// and anything inside the output or originals folder.</summary>
+ /// anything inside the output or originals folder, and names the rule's <see cref="WatchRule.Include"/> leaves out.</summary>
public static bool ShouldIgnore(string path, WatchRule rule)
{
var name = Path.GetFileName(path);
@@ -189,6 +189,8 @@ public sealed class FolderWatcher : IAsyncDisposable
return true;
if (FormatRegistry.Detect(path) is null)
return true;
+ if (!FileNameFilter.Of(rule.Include).Matches(name))
+ return true;
try
{
var attributes = File.GetAttributes(path);
diff --git a/src/Filee.Core/Watching/WatchRule.cs b/src/Filee.Core/Watching/WatchRule.cs
index ab49a6e6..37f096e1 100644
--- a/src/Filee.Core/Watching/WatchRule.cs
+++ b/src/Filee.Core/Watching/WatchRule.cs
@@ -1,6 +1,8 @@
// A watch folder: files that land in the folder are converted with a preset (Settings → Watch folders, or
// "filee watch" on the command line).
+using Filee.Core.Presets;
+
namespace Filee.Core.Watching;
/// <summary>What happens to a source file once it was converted.</summary>
@@ -38,6 +40,17 @@ public sealed class WatchRule
public AfterConversion Originals { get; set; } = AfterConversion.Keep;
+ // Optional: empty means every file, and names as the preset gives them.
+
+ /// <summary>Which files are converted (<see cref="FileNameFilter"/>), e.g. <c>*.heic</c> and <c>scan_*</c>; empty for all.</summary>
+ public List<string> Include { get; set; } = [];
+
+ /// <summary>File name pattern of converted files (tokens as in <see cref="OutputRule.FileNamePattern"/>); empty for the preset's.</summary>
+ public string FileNamePattern { get; set; } = "";
+
+ /// <summary>Replacements applied in order to the names of converted files (<see cref="OutputRule.Renames"/>).</summary>
+ public List<RenameStep> Renames { get; set; } = [];
+
/// <summary>The output folder actually used.</summary>
public string ResolvedOutputFolder =>
string.IsNullOrWhiteSpace(OutputFolder) ? Path.Combine(Folder, DefaultOutputName) : OutputFolder;
@@ -45,5 +58,27 @@ public sealed class WatchRule
/// <summary>Where converted sources go with <see cref="AfterConversion.MoveToOriginals"/>.</summary>
public string OriginalsFolder => Path.Combine(Folder, OriginalsName);
- public WatchRule Clone() => (WatchRule)MemberwiseClone();
+ /// <summary>
+ /// The preset as this folder converts with it: output into <see cref="ResolvedOutputFolder"/>, and the folder's
+ /// own name rules where set.
+ /// </summary>
+ public Preset Apply(Preset preset)
+ {
+ var applied = preset.Clone();
+ applied.Output.Location = OutputLocation.CustomFolder;
+ applied.Output.CustomFolder = ResolvedOutputFolder;
+ if (!string.IsNullOrWhiteSpace(FileNamePattern))
+ applied.Output.FileNamePattern = FileNamePattern.Trim();
+ // Steps without a pattern are being typed; leaving them out keeps the name as it is.
+ applied.Output.Renames.AddRange(Renames.Where(r => r.Find.Length > 0).Select(r => r.Clone()));
+ return applied;
+ }
+
+ public WatchRule Clone()
+ {
+ var clone = (WatchRule)MemberwiseClone();
+ clone.Include = [.. Include];
+ clone.Renames = Renames.Select(r => r.Clone()).ToList();
+ return clone;
+ }
}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index cdb3e26c..68392eea 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -65,6 +65,9 @@ public class RenderTests
var item = Assert.Single(page.Rules);
Assert.Equal("to-pdf", item.Preset?.Value);
Assert.False(string.IsNullOrWhiteSpace(item.Status));
+ Assert.EndsWith(Path.Combine("converted", Path.ChangeExtension(AppHost.Get<Filee.Core.Localization.ILocalizer>()["watch.sample_file"], "pdf")),
+ item.PreviewExample); // where a converted file goes and what it is called
+ Assert.False(item.ShowOptions); // the optional settings stay folded until used
Save(window, $"page-watch-{language}.png");
window.Close();
}
@@ -74,6 +77,69 @@ public class RenderTests
}
}
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ public void Watch_folder_options_rename_and_filter_with_a_preview(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var store = AppHost.Get<Filee.Core.Settings.UserDataStore>();
+ var folder = Directory.CreateTempSubdirectory("filee-watch-").FullName;
+ File.WriteAllBytes(Path.Combine(folder, "notes.txt"), [0x41]);
+ File.WriteAllBytes(Path.Combine(folder, "IMG_0412.jpg"), [0xFF, 0xD8]);
+ var rule = new Filee.Core.Watching.WatchRule
+ {
+ Folder = folder,
+ PresetId = "to-pdf",
+ Enabled = false,
+ Include = ["*.jpg"],
+ FileNamePattern = "{name}_scan",
+ };
+ store.Settings.WatchFolders.Add(rule);
+ try
+ {
+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<UpdateService>());
+ vm.Navigate("watch");
+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 1500 };
+ window.Show();
+ Pump();
+
+ var item = Assert.Single(((Filee.App.ViewModels.Pages.WatchFoldersPageViewModel)vm.CurrentPage).Rules);
+ Assert.True(item.ShowOptions); // options in use are shown
+
+ // Typed patterns become chips: an extension turns into *.ext, a broken expression is not added.
+ item.AddIncludeCommand.Execute("heic");
+ Assert.Equal(["*.jpg", "*.heic"], rule.Include);
+ item.AddIncludeCommand.Execute("/IMG_(/");
+ Assert.NotNull(item.IncludeError);
+ Assert.Equal("/IMG_(/", item.IncludeText);
+ item.IncludeText = "";
+ Assert.NotNull(item.IncludeMatches); // IMG_0412.jpg matches, notes.txt doesn't
+
+ // A ready-made replacement becomes a step; steps run in order.
+ item.Recipes[0].AddCommand.Execute(null); // camera number → Photo_number
+ Assert.Equal(@"^(?:IMG|DSC|PXL)_(\d+)", Assert.Single(rule.Renames).Find);
+ // A file already in the folder that the patterns let through, renamed by the name rule and the step.
+ Assert.Equal($"IMG_0412.jpg → {Path.Combine("converted", "Photo_0412_scan.pdf")}", item.PreviewExample);
+
+ var step = item.RenameSteps[0];
+ step.Find = "IMG_(";
+ Assert.NotNull(step.Error);
+ step.Find = @"^(?:IMG|DSC|PXL)_(\d+)";
+ Assert.Null(step.Error);
+ item.ShowRecipes = true;
+ Pump();
+ Save(window, $"page-watch-options-{language}.png");
+ window.Close();
+ }
+ finally
+ {
+ store.Settings.WatchFolders.Remove(rule);
+ store.SaveSettings(); // editing the rule saved it: the next test's application would load it again
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
[AvaloniaTheory]
[InlineData("en")]
[InlineData("ko")]
diff --git a/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs b/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs
new file mode 100644
index 00000000..cd259969
--- /dev/null
+++ b/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs
@@ -0,0 +1,110 @@
+// A watch folder's optional settings: which files it converts, and how converted files are named.
+
+using Filee.Core.Presets;
+using Filee.Core.Watching;
+
+namespace Filee.Core.Tests;
+
+public class WatchRuleOptionsTests
+{
+ [Theory]
+ [InlineData("*.heic", "IMG_0001.HEIC", true)]
+ [InlineData("*.heic", "IMG_0001.jpg", false)]
+ [InlineData("scan_??.png", "scan_12.png", true)]
+ [InlineData("scan_??.png", "scan_123.png", false)]
+ [InlineData(@"/^IMG_\d+\.jpg$/", "img_20261011.jpg", true)]
+ [InlineData(@"/^IMG_\d+\.jpg$/", "IMG_cat.jpg", false)]
+ [InlineData(@"/^report-\d{2,4}/", "report-2026 final.docx", true)]
+ public void A_pattern_lets_through_the_names_it_matches(string pattern, string name, bool matches)
+ {
+ Assert.Null(FileNameFilter.Validate(pattern));
+ Assert.Equal(matches, FileNameFilter.Of([pattern]).Matches(name));
+ }
+
+ [Fact]
+ public void A_file_matching_any_pattern_passes_and_no_patterns_let_everything_through()
+ {
+ var filter = FileNameFilter.Of(["*.heic", "scan_*"]);
+ Assert.True(filter.Matches("scan_0412.pdf"));
+ Assert.True(filter.Matches("a.heic"));
+ Assert.False(filter.Matches("notes.txt"));
+ Assert.True(FileNameFilter.Of([]).Matches("anything.pdf"));
+ }
+
+ [Theory]
+ [InlineData("heic", "*.heic")]
+ [InlineData(".HEIC", "*.heic")]
+ [InlineData("scan", "*scan*")]
+ [InlineData("scan_*", "scan_*")]
+ [InlineData(@"/^IMG_\d+/", @"/^IMG_\d+/")]
+ [InlineData(" ", null)]
+ public void What_is_typed_becomes_a_pattern(string typed, string? pattern)
+ {
+ Assert.Equal(pattern, FileNameFilter.Normalize(typed));
+ }
+
+ [Fact]
+ public void A_regular_expression_that_is_not_valid_is_reported_and_left_out()
+ {
+ Assert.NotNull(FileNameFilter.Validate("/IMG_(/"));
+ Assert.True(FileNameFilter.Of(["/IMG_(/"]).Matches("anything.jpg"));
+ }
+
+ [Fact]
+ public void Files_the_patterns_leave_out_are_not_converted()
+ {
+ using var dir = new TempDir();
+ var heic = dir.File("IMG_0001.heic");
+ var jpg = dir.File("IMG_0002.jpg");
+ var rule = new WatchRule { Folder = dir.Path, Include = ["*.heic"] };
+
+ Assert.False(FolderWatcher.ShouldIgnore(heic, rule));
+ Assert.True(FolderWatcher.ShouldIgnore(jpg, rule));
+ }
+
+ [Fact]
+ public void The_folder_name_rules_replace_the_presets_and_empty_ones_keep_them()
+ {
+ var preset = new Preset { TargetFormat = "pdf", Output = { FileNamePattern = "{name}_{preset}" } };
+ var plain = new WatchRule { Folder = Path.Combine("x", "Inbox") }.Apply(preset);
+ Assert.Equal("{name}_{preset}", plain.Output.FileNamePattern);
+ Assert.Empty(plain.Output.Renames);
+ Assert.Equal(OutputLocation.CustomFolder, plain.Output.Location);
+ Assert.Equal(Path.Combine("x", "Inbox", "converted"), plain.Output.CustomFolder);
+
+ var rule = new WatchRule
+ {
+ Folder = "Inbox",
+ FileNamePattern = "{name}_{date}",
+ Renames = [new() { Find = @"IMG_(\d+)", Replace = "Photo_$1" }, new() { Find = "", Replace = "typing" }],
+ };
+ var own = rule.Apply(preset);
+ Assert.Equal("{name}_{date}", own.Output.FileNamePattern);
+ Assert.Equal(@"IMG_(\d+)", Assert.Single(own.Output.Renames).Find); // a step still being typed is left out
+ Assert.Equal("{name}_{preset}", preset.Output.FileNamePattern); // the preset itself is not changed
+ Assert.Empty(preset.Output.Renames);
+ }
+
+ [Fact]
+ public void Rename_steps_are_applied_in_order()
+ {
+ var rule = new OutputRule
+ {
+ Location = OutputLocation.SameFolder,
+ Renames = [new() { Find = @"IMG_(\d+)", Replace = "Photo $1" }, new() { Find = @"\s+", Replace = "_" }],
+ };
+ var source = Path.Combine(Path.GetTempPath(), "IMG_0412.heic");
+
+ var path = OutputPathResolver.Resolve(rule, new OutputPathResolver.Tokens(source, "JPG", 1, DateTime.Now), "jpg", _ => false);
+
+ Assert.Equal(Path.Combine(Path.GetTempPath(), "Photo_0412.jpg"), path);
+ }
+
+ [Fact]
+ public void A_rename_pattern_that_is_not_valid_leaves_the_name_as_it_is()
+ {
+ Assert.NotNull(OutputPathResolver.RenameError("IMG_("));
+ Assert.Equal("IMG_0412", OutputPathResolver.Rename("IMG_0412", "IMG_(", "x"));
+ Assert.Null(OutputPathResolver.RenameError(""));
+ }
+}