/
aleksandrazimut
/
TimerCountdownDesktop
Обзор
Документация
Войти
/
aleksandrazimut
/
TimerCountdownDesktop
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/main/java/com/timerapp/service/ConfigService.java
198 строк
8 KB
Aleksandr Azimut
init commit
17 дек 2025, 21:59
17 дек 2025, 21:59
3c602f1
Код
Авторство
О чём код?
package com.timerapp.service; import com.timerapp.model.TimerConfig; import java.io.*; import java.nio.file.Files; import java.util.Properties; /** * Сервис для работы с конфигурацией приложения */ public class ConfigService { private static final String APP_DIR_NAME = "DesktopTimer"; private static final String CONFIG_FILE_NAME = "timer-config.txt"; private static final String USER_DATA_DIR_NAME = "user_data"; // Пути к файлам в AppData private final File appDataDir; private final File configFile; private final File userDataDir; public ConfigService() { // Определяет системную папку для данных String userHome = System.getProperty("user.home"); String os = System.getProperty("os.name").toLowerCase(); File rootDir; if (os.contains("win")) { // Windows: %LOCALAPPDATA% или <user.home>/AppData/Local String localAppData = System.getenv("LOCALAPPDATA"); if (localAppData != null && !localAppData.isEmpty()) { rootDir = new File(localAppData); } else { rootDir = new File(userHome, "AppData/Local"); } } else if (os.contains("mac")) { // MacOS: ~/Library/Application Support rootDir = new File(userHome, "Library/Application Support"); } else { // Linux/Unix: ~/.local/share или ~/.config rootDir = new File(userHome, ".config"); } this.appDataDir = new File(rootDir, APP_DIR_NAME); this.configFile = new File(appDataDir, CONFIG_FILE_NAME); this.userDataDir = new File(appDataDir, USER_DATA_DIR_NAME); // Создает папки если нет if (!appDataDir.exists()) { appDataDir.mkdirs(); } if (!userDataDir.exists()) { userDataDir.mkdirs(); } System.out.println("Config dir: " + appDataDir.getAbsolutePath()); } /** * Загружает конфигурацию из файла * * @return объект TimerConfig */ public TimerConfig loadConfig() { Properties props = new Properties(); if (configFile.exists()) { try (FileInputStream fis = new FileInputStream(configFile)) { props.load(fis); } catch (IOException e) { System.err.println("Ошибка загрузки конфигурации: " + e.getMessage()); } } // Создает конфигурацию с помощью Builder TimerConfig.Builder builder = new TimerConfig.Builder(); String backgroundPath = props.getProperty("background_path", ""); String iconPath = props.getProperty("icon_path", ""); String soundPath = props.getProperty("sound_path", ""); boolean soundEnabled = Boolean.parseBoolean(props.getProperty("sound_enabled", "true")); String customPresetsStr = props.getProperty("custom_presets", ""); // Получает тему (или null, если её нет) String themeName = props.getProperty("theme_name"); String buttonGradient = props.getProperty("button_gradient", "None"); String buttonColor = props.getProperty("button_color", "#4a5568"); String buttonTextColor = props.getProperty("button_text_color", "#FFFFFF"); double buttonOpacity = Double.parseDouble(props.getProperty("button_opacity", "1.0")); String timerTextColor = props.getProperty("timer_text_color", "#FFFFFF"); String progressBarColor = props.getProperty("progress_bar_color", "#4CAF50"); builder.setBackgroundPath(backgroundPath) .setIconPath(iconPath) .setSoundPath(soundPath) .setSoundEnabled(soundEnabled); // Если тема сохранена - применяет её. Если нет (первый запуск) - остаётся // дефолтная из Builder (London) if (themeName != null) { builder.setThemeName(themeName); } builder.setButtonGradient(buttonGradient) .setButtonColor(buttonColor) .setButtonTextColor(buttonTextColor) .setButtonOpacity(buttonOpacity) .setTimerTextColor(timerTextColor) .setProgressBarColor(progressBarColor); // Парсит пользовательские пресеты if (!customPresetsStr.isEmpty()) { String[] presets = customPresetsStr.split(";"); builder.setCustomPresets(presets); System.out.println("[ConfigService] Загружены custom_presets: " + customPresetsStr); } return builder.build(); } /** * Сохраняет конфигурацию в файл * * @param config объект конфигурации */ public void saveConfig(TimerConfig config) { Properties props = new Properties(); props.setProperty("background_path", config.getBackgroundPath()); props.setProperty("icon_path", config.getIconPath()); props.setProperty("sound_path", config.getSoundPath()); props.setProperty("sound_enabled", String.valueOf(config.isSoundEnabled())); // Сохраняет название темы if (config.getThemeName() != null && !config.getThemeName().isEmpty()) { props.setProperty("theme_name", config.getThemeName()); } // Сохраняет пользовательские пресеты (всегда, даже если пустой) if (config.getCustomPresets() != null && config.getCustomPresets().length > 0) { String customPresetsStr = String.join(";", config.getCustomPresets()); props.setProperty("custom_presets", customPresetsStr); System.out.println("[ConfigService] Сохранены custom_presets: " + customPresetsStr); } else { props.setProperty("custom_presets", ""); System.out.println("[ConfigService] Очищены custom_presets"); } // Сохраняет настройки кнопок props.setProperty("button_gradient", config.getButtonGradient()); props.setProperty("button_color", config.getButtonColor()); props.setProperty("button_text_color", config.getButtonTextColor() != null ? config.getButtonTextColor() : "#FFFFFF"); props.setProperty("button_opacity", String.valueOf(config.getButtonOpacity())); // Сохраняет цвета таймера и прогресс-бара props.setProperty("timer_text_color", config.getTimerTextColor() != null ? config.getTimerTextColor() : "#FFFFFF"); props.setProperty("progress_bar_color", config.getProgressBarColor() != null ? config.getProgressBarColor() : "#4CAF50"); try (FileOutputStream fos = new FileOutputStream(configFile)) { props.store(fos, "Timer Application Configuration"); System.out.println("Конфигурация сохранена в " + configFile.getAbsolutePath()); } catch (IOException e) { System.err.println("Ошибка сохранения конфигурации: " + e.getMessage()); } } /** * Копирует пользовательский файл в директорию приложения * * @param sourcePath путь к исходному файлу * @param fileName имя файла для сохранения * @return путь к сохраненному файлу */ public String copyUserFile(String sourcePath, String fileName) { try { // Директория уже создана в конструкторе if (!userDataDir.exists()) { userDataDir.mkdirs(); } // Копирует файл File sourceFile = new File(sourcePath); File destFile = new File(userDataDir, fileName); Files.copy(sourceFile.toPath(), destFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING); return destFile.getAbsolutePath(); } catch (IOException e) { System.err.println("Ошибка копирования файла: " + e.getMessage()); return sourcePath; // Возвращает исходный путь в случае ошибки } } }