package cview

import (
	
	
	
	
	
	

	
	am 

	ssApp 
)

const (
	// The size of the event/update channels.
	queueSize = 100

	// The minimum duration between resize event callbacks.
	resizeEventThrottle = 50 * time.Millisecond

	// appHandlerTimeout is the time a single event loop handler may take before
	// it is aborted by the state machine.
	appHandlerTimeout = 30 * time.Second
	// appEvalTimeout is the time the state machine waits for an Eval func.
	appEvalTimeout = 30 * time.Second
)

// Application represents the top node of an application.
//
// It is not strictly required to use this class as none of the other classes
// depend on it. However, it provides useful tools to set up an application and
// plays nicely with all widgets.
//
// The event loop of the application is driven by an asyncmachine-go state
// machine, see [Application.Mach]. Input events, queued updates, and screen
// replacements are serialized with [am.Machine.Eval], which allows primitives
// to operate without locks during the event loop. Calls from other goroutines
// should be queued with [Application.QueueUpdate] or
// [Application.QueueEvent].
//
// The following command displays a primitive p on the screen until Ctrl-C is
// pressed:
//
//	if err := cview.NewApplication().SetRoot(p, true).Run(); err != nil {
//	    panic(err)
//	}
type Application struct {
	// Mach is the state machine driving the application's event loop.
	Mach *am.Machine

	// screen holds the application's screen. Apart from Run(), this value
	// should never be set directly. Always use SetScreen to replace it.
	screen atomic.Pointer[tcell.Screen]

	// width, height hold the size of the application's screen.
	width, height atomic.Int32

	// focus holds the primitive which currently has the keyboard focus.
	focus atomic.Pointer[primitiveRef]

	// root holds the root primitive to be seen on the screen.
	root atomic.Pointer[primitiveRef]

	// rootFullscreen tells whether the application resizes the root primitive.
	rootFullscreen atomic.Bool

	// callbacks holds the optional user callbacks of the application.
	callbacks atomic.Pointer[appCallbacks]

	// enableBracketedPaste tells whether to enable bracketed paste mode.
	enableBracketedPaste atomic.Bool

	// enableMouse tells whether to enable mouse events.
	enableMouse atomic.Bool

	// doubleClickInterval specifies the maximum time between clicks to
	// register a double click rather than a single click.
	doubleClickInterval atomic.Int64

	// Time a resize event was last processed. Event loop only.
	lastResize time.Time
	// Timer limiting how quickly resize events are processed. Event loop only.
	throttleResize *time.Timer

	// Used to send screen events from separate goroutine to the main event
	// loop.
	events chan tcell.Event

	// Functions queued from goroutines, used to serialize updates to
	// primitives.
	updates chan func()

	// The last mouse state. Event loop only.
	mouseCapturingPrimitive Primitive        // A Primitive returned by a MouseHandler which will capture future mouse events.
	lastMouseX, lastMouseY  int              // The last position of the mouse.
	mouseDownX, mouseDownY  int              // The position of the mouse when its button was last pressed.
	lastMouseClick          time.Time        // The time when a mouse button was last clicked.
	lastMouseButtons        tcell.ButtonMask // The last mouse button state.

	// runErr holds the error which terminated the event loop.
	runErr error
}

// primitiveRef is a comparable holder for a Primitive, so it can be stored in
// an atomic pointer.
type primitiveRef struct {
	p Primitive
}

// appCallbacks holds the optional callbacks of an Application.
type appCallbacks struct {
	inputCapture func(event *tcell.EventKey) *tcell.EventKey
	mouseCapture func(event *tcell.EventMouse, action MouseAction) (*tcell.EventMouse, MouseAction)
	beforeFocus  func(p Primitive) bool
	afterFocus   func(p Primitive)
	beforeDraw   func(screen tcell.Screen) bool
	afterDraw    func(screen tcell.Screen)
	afterResize  func(width int, height int)
	// drawOnKey redraws the screen after a key event. Defaults to true.
	drawOnKey bool
}

