Files
ClassicAssist.Avalonia/.qoder/repowiki/en/content/Macro System/Built-in Commands/Utility Commands.md
T
Beyhan Oğur d5f52cc3d3 first commit
2026-09-03 04:45:36 +03:00

18 KiB
Raw Blame History

Utility Commands

**Referenced Files in This Document** - [TimerCommands.cs](file://ClassicAssist.Shared/Data/Macros/Commands/TimerCommands.cs) - [MacroInvoker.cs](file://ClassicAssist.Shared/Data/Macros/MacroInvoker.cs) - [MacroManager.cs](file://ClassicAssist.Shared/Data/Macros/MacroManager.cs) - [SystemMessageTextWriter.cs](file://ClassicAssist.Shared/Data/Macros/SystemMessageTextWriter.cs) - [ParameterType.cs](file://ClassicAssist.Shared/Data/Macros/ParameterType.cs) - [OffsetStopwatch.cs](file://ClassicAssist.Shared/Misc/OffsetStopwatch.cs) - [ThreadQueue.cs](file://ClassicAssist.Shared/Misc/ThreadQueue.cs) - [ThreadPriorityQueue.cs](file://ClassicAssist.Shared/Misc/ThreadPriorityQueue.cs) - [TimerTests.cs](file://ClassicAssist.Tests/MacroCommands/TimerTests.cs)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendices

Introduction

This document explains the utility commands available in the ClassicAssist.Avalonia macro system, focusing on timing controls, conditional logic, loops, variable management, and debugging utilities. It provides parameter specifications for timers, conditions, iteration patterns, and data storage, along with examples of complex automation flows, error handling, logging, and performance monitoring. The goal is to help you build robust, maintainable macros that execute reliably under game conditions.

Project Structure

The macro command implementations live in the shared module under Data/Macros/Commands. Timer-related commands are implemented in a dedicated file, while the macro execution engine and supporting utilities (logging, threading primitives, timing helpers) are spread across related files. Tests validate timer behavior and integration points.

graph TB
subgraph "Shared Macro System"
A["TimerCommands.cs"]
B["MacroInvoker.cs"]
C["MacroManager.cs"]
D["SystemMessageTextWriter.cs"]
E["ParameterType.cs"]
F["OffsetStopwatch.cs"]
G["ThreadQueue.cs"]
H["ThreadPriorityQueue.cs"]
end
subgraph "Tests"
T["TimerTests.cs"]
end
A --> B
B --> C
B --> D
B --> E
B --> F
B --> G
B --> H
T --> A

Diagram sources

Section sources

Core Components

  • Timer commands: Provide scheduling, delays, and periodic execution hooks used by macros to coordinate actions over time.
  • Macro invoker: Executes macro commands, manages parameters, and coordinates with logging and threading primitives.
  • Macro manager: Hosts and orchestrates macro instances, including lifecycle and dispatching.
  • Logging writer: Routes macro output to the in-game system message channel for visibility.
  • Parameter types: Define supported argument types for commands and their parsing rules.
  • Timing utilities: High-resolution timing helpers for accurate delays and intervals.
  • Threading queues: Priority and FIFO queues used to schedule work items safely across threads.

Key responsibilities:

  • TimerCommands.cs: Implements timer-related operations exposed to macros.
  • MacroInvoker.cs: Parses parameters, resolves command handlers, and executes them within the macro context.
  • MacroManager.cs: Manages macro registration, discovery, and runtime control.
  • SystemMessageTextWriter.cs: Bridges macro logs to the UI/game messages.
  • OffsetStopwatch.cs: Provides precise elapsed time measurements.
  • ThreadQueue.cs / ThreadPriorityQueue.cs: Provide thread-safe queuing for scheduled tasks.

Section sources

Architecture Overview

The macro system exposes commands to scripts/macros. Timer commands integrate with the macro invoker and underlying timing and queueing infrastructure to schedule work. Logging is routed through a writer that integrates with the application’s message channels.

sequenceDiagram
participant M as "Macro"
participant Inv as "MacroInvoker"
participant TC as "TimerCommands"
participant Q as "ThreadQueue/PriorityQueue"
participant SW as "SystemMessageTextWriter"
M->>Inv : Invoke("timer", args)
Inv->>TC : Execute timer operation
TC->>Q : Schedule task/delay
Q-->>TC : Task queued
TC-->>Inv : Status/result
Inv->>SW : Log status/info
SW-->>M : Visible in game/system messages

Diagram sources

Detailed Component Analysis

Timer Commands

Timer commands enable macros to delay execution, schedule one-shot or recurring tasks, and synchronize with external events. They rely on high-resolution timing and thread-safe queues to ensure predictable behavior.

  • Scheduling model:
    • One-shot delays: Execute a callback after a specified duration.
    • Periodic tasks: Repeatedly execute a callback at fixed intervals until cancelled.
    • Cancellation: Support stopping scheduled tasks when macros terminate or explicitly cancel.
  • Time units:
    • Durations are expressed in milliseconds; use integer values for precision.
  • Concurrency:
    • Tasks are enqueued into priority or FIFO queues and executed on appropriate threads.
  • Error handling:
    • Exceptions inside scheduled callbacks should be caught and logged via the system message writer to avoid crashing the macro runtime.
  • Performance:
    • Prefer batching small tasks and avoiding excessive short-interval timers to reduce overhead.
flowchart TD
Start(["Start"]) --> ParseArgs["Parse arguments<br/>duration(ms), repeat?, interval(ms)"]
ParseArgs --> Validate{"Valid inputs?"}
Validate --> |No| LogError["Log error via SystemMessageTextWriter"]
Validate --> |Yes| CreateTask["Create task entry"]
CreateTask --> QueueType{"Periodic?"}
QueueType --> |No| EnqueueOneShot["Enqueue one-shot delay"]
QueueType --> |Yes| EnqueuePeriodic["Enqueue periodic interval"]
EnqueueOneShot --> Done(["Done"])
EnqueuePeriodic --> Done
LogError --> Done

Diagram sources

Section sources

Conditional Logic

Conditional logic in macros typically evaluates expressions and branches execution based on results. While specific condition commands may be defined elsewhere, the invoker parses parameters and delegates evaluation to command handlers.

  • Expression evaluation:
    • Supports numeric comparisons, string equality, and boolean flags.
  • Type safety:
    • Uses ParameterType definitions to coerce and validate inputs before evaluation.
  • Short-circuiting:
    • Logical operators can short-circuit to optimize performance.
  • Debugging:
    • Use logging to print intermediate values during development.
flowchart TD
Entry(["Evaluate Condition"]) --> Parse["Parse operands and operator"]
Parse --> Coerce["Coerce types using ParameterType"]
Coerce --> Eval["Evaluate expression"]
Eval --> Branch{"True?"}
Branch --> |Yes| ThenBranch["Execute then-block"]
Branch --> |No| ElseBranch["Execute else-block"]
ThenBranch --> Exit(["Exit"])
ElseBranch --> Exit

[No diagram sources since this section describes conceptual flow without mapping to specific files]

Section sources

Loops

Loops allow repeated execution of blocks until a condition changes or a count is reached.

  • For-style loops:
    • Iterate a fixed number of times with an index variable.
  • While-style loops:
    • Repeat while a condition remains true; include safeguards against infinite loops.
  • Break and continue:
    • Control flow keywords to exit early or skip iterations.
  • Performance:
    • Avoid heavy operations inside tight loops; batch I/O and minimize allocations.
flowchart TD
Init(["Initialize loop variables"]) --> CheckCond["Check loop condition"]
CheckCond --> |False| EndLoop(["Exit loop"])
CheckCond --> |True| Body["Execute loop body"]
Body --> Update["Update loop variables"]
Update --> CheckCond

[No diagram sources since this section describes conceptual flow without mapping to specific files]

Section sources

Variable Management

Variables store state across macro executions and between commands.

  • Scope:
    • Local variables scoped to the current macro instance.
    • Global variables accessible across macros if explicitly designed.
  • Types:
    • Integers, strings, booleans, and collections as supported by ParameterType.
  • Operations:
    • Set, get, increment/decrement, and list variables.
  • Persistence:
    • Optional persistence to configuration or profile storage for long-term state.
classDiagram
class MacroContext {
+SetVariable(name, value)
+GetVariable(name) object
+ListVariables() IEnumerable
}
class ParameterType {
+Int
+String
+Boolean
+Collection
}
MacroContext --> ParameterType : "uses for coercion"

Diagram sources

Section sources

Debugging Utilities

Debugging utilities provide logging, inspection, and diagnostics to aid macro development.

  • Logging:
    • Write messages to the in-game system channel via SystemMessageTextWriter.
  • Inspection:
    • Dump variables, counters, and internal state for troubleshooting.
  • Timing metrics:
    • Use OffsetStopwatch to measure durations of critical sections.
  • Test coverage:
    • Unit tests validate timer behavior and edge cases.
sequenceDiagram
participant Dev as "Developer"
participant Macro as "Macro"
participant Inv as "MacroInvoker"
participant Log as "SystemMessageTextWriter"
participant Sw as "OffsetStopwatch"
Dev->>Macro : Run macro with debug statements
Macro->>Inv : Log("debug info")
Inv->>Log : Write message
Macro->>Sw : Start measurement
Macro->>Macro : Perform operation
Macro->>Sw : Stop measurement
Macro->>Log : Log elapsed time

Diagram sources

Section sources

Dependency Analysis

The macro system exhibits clear separation of concerns:

  • TimerCommands depends on the invoker for parameter parsing and on queues for scheduling.
  • MacroInvoker depends on ParameterType for input validation and on SystemMessageTextWriter for logging.
  • OffsetStopwatch provides timing accuracy for both timers and performance measurements.
  • Tests depend on TimerCommands to assert expected behaviors.
graph LR
Timer["TimerCommands.cs"] --> Invoker["MacroInvoker.cs"]
Timer --> Q1["ThreadQueue.cs"]
Timer --> Q2["ThreadPriorityQueue.cs"]
Invoker --> Params["ParameterType.cs"]
Invoker --> Log["SystemMessageTextWriter.cs"]
Invoker --> Stop["OffsetStopwatch.cs"]
Tests["TimerTests.cs"] --> Timer

Diagram sources

Section sources

Performance Considerations

  • Minimize timer granularity:
    • Avoid very short intervals unless necessary; prefer coarser intervals and batching.
  • Reduce allocations:
    • Reuse objects where possible and avoid creating large temporary structures inside loops.
  • Efficient logging:
    • Batch log messages and avoid excessive verbosity in production runs.
  • Queue selection:
    • Use priority queues for urgent tasks and FIFO for background work to balance responsiveness and throughput.
  • Measurement:
    • Use OffsetStopwatch to identify hotspots and validate improvements.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

Common issues and resolutions:

  • Timers not firing:
    • Verify queue availability and thread pool health; check for exceptions in scheduled callbacks.
  • Delays too long or too short:
    • Confirm unit conversions and ensure millisecond values are correct.
  • Memory growth:
    • Inspect variable scopes and ensure cleanup of scheduled tasks upon macro termination.
  • Logging missing:
    • Ensure SystemMessageTextWriter is initialized and permissions allow writing messages.
  • Flaky conditions:
    • Add logging around condition evaluations and consider debouncing rapid state changes.

Validation references:

  • Timer behavior assertions and edge cases are covered by tests.

Section sources

Conclusion

The utility commands in the ClassicAssist.Avalonia macro system provide robust timing, conditional logic, looping, variable management, and debugging capabilities. By leveraging the timer commands, parameter typing, logging, and timing utilities, you can construct reliable automations that are easy to test and maintain. Follow best practices for organization, reuse, and performance to keep macros responsive and resilient.

[No sources needed since this section summarizes without analyzing specific files]

Appendices

Best Practices for Macro Organization

  • Modularize logic:
    • Split complex workflows into reusable sub-macros invoked by name.
  • Centralize constants:
    • Store durations, thresholds, and identifiers in a single place for consistency.
  • Defensive programming:
    • Validate inputs, handle exceptions, and log meaningful messages.
  • Testing:
    • Write unit tests for critical paths, especially timers and conditions.
  • Documentation:
    • Comment non-obvious logic and maintain a changelog for macro versions.

[No sources needed since this section provides general guidance]