Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1118 lines (1047 loc) · 42.1 KB
/
Copy pathmain.go
File metadata and controls
1118 lines (1047 loc) · 42.1 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 (
"context"
"embed"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
"unidoc-pdf-debugger/internal/clitool"
"unidoc-pdf-debugger/internal/filewatch"
"unidoc-pdf-debugger/internal/pdfcore"
"unidoc-pdf-debugger/internal/pdfservice"
"unidoc-pdf-debugger/internal/pendingopen"
"unidoc-pdf-debugger/internal/recentfiles"
"unidoc-pdf-debugger/internal/splash"
"unidoc-pdf-debugger/internal/updateservice"
)
// version is the release version of the GUI binary, printed by the `--version`
// flag. Overridden at build time via `-ldflags "-X main.version=x.y.z"` (see
// build/{darwin,linux,windows}/Taskfile.yml). Default `"dev"` applies to
// untagged local builds.
var version = "dev"
// appName is the application's display name. It is BOTH the Wails app Name and
// the macOS app-submenu label (Wails builds the app submenu via
// NewSubMenuItem(options.Name)), so the install item lookup
// (menu.FindByLabel(appName)) MUST use the same literal -- a single source of
// truth here prevents the menu item from silently vanishing on a rename.
const appName = "UniDoc PDF Debugger"
// appID identifies the app to the OS: the single-instance lock, and on Linux
// the GTK application id, which must match StartupWMClass in the .desktop file
// for the desktop to show the app's name and icon.
const appID = "com.unidoc.unidoc-pdf-debugger"
// instanceID is the single-instance lock id and the Linux GTK application id.
// It equals appID except in a build with the mcp tag, which uses its own id
// so the agent build runs beside the production app.
var instanceID = appID
// windowTitle is the main window title. It equals appName except in a build
// with the mcp tag.
var windowTitle = appName
// recentFlushDelay is how long Open Recent waits, with no open in flight, after
// the last open before it saves the list and rebuilds its menu.
const recentFlushDelay = 500 * time.Millisecond
// recentMaxHold is how long an open in flight can hold an Open Recent save;
// an open running longer stops holding it.
const recentMaxHold = 10 * time.Second
// Wails uses Go's `embed` package to embed the frontend files into the binary.
// Any files in the frontend/dist folder will be embedded into the binary and
// made available to the frontend.
// See https://pkg.go.dev/embed for more information.
//go:embed all:frontend/dist
var assets embed.FS
// extractPDFPaths returns all arguments (after the first, which is the binary
// name) that end in .pdf (case-insensitive). Returns nil if args has fewer
// than 2 elements.
func extractPDFPaths(args []string) []string {
if len(args) < 2 {
return nil
}
var paths []string
for _, arg := range args[1:] {
if strings.EqualFold(filepath.Ext(arg), ".pdf") {
paths = append(paths, arg)
}
}
return paths
}
// routeOpenPath is the shared per-path decision used by both file-open entry
// points (ApplicationOpenedWithFile, OnSecondInstanceLaunch). It
// adds the path to the queue first; if the queue is ready (warm path) it opens
// the path immediately via open and returns true so the caller can decide
// whether to Focus the window. If the queue is not yet ready (cold start) the
// path is buffered for the frontend drain and the function returns false
// without opening. Extracting the decision keeps the two callbacks in lockstep
// and gives the wiring a unit-testable seam (see TestRouteOpenPath).
func routeOpenPath(q *pendingopen.Queue, path string, open func(string)) bool {
if q.Add(path) {
open(path)
return true
}
return false
}
// pdfOpener is the narrow surface openFileAndEmitWithWarning needs from
// pdfservice.PDFService. Defined as an interface so the latency test can
// swap in a stub that sleeps inside OpenFile without dragging the full
// Wails service plumbing into the unit test. *pdfservice.PDFService
// satisfies this implicitly via its pointer-receiver methods.
type pdfOpener interface {
OpenFile(path string) (*pdfcore.DocumentInfo, error)
GetTreeRoot(tabID string) (*pdfcore.TreeNode, error)
GetChildren(tabID string, nodeID string) ([]*pdfcore.TreeNode, error)
CloseDocument(tabID string) error
}
// literalMenuLabel returns label escaped so the native menu on goos shows it
// as written. Windows reads "&" and GTK reads "_" as a mnemonic marker, and a
// doubled marker shows one literal character; macOS has no markers.
func literalMenuLabel(label, goos string) string {
switch goos {
case "windows":
return strings.ReplaceAll(label, "&", "&&")
case "linux":
return strings.ReplaceAll(label, "_", "__")
}
return label
}
// recentRecorder is implemented by openers that record a successful open in
// File > Open Recent. *pdfservice.PDFService implements it; the latency test's
// stubs do not, so for them recording is skipped.
type recentRecorder interface {
RecordRecentFile(path string)
}
// eventEmitter is the narrow surface openFileAndEmitWithWarning needs from
// application.EventManager. *application.EventManager satisfies this
// implicitly; the latency test passes a recording stub.
type eventEmitter interface {
Emit(name string, data ...any) bool
}
// openFileAndEmitWithWarning opens a PDF, fetches the tree root + children,
// and emits document:opened with the result. If extraWarning is non-empty,
// it is appended to (or replaces) the per-document warning field in the
// payload. A successful open is recorded in Open Recent when svc implements
// recentRecorder. This lets callers piggyback advisory messages (e.g. "2
// unsupported files could not be opened") onto a document's open event so
// the frontend handler dispatches SET_DOCUMENT_WARNING in the same tick as
// the OPEN_DOCUMENT that would otherwise clear it -- guaranteeing the
// warning survives regardless of event-bus ordering.
//
// The pdfcpu read is dispatched to a goroutine so the caller
// (Wails event-dispatch goroutine for menu / file-drop / single instance)
// returns immediately, leaving the native event loop free to service
// window resize / menu clicks during the parse. The wg argument lets
// callers synchronise on goroutine completion: openFilesBatch awaits per
// file (sequential at the file boundary because pdfcpu's ReadContextFile
// is not documented as concurrent-safe across files), and single-file
// entry points pass a local WaitGroup so they preserve their
// synchronous-completion contract.
//
// The caller MUST call wg.Add(1) BEFORE invoking this function. The
// goroutine launched here calls wg.Done() on completion.
// document:load-start is emitted synchronously (before the goroutine is
// dispatched) so the frontend renders the loading indicator without
// waiting on the goroutine scheduler.
//
// svc and emitter are narrow interfaces (pdfOpener, eventEmitter) so the
// latency test can inject a slow-OpenFile stub and a recording emitter.
// Production passes &pdfService and app.Event respectively.
func openFileAndEmitWithWarning(svc pdfOpener, emitter eventEmitter, path string, extraWarning string, wg *sync.WaitGroup) {
// Emit load-start synchronously so the frontend can render an immediate
// "Opening ..." indicator instead of leaving the EmptyState drop area
// silent for the duration of a large-file parse.
emitter.Emit(eventDocumentLoadStart, map[string]any{
"filePath": path,
"fileName": filepath.Base(path),
})
// Dispatch the pdfcpu read to a goroutine. The long-lived values are
// passed as explicit parameters to document their lifetime.
go func(p, ew string, s pdfOpener, a eventEmitter, w *sync.WaitGroup) {
defer w.Done()
docInfo, err := s.OpenFile(p)
if err != nil {
a.Emit(eventDocumentError, map[string]any{
"message": err.Error(),
})
return
}
root, err := s.GetTreeRoot(docInfo.TabID)
if err != nil {
_ = s.CloseDocument(docInfo.TabID)
a.Emit(eventDocumentError, map[string]any{
"message": err.Error(),
})
return
}
children, err := s.GetChildren(docInfo.TabID, "root")
if err != nil {
log.Printf("warning: failed to get root children for tab %s: %v", docInfo.TabID, err)
}
payload := map[string]any{
"tabId": docInfo.TabID,
"fileName": docInfo.FileName,
"filePath": docInfo.FilePath,
"pageCount": docInfo.PageCount,
"fileSize": docInfo.FileSize,
"rootNode": root,
"rootChildren": children,
}
warnings := make([]string, 0, 2)
if docInfo.Error != "" {
warnings = append(warnings, docInfo.Error)
}
if ew != "" {
warnings = append(warnings, ew)
}
if len(warnings) > 0 {
payload["warning"] = strings.Join(warnings, " ")
}
a.Emit(eventDocumentOpened, payload)
if r, ok := s.(recentRecorder); ok {
r.RecordRecentFile(p)
}
}(path, extraWarning, svc, emitter, wg)
}
// onSplashDismiss is the success-path dismissal handler for the startup
// splash. It clears the splash's AlwaysOnTop so the main
// window can render above it, triggers the crossfade by emitting
// splash:dismiss (the splash's inline JS toggles its body opacity to 0)
// and splash:dismissed (the main frontend fades its #root opacity to 1),
// unhides the main window, then closes + destroys the splash after the
// 200ms crossfade. The callback can be invoked from a non-main goroutine
// (clock-driven); Wails SetAlwaysOnTop / Show / Close all InvokeSync to the
// impl thread internally and app.Event.Emit is goroutine-safe, so direct
// calls from a worker goroutine are safe.
func onSplashDismiss(app *application.App, splashWindow, mainWindow *application.WebviewWindow) {
if splashWindow != nil {
splashWindow.SetAlwaysOnTop(false)
}
// Tell the splash WebView to fade its body to opacity 0.
app.Event.Emit(eventSplashDismiss, nil)
// Reveal the main window and let the frontend transition opacity up.
if mainWindow != nil {
mainWindow.Show()
}
app.Event.Emit(eventSplashDismissed, nil)
// Close the splash after the 200ms crossfade window.
// WebviewWindow.Close() dispatches to the impl thread internally, so it
// can be called from a time.AfterFunc goroutine.
time.AfterFunc(220*time.Millisecond, func() {
if splashWindow != nil {
splashWindow.Close()
}
})
}
// installedLinkPath returns the path of OUR installed pdfdebug symlink if one
// already exists in the install dir (used to initialize the menu label and to
// drive uninstall). Returns "" if not installed.
func installedLinkPath() string {
dir := clitool.DefaultInstallDir()
if dir == "" {
return ""
}
link := filepath.Join(dir, "pdfdebug")
if clitool.IsInstalled(link) {
return link
}
return ""
}
// runInstallCLI invokes the install package and presents the appropriate native
// dialog for each typed result. On a confirmed-overwrite it re-invokes with the
// Overwrite flag. After a successful install it flips the menu item to the
// uninstall affordance. macOS-only (the menu item is gated to darwin).
func runInstallCLI(app *application.App, installItem *application.MenuItem, overwrite bool) {
exe, err := clitool.RunningExecutablePath()
if err != nil {
app.Dialog.Error().
SetTitle("Install pdfdebug").
SetMessage("Could not locate the running application: " + err.Error()).
Show()
return
}
res, err := clitool.InstallCLI(clitool.Options{ExecutablePath: exe, Overwrite: overwrite})
if err != nil {
app.Dialog.Error().
SetTitle("Install pdfdebug").
SetMessage("Install failed: " + err.Error()).
Show()
return
}
switch r := res.(type) {
case clitool.Installed:
app.Dialog.Info().
SetTitle("pdfdebug is ready").
SetMessage("Installed at:\n" + r.Path + "\n\nOpen a NEW terminal window and try:\n pdfdebug --version").
Show()
flipToUninstall(app, installItem, r.Path)
case clitool.NeedsPathHelp:
dialog := app.Dialog.Question().
SetTitle("Almost there -- add pdfdebug to your PATH").
SetMessage("pdfdebug was linked into:\n" + r.Dir + "\n\nThat directory is not on your PATH yet, so the command will not be found until it is added. Want me to add it to your shell profile for you?")
addBtn := dialog.AddButton("Add it for me")
manualBtn := dialog.AddButton("I'll do it myself")
dialog.SetDefaultButton(addBtn)
addBtn.OnClick(func() {
profile, err := clitool.AddDirToShellProfile(r.Dir)
if err != nil {
// Unknown shell or write failure -> fall back to manual guidance.
showManualPathHelp(app, r.Dir, r.ExportLine)
return
}
app.Dialog.Info().
SetTitle("pdfdebug added to your PATH").
SetMessage("Updated:\n" + profile + "\n\nRestart your terminal (or run `source " + profile + "`), then run:\n pdfdebug --version").
Show()
})
manualBtn.OnClick(func() { showManualPathHelp(app, r.Dir, r.ExportLine) })
dialog.Show()
flipToUninstall(app, installItem, filepath.Join(r.Dir, "pdfdebug"))
case clitool.ConfirmOverwrite:
dialog := app.Dialog.Question().
SetTitle("Replace existing pdfdebug?").
SetMessage("An existing file is already at:\n" + r.LinkPath + "\n\nIt was not created by this app. Replace it with a link to the bundled pdfdebug?")
replace := dialog.AddButton("Replace")
cancel := dialog.AddButton("Cancel")
dialog.SetDefaultButton(cancel)
replace.OnClick(func() { runInstallCLI(app, installItem, true) })
dialog.Show()
case clitool.NotInBundle:
app.Dialog.Warning().
SetTitle("Install pdfdebug").
SetMessage("This command is only available when running the installed app. Run UniDoc PDF Debugger from /Applications (or wherever you installed the .app), then try again.").
Show()
}
}
// showManualPathHelp presents the manual PATH-export instructions (the fallback
// when the user declines the auto-edit or the shell is unrecognized).
func showManualPathHelp(app *application.App, dir, exportLine string) {
app.Dialog.Info().
SetTitle("Add pdfdebug to your PATH").
SetMessage("pdfdebug was linked into:\n" + dir + "\n\nAdd this line to your shell profile (e.g. ~/.zshrc), then open a NEW terminal:\n\n " + exportLine + "\n\nThen run:\n pdfdebug --version").
Show()
}
// runUninstallCLI removes our symlink and flips the menu item back to the
// install affordance.
func runUninstallCLI(app *application.App, installItem *application.MenuItem, linkPath string) {
if err := clitool.UninstallCLI(linkPath); err != nil {
app.Dialog.Error().
SetTitle("Uninstall pdfdebug").
SetMessage("Uninstall failed: " + err.Error()).
Show()
return
}
app.Dialog.Info().
SetTitle("pdfdebug removed").
SetMessage("The pdfdebug command was removed from your PATH.").
Show()
flipToInstall(app, installItem)
}
// flipToUninstall mutates the retained menu item to the uninstall affordance.
func flipToUninstall(app *application.App, installItem *application.MenuItem, linkPath string) {
installItem.SetLabel(clitool.UninstallMenuItemLabel)
installItem.OnClick(func(ctx *application.Context) {
runUninstallCLI(app, installItem, linkPath)
})
}
// flipToInstall mutates the retained menu item back to the install affordance.
func flipToInstall(app *application.App, installItem *application.MenuItem) {
installItem.SetLabel(clitool.MenuItemLabel)
installItem.OnClick(func(ctx *application.Context) {
runInstallCLI(app, installItem, false)
})
}
// wireInstallCLIMenuItem appends the install item to the macOS app submenu,
// initializes its label from the current installed state, and wires its click
// handler. The retained *MenuItem is the runtime mutation target for the
// install/uninstall label flip (the app menu is set once via
// SetApplicationMenu). macOS-only; the caller gates on runtime.GOOS.
func wireInstallCLIMenuItem(app *application.App, appSub *application.Menu) {
installItem := appSub.Add(clitool.MenuItemLabel)
if link := installedLinkPath(); link != "" {
flipToUninstall(app, installItem, link)
} else {
flipToInstall(app, installItem)
}
}
// diskWatchService runs the disk watcher for the app's lifetime. Only the
// Wails lifecycle methods are exported, so it adds no frontend binding.
type diskWatchService struct {
w *filewatch.Watcher
}
// ServiceStartup starts the watcher's scheduler.
func (s *diskWatchService) ServiceStartup(_ context.Context, _ application.ServiceOptions) error {
s.w.Start()
return nil
}
// ServiceShutdown stops the scheduler without waiting for stats in flight.
func (s *diskWatchService) ServiceShutdown() error {
s.w.Stop()
return nil
}
// diskStatusEmitter forwards settled watcher events to the frontend.
type diskStatusEmitter struct {
app *application.App
}
// Emit sends ev as a document:disk-status event.
func (e diskStatusEmitter) Emit(ev filewatch.Event) {
e.app.Event.Emit(eventDocumentDiskStatus, ev)
}
func main() {
// --version short-circuit: must run BEFORE application.New so that
// `unidoc-pdf-debugger --version` does not spin up a Wails webview/window
// on headless runners.
if len(os.Args) > 1 && os.Args[1] == "--version" {
fmt.Println(version)
os.Exit(0)
}
// Declare variables before application.New() so the SingleInstance callback
// can capture them by reference. They are assigned after app/window creation
// but before app.Run(), so they are safe to use in the async callback.
var openFileAndEmit func(string)
var window *application.WebviewWindow
// The cold-start file-association queue. Constructed BEFORE
// application.New() so both file-open callbacks can capture it by value
// (it has no dependency on app/window, unlike the openFileAndEmit/window
// closure dance above). On cold start, paths arriving before the frontend
// has drained are buffered here instead of being emitted into a
// not-yet-listening WebView and silently dropped.
openQueue := &pendingopen.Queue{}
// Create a new Wails application by providing the necessary options.
app := application.New(application.Options{
Name: appName,
Description: "PDF structure inspector and debugger\n\nUniDoc ehf. -- https://unidoc.io",
Assets: application.AssetOptions{
Handler: application.AssetFileServerFS(assets),
},
Mac: application.MacOptions{
ApplicationShouldTerminateAfterLastWindowClosed: true,
},
FileAssociations: []string{".pdf"},
Linux: application.LinuxOptions{
ApplicationID: instanceID,
},
SingleInstance: &application.SingleInstanceOptions{
UniqueID: instanceID,
OnSecondInstanceLaunch: func(data application.SecondInstanceData) {
// Route every path through the queue first. A path
// that arrives before the frontend has drained is buffered
// (Add returns false) instead of dropped; only ready/warm paths
// open immediately. window.Focus() fires only when at least one
// path opened on the ready (warm) path.
focus := false
for _, p := range extractPDFPaths(data.Args) {
if routeOpenPath(openQueue, p, openFileAndEmit) {
focus = true
}
}
if focus {
window.Focus()
}
},
},
})
if app == nil {
log.Fatal("application.New returned nil")
}
pdfService := pdfservice.NewPDFService(app)
// Wire the cold-start queue so ConsumePendingOpenFiles can
// drain it from the frontend.
pdfService.SetPendingOpens(openQueue)
app.RegisterService(application.NewService(&pdfService))
// Disk watcher: polls every open document's file and emits
// document:disk-status once a change has settled.
diskWatcher := pdfservice.WatchDiskStatus(&pdfService, diskStatusEmitter{app: app}, filewatch.SystemClock{})
app.RegisterService(application.NewService(&diskWatchService{w: diskWatcher}))
// Update-notification service. Version-aware; skips the check on "dev".
updateSvc := updateservice.NewUpdateService(app, version)
app.RegisterService(application.NewService(updateSvc))
// openFileAndEmit handles the shared logic for opening a PDF and emitting
// the result to the frontend. Used by menu, file drop, file association,
// and single-instance handlers.
//
// openFileAndEmitWithWarning now dispatches the pdfcpu read
// to a goroutine. Single-file entry points (menu / file-drop /
// single-instance / file-association) wrap with a local WaitGroup +
// wg.Wait() so callers preserve their synchronous-completion contract.
// Without this Wait, callers would return to the event loop before the
// document opens, breaking the implicit "first call after Open succeeds
// returns the new tab" assumption.
openFileAndEmit = func(path string) {
// Code shape: wg.Add(1) is called by the caller before invoking
// openFileAndEmitWithWarning; the launched goroutine inside calls
// wg.Done() on completion.
var wg sync.WaitGroup
wg.Add(1)
openFileAndEmitWithWarning(&pdfService, app.Event, path, "", &wg)
wg.Wait()
}
// batchCancelled is checked between iterations of openFilesBatch.
// Set by the frontend Cancel button via document:batch-cancel; reset
// at the start of each batch.
var batchCancelled atomic.Bool
app.Event.On(eventDocumentBatchCancel, func(_ *application.CustomEvent) {
batchCancelled.Store(true)
})
// File > Open Recent. The list is shared by the Go open paths (through
// RecordRecentFile on the opener) and the frontend's own opens (through
// the bound PDFService.RecordRecentFile), so it is guarded by its mutex and
// the submenu rebuild by recentMu. recentFlush decides when the list is
// saved and the menu rebuilt (rebuildRecentMenu is assigned with the menu
// below).
recent := recentfiles.Load(recentfiles.DefaultPath())
saveRecent := func() {
if err := recent.Save(); err != nil {
log.Printf("warning: could not save the recent files list: %v", err)
}
}
var rebuildRecentMenu func()
recentFlush := newRecentFlusher(recentFlushDelay, recentMaxHold, saveRecent, func() { rebuildRecentMenu() }, application.InvokeSync)
pdfService.SetOpenTracker(recentFlush.OpenStarted)
// openFilesBatch opens a slice of PDF paths sequentially and emits
// document:batch-* progress events when more than one file is in flight.
// Used by both the file-drop handler and the menu Open... item.
openFilesBatch := func(pdfPaths []string, unsupportedCount int) {
if len(pdfPaths) == 0 {
return
}
batchCancelled.Store(false)
// Piggyback the unsupported-files advisory onto the last
// document:opened payload so the frontend sets the warning in the
// same tick as the OPEN_DOCUMENT that would otherwise clear it.
var unsupportedMsg string
if unsupportedCount > 0 {
noun := "files"
if unsupportedCount == 1 {
noun = "file"
}
unsupportedMsg = fmt.Sprintf("%d unsupported %s could not be opened.", unsupportedCount, noun)
}
if len(pdfPaths) > 1 {
app.Event.Emit(eventDocumentBatchStart, map[string]any{
"total": len(pdfPaths),
})
}
// Sequential dispatch at the file boundary.
// Local WaitGroup; wg.Add(1) before each call (code shape);
// wg.Wait() per iteration enforces "one file at a time" (pdfcpu's
// ReadContextFile is not documented as concurrent-safe across
// DIFFERENT files). The per-iteration Wait sits BEFORE the next
// iteration's batchCancelled.Load() check, so cancel skips remaining
// un-kicked files but does NOT preempt the in-flight read.
var wg sync.WaitGroup
for i, p := range pdfPaths {
if batchCancelled.Load() {
break
}
// Attach the unsupported-files advisory to the last file's
// document:opened payload. Natural break on cancel skips this.
extra := ""
if i == len(pdfPaths)-1 {
extra = unsupportedMsg
}
wg.Add(1)
openFileAndEmitWithWarning(&pdfService, app.Event, p, extra, &wg)
wg.Wait() // serialize at file boundary
}
if len(pdfPaths) > 1 {
// Defensive final Wait. By the per-iteration Wait above the
// WaitGroup is already drained; this explicit Wait makes the
// contract obvious and survives future refactors that move the
// Wait out of the loop.
wg.Wait()
app.Event.Emit(eventDocumentBatchComplete, nil)
}
}
// Handle files opened via OS file association (right-click > "Open with").
// On macOS this fires for both cold and warm starts. On Windows/Linux cold
// start only -- warm start is handled by OnSecondInstanceLaunch.
app.Event.OnApplicationEvent(events.Common.ApplicationOpenedWithFile, func(event *application.ApplicationEvent) {
// No nil guard. The invariant: Drain is reachable only
// through the bound ConsumePendingOpenFiles method, bindings serve only
// after app.Run(), and both openFileAndEmit (assigned above) and window
// (assigned before app.Run()) exist by then. An early-fire path is
// buffered by routeOpenPath (queue not ready) rather than dropped, so a
// guard here would re-introduce the silent drop this story fixes.
filePath := event.Context().Filename()
if filePath != "" && strings.EqualFold(filepath.Ext(filePath), ".pdf") {
if routeOpenPath(openQueue, filePath, openFileAndEmit) {
window.Focus()
}
}
})
// showAbout brings the main window forward when it is minimised or on
// screen, then asks its frontend to show the About dialog. Until the
// frontend has mounted (aboutReady), the request is held in aboutPending
// and sent when it has. A main window still hidden behind the splash stays
// hidden; the dialog is open when it appears.
var aboutMu sync.Mutex
var aboutReady, aboutPending bool
showAbout := func() {
if window != nil {
if window.IsMinimised() {
window.UnMinimise()
window.Focus()
} else if window.IsVisible() {
window.Focus()
}
}
aboutMu.Lock()
defer aboutMu.Unlock()
if !aboutReady {
aboutPending = true
return
}
app.Event.Emit(eventAboutOpen, version)
}
// Build native menu bar
menu := application.NewMenu()
// macOS app menu (About, Services, Hide, Quit) -- AddRole is a no-op on non-macOS
menu.AddRole(application.AppMenu)
// macOS-only app-submenu wiring. AddRole(AppMenu) returns the PARENT
// *Menu, not the app submenu, so items are reached via
// FindByLabel(appName).GetSubmenu().
// Two changes here:
// - Append the "Install 'pdfdebug' Command in PATH..." item.
// - Replace the native About item with the in-app About dialog. The
// role-based About item carries the native orderFrontStandardAboutPanel
// selector, so clearing its role (NoRole) routes clicks through the Go
// callback instead, which asks the frontend to show the dialog.
if runtime.GOOS == "darwin" {
if appItem := menu.FindByLabel(appName); appItem != nil {
if appSub := appItem.GetSubmenu(); appSub != nil {
appSub.AddSectionHeader("Command Line")
wireInstallCLIMenuItem(app, appSub)
if aboutItem := appSub.FindByRole(application.About); aboutItem != nil {
aboutItem.SetRole(application.NoRole).
SetLabel("About " + appName).
OnClick(func(_ *application.Context) {
showAbout()
})
}
}
}
}
// File menu. Section headers group the items on macOS 14+ and are no-ops
// elsewhere.
fileMenu := menu.AddSubmenu("File")
fileMenu.AddSectionHeader("Open")
fileMenu.Add("Open...").
SetAccelerator("CmdOrCtrl+o").
OnClick(func(ctx *application.Context) {
paths, err := app.Dialog.OpenFile().
SetTitle("Open PDF").
AddFilter("PDF Files", "*.pdf").
AddFilter("All Files", "*.*").
PromptForMultipleSelection()
if err != nil || len(paths) == 0 {
return
}
// Filter on extension defensively in case the user picked
// non-PDFs via the "All Files" filter.
var pdfPaths []string
for _, p := range paths {
if strings.EqualFold(filepath.Ext(p), ".pdf") {
pdfPaths = append(pdfPaths, p)
}
}
unsupported := len(paths) - len(pdfPaths)
if len(pdfPaths) == 0 {
app.Event.Emit(eventDocumentError, map[string]any{
"message": "Only PDF files can be opened.",
})
return
}
openFilesBatch(pdfPaths, unsupported)
})
recentMenu := fileMenu.AddSubmenu("Open Recent")
fileMenu.AddSectionHeader("Current Document")
closeDocItem := fileMenu.Add("Close Document").
SetAccelerator("CmdOrCtrl+w").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventDocumentCloseActive, nil)
})
reloadDocItem := fileMenu.Add("Reload from Disk").
SetAccelerator("CmdOrCtrl+r").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventDocumentReloadActive, nil)
})
compareDocItem := fileMenu.Add("Compare with File on Disk").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventDocumentCompareActive, nil)
})
if runtime.GOOS != "darwin" {
fileMenu.AddSeparator()
fileMenu.Add("Quit").
SetAccelerator("Ctrl+q").
OnClick(func(ctx *application.Context) {
app.Quit()
})
}
// Edit menu (standard roles -- Cut, Copy, Paste, Select All, etc.)
menu.AddRole(application.EditMenu)
// Navigate menu
navMenu := menu.AddSubmenu("Navigate")
navBackItem := navMenu.Add("Back").
SetAccelerator("CmdOrCtrl+[").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventNavigateBack, nil)
})
navForwardItem := navMenu.Add("Forward").
SetAccelerator("CmdOrCtrl+]").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventNavigateForward, nil)
})
navMenu.AddSeparator()
goToPageItem := navMenu.Add("Go to Page...").
SetAccelerator("CmdOrCtrl+G").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventNavigateGoToPage, nil)
})
findObjectItem := navMenu.Add("Find Object...").
SetAccelerator("CmdOrCtrl+K").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventPaletteOpen, nil)
})
navMenu.AddSeparator()
nextDocItem := navMenu.Add("Next Document").
SetAccelerator("CmdOrCtrl+Right").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventTabNext, nil)
})
prevDocItem := navMenu.Add("Previous Document").
SetAccelerator("CmdOrCtrl+Left").
SetEnabled(false).
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventTabPrev, nil)
})
// Help menu: on-demand update check. The frontend runs the live bound check
// (CheckForUpdate) and surfaces the result, including the up-to-date and
// unreachable messages that the silent, cache-gated automatic path
// (CheckForUpdateAtStartup) omits.
helpMenu := menu.AddSubmenu("Help")
helpMenu.Add("Check for Updates...").
OnClick(func(ctx *application.Context) {
app.Event.Emit(eventUpdateCheckRequested, nil)
})
// About lives in the app menu on macOS and at the end of Help elsewhere.
if runtime.GOOS != "darwin" {
helpMenu.AddSeparator()
helpMenu.Add("About " + appName).
OnClick(func(_ *application.Context) {
showAbout()
})
}
// Frontend sends navigation state and the open document count to sync
// menu enabled state: document items need one document, cycling needs two.
// The first report comes after the frontend's first render, when the About
// dialog listens, so it also sends an About request held until then.
app.Event.On(eventNavigateStateChanged, func(event *application.CustomEvent) {
aboutMu.Lock()
aboutReady = true
if aboutPending {
aboutPending = false
app.Event.Emit(eventAboutOpen, version)
}
aboutMu.Unlock()
data, ok := event.Data.(map[string]any)
if !ok {
return
}
if canBack, ok := data["canGoBack"].(bool); ok {
navBackItem.SetEnabled(canBack)
}
if canFwd, ok := data["canGoForward"].(bool); ok {
navForwardItem.SetEnabled(canFwd)
}
// JSON numbers arrive as float64.
if count, ok := data["documentCount"].(float64); ok {
for _, item := range []*application.MenuItem{closeDocItem, reloadDocItem, compareDocItem, goToPageItem, findObjectItem} {
item.SetEnabled(count > 0)
}
nextDocItem.SetEnabled(count > 1)
prevDocItem.SetEnabled(count > 1)
}
})
var recentMu sync.Mutex
// openRecent drops an entry whose file is gone, then opens through the
// normal path so the user still sees the usual open error.
openRecent := func(path string) {
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
recent.Remove(path)
recentFlush.SaveNow()
}
openFilesBatch([]string{path}, 0)
}
rebuildRecentMenu = func() {
recentMu.Lock()
defer recentMu.Unlock()
recentMenu.Clear()
paths := recent.Paths()
for i, label := range recentfiles.Labels(paths) {
p := paths[i]
recentMenu.Add(literalMenuLabel(label, runtime.GOOS)).
SetTooltip(p).
OnClick(func(_ *application.Context) {
openRecent(p)
})
}
recentMenu.AddSeparator()
recentMenu.Add("Clear Menu").
SetEnabled(len(paths) > 0).
OnClick(func(_ *application.Context) {
recent.Clear()
recentFlush.SaveNow()
})
// A rebuilt submenu reaches the screen through the top-level menu on
// macOS and through the window's own menu on Windows and Linux. Both
// are no-ops before the app runs, when SetApplicationMenu shows it.
if runtime.GOOS == "darwin" {
menu.Update()
} else if window != nil {
window.SetMenu(menu)
}
}
rebuildRecentMenu()
// Opens are added to the list at once; recentFlush decides when the list
// is saved and the menu rebuilt.
pdfService.SetRecentFileRecorder(func(path string) {
recent.Add(path)
recentFlush.Record()
})
app.OnShutdown(recentFlush.Close)
// macOS uses the screen-top system menu bar via SetApplicationMenu.
// Windows requires UseApplicationMenu: true on each window to opt in
// (Wails alpha.74 windowsWebviewWindow only honors the app menu when
// UseApplicationMenu is set; Windows.Menu would also work but is more
// verbose). Linux falls back to the app menu unconditionally.
app.Menu.SetApplicationMenu(menu)
registerRowMenus(app)
// Startup splash window. Created BEFORE the main WebviewWindow so the
// user sees branding during WebView2 cold init (especially on Windows
// where the main webview can take 10-30s on first launch). Lives only
// in this first-instance bootstrap path -- the OnSecondInstanceLaunch
// and ApplicationOpenedWithFile callbacks above can fire more than once
// per process, so they MUST NOT spawn additional splash windows. The
// splash is on EVERY launch by design (consistency is the brand
// signal); no first-launch persistence gate.
//
// The splash is a separate WebviewWindow because Wails does not
// expose a pre-WebView native window primitive on Windows. The
// Windows perception trade-off is documented in deferred-work.md.
//
// WebviewWindowOptions has no separate Resizable / Minimisable /
// Closable boolean fields -- the splash disables resize via
// DisableResize and suppresses close/minimise affordances by being
// Frameless.
//
// The splash integration tests grep this file for each option as
// `Name: value`, so the three options with no field to carry them are
// load-bearing as comment text: the `Resizable: false`,
// `Minimisable: false` and `Closable: false` spellings below are the
// only thing those greps can match. Reword the rationale after the
// `--` freely; do not reword those three names or values.
//
// Splash window options:
// Width: 480 -- logical width
// Height: 320 -- logical height
// Frameless: true -- no title bar / chrome
// AlwaysOnTop: true -- cleared in the dismissal handler
// Resizable: false -- carried by DisableResize: true
// Minimisable: false -- frameless suppresses the affordance
// Closable: false -- frameless suppresses the affordance
splashWindow := app.Window.NewWithOptions(application.WebviewWindowOptions{
Title: "",
Width: 480,
Height: 320,
Frameless: true,
AlwaysOnTop: true,
DisableResize: true,
// The splash shows no context menu. Without this the WebView's
// default right-click menu (Reload / Inspect Element / etc.)
// appears on it, especially in dev builds where DevToolsEnabled
// defaults to true.
DefaultContextMenuDisabled: true,
BackgroundColour: application.NewRGB(248, 250, 252),
HTML: splash.Render(version),
// WebKitGTK paints a new view late, so on Linux the splash shows only
// once its page has loaded (see the WindowLoadFinished handler below).
Hidden: runtime.GOOS == "linux",
Windows: application.WindowsWindow{
// Keep the splash off the Windows taskbar so the user does
// not see a phantom entry between splash dismissal and main
// window show.
HiddenOnTaskbar: true,
},
// Linux gives every window the application menu unless it has its own;
// an empty one keeps the menu bar off the splash.
Linux: application.LinuxWindow{
Menu: application.NewMenu(),
},
})
// Guard: NewWithOptions can return nil on platforms where window
// creation fails (e.g. WebView2 missing on Windows pre-bootstrap).
// Center() would panic on a nil receiver; skip splash plumbing
// entirely and let the main window come up unsplashed.
if splashWindow != nil {
splashWindow.Center()
}
// splashFailed tracks whether the splash entered the failure
// (timeout) state. The flag is read by the splash WindowClosing
// listener below: if the user closes the splash error pane (via the
// Close button's window.close() or the OS), we terminate the app so
// they are not left with a hidden main window stuck in cold-init.
// Tracked as an atomic.Bool because the timeout callback fires on a
// clock goroutine while WindowClosing fires on Wails' impl thread.
var splashFailed atomic.Bool
// Wire the failure-path timeout and the success-path dismissal
// via the injectable-clock scheduler in internal/splash. The
// min-display floor and the failure-path timeout are both served
// by this single Scheduler instance.
splashScheduler := splash.NewScheduler(
splash.RealClock{},
// onDismiss: clear AlwaysOnTop, trigger crossfade, then close
// + destroy the splash so it does not linger in the OS
// window list. The callback fires on a clock goroutine;
// SetAlwaysOnTop / Show / Close InvokeSync internally and
// Event.Emit is goroutine-safe, so direct calls from a worker
// goroutine are safe.
func() {
onSplashDismiss(app, splashWindow, window)
},
// onTimeout: flag the failure state, emit splash:timeout so the
// splash inline JS reveals the pre-bundled error pane, and arm a
// 60s force-quit safety net for platforms where the Close
// button's window.close() does not propagate to WindowClosing
// (WKWebView / WebKitGTK on top-level windows). Event.Emit is
// goroutine-safe.
func() {
splashFailed.Store(true)
app.Event.Emit(eventSplashTimeout, nil)
time.AfterFunc(60*time.Second, func() {
if splashFailed.Load() {
app.Quit()
}