// NewApplication creates and returns a new application with its own state
// machine.
func () *Application {
	,  := NewApplicationWithMach(nil)
	if  != nil {
		panic()
	}
	return 
}

// NewApplicationWithMach creates and returns a new application using the passed
// state machine. If mach is nil, a new machine is created.
//
// The machine's schema must implement states.AppSchema, usually by merging it
// with a custom schema:
//
//	schema := states.AppSchema.Merge(customSchema)
//	names := states.AppStates.Names().Add(customNames)
//
// The caller keeps ownership of a passed machine, i.e. the application will not
// dispose it.
func ( *am.Machine) (*Application, error) {
	 := &Application{
		events:  make(chan tcell.Event, queueSize),
		updates: make(chan func(), queueSize),
	}
	.enableBracketedPaste.Store(true)

	var  error
	if  == nil {
		,  = .newMachine()
		if  != nil {
			return nil, 
		}
	}
	if  := .bindMachine();  != nil {
		return nil, 
	}

	return , nil
}

// newMachine creates a new state machine for the application.
func ( *Application) () (*am.Machine, error) {
	,  := am.NewCommon(context.Background(), "", ssApp.AppSchema,
		ssApp.AppStates.Names(), nil, nil, &am.Opts{
			HandlerTimeout: appHandlerTimeout,
			QueueLimit:     1000,
		})
	if  != nil {
		return nil, 
	}
	.EvalTimeout = appEvalTimeout
	.SemLogger().SetArgsMapper(am.NewLogArgsMapper(0, nil))

	return , nil
}

// bindMachine validates the passed machine and binds the application handlers.
func ( *Application) ( *am.Machine) error {
	if  == nil {
		return errors.New("cview: nil machine")
	}
	if .IsDisposed() {
		return errors.New("cview: machine is disposed")
	}
	if !.Schema().Implements(ssApp.AppSchema) {
		 := ssApp.AppStates.Names().Sub(.StateNames())
		return fmt.Errorf("cview: machine schema is missing app states: %v",
			)
	}

	 := &appHandlers{
		ExceptionHandler: &am.ExceptionHandler{},
		app:              ,
	}
	if ,  := .HandlersBind(, am.BindOpts{Id: "cview:app"});  != nil {
		return fmt.Errorf("cview: bind app handlers: %w", )
	}

	.Mach = 
	return nil
}

// HandlePanic (when deferred at the start of a goroutine) handles panics
// gracefully. The terminal is returned to its original state before the panic
// message is printed.
//
// Panics may only be handled by the panicking goroutine. Because of this,
// HandlePanic must be deferred at the start of each goroutine (including main).
func ( *Application) () {
	 := recover()
	if  == nil {
		return
	}

	.finalizeScreen()

	panic()
}

// SetInputCapture sets a function which captures all key events before they are
// forwarded to the key event handler of the primitive which currently has
// focus. This function can then choose to forward that key event (or a
// different one) by returning it or stop the key event processing by returning
// nil.
//
// Note that this also affects the default event handling of the application
// itself: Such a handler can intercept the Ctrl-C event which closes the
// application.
func ( *Application) ( func( *tcell.EventKey) *tcell.EventKey) {
	.setCallbacks(func( *appCallbacks) {
		.inputCapture = 
	})
}

// GetInputCapture returns the function installed with SetInputCapture() or nil
// if no such function has been installed.
func ( *Application) () func( *tcell.EventKey) *tcell.EventKey {
	return .getCallbacks().inputCapture
}

// SetDrawOnKey sets whether the application redraws the screen automatically
// after handling a key event. Disable it when key handlers redraw the affected
// primitives themselves (e.g. via [Application.Draw]). Defaults to true.
func ( *Application) ( bool) {
	.setCallbacks(func( *appCallbacks) {
		.drawOnKey = 
	})
}

