-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
6328 lines (5435 loc) · 212 KB
/
app.go
File metadata and controls
6328 lines (5435 loc) · 212 KB
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/zip"
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
goruntime "runtime"
"strings"
"sync"
"time"
"latex-translator/internal/compiler"
"latex-translator/internal/config"
"latex-translator/internal/downloader"
"latex-translator/internal/errors"
"latex-translator/internal/github"
"latex-translator/internal/license"
"latex-translator/internal/logger"
"latex-translator/internal/parser"
"latex-translator/internal/pdf"
"latex-translator/internal/results"
"latex-translator/internal/translator"
"latex-translator/internal/types"
"latex-translator/internal/validator"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// Event names for frontend communication
const (
EventOriginalPDFReady = "original-pdf-ready"
EventTranslatedPDFReady = "translated-pdf-ready"
)
// Default GitHub repository settings
const (
DefaultGitHubOwner = "rapidaicoder"
DefaultGitHubRepo = "chinesepaper"
)
// StatusCallback is a function type for status update callbacks.
// It is called whenever the processing status changes.
type StatusCallback func(status *types.Status)
// App is the main Wails application controller.
// It integrates all modules (ConfigManager, SourceDownloader, TranslationEngine,
// LaTeXCompiler, SyntaxValidator) and manages the application lifecycle.
type App struct {
ctx context.Context
config *config.ConfigManager
downloader *downloader.SourceDownloader
translator *translator.TranslationEngine
compiler *compiler.LaTeXCompiler
validator *validator.SyntaxValidator
results *results.ResultManager
errorMgr *errors.ErrorManager
workDir string
// License client for commercial mode
licenseClient *license.Client
// Status tracking
status *types.Status
statusMu sync.RWMutex
statusCallback StatusCallback
// Cancellation support
cancelFunc context.CancelFunc
// Last process result for download
lastResult *types.ProcessResult
// PDF translation support
pdfTranslator *pdf.PDFTranslator
// isWailsRuntime indicates if the app is running in a Wails environment
// This is used to safely skip EventsEmit calls during tests
isWailsRuntime bool
}
// safeEmit safely emits an event to the frontend.
// It only emits events when running in a Wails environment.
func (a *App) safeEmit(eventName string, data ...interface{}) {
if !a.isWailsRuntime {
logger.Debug("event emit skipped (not in Wails runtime)",
logger.String("event", eventName))
return
}
runtime.EventsEmit(a.ctx, eventName, data...)
}
// SetWailsRuntime sets the Wails runtime flag.
// This should be called from main.go when the app is started in Wails mode.
func (a *App) SetWailsRuntime(isWails bool) {
a.isWailsRuntime = isWails
}
// NewApp creates a new App application struct with all dependencies initialized.
// It sets up the work directory and creates instances of all required modules.
func NewApp() *App {
return &App{
status: &types.Status{
Phase: types.PhaseIdle,
Progress: 0,
Message: "",
},
}
}
// NewAppWithConfig creates a new App with a custom config path.
// This is useful for testing or when a specific configuration location is needed.
func NewAppWithConfig(configPath string) (*App, error) {
app := &App{
status: &types.Status{
Phase: types.PhaseIdle,
Progress: 0,
Message: "",
},
}
// Initialize config manager
configMgr, err := config.NewConfigManager(configPath)
if err != nil {
return nil, err
}
app.config = configMgr
return app, nil
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods. It initializes all modules
// and prepares the application for use.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
logger.Info("application starting up")
// Initialize config manager if not already set
if a.config == nil {
configMgr, err := config.NewConfigManager("")
if err != nil {
logger.Error("failed to create config manager", err)
return
}
a.config = configMgr
}
// Load configuration
if err := a.config.Load(); err != nil {
// Continue with defaults if config load fails
logger.Warn("failed to load config, using defaults", logger.Err(err))
}
// Initialize work directory (after config is loaded so we can use configured work dir)
if err := a.initWorkDir(); err != nil {
// Log error but continue - work dir can be set later
logger.Error("failed to initialize work directory", err)
}
// Initialize downloader with work directory
a.downloader = downloader.NewSourceDownloader(a.workDir)
logger.Debug("downloader initialized", logger.String("workDir", a.workDir))
// Initialize license client for commercial mode (needed before checking work mode)
a.licenseClient = license.NewClient()
logger.Debug("license client initialized")
// Check work mode status and apply license config BEFORE initializing translator
// This ensures the translator uses the correct API key from the license
// Validates: Requirements 1.1, 1.2, 1.3, 1.4, 1.5, 3.4
if a.config != nil {
workModeStatus := a.config.GetWorkModeStatus()
logger.Info("work mode status at startup",
logger.Bool("hasWorkMode", workModeStatus.HasWorkMode),
logger.String("workMode", string(workModeStatus.WorkMode)),
logger.Bool("needsSelection", workModeStatus.NeedsSelection),
logger.Bool("hasValidLicense", workModeStatus.HasValidLicense),
logger.Bool("licenseExpired", workModeStatus.LicenseExpired),
logger.Bool("licenseExpiringSoon", workModeStatus.LicenseExpiringSoon))
// If commercial mode with valid license, update config with license LLM settings
// This must happen BEFORE translator initialization so GetAPIKey() returns the correct value
if workModeStatus.IsCommercial && workModeStatus.HasValidLicense {
licenseInfo := a.config.GetLicenseInfo()
if licenseInfo != nil && licenseInfo.ActivationData != nil {
activationData := licenseInfo.ActivationData
// Get effective base URL - derives from LLMType if LLMBaseURL is empty
effectiveBaseURL := a.licenseClient.GetEffectiveBaseURL(activationData)
logger.Info("applying license LLM config before translator init",
logger.String("llmType", activationData.LLMType),
logger.String("model", activationData.LLMModel),
logger.Int("apiKeyLength", len(activationData.LLMAPIKey)),
logger.String("originalBaseURL", activationData.LLMBaseURL),
logger.String("effectiveBaseURL", effectiveBaseURL))
// Update config with license values so GetAPIKey/GetModel/GetBaseURL return correct values
if err := a.config.UpdateConfig(
activationData.LLMAPIKey,
effectiveBaseURL, // Use effective base URL instead of raw LLMBaseURL
activationData.LLMModel,
a.config.GetContextWindow(),
a.config.GetDefaultCompiler(),
a.config.GetWorkDirectory(),
a.config.GetConcurrency(),
a.config.GetLibraryPageSize(),
true, // sharePromptEnabled
); err != nil {
logger.Warn("failed to apply license LLM config", logger.Err(err))
}
}
}
// Emit startup mode event to frontend
// The frontend will handle showing mode selection or proceeding to main interface
a.safeEmit("startup-mode-status", map[string]interface{}{
"has_work_mode": workModeStatus.HasWorkMode,
"work_mode": string(workModeStatus.WorkMode),
"needs_selection": workModeStatus.NeedsSelection,
"is_commercial": workModeStatus.IsCommercial,
"is_open_source": workModeStatus.IsOpenSource,
"has_valid_license": workModeStatus.HasValidLicense,
"license_expired": workModeStatus.LicenseExpired,
"license_expiring_soon": workModeStatus.LicenseExpiringSoon,
"days_until_expiry": workModeStatus.DaysUntilExpiry,
})
}
// Now initialize translator with API key from config (which now includes license values if applicable)
apiKey := a.config.GetAPIKey()
model := a.config.GetModel()
baseURL := a.config.GetBaseURL()
concurrency := a.config.GetConcurrency()
logger.Info("initializing translator",
logger.Int("apiKeyLength", len(apiKey)),
logger.String("model", model),
logger.String("baseURL", baseURL),
logger.Int("concurrency", concurrency))
a.translator = translator.NewTranslationEngineWithConfig(apiKey, model, baseURL, 0, concurrency)
// Initialize compiler with default compiler from config
defaultCompiler := a.config.GetDefaultCompiler()
// Use 10 minute timeout for large projects
a.compiler = compiler.NewLaTeXCompiler(defaultCompiler, a.workDir, 10*time.Minute)
logger.Debug("compiler initialized", logger.String("compiler", defaultCompiler))
// Initialize validator with API key and base URL from config
a.validator = validator.NewSyntaxValidatorWithConfig(apiKey, model, baseURL, 0)
logger.Debug("validator initialized", logger.String("baseURL", baseURL))
// Initialize PDF translator with config
pdfConfig := pdf.PDFTranslatorConfig{
Config: &types.Config{
OpenAIAPIKey: apiKey,
OpenAIBaseURL: baseURL,
OpenAIModel: model,
ContextWindow: a.config.GetContextWindow(),
Concurrency: concurrency,
},
WorkDir: a.workDir,
}
a.pdfTranslator = pdf.NewPDFTranslator(pdfConfig)
// Set page complete callback for progressive PDF display
a.pdfTranslator.SetPageCompleteCallback(func(currentPage, totalPages int, outputPath string) {
// Emit event to frontend for progressive display
a.safeEmit("pdf-page-translated", map[string]interface{}{
"currentPage": currentPage,
"totalPages": totalPages,
"outputPath": outputPath,
})
logger.Debug("PDF page translated",
logger.Int("currentPage", currentPage),
logger.Int("totalPages", totalPages))
})
logger.Debug("PDF translator initialized")
// Initialize result manager
resultMgr, err := results.NewResultManager("")
if err != nil {
logger.Warn("failed to initialize result manager", logger.Err(err))
} else {
a.results = resultMgr
logger.Debug("result manager initialized", logger.String("baseDir", resultMgr.GetBaseDir()))
}
// Initialize error manager
errorMgr, err := errors.NewErrorManager("")
if err != nil {
logger.Warn("failed to initialize error manager", logger.Err(err))
} else {
a.errorMgr = errorMgr
logger.Debug("error manager initialized")
}
// Ensure GitHub token is available
if err := a.EnsureGitHubToken(); err != nil {
logger.Warn("failed to ensure GitHub token", logger.Err(err))
}
logger.Info("application startup complete")
}
// shutdown is called when the app is closing. It performs cleanup
// of temporary files and resources.
func (a *App) shutdown(ctx context.Context) {
logger.Info("application shutting down")
// Close PDF translator to save cache
if a.pdfTranslator != nil {
if err := a.pdfTranslator.Close(); err != nil {
logger.Warn("failed to close PDF translator", logger.Err(err))
}
}
// Clean up work directory if it exists and is a temp directory
if a.workDir != "" && a.isTemporaryWorkDir() {
// Attempt to clean up, but don't fail if it doesn't work
if err := os.RemoveAll(a.workDir); err != nil {
logger.Warn("failed to clean up work directory", logger.String("workDir", a.workDir), logger.Err(err))
} else {
logger.Debug("cleaned up temporary work directory", logger.String("workDir", a.workDir))
}
}
logger.Info("application shutdown complete")
}
// initWorkDir initializes the work directory for temporary files.
// It first checks if a work directory is configured, otherwise creates
// a temporary directory.
func (a *App) initWorkDir() error {
// Check if config has a work directory set
if a.config != nil {
configWorkDir := a.config.GetWorkDirectory()
if configWorkDir != "" {
a.workDir = configWorkDir
return os.MkdirAll(a.workDir, 0755)
}
}
// Create a temporary directory
tempDir, err := os.MkdirTemp("", "latex-translator-*")
if err != nil {
return err
}
a.workDir = tempDir
return nil
}
// isTemporaryWorkDir checks if the current work directory is a temporary directory.
func (a *App) isTemporaryWorkDir() bool {
if a.workDir == "" {
return false
}
// Check if it's in the system temp directory
tempDir := os.TempDir()
return filepath.HasPrefix(a.workDir, tempDir)
}
// GetConfig returns the config manager.
func (a *App) GetConfig() *config.ConfigManager {
return a.config
}
// GetDownloader returns the source downloader.
func (a *App) GetDownloader() *downloader.SourceDownloader {
return a.downloader
}
// GetTranslator returns the translation engine.
func (a *App) GetTranslator() *translator.TranslationEngine {
return a.translator
}
// GetCompiler returns the LaTeX compiler.
func (a *App) GetCompiler() *compiler.LaTeXCompiler {
return a.compiler
}
// GetValidator returns the syntax validator.
func (a *App) GetValidator() *validator.SyntaxValidator {
return a.validator
}
// GetWorkDir returns the current work directory.
func (a *App) GetWorkDir() string {
return a.workDir
}
// SetWorkDir sets the work directory and updates all modules.
func (a *App) SetWorkDir(workDir string) error {
if err := os.MkdirAll(workDir, 0755); err != nil {
return err
}
a.workDir = workDir
// Update downloader work directory
if a.downloader != nil {
a.downloader.SetWorkDir(workDir)
}
return nil
}
// ReloadConfig reloads the configuration and updates all modules with new settings.
func (a *App) ReloadConfig() error {
if a.config == nil {
return nil
}
// Reload configuration
if err := a.config.Load(); err != nil {
return err
}
// Update translator with new API key and model
apiKey := a.config.GetAPIKey()
model := a.config.GetModel()
baseURL := a.config.GetBaseURL()
concurrency := a.config.GetConcurrency()
logger.Info("ReloadConfig: updating translator",
logger.Int("apiKeyLength", len(apiKey)),
logger.String("model", model),
logger.String("baseURL", baseURL),
logger.Int("concurrency", concurrency))
if a.translator != nil {
a.translator = translator.NewTranslationEngineWithConfig(apiKey, model, baseURL, 0, concurrency)
}
// Update validator with new API key and base URL
if a.validator != nil {
a.validator = validator.NewSyntaxValidatorWithConfig(apiKey, model, baseURL, 0)
}
// Update compiler with new default compiler
defaultCompiler := a.config.GetDefaultCompiler()
if a.compiler != nil {
a.compiler.SetCompiler(defaultCompiler)
}
// Update work directory if configured
configWorkDir := a.config.GetWorkDirectory()
if configWorkDir != "" && configWorkDir != a.workDir {
if err := a.SetWorkDir(configWorkDir); err != nil {
return err
}
}
// Update PDF translator with new config
if a.pdfTranslator != nil {
a.pdfTranslator.UpdateConfig(&types.Config{
OpenAIAPIKey: apiKey,
OpenAIBaseURL: baseURL,
OpenAIModel: model,
ContextWindow: a.config.GetContextWindow(),
Concurrency: concurrency,
})
// Also update work directory for PDF translator
if configWorkDir != "" {
a.pdfTranslator.SetWorkDir(configWorkDir)
}
}
return nil
}
// applyLicenseLLMConfig applies LLM configuration from the commercial license.
// This is called at startup when commercial mode has a valid license.
// It updates the translator, validator, and PDF translator with the license LLM settings.
// Validates: Requirements 3.4
func (a *App) applyLicenseLLMConfig() {
if a.config == nil {
return
}
licenseInfo := a.config.GetLicenseInfo()
if licenseInfo == nil || licenseInfo.ActivationData == nil {
return
}
activationData := licenseInfo.ActivationData
// Get effective base URL - derives from LLMType if LLMBaseURL is empty
effectiveBaseURL := a.licenseClient.GetEffectiveBaseURL(activationData)
logger.Info("applying LLM config from license",
logger.String("llmType", activationData.LLMType),
logger.String("model", activationData.LLMModel),
logger.String("originalBaseURL", activationData.LLMBaseURL),
logger.String("effectiveBaseURL", effectiveBaseURL))
// Get current config values for fields we don't want to change
contextWindow := config.DefaultContextWindow
compiler := config.DefaultCompiler
workDir := ""
concurrency := config.DefaultConcurrency
libraryPageSize := config.DefaultLibraryPageSize
sharePromptEnabled := true
if a.config != nil {
contextWindow = a.config.GetContextWindow()
compiler = a.config.GetDefaultCompiler()
workDir = a.config.GetWorkDirectory()
concurrency = a.config.GetConcurrency()
libraryPageSize = a.config.GetLibraryPageSize()
// Get current share prompt setting from config
cfg := a.config.GetConfig()
if cfg != nil {
sharePromptEnabled = cfg.SharePromptEnabled
}
}
// Update config manager with license LLM settings using UpdateConfig
if a.config != nil {
if err := a.config.UpdateConfig(
activationData.LLMAPIKey,
effectiveBaseURL, // Use effective base URL instead of raw LLMBaseURL
activationData.LLMModel,
contextWindow,
compiler,
workDir,
concurrency,
libraryPageSize,
sharePromptEnabled,
); err != nil {
logger.Warn("failed to save license LLM config", logger.Err(err))
}
}
// Update translator with new config
if a.translator != nil {
a.translator = translator.NewTranslationEngineWithConfig(
activationData.LLMAPIKey,
activationData.LLMModel,
effectiveBaseURL, // Use effective base URL
0,
concurrency,
)
}
// Update validator with new config
if a.validator != nil {
a.validator = validator.NewSyntaxValidatorWithConfig(
activationData.LLMAPIKey,
activationData.LLMModel,
effectiveBaseURL, // Use effective base URL
0,
)
}
// Update PDF translator with new config
if a.pdfTranslator != nil {
a.pdfTranslator.UpdateConfig(&types.Config{
OpenAIAPIKey: activationData.LLMAPIKey,
OpenAIBaseURL: effectiveBaseURL, // Use effective base URL
OpenAIModel: activationData.LLMModel,
ContextWindow: contextWindow,
Concurrency: concurrency,
})
}
logger.Info("license LLM config applied successfully")
}
// SetStatusCallback sets the callback function for status updates.
// The callback will be called whenever the processing status changes.
func (a *App) SetStatusCallback(callback StatusCallback) {
a.statusMu.Lock()
defer a.statusMu.Unlock()
a.statusCallback = callback
}
// GetStatus returns the current processing status.
// This method is thread-safe.
func (a *App) GetStatus() *types.Status {
a.statusMu.RLock()
defer a.statusMu.RUnlock()
// Return a copy to prevent external modification
return &types.Status{
Phase: a.status.Phase,
Progress: a.status.Progress,
Message: a.status.Message,
Error: a.status.Error,
}
}
// IsProcessing returns true if a translation task is currently in progress.
// This method is thread-safe.
func (a *App) IsProcessing() bool {
a.statusMu.RLock()
defer a.statusMu.RUnlock()
// Processing is active if phase is not idle, complete, or error
switch a.status.Phase {
case types.PhaseIdle, types.PhaseComplete, types.PhaseError:
return false
default:
return true
}
}
// IsPDFTranslating returns true if a PDF translation task is currently in progress.
// This method is thread-safe.
func (a *App) IsPDFTranslating() bool {
if a.pdfTranslator == nil {
return false
}
status := a.pdfTranslator.GetStatus()
if status == nil {
return false
}
// PDF translation is active if phase is not idle, complete, or error
switch status.Phase {
case pdf.PDFPhaseIdle, pdf.PDFPhaseComplete, pdf.PDFPhaseError:
return false
default:
return true
}
}
// IsAnyTranslationInProgress returns true if any translation task (LaTeX or PDF) is in progress.
// This is used for close confirmation dialog.
func (a *App) IsAnyTranslationInProgress() bool {
return a.IsProcessing() || a.IsPDFTranslating()
}
// updateStatus updates the current status and notifies the callback.
func (a *App) updateStatus(phase types.ProcessPhase, progress int, message string) {
a.statusMu.Lock()
a.status.Phase = phase
a.status.Progress = progress
a.status.Message = message
a.status.Error = ""
// Get callback while holding lock
callback := a.statusCallback
// Make a copy for the callback
statusCopy := &types.Status{
Phase: a.status.Phase,
Progress: a.status.Progress,
Message: a.status.Message,
Error: a.status.Error,
}
a.statusMu.Unlock()
// Call callback outside of lock to prevent deadlocks
if callback != nil {
callback(statusCopy)
}
}
// updateStatusError updates the status with an error.
func (a *App) updateStatusError(errorMsg string) {
a.statusMu.Lock()
a.status.Phase = types.PhaseError
a.status.Error = errorMsg
// Get callback while holding lock
callback := a.statusCallback
// Make a copy for the callback
statusCopy := &types.Status{
Phase: a.status.Phase,
Progress: a.status.Progress,
Message: a.status.Message,
Error: a.status.Error,
}
a.statusMu.Unlock()
// Call callback outside of lock to prevent deadlocks
if callback != nil {
callback(statusCopy)
}
}
// CheckExistingTranslation checks if a translation already exists for the given input
// This is called by the frontend before starting a translation to avoid duplicates
func (a *App) CheckExistingTranslation(input string) (*results.ExistingTranslationInfo, error) {
logger.Info("checking existing translation", logger.String("input", input))
if a.results == nil {
return &results.ExistingTranslationInfo{
Exists: false,
Message: "结果管理器未初始化",
}, nil
}
// Determine source type
sourceType, err := parser.ParseInput(input)
if err != nil {
return nil, err
}
var resultSourceType results.SourceType
switch sourceType {
case types.SourceTypeArxivID, types.SourceTypeURL:
resultSourceType = results.SourceTypeArxiv
case types.SourceTypeLocalZip:
resultSourceType = results.SourceTypeZip
case types.SourceTypeLocalPDF:
resultSourceType = results.SourceTypePDF
default:
return &results.ExistingTranslationInfo{
Exists: false,
Message: "未知的输入类型",
}, nil
}
return a.results.CheckExistingTranslation(input, resultSourceType)
}
// ProcessSourceWithForce processes the input source, optionally forcing re-translation
// The force parameter behavior depends on the existing translation status:
// - If translation is complete: force=true means re-translate, force=false means return existing
// - If translation can continue: force=true means continue, force=false means restart
// - If translation failed: force=true means retry, force=false means give up
func (a *App) ProcessSourceWithForce(input string, force bool) (*types.ProcessResult, error) {
logger.Info("processing source with force option",
logger.String("input", input),
logger.Bool("force", force))
// Check if already processing to prevent duplicate calls
if a.IsProcessing() {
logger.Warn("ProcessSourceWithForce called while already processing, ignoring duplicate call")
return nil, types.NewAppError(types.ErrInternal, "已有翻译任务正在进行中", nil)
}
// Check for existing translation
existingInfo, err := a.CheckExistingTranslation(input)
if err != nil {
logger.Warn("failed to check existing translation", logger.Err(err))
// Continue anyway - don't block translation due to check failure
} else if existingInfo != nil && existingInfo.Exists {
if existingInfo.IsComplete {
// Translation is complete
if force {
// User wants to re-translate - delete existing and start fresh
if existingInfo.PaperInfo != nil && existingInfo.PaperInfo.ArxivID != "" {
logger.Info("deleting existing translation for force re-translation",
logger.String("arxivID", existingInfo.PaperInfo.ArxivID))
if err := a.results.DeletePaper(existingInfo.PaperInfo.ArxivID); err != nil {
logger.Warn("failed to delete existing paper", logger.Err(err))
}
}
// Fall through to ProcessSource
} else {
// Return the existing result
logger.Info("returning existing translation result",
logger.String("arxivID", existingInfo.PaperInfo.ArxivID))
return &types.ProcessResult{
OriginalPDFPath: existingInfo.PaperInfo.OriginalPDF,
TranslatedPDFPath: existingInfo.PaperInfo.TranslatedPDF,
SourceID: existingInfo.PaperInfo.ArxivID,
}, nil
}
} else if existingInfo.CanContinue {
// Translation can be continued (interrupted or error state)
if force {
// User wants to continue from where it left off
logger.Info("continuing existing translation",
logger.String("arxivID", existingInfo.PaperInfo.ArxivID))
return a.ContinueTranslation(existingInfo.PaperInfo.ArxivID)
} else {
// User wants to restart from scratch - delete existing
if existingInfo.PaperInfo != nil && existingInfo.PaperInfo.ArxivID != "" {
logger.Info("deleting existing translation for restart",
logger.String("arxivID", existingInfo.PaperInfo.ArxivID))
if err := a.results.DeletePaper(existingInfo.PaperInfo.ArxivID); err != nil {
logger.Warn("failed to delete existing paper", logger.Err(err))
}
}
// Fall through to ProcessSource
}
}
// For other cases (e.g., pending), just start fresh
}
return a.ProcessSource(input)
}
// ProcessSource processes the input source and executes the complete translation flow.
// The flow is:
// 1. Parse input (URL, ArxivID, or LocalZip)
// 2. Download/extract source code
// 3. Find main tex file
// 4. Compile original document to PDF
// 5. Translate tex content
// 6. Validate and fix syntax errors
// 7. Compile translated document to PDF
// 8. Return ProcessResult with both PDF paths
//
// Validates: Requirements 1.1-1.5, 2.1-2.5, 3.1-3.5
func (a *App) ProcessSource(input string) (*types.ProcessResult, error) {
logger.Info("starting source processing", logger.String("input", input))
// Check if already processing to prevent duplicate calls
if a.IsProcessing() {
logger.Warn("ProcessSource called while already processing, ignoring duplicate call")
return nil, types.NewAppError(types.ErrInternal, "已有翻译任务正在进行中", nil)
}
// Create a cancellable context for this processing session
ctx, cancel := context.WithCancel(a.ctx)
a.cancelFunc = cancel
defer func() {
a.cancelFunc = nil
}()
// Reset status to idle at the start
a.updateStatus(types.PhaseIdle, 0, "开始处理...")
// Step 1: Parse input to determine source type
a.updateStatus(types.PhaseDownloading, 5, "解析输入...")
logger.Debug("parsing input")
sourceType, err := parser.ParseInput(input)
if err != nil {
logger.Error("input parsing failed", err, logger.String("input", input))
a.updateStatusError(fmt.Sprintf("下载失败: %v", err))
return nil, err
}
logger.Info("input parsed successfully", logger.String("sourceType", string(sourceType)))
// Check for cancellation
if ctx.Err() != nil {
logger.Warn("processing cancelled")
a.updateStatusError("已取消")
return nil, types.NewAppError(types.ErrInternal, "已取消", ctx.Err())
}
// Step 2: Download/extract source code based on type
var sourceInfo *types.SourceInfo
switch sourceType {
case types.SourceTypeURL:
a.updateStatus(types.PhaseDownloading, 10, "下载 URL 源码...")
logger.Info("downloading from URL", logger.String("url", input))
sourceInfo, err = a.downloader.DownloadFromURL(input)
if err != nil {
logger.Error("download from URL failed", err, logger.String("url", input))
a.updateStatusError(fmt.Sprintf("下载失败: %v", err))
return nil, err
}
// Extract the downloaded archive
a.updateStatus(types.PhaseExtracting, 20, "解压源码...")
logger.Debug("extracting downloaded archive")
sourceInfo, err = a.downloader.ExtractZip(sourceInfo.ExtractDir)
if err != nil {
logger.Error("extraction failed", err)
a.updateStatusError(fmt.Sprintf("解压失败: %v", err))
return nil, err
}
sourceInfo.SourceType = types.SourceTypeURL
sourceInfo.OriginalRef = input
case types.SourceTypeArxivID:
a.updateStatus(types.PhaseDownloading, 10, "下载 arXiv 源码...")
logger.Info("downloading by arXiv ID", logger.String("arxivID", input))
sourceInfo, err = a.downloader.DownloadByID(input)
if err != nil {
logger.Error("download by ID failed", err, logger.String("arxivID", input))
a.updateStatusError(fmt.Sprintf("下载失败: %v", err))
// 记录下载错误
arxivID := results.ExtractArxivID(input)
if arxivID != "" {
a.recordError(arxivID, arxivID, input, errors.StageDownload, err.Error())
}
return nil, err
}
// Extract the downloaded archive
a.updateStatus(types.PhaseExtracting, 20, "解压源码...")
logger.Debug("extracting downloaded archive")
sourceInfo, err = a.downloader.ExtractZip(sourceInfo.ExtractDir)
if err != nil {
logger.Error("extraction failed", err)
a.updateStatusError(fmt.Sprintf("解压失败: %v", err))
// 记录解压错误
arxivID := results.ExtractArxivID(input)
if arxivID != "" {
a.recordError(arxivID, arxivID, input, errors.StageExtract, err.Error())
}
return nil, err
}
sourceInfo.SourceType = types.SourceTypeArxivID
sourceInfo.OriginalRef = input
case types.SourceTypeLocalZip:
a.updateStatus(types.PhaseExtracting, 15, "解压本地文件...")
logger.Info("extracting local zip file", logger.String("path", input))
sourceInfo, err = a.downloader.ExtractZip(input)
if err != nil {
logger.Error("extraction failed", err, logger.String("path", input))
a.updateStatusError(fmt.Sprintf("解压失败: %v", err))
return nil, err
}
default:
err := types.NewAppError(types.ErrInvalidInput, "不支持的输入类型", nil)
logger.Error("unsupported input type", err)
a.updateStatusError(err.Error())
return nil, err
}
// Check for cancellation
if ctx.Err() != nil {
logger.Warn("processing cancelled")
a.updateStatusError("已取消")
return nil, types.NewAppError(types.ErrInternal, "已取消", ctx.Err())
}
// Step 2.5: Preprocess tex files to fix common issues
a.updateStatus(types.PhaseExtracting, 22, "预处理 LaTeX 源文件...")
logger.Info("preprocessing tex files", logger.String("extractDir", sourceInfo.ExtractDir))
if err := compiler.PreprocessTexFiles(sourceInfo.ExtractDir); err != nil {
// Log warning but don't fail - preprocessing is best-effort
logger.Warn("preprocessing failed", logger.Err(err))
}
// Step 3: Find main tex file
a.updateStatus(types.PhaseExtracting, 25, "查找主 tex 文件...")
logger.Debug("finding main tex file", logger.String("extractDir", sourceInfo.ExtractDir))
mainTexFile, err := a.downloader.FindMainTexFile(sourceInfo.ExtractDir)
if err != nil {
logger.Error("failed to find main tex file", err)
a.updateStatusError(fmt.Sprintf("未找到主 tex 文件: %v", err))
// Save intermediate result on error
arxivID := results.ExtractArxivID(input)
if arxivID != "" {
a.saveIntermediateResult(arxivID, arxivID, input, sourceInfo, results.StatusError, err.Error(), "", "")
// 记录解压/查找文件错误
a.recordError(arxivID, arxivID, input, errors.StageExtract, err.Error())
}
return nil, err
}
sourceInfo.MainTexFile = mainTexFile
logger.Info("found main tex file", logger.String("mainTexFile", mainTexFile))
mainTexPath := filepath.Join(sourceInfo.ExtractDir, mainTexFile)
// Extract arXiv ID and title for saving intermediate results
arxivID := results.ExtractArxivID(input)
// Extract source ID for file naming (arXiv ID or zip filename without extension)
sourceID := arxivID
if sourceID == "" && sourceType == types.SourceTypeLocalZip {
// For local zip files, use the filename without extension
sourceID = strings.TrimSuffix(filepath.Base(input), filepath.Ext(input))
}
title := ""
if arxivID != "" {
mainTexContent, readErr := os.ReadFile(mainTexPath)
if readErr == nil {
title = results.ExtractTitleFromTeX(string(mainTexContent))
}
if title == "" {
title = arxivID
}
// Save intermediate result after extraction
a.saveIntermediateResult(arxivID, title, input, sourceInfo, results.StatusExtracted, "", "", "")
}
// Check for cancellation
if ctx.Err() != nil {
logger.Warn("processing cancelled")
a.updateStatusError("已取消")
return nil, types.NewAppError(types.ErrInternal, "已取消", ctx.Err())
}
// Detect project size and adjust timeout if needed
texFileCount := len(sourceInfo.AllTexFiles)
isLargeProject := texFileCount > 20
if isLargeProject {
logger.Info("detected large project",
logger.Int("texFiles", texFileCount))
a.updateStatus(types.PhaseCompiling, 28,
fmt.Sprintf("检测到大型项目(%d 个文件),编译可能需要较长时间...", texFileCount))
// For very large projects (50+ files), use even longer timeout
if texFileCount > 50 {
a.compiler = compiler.NewLaTeXCompiler(a.compiler.GetCompiler(), a.workDir, 15*time.Minute)
logger.Info("using extended timeout for very large project",
logger.String("timeout", "15 minutes"))
}
}
// Step 4: Compile original document to PDF
a.updateStatus(types.PhaseCompiling, 30, "编译原始文档...")