├── image1.png ├── image2.png ├── PDF_Title_to_Filename ├── Icons │ └── app.ico ├── Services │ ├── ILanguageService.cs │ ├── IPdfProcessingService.cs │ ├── ILogService.cs │ ├── LogService.cs │ ├── PdfProcessingService.cs │ └── LanguageService.cs ├── Converters │ └── LanguageToggleConverter.cs ├── Helpers │ └── VersionHelper.cs ├── Models │ ├── PdfMetadata.cs │ ├── FileNameElement.cs │ ├── FileItem.cs │ └── FileNameSettings.cs ├── Views │ ├── SettingsWindow.xaml.cs │ ├── AboutWindow.xaml.cs │ ├── MainWindow.xaml.cs │ ├── SettingsWindow.xaml │ ├── MainWindow.xaml │ └── AboutWindow.xaml ├── ViewModels │ ├── RelayCommand.cs │ ├── AboutWindowViewModel.cs │ ├── SettingsWindowViewModel.cs │ └── MainWindowViewModel.cs ├── App.xaml ├── PDF_Title_to_Filename.csproj ├── app.manifest ├── App.xaml.cs └── Resources │ ├── Strings.jp.resx │ └── Strings.resx ├── PDF_Title_to_Filename.sln └── .gitignore /image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fa-yoshinobu/PDF_Title_to_Filename/HEAD/image1.png -------------------------------------------------------------------------------- /image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fa-yoshinobu/PDF_Title_to_Filename/HEAD/image2.png -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Icons/app.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fa-yoshinobu/PDF_Title_to_Filename/HEAD/PDF_Title_to_Filename/Icons/app.ico -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Services/ILanguageService.cs: -------------------------------------------------------------------------------- 1 | namespace PdfTitleRenamer.Services 2 | { 3 | public interface ILanguageService 4 | { 5 | string GetString(string key); 6 | void SetLanguage(string languageCode); 7 | string CurrentLanguage { get; } 8 | event EventHandler? LanguageChanged; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Services/IPdfProcessingService.cs: -------------------------------------------------------------------------------- 1 | using PdfTitleRenamer.Models; 2 | 3 | namespace PdfTitleRenamer.Services 4 | { 5 | public interface IPdfProcessingService 6 | { 7 | PdfMetadata ExtractMetadataFromPdf(string filePath); 8 | string SanitizeFileName(string fileName, bool applyNFKC = true); 9 | string GetUniqueFilePath(string filePath); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Services/ILogService.cs: -------------------------------------------------------------------------------- 1 | namespace PdfTitleRenamer.Services 2 | { 3 | public interface ILogService 4 | { 5 | void LogMessage(string message); 6 | void LogError(string message, Exception? exception = null); 7 | void LogInfo(string message); 8 | void LogWarning(string message); 9 | void LogDebug(string message); 10 | void LogVerbose(string category, string message, object? data = null); 11 | string GetLogText(); 12 | void ClearLog(); 13 | event EventHandler? LogAdded; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Converters/LanguageToggleConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | using System.IO; 5 | 6 | namespace PdfTitleRenamer.Converters 7 | { 8 | public class LanguageToggleConverter : IValueConverter 9 | { 10 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 11 | { 12 | if (value is string currentLanguageDisplay) 13 | { 14 | return currentLanguageDisplay == "Japanese" ? "en" : "ja"; 15 | } 16 | return "en"; // デフォルト 17 | } 18 | 19 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 20 | { 21 | throw new NotImplementedException(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Version 17 3 | VisualStudioVersion = 17.0.31903.59 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PDF_Title_to_Filename", "PDF_Title_to_Filename\PDF_Title_to_Filename.csproj", "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}" 6 | EndProject 7 | Global 8 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 9 | Debug|Any CPU = Debug|Any CPU 10 | Release|Any CPU = Release|Any CPU 11 | EndGlobalSection 12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 13 | {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 14 | {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.Build.0 = Debug|Any CPU 15 | {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.ActiveCfg = Release|Any CPU 16 | {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.Build.0 = Release|Any CPU 17 | EndGlobalSection 18 | EndGlobal 19 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Helpers/VersionHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace PdfTitleRenamer.Helpers 4 | { 5 | public static class VersionHelper 6 | { 7 | public static string GetVersion() 8 | { 9 | try 10 | { 11 | var version = Assembly.GetExecutingAssembly().GetName().Version; 12 | return version?.ToString() ?? "1.0.4"; 13 | } 14 | catch 15 | { 16 | return "1.0.4"; 17 | } 18 | } 19 | 20 | public static string GetFileVersion() 21 | { 22 | try 23 | { 24 | var assembly = Assembly.GetExecutingAssembly(); 25 | var fileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location); 26 | return fileVersionInfo.FileVersion ?? "1.0.4"; 27 | } 28 | catch 29 | { 30 | return "1.0.4"; 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Models/PdfMetadata.cs: -------------------------------------------------------------------------------- 1 | namespace PdfTitleRenamer.Models 2 | { 3 | public class PdfMetadata 4 | { 5 | public string Title { get; set; } = ""; 6 | public string Author { get; set; } = ""; 7 | public string Subject { get; set; } = ""; 8 | public string Keywords { get; set; } = ""; 9 | public string Creator { get; set; } = ""; 10 | public string Producer { get; set; } = ""; 11 | 12 | public bool HasAnyData => !string.IsNullOrWhiteSpace(Title) || 13 | !string.IsNullOrWhiteSpace(Author) || 14 | !string.IsNullOrWhiteSpace(Subject) || 15 | !string.IsNullOrWhiteSpace(Keywords); 16 | 17 | public override string ToString() 18 | { 19 | var parts = new List(); 20 | 21 | if (!string.IsNullOrWhiteSpace(Title)) parts.Add($"Title: {Title}"); 22 | if (!string.IsNullOrWhiteSpace(Author)) parts.Add($"Author: {Author}"); 23 | if (!string.IsNullOrWhiteSpace(Subject)) parts.Add($"Subject: {Subject}"); 24 | if (!string.IsNullOrWhiteSpace(Keywords)) parts.Add($"Keywords: {Keywords}"); 25 | 26 | return string.Join(", ", parts); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Views/SettingsWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using System.Windows.Controls; 3 | using PdfTitleRenamer.ViewModels; 4 | 5 | namespace PdfTitleRenamer.Views 6 | { 7 | public partial class SettingsWindow : Window 8 | { 9 | public SettingsWindow(SettingsWindowViewModel viewModel) 10 | { 11 | InitializeComponent(); 12 | DataContext = viewModel; 13 | 14 | // ドラッグ&ドロップイベントの設定 15 | Loaded += SettingsWindow_Loaded; 16 | 17 | // ウィンドウを閉じるイベントを購読 18 | viewModel.WindowClosed += (s, e) => Close(); 19 | } 20 | 21 | private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) 22 | { 23 | // ドラッグ&ドロップ機能は削除し、矢印ボタンのみを使用 24 | } 25 | 26 | 27 | 28 | private void CheckBox_Changed(object sender, RoutedEventArgs e) 29 | { 30 | if (sender is CheckBox checkBox) 31 | { 32 | // プレビューを更新 33 | var viewModel = DataContext as SettingsWindowViewModel; 34 | if (viewModel != null) 35 | { 36 | viewModel.UpdatePreview(); 37 | } 38 | } 39 | } 40 | 41 | private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 42 | { 43 | if (sender is TextBox textBox) 44 | { 45 | // プレビューを更新 46 | var viewModel = DataContext as SettingsWindowViewModel; 47 | if (viewModel != null) 48 | { 49 | viewModel.UpdatePreview(); 50 | } 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/ViewModels/RelayCommand.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Input; 2 | 3 | namespace PdfTitleRenamer.ViewModels 4 | { 5 | public class RelayCommand : ICommand 6 | { 7 | private readonly Action _execute; 8 | private readonly Func? _canExecute; 9 | 10 | public RelayCommand(Action execute, Func? canExecute = null) 11 | { 12 | _execute = execute ?? throw new ArgumentNullException(nameof(execute)); 13 | _canExecute = canExecute; 14 | } 15 | 16 | public event EventHandler? CanExecuteChanged; 17 | 18 | public bool CanExecute(object? parameter) 19 | { 20 | return _canExecute?.Invoke() ?? true; 21 | } 22 | 23 | public void Execute(object? parameter) 24 | { 25 | _execute(); 26 | } 27 | 28 | public void RaiseCanExecuteChanged() 29 | { 30 | CanExecuteChanged?.Invoke(this, EventArgs.Empty); 31 | } 32 | } 33 | 34 | public class RelayCommand : ICommand 35 | { 36 | private readonly Action _execute; 37 | private readonly Func? _canExecute; 38 | 39 | public RelayCommand(Action execute, Func? canExecute = null) 40 | { 41 | _execute = execute ?? throw new ArgumentNullException(nameof(execute)); 42 | _canExecute = canExecute; 43 | } 44 | 45 | public event EventHandler? CanExecuteChanged; 46 | 47 | public bool CanExecute(object? parameter) 48 | { 49 | return _canExecute?.Invoke((T?)parameter) ?? true; 50 | } 51 | 52 | public void Execute(object? parameter) 53 | { 54 | _execute((T?)parameter); 55 | } 56 | 57 | public void RaiseCanExecuteChanged() 58 | { 59 | CanExecuteChanged?.Invoke(this, EventArgs.Empty); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/App.xaml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 22 | 23 | 32 | 33 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/PDF_Title_to_Filename.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WinExe 6 | net8.0-windows 7 | true 8 | app.manifest 9 | Icons\app.ico 10 | 11 | PDF Title to Filename 12 | PDFファイルのタイトルからファイル名を自動生成するアプリケーション 13 | fa-yoshinobu 14 | PDF Title to Filename 15 | 1.0.4.0 16 | 1.0.4.0 17 | enable 18 | enable 19 | false 20 | 21 | 22 | $(DefineConstants);ENABLE_DETAILED_LOGGING 23 | 24 | 25 | true 26 | true 27 | win-x64 28 | true 29 | true 30 | true 31 | 32 | 33 | false 34 | none 35 | false 36 | false 37 | false 38 | false 39 | false 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | Strings.resx 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Models/FileNameElement.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Runtime.CompilerServices; 3 | using System.Collections.Generic; 4 | using PdfTitleRenamer.Services; 5 | 6 | namespace PdfTitleRenamer.Models 7 | { 8 | public class FileNameElement : INotifyPropertyChanged 9 | { 10 | private bool _isEnabled; 11 | private string _elementType = string.Empty; 12 | public static ILanguageService? _languageService; 13 | 14 | public FileNameElement(string elementType, bool isEnabled = true) 15 | { 16 | ElementType = elementType; 17 | IsEnabled = isEnabled; 18 | } 19 | 20 | public static void SetLanguageService(ILanguageService languageService) 21 | { 22 | _languageService = languageService; 23 | } 24 | 25 | public string ElementType 26 | { 27 | get => _elementType; 28 | set => SetProperty(ref _elementType, value); 29 | } 30 | 31 | [System.Text.Json.Serialization.JsonIgnore] 32 | public string DisplayName 33 | { 34 | get => ElementType switch 35 | { 36 | "Title" => _languageService?.GetString("PDFTitleDisplay") ?? "PDF Title", 37 | "Author" => _languageService?.GetString("PDFAuthorDisplay") ?? "PDF Author", 38 | "Subject" => _languageService?.GetString("PDFSubjectDisplay") ?? "PDF Subject", 39 | "Keywords" => _languageService?.GetString("PDFKeywordsDisplay") ?? "PDF Keywords", 40 | "OriginalFileName" => _languageService?.GetString("OriginalFileNameDisplay") ?? "Original File Name", 41 | "CustomPrefix" => _languageService?.GetString("CustomPrefixDisplay") ?? "Prefix", 42 | "CustomSuffix" => _languageService?.GetString("CustomSuffixDisplay") ?? "Suffix", 43 | _ => ElementType 44 | }; 45 | } 46 | 47 | public bool IsEnabled 48 | { 49 | get => _isEnabled; 50 | set 51 | { 52 | SetProperty(ref _isEnabled, value); 53 | } 54 | } 55 | 56 | public event PropertyChangedEventHandler? PropertyChanged; 57 | 58 | protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) 59 | { 60 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 61 | } 62 | 63 | protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null) 64 | { 65 | if (EqualityComparer.Default.Equals(field, value)) return false; 66 | field = value; 67 | OnPropertyChanged(propertyName); 68 | return true; 69 | } 70 | 71 | public override string ToString() 72 | { 73 | return DisplayName; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Services/LogService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using System.Text; 3 | 4 | namespace PdfTitleRenamer.Services 5 | { 6 | public class LogService : ILogService 7 | { 8 | private readonly ILogger _logger; 9 | private readonly StringBuilder _logBuilder = new(); 10 | private readonly object _lock = new(); 11 | 12 | public LogService(ILogger logger) 13 | { 14 | _logger = logger; 15 | } 16 | 17 | public event EventHandler? LogAdded; 18 | 19 | public void LogMessage(string message) 20 | { 21 | LogInfo(message); 22 | } 23 | 24 | public void LogError(string message, Exception? exception = null) 25 | { 26 | var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); 27 | var logMessage = $"[{timestamp}] ERROR: {message}"; 28 | 29 | if (exception != null) 30 | { 31 | logMessage += $"\n{exception}"; 32 | } 33 | 34 | AddToLog(logMessage); 35 | _logger.LogError(exception, message); 36 | } 37 | 38 | public void LogInfo(string message) 39 | { 40 | var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); 41 | var logMessage = $"[{timestamp}] INFO: {message}"; 42 | 43 | AddToLog(logMessage); 44 | _logger.LogInformation(message); 45 | } 46 | 47 | public void LogWarning(string message) 48 | { 49 | var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); 50 | var logMessage = $"[{timestamp}] WARNING: {message}"; 51 | 52 | AddToLog(logMessage); 53 | _logger.LogWarning(message); 54 | } 55 | 56 | public string GetLogText() 57 | { 58 | lock (_lock) 59 | { 60 | return _logBuilder.ToString(); 61 | } 62 | } 63 | 64 | public void ClearLog() 65 | { 66 | lock (_lock) 67 | { 68 | _logBuilder.Clear(); 69 | } 70 | 71 | LogAdded?.Invoke(this, ""); 72 | } 73 | 74 | public void LogDebug(string message) 75 | { 76 | // 本番環境では詳細なデバッグログは出力しない 77 | _logger.LogDebug(message); 78 | } 79 | 80 | public void LogVerbose(string category, string message, object? data = null) 81 | { 82 | // 本番環境では詳細なVerboseログは出力しない 83 | _logger.LogTrace($"[{category}]: {message}"); 84 | } 85 | 86 | private void AddToLog(string message) 87 | { 88 | lock (_lock) 89 | { 90 | _logBuilder.AppendLine(message); 91 | } 92 | 93 | LogAdded?.Invoke(this, GetLogText()); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/app.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 55 | 56 | 57 | true 58 | PerMonitorV2 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Models/FileItem.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.ComponentModel; 3 | 4 | namespace PdfTitleRenamer.Models 5 | { 6 | public class FileItem : INotifyPropertyChanged 7 | { 8 | private string _newFileName; 9 | private string _status; 10 | private string _errorDetails; 11 | 12 | public FileItem(string filePath) 13 | { 14 | FilePath = filePath; 15 | FileName = Path.GetFileName(filePath); 16 | _newFileName = "ProcessingPending"; 17 | _status = "Waiting"; // 定数を使用する場合は、MainWindowViewModelから定数を参照する必要があります 18 | _errorDetails = ""; 19 | } 20 | 21 | 22 | 23 | public string FilePath { get; } 24 | public string FileName { get; } 25 | 26 | public string NewFileName 27 | { 28 | get => _newFileName; 29 | set 30 | { 31 | _newFileName = value; 32 | OnPropertyChanged(nameof(NewFileName)); 33 | OnPropertyChanged(nameof(NewFileNameDisplay)); 34 | } 35 | } 36 | 37 | // 表示用のファイル名(ローカライズ対応) 38 | public string NewFileNameDisplay 39 | { 40 | get 41 | { 42 | if (FileNameElement._languageService != null) 43 | { 44 | return FileNameElement._languageService.GetString(_newFileName) ?? _newFileName; 45 | } 46 | return _newFileName; 47 | } 48 | } 49 | 50 | public string Status 51 | { 52 | get => _status; 53 | set 54 | { 55 | _status = value; 56 | OnPropertyChanged(nameof(Status)); 57 | OnPropertyChanged(nameof(StatusDisplay)); 58 | } 59 | } 60 | 61 | public string ErrorDetails 62 | { 63 | get => _errorDetails; 64 | set 65 | { 66 | _errorDetails = value; 67 | OnPropertyChanged(nameof(ErrorDetails)); 68 | } 69 | } 70 | 71 | // 表示用の状態文字列(ローカライズ対応) 72 | public string StatusDisplay 73 | { 74 | get 75 | { 76 | if (FileNameElement._languageService != null) 77 | { 78 | return FileNameElement._languageService.GetString(Status) ?? Status; 79 | } 80 | return Status; 81 | } 82 | } 83 | 84 | public event PropertyChangedEventHandler? PropertyChanged; 85 | 86 | protected virtual void OnPropertyChanged(string propertyName) 87 | { 88 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 89 | } 90 | 91 | // 言語変更時にStatusDisplayとNewFileNameDisplayを更新するための公開メソッド 92 | public void UpdateStatusDisplay() 93 | { 94 | OnPropertyChanged(nameof(StatusDisplay)); 95 | OnPropertyChanged(nameof(NewFileNameDisplay)); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Views/AboutWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using System.Diagnostics; 3 | using PdfTitleRenamer.Helpers; 4 | using PdfTitleRenamer.ViewModels; 5 | using PdfTitleRenamer.Services; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace PdfTitleRenamer.Views 9 | { 10 | /// 11 | /// AboutWindow.xaml の相互作用ロジック 12 | /// 13 | public partial class AboutWindow : Window 14 | { 15 | private readonly ILanguageService _languageService; 16 | 17 | public AboutWindow() 18 | { 19 | InitializeComponent(); 20 | 21 | // ViewModelを設定 22 | _languageService = GetLanguageService(); 23 | DataContext = new AboutWindowViewModel(_languageService); 24 | 25 | SetVersionInfo(); 26 | } 27 | 28 | public AboutWindow(Window owner) 29 | { 30 | InitializeComponent(); 31 | Owner = owner; 32 | 33 | // ViewModelを設定 34 | _languageService = GetLanguageService(); 35 | DataContext = new AboutWindowViewModel(_languageService); 36 | 37 | SetVersionInfo(); 38 | } 39 | 40 | private ILanguageService GetLanguageService() 41 | { 42 | try 43 | { 44 | if (App.Current is App app && app.Services != null) 45 | { 46 | return app.Services.GetService() ?? new LanguageService(); 47 | } 48 | } 49 | catch 50 | { 51 | // エラーが発生した場合はデフォルトのLanguageServiceを作成 52 | } 53 | 54 | return new LanguageService(); 55 | } 56 | 57 | private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e) 58 | { 59 | try 60 | { 61 | Process.Start(new ProcessStartInfo 62 | { 63 | FileName = e.Uri.ToString(), 64 | UseShellExecute = true 65 | }); 66 | e.Handled = true; 67 | } 68 | catch 69 | { 70 | // エラーが発生した場合は何もしない 71 | } 72 | } 73 | 74 | private void SetVersionInfo() 75 | { 76 | try 77 | { 78 | var version = VersionHelper.GetVersion(); 79 | var fileVersion = VersionHelper.GetFileVersion(); 80 | 81 | // バージョン情報をUIに設定 82 | if (VersionTextBlock != null) 83 | { 84 | VersionTextBlock.Text = $"{_languageService?.GetString("VersionPrefix") ?? "Version"} {version}"; 85 | } 86 | 87 | if (VersionDetailTextBlock != null) 88 | { 89 | VersionDetailTextBlock.Text = version; 90 | } 91 | } 92 | catch 93 | { 94 | // エラーが発生した場合はデフォルト値を設定 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Logging; 3 | using PdfTitleRenamer.Services; 4 | using PdfTitleRenamer.ViewModels; 5 | using System.Windows; 6 | using System; 7 | using System.Windows.Threading; 8 | 9 | namespace PdfTitleRenamer 10 | { 11 | public partial class App : Application 12 | { 13 | private ServiceProvider? _serviceProvider; 14 | private ILanguageService? _languageService; 15 | 16 | public IServiceProvider Services => _serviceProvider ?? throw new InvalidOperationException("Services not initialized"); 17 | 18 | public App() 19 | { 20 | // ハンドルされていない例外をキャッチ 21 | DispatcherUnhandledException += App_DispatcherUnhandledException; 22 | AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; 23 | } 24 | 25 | protected override void OnStartup(StartupEventArgs e) 26 | { 27 | base.OnStartup(e); 28 | 29 | try 30 | { 31 | var serviceCollection = new ServiceCollection(); 32 | ConfigureServices(serviceCollection); 33 | _serviceProvider = serviceCollection.BuildServiceProvider(); 34 | _languageService = _serviceProvider.GetRequiredService(); 35 | 36 | var mainWindow = _serviceProvider.GetRequiredService(); 37 | 38 | // ウィンドウを確実に表示 39 | mainWindow.WindowState = WindowState.Normal; 40 | mainWindow.Visibility = Visibility.Visible; 41 | mainWindow.ShowInTaskbar = true; 42 | 43 | mainWindow.Show(); 44 | 45 | // ウィンドウをアクティブにする 46 | mainWindow.Activate(); 47 | mainWindow.Focus(); 48 | } 49 | catch (Exception ex) 50 | { 51 | // ユーザーにエラーを表示 52 | MessageBox.Show($"{_languageService?.GetString("AppStartupError")}\n\n" + 53 | $"{_languageService?.GetString("ErrorPrefix") ?? "Error:"} {ex.Message}", 54 | _languageService?.GetString("StartupErrorTitle") ?? "Startup Error", 55 | MessageBoxButton.OK, 56 | MessageBoxImage.Error); 57 | 58 | // アプリケーションを終了 59 | Environment.Exit(1); 60 | } 61 | } 62 | 63 | private void ConfigureServices(IServiceCollection services) 64 | { 65 | // Logging (Microsoft.Extensions.Logging) - 本番環境では最小限 66 | services.AddLogging(builder => 67 | { 68 | builder.SetMinimumLevel(LogLevel.Warning); 69 | }); 70 | 71 | // カスタムログサービス 72 | services.AddSingleton(); 73 | 74 | // PDF処理サービス 75 | services.AddSingleton(); 76 | 77 | // 言語サービス 78 | services.AddSingleton(); 79 | 80 | // ViewModels 81 | services.AddTransient(); 82 | services.AddTransient(); 83 | 84 | // Views 85 | services.AddTransient(); 86 | services.AddTransient(); 87 | services.AddTransient(); 88 | } 89 | 90 | protected override void OnExit(ExitEventArgs e) 91 | { 92 | _serviceProvider?.Dispose(); 93 | base.OnExit(e); 94 | } 95 | 96 | private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 97 | { 98 | try 99 | { 100 | MessageBox.Show($"{_languageService?.GetString("AppError")}\n\n" + 101 | $"{_languageService?.GetString("ErrorPrefix") ?? "Error:"} {e.Exception.Message}", 102 | _languageService?.GetString("AppErrorTitle") ?? "Application Error", 103 | MessageBoxButton.OK, 104 | MessageBoxImage.Error); 105 | 106 | e.Handled = true; // アプリケーションを継続 107 | } 108 | catch 109 | { 110 | // 何もできない場合はアプリケーションを終了 111 | } 112 | } 113 | 114 | private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 115 | { 116 | // 致命的エラーの場合は静かに終了 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/ViewModels/AboutWindowViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Runtime.CompilerServices; 3 | using PdfTitleRenamer.Services; 4 | using System.Collections.Generic; 5 | 6 | namespace PdfTitleRenamer.ViewModels 7 | { 8 | public class AboutWindowViewModel : INotifyPropertyChanged 9 | { 10 | private readonly ILanguageService _languageService; 11 | 12 | public AboutWindowViewModel(ILanguageService languageService) 13 | { 14 | _languageService = languageService; 15 | 16 | // 言語変更イベントを購読 17 | _languageService.LanguageChanged += (s, e) => { 18 | OnPropertyChanged(string.Empty); 19 | }; 20 | 21 | // 初期化 22 | _licenseLabel = _languageService.GetString("LicenseLabel"); 23 | } 24 | 25 | // UI文字列プロパティ 26 | public string AboutWindowTitle => _languageService.GetString("AboutWindowTitle"); 27 | public string AppDescription => _languageService.GetString("AppDescription"); 28 | public string AboutTab => _languageService.GetString("AboutTab"); 29 | public string LicenseTab => _languageService.GetString("LicenseTab"); 30 | public string AppInfoHeader => _languageService.GetString("AppInfoHeader"); 31 | public string VersionLabel => _languageService.GetString("VersionLabel"); 32 | public string AuthorLabel => _languageService.GetString("AuthorLabel"); 33 | public string LinkLabel => _languageService.GetString("LinkLabel"); 34 | public string DevelopmentLanguageLabel => _languageService.GetString("DevelopmentLanguageLabel"); 35 | public string UIFrameworkLabel => _languageService.GetString("UIFrameworkLabel"); 36 | public string DesignLabel => _languageService.GetString("DesignLabel"); 37 | public string SupportedOSLabel => _languageService.GetString("SupportedOSLabel"); 38 | public string MainFeaturesHeader => _languageService.GetString("MainFeaturesHeader"); 39 | public string Feature1 => _languageService.GetString("Feature1"); 40 | public string Feature2 => _languageService.GetString("Feature2"); 41 | public string Feature3 => _languageService.GetString("Feature3"); 42 | public string Feature4 => _languageService.GetString("Feature4"); 43 | public string Feature5 => _languageService.GetString("Feature5"); 44 | public string Feature6 => _languageService.GetString("Feature6"); 45 | public string UsageHeader => _languageService.GetString("UsageHeader"); 46 | public string Usage1 => _languageService.GetString("Usage1"); 47 | public string Usage2 => _languageService.GetString("Usage2"); 48 | public string Usage3 => _languageService.GetString("Usage3"); 49 | public string Usage4 => _languageService.GetString("Usage4"); 50 | 51 | // Value properties for AboutWindow 52 | public string VersionValue => "1.0.4"; 53 | public string AuthorValue => "fa-yoshinobu"; 54 | public string LinkValue => "https://github.com/fa-yoshinobu/PDF_Title_to_Filename"; 55 | public string DevelopmentLanguageValue => _languageService.GetString("DevelopmentLanguageValue"); 56 | public string UIFrameworkValue => _languageService.GetString("UIFrameworkValue"); 57 | public string DesignValue => _languageService.GetString("DesignValue"); 58 | public string SupportedOSValue => _languageService.GetString("SupportedOSValue"); 59 | 60 | private string _licenseLabel = ""; 61 | public string LicenseLabel 62 | { 63 | get => _licenseLabel; 64 | set => SetProperty(ref _licenseLabel, value); 65 | } 66 | 67 | public event PropertyChangedEventHandler? PropertyChanged; 68 | 69 | protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) 70 | { 71 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 72 | } 73 | 74 | protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null) 75 | { 76 | if (EqualityComparer.Default.Equals(field, value)) 77 | return false; 78 | 79 | field = value; 80 | OnPropertyChanged(propertyName); 81 | return true; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Services/PdfProcessingService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using UglyToad.PdfPig; 3 | using PdfTitleRenamer.Models; 4 | using System.IO; 5 | using System.Text; 6 | using System.Text.RegularExpressions; 7 | 8 | namespace PdfTitleRenamer.Services 9 | { 10 | public class PdfProcessingService : IPdfProcessingService 11 | { 12 | private readonly ILogger _logger; 13 | private readonly ILogService _logService; 14 | private readonly ILanguageService _languageService; 15 | 16 | public PdfProcessingService(ILogger logger, ILogService logService, ILanguageService languageService) 17 | { 18 | _logger = logger; 19 | _logService = logService; 20 | _languageService = languageService; 21 | 22 | // .NET 8でShift_JISなどの追加エンコーディングを使用可能にする 23 | Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); 24 | } 25 | 26 | 27 | 28 | public PdfMetadata ExtractMetadataFromPdf(string filePath) 29 | { 30 | try 31 | { 32 | if (!File.Exists(filePath)) 33 | { 34 | _logger.LogError($"{_languageService?.GetString("PDFFileNotFound") ?? "PDF file not found"}: {filePath}"); 35 | return new PdfMetadata(); 36 | } 37 | 38 | using var document = PdfDocument.Open(filePath); 39 | var info = document.Information; 40 | 41 | var metadata = new PdfMetadata 42 | { 43 | Title = info?.Title?.Trim() ?? "", 44 | Author = info?.Author?.Trim() ?? "", 45 | Subject = info?.Subject?.Trim() ?? "", 46 | Keywords = info?.Keywords?.Trim() ?? "", 47 | Creator = info?.Creator?.Trim() ?? "", 48 | Producer = info?.Producer?.Trim() ?? "" 49 | }; 50 | 51 | 52 | 53 | return metadata; 54 | } 55 | catch (Exception ex) 56 | { 57 | _logger.LogError(ex, $"{_languageService?.GetString("PDFMetadataExtractionFailed") ?? "PDF metadata extraction failed"}: {filePath}"); 58 | return new PdfMetadata(); 59 | } 60 | } 61 | 62 | 63 | 64 | public string SanitizeFileName(string fileName, bool applyNFKC = true) 65 | { 66 | if (string.IsNullOrWhiteSpace(fileName)) 67 | return "Untitled"; 68 | 69 | // NFKC正規化で全角英数字を半角に変換(オプション) 70 | var sanitized = applyNFKC ? fileName.Normalize(NormalizationForm.FormKC) : fileName; 71 | 72 | // ファイル名に使用できない文字を置換 73 | var invalidChars = Path.GetInvalidFileNameChars(); 74 | 75 | foreach (var invalidChar in invalidChars) 76 | { 77 | sanitized = sanitized.Replace(invalidChar, '_'); 78 | } 79 | 80 | // 追加の無効文字パターンを処理 81 | sanitized = Regex.Replace(sanitized, @"[<>:""/\\|?*\x00-\x1f]", "_"); 82 | 83 | // 連続する空白を1つにまとめる 84 | sanitized = Regex.Replace(sanitized, @"\s+", " "); 85 | 86 | // 先頭と末尾の空白を削除 87 | sanitized = sanitized.Trim(); 88 | 89 | // 空文字列になった場合のフォールバック 90 | if (string.IsNullOrWhiteSpace(sanitized)) 91 | return "Untitled"; 92 | 93 | // Windowsの予約語をチェック 94 | var reservedNames = new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }; 95 | var nameWithoutExtension = Path.GetFileNameWithoutExtension(sanitized); 96 | 97 | if (reservedNames.Contains(nameWithoutExtension.ToUpper())) 98 | { 99 | sanitized = $"_{sanitized}"; 100 | } 101 | 102 | // 長すぎるファイル名を切り詰め(Windowsの最大パス長制限を考慮) 103 | var maxLength = 240; // 拡張子とパスの分を考慮 104 | if (sanitized.Length > maxLength) 105 | { 106 | sanitized = sanitized.Substring(0, maxLength); 107 | } 108 | 109 | return sanitized; 110 | } 111 | 112 | public string GetUniqueFilePath(string filePath) 113 | { 114 | if (!File.Exists(filePath)) 115 | return filePath; 116 | 117 | var directory = Path.GetDirectoryName(filePath)!; 118 | var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); 119 | var extension = Path.GetExtension(filePath); 120 | 121 | var counter = 1; 122 | string newFilePath; 123 | 124 | do 125 | { 126 | var newFileName = $"{fileNameWithoutExtension}({counter}){extension}"; 127 | newFilePath = Path.Combine(directory, newFileName); 128 | counter++; 129 | } 130 | while (File.Exists(newFilePath)); 131 | 132 | return newFilePath; 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Views/MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using PdfTitleRenamer.ViewModels; 2 | using PdfTitleRenamer.Services; 3 | using System.Windows; 4 | using System.Linq; 5 | using System; 6 | using System.IO; 7 | 8 | namespace PdfTitleRenamer.Views 9 | { 10 | public partial class MainWindow : Window 11 | { 12 | private MainWindowViewModel ViewModel => (MainWindowViewModel)DataContext; 13 | private ILanguageService? _languageService; 14 | 15 | public MainWindow(MainWindowViewModel viewModel) 16 | { 17 | InitializeComponent(); 18 | DataContext = viewModel; 19 | _languageService = viewModel.GetLanguageService(); 20 | 21 | // ファイル数の変化に応じてVisibilityを制御 22 | viewModel.PropertyChanged += (s, e) => { 23 | if (e.PropertyName == nameof(viewModel.HasFiles)) 24 | { 25 | UpdateVisibility(); 26 | } 27 | }; 28 | 29 | UpdateVisibility(); 30 | } 31 | 32 | private void UpdateVisibility() 33 | { 34 | EmptyDropZone.Visibility = ViewModel.HasFiles ? Visibility.Collapsed : Visibility.Visible; 35 | FileDataGrid.Visibility = ViewModel.HasFiles ? Visibility.Visible : Visibility.Collapsed; 36 | } 37 | 38 | private void Window_Drop(object sender, DragEventArgs e) 39 | { 40 | try 41 | { 42 | if (e.Data.GetDataPresent(DataFormats.FileDrop)) 43 | { 44 | string[] items = (string[])e.Data.GetData(DataFormats.FileDrop); 45 | var allPdfFiles = new List(); 46 | 47 | foreach (var item in items) 48 | { 49 | if (File.Exists(item)) 50 | { 51 | // ファイルの場合 52 | if (item.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) 53 | { 54 | allPdfFiles.Add(item); 55 | } 56 | } 57 | else if (Directory.Exists(item)) 58 | { 59 | // フォルダの場合、再帰的にPDFファイルを検索 60 | var pdfFilesInFolder = GetPdfFilesFromDirectory(item); 61 | allPdfFiles.AddRange(pdfFilesInFolder); 62 | } 63 | } 64 | 65 | if (allPdfFiles.Any()) 66 | { 67 | ViewModel.AddFiles(allPdfFiles.ToArray()); 68 | } 69 | } 70 | } 71 | catch (Exception ex) 72 | { 73 | MessageBox.Show($"{_languageService?.GetString("DragDropError")}: {ex.Message}", 74 | _languageService?.GetString("ErrorTitle") ?? "Error", 75 | MessageBoxButton.OK, MessageBoxImage.Error); 76 | } 77 | } 78 | 79 | private void Window_DragOver(object sender, DragEventArgs e) 80 | { 81 | try 82 | { 83 | if (e.Data.GetDataPresent(DataFormats.FileDrop)) 84 | { 85 | string[] items = (string[])e.Data.GetData(DataFormats.FileDrop); 86 | bool hasValidItems = items.Any(item => 87 | (File.Exists(item) && item.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) || 88 | Directory.Exists(item)); 89 | 90 | e.Effects = hasValidItems ? System.Windows.DragDropEffects.Copy : System.Windows.DragDropEffects.None; 91 | } 92 | else 93 | { 94 | e.Effects = System.Windows.DragDropEffects.None; 95 | } 96 | 97 | e.Handled = true; 98 | } 99 | catch 100 | { 101 | e.Effects = System.Windows.DragDropEffects.None; 102 | e.Handled = true; 103 | } 104 | } 105 | 106 | private void DataGrid_Drop(object sender, DragEventArgs e) 107 | { 108 | Window_Drop(sender, e); 109 | } 110 | 111 | private void DataGrid_DragOver(object sender, DragEventArgs e) 112 | { 113 | Window_DragOver(sender, e); 114 | } 115 | 116 | /// 117 | /// 指定されたディレクトリから再帰的にPDFファイルを検索 118 | /// 119 | private List GetPdfFilesFromDirectory(string directoryPath) 120 | { 121 | var pdfFiles = new List(); 122 | 123 | try 124 | { 125 | // 現在のディレクトリのPDFファイルを検索 126 | var files = Directory.GetFiles(directoryPath, "*.pdf", SearchOption.TopDirectoryOnly); 127 | pdfFiles.AddRange(files); 128 | 129 | // サブディレクトリも再帰的に検索 130 | var subDirectories = Directory.GetDirectories(directoryPath); 131 | foreach (var subDir in subDirectories) 132 | { 133 | var subDirFiles = GetPdfFilesFromDirectory(subDir); 134 | pdfFiles.AddRange(subDirFiles); 135 | } 136 | } 137 | catch (Exception) 138 | { 139 | // アクセス権限エラーなどは無視して続行 140 | } 141 | 142 | return pdfFiles; 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Resources/Strings.jp.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PDF Title to Filename 5 | 6 | 7 | PDFファイルのメタデータからタイトルを抽出し、ファイル名として自動設定するアプリケーションです 8 | 9 | 10 | ファイル選択 11 | 12 | 13 | 処理開始 14 | 15 | 16 | リストクリア 17 | 18 | 19 | 現在の名前 20 | 21 | 22 | 新しい名前 23 | 24 | 25 | ステータス 26 | 27 | 28 | 操作 29 | 30 | 31 | 待機中 32 | 33 | 34 | 処理中... 35 | 36 | 37 | リネーム完了 38 | 39 | 40 | タイトルなし 41 | 42 | 43 | メタデータなし 44 | 45 | 46 | 変更不要 47 | 48 | 49 | エラー 50 | 51 | 52 | リネーム予定 53 | 54 | 55 | 設定 56 | 57 | 58 | アプリについて 59 | 60 | 61 | 言語 62 | 63 | 64 | Japanese 65 | 66 | 67 | English 68 | 69 | 70 | ファイル名要素 71 | 72 | 73 | 要素の順序(矢印ボタンで変更可能) 74 | 75 | 76 | プレフィックス 77 | 78 | 79 | サフィックス 80 | 81 | 82 | セパレータ 83 | 84 | 85 | プレビュー 86 | 87 | 88 | 保存 89 | 90 | 91 | キャンセル 92 | 93 | 94 | リセット 95 | 96 | 97 | PDFのタイトル 98 | 99 | 100 | PDFの作成者 101 | 102 | 103 | PDFのサブタイトル 104 | 105 | 106 | PDFのキーワード 107 | 108 | 109 | 変更前のファイル名 110 | 111 | 112 | バージョン 113 | 114 | 115 | 作者 116 | 117 | 118 | リンク 119 | 120 | 121 | 開発言語 122 | 123 | 124 | UI フレームワーク 125 | 126 | 127 | デザイン 128 | 129 | 130 | 対応OS 131 | 132 | 133 | 主な機能 134 | 135 | 136 | 使用方法 137 | 138 | 139 | オープンソースライセンス 140 | 141 | 142 | ライセンス 143 | 144 | 145 | PDFファイルをここにドラッグ&ドロップ 146 | 147 | 148 | または 149 | 150 | 151 | クリックしてファイルを選択 152 | 153 | 154 | 処理ログ 155 | 156 | 157 | ファイルが選択されていません 158 | 159 | 160 | 処理完了 161 | 162 | 163 | 処理失敗 164 | 165 | 166 | サンプルタイトル 167 | 168 | 169 | 作成者名 170 | 171 | 172 | サブタイトル 173 | 174 | 175 | キーワード 176 | 177 | 178 | sample.pdf 179 | 180 | 181 | ファイル選択済み 182 | 183 | 184 | 処理結果 185 | 186 | 187 | PDFメタデータ項目(タイトル、作成者、サブタイトル、キーワード)がすべて無効になっています。少なくとも1つの項目を有効にしてください。 188 | 189 | 190 | 設定警告 191 | 192 | 193 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Resources/Strings.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PDF Title to Filename 5 | 6 | 7 | An application that extracts titles from PDF metadata and automatically sets them as filenames 8 | 9 | 10 | Select Files 11 | 12 | 13 | Start Processing 14 | 15 | 16 | Clear List 17 | 18 | 19 | Current Name 20 | 21 | 22 | New Name 23 | 24 | 25 | Status 26 | 27 | 28 | Operation 29 | 30 | 31 | Waiting 32 | 33 | 34 | Processing... 35 | 36 | 37 | Rename Completed 38 | 39 | 40 | No Title 41 | 42 | 43 | No Metadata 44 | 45 | 46 | No Change Needed 47 | 48 | 49 | Error 50 | 51 | 52 | Rename Scheduled 53 | 54 | 55 | Settings 56 | 57 | 58 | About 59 | 60 | 61 | Language 62 | 63 | 64 | Japanese 65 | 66 | 67 | English 68 | 69 | 70 | Filename Elements 71 | 72 | 73 | Element Order (Change with arrow buttons) 74 | 75 | 76 | Prefix 77 | 78 | 79 | Suffix 80 | 81 | 82 | Separator 83 | 84 | 85 | Preview 86 | 87 | 88 | Save 89 | 90 | 91 | Cancel 92 | 93 | 94 | Reset 95 | 96 | 97 | PDF Title 98 | 99 | 100 | PDF Author 101 | 102 | 103 | PDF Subject 104 | 105 | 106 | PDF Keywords 107 | 108 | 109 | Original Filename 110 | 111 | 112 | Version 113 | 114 | 115 | Author 116 | 117 | 118 | Link 119 | 120 | 121 | Development Language 122 | 123 | 124 | UI Framework 125 | 126 | 127 | Design 128 | 129 | 130 | Supported OS 131 | 132 | 133 | Main Features 134 | 135 | 136 | Usage 137 | 138 | 139 | Open Source Licenses 140 | 141 | 142 | License 143 | 144 | 145 | Drag and drop PDF files here 146 | 147 | 148 | or 149 | 150 | 151 | Click to select files 152 | 153 | 154 | Processing Log 155 | 156 | 157 | No files selected 158 | 159 | 160 | Processing Complete 161 | 162 | 163 | Processing Failed 164 | 165 | 166 | Sample Title 167 | 168 | 169 | Author Name 170 | 171 | 172 | Subject 173 | 174 | 175 | Keywords 176 | 177 | 178 | sample.pdf 179 | 180 | 181 | files selected 182 | 183 | 184 | Processing Results 185 | 186 | 187 | All PDF metadata items (Title, Author, Subject, Keywords) are disabled. Please enable at least one item. 188 | 189 | 190 | Settings Warning 191 | 192 | 193 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/ViewModels/SettingsWindowViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Runtime.CompilerServices; 3 | using System.Windows.Input; 4 | using PdfTitleRenamer.Models; 5 | using PdfTitleRenamer.Services; 6 | using System.Collections.ObjectModel; 7 | using System.Collections.Specialized; 8 | using System.Collections.Generic; 9 | 10 | namespace PdfTitleRenamer.ViewModels 11 | { 12 | public class SettingsWindowViewModel : INotifyPropertyChanged 13 | { 14 | private readonly FileNameSettings _settings; 15 | private readonly ILogService _logService; 16 | private readonly ILanguageService _languageService; 17 | 18 | public SettingsWindowViewModel(FileNameSettings settings, ILogService logService, ILanguageService languageService) 19 | { 20 | _settings = settings; 21 | _logService = logService; 22 | _languageService = languageService; 23 | 24 | // 言語変更イベントを購読 25 | _languageService.LanguageChanged += (s, e) => { 26 | OnPropertyChanged(string.Empty); 27 | }; 28 | 29 | // FileNameElementにLanguageServiceを設定 30 | FileNameElement.SetLanguageService(_languageService); 31 | 32 | // Commands 33 | SaveCommand = new RelayCommand(Save); 34 | ResetCommand = new RelayCommand(Reset); 35 | CancelCommand = new RelayCommand(Cancel); 36 | MoveUpCommand = new RelayCommand(MoveUp); 37 | MoveDownCommand = new RelayCommand(MoveDown); 38 | 39 | UpdatePreview(); 40 | } 41 | 42 | public FileNameSettings Settings => _settings; 43 | 44 | // UI文字列プロパティ 45 | public string SettingsWindowTitle => _languageService.GetString("SettingsWindowTitle"); 46 | public string FileNameElementsHeader => _languageService.GetString("FileNameElementsHeader"); 47 | public string ElementsDescription => _languageService.GetString("ElementsDescription"); 48 | public string CustomStringSettingsHeader => _languageService.GetString("CustomStringSettingsHeader"); 49 | public string PrefixLabel => _languageService.GetString("PrefixLabel"); 50 | public string SuffixLabel => _languageService.GetString("SuffixLabel"); 51 | public string PrefixToolTip => _languageService.GetString("PrefixToolTip"); 52 | public string SuffixToolTip => _languageService.GetString("SuffixToolTip"); 53 | public string SeparatorSettingsHeader => _languageService.GetString("SeparatorSettingsHeader"); 54 | public string SeparatorLabel => _languageService.GetString("SeparatorLabel"); 55 | public string SeparatorToolTip => _languageService.GetString("SeparatorToolTip"); 56 | public string PreviewHeader => _languageService.GetString("PreviewHeader"); 57 | public string PreviewLabel => _languageService.GetString("PreviewLabel"); 58 | public string SaveButton => _languageService.GetString("SaveButton"); 59 | public string ResetButton => _languageService.GetString("ResetButton"); 60 | public string CancelButton => _languageService.GetString("CancelButton"); 61 | // FileNameElement display names 62 | public string OriginalFileNameDisplay => _languageService.GetString("OriginalFileNameDisplay"); 63 | public string PDFTitleDisplay => _languageService.GetString("PDFTitleDisplay"); 64 | public string PDFAuthorDisplay => _languageService.GetString("PDFAuthorDisplay"); 65 | public string PDFSubjectDisplay => _languageService.GetString("PDFSubjectDisplay"); 66 | public string PDFKeywordsDisplay => _languageService.GetString("PDFKeywordsDisplay"); 67 | public string CustomPrefixDisplay => _languageService.GetString("CustomPrefixDisplay"); 68 | public string CustomSuffixDisplay => _languageService.GetString("CustomSuffixDisplay"); 69 | 70 | private string _previewFileName = ""; 71 | public string PreviewFileName 72 | { 73 | get => _previewFileName; 74 | set => SetProperty(ref _previewFileName, value); 75 | } 76 | 77 | // Commands 78 | public ICommand SaveCommand { get; } 79 | public ICommand ResetCommand { get; } 80 | public ICommand CancelCommand { get; } 81 | public ICommand MoveUpCommand { get; } 82 | public ICommand MoveDownCommand { get; } 83 | 84 | // 設定保存イベント 85 | public event EventHandler? SettingsSaved; 86 | // ウィンドウを閉じるイベント 87 | public event EventHandler? WindowClosed; 88 | 89 | private void Save() 90 | { 91 | try 92 | { 93 | _settings.Save(); 94 | _logService.LogInfo(_languageService.GetString("SettingsUpdatedLog")); 95 | // 設定保存イベントを発生 96 | SettingsSaved?.Invoke(this, EventArgs.Empty); 97 | // ウィンドウを閉じるイベントを発生 98 | WindowClosed?.Invoke(this, EventArgs.Empty); 99 | } 100 | catch (Exception ex) 101 | { 102 | _logService.LogError($"{_languageService.GetString("SettingsWindowError")}: {ex.Message}"); 103 | } 104 | } 105 | 106 | private void Reset() 107 | { 108 | try 109 | { 110 | // デフォルト設定を現在の設定にコピー 111 | var defaultSettings = FileNameSettings.Default; 112 | _settings.CustomPrefix = defaultSettings.CustomPrefix; 113 | _settings.CustomSuffix = defaultSettings.CustomSuffix; 114 | _settings.Separator = defaultSettings.Separator; 115 | 116 | _settings.Elements.Clear(); 117 | foreach (var element in defaultSettings.Elements) 118 | { 119 | _settings.Elements.Add(new FileNameElement(element.ElementType, element.IsEnabled)); 120 | } 121 | 122 | UpdatePreview(); 123 | _logService.LogInfo(_languageService.GetString("SettingsUpdatedLog")); 124 | } 125 | catch (Exception ex) 126 | { 127 | _logService.LogError($"{_languageService.GetString("SettingsWindowError")}: {ex.Message}"); 128 | } 129 | } 130 | 131 | private void Cancel() 132 | { 133 | // ウィンドウを閉じるイベントを発生 134 | WindowClosed?.Invoke(this, EventArgs.Empty); 135 | } 136 | 137 | private void MoveUp(FileNameElement? element) 138 | { 139 | if (element != null) 140 | { 141 | var index = _settings.Elements.IndexOf(element); 142 | if (index > 0) 143 | { 144 | _settings.Elements.Move(index, index - 1); 145 | UpdatePreview(); 146 | } 147 | } 148 | } 149 | 150 | private void MoveDown(FileNameElement? element) 151 | { 152 | if (element != null) 153 | { 154 | var index = _settings.Elements.IndexOf(element); 155 | if (index < _settings.Elements.Count - 1) 156 | { 157 | _settings.Elements.Move(index, index + 1); 158 | UpdatePreview(); 159 | } 160 | } 161 | } 162 | 163 | public void UpdatePreview() 164 | { 165 | PreviewFileName = _settings.GeneratePreviewFileName(); 166 | } 167 | 168 | public event PropertyChangedEventHandler? PropertyChanged; 169 | 170 | protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) 171 | { 172 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 173 | } 174 | 175 | protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null) 176 | { 177 | if (EqualityComparer.Default.Equals(field, value)) 178 | return false; 179 | 180 | field = value; 181 | OnPropertyChanged(propertyName); 182 | return true; 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Build results 2 | [Dd]ebug/ 3 | [Dd]ebugPublic/ 4 | [Rr]elease/ 5 | [Rr]eleases/ 6 | x64/ 7 | x86/ 8 | [Ww][Ii][Nn]32/ 9 | [Aa][Rr][Mm]/ 10 | [Aa][Rr][Mm]64/ 11 | bld/ 12 | [Bb]in/ 13 | [Oo]bj/ 14 | [Ll]og/ 15 | [Ll]ogs/ 16 | 17 | # Visual Studio 2015/2017 cache/options directory 18 | .vs/ 19 | # Uncomment if you have tasks that create the project's static files in wwwroot 20 | #wwwroot/ 21 | 22 | # Visual Studio 2017 auto generated files 23 | Generated\ Files/ 24 | 25 | # MSTest test Results 26 | [Tt]est[Rr]esult*/ 27 | [Bb]uild[Ll]og.* 28 | 29 | # NUnit 30 | *.VisualState.xml 31 | TestResult.xml 32 | nunit-*.xml 33 | 34 | # Build Results of an ATL Project 35 | [Dd]ebugPS/ 36 | [Rr]eleasePS/ 37 | dlldata.c 38 | 39 | # Benchmark Results 40 | BenchmarkDotNet.Artifacts/ 41 | 42 | # .NET Core 43 | project.lock.json 44 | project.fragment.lock.json 45 | artifacts/ 46 | 47 | # ASP.NET Scaffolding 48 | ScaffoldingReadMe.txt 49 | 50 | # StyleCop 51 | StyleCopReport.xml 52 | 53 | # Files built by Visual Studio 54 | *_i.c 55 | *_p.c 56 | *_h.h 57 | *.ilk 58 | *.meta 59 | *.obj 60 | *.iobj 61 | *.pch 62 | *.pdb 63 | *.ipdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *_wpftmp.csproj 74 | *.log 75 | *.tlog 76 | *.vspscc 77 | *.vssscc 78 | .builds 79 | *.pidb 80 | *.svclog 81 | *.scc 82 | 83 | # Chutzpah Test files 84 | _Chutzpah* 85 | 86 | # Visual C++ cache files 87 | ipch/ 88 | *.aps 89 | *.ncb 90 | *.opendb 91 | *.opensdf 92 | *.sdf 93 | *.cachefile 94 | *.VC.db 95 | *.VC.VC.opendb 96 | 97 | # Visual Studio profiler 98 | *.psess 99 | *.vsp 100 | *.vspx 101 | *.sap 102 | 103 | # Visual Studio Trace Files 104 | *.e2e 105 | 106 | # TFS 2012 Local Workspace 107 | $tf/ 108 | 109 | # Guidance Automation Toolkit 110 | *.gpState 111 | 112 | # ReSharper is a .NET coding add-in 113 | _ReSharper*/ 114 | *.[Rr]e[Ss]harper 115 | *.DotSettings.user 116 | 117 | # TeamCity is a build add-in 118 | _TeamCity* 119 | 120 | # DotCover is a Code Coverage Tool 121 | *.dotCover 122 | 123 | # AxoCover is a Code Coverage Tool 124 | .axoCover/* 125 | !.axoCover/settings.json 126 | 127 | # Coverlet is a free, cross platform Code Coverage Tool 128 | coverage*.json 129 | coverage*.xml 130 | coverage*.info 131 | 132 | # Visual Studio code coverage results 133 | *.coverage 134 | *.coveragexml 135 | 136 | # NCrunch 137 | _NCrunch_* 138 | .*crunch*.local.xml 139 | nCrunchTemp_* 140 | 141 | # MightyMoose 142 | *.mm.* 143 | AutoTest.Net/ 144 | 145 | # Web workbench (sass) 146 | .sass-cache/ 147 | 148 | # Installshield output folder 149 | [Ee]xpress/ 150 | 151 | # DocProject is a documentation generator add-in 152 | DocProject/buildhelp/ 153 | DocProject/Help/*.HxT 154 | DocProject/Help/*.HxC 155 | DocProject/Help/*.hhc 156 | DocProject/Help/*.hhk 157 | DocProject/Help/*.hhp 158 | DocProject/Help/Html2 159 | DocProject/Help/html 160 | 161 | # Click-Once directory 162 | publish/ 163 | 164 | # Publish Web Output 165 | *.[Pp]ublish.xml 166 | *.azurePubxml 167 | # Note: Comment the next line if you want to checkin your web deploy settings, 168 | # but database connection strings (with potential passwords) will be unencrypted 169 | *.pubxml 170 | *.publishproj 171 | 172 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 173 | # checkin your Azure Web App publish settings, but sensitive information contained 174 | # in these files will be unencrypted 175 | PublishScripts/ 176 | 177 | # NuGet Packages 178 | *.nupkg 179 | # NuGet Symbol Packages 180 | *.snupkg 181 | # The packages folder can be ignored because of Package Restore 182 | **/[Pp]ackages/* 183 | # except build/, which is used as an MSBuild target. 184 | !**/[Pp]ackages/build/ 185 | # Uncomment if necessary however generally it will be regenerated when needed 186 | #!**/[Pp]ackages/repositories.config 187 | # NuGet v3's project.json files produces more ignorable files 188 | *.nuget.props 189 | *.nuget.targets 190 | 191 | # Microsoft Azure Build Output 192 | csx/ 193 | *.build.csdef 194 | 195 | # Microsoft Azure Emulator 196 | ecf/ 197 | rcf/ 198 | 199 | # Windows Store app package directories and files 200 | AppPackages/ 201 | BundleArtifacts/ 202 | Package.StoreAssociation.xml 203 | _pkginfo.txt 204 | *.appx 205 | *.appxbundle 206 | *.appxupload 207 | 208 | # Visual Studio cache files 209 | # files ending in .cache can be ignored 210 | *.[Cc]ache 211 | # but keep track of directories ending in .cache 212 | !?*.[Cc]ache/ 213 | 214 | # Others 215 | ClientBin/ 216 | ~$* 217 | *~ 218 | *.dbmdl 219 | *.dbproj.schemaview 220 | *.jfm 221 | *.pfx 222 | *.publishsettings 223 | orleans.codegen.cs 224 | 225 | # Including strong name files can present a security risk 226 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 227 | #*.snk 228 | 229 | # Since there are multiple workflows, uncomment the next line to ignore bower_components 230 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 231 | #bower_components/ 232 | 233 | # RIA/Silverlight projects 234 | Generated_Code/ 235 | 236 | # Backup & report files from converting an old project file 237 | # to a newer Visual Studio version. Backup files are not needed, 238 | # because we have git ;-) 239 | _UpgradeReport_Files/ 240 | Backup*/ 241 | UpgradeLog*.XML 242 | UpgradeLog*.htm 243 | CachedCopyright.txt 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | *- [Bb]ackup.rdl 256 | *- [Bb]ackup ([0-9]).rdl 257 | *- [Bb]ackup ([0-9][0-9]).rdl 258 | 259 | # Microsoft Fakes 260 | FakesAssemblies/ 261 | 262 | # GhostDoc plugin setting file 263 | *.GhostDoc.xml 264 | 265 | # Node.js Tools for Visual Studio 266 | .ntvs_analysis.dat 267 | node_modules/ 268 | 269 | # Visual Studio 6 build log 270 | *.plg 271 | 272 | # Visual Studio 6 workspace options file 273 | *.opt 274 | 275 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 276 | *.vbw 277 | 278 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 279 | *.vbp 280 | 281 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 282 | *.dsw 283 | *.dsp 284 | 285 | # Visual Studio 6 technical files 286 | *.ncb 287 | *.aps 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # Visual Studio History (VSHistory) files 346 | .vshistory/ 347 | 348 | # BeatPulse healthcheck temp database 349 | healthchecksdb 350 | 351 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 352 | MigrationBackup/ 353 | 354 | # Ionide (cross platform F# VS Code tools) working folder 355 | .ionide/ 356 | 357 | # Fody - auto-generated XML schema 358 | FodyWeavers.xsd 359 | 360 | # VS Code files for those working on multiple tools 361 | .vscode/* 362 | !.vscode/settings.json 363 | !.vscode/tasks.json 364 | !.vscode/launch.json 365 | !.vscode/extensions.json 366 | *.code-workspace 367 | 368 | # Local History for Visual Studio Code 369 | .history/ 370 | 371 | # Windows Installer files from build outputs 372 | *.cab 373 | *.msi 374 | *.msix 375 | *.msm 376 | *.msp 377 | 378 | # JetBrains Rider 379 | *.sln.iml 380 | 381 | # Application specific files 382 | # User settings and logs 383 | *.log 384 | settings.json 385 | rename_log.txt 386 | debug.log 387 | application.log 388 | 389 | # Application data directories 390 | AppData/ 391 | LocalAppData/ 392 | 393 | # Temporary files 394 | *.tmp 395 | *.temp 396 | 397 | # OS generated files 398 | .DS_Store 399 | .DS_Store? 400 | ._* 401 | .Spotlight-V100 402 | .Trashes 403 | ehthumbs.db 404 | Thumbs.db 405 | 406 | # IDE files 407 | *.swp 408 | *.swo 409 | *~ 410 | 411 | # Backup files 412 | *.bak 413 | *.backup 414 | *.old 415 | 416 | # Python files (from original project reference) 417 | py/ 418 | __pycache__/ 419 | *.py[cod] 420 | *$py.class 421 | *.so 422 | .Python 423 | build/ 424 | develop-eggs/ 425 | dist/ 426 | downloads/ 427 | eggs/ 428 | .eggs/ 429 | lib/ 430 | lib64/ 431 | parts/ 432 | sdist/ 433 | var/ 434 | wheels/ 435 | pip-wheel-metadata/ 436 | share/python-wheels/ 437 | *.egg-info/ 438 | .installed.cfg 439 | *.egg 440 | MANIFEST 441 | 442 | # Environments 443 | .env 444 | .venv 445 | env/ 446 | venv/ 447 | ENV/ 448 | env.bak/ 449 | venv.bak/ 450 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Models/FileNameSettings.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Runtime.CompilerServices; 3 | using System.Text.Json; 4 | using System.IO; 5 | using System.Collections.ObjectModel; 6 | 7 | namespace PdfTitleRenamer.Models 8 | { 9 | public class FileNameSettings : INotifyPropertyChanged 10 | { 11 | private string _customPrefix = ""; 12 | private string _customSuffix = ""; 13 | private string _separator = " - "; 14 | private ObservableCollection _elements = new(); 15 | private string _currentLanguage = "en"; 16 | 17 | public string CustomPrefix 18 | { 19 | get => _customPrefix; 20 | set => SetProperty(ref _customPrefix, value); 21 | } 22 | 23 | public string CustomSuffix 24 | { 25 | get => _customSuffix; 26 | set => SetProperty(ref _customSuffix, value); 27 | } 28 | 29 | 30 | 31 | public string Separator 32 | { 33 | get => _separator; 34 | set => SetProperty(ref _separator, value); 35 | } 36 | 37 | public ObservableCollection Elements 38 | { 39 | get => _elements; 40 | set => SetProperty(ref _elements, value); 41 | } 42 | 43 | public string CurrentLanguage 44 | { 45 | get => _currentLanguage; 46 | set => SetProperty(ref _currentLanguage, value); 47 | } 48 | 49 | 50 | 51 | // 設定ファイルパスを取得 52 | public static string GetSettingsFilePath() 53 | { 54 | // 優先: 実行ファイルと同じディレクトリ 55 | string? exeDirectory = null; 56 | 57 | try 58 | { 59 | var processPath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName; 60 | if (!string.IsNullOrEmpty(processPath)) 61 | { 62 | exeDirectory = Path.GetDirectoryName(processPath); 63 | } 64 | } 65 | catch (Exception) 66 | { 67 | // エラーが発生した場合は次の方法を試す 68 | } 69 | 70 | if (string.IsNullOrEmpty(exeDirectory)) 71 | { 72 | var exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; 73 | exeDirectory = Path.GetDirectoryName(exePath); 74 | } 75 | 76 | if (string.IsNullOrEmpty(exeDirectory)) 77 | { 78 | exeDirectory = AppDomain.CurrentDomain.BaseDirectory; 79 | } 80 | 81 | if (!string.IsNullOrEmpty(exeDirectory)) 82 | { 83 | return Path.Combine(exeDirectory, "PDF_Title_to_Filename.json"); 84 | } 85 | 86 | // フォールバック1: Windows標準のアプリケーション設定保存場所 87 | var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); 88 | if (!string.IsNullOrEmpty(localAppDataPath)) 89 | { 90 | var appFolder = Path.Combine(localAppDataPath, "PDF_Title_to_Filename"); 91 | return Path.Combine(appFolder, "PDF_Title_to_Filename.json"); 92 | } 93 | 94 | // フォールバック2: ユーザーのドキュメントフォルダ 95 | var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 96 | if (!string.IsNullOrEmpty(documentsPath)) 97 | { 98 | var appFolder = Path.Combine(documentsPath, "PDF_Title_to_Filename"); 99 | return Path.Combine(appFolder, "PDF_Title_to_Filename.json"); 100 | } 101 | 102 | // 最終フォールバック: 一時ディレクトリ 103 | var tempPath = Path.GetTempPath(); 104 | return Path.Combine(tempPath, "PDF_Title_to_Filename_settings.json"); 105 | } 106 | 107 | // デフォルト設定 108 | public static FileNameSettings Default => new() 109 | { 110 | CustomPrefix = "", 111 | CustomSuffix = "", 112 | Separator = " - ", 113 | Elements = CreateDefaultElements(), 114 | CurrentLanguage = "en" 115 | }; 116 | 117 | // デフォルト要素の作成 118 | private static ObservableCollection CreateDefaultElements() 119 | { 120 | return new ObservableCollection 121 | { 122 | new FileNameElement("CustomPrefix", false), 123 | new FileNameElement("Title", true), 124 | new FileNameElement("Author", false), 125 | new FileNameElement("Subject", false), 126 | new FileNameElement("Keywords", false), 127 | new FileNameElement("OriginalFileName", false), 128 | new FileNameElement("CustomSuffix", false) 129 | }; 130 | } 131 | 132 | // 設定を保存 133 | public void Save() 134 | { 135 | try 136 | { 137 | // デフォルト設定を確実に初期化 138 | if (Elements == null || Elements.Count == 0) 139 | { 140 | Elements = CreateDefaultElements(); 141 | } 142 | 143 | // 設定ファイルパスを取得 144 | var settingsPath = GetSettingsFilePath(); 145 | var settingsDirectory = Path.GetDirectoryName(settingsPath); 146 | 147 | // ディレクトリが存在しない場合は作成 148 | if (!string.IsNullOrEmpty(settingsDirectory) && !Directory.Exists(settingsDirectory)) 149 | { 150 | Directory.CreateDirectory(settingsDirectory); 151 | } 152 | 153 | // 書き込み権限の確認 154 | try 155 | { 156 | if (!string.IsNullOrEmpty(settingsDirectory)) 157 | { 158 | var testFile = Path.Combine(settingsDirectory, "test_write.tmp"); 159 | File.WriteAllText(testFile, "test"); 160 | File.Delete(testFile); 161 | } 162 | } 163 | catch (Exception) 164 | { 165 | // 書き込み権限がない場合は、一時ディレクトリを使用 166 | var tempPath = Path.GetTempPath(); 167 | settingsPath = Path.Combine(tempPath, "PDF_Title_to_Filename_settings.json"); 168 | } 169 | 170 | var json = JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }); 171 | File.WriteAllText(settingsPath, json); 172 | } 173 | catch (Exception) 174 | { 175 | // 設定保存に失敗した場合は無視(デフォルト設定を使用) 176 | } 177 | } 178 | 179 | // 設定を読み込み 180 | public static FileNameSettings Load() 181 | { 182 | try 183 | { 184 | var settingsPath = GetSettingsFilePath(); 185 | 186 | if (File.Exists(settingsPath)) 187 | { 188 | var json = File.ReadAllText(settingsPath); 189 | var settings = JsonSerializer.Deserialize(json); 190 | if (settings != null) 191 | { 192 | // Elementsがnullの場合はデフォルトで初期化 193 | if (settings.Elements == null || settings.Elements.Count == 0) 194 | { 195 | settings.Elements = CreateDefaultElements(); 196 | } 197 | return settings; 198 | } 199 | } 200 | } 201 | catch (Exception) 202 | { 203 | // 設定読み込みに失敗した場合はデフォルト設定を使用 204 | } 205 | 206 | return Default; 207 | } 208 | 209 | // テンプレートからファイル名を生成 210 | public string GenerateFileName(string originalFileName, string title, string author, string subject, string keywords) 211 | { 212 | var parts = new List(); 213 | 214 | // ログサービスは直接取得できないため、ログ出力は行わない 215 | // 代わりにMainWindowViewModelでログを出力する 216 | 217 | // 有効な要素を順序に従って追加 218 | foreach (var element in Elements.Where(e => e.IsEnabled)) 219 | { 220 | string? value = element.ElementType switch 221 | { 222 | "OriginalFileName" => !string.IsNullOrWhiteSpace(originalFileName) ? Path.GetFileNameWithoutExtension(originalFileName) : null, 223 | "Title" => !string.IsNullOrWhiteSpace(title) ? title.Trim() : null, 224 | "Author" => !string.IsNullOrWhiteSpace(author) ? author.Trim() : null, 225 | "Subject" => !string.IsNullOrWhiteSpace(subject) ? subject.Trim() : null, 226 | "Keywords" => !string.IsNullOrWhiteSpace(keywords) ? keywords.Trim() : null, 227 | "CustomPrefix" => !string.IsNullOrWhiteSpace(CustomPrefix) ? CustomPrefix.Trim() : null, 228 | "CustomSuffix" => !string.IsNullOrWhiteSpace(CustomSuffix) ? CustomSuffix.Trim() : null, 229 | _ => null 230 | }; 231 | 232 | if (!string.IsNullOrWhiteSpace(value)) 233 | { 234 | parts.Add(value); 235 | } 236 | } 237 | 238 | // パーツがない場合は空文字列を返す(メタデータなしとして処理) 239 | if (parts.Count == 0) 240 | { 241 | return ""; 242 | } 243 | 244 | // セパレータで結合 245 | return string.Join(Separator, parts); 246 | } 247 | 248 | // プレビュー用のファイル名生成 249 | public string GeneratePreviewFileName(string originalFileName = "sample.pdf", string? title = null, 250 | string? author = null, string? subject = null, string? keywords = null) 251 | { 252 | // デフォルト値を動的に取得 253 | var defaultTitle = title ?? GetDefaultPreviewValue("SampleTitle"); 254 | var defaultAuthor = author ?? GetDefaultPreviewValue("SampleAuthor"); 255 | var defaultSubject = subject ?? GetDefaultPreviewValue("SampleSubject"); 256 | var defaultKeywords = keywords ?? GetDefaultPreviewValue("SampleKeywords"); 257 | 258 | return GenerateFileName(originalFileName, defaultTitle, defaultAuthor, defaultSubject, defaultKeywords); 259 | } 260 | 261 | private string GetDefaultPreviewValue(string key) 262 | { 263 | // LanguageServiceが利用可能な場合はローカライズされた値を取得 264 | if (FileNameElement._languageService != null) 265 | { 266 | return FileNameElement._languageService.GetString(key) ?? GetFallbackValue(key); 267 | } 268 | return GetFallbackValue(key); 269 | } 270 | 271 | private string GetFallbackValue(string key) 272 | { 273 | return key switch 274 | { 275 | "SampleTitle" => "Sample Title", 276 | "SampleAuthor" => "Author Name", 277 | "SampleSubject" => "Subject", 278 | "SampleKeywords" => "Keywords", 279 | _ => "Unknown" 280 | }; 281 | } 282 | 283 | // 要素の有効状態を取得 284 | private bool GetElementEnabled(string elementType) 285 | { 286 | return Elements?.FirstOrDefault(e => e.ElementType == elementType)?.IsEnabled ?? false; 287 | } 288 | 289 | // 要素の有効状態を設定 290 | private void SetElementEnabled(string elementType, bool enabled) 291 | { 292 | var element = Elements?.FirstOrDefault(e => e.ElementType == elementType); 293 | if (element != null) 294 | { 295 | element.IsEnabled = enabled; 296 | } 297 | } 298 | 299 | public event PropertyChangedEventHandler? PropertyChanged; 300 | 301 | protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) 302 | { 303 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 304 | } 305 | 306 | protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null) 307 | { 308 | if (EqualityComparer.Default.Equals(field, value)) return false; 309 | field = value; 310 | OnPropertyChanged(propertyName); 311 | return true; 312 | } 313 | } 314 | } 315 | -------------------------------------------------------------------------------- /PDF_Title_to_Filename/Views/SettingsWindow.xaml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 16 | 17 | 21 | 22 | 28 | 29 | 36 | 37 | 41 | 42 | 46 | 47 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 94 | 95 | 96 | 100 | 101 | 102 | 46 | 47 | 55 | 56 | 64 | 65 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 113 | 114 | 115 | 116 | 117 | 118 | 123 | 124 | 125 | 126 | 127 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 175 | 176 | 177 | 182 | 187 | 188 | 189 | 190 | 191 | 211 | 212 | 222 | 223 | 224 | 235 | 236 | 237 | 238 | 239 | 240 |