// GetDrawOnKey returns whether the application redraws after key events.
func ( *Application) () bool {
	return .getCallbacks().drawOnKey
}

// SetMouseCapture sets a function which captures mouse events (consisting of
// the original tcell mouse event and the semantic mouse action) before they are
// forwarded to the appropriate mouse event handler. This function can then
// choose to forward that event (or a different one) by returning it or stop
// the event processing by returning a nil mouse event.
func ( *Application) ( func( *tcell.EventMouse,  MouseAction) (*tcell.EventMouse, MouseAction)) {
	.setCallbacks(func( *appCallbacks) {
		.mouseCapture = 
	})
}

// GetMouseCapture returns the function installed with SetMouseCapture() or nil
// if no such function has been installed.
func ( *Application) () func( *tcell.EventMouse,  MouseAction) (*tcell.EventMouse, MouseAction) {
	return .getCallbacks().mouseCapture
}

// SetDoubleClickInterval sets the maximum time between clicks to register a
// double click rather than a single click. A standard duration is provided as
// StandardDoubleClick. No interval is set by default, disabling double clicks.
func ( *Application) ( time.Duration) {
	.doubleClickInterval.Store(int64())
}

// SetScreen allows you to provide your own tcell.Screen object. For most
// applications, this is not needed and you should be familiar with
// tcell.Screen when using this function.
//
// This function is typically called before the first call to Run(). Init() need
// not be called on the screen.
func ( *Application) ( tcell.Screen) {
	if  == nil {
		return // Invalid input. Do nothing.
	}

	if .Mach.Is1(ssApp.AppStates.Start) {
		// Run() is already in progress. Exchange the screen on the event loop.
		.Mach.Add1(ssApp.AppStates.CviewScreenReplacing,
			am.Pass(&AScreen{Screen: }))
		return
	}

	// Run() has not been called yet.
	.setScreen()
}

// GetScreen returns the current tcell.Screen of the application. This value is
// only available after calling Init or Run.
func ( *Application) () tcell.Screen {
	return .getScreen()
}

// GetScreenSize returns the size of the application's screen. These values are
// only available after calling Init or Run.
func ( *Application) () (,  int) {
	return int(.width.Load()), int(.height.Load())
}

// Init initializes the application screen. Calling Init before running is not
// required. Its primary use is to populate screen dimensions before running an
// application.
func ( *Application) () error {
	return .init()
}

func ( *Application) () error {
	if  := .getScreen();  != nil {
		// the screen was provided via SetScreen, it's already initialized
		,  := .Size()
		.width.Store(int32())
		.height.Store(int32())
		return nil
	}

	,  := tcell.NewScreen()
	if  != nil {
		return 
	}
	if  = .Init();  != nil {
		return 
	}
	.setScreen()
	,  := .Size()
	.width.Store(int32())
	.height.Store(int32())
	if .enableBracketedPaste.Load() {
		.EnablePaste()
	}
	if .enableMouse.Load() {
		.EnableMouse()
	}
	return nil
}

// EnableBracketedPaste enables bracketed paste mode, which is enabled by default.
func ( *Application) ( bool) {
	if  != .enableBracketedPaste.Load() {
		if  := .getScreen();  != nil {
			if  {
				.EnablePaste()
			} else {
				.DisablePaste()
			}
		}
	}
	.enableBracketedPaste.Store()
}

// EnableMouse enables mouse events.
func ( *Application) ( bool) {
	if  != .enableMouse.Load() {
		if  := .getScreen();  != nil {
			if  {
				.EnableMouse()
			} else {
				.DisableMouse()
			}
		}
	}
	.enableMouse.Store()
}

// Run starts the application and thus the event loop. This function returns
// when Stop() was called.
func ( *Application) () error {
	.runErr = nil
	if .Mach.Add1(ssApp.AppStates.Start, nil) == am.Canceled {
		return .runErr
	}

	// wait until the event loop stopped
	<-.Mach.When1(ssApp.AppStates.CviewStopped, nil)

	return .runErr
}

