Kaynağa Gözat

Merge branch 'v2_develop' into v2_release

Tig 3 ay önce
ebeveyn
işleme
94ab1792af

+ 1 - 0
Terminal.Gui/App/Application.cs

@@ -16,6 +16,7 @@ global using Terminal.Gui.Drawing;
 global using Terminal.Gui.Text;
 global using Terminal.Gui.Resources;
 global using Terminal.Gui.FileServices;
+using System.Diagnostics;
 using System.Globalization;
 using System.Reflection;
 using System.Resources;

+ 1 - 1
Terminal.Gui/Views/FileDialogs/FileSystemColorProvider.cs → Terminal.Gui/FileServices/FileSystemColorProvider.cs

@@ -3,7 +3,7 @@
 using System.Diagnostics.CodeAnalysis;
 using System.IO.Abstractions;
 
-namespace Terminal.Gui.Views;
+namespace Terminal.Gui.FileServices;
 
 /// <summary>Provides a way to get the color of a file or directory.</summary>
 public class FileSystemColorProvider

+ 1 - 1
Terminal.Gui/Views/FileDialogs/FileSystemIconProvider.cs → Terminal.Gui/FileServices/FileSystemIconProvider.cs

@@ -1,6 +1,6 @@
 using System.IO.Abstractions;
 
-namespace Terminal.Gui.Views;
+namespace Terminal.Gui.FileServices;
 
 /// <summary>Determines which symbol to use to represent files and directories.</summary>
 public class FileSystemIconProvider

+ 1 - 1
Terminal.Gui/FileServices/AllowedType.cs → Terminal.Gui/Views/FileDialogs/AllowedType.cs

@@ -1,5 +1,5 @@
 
-namespace Terminal.Gui.FileServices;
+namespace Terminal.Gui.Views;
 
 /// <summary>Interface for <see cref="FileDialog"/> restrictions on which file type(s) the user is allowed to select/enter.</summary>
 public interface IAllowedType

+ 1 - 1
Terminal.Gui/FileServices/DefaultFileOperations.cs → Terminal.Gui/Views/FileDialogs/DefaultFileOperations.cs

@@ -1,6 +1,6 @@
 using System.IO.Abstractions;
 
-namespace Terminal.Gui.FileServices;
+namespace Terminal.Gui.Views;
 
 /// <summary>Default file operation handlers using modal dialogs.</summary>
 public class DefaultFileOperations : IFileOperations

+ 1 - 1
Terminal.Gui/FileServices/FileDialogHistory.cs → Terminal.Gui/Views/FileDialogs/FileDialogHistory.cs

@@ -1,6 +1,6 @@
 using System.IO.Abstractions;
 
