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

Put Processes with Visible Window On the Top & Do not kill FL Process #3150

Open
wants to merge 9 commits into
base: dev
Choose a base branch
from

Conversation

PaulPSta
Copy link

@PaulPSta PaulPSta commented Dec 27, 2024

Put Processes with Visible Window On the Top

When using the killer process feature, I often find it difficult to recall the exact name of the process I want to terminate. However, in most cases, I am trying to close a process associated with a visible window on my screen, rather than a background service or job.

To improve usability and speed, I propose sorting the search results to prioritize processes that have a non-empty MainWindowTitle, so that processes with visible windows appear first.

The process name & id is still visible and I move it to the tooltip of the title.

Additionally, since we are using FL, we should not allow to kill FL process, so I remove FL process from the list.

Test

Screenshot 2025-03-14 161114

Screenshot 2025-03-14 161132

This comment has been minimized.

@prlabeler prlabeler bot added the enhancement New feature or request label Dec 27, 2024
Copy link

gitstream-cm bot commented Dec 27, 2024

🥷 Code experts: Jack251970

Jack251970 has most 👩‍💻 activity in the files.
Jack251970 has most 🧠 knowledge in the files.

See details

Flow.Launcher.Infrastructure/FileExplorerHelper.cs

Activity based on git-commit:

Jack251970
MAR
FEB 14 additions & 1 deletions
JAN 2 additions & 2 deletions
DEC 3 additions & 7 deletions
NOV
OCT

Knowledge based on git-blame:
Jack251970: 17%

Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs

Activity based on git-commit:

Jack251970
MAR
FEB
JAN
DEC
NOV
OCT

Knowledge based on git-blame:

Plugins/Flow.Launcher.Plugin.ProcessKiller/NativeMethods.txt

Activity based on git-commit:

Jack251970
MAR
FEB
JAN
DEC 2 additions & 0 deletions
NOV
OCT

Knowledge based on git-blame:
Jack251970: 100%

Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs

Activity based on git-commit:

Jack251970
MAR
FEB
JAN
DEC 27 additions & 32 deletions
NOV
OCT

Knowledge based on git-blame:
Jack251970: 17%

To learn more about /:\ gitStream - Visit our Docs

Copy link
Contributor

coderabbitai bot commented Dec 27, 2024

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the Process Killer plugin in Flow Launcher, enhancing process management capabilities. Key changes include the declaration of a readonly processHelper, updates to the TryKill method to accept a context parameter, and a restructuring of the CreateResultsFromQuery method to improve process filtering and scoring. The ProcessResult class has been expanded to include new properties for better encapsulation of process data. Additionally, several native methods have been added to the NativeMethods.txt file, and a project reference has been removed.

Changes

File Change Summary
Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs - Made processHelper readonly and initialized it with shorthand syntax.
- Updated TryKill method to accept _context parameter.
- Restructured CreateResultsFromQuery to retrieve all non-system processes first and improved filtering logic.
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs - Added constant FlowLauncherProcessName and updated IsSystemProcess method.
- Introduced GetProcessNameIdTitle and GetProcessesWithNonEmptyWindowTitle methods.
- Updated GetMatchingProcesses method to return a list of Process objects.
- Modified TryKill method to accept PluginInitContext.
Plugins/Flow.Launcher.Plugin.ProcessKiller/NativeMethods.txt - Added method names: EnumWindows, GetWindowTextLength, GetWindowText, IsWindowVisible, GetWindowThreadProcessId.
Flow.Launcher.Infrastructure/FileExplorerHelper.cs - Removed EnumWindowsProc delegate.
Plugins/Flow.Launcher.Plugin.ProcessKiller/Flow.Launcher.Plugin.ProcessKiller.csproj - Removed project reference to Flow.Launcher.Infrastructure.csproj.
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessResult.cs - Updated constructor to include new parameters: title, match, and tooltip.
- Added properties: Title, TitleMatch, and Tooltip.

Possibly related PRs

Suggested labels

bug, kind/ui

Suggested reviewers

  • taooceros

Poem

🐰 In the land of processes, swift and bright,
A plugin evolves, taking flight.
Titles and tooltips, oh what a sight,
Killing tasks with all of our might!
Flowing like water, our code's a delight! 🔪

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f25c5b9 and aa6c9d9.