// fireMouseActions analyzes the provided mouse event, derives mouse actions
// from it and then forwards them to the corresponding primitives.
func ( *Application) ( *tcell.EventMouse) (,  bool) {
	// We want to relay follow-up events to the same target primitive.
	var  Primitive
	 := .getCallbacks().mouseCapture
	 := .getRoot()
	 := time.Duration(.doubleClickInterval.Load())

	// Helper function to fire a mouse action.
	 := func( MouseAction) {
		switch  {
		case MouseLeftDown, MouseMiddleDown, MouseRightDown:
			 = true
		}

		// Intercept event.
		if  != nil {
			,  = (, )
			if  == nil {
				 = true
				return // Don't forward event.
			}
		}

		// Determine the target primitive.
		var ,  Primitive
		if .mouseCapturingPrimitive != nil {
			 = .mouseCapturingPrimitive
			 = .mouseCapturingPrimitive
		} else if  != nil {
			 = 
		} else {
			 = 
		}
		if  != nil {
			if  := .MouseHandler();  != nil {
				var  bool
				,  = (, , func( Primitive) {
					.SetFocus()
				})
				if  {
					 = true
				}
			}
		}
		.mouseCapturingPrimitive = 
	}

	,  := .Position()
	 := .Buttons()
	 :=  != .mouseDownX ||  != .mouseDownY
	 :=  ^ .lastMouseButtons

	if  != .lastMouseX ||  != .lastMouseY {
		(MouseMove)
		.lastMouseX = 
		.lastMouseY = 
	}

	for ,  := range []struct {
		                  tcell.ButtonMask
		, , ,  MouseAction
	}{
		{tcell.ButtonPrimary, MouseLeftDown, MouseLeftUp, MouseLeftClick, MouseLeftDoubleClick},
		{tcell.ButtonMiddle, MouseMiddleDown, MouseMiddleUp, MouseMiddleClick, MouseMiddleDoubleClick},
		{tcell.ButtonSecondary, MouseRightDown, MouseRightUp, MouseRightClick, MouseRightDoubleClick},
	} {
		if &. != 0 {
			if &. != 0 {
				(.)
			} else {
				(.)
				if ! {
					if  == 0 || .lastMouseClick.Add().Before(time.Now()) {
						(.)
						.lastMouseClick = time.Now()
					} else {
						(.)
						.lastMouseClick = time.Time{} // reset
					}
				}
			}
		}
	}

	for ,  := range []struct {
		 tcell.ButtonMask
		 MouseAction
	}{
		{tcell.WheelUp, MouseScrollUp},
		{tcell.WheelDown, MouseScrollDown},
		{tcell.WheelLeft, MouseScrollLeft},
		{tcell.WheelRight, MouseScrollRight}} {
		if &. != 0 {
			(.)
		}
	}

	return , 
}

// Stop stops the application, causing Run() to return.
func ( *Application) () {
	if .Mach.Not1(ssApp.AppStates.Start) &&
		!.Mach.WillBe1(ssApp.AppStates.Start) {
		// Run() has not been called yet
		.finalizeScreen()
		return
	}
	.Mach.Add1(ssApp.AppStates.CviewStopping, nil)
}

func ( *Application) () {
	 := .getScreen()
	if  == nil {
		return
	}

	.setScreen(nil)
	.finiScreen()
}

// finiScreen finalizes a screen in a separate goroutine, as Fini may deadlock.
func ( *Application) ( tcell.Screen) {
	// TODO deadlocks on SSH
	// screen.Fini()

	go func() {
		defer func() {
			if  := recover();  != nil {
				// TODO close of a nil chan `quit`
			}
		}()
		.Fini()
	}()
}