-namespace Terminal.Gui.FileServices;
+namespace Terminal.Gui.Views;
 
 internal class FileDialogHistory
 {

+ 1 - 1
Terminal.Gui/FileServices/FileDialogState.cs → Terminal.Gui/Views/FileDialogs/FileDialogState.cs

@@ -1,6 +1,6 @@
 using System.IO.Abstractions;
 
-namespace Terminal.Gui.FileServices;
+namespace Terminal.Gui.Views;
 
 internal class FileDialogState
 {

+ 1 - 1
Terminal.Gui/FileServices/FileDialogStyle.cs → Terminal.Gui/Views/FileDialogs/FileDialogStyle.cs

@@ -3,7 +3,7 @@ using System.Globalization;
 using System.IO.Abstractions;
 using static System.Environment;
 
-namespace Terminal.Gui.FileServices;
+namespace Terminal.Gui.Views;
 
 /// <summary>Stores style settings for <see cref="FileDialog"/>.</summary>
 public class FileDialogStyle

+ 1 - 1
Terminal.Gui/FileServices/FilesSelectedEventArgs.cs → Terminal.Gui/Views/FileDialogs/FilesSelectedEventArgs.cs

@@ -1,5 +1,5 @@
 
-namespace Terminal.Gui.FileServices;
+namespace Terminal.Gui.Views;
 
 /// <summary>Event args for the <see cref="FileDialog.FilesSelected"/> event</summary>
 public class FilesSelectedEventArgs : EventArgs

+ 26 - 0
docfx/apispec/namespace-app.md

@@ -0,0 +1,26 @@
+---
+uid: Terminal.Gui.App
+summary: The `App` namespace holds @Terminal.Gui.Application and associated classes.
+---
+
[email protected] provides the main entry point and core application logic for Terminal.Gui applications. This static singleton class is responsible for initializing and shutting down the Terminal.Gui environment, managing the main event loop, handling input and output, and providing access to global application state.
+
+Typical usage involves calling `Application.Init()` to initialize the application, creating and running a `Window`, and then calling `Application.Shutdown()` to clean up resources. The class also provides methods for culture support, idle handlers, and rendering the application state as a string.
+
+## Example Usage
+
+```csharp
+Application.Init();
+var win = new Window()
+{
+    Title = $"Example App ({Application.QuitKey} to quit)"
+};
+Application.Run(win);
+win.Dispose();
+Application.Shutdown();
+```
+
+## See Also
+
+- [Logging](~/docs/logging.md)
+- [Multitasking](~/docs/multitasking.md)

+ 30 - 0
docfx/apispec/namespace-configuration.md

@@ -0,0 +1,30 @@
+---
+uid: Terminal.Gui.Configuration
+summary: The `Configuration` namespace provides comprehensive configuration management for Terminal.Gui applications.
+---
+
[email protected] provides a robust system for managing application settings, themes, and runtime configuration. This namespace includes the configuration manager, property attributes, and scoping mechanisms that allow applications to persist and load settings from various sources.
+
+The configuration system supports multiple scopes (Settings, Themes, AppSettings) and sources (user directory, application directory, etc.), enabling flexible deployment and customization scenarios. It also provides theme inheritance and hot-reloading capabilities for dynamic configuration updates.
+
+## Key Components
+
+- **ConfigurationManager**: Central system for loading, applying, and managing configuration
+- **ConfigProperty**: Attribute for marking properties as configurable
+- **Scopes**: Settings, Theme, and AppSettings contexts
+- **Sources**: Multiple storage locations for configuration persistence
+
+## Example Usage
+
+```csharp
+// Mark a property as configurable
+[ConfigProperty]
+public static bool MyFeatureEnabled { get; set; } = true;
+
+// Load configuration from default sources
+ConfigurationManager.Enable(ConfigLocations.All);
+```
+
+## Deep Dive
+
+- [Configuration Management Deep Dive](~/docs/config.md) - Comprehensive configuration system documentation

+ 28 - 0
docfx/apispec/namespace-drawing.md

@@ -0,0 +1,28 @@
+---
+uid: Terminal.Gui.Drawing
+summary: The `Drawing` namespace provides comprehensive text rendering, color management, and visual styling for Terminal.Gui applications.
+---
+
[email protected] contains the core drawing primitives and visual styling system for Terminal.Gui. This namespace handles everything from basic color and attribute management to complex line drawing and text formatting capabilities.
+
+The drawing system supports both simple and advanced scenarios, including Unicode text rendering, automatic line joining for complex shapes, thickness-based adornments, and comprehensive color schemes with semantic visual roles.
+
+## Key Components
+
+- **Attribute**: Defines visual styling (foreground, background, text style)
+- **Color**: Terminal color support including TrueColor and named colors
+- **Scheme**: Maps semantic visual roles to concrete attributes
+- **LineCanvas**: Advanced line drawing with automatic glyph joining
+- **Thickness**: Framework for defining border and adornment widths
+- **Glyphs**: Standard set of drawing characters for UI elements
+
+## Example Usage 
+
+```csharp
+// Get the attribute for a Focused view
+Attribute? focusedAttribute = GetAttributeForRole(VisualRole.Focused);
+
+// Move to 5,5 and output a string with the focused attribute
+Move (5,5);
+AddStr("Hello");
+```

+ 30 - 0
docfx/apispec/namespace-drivers.md

@@ -0,0 +1,30 @@
+---
+uid: Terminal.Gui.Drivers
+summary: The `Drivers` namespace provides cross-platform terminal abstraction and console driver implementations.
+---
+
[email protected] contains the platform abstraction layer that enables Terminal.Gui to run consistently across Windows, macOS, and Linux/Unix systems. This namespace includes console drivers, terminal capability detection, and platform-specific optimizations.
+
+The driver system handles low-level terminal operations including cursor management, color support detection, input processing, and screen buffer management. It provides a unified API while accommodating the unique characteristics of different terminal environments.
+
+## Key Components
+
+- **ConsoleDriver**: Base class for platform-specific terminal implementations
+- **WindowsDriver**: Windows Console API implementation
+- **CursesDriver**: Unix/Linux ncurses-based implementation
+- **NetDriver**: Cross-platform .NET Console implementation
+
+## Example Usage
+
+```csharp
+// Driver selection is typically automatic
+Application.Init();
+
+// Access current driver capabilities
+var driver = Application.Driver;
+bool supportsColors = driver.SupportsTrueColor;
+```
+
+## Deep Dive
+
+See the [Cross-Platform Driver Model](~/docs/drivers.md) for comprehensive details. 

+ 7 - 0
docfx/apispec/namespace-fileservices.md

@@ -0,0 +1,7 @@
+---
+uid: Terminal.Gui.FileServices
+summary: The `FileServices` namespace provides low-level file system operations.
+---
+
+See @Terminal.Gui.Views.OpenDialog and @Terminal.Gui.FileServices.SaveDialog for high-level user interface components for file selection and management.
+

+ 42 - 0
docfx/apispec/namespace-input.md

@@ -0,0 +1,42 @@
+---
+uid: Terminal.Gui.Input
+summary: The `Input` namespace provides comprehensive input handling for keyboard, mouse, and command processing.
+---
+
[email protected] contains the input processing system for Terminal.Gui applications, including keyboard event handling, mouse interaction, and the command execution framework. This namespace defines the core input primitives and event structures used throughout the framework.
+
+The input system provides both low-level input events and high-level command abstractions, enabling applications to handle everything from basic key presses to complex gesture recognition and command routing.
+
+## Key Components
+
+- **Key**: Represents keyboard input with modifier support
+- **MouseEventArgs**: Comprehensive mouse event information
+- **Command**: Enumeration of standard application commands
+- **KeyBinding**: Associates keys with commands
+- **MouseBinding**: Associates mouse events with commands
+
+## Example Usage
+
+```csharp
+// First, add command handlers
+AddCommand(Command.Up, commandContext => Move(commandContext, -16));
+AddCommand(Command.Down, commandContext => Move(commandContext, 16));
+AddCommand(Command.Accept, HandleAcceptCommand);
+
+// Then bind keys to commands
+KeyBindings.Add(Key.CursorUp, Command.Up);
+KeyBindings.Add(Key.CursorDown, Command.Down);
+KeyBindings.Add(Key.Enter, Command.Accept);
+
+// Then bind mouse events to commands
+MouseBindings.Add(MouseFlags.Button1DoubleClicked, Command.Accept);
+MouseBindings.Add(MouseFlags.WheeledDown, Command.ScrollDown);
+MouseBindings.ReplaceCommands(MouseFlags.Button3Clicked, Command.Context);
+```
+
+## Deep Dives
+
+- [Keyboard Input](~/docs/keyboard.md) - Comprehensive keyboard input handling
+- [Mouse Input](~/docs/mouse.md) - Comprehensive mouse input handling
+- [Commands](~/docs/command.md) - Command execution framework details
+

+ 35 - 0
docfx/apispec/namespace-text.md

@@ -0,0 +1,35 @@
+---
+uid: Terminal.Gui.Text
+summary: The `Text` namespace provides advanced text processing, formatting, and Unicode handling capabilities.
+---
+
[email protected] contains the text processing and formatting system for Terminal.Gui applications. This namespace handles Unicode text rendering, text measurement, formatting with alignment and wrapping, and hot key processing for accessible user interfaces.
+
+The text system supports complex text scenarios including bidirectional text, combining characters, wide characters, and sophisticated formatting options with both horizontal and vertical alignment capabilities.
+
+## Key Components
+
+- **TextFormatter**: Advanced text formatting with alignment and wrapping
+- **Rune**: Unicode character representation and processing
+- **TextDirection**: Support for left-to-right and right-to-left text
+- **TextAlignment**: Horizontal and vertical text positioning
+
+## Text Processing Features
+
+- **Unicode Support**: Full Unicode character set including combining characters
+- **Text Formatting**: Word wrapping, alignment, and hot key processing
+- **Accessibility**: Hot key support for keyboard navigation
+
+## Example Usage 
+
+```csharp
+// Create a text formatter with default settings
+var formatter = new TextFormatter();
+
+// Format a string with alignment
+var formatted = formatter.Format("Hello, World!", 10, 10, TextAlignment.Center);
+```
+
+## Deep Dive
+
+- [Text Formatting](~/docs/drawing.md) - Comprehensive text formatting documentation

+ 55 - 0
docfx/apispec/namespace-viewbase.md

@@ -0,0 +1,55 @@
+---
+uid: Terminal.Gui.ViewBase
+summary: The `ViewBase` namespace contains the foundational view system and core UI building blocks.
+---
+
[email protected] provides the fundamental view architecture that forms the foundation of all Terminal.Gui user interface elements. This namespace contains the base View class, adornment system, layout primitives, and core view behaviors that enable the rich UI capabilities of Terminal.Gui.
+
+The View system implements the complete view lifecycle, coordinate systems, event handling, focus management, and the innovative adornment system that separates content from visual decoration.
+
+## Key Components
+
+- @Terminal.Gui.ViewBase.View - Base class for all UI elements with complete lifecycle management
+- @Terminal.Gui.ViewBase.Adornment - Visual decorations (Margin, Border, Padding) outside content area
+- @Terminal.Gui.ViewBase.View.Viewport - Scrollable window into view content with built-in scrolling support
+- @Terminal.Gui.ViewBase.ViewArrangement - Flags controlling user interaction (Movable, Resizable, etc.)
+- @Terminal.Gui.ViewBase.Pos and @Terminal.Gui.ViewBase.Dim - Flexible positioning and sizing system with relative and absolute options
+
+## View Architecture
+
+- **Hierarchy**: SuperView/SubView relationships with automatic lifecycle management
+- **Coordinate Systems**: Multiple coordinate spaces (Frame, Viewport, Content, Screen)
+- **Layout Engine**: Automatic positioning and sizing with constraint-based layout
+- **Event System**: Comprehensive event handling with cancellation support
+- **Focus Management**: Built-in keyboard navigation and focus chain management
+
+## Example Usage
+
+```csharp
+// Create a view with a Border adornment and Title
+var view = new View()
+{
+    X = Pos.Center(),
+    Y = Pos.Center(),
+    Width = Dim.Percent(50),
+    Height = Dim.Percent(30),
+    Title = "My View",
+    BorderStyle = LineStyle.Rounded
+};
+
+// Enable user arrangement
+view.Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable;
+
+// Add to SuperView 
+superView.Add(view);
+```
+
+## See Also
+
+- [View Deep Dive](~/docs/View.md) - Comprehensive view system documentation
+- [List of Views](~/docs/views.md) - List of all built-in views
+- [Layout Deep Dive](~/docs/layout.md) - Layout system and coordinate spaces
+- [Arrangement Deep Dive](~/docs/arrangement.md) - User interaction and view arrangement
+- [Navigation Deep Dive](~/docs/navigation.md) - Focus management and keyboard navigation
+- [Scrolling Deep Dive](~/docs/scrolling.md) - Built-in scrolling capabilities
+- [Events Deep Dive](~/docs/events.md) - Event handling patterns 

+ 11 - 0
docfx/apispec/namespace-views.md

@@ -0,0 +1,11 @@
+---
+uid: Terminal.Gui.Views
+summary: The `Views` namespace contains the complete collection of built-in UI controls and widgets.
+---
+
[email protected] provides a comprehensive set of pre-built user interface controls, derived from @Terminal.Gui.ViewBase.View, that cover common application needs. From simple labels and buttons to complex data grids and tree views, this namespace contains production-ready controls with consistent behavior, theming, and accessibility support.
+
+All Views in this namespace are built on the @Terminal.Gui.ViewBase.View foundation and inherit the complete feature set including adornments, scrolling, focus management, and user arrangement capabilities.
+
+For a complete list of all views with examples, see the [List of Views](~/docs/views.md) page.
+

+ 3 - 1
docfx/docfx.json

@@ -42,7 +42,8 @@
         ],
         "exclude": [
           "_site/**",
-          "includes/**"
+          "includes/**",
+          "apispec/**"
         ]
       }
     ],
