Migrate dictionary data from UserDefaults to SwiftData
Migrates vocabulary words and word replacements from UserDefaults to SwiftData for better data management and persistence. Changes: - Create VocabularyWord and WordReplacement SwiftData models - Add dual ModelConfiguration setup (default.store for transcripts, dictionary.store for dictionary data) - Implement DictionaryMigrationService for one-time UserDefaults→SwiftData migration - Rename "Correct Spellings" to "Vocabulary" for clearer terminology - Update all dictionary views to use @Query instead of manager classes - Update all services to fetch from SwiftData using FetchDescriptor - Enhance word replacement duplicate detection (now checks during add AND edit) - Update import/export services to work with SwiftData - Preserve all existing functionality with improved data integrity Technical details: - Separate store files: default.store (transcripts) + dictionary.store (vocabulary + replacements) - Migration flag: "HasMigratedDictionaryToSwiftData_v2" - All CRUD operations properly implemented with duplicate detection
This commit is contained in:
parent
2a9bf12e0e
commit
60125c316b
13
VoiceInk/Models/VocabularyWord.swift
Normal file
13
VoiceInk/Models/VocabularyWord.swift
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import Foundation
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
|
@Model
|
||||||
|
final class VocabularyWord {
|
||||||
|
@Attribute(.unique) var word: String
|
||||||
|
var dateAdded: Date
|
||||||
|
|
||||||
|
init(word: String, dateAdded: Date = Date()) {
|
||||||
|
self.word = word
|
||||||
|
self.dateAdded = dateAdded
|
||||||
|
}
|
||||||
|
}
|
||||||
19
VoiceInk/Models/WordReplacement.swift
Normal file
19
VoiceInk/Models/WordReplacement.swift
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import Foundation
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
|
@Model
|
||||||
|
final class WordReplacement {
|
||||||
|
var id: UUID
|
||||||
|
var originalText: String
|
||||||
|
var replacementText: String
|
||||||
|
var dateAdded: Date
|
||||||
|
var isEnabled: Bool
|
||||||
|
|
||||||
|
init(originalText: String, replacementText: String, dateAdded: Date = Date(), isEnabled: Bool = true) {
|
||||||
|
self.id = UUID()
|
||||||
|
self.originalText = originalText
|
||||||
|
self.replacementText = replacementText
|
||||||
|
self.dateAdded = dateAdded
|
||||||
|
self.isEnabled = isEnabled
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -167,7 +167,7 @@ class AIEnhancementService: ObservableObject {
|
|||||||
""
|
""
|
||||||
}
|
}
|
||||||
|
|
||||||
let customVocabulary = customVocabularyService.getCustomVocabulary()
|
let customVocabulary = customVocabularyService.getCustomVocabulary(from: modelContext)
|
||||||
|
|
||||||
let allContextSections = selectedTextContext + clipboardContext + screenCaptureContext
|
let allContextSections = selectedTextContext + clipboardContext + screenCaptureContext
|
||||||
|
|
||||||
|
|||||||
@ -96,7 +96,7 @@ class AudioTranscriptionManager: ObservableObject {
|
|||||||
text = WhisperTextFormatter.format(text)
|
text = WhisperTextFormatter.format(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
text = WordReplacementService.shared.applyReplacements(to: text)
|
text = WordReplacementService.shared.applyReplacements(to: text, using: modelContext)
|
||||||
|
|
||||||
// Handle enhancement if enabled
|
// Handle enhancement if enabled
|
||||||
if let enhancementService = whisperState.enhancementService,
|
if let enhancementService = whisperState.enhancementService,
|
||||||
|
|||||||
@ -55,7 +55,7 @@ class AudioTranscriptionService: ObservableObject {
|
|||||||
text = WhisperTextFormatter.format(text)
|
text = WhisperTextFormatter.format(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
text = WordReplacementService.shared.applyReplacements(to: text)
|
text = WordReplacementService.shared.applyReplacements(to: text, using: modelContext)
|
||||||
logger.notice("✅ Word replacements applied")
|
logger.notice("✅ Word replacements applied")
|
||||||
|
|
||||||
let audioAsset = AVURLAsset(url: url)
|
let audioAsset = AVURLAsset(url: url)
|
||||||
|
|||||||
@ -1,16 +1,14 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
class CustomVocabularyService {
|
class CustomVocabularyService {
|
||||||
static let shared = CustomVocabularyService()
|
static let shared = CustomVocabularyService()
|
||||||
|
|
||||||
private init() {
|
private init() {}
|
||||||
// Migrate old key to new key if needed
|
|
||||||
migrateOldDataIfNeeded()
|
|
||||||
}
|
|
||||||
|
|
||||||
func getCustomVocabulary() -> String {
|
func getCustomVocabulary(from context: ModelContext) -> String {
|
||||||
guard let customWords = getCustomVocabularyWords(), !customWords.isEmpty else {
|
guard let customWords = getCustomVocabularyWords(from: context), !customWords.isEmpty else {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -18,26 +16,15 @@ class CustomVocabularyService {
|
|||||||
return "Important Vocabulary: \(wordsText)"
|
return "Important Vocabulary: \(wordsText)"
|
||||||
}
|
}
|
||||||
|
|
||||||
private func getCustomVocabularyWords() -> [String]? {
|
private func getCustomVocabularyWords(from context: ModelContext) -> [String]? {
|
||||||
guard let data = UserDefaults.standard.data(forKey: "CustomVocabularyItems") else {
|
let descriptor = FetchDescriptor<VocabularyWord>(sortBy: [SortDescriptor(\VocabularyWord.word)])
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
do {
|
||||||
let items = try JSONDecoder().decode([VocabularyWord].self, from: data)
|
let items = try context.fetch(descriptor)
|
||||||
let words = items.map { $0.word }
|
let words = items.map { $0.word }
|
||||||
return words.isEmpty ? nil : words
|
return words.isEmpty ? nil : words
|
||||||
} catch {
|
} catch {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func migrateOldDataIfNeeded() {
|
|
||||||
// Migrate from old "CustomDictionaryItems" key to new "CustomVocabularyItems" key
|
|
||||||
if UserDefaults.standard.data(forKey: "CustomVocabularyItems") == nil,
|
|
||||||
let oldData = UserDefaults.standard.data(forKey: "CustomDictionaryItems") {
|
|
||||||
UserDefaults.standard.set(oldData, forKey: "CustomVocabularyItems")
|
|
||||||
UserDefaults.standard.removeObject(forKey: "CustomDictionaryItems")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import AppKit
|
import AppKit
|
||||||
import UniformTypeIdentifiers
|
import UniformTypeIdentifiers
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
struct DictionaryExportData: Codable {
|
struct DictionaryExportData: Codable {
|
||||||
let version: String
|
let version: String
|
||||||
@ -11,19 +12,23 @@ struct DictionaryExportData: Codable {
|
|||||||
|
|
||||||
class DictionaryImportExportService {
|
class DictionaryImportExportService {
|
||||||
static let shared = DictionaryImportExportService()
|
static let shared = DictionaryImportExportService()
|
||||||
private let dictionaryItemsKey = "CustomVocabularyItems"
|
|
||||||
private let wordReplacementsKey = "wordReplacements"
|
|
||||||
|
|
||||||
private init() {}
|
private init() {}
|
||||||
|
|
||||||
func exportDictionary() {
|
func exportDictionary(from context: ModelContext) {
|
||||||
|
// Fetch vocabulary words from SwiftData
|
||||||
var dictionaryWords: [String] = []
|
var dictionaryWords: [String] = []
|
||||||
if let data = UserDefaults.standard.data(forKey: dictionaryItemsKey),
|
let vocabularyDescriptor = FetchDescriptor<VocabularyWord>(sortBy: [SortDescriptor(\VocabularyWord.word)])
|
||||||
let items = try? JSONDecoder().decode([VocabularyWord].self, from: data) {
|
if let items = try? context.fetch(vocabularyDescriptor) {
|
||||||
dictionaryWords = items.map { $0.word }
|
dictionaryWords = items.map { $0.word }
|
||||||
}
|
}
|
||||||
|
|
||||||
let wordReplacements = UserDefaults.standard.dictionary(forKey: wordReplacementsKey) as? [String: String] ?? [:]
|
// Fetch word replacements from SwiftData
|
||||||
|
var wordReplacements: [String: String] = [:]
|
||||||
|
let replacementsDescriptor = FetchDescriptor<WordReplacement>()
|
||||||
|
if let replacements = try? context.fetch(replacementsDescriptor) {
|
||||||
|
wordReplacements = Dictionary(uniqueKeysWithValues: replacements.map { ($0.originalText, $0.replacementText) })
|
||||||
|
}
|
||||||
|
|
||||||
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0.0"
|
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0.0"
|
||||||
|
|
||||||
@ -66,7 +71,7 @@ class DictionaryImportExportService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func importDictionary() {
|
func importDictionary(into context: ModelContext) {
|
||||||
let openPanel = NSOpenPanel()
|
let openPanel = NSOpenPanel()
|
||||||
openPanel.allowedContentTypes = [UTType.json]
|
openPanel.allowedContentTypes = [UTType.json]
|
||||||
openPanel.canChooseFiles = true
|
openPanel.canChooseFiles = true
|
||||||
@ -88,63 +93,65 @@ class DictionaryImportExportService {
|
|||||||
decoder.dateDecodingStrategy = .iso8601
|
decoder.dateDecodingStrategy = .iso8601
|
||||||
let importedData = try decoder.decode(DictionaryExportData.self, from: jsonData)
|
let importedData = try decoder.decode(DictionaryExportData.self, from: jsonData)
|
||||||
|
|
||||||
var existingItems: [VocabularyWord] = []
|
// Fetch existing vocabulary words from SwiftData
|
||||||
if let data = UserDefaults.standard.data(forKey: self.dictionaryItemsKey),
|
let vocabularyDescriptor = FetchDescriptor<VocabularyWord>()
|
||||||
let items = try? JSONDecoder().decode([VocabularyWord].self, from: data) {
|
let existingItems = (try? context.fetch(vocabularyDescriptor)) ?? []
|
||||||
existingItems = items
|
|
||||||
}
|
|
||||||
|
|
||||||
let existingWordsLower = Set(existingItems.map { $0.word.lowercased() })
|
let existingWordsLower = Set(existingItems.map { $0.word.lowercased() })
|
||||||
let originalExistingCount = existingItems.count
|
let originalExistingCount = existingItems.count
|
||||||
var newWordsAdded = 0
|
var newWordsAdded = 0
|
||||||
|
|
||||||
|
// Import vocabulary words
|
||||||
for importedWord in importedData.vocabularyWords {
|
for importedWord in importedData.vocabularyWords {
|
||||||
if !existingWordsLower.contains(importedWord.lowercased()) {
|
if !existingWordsLower.contains(importedWord.lowercased()) {
|
||||||
existingItems.append(VocabularyWord(word: importedWord))
|
let newWord = VocabularyWord(word: importedWord)
|
||||||
|
context.insert(newWord)
|
||||||
newWordsAdded += 1
|
newWordsAdded += 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let encoded = try? JSONEncoder().encode(existingItems) {
|
// Fetch existing word replacements from SwiftData
|
||||||
UserDefaults.standard.set(encoded, forKey: self.dictionaryItemsKey)
|
let replacementsDescriptor = FetchDescriptor<WordReplacement>()
|
||||||
}
|
let existingReplacements = (try? context.fetch(replacementsDescriptor)) ?? []
|
||||||
|
|
||||||
var existingReplacements = UserDefaults.standard.dictionary(forKey: self.wordReplacementsKey) as? [String: String] ?? [:]
|
|
||||||
var addedCount = 0
|
var addedCount = 0
|
||||||
var updatedCount = 0
|
var updatedCount = 0
|
||||||
|
|
||||||
|
// Import word replacements
|
||||||
for (importedKey, importedReplacement) in importedData.wordReplacements {
|
for (importedKey, importedReplacement) in importedData.wordReplacements {
|
||||||
let normalizedImportedKey = self.normalizeReplacementKey(importedKey)
|
let normalizedImportedKey = self.normalizeReplacementKey(importedKey)
|
||||||
let importedWords = self.extractWords(from: normalizedImportedKey)
|
let importedWords = self.extractWords(from: normalizedImportedKey)
|
||||||
|
|
||||||
var modifiedExisting: [String: String] = [:]
|
// Check for conflicts and update existing replacements
|
||||||
for (existingKey, existingReplacement) in existingReplacements {
|
var hasConflict = false
|
||||||
var existingWords = self.extractWords(from: existingKey)
|
for existingReplacement in existingReplacements {
|
||||||
|
var existingWords = self.extractWords(from: existingReplacement.originalText)
|
||||||
var modified = false
|
var modified = false
|
||||||
|
|
||||||
for importedWord in importedWords {
|
for importedWord in importedWords {
|
||||||
if let index = existingWords.firstIndex(where: { $0.lowercased() == importedWord.lowercased() }) {
|
if let index = existingWords.firstIndex(where: { $0.lowercased() == importedWord.lowercased() }) {
|
||||||
existingWords.remove(at: index)
|
existingWords.remove(at: index)
|
||||||
modified = true
|
modified = true
|
||||||
|
hasConflict = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !existingWords.isEmpty {
|
|
||||||
let newKey = existingWords.joined(separator: ", ")
|
|
||||||
modifiedExisting[newKey] = existingReplacement
|
|
||||||
}
|
|
||||||
|
|
||||||
if modified {
|
if modified {
|
||||||
|
if existingWords.isEmpty {
|
||||||
|
context.delete(existingReplacement)
|
||||||
|
} else {
|
||||||
|
existingReplacement.originalText = existingWords.joined(separator: ", ")
|
||||||
|
}
|
||||||
updatedCount += 1
|
updatedCount += 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
existingReplacements = modifiedExisting
|
// Add new replacement
|
||||||
existingReplacements[normalizedImportedKey] = importedReplacement
|
let newReplacement = WordReplacement(originalText: normalizedImportedKey, replacementText: importedReplacement)
|
||||||
|
context.insert(newReplacement)
|
||||||
addedCount += 1
|
addedCount += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
UserDefaults.standard.set(existingReplacements, forKey: self.wordReplacementsKey)
|
// Save all changes
|
||||||
|
try context.save()
|
||||||
|
|
||||||
var message = "Dictionary data imported successfully from \(url.lastPathComponent).\n\n"
|
var message = "Dictionary data imported successfully from \(url.lastPathComponent).\n\n"
|
||||||
message += "Vocabulary Words: \(newWordsAdded) added, \(originalExistingCount) kept\n"
|
message += "Vocabulary Words: \(newWordsAdded) added, \(originalExistingCount) kept\n"
|
||||||
|
|||||||
99
VoiceInk/Services/DictionaryMigrationService.swift
Normal file
99
VoiceInk/Services/DictionaryMigrationService.swift
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
import Foundation
|
||||||
|
import SwiftData
|
||||||
|
import OSLog
|
||||||
|
|
||||||
|
class DictionaryMigrationService {
|
||||||
|
static let shared = DictionaryMigrationService()
|
||||||
|
private let logger = Logger(subsystem: "com.prakashjoshipax.voiceink", category: "DictionaryMigration")
|
||||||
|
|
||||||
|
private let migrationCompletedKey = "HasMigratedDictionaryToSwiftData_v2"
|
||||||
|
private let vocabularyKey = "CustomVocabularyItems"
|
||||||
|
private let wordReplacementsKey = "wordReplacements"
|
||||||
|
|
||||||
|
private init() {}
|
||||||
|
|
||||||
|
/// Migrates dictionary data from UserDefaults to SwiftData
|
||||||
|
/// This is a one-time operation that preserves all existing user data
|
||||||
|
func migrateIfNeeded(context: ModelContext) {
|
||||||
|
// Check if migration has already been completed
|
||||||
|
if UserDefaults.standard.bool(forKey: migrationCompletedKey) {
|
||||||
|
logger.info("Dictionary migration already completed, skipping")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("Starting dictionary migration from UserDefaults to SwiftData")
|
||||||
|
|
||||||
|
var vocabularyMigrated = 0
|
||||||
|
var replacementsMigrated = 0
|
||||||
|
|
||||||
|
// Migrate vocabulary words
|
||||||
|
if let data = UserDefaults.standard.data(forKey: vocabularyKey) {
|
||||||
|
do {
|
||||||
|
// Decode old vocabulary structure
|
||||||
|
let decoder = JSONDecoder()
|
||||||
|
let oldVocabulary = try decoder.decode([OldVocabularyWord].self, from: data)
|
||||||
|
|
||||||
|
logger.info("Found \(oldVocabulary.count) vocabulary words to migrate")
|
||||||
|
|
||||||
|
for oldWord in oldVocabulary {
|
||||||
|
let newWord = VocabularyWord(word: oldWord.word)
|
||||||
|
context.insert(newWord)
|
||||||
|
vocabularyMigrated += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("Successfully migrated \(vocabularyMigrated) vocabulary words")
|
||||||
|
} catch {
|
||||||
|
logger.error("Failed to migrate vocabulary words: \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("No vocabulary words found to migrate")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migrate word replacements
|
||||||
|
if let replacements = UserDefaults.standard.dictionary(forKey: wordReplacementsKey) as? [String: String] {
|
||||||
|
logger.info("Found \(replacements.count) word replacements to migrate")
|
||||||
|
|
||||||
|
for (originalText, replacementText) in replacements {
|
||||||
|
let wordReplacement = WordReplacement(
|
||||||
|
originalText: originalText,
|
||||||
|
replacementText: replacementText
|
||||||
|
)
|
||||||
|
context.insert(wordReplacement)
|
||||||
|
replacementsMigrated += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("Successfully migrated \(replacementsMigrated) word replacements")
|
||||||
|
} else {
|
||||||
|
logger.info("No word replacements found to migrate")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the migrated data
|
||||||
|
do {
|
||||||
|
try context.save()
|
||||||
|
logger.info("Successfully saved migrated data to SwiftData")
|
||||||
|
|
||||||
|
// Mark migration as completed
|
||||||
|
UserDefaults.standard.set(true, forKey: migrationCompletedKey)
|
||||||
|
logger.info("Migration completed successfully")
|
||||||
|
} catch {
|
||||||
|
logger.error("Failed to save migrated data: \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy structure for decoding old vocabulary data
|
||||||
|
private struct OldVocabularyWord: Decodable {
|
||||||
|
let word: String
|
||||||
|
|
||||||
|
private enum CodingKeys: String, CodingKey {
|
||||||
|
case id, word, dateAdded
|
||||||
|
}
|
||||||
|
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
word = try container.decode(String.self, forKey: .word)
|
||||||
|
// Ignore other fields that may exist in old format
|
||||||
|
_ = try? container.decodeIfPresent(UUID.self, forKey: .id)
|
||||||
|
_ = try? container.decodeIfPresent(Date.self, forKey: .dateAdded)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,6 +3,7 @@ import AppKit
|
|||||||
import UniformTypeIdentifiers
|
import UniformTypeIdentifiers
|
||||||
import KeyboardShortcuts
|
import KeyboardShortcuts
|
||||||
import LaunchAtLogin
|
import LaunchAtLogin
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
struct GeneralSettings: Codable {
|
struct GeneralSettings: Codable {
|
||||||
let toggleMiniRecorderShortcut: KeyboardShortcuts.Shortcut?
|
let toggleMiniRecorderShortcut: KeyboardShortcuts.Shortcut?
|
||||||
@ -28,11 +29,16 @@ struct GeneralSettings: Codable {
|
|||||||
let clipboardRestoreDelay: Double?
|
let clipboardRestoreDelay: Double?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Simple codable struct for vocabulary words (for export/import only)
|
||||||
|
struct VocabularyWordData: Codable {
|
||||||
|
let word: String
|
||||||
|
}
|
||||||
|
|
||||||
struct VoiceInkExportedSettings: Codable {
|
struct VoiceInkExportedSettings: Codable {
|
||||||
let version: String
|
let version: String
|
||||||
let customPrompts: [CustomPrompt]
|
let customPrompts: [CustomPrompt]
|
||||||
let powerModeConfigs: [PowerModeConfig]
|
let powerModeConfigs: [PowerModeConfig]
|
||||||
let vocabularyWords: [VocabularyWord]?
|
let vocabularyWords: [VocabularyWordData]?
|
||||||
let wordReplacements: [String: String]?
|
let wordReplacements: [String: String]?
|
||||||
let generalSettings: GeneralSettings?
|
let generalSettings: GeneralSettings?
|
||||||
let customEmojis: [String]?
|
let customEmojis: [String]?
|
||||||
@ -78,13 +84,19 @@ class ImportExportService {
|
|||||||
// Export custom models
|
// Export custom models
|
||||||
let customModels = CustomModelManager.shared.customModels
|
let customModels = CustomModelManager.shared.customModels
|
||||||
|
|
||||||
var exportedDictionaryItems: [VocabularyWord]? = nil
|
// Fetch vocabulary words from SwiftData
|
||||||
if let data = UserDefaults.standard.data(forKey: dictionaryItemsKey),
|
var exportedDictionaryItems: [VocabularyWordData]? = nil
|
||||||
let items = try? JSONDecoder().decode([VocabularyWord].self, from: data) {
|
let vocabularyDescriptor = FetchDescriptor<VocabularyWord>()
|
||||||
exportedDictionaryItems = items
|
if let items = try? whisperState.modelContext.fetch(vocabularyDescriptor), !items.isEmpty {
|
||||||
|
exportedDictionaryItems = items.map { VocabularyWordData(word: $0.word) }
|
||||||
}
|
}
|
||||||
|
|
||||||
let exportedWordReplacements = UserDefaults.standard.dictionary(forKey: wordReplacementsKey) as? [String: String]
|
// Fetch word replacements from SwiftData
|
||||||
|
var exportedWordReplacements: [String: String]? = nil
|
||||||
|
let replacementsDescriptor = FetchDescriptor<WordReplacement>()
|
||||||
|
if let replacements = try? whisperState.modelContext.fetch(replacementsDescriptor), !replacements.isEmpty {
|
||||||
|
exportedWordReplacements = Dictionary(uniqueKeysWithValues: replacements.map { ($0.originalText, $0.replacementText) })
|
||||||
|
}
|
||||||
|
|
||||||
let generalSettingsToExport = GeneralSettings(
|
let generalSettingsToExport = GeneralSettings(
|
||||||
toggleMiniRecorderShortcut: KeyboardShortcuts.getShortcut(for: .toggleMiniRecorder),
|
toggleMiniRecorderShortcut: KeyboardShortcuts.getShortcut(for: .toggleMiniRecorder),
|
||||||
@ -203,16 +215,32 @@ class ImportExportService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Import vocabulary words to SwiftData
|
||||||
if let itemsToImport = importedSettings.vocabularyWords {
|
if let itemsToImport = importedSettings.vocabularyWords {
|
||||||
if let encoded = try? JSONEncoder().encode(itemsToImport) {
|
let vocabularyDescriptor = FetchDescriptor<VocabularyWord>()
|
||||||
UserDefaults.standard.set(encoded, forKey: "CustomVocabularyItems")
|
let existingWords = (try? whisperState.modelContext.fetch(vocabularyDescriptor)) ?? []
|
||||||
|
let existingWordsSet = Set(existingWords.map { $0.word.lowercased() })
|
||||||
|
|
||||||
|
for item in itemsToImport {
|
||||||
|
if !existingWordsSet.contains(item.word.lowercased()) {
|
||||||
|
let newWord = VocabularyWord(word: item.word)
|
||||||
|
whisperState.modelContext.insert(newWord)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
try? whisperState.modelContext.save()
|
||||||
|
print("Successfully imported vocabulary words to SwiftData.")
|
||||||
} else {
|
} else {
|
||||||
print("No vocabulary words found in the imported file. Existing items remain unchanged.")
|
print("No vocabulary words found in the imported file. Existing items remain unchanged.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Import word replacements to SwiftData
|
||||||
if let replacementsToImport = importedSettings.wordReplacements {
|
if let replacementsToImport = importedSettings.wordReplacements {
|
||||||
UserDefaults.standard.set(replacementsToImport, forKey: self.wordReplacementsKey)
|
for (original, replacement) in replacementsToImport {
|
||||||
|
let newReplacement = WordReplacement(originalText: original, replacementText: replacement)
|
||||||
|
whisperState.modelContext.insert(newReplacement)
|
||||||
|
}
|
||||||
|
try? whisperState.modelContext.save()
|
||||||
|
print("Successfully imported word replacements to SwiftData.")
|
||||||
} else {
|
} else {
|
||||||
print("No word replacements found in the imported file. Existing replacements remain unchanged.")
|
print("No word replacements found in the imported file. Existing replacements remain unchanged.")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,20 +1,27 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
class WordReplacementService {
|
class WordReplacementService {
|
||||||
static let shared = WordReplacementService()
|
static let shared = WordReplacementService()
|
||||||
|
|
||||||
private init() {}
|
private init() {}
|
||||||
|
|
||||||
func applyReplacements(to text: String) -> String {
|
func applyReplacements(to text: String, using context: ModelContext) -> String {
|
||||||
guard let replacements = UserDefaults.standard.dictionary(forKey: "wordReplacements") as? [String: String],
|
let descriptor = FetchDescriptor<WordReplacement>(
|
||||||
!replacements.isEmpty else {
|
predicate: #Predicate { $0.isEnabled }
|
||||||
|
)
|
||||||
|
|
||||||
|
guard let replacements = try? context.fetch(descriptor), !replacements.isEmpty else {
|
||||||
return text // No replacements to apply
|
return text // No replacements to apply
|
||||||
}
|
}
|
||||||
|
|
||||||
var modifiedText = text
|
var modifiedText = text
|
||||||
|
|
||||||
// Apply replacements (case-insensitive)
|
// Apply replacements (case-insensitive)
|
||||||
for (originalGroup, replacement) in replacements {
|
for replacement in replacements {
|
||||||
|
let originalGroup = replacement.originalText
|
||||||
|
let replacementText = replacement.replacementText
|
||||||
|
|
||||||
// Split comma-separated originals at apply time only
|
// Split comma-separated originals at apply time only
|
||||||
let variants = originalGroup
|
let variants = originalGroup
|
||||||
.split(separator: ",")
|
.split(separator: ",")
|
||||||
@ -33,16 +40,16 @@ class WordReplacementService {
|
|||||||
in: modifiedText,
|
in: modifiedText,
|
||||||
options: [],
|
options: [],
|
||||||
range: range,
|
range: range,
|
||||||
withTemplate: replacement
|
withTemplate: replacementText
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Fallback substring replace for non-spaced scripts
|
// Fallback substring replace for non-spaced scripts
|
||||||
modifiedText = modifiedText.replacingOccurrences(of: original, with: replacement, options: .caseInsensitive)
|
modifiedText = modifiedText.replacingOccurrences(of: original, with: replacementText, options: .caseInsensitive)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return modifiedText
|
return modifiedText
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
struct DictionarySettingsView: View {
|
struct DictionarySettingsView: View {
|
||||||
|
@Environment(\.modelContext) private var modelContext
|
||||||
@State private var selectedSection: DictionarySection = .replacements
|
@State private var selectedSection: DictionarySection = .replacements
|
||||||
let whisperPrompt: WhisperPrompt
|
let whisperPrompt: WhisperPrompt
|
||||||
|
|
||||||
@ -83,7 +85,7 @@ struct DictionarySettingsView: View {
|
|||||||
|
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
Button(action: {
|
Button(action: {
|
||||||
DictionaryImportExportService.shared.importDictionary()
|
DictionaryImportExportService.shared.importDictionary(into: modelContext)
|
||||||
}) {
|
}) {
|
||||||
Image(systemName: "square.and.arrow.down")
|
Image(systemName: "square.and.arrow.down")
|
||||||
.font(.system(size: 18))
|
.font(.system(size: 18))
|
||||||
@ -93,7 +95,7 @@ struct DictionarySettingsView: View {
|
|||||||
.help("Import vocabulary and word replacements")
|
.help("Import vocabulary and word replacements")
|
||||||
|
|
||||||
Button(action: {
|
Button(action: {
|
||||||
DictionaryImportExportService.shared.exportDictionary()
|
DictionaryImportExportService.shared.exportDictionary(from: modelContext)
|
||||||
}) {
|
}) {
|
||||||
Image(systemName: "square.and.arrow.up")
|
Image(systemName: "square.and.arrow.up")
|
||||||
.font(.system(size: 18))
|
.font(.system(size: 18))
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
// Edit existing word replacement entry
|
// Edit existing word replacement entry
|
||||||
struct EditReplacementSheet: View {
|
struct EditReplacementSheet: View {
|
||||||
@ObservedObject var manager: WordReplacementManager
|
let replacement: WordReplacement
|
||||||
let originalKey: String
|
let modelContext: ModelContext
|
||||||
|
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
@ -12,11 +14,11 @@ struct EditReplacementSheet: View {
|
|||||||
@State private var alertMessage = ""
|
@State private var alertMessage = ""
|
||||||
|
|
||||||
// MARK: – Initialiser
|
// MARK: – Initialiser
|
||||||
init(manager: WordReplacementManager, originalKey: String) {
|
init(replacement: WordReplacement, modelContext: ModelContext) {
|
||||||
self.manager = manager
|
self.replacement = replacement
|
||||||
self.originalKey = originalKey
|
self.modelContext = modelContext
|
||||||
_originalWord = State(initialValue: originalKey)
|
_originalWord = State(initialValue: replacement.originalText)
|
||||||
_replacementWord = State(initialValue: manager.replacements[originalKey] ?? "")
|
_replacementWord = State(initialValue: replacement.replacementText)
|
||||||
}
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@ -128,25 +130,37 @@ struct EditReplacementSheet: View {
|
|||||||
.filter { !$0.isEmpty }
|
.filter { !$0.isEmpty }
|
||||||
guard !tokens.isEmpty, !newReplacement.isEmpty else { return }
|
guard !tokens.isEmpty, !newReplacement.isEmpty else { return }
|
||||||
|
|
||||||
let result = manager.updateReplacement(oldOriginal: originalKey, newOriginal: newOriginal, newReplacement: newReplacement)
|
// Check for duplicates (excluding current replacement)
|
||||||
if result.success {
|
let newTokensPairs = tokens.map { (original: $0, lowercased: $0.lowercased()) }
|
||||||
dismiss()
|
|
||||||
} else {
|
|
||||||
if let conflictingWord = result.conflictingWord {
|
|
||||||
alertMessage = "'\(conflictingWord)' already exists in word replacements"
|
|
||||||
} else {
|
|
||||||
alertMessage = "This word replacement already exists"
|
|
||||||
}
|
|
||||||
showAlert = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: – Preview
|
let descriptor = FetchDescriptor<WordReplacement>()
|
||||||
#if DEBUG
|
if let allReplacements = try? modelContext.fetch(descriptor) {
|
||||||
struct EditReplacementSheet_Previews: PreviewProvider {
|
for existingReplacement in allReplacements {
|
||||||
static var previews: some View {
|
// Skip checking against itself
|
||||||
EditReplacementSheet(manager: WordReplacementManager(), originalKey: "hello")
|
if existingReplacement.id == replacement.id {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
let existingTokens = existingReplacement.originalText
|
||||||
|
.split(separator: ",")
|
||||||
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
|
||||||
|
.filter { !$0.isEmpty }
|
||||||
|
|
||||||
|
for tokenPair in newTokensPairs {
|
||||||
|
if existingTokens.contains(tokenPair.lowercased) {
|
||||||
|
alertMessage = "'\(tokenPair.original)' already exists in word replacements"
|
||||||
|
showAlert = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the replacement
|
||||||
|
replacement.originalText = newOriginal
|
||||||
|
replacement.replacementText = newReplacement
|
||||||
|
try? modelContext.save()
|
||||||
|
|
||||||
|
dismiss()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
@ -1,83 +1,14 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SwiftData
|
||||||
struct VocabularyWord: Identifiable, Hashable, Codable {
|
|
||||||
var word: String
|
|
||||||
|
|
||||||
var id: String { word }
|
|
||||||
|
|
||||||
init(word: String) {
|
|
||||||
self.word = word
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum CodingKeys: String, CodingKey {
|
|
||||||
case id, word, dateAdded
|
|
||||||
}
|
|
||||||
|
|
||||||
init(from decoder: Decoder) throws {
|
|
||||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
|
||||||
word = try container.decode(String.self, forKey: .word)
|
|
||||||
_ = try? container.decodeIfPresent(UUID.self, forKey: .id)
|
|
||||||
_ = try? container.decodeIfPresent(Date.self, forKey: .dateAdded)
|
|
||||||
}
|
|
||||||
|
|
||||||
func encode(to encoder: Encoder) throws {
|
|
||||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
|
||||||
try container.encode(word, forKey: .word)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum VocabularySortMode: String {
|
enum VocabularySortMode: String {
|
||||||
case wordAsc = "wordAsc"
|
case wordAsc = "wordAsc"
|
||||||
case wordDesc = "wordDesc"
|
case wordDesc = "wordDesc"
|
||||||
}
|
}
|
||||||
|
|
||||||
class VocabularyManager: ObservableObject {
|
|
||||||
@Published var items: [VocabularyWord] = []
|
|
||||||
private let saveKey = "CustomVocabularyItems"
|
|
||||||
private let whisperPrompt: WhisperPrompt
|
|
||||||
|
|
||||||
init(whisperPrompt: WhisperPrompt) {
|
|
||||||
self.whisperPrompt = whisperPrompt
|
|
||||||
loadItems()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func loadItems() {
|
|
||||||
guard let data = UserDefaults.standard.data(forKey: saveKey) else { return }
|
|
||||||
|
|
||||||
if let savedItems = try? JSONDecoder().decode([VocabularyWord].self, from: data) {
|
|
||||||
items = savedItems
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func saveItems() {
|
|
||||||
if let encoded = try? JSONEncoder().encode(items) {
|
|
||||||
UserDefaults.standard.set(encoded, forKey: saveKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func addWord(_ word: String) {
|
|
||||||
let normalizedWord = word.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
||||||
guard !items.contains(where: { $0.word.lowercased() == normalizedWord.lowercased() }) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let newItem = VocabularyWord(word: normalizedWord)
|
|
||||||
items.insert(newItem, at: 0)
|
|
||||||
saveItems()
|
|
||||||
}
|
|
||||||
|
|
||||||
func removeWord(_ word: String) {
|
|
||||||
items.removeAll(where: { $0.word == word })
|
|
||||||
saveItems()
|
|
||||||
}
|
|
||||||
|
|
||||||
var allWords: [String] {
|
|
||||||
items.map { $0.word }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct VocabularyView: View {
|
struct VocabularyView: View {
|
||||||
@StateObject private var vocabularyManager: VocabularyManager
|
@Query private var vocabularyWords: [VocabularyWord]
|
||||||
|
@Environment(\.modelContext) private var modelContext
|
||||||
@ObservedObject var whisperPrompt: WhisperPrompt
|
@ObservedObject var whisperPrompt: WhisperPrompt
|
||||||
@State private var newWord = ""
|
@State private var newWord = ""
|
||||||
@State private var showAlert = false
|
@State private var showAlert = false
|
||||||
@ -86,7 +17,6 @@ struct VocabularyView: View {
|
|||||||
|
|
||||||
init(whisperPrompt: WhisperPrompt) {
|
init(whisperPrompt: WhisperPrompt) {
|
||||||
self.whisperPrompt = whisperPrompt
|
self.whisperPrompt = whisperPrompt
|
||||||
_vocabularyManager = StateObject(wrappedValue: VocabularyManager(whisperPrompt: whisperPrompt))
|
|
||||||
|
|
||||||
if let savedSort = UserDefaults.standard.string(forKey: "vocabularySortMode"),
|
if let savedSort = UserDefaults.standard.string(forKey: "vocabularySortMode"),
|
||||||
let mode = VocabularySortMode(rawValue: savedSort) {
|
let mode = VocabularySortMode(rawValue: savedSort) {
|
||||||
@ -97,9 +27,9 @@ struct VocabularyView: View {
|
|||||||
private var sortedItems: [VocabularyWord] {
|
private var sortedItems: [VocabularyWord] {
|
||||||
switch sortMode {
|
switch sortMode {
|
||||||
case .wordAsc:
|
case .wordAsc:
|
||||||
return vocabularyManager.items.sorted { $0.word.localizedCaseInsensitiveCompare($1.word) == .orderedAscending }
|
return vocabularyWords.sorted { $0.word.localizedCaseInsensitiveCompare($1.word) == .orderedAscending }
|
||||||
case .wordDesc:
|
case .wordDesc:
|
||||||
return vocabularyManager.items.sorted { $0.word.localizedCaseInsensitiveCompare($1.word) == .orderedDescending }
|
return vocabularyWords.sorted { $0.word.localizedCaseInsensitiveCompare($1.word) == .orderedDescending }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,11 +76,11 @@ struct VocabularyView: View {
|
|||||||
}
|
}
|
||||||
.animation(.easeInOut(duration: 0.2), value: shouldShowAddButton)
|
.animation(.easeInOut(duration: 0.2), value: shouldShowAddButton)
|
||||||
|
|
||||||
if !vocabularyManager.items.isEmpty {
|
if !vocabularyWords.isEmpty {
|
||||||
VStack(alignment: .leading, spacing: 12) {
|
VStack(alignment: .leading, spacing: 12) {
|
||||||
Button(action: toggleSort) {
|
Button(action: toggleSort) {
|
||||||
HStack(spacing: 4) {
|
HStack(spacing: 4) {
|
||||||
Text("Vocabulary Words (\(vocabularyManager.items.count))")
|
Text("Vocabulary Words (\(vocabularyWords.count))")
|
||||||
.font(.system(size: 12, weight: .medium))
|
.font(.system(size: 12, weight: .medium))
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
|
|
||||||
@ -166,7 +96,7 @@ struct VocabularyView: View {
|
|||||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 240, maximum: .infinity), spacing: 12)], alignment: .leading, spacing: 12) {
|
LazyVGrid(columns: [GridItem(.adaptive(minimum: 240, maximum: .infinity), spacing: 12)], alignment: .leading, spacing: 12) {
|
||||||
ForEach(sortedItems) { item in
|
ForEach(sortedItems) { item in
|
||||||
VocabularyWordView(item: item) {
|
VocabularyWordView(item: item) {
|
||||||
vocabularyManager.removeWord(item.word)
|
removeWord(item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -188,33 +118,49 @@ struct VocabularyView: View {
|
|||||||
private func addWords() {
|
private func addWords() {
|
||||||
let input = newWord.trimmingCharacters(in: .whitespacesAndNewlines)
|
let input = newWord.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !input.isEmpty else { return }
|
guard !input.isEmpty else { return }
|
||||||
|
|
||||||
let parts = input
|
let parts = input
|
||||||
.split(separator: ",")
|
.split(separator: ",")
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||||
.filter { !$0.isEmpty }
|
.filter { !$0.isEmpty }
|
||||||
|
|
||||||
guard !parts.isEmpty else { return }
|
guard !parts.isEmpty else { return }
|
||||||
|
|
||||||
if parts.count == 1, let word = parts.first {
|
if parts.count == 1, let word = parts.first {
|
||||||
if vocabularyManager.items.contains(where: { $0.word.lowercased() == word.lowercased() }) {
|
if vocabularyWords.contains(where: { $0.word.lowercased() == word.lowercased() }) {
|
||||||
alertMessage = "'\(word)' is already in the vocabulary"
|
alertMessage = "'\(word)' is already in the vocabulary"
|
||||||
showAlert = true
|
showAlert = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
vocabularyManager.addWord(word)
|
addWord(word)
|
||||||
newWord = ""
|
newWord = ""
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for word in parts {
|
for word in parts {
|
||||||
let lower = word.lowercased()
|
let lower = word.lowercased()
|
||||||
if !vocabularyManager.items.contains(where: { $0.word.lowercased() == lower }) {
|
if !vocabularyWords.contains(where: { $0.word.lowercased() == lower }) {
|
||||||
vocabularyManager.addWord(word)
|
addWord(word)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
newWord = ""
|
newWord = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func addWord(_ word: String) {
|
||||||
|
let normalizedWord = word.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !vocabularyWords.contains(where: { $0.word.lowercased() == normalizedWord.lowercased() }) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let newWord = VocabularyWord(word: normalizedWord)
|
||||||
|
modelContext.insert(newWord)
|
||||||
|
try? modelContext.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func removeWord(_ word: VocabularyWord) {
|
||||||
|
modelContext.delete(word)
|
||||||
|
try? modelContext.save()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct VocabularyWordView: View {
|
struct VocabularyWordView: View {
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SwiftData
|
||||||
|
|
||||||
extension String: Identifiable {
|
extension String: Identifiable {
|
||||||
public var id: String { self }
|
public var id: String { self }
|
||||||
@ -16,110 +17,34 @@ enum SortColumn {
|
|||||||
case replacement
|
case replacement
|
||||||
}
|
}
|
||||||
|
|
||||||
class WordReplacementManager: ObservableObject {
|
|
||||||
@Published var replacements: [String: String] {
|
|
||||||
didSet {
|
|
||||||
UserDefaults.standard.set(replacements, forKey: "wordReplacements")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
init() {
|
|
||||||
self.replacements = UserDefaults.standard.dictionary(forKey: "wordReplacements") as? [String: String] ?? [:]
|
|
||||||
}
|
|
||||||
|
|
||||||
func addReplacement(original: String, replacement: String) -> (success: Bool, conflictingWord: String?) {
|
|
||||||
let trimmed = original.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
||||||
guard !trimmed.isEmpty else { return (false, nil) }
|
|
||||||
|
|
||||||
let newTokensPairs = trimmed
|
|
||||||
.split(separator: ",")
|
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
|
||||||
.filter { !$0.isEmpty }
|
|
||||||
.map { (original: $0, lowercased: $0.lowercased()) }
|
|
||||||
|
|
||||||
for existingKey in replacements.keys {
|
|
||||||
let existingTokens = existingKey
|
|
||||||
.split(separator: ",")
|
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
|
|
||||||
.filter { !$0.isEmpty }
|
|
||||||
|
|
||||||
for tokenPair in newTokensPairs {
|
|
||||||
if existingTokens.contains(tokenPair.lowercased) {
|
|
||||||
return (false, tokenPair.original)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
replacements[trimmed] = replacement
|
|
||||||
return (true, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
func removeReplacement(original: String) {
|
|
||||||
replacements.removeValue(forKey: original)
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateReplacement(oldOriginal: String, newOriginal: String, newReplacement: String) -> (success: Bool, conflictingWord: String?) {
|
|
||||||
let trimmed = newOriginal.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
||||||
guard !trimmed.isEmpty else { return (false, nil) }
|
|
||||||
|
|
||||||
let newTokensPairs = trimmed
|
|
||||||
.split(separator: ",")
|
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
|
||||||
.filter { !$0.isEmpty }
|
|
||||||
.map { (original: $0, lowercased: $0.lowercased()) }
|
|
||||||
|
|
||||||
for existingKey in replacements.keys {
|
|
||||||
if existingKey == oldOriginal {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
let existingTokens = existingKey
|
|
||||||
.split(separator: ",")
|
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
|
|
||||||
.filter { !$0.isEmpty }
|
|
||||||
|
|
||||||
for tokenPair in newTokensPairs {
|
|
||||||
if existingTokens.contains(tokenPair.lowercased) {
|
|
||||||
return (false, tokenPair.original)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
replacements.removeValue(forKey: oldOriginal)
|
|
||||||
replacements[trimmed] = newReplacement
|
|
||||||
return (true, nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct WordReplacementView: View {
|
struct WordReplacementView: View {
|
||||||
@StateObject private var manager = WordReplacementManager()
|
@Query private var wordReplacements: [WordReplacement]
|
||||||
|
@Environment(\.modelContext) private var modelContext
|
||||||
@State private var showAlert = false
|
@State private var showAlert = false
|
||||||
@State private var editingOriginal: String? = nil
|
@State private var editingReplacement: WordReplacement? = nil
|
||||||
@State private var alertMessage = ""
|
@State private var alertMessage = ""
|
||||||
@State private var sortMode: SortMode = .originalAsc
|
@State private var sortMode: SortMode = .originalAsc
|
||||||
@State private var originalWord = ""
|
@State private var originalWord = ""
|
||||||
@State private var replacementWord = ""
|
@State private var replacementWord = ""
|
||||||
@State private var showInfoPopover = false
|
@State private var showInfoPopover = false
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
if let savedSort = UserDefaults.standard.string(forKey: "wordReplacementSortMode"),
|
if let savedSort = UserDefaults.standard.string(forKey: "wordReplacementSortMode"),
|
||||||
let mode = SortMode(rawValue: savedSort) {
|
let mode = SortMode(rawValue: savedSort) {
|
||||||
_sortMode = State(initialValue: mode)
|
_sortMode = State(initialValue: mode)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var sortedReplacements: [(key: String, value: String)] {
|
private var sortedReplacements: [WordReplacement] {
|
||||||
let pairs = Array(manager.replacements)
|
|
||||||
|
|
||||||
switch sortMode {
|
switch sortMode {
|
||||||
case .originalAsc:
|
case .originalAsc:
|
||||||
return pairs.sorted { $0.key.localizedCaseInsensitiveCompare($1.key) == .orderedAscending }
|
return wordReplacements.sorted { $0.originalText.localizedCaseInsensitiveCompare($1.originalText) == .orderedAscending }
|
||||||
case .originalDesc:
|
case .originalDesc:
|
||||||
return pairs.sorted { $0.key.localizedCaseInsensitiveCompare($1.key) == .orderedDescending }
|
return wordReplacements.sorted { $0.originalText.localizedCaseInsensitiveCompare($1.originalText) == .orderedDescending }
|
||||||
case .replacementAsc:
|
case .replacementAsc:
|
||||||
return pairs.sorted { $0.value.localizedCaseInsensitiveCompare($1.value) == .orderedAscending }
|
return wordReplacements.sorted { $0.replacementText.localizedCaseInsensitiveCompare($1.replacementText) == .orderedAscending }
|
||||||
case .replacementDesc:
|
case .replacementDesc:
|
||||||
return pairs.sorted { $0.value.localizedCaseInsensitiveCompare($1.value) == .orderedDescending }
|
return wordReplacements.sorted { $0.replacementText.localizedCaseInsensitiveCompare($1.replacementText) == .orderedDescending }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -186,7 +111,7 @@ struct WordReplacementView: View {
|
|||||||
}
|
}
|
||||||
.animation(.easeInOut(duration: 0.2), value: shouldShowAddButton)
|
.animation(.easeInOut(duration: 0.2), value: shouldShowAddButton)
|
||||||
|
|
||||||
if !manager.replacements.isEmpty {
|
if !wordReplacements.isEmpty {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
Button(action: { toggleSort(for: .original) }) {
|
Button(action: { toggleSort(for: .original) }) {
|
||||||
@ -235,15 +160,15 @@ struct WordReplacementView: View {
|
|||||||
|
|
||||||
ScrollView {
|
ScrollView {
|
||||||
LazyVStack(spacing: 0) {
|
LazyVStack(spacing: 0) {
|
||||||
ForEach(sortedReplacements, id: \.key) { pair in
|
ForEach(sortedReplacements) { replacement in
|
||||||
ReplacementRow(
|
ReplacementRow(
|
||||||
original: pair.key,
|
original: replacement.originalText,
|
||||||
replacement: pair.value,
|
replacement: replacement.replacementText,
|
||||||
onDelete: { manager.removeReplacement(original: pair.key) },
|
onDelete: { removeReplacement(replacement) },
|
||||||
onEdit: { editingOriginal = pair.key }
|
onEdit: { editingReplacement = replacement }
|
||||||
)
|
)
|
||||||
|
|
||||||
if pair.key != sortedReplacements.last?.key {
|
if replacement.id != sortedReplacements.last?.id {
|
||||||
Divider()
|
Divider()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -255,8 +180,8 @@ struct WordReplacementView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding()
|
.padding()
|
||||||
.sheet(item: $editingOriginal) { original in
|
.sheet(item: $editingReplacement) { replacement in
|
||||||
EditReplacementSheet(manager: manager, originalKey: original)
|
EditReplacementSheet(replacement: replacement, modelContext: modelContext)
|
||||||
}
|
}
|
||||||
.alert("Word Replacement", isPresented: $showAlert) {
|
.alert("Word Replacement", isPresented: $showAlert) {
|
||||||
Button("OK", role: .cancel) {}
|
Button("OK", role: .cancel) {}
|
||||||
@ -275,18 +200,36 @@ struct WordReplacementView: View {
|
|||||||
.filter { !$0.isEmpty }
|
.filter { !$0.isEmpty }
|
||||||
guard !tokens.isEmpty && !replacement.isEmpty else { return }
|
guard !tokens.isEmpty && !replacement.isEmpty else { return }
|
||||||
|
|
||||||
let result = manager.addReplacement(original: original, replacement: replacement)
|
// Check for duplicates
|
||||||
if result.success {
|
let newTokensPairs = tokens.map { (original: $0, lowercased: $0.lowercased()) }
|
||||||
originalWord = ""
|
|
||||||
replacementWord = ""
|
for existingReplacement in wordReplacements {
|
||||||
} else {
|
let existingTokens = existingReplacement.originalText
|
||||||
if let conflictingWord = result.conflictingWord {
|
.split(separator: ",")
|
||||||
alertMessage = "'\(conflictingWord)' already exists in word replacements"
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
|
||||||
} else {
|
.filter { !$0.isEmpty }
|
||||||
alertMessage = "This word replacement already exists"
|
|
||||||
|
for tokenPair in newTokensPairs {
|
||||||
|
if existingTokens.contains(tokenPair.lowercased) {
|
||||||
|
alertMessage = "'\(tokenPair.original)' already exists in word replacements"
|
||||||
|
showAlert = true
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
showAlert = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add new replacement
|
||||||
|
let newReplacement = WordReplacement(originalText: original, replacementText: replacement)
|
||||||
|
modelContext.insert(newReplacement)
|
||||||
|
try? modelContext.save()
|
||||||
|
|
||||||
|
originalWord = ""
|
||||||
|
replacementWord = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private func removeReplacement(_ replacement: WordReplacement) {
|
||||||
|
modelContext.delete(replacement)
|
||||||
|
try? modelContext.save()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -42,13 +42,17 @@ struct VoiceInkApp: App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let logger = Logger(subsystem: "com.prakashjoshipax.voiceink", category: "Initialization")
|
let logger = Logger(subsystem: "com.prakashjoshipax.voiceink", category: "Initialization")
|
||||||
let schema = Schema([Transcription.self])
|
let schema = Schema([
|
||||||
|
Transcription.self,
|
||||||
|
VocabularyWord.self,
|
||||||
|
WordReplacement.self
|
||||||
|
])
|
||||||
var initializationFailed = false
|
var initializationFailed = false
|
||||||
|
|
||||||
// Attempt 1: Try persistent storage
|
// Attempt 1: Try persistent storage
|
||||||
if let persistentContainer = Self.createPersistentContainer(schema: schema, logger: logger) {
|
if let persistentContainer = Self.createPersistentContainer(schema: schema, logger: logger) {
|
||||||
container = persistentContainer
|
container = persistentContainer
|
||||||
|
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
// Print SwiftData storage location in debug builds only
|
// Print SwiftData storage location in debug builds only
|
||||||
if let url = persistentContainer.mainContext.container.configurations.first?.url {
|
if let url = persistentContainer.mainContext.container.configurations.first?.url {
|
||||||
@ -59,9 +63,9 @@ struct VoiceInkApp: App {
|
|||||||
// Attempt 2: Try in-memory storage
|
// Attempt 2: Try in-memory storage
|
||||||
else if let memoryContainer = Self.createInMemoryContainer(schema: schema, logger: logger) {
|
else if let memoryContainer = Self.createInMemoryContainer(schema: schema, logger: logger) {
|
||||||
container = memoryContainer
|
container = memoryContainer
|
||||||
|
|
||||||
logger.warning("Using in-memory storage as fallback. Data will not persist between sessions.")
|
logger.warning("Using in-memory storage as fallback. Data will not persist between sessions.")
|
||||||
|
|
||||||
// Show alert to user about storage issue
|
// Show alert to user about storage issue
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
let alert = NSAlert()
|
let alert = NSAlert()
|
||||||
@ -72,19 +76,16 @@ struct VoiceInkApp: App {
|
|||||||
alert.runModal()
|
alert.runModal()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Attempt 3: Try ultra-minimal default container
|
// All attempts failed
|
||||||
else if let minimalContainer = Self.createMinimalContainer(schema: schema, logger: logger) {
|
|
||||||
container = minimalContainer
|
|
||||||
logger.warning("Using minimal emergency container")
|
|
||||||
}
|
|
||||||
// All attempts failed: Create disabled container and mark for termination
|
|
||||||
else {
|
else {
|
||||||
logger.critical("All ModelContainer initialization attempts failed")
|
logger.critical("ModelContainer initialization failed")
|
||||||
initializationFailed = true
|
initializationFailed = true
|
||||||
|
|
||||||
// Create a dummy container to satisfy Swift's initialization requirements
|
// Create minimal in-memory container to satisfy initialization
|
||||||
// App will show error and terminate in onAppear
|
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
|
||||||
container = Self.createDummyContainer(schema: schema)
|
container = (try? ModelContainer(for: schema, configurations: [config])) ?? {
|
||||||
|
preconditionFailure("Unable to create ModelContainer. SwiftData is unavailable.")
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
containerInitializationFailed = initializationFailed
|
containerInitializationFailed = initializationFailed
|
||||||
@ -134,15 +135,37 @@ struct VoiceInkApp: App {
|
|||||||
// Create app-specific Application Support directory URL
|
// Create app-specific Application Support directory URL
|
||||||
let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||||||
.appendingPathComponent("com.prakashjoshipax.VoiceInk", isDirectory: true)
|
.appendingPathComponent("com.prakashjoshipax.VoiceInk", isDirectory: true)
|
||||||
|
|
||||||
// Create the directory if it doesn't exist
|
// Create the directory if it doesn't exist
|
||||||
try? FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true)
|
try? FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true)
|
||||||
|
|
||||||
// Configure SwiftData to use the conventional location
|
// Define storage locations
|
||||||
let storeURL = appSupportURL.appendingPathComponent("default.store")
|
let defaultStoreURL = appSupportURL.appendingPathComponent("default.store")
|
||||||
let modelConfiguration = ModelConfiguration(schema: schema, url: storeURL)
|
let dictionaryStoreURL = appSupportURL.appendingPathComponent("dictionary.store")
|
||||||
|
|
||||||
return try ModelContainer(for: schema, configurations: [modelConfiguration])
|
// Transcript configuration
|
||||||
|
let transcriptSchema = Schema([Transcription.self])
|
||||||
|
let transcriptConfig = ModelConfiguration(
|
||||||
|
"default",
|
||||||
|
schema: transcriptSchema,
|
||||||
|
url: defaultStoreURL,
|
||||||
|
cloudKitDatabase: .none
|
||||||
|
)
|
||||||
|
|
||||||
|
// Dictionary configuration
|
||||||
|
let dictionarySchema = Schema([VocabularyWord.self, WordReplacement.self])
|
||||||
|
let dictionaryConfig = ModelConfiguration(
|
||||||
|
"dictionary",
|
||||||
|
schema: dictionarySchema,
|
||||||
|
url: dictionaryStoreURL,
|
||||||
|
cloudKitDatabase: .none
|
||||||
|
)
|
||||||
|
|
||||||
|
// Initialize container
|
||||||
|
return try ModelContainer(
|
||||||
|
for: schema,
|
||||||
|
configurations: transcriptConfig, dictionaryConfig
|
||||||
|
)
|
||||||
} catch {
|
} catch {
|
||||||
logger.error("Failed to create persistent ModelContainer: \(error.localizedDescription)")
|
logger.error("Failed to create persistent ModelContainer: \(error.localizedDescription)")
|
||||||
return nil
|
return nil
|
||||||
@ -151,45 +174,29 @@ struct VoiceInkApp: App {
|
|||||||
|
|
||||||
private static func createInMemoryContainer(schema: Schema, logger: Logger) -> ModelContainer? {
|
private static func createInMemoryContainer(schema: Schema, logger: Logger) -> ModelContainer? {
|
||||||
do {
|
do {
|
||||||
let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
|
// Transcript configuration
|
||||||
return try ModelContainer(for: schema, configurations: [configuration])
|
let transcriptSchema = Schema([Transcription.self])
|
||||||
|
let transcriptConfig = ModelConfiguration(
|
||||||
|
"default",
|
||||||
|
schema: transcriptSchema,
|
||||||
|
isStoredInMemoryOnly: true
|
||||||
|
)
|
||||||
|
|
||||||
|
// Dictionary configuration
|
||||||
|
let dictionarySchema = Schema([VocabularyWord.self, WordReplacement.self])
|
||||||
|
let dictionaryConfig = ModelConfiguration(
|
||||||
|
"dictionary",
|
||||||
|
schema: dictionarySchema,
|
||||||
|
isStoredInMemoryOnly: true
|
||||||
|
)
|
||||||
|
|
||||||
|
return try ModelContainer(for: schema, configurations: transcriptConfig, dictionaryConfig)
|
||||||
} catch {
|
} catch {
|
||||||
logger.error("Failed to create in-memory ModelContainer: \(error.localizedDescription)")
|
logger.error("Failed to create in-memory ModelContainer: \(error.localizedDescription)")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static func createMinimalContainer(schema: Schema, logger: Logger) -> ModelContainer? {
|
|
||||||
do {
|
|
||||||
// Try default initializer without custom configuration
|
|
||||||
return try ModelContainer(for: schema)
|
|
||||||
} catch {
|
|
||||||
logger.error("Failed to create minimal ModelContainer: \(error.localizedDescription)")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func createDummyContainer(schema: Schema) -> ModelContainer {
|
|
||||||
// Create an absolute minimal container for initialization
|
|
||||||
// This uses in-memory storage and will never actually be used
|
|
||||||
// as the app will show an error and terminate in onAppear
|
|
||||||
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
|
|
||||||
|
|
||||||
// Note: In-memory containers should always succeed unless SwiftData itself is unavailable
|
|
||||||
// (which would indicate a serious system-level issue). We use preconditionFailure here
|
|
||||||
// rather than fatalError because:
|
|
||||||
// 1. This code is only reached after 3 prior initialization attempts have failed
|
|
||||||
// 2. An in-memory container failing indicates SwiftData is completely unavailable
|
|
||||||
// 3. Swift requires non-optional container property to be initialized
|
|
||||||
// 4. The app will immediately terminate in onAppear when containerInitializationFailed is checked
|
|
||||||
do {
|
|
||||||
return try ModelContainer(for: schema, configurations: [config])
|
|
||||||
} catch {
|
|
||||||
// This indicates a system-level SwiftData failure - app cannot function
|
|
||||||
preconditionFailure("Unable to create even a dummy ModelContainer. SwiftData is unavailable: \(error)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
WindowGroup {
|
WindowGroup {
|
||||||
if hasCompletedOnboarding {
|
if hasCompletedOnboarding {
|
||||||
@ -210,11 +217,14 @@ struct VoiceInkApp: App {
|
|||||||
alert.alertStyle = .critical
|
alert.alertStyle = .critical
|
||||||
alert.addButton(withTitle: "Quit")
|
alert.addButton(withTitle: "Quit")
|
||||||
alert.runModal()
|
alert.runModal()
|
||||||
|
|
||||||
NSApplication.shared.terminate(nil)
|
NSApplication.shared.terminate(nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Migrate dictionary data from UserDefaults to SwiftData (one-time operation)
|
||||||
|
DictionaryMigrationService.shared.migrateIfNeeded(context: container.mainContext)
|
||||||
|
|
||||||
updaterViewModel.silentlyCheckForUpdates()
|
updaterViewModel.silentlyCheckForUpdates()
|
||||||
if enableAnnouncements {
|
if enableAnnouncements {
|
||||||
AnnouncementsService.shared.start()
|
AnnouncementsService.shared.start()
|
||||||
|
|||||||
@ -316,7 +316,7 @@ class WhisperState: NSObject, ObservableObject {
|
|||||||
logger.notice("📝 Formatted transcript: \(text, privacy: .public)")
|
logger.notice("📝 Formatted transcript: \(text, privacy: .public)")
|
||||||
}
|
}
|
||||||
|
|
||||||
text = WordReplacementService.shared.applyReplacements(to: text)
|
text = WordReplacementService.shared.applyReplacements(to: text, using: modelContext)
|
||||||
logger.notice("📝 WordReplacement: \(text, privacy: .public)")
|
logger.notice("📝 WordReplacement: \(text, privacy: .public)")
|
||||||
|
|
||||||
let audioAsset = AVURLAsset(url: url)
|
let audioAsset = AVURLAsset(url: url)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user