// Suspend temporarily suspends the application by exiting terminal UI mode and
// invoking the provided function "f". When "f" returns, terminal UI mode is
// entered again and the application resumes.
//
// A return value of true indicates that the application was suspended and "f"
// was called. If false is returned, the application was already suspended,
// terminal UI mode was not exited, and "f" was not called.
func ( *Application) ( func()) bool {
	 := make(chan bool, 1)
	 := .Mach.Add1(ssApp.AppStates.CviewSuspending,
		am.Pass(&ASuspend{Fn: , Done: }))
	if  == am.Canceled {
		return false
	}

	return <-
}

// Draw draws the provided primitives on the screen, or when no primitives are
// provided, draws the application's root primitive (i.e. the entire screen).
//
// When one or more primitives are supplied, the Draw functions of the
// primitives are called. Handlers set via BeforeDrawFunc and AfterDrawFunc are
// not called.
//
// When no primitives are provided, the Draw function of the application's root
// primitive is called. This results in drawing the entire screen. Handlers set
// via BeforeDrawFunc and AfterDrawFunc are also called.
func ( *Application) ( ...Primitive) {
	.QueueUpdate(func() {
		if len() == 0 {
			.draw()
			return
		}

		 := .getScreen()
		if  != nil {
			for ,  := range  {
				.Draw()
			}
			.Show()
		}
	})
}

// draw actually does what Draw() promises to do.
func ( *Application) () {
	 := .getScreen()
	 := .getRoot()
	 := .getCallbacks()

	// Maybe we're not ready yet or not anymore.
	if  == nil ||  == nil {
		return
	}

	// Resize if requested.
	if .rootFullscreen.Load() {
		.SetRect(0, 0, int(.width.Load()), int(.height.Load()))
	}

	// Call before handler if there is one.
	if .beforeDraw != nil {
		if .beforeDraw() {
			.Show()
			return
		}
	}

	// Draw all primitives.
	.Draw()

	// Call after handler if there is one.
	if .afterDraw != nil {
		.afterDraw()
	}

	// Sync screen.
	.Show()
}

// SetBeforeDrawFunc installs a callback function which is invoked just before
// the root primitive is drawn during screen updates. If the function returns
// true, drawing will not continue, i.e. the root primitive will not be drawn
// (and an after-draw-handler will not be called).
//
// Note that the screen is not cleared by the application. To clear the screen,
// you may call screen.Clear().
//
// Provide nil to uninstall the callback function.
func ( *Application) ( func( tcell.Screen) bool) {
	.setCallbacks(func( *appCallbacks) {
		.beforeDraw = 
	})
}

// GetBeforeDrawFunc returns the callback function installed with
// SetBeforeDrawFunc() or nil if none has been installed.
func ( *Application) () func( tcell.Screen) bool {
	return .getCallbacks().beforeDraw
}

// SetAfterDrawFunc installs a callback function which is invoked after the root
// primitive was drawn during screen updates.
//
// Provide nil to uninstall the callback function.
func ( *Application) ( func( tcell.Screen)) {
	.setCallbacks(func( *appCallbacks) {
		.afterDraw = 
	})
}

// GetAfterDrawFunc returns the callback function installed with
// SetAfterDrawFunc() or nil if none has been installed.
func ( *Application) () func( tcell.Screen) {
	return .getCallbacks().afterDraw
}

// SetRoot sets the root primitive for this application. If "fullscreen" is set
// to true, the root primitive's position will be changed to fill the screen.
//
// This function must be called at least once or nothing will be displayed when
// the application starts.
//
// It also calls SetFocus() on the primitive and draws the application.
func ( *Application) ( Primitive,  bool) {
	.setRoot()
	.rootFullscreen.Store()
	if  := .getScreen();  != nil {
		.Clear()
	}

	.SetFocus()

	.Draw()
}

// ResizeToFullScreen resizes the given primitive such that it fills the entire
// screen.
func ( *Application) ( Primitive) {
	.SetRect(0, 0, int(.width.Load()), int(.height.Load()))
}

