Tig 3 ay önce
ebeveyn
işleme
fb820fd32b

+ 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

+ 2 - 3
docfx/apispec/namespace-app.md

@@ -22,6 +22,5 @@ Application.Shutdown();
 
 ## See Also
 
-- [Logging](logging.md)
-- [Mainloop](mainloop.md)
-<!-- - [Application](application.md) -->
+- [Logging](~/docs/logging.md)
+- [Multitasking](~/docs/multitasking.md)

+ 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.
+

+ 2 - 1
docfx/docfx.json

@@ -42,7 +42,8 @@
         ],
         "exclude": [
           "_site/**",
-          "includes/**"
+          "includes/**",
+          "apispec/**"
         ]
       }
     ],

+ 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/Terminal.Gui).
+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