1
2
3
4
5
6
7
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
65
66
67
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
|
package gui
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/dialog"
"codeberg.org/snonux/totalrecall/internal"
"codeberg.org/snonux/totalrecall/internal/anki"
)
// findCardDirectory finds the directory for a given Bulgarian word
func (a *Application) findCardDirectory(word string) string {
entries, err := os.ReadDir(a.config.OutputDir)
if err != nil {
return ""
}
// Look through all directories to find one with matching _word.txt
for _, entry := range entries {
if !entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
continue
}
dirPath := filepath.Join(a.config.OutputDir, entry.Name())
wordFile := filepath.Join(dirPath, "word.txt")
// Read the word file to check if it matches
if data, err := os.ReadFile(wordFile); err == nil {
storedWord := strings.TrimSpace(string(data))
if storedWord == word {
return dirPath
}
} else {
// Try old format with underscore for backward compatibility
wordFile = filepath.Join(dirPath, "_word.txt")
if data, err := os.ReadFile(wordFile); err == nil {
storedWord := strings.TrimSpace(string(data))
if storedWord == word {
return dirPath
}
}
}
}
return ""
}
// scanExistingWords scans the output directory for existing words
func (a *Application) scanExistingWords() {
a.existingWords = []string{}
// Read directory
entries, err := os.ReadDir(a.config.OutputDir)
if err != nil {
// Directory doesn't exist yet, that's OK
return
}
// Each subdirectory represents a word
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// Directory name is now a card ID
cardID := entry.Name()
wordDir := filepath.Join(a.config.OutputDir, cardID)
// Read the original Bulgarian word from word.txt
wordFile := filepath.Join(wordDir, "word.txt")
wordData, err := os.ReadFile(wordFile)
if err != nil {
// Try old format with underscore for backward compatibility
wordFile = filepath.Join(wordDir, "_word.txt")
wordData, err = os.ReadFile(wordFile)
if err != nil {
// No word file, skip this directory
continue
}
}
word := string(wordData)
if word == "" {
continue
}
// Look for at least one of: audio, image, or translation file
hasContent := false
// Check for audio file (both en-bg and bg-bg formats)
if a.hasAnyAudioFile(wordDir) {
hasContent = true
}
// Check for image files
if !hasContent {
patterns := []string{
"image.jpg",
"image.png",
}
for _, pattern := range patterns {
if _, err := os.Stat(filepath.Join(wordDir, pattern)); err == nil {
hasContent = true
break
}
}
}
// Check for translation file
if !hasContent {
translationFile := filepath.Join(wordDir, "translation.txt")
if _, err := os.Stat(translationFile); err == nil {
hasContent = true
}
}
// If directory has content, add the word to the list
if hasContent {
a.existingWords = append(a.existingWords, word)
}
}
// Sort the words
sort.Strings(a.existingWords)
// Update navigation buttons
a.updateNavigation()
// Load first word if available and nothing is loaded yet
if len(a.existingWords) > 0 && a.currentWord == "" {
a.loadWordByIndex(0)
}
}
// updateNavigation updates the navigation button states
func (a *Application) updateNavigation() {
// Get all available words (existing + completed from queue)
allWords := a.getAllAvailableWords()
if len(allWords) > 1 {
// Enable both buttons when there's more than one word (allows circular navigation)
a.prevWordBtn.Enable()
a.nextWordBtn.Enable()
// Find current word index
a.currentWordIndex = -1
for i, word := range allWords {
if word == a.currentWord {
a.currentWordIndex = i
break
}
}
} else if len(allWords) == 1 {
// With only one word, disable navigation
a.prevWordBtn.Disable()
a.nextWordBtn.Disable()
} else {
// No words at all
a.prevWordBtn.Disable()
a.nextWordBtn.Disable()
}
}
// getAllAvailableWords returns all words (from disk and completed queue jobs)
func (a *Application) getAllAvailableWords() []string {
// Start with existing words from disk
words := make([]string, len(a.existingWords))
copy(words, a.existingWords)
// Add completed jobs from queue
completedJobs := a.queue.GetCompletedJobs()
for _, job := range completedJobs {
// Check if this word is already in the list
found := false
for _, w := range words {
if w == job.Word {
found = true
break
}
}
if !found {
words = append(words, job.Word)
}
}
// Sort the combined list
sort.Strings(words)
return words
}
// onPrevWord loads the previous word
func (a *Application) onPrevWord() {
// Store current word before rescanning
currentWord := a.currentWord
// Rescan to pick up any new cards added externally
a.scanExistingWords()
allWords := a.getAllAvailableWords()
if len(allWords) == 0 {
return
}
// Find current word's new index after rescan
currentIndex := -1
for i, word := range allWords {
if word == currentWord {
currentIndex = i
break
}
}
// If current word not found, use the stored index
if currentIndex == -1 {
currentIndex = a.currentWordIndex
}
newIndex := currentIndex - 1
// Wrap around to the end if at beginning
if newIndex < 0 {
newIndex = len(allWords) - 1
}
a.loadWordByIndex(newIndex)
}
// onNextWord loads the next word
func (a *Application) onNextWord() {
// Store current word before rescanning
currentWord := a.currentWord
// Rescan to pick up any new cards added externally
a.scanExistingWords()
allWords := a.getAllAvailableWords()
if len(allWords) == 0 {
return
}
// Find current word's new index after rescan
currentIndex := -1
for i, word := range allWords {
if word == currentWord {
currentIndex = i
break
}
}
// If current word not found, use the stored index
if currentIndex == -1 {
currentIndex = a.currentWordIndex
}
newIndex := currentIndex + 1
// Wrap around to the beginning if at end
if newIndex >= len(allWords) {
newIndex = 0
}
a.loadWordByIndex(newIndex)
}
// loadWordByIndex loads a word by its index in the combined word list
func (a *Application) loadWordByIndex(index int) {
// Stop any existing file check ticker
if a.fileCheckTicker != nil {
a.fileCheckTicker.Stop()
a.fileCheckTicker = nil
}
allWords := a.getAllAvailableWords()
if index < 0 || index >= len(allWords) {
return
}
word := allWords[index]
a.currentWord = word
a.currentWordIndex = index
// Update input field
a.wordInput.SetText(word)
// Clear UI
a.clearUI()
// Check if this word is from a completed queue job
var fromQueue bool
completedJobs := a.queue.GetCompletedJobs()
for _, job := range completedJobs {
if job.Word == word && job.Status == StatusCompleted {
// Load from queue job
a.currentTranslation = job.Translation
a.currentAudioFile = job.AudioFile
a.currentAudioFileBack = job.AudioFileBack
a.currentImage = job.ImageFile
a.currentCardType = job.CardType
a.syncCardTypeSelection(internal.CardType(job.CardType))
fyne.Do(func() {
if job.Translation != "" {
a.translationEntry.SetText(job.Translation)
}
if job.AudioFile != "" {
a.audioPlayer.SetAudioFile(job.AudioFile)
}
if job.AudioFileBack != "" {
a.audioPlayer.SetBackAudioFile(job.AudioFileBack)
}
if job.ImageFile != "" {
a.imageDisplay.SetImages([]string{job.ImageFile})
}
// Load phonetic info from disk if it exists
a.loadPhoneticInfo(word)
// Load image prompt from disk if it exists
if wordDir := a.findCardDirectory(word); wordDir != "" {
promptFile := filepath.Join(wordDir, "image_prompt.txt")
if data, err := os.ReadFile(promptFile); err == nil {
prompt := strings.TrimSpace(string(data))
a.imagePromptEntry.SetText(prompt)
}
}
a.updateStatus(fmt.Sprintf("Loaded from queue: %s", word))
})
fromQueue = true
break
}
}
// If not from queue, load existing files from disk
if !fromQueue {
a.loadExistingFiles(word)
}
// Update navigation
a.updateNavigation()
// Enable action buttons if we have content
hasContent := a.currentAudioFile != "" || a.currentImage != "" || a.currentTranslation != ""
if hasContent {
a.setActionButtonsEnabled(true)
}
// Start ticker to check for missing files
a.startFileCheckTicker()
}
// loadExistingFiles loads existing files for a word
func (a *Application) loadExistingFiles(word string) {
// Find the card directory for this word
wordDir := a.findCardDirectory(word)
if wordDir == "" {
// No existing directory found
fmt.Printf("No card directory found for word: %s\n", word)
return
}
fmt.Printf("Loading files from directory: %s\n", wordDir)
// Load translation
translationFile := filepath.Join(wordDir, "translation.txt")
if data, err := os.ReadFile(translationFile); err == nil {
// Parse translation from "word = translation" format
content := string(data)
fmt.Printf("DEBUG (loadExistingFiles): Read translation.txt: %s\n", content)
parts := strings.Split(content, "=")
fmt.Printf("DEBUG (loadExistingFiles): Split into %d parts\n", len(parts))
if len(parts) >= 2 {
translation := strings.TrimSpace(parts[1])
fmt.Printf("DEBUG (loadExistingFiles): Extracted translation (part 1, after '='): %s\n", translation)
// CRITICAL: Set the state BEFORE SetText so it's available when needed
a.currentTranslation = translation
fmt.Printf("DEBUG (loadExistingFiles): Set a.currentTranslation state variable to: %s\n", a.currentTranslation)
fyne.Do(func() {
a.translationEntry.SetText(translation)
fmt.Printf("DEBUG (loadExistingFiles): Set translationEntry UI field to: %s\n", translation)
// CRITICAL: After SetText, verify the state is correct
fmt.Printf("DEBUG (loadExistingFiles): After SetText, a.currentTranslation is: %s\n", a.currentTranslation)
})
} else {
fmt.Printf("DEBUG (loadExistingFiles): Translation file did not have '=' separator\n")
}
} else {
fmt.Printf("DEBUG (loadExistingFiles): Could not read translation.txt: %v\n", err)
}
// Load image prompt file
promptFile := filepath.Join(wordDir, "image_prompt.txt")
if data, err := os.ReadFile(promptFile); err == nil {
prompt := strings.TrimSpace(string(data))
fmt.Printf("Loaded prompt from file: %s\n", promptFile)
fyne.Do(func() {
a.imagePromptEntry.SetText(prompt)
})
} else {
fmt.Printf("No prompt file found at: %s\n", promptFile)
}
// Load phonetic information
phoneticFile := filepath.Join(wordDir, "phonetic.txt")
if data, err := os.ReadFile(phoneticFile); err == nil {
phoneticInfo := string(data)
fmt.Printf("Loaded phonetic info from file: %s\n", phoneticFile)
fyne.Do(func() {
a.audioPlayer.SetPhonetic(phoneticInfo)
})
} else {
fmt.Printf("No phonetic file found at: %s (error: %v)\n", phoneticFile, err)
}
// Load card type and audio files
cardType := internal.LoadCardType(wordDir)
a.currentCardType = string(cardType)
fmt.Printf("DEBUG (loadExistingFiles): Loaded card type: %s (isBgBg: %v)\n", cardType, cardType.IsBgBg())
// Update UI card type selector
fmt.Printf("DEBUG (loadExistingFiles): Syncing UI card type selector to %s\n", cardType)
a.syncCardTypeSelection(cardType)
// Load audio file(s)
if cardType.IsBgBg() {
fmt.Printf("DEBUG (loadExistingFiles): Loading audio files for bg-bg card\n")
// For bg-bg cards, load both front and back audio
frontAudio, backAudio := a.resolveBgBgAudioFiles(wordDir)
if frontAudio != "" {
a.currentAudioFile = frontAudio
fmt.Printf("DEBUG (loadExistingFiles): Found front audio: %s\n", frontAudio)
if a.window == nil {
a.audioPlayer.SetAudioFile(frontAudio)
} else {
fyne.Do(func() {
a.audioPlayer.SetAudioFile(frontAudio)
})
}
} else {
fmt.Printf("DEBUG (loadExistingFiles): Front audio not found: %s\n", frontAudio)
}
if backAudio != "" {
a.currentAudioFileBack = backAudio
fmt.Printf("DEBUG (loadExistingFiles): Found back audio: %s\n", backAudio)
if a.window == nil {
a.audioPlayer.SetBackAudioFile(backAudio)
} else {
fyne.Do(func() {
a.audioPlayer.SetBackAudioFile(backAudio)
})
}
} else {
fmt.Printf("DEBUG (loadExistingFiles): Back audio not found: %s\n", backAudio)
}
} else {
fmt.Printf("DEBUG (loadExistingFiles): Loading audio files for en-bg card\n")
// For en-bg cards, load standard audio file
audioFile := a.resolveSingleAudioFile(wordDir)
if audioFile != "" {
a.currentAudioFile = audioFile
fmt.Printf("DEBUG (loadExistingFiles): Found audio: %s\n", audioFile)
if a.window == nil {
a.audioPlayer.SetAudioFile(audioFile)
} else {
fyne.Do(func() {
a.audioPlayer.SetAudioFile(audioFile)
})
}
} else {
fmt.Printf("DEBUG (loadExistingFiles): Audio not found: %s\n", audioFile)
}
// Hide back audio button for en-bg cards
a.currentAudioFileBack = ""
fmt.Printf("DEBUG (loadExistingFiles): Clearing back audio for en-bg card\n")
if a.window == nil {
a.audioPlayer.SetBackAudioFile("")
} else {
fyne.Do(func() {
a.audioPlayer.SetBackAudioFile("")
})
}
}
// Load image file
a.currentImage = ""
// Try to find images with different patterns
patterns := []string{
"image.jpg",
"image.png",
}
for _, pattern := range patterns {
imagePath := filepath.Join(wordDir, pattern)
if _, err := os.Stat(imagePath); err == nil {
a.currentImage = imagePath
break // Just load the first image found
}
}
if a.currentImage != "" {
fyne.Do(func() {
a.imageDisplay.SetImages([]string{a.currentImage})
})
// Try to load the prompt from attribution file for AI image providers.
if a.config.ImageProvider == imageProviderOpenAI || a.config.ImageProvider == imageProviderNanoBanana {
// Look for attribution file
baseImagePath := a.currentImage
attrPath := strings.TrimSuffix(baseImagePath, filepath.Ext(baseImagePath)) + "_attribution.txt"
if data, err := os.ReadFile(attrPath); err == nil {
// Parse prompt from attribution file
content := string(data)
lines := strings.Split(content, "\n")
for i, line := range lines {
if strings.HasPrefix(line, "Prompt used:") && i+1 < len(lines) {
// The prompt is on the next line
prompt := strings.TrimSpace(lines[i+1])
if a.imagePromptEntry != nil {
fyne.Do(func() {
a.imagePromptEntry.SetText(prompt)
})
}
break
}
}
}
}
}
fyne.Do(func() {
a.updateStatus(fmt.Sprintf("Loaded: %s", word))
})
}
// startFileCheckTicker starts a ticker to check for missing files
func (a *Application) startFileCheckTicker() {
// Stop any existing ticker first
if a.fileCheckTicker != nil {
a.fileCheckTicker.Stop()
}
// Create ticker that checks every 2 seconds
ticker := time.NewTicker(2 * time.Second)
a.fileCheckTicker = ticker
go func() {
for {
select {
case <-ticker.C:
// Only check files for the current word
a.mu.Lock()
currentWord := a.currentWord
a.mu.Unlock()
if currentWord != "" {
a.checkForMissingFiles(currentWord)
}
case <-a.ctx.Done():
// Application is shutting down
return
}
}
}()
}
// checkForMissingFiles checks for missing files and attempts to load them
func (a *Application) checkForMissingFiles(word string) {
// Find the card directory for this word
wordDir := a.findCardDirectory(word)
if wordDir == "" {
return
}
// Check for missing audio file
if a.currentAudioFile == "" {
if a.currentCardType == "bg-bg" {
frontAudio, _ := a.resolveBgBgAudioFiles(wordDir)
if frontAudio != "" {
a.currentAudioFile = frontAudio
fyne.Do(func() {
a.audioPlayer.SetAudioFile(frontAudio)
a.updateStatus(fmt.Sprintf("Found audio file for %s", word))
})
}
} else {
audioFile := a.resolveSingleAudioFile(wordDir)
if audioFile != "" {
a.currentAudioFile = audioFile
fyne.Do(func() {
a.audioPlayer.SetAudioFile(audioFile)
a.updateStatus(fmt.Sprintf("Found audio file for %s", word))
})
}
}
}
// Check for missing back audio file (bg-bg cards)
if a.currentAudioFileBack == "" {
_, backAudio := a.resolveBgBgAudioFiles(wordDir)
if backAudio != "" {
a.currentAudioFileBack = backAudio
fyne.Do(func() {
a.audioPlayer.SetBackAudioFile(backAudio)
a.updateStatus(fmt.Sprintf("Found back audio file for %s", word))
})
}
}
// Check for missing image file
if a.currentImage == "" {
patterns := []string{"image.jpg", "image.png"}
for _, pattern := range patterns {
imagePath := filepath.Join(wordDir, pattern)
if _, err := os.Stat(imagePath); err == nil {
a.currentImage = imagePath
fyne.Do(func() {
a.imageDisplay.SetImages([]string{imagePath})
a.updateStatus(fmt.Sprintf("Found image file for %s", word))
})
break
}
}
}
// Check for missing translation
if a.currentTranslation == "" {
translationFile := filepath.Join(wordDir, "translation.txt")
if data, err := os.ReadFile(translationFile); err == nil {
content := string(data)
parts := strings.Split(content, "=")
if len(parts) >= 2 {
a.currentTranslation = strings.TrimSpace(parts[1])
fyne.Do(func() {
a.translationEntry.SetText(a.currentTranslation)
a.updateStatus(fmt.Sprintf("Found translation for %s", word))
})
}
}
}
// Check for missing prompt
currentPrompt := a.imagePromptEntry.Text
if currentPrompt == "" {
promptFile := filepath.Join(wordDir, "image_prompt.txt")
if data, err := os.ReadFile(promptFile); err == nil {
prompt := strings.TrimSpace(string(data))
fyne.Do(func() {
a.imagePromptEntry.SetText(prompt)
a.updateStatus(fmt.Sprintf("Found prompt for %s", word))
})
}
}
// Check for missing phonetic info
if a.currentPhonetic == "" {
phoneticFile := filepath.Join(wordDir, "phonetic.txt")
if data, err := os.ReadFile(phoneticFile); err == nil {
phoneticInfo := string(data)
a.currentPhonetic = phoneticInfo
fyne.Do(func() {
a.audioPlayer.SetPhonetic(phoneticInfo)
a.updateStatus(fmt.Sprintf("Found phonetic info for %s", word))
})
}
}
// Update action buttons if we now have content
hasContent := a.currentAudioFile != "" || a.currentImage != "" || a.currentTranslation != ""
if hasContent {
fyne.Do(func() {
a.setActionButtonsEnabled(true)
})
}
}
// onDelete moves the current word's files to trash bin
func (a *Application) onDelete() {
if a.currentWord == "" {
return
}
// Check if this word has active operations
if a.hasActiveOperations(a.currentWord) {
dialog.ShowError(fmt.Errorf("cannot delete %q while content is being generated; please wait for generation to complete", a.currentWord), a.window)
return
}
// Also check if word is in the processing queue
if a.queue.IsWordProcessing(a.currentWord) {
dialog.ShowError(fmt.Errorf("cannot delete %q while it is in the processing queue; please wait for processing to complete", a.currentWord), a.window)
return
}
// Create custom confirmation dialog with keyboard support
message := fmt.Sprintf("Move all files for '%s' to trash?\n\nPress y to confirm or n to cancel", a.currentWord)
confirmDialog := dialog.NewConfirm("Move to Trash", message, func(confirm bool) {
a.deleteConfirming = false
if confirm {
a.deleteCurrentWord()
}
}, a.window)
// Set up keyboard handler for the dialog
a.deleteConfirming = true
// Create a custom key handler for the dialog window
oldKeyHandler := a.window.Canvas().OnTypedKey()
oldRuneHandler := a.window.Canvas().OnTypedRune()
// Handle both Latin and Cyrillic keys
a.window.Canvas().SetOnTypedRune(func(r rune) {
if a.deleteConfirming {
switch r {
case 'y', 'Y', 'ъ', 'Ъ':
confirmDialog.Hide()
a.deleteConfirming = false
a.deleteCurrentWord()
// Restore original handlers
a.window.Canvas().SetOnTypedKey(oldKeyHandler)
a.window.Canvas().SetOnTypedRune(oldRuneHandler)
case 'n', 'N', 'н', 'Н':
confirmDialog.Hide()
a.deleteConfirming = false
// Restore original handlers
a.window.Canvas().SetOnTypedKey(oldKeyHandler)
a.window.Canvas().SetOnTypedRune(oldRuneHandler)
}
} else if oldRuneHandler != nil {
oldRuneHandler(r)
}
})
a.window.Canvas().SetOnTypedKey(func(ev *fyne.KeyEvent) {
if a.deleteConfirming {
switch ev.Name {
case fyne.KeyY:
confirmDialog.Hide()
a.deleteConfirming = false
a.deleteCurrentWord()
// Restore original handlers
a.window.Canvas().SetOnTypedKey(oldKeyHandler)
a.window.Canvas().SetOnTypedRune(oldRuneHandler)
case fyne.KeyN, fyne.KeyEscape:
confirmDialog.Hide()
a.deleteConfirming = false
// Restore original handlers
a.window.Canvas().SetOnTypedKey(oldKeyHandler)
a.window.Canvas().SetOnTypedRune(oldRuneHandler)
}
} else if oldKeyHandler != nil {
oldKeyHandler(ev)
}
})
confirmDialog.Show()
}
// deleteCurrentWord moves the word's subdirectory to trash
func (a *Application) deleteCurrentWord() {
// Cancel any ongoing operations for this card
a.cancelCardOperations(a.currentWord)
// Find the card directory for this word
wordDir := a.findCardDirectory(a.currentWord)
if wordDir == "" {
fyne.Do(func() {
a.updateStatus("No files found for this word")
})
return
}
// Create trash directory if it doesn't exist
trashDir := filepath.Join(a.config.OutputDir, ".trashbin")
if err := os.MkdirAll(trashDir, 0755); err != nil {
fyne.Do(func() {
a.updateStatus(fmt.Sprintf("Failed to create trash directory: %v", err))
})
return
}
// Create destination path in trash
// Use the directory name from the card directory
dirName := filepath.Base(wordDir)
timestamp := time.Now().Format("20060102_150405")
trashWordDir := filepath.Join(trashDir, fmt.Sprintf("%s_%s", dirName, timestamp))
// Move entire directory to trash
if err := os.Rename(wordDir, trashWordDir); err != nil {
fyne.Do(func() {
a.updateStatus(fmt.Sprintf("Failed to move files to trash: %v", err))
})
return
}
// Remove from existingWords
newWords := []string{}
for _, w := range a.existingWords {
if w != a.currentWord {
newWords = append(newWords, w)
}
}
a.existingWords = newWords
// Also remove from saved cards if present
a.mu.Lock()
newSavedCards := make([]anki.Card, 0, len(a.savedCards))
for _, card := range a.savedCards {
if card.Bulgarian != a.currentWord {
newSavedCards = append(newSavedCards, card)
}
}
a.savedCards = newSavedCards
a.mu.Unlock()
// Also remove from completed queue jobs
a.queue.RemoveCompletedJobByWord(a.currentWord)
// Clear UI
a.clearUI()
// Update status
fyne.Do(func() {
a.updateStatus(fmt.Sprintf("Moved '%s' to trash", a.currentWord))
// Update queue status to reflect the reduced card count
a.updateQueueStatus()
})
// Clear current word
deletedWord := a.currentWord
a.currentWord = ""
a.wordInput.SetText("")
// Try to load previous or next word
if a.currentWordIndex > 0 && a.currentWordIndex <= len(a.existingWords) {
a.loadWordByIndex(a.currentWordIndex - 1)
} else if len(a.existingWords) > 0 {
a.loadWordByIndex(0)
} else {
// No more words
a.updateNavigation()
a.setActionButtonsEnabled(false)
// But keep delete button enabled
a.deleteButton.Enable()
}
// Start a cleanup goroutine to remove directory after any pending operations complete
go func() {
// Wait a bit for any ongoing operations to notice cancellation
time.Sleep(500 * time.Millisecond)
// Check if the directory was somehow recreated (by a racing operation)
recreatedDir := a.findCardDirectory(deletedWord)
if recreatedDir != "" {
// Directory was recreated, try to delete it again
timestamp := time.Now().Format("20060102_150405")
trashWordDir := filepath.Join(trashDir, fmt.Sprintf("%s_%s_cleanup", filepath.Base(recreatedDir), timestamp))
// Move to trash again
if err := os.Rename(recreatedDir, trashWordDir); err == nil {
fmt.Printf("Cleanup: moved recreated directory for '%s' to trash\n", deletedWord)
}
}
}()
}
|