// SetAfterResizeFunc installs a callback function which is invoked when the
// application's window is initialized, and when the application's window size
// changes. After invoking this callback the screen is cleared and the
// application is drawn.
//
// Provide nil to uninstall the callback function.
func ( *Application) ( func( int,  int)) {
	.setCallbacks(func( *appCallbacks) {
		.afterResize = 
	})
}

// GetAfterResizeFunc returns the callback function installed with
// SetAfterResizeFunc() or nil if none has been installed.
func ( *Application) () func( int,  int) {
	return .getCallbacks().afterResize
}

// SetFocus sets the focus on a new primitive. All key events will be redirected
// to that primitive. Callers must ensure that the primitive will handle key
// events.
//
// Blur() will be called on the previously focused primitive. Focus() will be
// called on the new primitive.
func ( *Application) ( Primitive) {
	 := .getCallbacks()

	if .beforeFocus != nil {
		if !.beforeFocus() {
			return
		}
	}

	if  := .getFocus();  != nil {
		.Blur()
	}

	.setFocus()

	if  := .getScreen();  != nil {
		.HideCursor()
	}

	if .afterFocus != nil {
		.afterFocus()
	}

	if  != nil {
		.Focus(func( Primitive) {
			.()
		})
	}
}

// GetFocus returns the primitive which has the current focus. If none has it,
// nil is returned.
func ( *Application) () Primitive {
	return .getFocus()
}

// SetBeforeFocusFunc installs a callback function which is invoked before the
// application's focus changes. Return false to maintain the current focus.
//
// Provide nil to uninstall the callback function.
func ( *Application) ( func( Primitive) bool) {
	.setCallbacks(func( *appCallbacks) {
		.beforeFocus = 
	})
}

// SetAfterFocusFunc installs a callback function which is invoked after the
// application's focus changes.
//
// Provide nil to uninstall the callback function.
func ( *Application) ( func( Primitive)) {
	.setCallbacks(func( *appCallbacks) {
		.afterFocus = 
	})
}

// QueueUpdate queues a function to be executed as part of the event loop.
//
// Note that Draw() is not implicitly called after the execution of f as that
// may not be desirable. You can call Draw() from f if the screen should be
// refreshed after each update. Alternatively, use QueueUpdateDraw() to follow
// up with an immediate refresh of the screen.
func ( *Application) ( func()) {
	.updates <- 
}

// QueueUpdateDraw works like QueueUpdate() except, when one or more primitives
// are provided, the primitives are drawn after the provided function returns.
// When no primitives are provided, the entire screen is drawn after the
// provided function returns.
func ( *Application) ( func(),  ...Primitive) {
	.QueueUpdate(func() {
		()

		if len() == 0 {
			.draw()
			return
		}
		 := .getScreen()
		if  != nil {
			for ,  := range  {
				.Draw()
			}
			.Show()
		}
	})
}

// QueueEvent sends an event to the Application event loop.
//
// It is not recommended for event to be nil.
func ( *Application) ( tcell.Event) {
	.events <- 
}

// RingBell sends a bell code to the terminal.
func ( *Application) () {
	.QueueUpdate(func() {
		fmt.Print(string(byte(7)))
	})
}

// ScreenText extracts the current screen buffer as plain text.
func ( *Application) () string {
	return TextFromScreen(.getScreen())
}

func ( tcell.Screen) string {
	if  == nil {
		return ""
	}

	,  := .Size()
	var  strings.Builder

	// Pre-allocate memory based on screen size (width + 1 for newline) * height
	.Grow(( + 1) * )

	for  := 0;  < ; ++ {
		for  := 0;  < ; ++ {
			// GetContent returns the rune, combining runes, style, and cell width.
			// We ignore the style completely, which strips all colors/formatting.
			, ,  := .Get(, )
			.Write([]byte())

			// If a character spans multiple cells (e.g., CJK characters or emojis),
			// skip the next cell(s) to avoid duplicating characters or reading placeholders.
			if  > 1 {
				 +=  - 1
			}
		}
		// Append a newline at the end of each row
		.WriteRune('\n')
	}

	return .String()
}