📒 Files selected for processing (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs

🪧 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.
  • @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 (3)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (2)

68-70: Consolidate dictionary usage
You're retrieving a dictionary of processes with non-empty window titles while also retrieving a broader processList. Consider whether this dictionary or an alternative data structure can more seamlessly integrate with the main list. This might streamline lookups and reduce repeated iteration.


78-90: Avoid potential performance overhead in large loops
The approach of building a new Result for each process is fine for modest lists, but in systems with many processes, enumerating them all might cause performance concerns. Periodically review if you need a paging mechanism or a more optimized approach for large process sets.

Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

80-104: Handle potential exceptions from Process.GetProcessById
If the process exits between the time of enumeration and retrieval, it may throw an exception. Consider wrapping it in a try-catch block to avoid runtime issues.

Potential approach:

+try
+{
+    var process = Process.GetProcessById((int)processId);
+    if (!processDict.ContainsKey((int)processId))
+    {
+        processDict.Add((int)processId, windowTitle.ToString());
+    }
+}
+catch (ArgumentException)
+{
+    // Process no longer exists, skip
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7e825e and b2532fc.

📒 Files selected for processing (2)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (3 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (3 hunks)
🔇 Additional comments (11)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (4)

63-64: Use a dedicated model for clarity
Defining a record for process data is a neat way to group and transport relevant info (ProcessName, MainWindowTitle). This improves maintainability and readability. Great approach!


71-71: Consider user feedback for empty query
When processList.Any() is false, you return null. If someone types an invalid or empty query, returning null means no results. Make sure this behavior aligns with desired user experience (e.g., we might want to show a “No matching processes” item).


101-104: Sorting logic fits the use case
You’re correctly using OrderBy to push processes with non-empty window titles to the top. The subsequent .ThenBy(x => x.Title) helps group them by logical title ordering. This is straightforward and readable.


109-120: Re-check concurrency or potential race conditions
Inserting a “Kill All” option is a solid UX improvement. However, calls to TryKill for multiple processes could face concurrency or ephemeral process states. If a process closes just as the user selects “Kill All,” handle or log that possibility gracefully.

Would you like me to create a verification script to check for concurrency handling across all kill calls?

Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (7)

1-1: File header looks good
No issues found regarding the top-level using directives.


14-16: Verify multi-platform considerations for EnumWindows
EnumWindows is a Windows API function. Ensure that the plugin gracefully handles or skips this functionality on non-Windows platforms.


17-17: Delegate for EnumWindowsProc
This delegate looks correctly declared for the callback.


22-23: Checks for window visibility
Using IsWindowVisible is a valid approach for filtering out hidden windows.


25-26: GetWindowThreadProcessId usage
Acquiring the process ID via GetWindowThreadProcessId is standard practice and looks good here.


77-79: Docstring clarity
The XML comment accurately describes the method’s purpose and return value.


19-20: ⚠️ Potential issue

Use a larger StringBuilder capacity
Calling new StringBuilder() defaults to 16 as capacity. This may truncate window titles longer than 16 characters.

Consider specifying a larger capacity, for example:

-StringBuilder windowTitle = new StringBuilder();
+StringBuilder windowTitle = new StringBuilder(256);

Likely invalid or redundant comment.

@taooceros
Copy link
Member

make sense! Thanks. How do you think if we rank them by the z-index on the screen (I don't know whether it is possible though)?

Copy link

gitstream-cm bot commented Jan 9, 2025

Be a legend 🏆 by adding a before and after screenshot of the changes you made, especially if they are around UI/UX.

This comment has been minimized.

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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2532fc and db5bc41.

📒 Files selected for processing (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Report (PR)
🔇 Additional comments (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

79-82: LGTM on API documentation

The XML documentation for the method is clear and descriptive, accurately explaining the purpose and return value of the method.

This comment has been minimized.

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 (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/NativeMethods.txt (1)

2-7: Native Methods for Window Handling Added

The addition of new native method names—OpenProcess, EnumWindows, GetWindowTextLength, GetWindowText, IsWindowVisible, and GetWindowThreadProcessId—is aligned with the functionality to prioritize processes that have a non-empty main window title. This enhancement supports the new process filtering feature by ensuring that processes linked to visible windows can be identified and managed more effectively.

A minor suggestion: consider adding inline comments or a short documentation block in this file to briefly describe the purpose of each native method. This will help maintain clarity and aid future maintenance or onboarding of new developers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db5bc41 and fa46513.

📒 Files selected for processing (3)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (3 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/NativeMethods.txt (1 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: gitStream.cm
  • GitHub Check: gitStream.cm
  • GitHub Check: gitStream.cm

This comment has been minimized.

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

♻️ Duplicate comments (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

65-94: ⚠️ Potential issue

Fix resource management and add exception handling

The method has two critical issues:

  1. No resource management for the Process object at line 83
  2. No exception handling around Process.GetProcessById() which may throw if the process terminates

You should implement the following fixes:

public static unsafe Dictionary<int, string> GetProcessesWithNonEmptyWindowTitle()
{
    var processDict = new Dictionary<int, string>();
    PInvoke.EnumWindows((hWnd, _) =>
    {
        var windowTitle = GetWindowTitle(hWnd);
        if (!string.IsNullOrWhiteSpace(windowTitle) && PInvoke.IsWindowVisible(hWnd))
        {
            uint processId = 0;
            var result = PInvoke.GetWindowThreadProcessId(hWnd, &processId);
            if (result == 0u || processId == 0u)
            {
                return false;
            }

-           var process = Process.GetProcessById((int)processId);
-           if (!processDict.ContainsKey((int)processId))
-           {
-               processDict.Add((int)processId, windowTitle);
-           }
+           try
+           {
+               using var process = Process.GetProcessById((int)processId);
+               if (!processDict.ContainsKey((int)processId))
+               {
+                   processDict.Add((int)processId, windowTitle);
+               }
+           }
+           catch (ArgumentException)
+           {
+               // Process might have exited between enumeration and retrieval
+           }
+           catch (InvalidOperationException)
+           {
+               // Process might be in an invalid state
+           }
        }

        return true;
    }, IntPtr.Zero);

    return processDict;
}

Note that this issue was already identified in a previous review but hasn't been addressed in this version.

🧹 Nitpick comments (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

65-94: Consider handling processes with multiple windows

Currently, the dictionary only stores one window title per process ID. If a process has multiple windows, only the last one encountered will be stored. Consider whether your sorting logic would benefit from having access to all window titles for a process.

If you need to track multiple windows per process, you could modify the return type:

- public static unsafe Dictionary<int, string> GetProcessesWithNonEmptyWindowTitle()
+ public static unsafe Dictionary<int, List<string>> GetProcessesWithNonEmptyWindowTitle()
{
-   var processDict = new Dictionary<int, string>();
+   var processDict = new Dictionary<int, List<string>>();
    PInvoke.EnumWindows((hWnd, _) =>
    {
        var windowTitle = GetWindowTitle(hWnd);
        if (!string.IsNullOrWhiteSpace(windowTitle) && PInvoke.IsWindowVisible(hWnd))
        {
            // ... existing code to get processId ...
            
            try 
            {
                using var process = Process.GetProcessById((int)processId);
                if (!processDict.ContainsKey((int)processId))
                {
-                   processDict.Add((int)processId, windowTitle);
+                   processDict.Add((int)processId, new List<string> { windowTitle });
                }
+               else
+               {
+                   processDict[(int)processId].Add(windowTitle);
+               }
            }
            // ... exception handling ...
        }
        return true;
    }, IntPtr.Zero);

    return processDict;
}

This change would allow you to track all window titles for each process, which might provide more context for your sorting algorithm.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fa46513 and b7694d3.

📒 Files selected for processing (2)
  • Flow.Launcher.Infrastructure/FileExplorerHelper.cs (0 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (2 hunks)
💤 Files with no reviewable changes (1)
  • Flow.Launcher.Infrastructure/FileExplorerHelper.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: gitStream.cm
🔇 Additional comments (3)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (3)

16-16: Good syntax update using modern C# features

Using the target-typed new expression (new()) is cleaner and more maintainable.


96-109: Well-implemented window title retrieval method

This is an excellent implementation of GetWindowTitle:

  • Efficiently determines required buffer size
  • Uses stackalloc for small buffers to avoid heap allocations
  • Falls back to heap allocation for larger buffers
  • Uses modern C# features like Span<T> and fixed buffers
  • Handles empty return values correctly

1-11: 🛠️ Refactor suggestion

Add missing using directives for Runtime.InteropServices and Text

The code is using interop features and string manipulation, but missing the required using statements.

using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Threading;

Note that this issue was already identified in a previous review but hasn't been addressed in this version.

This comment has been minimized.

@Jack251970
Copy link
Contributor

@PaulPSta Hi, I have cleaned up your codes and done some improvements here.

Firstly, I replaced DllImport with PInvoke for code quality.

Secondly, every time you kill one process, I think the main window should remain open and re-query results instead of closing. This allows users to terminate multiple processes without interruption.

Could you please check if this works for you?

@Jack251970 Jack251970 changed the title Order search result by window title Process Killer Enhancement: Put Visible Window On the Top Mar 14, 2025
@Jack251970 Jack251970 changed the title Process Killer Enhancement: Put Visible Window On the Top Put Processes with Visible Window On the Top & Do not kill FL Process Mar 14, 2025

This comment has been minimized.

@Jack251970 Jack251970 requested a review from taooceros March 14, 2025 03:42
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

♻️ Duplicate comments (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

83-109: ⚠️ Potential issue

Handle potential exceptions and improve resource management

The implementation of GetProcessesWithNonEmptyWindowTitle needs to handle potential exceptions and properly dispose of Process objects.

public static unsafe Dictionary<int, string> GetProcessesWithNonEmptyWindowTitle()
{
    var processDict = new Dictionary<int, string>();
    PInvoke.EnumWindows((hWnd, _) =>
    {
        var windowTitle = GetWindowTitle(hWnd);
        if (!string.IsNullOrWhiteSpace(windowTitle) && PInvoke.IsWindowVisible(hWnd))
        {
            uint processId = 0;
            var result = PInvoke.GetWindowThreadProcessId(hWnd, &processId);
-           if (result == 0u || processId == 0u)
+           if (result == 0u || processId == 0u) 
            {
-               return false;
+               return true; // Continue enumeration even if we couldn't get this window's process ID
            }

-           var process = Process.GetProcessById((int)processId);
-           if (!processDict.ContainsKey((int)processId))
-           {
-               processDict.Add((int)processId, windowTitle);
-           }
+           try 
+           {
+               using var process = Process.GetProcessById((int)processId);
+               if (!processDict.ContainsKey((int)processId))
+               {
+                   processDict.Add((int)processId, windowTitle);
+               }
+           }
+           catch (ArgumentException)
+           {
+               // Process might have exited between enumeration and retrieval
+           }
+           catch (InvalidOperationException)
+           {
+               // Process might be in an invalid state
+           }
        }

        return true;
    }, IntPtr.Zero);

    return processDict;
}

This change:

  1. Makes the method continue enumeration even if GetWindowThreadProcessId fails
  2. Uses a try-catch block to handle potential exceptions from Process.GetProcessById
  3. Uses a using statement for proper disposal of the Process object
🧹 Nitpick comments (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

42-78: Consider deduplicating process entries in search results.

The current implementation might add the same process twice to the results list - once when matching by window title and again when matching by process name and ID.

public List<ProcessResult> GetMatchingProcesses(string searchTerm, Dictionary<int, string> processWindowTitle)
{
    var processlist = new List<ProcessResult>();
+   var addedProcessIds = new HashSet<int>();

    foreach (var p in Process.GetProcesses())
    {
        if (IsSystemProcess(p)) continue;

        if (string.IsNullOrWhiteSpace(searchTerm))
        {
            // Show all non-system processes
            processlist.Add(new ProcessResult(p, 0));
+           addedProcessIds.Add(p.Id);
        }
        else
        {
            // Search window title first
            if (processWindowTitle.TryGetValue(p.Id, out var windowTitle))
            {
                var score = StringMatcher.FuzzySearch(searchTerm, windowTitle).Score;
                if (score > 0)
                {
                    processlist.Add(new ProcessResult(p, score));
+                   addedProcessIds.Add(p.Id);
+                   continue;
                }
            }

            // Search process name and process id
            var score1 = StringMatcher.FuzzySearch(searchTerm, p.ProcessName + " - " + p.Id).Score;
-           if (score1 > 0)
+           if (score1 > 0 && !addedProcessIds.Contains(p.Id))
            {
                processlist.Add(new ProcessResult(p, score1));
+               addedProcessIds.Add(p.Id);
                continue;
            }
        }
    }

    return processlist;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d12cde7 and 8ee2d48.

📒 Files selected for processing (2)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (2 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: gitStream.cm
🔇 Additional comments (3)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (3)

34-37: Good preventive measure for Flow Launcher process.

Adding the constant for the Flow Launcher process name and modifying IsSystemProcess to prevent killing the Flow Launcher itself is a good safety measure. This aligns with the PR objective to prevent the program from self-terminating.


111-124: Good implementation of the GetWindowTitle method

The implementation of GetWindowTitle efficiently uses stack allocation for small buffers and heap allocation for larger ones. The use of Span and unsafe code is appropriate for this low-level Windows API interaction.


1-11: Missing using statements for Span and unsafe operations

The code uses Span and unsafe code, but the necessary using statements are missing.

using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Threading;

This comment has been minimized.

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: 1

♻️ Duplicate comments (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (1)

62-91: ⚠️ Potential issue

Handle potential exceptions when retrieving processes by ID.

GetProcessById can throw ArgumentException or InvalidOperationException if the process has exited between enumeration and retrieval. Currently, the callback returns false if an error arises early, but an unhandled exception would break EnumWindows. Consider a try/catch block around Process.GetProcessById to avoid partial enumeration failures.

- var process = Process.GetProcessById((int)processId);
- if (!processDict.ContainsKey((int)processId))
- {
-     processDict.Add((int)processId, windowTitle);
- }
+ try
+ {
+     var process = Process.GetProcessById((int)processId);
+     if (!processDict.ContainsKey((int)processId))
+     {
+         processDict.Add((int)processId, windowTitle);
+     }
+ }
+ catch (Exception)
+ {
+     // If process has exited, ignore and continue enumerating
+ }
🧹 Nitpick comments (4)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessResult.cs (1)

21-25: Good read-only properties for external access.

Providing Title, TitleMatch, and Tooltip as read-only properties makes the model more robust and predictable. Consider adding short doc comments summarizing each property’s purpose for maintainability.

Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (1)

144-145: Repeated re-query could affect responsiveness for multiple process kills.

Calling _context.API.ReQuery() once per kill updates results dynamically, but for many kills in quick succession, this might degrade responsiveness. Consider deferring re-query until all kills are complete or providing a batch-kill mode.

Also applies to: 169-171

Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (2)

14-35: Treating Flow Launcher as a system process.

Excluding Flow Launcher from termination is consistent with the PR objective. If there's ever a need for advanced users to kill Flow Launcher, you could make this configurable rather than hardcoded in _systemProcessList.


116-129: Exception logging is comprehensive.

The TryKill method logs any failure to kill the process with context. This ensures traceability for users without halting the workflow. If partial kills are common, consider whether to continue or abort subsequent kills in the calling code.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ee2d48 and f25c5b9.

📒 Files selected for processing (4)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Flow.Launcher.Plugin.ProcessKiller.csproj (0 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (4 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (5 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessResult.cs (1 hunks)
💤 Files with no reviewable changes (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Flow.Launcher.Plugin.ProcessKiller.csproj
🔇 Additional comments (7)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessResult.cs (2)

2-2: Use of new SharedModels namespace.

The using Flow.Launcher.Plugin.SharedModels; statement correctly provides access to MatchResult. There are no immediate concerns here, given that MatchResult is appropriately referenced in the constructor and property.


8-14: Constructor signature aligns well with new data needs.

The updated constructor appropriately captures the new parameters (title, match, and tooltip) and stores them in read-only properties, ensuring immutability. This is a clean approach to aggregating process data (score, match information, etc.) in one place.

Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (2)

9-9: Read-only initialization of ProcessHelper.

Declaring processHelper as readonly with the concise object instantiation improves immutability and readability. This is a good modern C# practice.


72-125:

❓ Verification inconclusive

Consider potential performance impact with large process lists.

Applying fuzzy scoring to every process and enumerating all windows can be expensive if hundreds of processes are running or if repeated frequently. If performance becomes a concern, consider caching or partial searching.


🏁 Script executed:

#!/bin/bash
# Description: Basic check for how many processes might typically exist on this system when enumerating
# This can inform whether fuzzy search might be a bottleneck.

# Attempt to see how many lines of active processes exist
ps aux | wc -l

Length of output: 111


Action Required: Evaluate potential performance overhead with high process counts.

The current implementation applies fuzzy search on all processes and intensity could increase with a high number of processes. Although typical systems might not trigger a problem, if hundreds of processes exist or the operation is repeated frequently, consider profiling and caching fuzzy search results or limiting the search scope to prevent performance degradation.

Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (3)

38-43: Useful utility for combining process name and ID.

GetProcessNameIdTitle is a convenient helper. Watch for edge cases if a process unexpectedly terminates before printing its name/ID. Typically, it’s fine as is, but you could add defensive checks if you suspect concurrency issues.


48-60: Unfiltered list of user processes.

GetMatchingProcesses returns all non-system processes without window constraints, aligning with the plugin’s design. If future requirements arise (e.g., ignoring background tasks lacking windows), filter them here to keep logic cohesive.


93-105: Efficient approach to retrieve window titles.

Using a capacity-based buffer with Span<char> is a good approach. Just ensure the overhead remains minimal for very large windows’ text. This is typically fine as the maximum title length is not too large in practice.

Copy link

@check-spelling-bot Report

🔴 Please review

See the 📂 files view, the 📜action log, or 📝 job summary for details.

❌ Errors Count
❌ forbidden-pattern 22
⚠️ ignored-expect-variant 1
⚠️ non-alpha-in-dictionary 19

See ❌ Event descriptions for more information.

If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
5 min review enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants