Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend Win32 Console #241

Closed
wants to merge 3 commits into from
Closed

Extend Win32 Console #241

wants to merge 3 commits into from

Conversation

tomlm
Copy link
Collaborator

@tomlm tomlm commented Jan 2, 2025

  • replaced hand coded partial and incomplete PInvoke signatures with Vanara.Kernel32 signatures.
  • Rewrote WindowsConsole to use Vanara signatures
  • Extended and fixed console flags so all buttons are properly implemented with up/down signatures, double click, etc.

Copy link
Contributor

coderabbitai bot commented Jan 2, 2025

📝 Walkthrough

Walkthrough

This pull request introduces updates to the Consolonia project's Windows console handling components. A new <ItemGroup> has been added to the project files Consolonia.GuiCS.csproj and Consolonia.PlatformSupport.csproj, including a package reference for Vanara.PInvoke.Kernel32 version 4.0.4. In the WindowsDriver.cs and WindowsConsole.cs files, significant refactoring has been performed to use type-safe Vanara PInvoke types for console input handling. Changes include updating variable types, modifying method signatures, and enhancing error handling for console input operations. The modifications aim to improve the clarity, functionality, and robustness of console input processing in the Windows-specific implementation of the Consolonia library.

Possibly related PRs

Suggested labels

enhancement, bug

Suggested reviewers

  • jinek

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/Consolonia.GuiCS/WindowsDriver.cs (1)

45-62: Null return caution
Returning null instead of an empty array could lead to NullReferenceException if callers assume a valid array. Consider returning an empty array instead to simplify downstream logic.

- return numberEventsRead == 0
-     ? null
-     : records;
+ return numberEventsRead == 0
+     ? Array.Empty<INPUT_RECORD>()
+     : records;
src/Consolonia.PlatformSupport/WindowsConsole.cs (3)

122-124: WindowBufferSize event block
The commented-out logic for resizing is left in place. If the resizing logic is not needed, consider safely removing it to avoid confusion.


222-222: Horizontal wheel
Currently unhandled. If horizontal scroll is needed, consider implementing a corresponding vector update.


245-245: Character extraction
Reading char character = keyEvent.uChar; is straightforward. Consider verifying if uChar can be non-ASCII.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b5b4a3f and 1e61653.

📒 Files selected for processing (4)
  • src/Consolonia.GuiCS/Consolonia.GuiCS.csproj (1 hunks)
  • src/Consolonia.GuiCS/WindowsDriver.cs (1 hunks)
  • src/Consolonia.PlatformSupport/Consolonia.PlatformSupport.csproj (1 hunks)
  • src/Consolonia.PlatformSupport/WindowsConsole.cs (3 hunks)
🔇 Additional comments (32)
src/Consolonia.GuiCS/WindowsDriver.cs (5)

5-7: Imports alignment looks good
These imports from Vanara.PInvoke and the static usage of Kernel32 are consistent with the new PInvoke approach in this PR. No issues spotted here.


11-14: Appropriate platform targeting
Applying [SupportedOSPlatform("windows")] is a good practice to indicate that this class is intended for Windows-specific functionalities.


15-17: Improved type safety
Switching from IntPtr to HFILE and from uint to CONSOLE_INPUT_MODE enhances clarity and reduces the risk of misusing handle or mode types.


18-28: Verify disabling of certain console modes
Disabling quick-edit mode and processed input, and enabling mouse input might limit typical console interactions (e.g. Ctrl+C). If this is intentional, proceed. Otherwise, you may want to selectively re-enable certain flags.


30-43: Straightforward console mode property
Capturing errors from GetConsoleMode and SetConsoleMode by throwing exceptions is a sensible approach. Ensure higher-level logic handles these errors gracefully, especially in production environments.

src/Consolonia.PlatformSupport/WindowsConsole.cs (25)

15-16: Vanara import usage
The static import of Vanara.PInvoke.Kernel32 is consistent with the rest of this PR’s approach. No issues noted.


22-22: Clear platform specification
Applying [SupportedOSPlatform("windows")] to Win32Console clarifies that this class is not cross-platform. Well done.


25-68: Comprehensive translator mappings
The new FlagTranslator usage for both keyboard and mouse states is clean and easy to understand. This mapping approach improves readability and maintainability compared to multiple conditional checks.


73-73: Initial mouse state
Initializing _mouseButtonsState to MOUSE_BUTTON_STATE.NONE ensures a known default. No issues here.


93-93: Focus event injection
Writing a focus event into the console input stream is an interesting approach to trigger internal logic. This can be fragile if used too extensively, but is acceptable for specialized console scenarios.


118-118: Validate read result
The code throws NotImplementedException on an empty read, which might abruptly terminate the loop. Confirm whether empty reads require graceful handling or if they are truly unexpected.


127-128: Focus event dispatch
Raising focus events on FOCUS_EVENT aligns with your injection approach. No issues here.


131-132: Key event
Invoking HandleKeyInput for KEY_EVENT is consistent. Straightforward approach.


134-136: Mouse event
Delegating handling to HandleMouseInput is sound. The method is sufficiently encapsulated for reading or modifying mouse input logic.


143-143: Mouse input function
HandleMouseInput is the central dispatch for translating raw mouse records into Avalonia pointer events. Good structure.


145-145: Use of Avalonia's Point
Creating a Point from dwMousePosition is straightforward. No issues here.


147-148: Combined modifiers
Combining recognized control-key states and current mouse-button states into RawInputModifiers is a good approach for consistency.


150-150: Default event type
Defaulting to RawPointerEventType.Move is a safe fallback.


153-153: Event flags switch
Handling different dwEventFlags in a switch is clear and maintainable.