@@ -54,6 +55,7 @@
         ]
       }
     ],
+    "overwrite": "apispec/*.md",
     "globalMetadata": {
       "_appName": "Terminal.Gui v2",
       "_appTitle": "Terminal.Gui v2",

+ 2 - 2
docfx/docs/index.md

@@ -26,7 +26,7 @@ Welcome to the Terminal.Gui documentation! This comprehensive guide covers every
 - [Layout System](~/docs/layout.md) - View positioning, sizing, and arrangement
 - [Lexicon & Taxonomy](~/docs/lexicon.md) - Terminology and concepts used throughout Terminal.Gui
 - [Logging & Metrics](~/docs/logging.md) - Comprehensive logging and performance monitoring
-- [Main Loop & Event Processing](~/docs/mainloop.md) - Application lifecycle and event dispatching
+- [Multitasking](~/docs/multitasking.md) - Application lifecycle and event dispatching
 - [Mouse Input](~/docs/mouse.md) - Mouse event handling and interaction patterns
 - [Navigation](~/docs/navigation.md) - Focus management, keyboard navigation, and accessibility
 - [Popovers](~/docs/Popovers.md) - Drawing outside viewport boundaries for menus and popups
@@ -34,5 +34,5 @@ Welcome to the Terminal.Gui documentation! This comprehensive guide covers every
 
 ## API Reference
 
-For detailed API documentation, see the [API Reference](~/api).
+For detailed API documentation, see the [API Reference](~/api/Terminal.Gui.App.yml).
 

+ 1 - 1
docfx/docs/keyboard.md

@@ -91,7 +91,7 @@ The Command can be invoked even if the `View` that defines them is not focused o
 
 ### **Key Events**
 
-Keyboard events are retrieved from [Console Drivers](drivers.md) each iteration of the [Application](~/api/Terminal.Gui.App.Application.yml) [Main Loop](mainloop.md). The console driver raises the @Terminal.Gui.Drivers.ConsoleDriver.KeyDown and @Terminal.Gui.Drivers.ConsoleDriver.KeyUp events which invoke @Terminal.Gui.App.Application.RaiseKeyDownEvent* and @Terminal.Gui.App.Application.RaiseKeyUpEvent(Terminal.Gui.Input.Key) respectively.
+Keyboard events are retrieved from [Console Drivers](drivers.md) each iteration of the [Application](~/api/Terminal.Gui.App.Application.yml) [Main Loop](multitasking.md). The console driver raises the @Terminal.Gui.Drivers.ConsoleDriver.KeyDown and @Terminal.Gui.Drivers.ConsoleDriver.KeyUp events which invoke @Terminal.Gui.App.Application.RaiseKeyDownEvent* and @Terminal.Gui.App.Application.RaiseKeyUpEvent(Terminal.Gui.Input.Key) respectively.
 
 > [!NOTE]
 > Not all drivers/platforms support sensing distinct KeyUp events. These drivers will simulate KeyUp events by raising KeyUp after KeyDown.

+ 0 - 102
docfx/docs/mainloop.md

@@ -1,102 +0,0 @@
-# Event Processing and the Application Main Loop
-
-_See also [Cross-platform Driver Model](drivers.md)_
-
-The method `Application.Run` will wait for events from either the keyboard or mouse and route those events to the proper view.
-
-The job of waiting for events and dispatching them in the `Application` is implemented by an instance of the Main Loop.
-
-Main loops are a common idiom in many user interface toolkits so many of the concepts will be familiar to you if you have used other toolkits before.
-
-This class provides the following capabilities:
-
-* Keyboard and mouse processing
-* .NET Async support
-* Timers processing
-* Idle processing handlers
-* Invoking UI code from a background thread
-
-The `MainLoop` property in the the [`Application`](~/api/Terminal.Gui.App.Application.yml)
-provides access to these functions.
-
-When `Application.Run (Toplevel)` is called, the application will prepare the current
-[`Toplevel`](~/api/Terminal.Gui.Views.Toplevel.yml) instance by redrawing the screen appropriately and then starting the main loop.
-
-Configure the Mainloop before calling Application.Run, or  configure the MainLoop in response to events during the execution.
-
-Keyboard input is dispatched by the Application class to the
-current TopLevel window. This is covered in more detail in the
-[Keyboard Event Processing](keyboard.md) document.
-
-Async Execution
----------------
-
-On startup, the `Application` class configures the .NET Asynchronous
-machinery to allow the use of the `await` keyword to run tasks in the
-background and have the execution of those tasks resume on the context
-of the main thread running the main loop.
-
-Timers Processing
------------------
-
-Timers can be set to be executed at specified intervals by calling the [`AddTimeout`]() method, like this:
-
-```csharp
-void UpdateTimer ()
-{
-	time.Text = DateTime.Now.ToString ();
-}
-
-var token = Application.MainLoop.AddTimeout (TimeSpan.FromSeconds (20), UpdateTimer);
-```
-
-The return value from AddTimeout is a token value that can be used to cancel the timer:
-
-```csharup
-Application.MainLoop.RemoveTimeout (token);
-```
-
-Idle Handlers
--------------
-
-[`AddIdle`]() registers a function to be executed when the application is idling and there are no events to process. Idle functions should return `true` if they should be invoked again,
-and `false` if the idle invocations should stop.
-
-Like the timer APIs, the return value is a token that can be used to cancel the scheduled idle function from being executed.
-
-Threading
----------
-
-Like most UI toolkits, Terminal.Gui should be assumed to not be thread-safe. Avoid calling methods in the UI classes from a background thread as there is no guarantee they will not corrupt the state of the UI application. 
-
-Instead, use C# async APIs (e.g. `await` and `System.Threading.Tasks.Task`). Only invoke
-APIs in Terminal.Gui from the main thread by using the `Application.Invoke`
-method to pass an `Action` that will be queued for execution on the main thread at an appropriate time.
-
-For example, the following shows how to properly update a label from a background thread:
-
-```cs
-void BackgroundThreadUpdateProgress ()
-{
-	Application.Invoke (() => {
-		progress.Text = $"Progress: {bytesDownloaded/totalBytes}";
-        });
-}
-```
-
-Low-Level Application APIs
-----------------------------------------
-
-It is possible to run the main loop in a cooperative way: Use the lower-level APIs in `Application`: the `Begin` method to prepare a toplevel for execution, followed by calls
-to `MainLoop.EventsPending` to determine whether the events must be processed, and in that case, calling `RunLoop` method and finally completing the process  by calling `End`.
-
-The method `Run` is implemented like this:
-
-```cs
-void Run (Toplevel top)
-{
-	var runToken = Begin (view);
-	RunLoop (runToken);
-	End (runToken);
-}
-```

+ 289 - 0
docfx/docs/multitasking.md

@@ -0,0 +1,289 @@
+# Multitasking and Background Operations
+
+_See also [Cross-platform Driver Model](drivers.md)_
+
+Terminal.Gui applications run on a single main thread with an event loop that processes keyboard, mouse, and system events. This document explains how to properly handle background work, timers, and asynchronous operations while keeping your UI responsive.
+
+## Threading Model
+
+Terminal.Gui follows the standard UI toolkit pattern where **all UI operations must happen on the main thread**. Attempting to modify views or their properties from background threads will result in undefined behavior and potential crashes.
+
+### The Golden Rule
+> Always use `Application.Invoke()` to update the UI from background threads.
+
+## Background Operations
+
+### Using async/await (Recommended)
+
+The preferred way to handle background work is using C#'s async/await pattern:
+
+```csharp
+private async void LoadDataButton_Clicked()
+{
+    loadButton.Enabled = false;
+    statusLabel.Text = "Loading...";
+    
+    try
+    {
+        // This runs on a background thread
+        var data = await FetchDataFromApiAsync();
+        
+        // This automatically returns to the main thread
+        dataView.LoadData(data);
+        statusLabel.Text = $"Loaded {data.Count} items";
+    }
+    catch (Exception ex)
+    {
+        statusLabel.Text = $"Error: {ex.Message}";
+    }
+    finally
+    {
+        loadButton.Enabled = true;
+    }
+}
+```
+
+### Using Application.Invoke()
+
+When working with traditional threading APIs or when async/await isn't suitable:
+
+```csharp
+private void StartBackgroundWork()
+{
+    Task.Run(() =>
+    {
+        // This code runs on a background thread
+        for (int i = 0; i <= 100; i++)
+        {
+            Thread.Sleep(50); // Simulate work
+            
+            // Marshal back to main thread for UI updates
+            Application.Invoke(() =>
+            {
+                progressBar.Fraction = i / 100f;
+                statusLabel.Text = $"Progress: {i}%";
+            });
+        }
+        
+        Application.Invoke(() =>
+        {
+            statusLabel.Text = "Complete!";
+        });
+    });
+}
+```
+
+## Timers
+
+Use timers for periodic updates like clocks, status refreshes, or animations:
+
+```csharp
+public class ClockView : View
+{
+    private Label timeLabel;
+    private object timerToken;
+    
+    public ClockView()
+    {
+        timeLabel = new Label { Text = DateTime.Now.ToString("HH:mm:ss") };
+        Add(timeLabel);
+        
+        // Update every second
+        timerToken = Application.MainLoop.AddTimeout(
+            TimeSpan.FromSeconds(1), 
+            UpdateTime
+        );
+    }
+    
+    private bool UpdateTime()
+    {
+        timeLabel.Text = DateTime.Now.ToString("HH:mm:ss");
+        return true; // Continue timer
+    }
+    
+    protected override void Dispose(bool disposing)
+    {
+        if (disposing && timerToken != null)
+        {
+            Application.MainLoop.RemoveTimeout(timerToken);
+        }
+        base.Dispose(disposing);
+    }
+}
+```
+
+### Timer Best Practices
+
+- **Always remove timers** when disposing views to prevent memory leaks
+- **Return `true`** from timer callbacks to continue, `false` to stop
+- **Keep timer callbacks fast** - they run on the main thread
+- **Use appropriate intervals** - too frequent updates can impact performance
+
+## Idle Processing
+
+Idle handlers run when the application has no events to process, useful for background maintenance:
+
+```csharp
+public class AutoSaveView : View
+{
+    private object idleToken;
+    private DateTime lastSave = DateTime.Now;
+    
+    public AutoSaveView()
+    {
+        idleToken = Application.MainLoop.AddIdle(CheckAutoSave);
+    }
+    
+    private bool CheckAutoSave()
+    {
+        if (DateTime.Now - lastSave > TimeSpan.FromMinutes(5))
+        {
+            if (HasUnsavedChanges())
+            {
+                SaveDocument();
+                lastSave = DateTime.Now;
+            }
+        }
+        return true; // Continue idle processing
+    }
+    
+    protected override void Dispose(bool disposing)
+    {
+        if (disposing && idleToken != null)
+        {
+            Application.MainLoop.RemoveIdle(idleToken);
+        }
+        base.Dispose(disposing);
+    }
+}
+```
+
+## Common Patterns
+
+### Progress Reporting
+
+```csharp
+private async void ProcessFiles()
+{
+    var files = Directory.GetFiles(folderPath);
+    progressBar.Fraction = 0;
+    
+    for (int i = 0; i < files.Length; i++)
+    {
+        await ProcessFileAsync(files[i]);
+        
+        // Update progress on main thread
+        progressBar.Fraction = (float)(i + 1) / files.Length;
+        statusLabel.Text = $"Processed {i + 1} of {files.Length} files";
+        
+        // Allow UI to update
+        await Task.Yield();
+    }
+}
+```
+
+### Cancellation Support
+
+```csharp
+private CancellationTokenSource cancellationSource;
+
+private async void StartLongOperation()
+{
+    cancellationSource = new CancellationTokenSource();
+    cancelButton.Enabled = true;
+    
+    try
+    {
+        await LongRunningOperationAsync(cancellationSource.Token);
+        statusLabel.Text = "Operation completed";
+    }
+    catch (OperationCanceledException)
+    {
+        statusLabel.Text = "Operation cancelled";
+    }
+    finally
+    {
+        cancelButton.Enabled = false;
+    }
+}
+
+private void CancelButton_Clicked()
+{
+    cancellationSource?.Cancel();
+}
+```
+
+### Responsive UI During Blocking Operations
+
+```csharp
+private async void ProcessLargeDataset()
+{
+    var data = GetLargeDataset();
+    var batchSize = 100;
+    
+    for (int i = 0; i < data.Count; i += batchSize)
+    {
+        // Process a batch
+        var batch = data.Skip(i).Take(batchSize);
+        ProcessBatch(batch);
+        
+        // Update UI and yield control
+        progressBar.Fraction = (float)i / data.Count;
+        await Task.Yield(); // Allows UI events to process
+    }
+}
+```
+
+## Common Mistakes to Avoid
+
+### ❌ Don't: Update UI from background threads
+```csharp
+Task.Run(() =>
+{
+    label.Text = "This will crash!"; // Wrong!
+});
+```
+
+### ✅ Do: Use Application.Invoke()
+```csharp
+Task.Run(() =>
+{
+    Application.Invoke(() =>
+    {
+        label.Text = "This is safe!"; // Correct!
+    });
+});
+```
+
+### ❌ Don't: Forget to clean up timers
+```csharp
+// Memory leak - timer keeps running after view is disposed
+Application.MainLoop.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
+```
+
+### ✅ Do: Remove timers in Dispose
+```csharp
+protected override void Dispose(bool disposing)
+{
+    if (disposing && timerToken != null)
+    {
+        Application.MainLoop.RemoveTimeout(timerToken);
+    }
+    base.Dispose(disposing);
+}
+```
+
+## Performance Considerations
+
+- **Batch UI updates** when possible instead of updating individual elements
+- **Use appropriate timer intervals** - 100ms is usually the maximum useful rate
+- **Yield control** in long-running operations with `await Task.Yield()`
+- **Consider using `ConfigureAwait(false)`** for non-UI async operations
+- **Profile your application** to identify performance bottlenecks
+
+## See Also
+
+- [Events](events.md) - Event handling patterns
+- [Keyboard Input](keyboard.md) - Keyboard event processing
+- [Mouse Input](mouse.md) - Mouse event handling
+- [Configuration Management](config.md) - Application settings and state

+ 1 - 1
docfx/docs/toc.yml

@@ -33,7 +33,7 @@
 - name: Mouse
   href: mouse.md
 - name: Multi-Tasking
-  href: mainloop.md
+  href: multitasking.md
 - name: Navigation
   href: navigation.md
 - name: Popovers

BIN
local_packages/Terminal.Gui.2.0.0.nupkg


BIN
local_packages/Terminal.Gui.2.0.0.snupkg