// ///// ///// /////

// ///// EVENT LOOP

// ///// ///// /////

// handle processes a single tcell event. It must be called on the machine's
// queue, i.e. from a handler or from [am.Machine.Eval].
func ( *Application) ( interface{}) {
	 := .getFocus()
	 := .getCallbacks()
	 := .getScreen()

	switch event := .(type) {
	case *tcell.EventKey:
		// Intercept keys.
		if .inputCapture != nil {
			 = .inputCapture()
			if  == nil {
				if .drawOnKey {
					.draw()
				}
				return // Don't forward event.
			}
		}

		// Ctrl-C closes the application.
		if .Key() == tcell.KeyCtrlC {
			.Stop()
			return
		}

		// Pass other key events to the currently focused primitive.
		if  != nil {
			if  := .InputHandler();  != nil {
				(, func( Primitive) {
					.SetFocus()
				})
				if .drawOnKey {
					.draw()
				}
			}
		}
	case *tcell.EventResize:
		// Throttle resize events.
		if time.Since(.lastResize) < resizeEventThrottle {
			// Stop timer
			if .throttleResize != nil && !.throttleResize.Stop() {
				select {
				case <-.throttleResize.C:
				default:
				}
			}

			 :=  // Capture

			// Start timer
			.throttleResize = time.AfterFunc(resizeEventThrottle, func() {
				.events <- 
			})

			return
		}

		.lastResize = time.Now()

		if  == nil {
			return
		}

		.Clear()
		,  := .Size()
		.width.Store(int32())
		.height.Store(int32())

		// Call afterResize handler if there is one.
		if .afterResize != nil {
			.afterResize(, )
		}

		.draw()
	case *tcell.EventMouse:
		,  := .fireMouseActions()
		if  {
			.draw()
		}
		.lastMouseButtons = .Buttons()
		if  {
			.mouseDownX, .mouseDownY = .Position()
		}
	}
}

// startPolling starts a screen event loop for the passed screen. It exits when
// the screen gets replaced or finalized.
func ( *Application) ( tcell.Screen) {
	 := .Mach.NewStateCtx(ssApp.AppStates.Start)

	.Mach.Go(, func() {
		for {
			 := .PollEvent()
			if .getScreen() !=  {
				// screen replaced or finalized
				return
			}
			if  == nil {
				.Mach.Add1(ssApp.AppStates.CviewStopping, nil)
				return
			}

			 := .Mach.Eval("pollEvent", func() {
				defer .HandlePanic()
				.handle()
			}, )
			if ! && .Err() != nil {
				return // expired
			}
		}
	})
}

// updatesLoop consumes queued updates and executes them on the machine's queue.
func ( *Application) ( context.Context) {
	for {
		select {
		case <-.Done():
			return
		case  := <-.updates:
			 := .Mach.Eval("queueUpdate", func() {
				defer .HandlePanic()
				()
			}, )
			if ! && .Err() != nil {
				return // expired
			}
		}
	}
}

// eventsLoop consumes queued tcell events and executes them on the machine's
// queue.
func ( *Application) ( context.Context) {
	for {
		select {
		case <-.Done():
			return
		case  := <-.events:
			 := .Mach.Eval("queueEvent", func() {
				defer .HandlePanic()
				.handle()
			}, )
			if ! && .Err() != nil {
				return // expired
			}
		}
	}
}

// ///// ///// /////

// ///// FIELDS

// ///// ///// /////

func ( *Application) () tcell.Screen {
	 := .screen.Load()
	if  == nil {
		return nil
	}
	return *
}

func ( *Application) ( tcell.Screen) {
	if  == nil {
		.screen.Store(nil)
		return
	}
	.screen.Store(&)
}

func ( *Application) () Primitive {
	 := .focus.Load()
	if  == nil {
		return nil
	}
	return .p
}