155-172: Double-click event generation
Generating two Down/Up sequences is a conventional approach to simulate double-clicks. Confirm that consumers do not misinterpret these repeated events as two single clicks.


175-209: Button state transitions
Looping over each MOUSE_BUTTON_STATE to detect transitions is robust. Ensure the default path (lines 204–209) does not trigger spurious Move events for unchanged states.


213-216: Vertical mouse wheel
Raising the Wheel event with a Vector(0, velocity) is logically correct.


218-220: Wheel event lines
This chunk is altogether part of the MOUSE_EVENT_FLAG.MOUSE_WHEELED handling. Looks fine.


224-225: Mouse moved event
A direct Move event is raised for any MOUSE_EVENT_FLAG.MOUSE_MOVED. This is standard usage.


229-230: Update state after Move
Updating _mouseButtonsState ensures the local state remains in sync.


231-235: Combination flag
This block attempts to handle a scenario where both MOUSE_MOVED and DOUBLE_CLICK flags appear together. Verify correctness, since it only calls LeftButtonDown and Move, omitting LeftButtonUp.


236-237: Unknown event
Throwing InvalidOperationException for unrecognized mouse flags is a safe fallback to detect unexpected input conditions.


239-240: Finalize state
Returning true from the method after updating _mouseButtonsState completes the cycle. No issues.


243-243: Dedicated KeyInput handler
Separating HandleKeyInput clarifies the event loop logic.


247-247: Consolidated modifiers
Translating the dwControlKeyState into RawInputModifiers merges seamlessly with the existing logic to detect Shift, Ctrl, and Alt.

src/Consolonia.GuiCS/Consolonia.GuiCS.csproj (1)

8-10: Vanara PInvoke dependency
Adding Vanara.PInvoke.Kernel32 version 4.0.4 is aligned with the updated console logic.

src/Consolonia.PlatformSupport/Consolonia.PlatformSupport.csproj (1)

3-5: Shared dependency
Including the same Vanara.PInvoke.Kernel32 reference here ensures consistent usage across both projects for improved console handling.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
src/Consolonia.PlatformSupport/PlatformSupportExtensions.cs (1)

25-32: Selective suppression of platform compatibility warnings.

Disabling CA1416 around Windows-specific code is a good practice when the code path is guaranteed to run on Windows only. Just remember to confirm that calls to Windows-specific APIs cannot be reached on non-Windows platforms at runtime.

src/Consolonia.PlatformSupport/WindowsConsole.cs (4)

36-45: Mouse modifiers mapping.

By mapping MOUSE_BUTTON_STATE to RawInputModifiers, you ensure consistent decoding of mouse button states. This is a neat approach that centralizes the logic. Watch for boundary cases, such as multi-button presses.


48-58: Distinct translators for mouse button down events.

Having separate translators for down and up events helps keep the logic straightforward. Consider adding references or comments clarifying the rationale for the “LeaveWindow” default scenario, which might confuse new contributors.


73-73: Track mouse state across events.

Using a private _mouseButtonsState eases stateful mouse event handling. For clarity, confirm this field’s usage in multi-threading scenarios, as race conditions can occur if it’s accessed from different threads.


143-239: Enhanced mouse event handling logic.

The comprehensive switch handling for different mouse events (e.g., double-click, press, release, wheel, etc.) appears robust. A few observations:
• Double-click logic triggers two down-up cycles—test thoroughly for race conditions or unintended repeated clicks.
• Large switch-statement can grow complex; consider extracting smaller methods if more event flags are introduced.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1e61653 and 6af70f9.

📒 Files selected for processing (2)
  • src/Consolonia.PlatformSupport/PlatformSupportExtensions.cs (2 hunks)
  • src/Consolonia.PlatformSupport/WindowsConsole.cs (3 hunks)
🔇 Additional comments (8)
src/Consolonia.PlatformSupport/PlatformSupportExtensions.cs (1)

11-14: Use of pragmas to suppress IDE warnings.

These pragmas to disable and restore specific IDE warnings are acceptable in cases where they address known false positives. However, ensure proper justification is documented to prevent confusion for future contributors.

src/Consolonia.PlatformSupport/WindowsConsole.cs (7)

15-16: Adopting Vanara Kernel32 API.

Bringing in Vanara.PInvoke.Kernel32 and the System.Runtime.Versioning attributes is aligned with modern Windows-specific development. This library use should increase code clarity and maintainability.


22-22: Marking class as Windows-specific.

Using [SupportedOSPlatform("windows")] clarifies the operating system dependencies of this code, which is particularly helpful for cross-platform scenarios.


25-34: FlagTranslator usage for key modifiers.

Defining a static FlagTranslator for mapping CONTROL_KEY_STATE to RawInputModifiers is a clean way to manage bit-flag mappings, limiting duplication elsewhere in the code. Ensure tests verify all relevant key modifier scenarios (e.g., SHIFT + CTRL).


59-68: Ensuring symmetrical mapping for button up events.

This symmetrical translator for button-up events is consistent with the button-down translator. Validate that XButton1 and XButton2 interactions are tested if the target environment utilizes them.


93-93: Triggering synthetic focus events.

Writing a FOCUS_EVENT record to the console input stream is a creative way to simulate focus changes. This can help unify event flow across the codebase.


118-136: Additional event routes in loop.

Handling WINDOW_BUFFER_SIZE_EVENT, FOCUS_EVENT, KEY_EVENT, and MOUSE_EVENT demonstrates improved coverage of console input scenarios. Double check if ignoring all other event types is intentional or if fallback handling is needed.


242-249: Refined key input interpretation.

Forwarding key events with KeyModifiersTranslator and character data is a good practice. Ensure that special characters (e.g., function keys) and combined keys (CTRL + ALT + SHIFT) are processed consistently.

@tomlm tomlm closed this Jan 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant