package appwindow import ( "context" "errors" "sync" "time" ) var ( ErrWindowOpen = errors.New("an app window is already open") ErrSessionsClosed = errors.New("app window service is closed") ) // Sessions owns the single app window opened during one plugin activation. type Sessions struct { mu sync.Mutex closed bool active *activeSession } type activeSession struct { cancel context.CancelFunc done chan struct{} } // Start prepares the window under the command's cancellation and transfers // its runtime to Sessions after preparation succeeds. func (s *Sessions) Start(command context.Context, prepare func(context.Context) (func(), error)) error { if err := command.Err(); err != nil { return err } s.mu.Lock() if s.closed { s.mu.Unlock() return ErrSessionsClosed } if s.active != nil { s.mu.Unlock() return ErrWindowOpen } ctx, cancel := context.WithCancel(context.Background()) active := &activeSession{cancel: cancel, done: make(chan struct{})} s.active = active s.mu.Unlock() finish := func() { cancel() s.mu.Lock() s.active = nil close(active.done) s.mu.Unlock() } stopStartup := context.AfterFunc(command, cancel) run, err := prepare(ctx) if !stopStartup() { cancel() } if err != nil { finish() return err } // Run even when startup was canceled after preparation. The prepared // function owns the initial capture resources and releases them on exit. startupErr := ctx.Err() go func() { defer finish() run() }() return startupErr } // Close prevents new sessions and cancels preparation or the active viewer. func (s *Sessions) Close() { s.mu.Lock() s.closed = true active := s.active s.mu.Unlock() if active == nil { return } active.cancel() // Keep plugin transitions bounded if the OS clipboard owner is stalled. timer := time.NewTimer(5 * time.Second) defer timer.Stop() select { case <-active.done: case <-timer.C: } }