func ( *Application) ( Primitive) {
	if  == nil {
		.focus.Store(nil)
		return
	}
	.focus.Store(&primitiveRef{p: })
}

func ( *Application) () Primitive {
	 := .root.Load()
	if  == nil {
		return nil
	}
	return .p
}

func ( *Application) ( Primitive) {
	if  == nil {
		.root.Store(nil)
		return
	}
	.root.Store(&primitiveRef{p: })
}

func ( *Application) () *appCallbacks {
	if  := .callbacks.Load();  != nil {
		return 
	}
	return &appCallbacks{drawOnKey: true}
}

func ( *Application) ( func( *appCallbacks)) {
	 := *.getCallbacks()
	(&)
	.callbacks.Store(&)
}

// ///// ///// /////

// ///// HANDLERS

// ///// ///// /////

// appHandlers contains the event loop handlers of the Application state
// machine.
type appHandlers struct {
	*am.ExceptionHandler

	app *Application
}

var _ = ssApp.AppStates.Start
var _ = ssApp.AppStates.CviewStopped

func ( *appHandlers) ( *am.Event) {
	 := .app

	// initialize the screen
	if  := .init();  != nil {
		.runErr = 
		.Mach.EvAddErrState(, ssApp.AppStates.CviewErrScreen, , nil)
		.Mach.EvAdd1(, ssApp.AppStates.CviewStopping, nil)
		return
	}

	// the queue consumers live as long as the machine does
	 := .Mach.Context()
	.Mach.Go(, func() {
		.updatesLoop()
	})
	.Mach.Go(, func() {
		.eventsLoop()
	})

	.Mach.EvAdd1(, ssApp.AppStates.CviewScreenInitialized, nil)
}

func ( *appHandlers) ( *am.Event) {
	 := .app

	// draw the screen for the first time
	.draw()

	// start the input event loop
	.startPolling(.getScreen())

	.Mach.EvAdd1(, ssApp.AppStates.CviewRunning, nil)
}

func ( *appHandlers) ( *am.Event) {
	 := .app
	 := am.ParseArgs[AScreen](.Args)
	if  == nil || .Screen == nil {
		return
	}

	if  := .getScreen();  != nil {
		.finiScreen()
	}
	.setScreen(.Screen)
	if  := .Screen.Init();  != nil {
		.Mach.EvAddErrState(, ssApp.AppStates.CviewErrScreen, , nil)
		return
	}
	if .enableBracketedPaste.Load() {
		.Screen.EnablePaste()
	}
	if .enableMouse.Load() {
		.Screen.EnableMouse()
	}

	// start a new input event loop
	.startPolling(.Screen)

	.draw()
}

func ( *appHandlers) ( *am.Event) {
	 := .app
	 := am.ParseArgs[ASuspend](.Args)
	if  == nil {
		return
	}

	 := .getScreen()
	if  == nil {
		.Done <- false
		return
	}
	if  := .Suspend();  != nil {
		.Done <- false
		.Mach.EvAddErrState(, ssApp.AppStates.CviewErrScreen, , nil)
		return
	}

	// resume once the suspended func returns
	 := .Mach.NewStateCtx(ssApp.AppStates.Start, )
	.Mach.Go(, func() {
		.Fn()
		.Mach.Add1(ssApp.AppStates.CviewResuming, am.Pass())
	})
}

func ( *appHandlers) ( *am.Event) {
	 := .app
	 := am.ParseArgs[ASuspend](.Args)
	if  == nil {
		return
	}

	 := .getScreen()
	if  == nil {
		.Done <- true
		return
	}
	if  := .Resume();  != nil {
		.Mach.EvAddErrState(, ssApp.AppStates.CviewErrScreen, , nil)
	}
	.Done <- true
}

func ( *appHandlers) ( *am.Event) {
	 := .app

	.finalizeScreen()

	.Mach.EvAdd1(, ssApp.AppStates.CviewStopped, nil)
}