Skip to content

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

New issue

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

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

Already on GitHub? # to your account

Merged

Conversation

PaulPSta
Copy link
Contributor

@PaulPSta PaulPSta commented Dec 27, 2024

Add New Option to 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.

Do not kill FL Process

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

Test

image

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.
Plugins/Flow.Launcher.Plugin.ProcessKiller/Languages/en.xaml - Reformatted <ResourceDictionary> and added new string resource for process visibility.
Plugins/Flow.Launcher.Plugin.ProcessKiller/Settings.cs - Introduced Settings class with a boolean property PutVisibleWindowProcessesTop.
Plugins/Flow.Launcher.Plugin.ProcessKiller/ViewModels/SettingsViewModel.cs - Added SettingsViewModel class with a property to manage PutVisibleWindowProcessesTop.
Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml - Created SettingsControl user control with a CheckBox for toggling process visibility.
Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml.cs - Implemented SettingsControl class to serve as the settings interface.

Possibly related PRs

Suggested labels

kind/ui, 20 min review

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! 🔪

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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
Member

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

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.

This comment has been minimized.

This comment has been minimized.

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 (3)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml (1)

12-12: Remove empty Grid.ColumnDefinitions element if not needed.

The Grid.ColumnDefinitions element is empty. If you're not planning to define any columns, consider removing this line for cleaner code.

    <Grid Margin="{StaticResource SettingPanelMargin}">
-        <Grid.ColumnDefinitions />
        <Grid.RowDefinitions>
Plugins/Flow.Launcher.Plugin.ProcessKiller/ViewModels/SettingsViewModel.cs (1)

5-5: Consider making the Settings property setter private.

The Settings property setter is public but only used in the constructor. To prevent unintended modification of the Settings object, consider making the setter private.

-    public Settings Settings { get; set; }
+    public Settings Settings { get; private set; }
Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (1)

16-18: Consider encapsulation for Settings property.

The Settings field is declared as internal, which exposes it to other classes in the assembly. Consider making it private with a property accessor to better control access.

-internal Settings Settings;
+private Settings _settings;
+internal Settings Settings => _settings;
📜 Review details

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

📥 Commits

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

📒 Files selected for processing (6)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Languages/en.xaml (2 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (4 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Settings.cs (1 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/ViewModels/SettingsViewModel.cs (1 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml (1 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml.cs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Settings.cs
🧰 Additional context used
🧬 Code Definitions (2)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ViewModels/SettingsViewModel.cs (1)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Settings.cs (1)
  • Settings (3-6)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Main.cs (4)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessHelper.cs (5)
  • ProcessHelper (13-166)
  • TryKill (122-136)
  • List (54-66)
  • GetProcessNameIdTitle (42-49)
  • TryGetProcessFilename (138-165)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Settings.cs (1)
  • Settings (3-6)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ViewModels/SettingsViewModel.cs (2)
  • SettingsViewModel (3-17)
  • SettingsViewModel (7-10)
Plugins/Flow.Launcher.Plugin.ProcessKiller/ProcessResult.cs (2)
  • ProcessResult (6-26)
  • ProcessResult (8-15)
🔇 Additional comments (17)
Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml.cs (1)

1-18: Clean implementation of MVVM pattern.

The code-behind for the SettingsControl follows good MVVM practices by initializing components and properly setting up data binding. The class correctly takes a ViewModel instance through constructor injection and sets it as the DataContext.

Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml (1)

1-22: Well-structured XAML with proper data binding.

The XAML file defines a clean UI for toggling the "Put processes with visible windows on top" setting.

Plugins/Flow.Launcher.Plugin.ProcessKiller/Languages/en.xaml (2)

1-4: Improved XAML readability with multi-line formatting.

The ResourceDictionary opening tag has been reformatted to a multi-line style, which improves readability.


13-14: Clear and descriptive string resource for new feature.

The new string resource clearly describes the functionality and follows the existing naming convention pattern.

Plugins/Flow.Launcher.Plugin.ProcessKiller/ViewModels/SettingsViewModel.cs (1)

1-18: Good ViewModel implementation with property delegation.

The ViewModel correctly implements the MVVM pattern by delegating property access to the underlying Settings model.

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

10-10: Well-structured interface implementation.

The class now implements ISettingProvider which is appropriate for adding user settings capability to the plugin. This follows the Flow Launcher plugin architecture pattern for settings management.


12-12: Good use of readonly and new C# initialization syntax.

Using readonly for the processHelper prevents accidental reassignment, and the new C# shorthand initialization syntax makes the code more concise.


23-24: Good initialization of settings and view model.

The code properly loads settings from JSON storage and initializes the view model, following MVVM pattern principles.


74-79: Avoid returning null when no processes exist.

Currently, the method returns null if allPocessList.Any() is false. Returning an empty list instead of null helps prevent NullReferenceException issues for callers that iterate or manipulate the results without explicit null checks.

-if (!allPocessList.Any())
-{
-    return null;
-}
+if (!allPocessList.Any())
-{
-    return new List<Result>();
-}

85-102: Good implementation for non-filtered process display.

The code properly handles displaying all processes when no search term is provided, with special handling for processes with visible windows. The approach is clear and maintainable.


109-126: Well-implemented prioritization for processes with visible windows.

The code effectively implements the core feature of prioritizing processes with visible windows. It calculates scores based on both window titles and process names, then applies a boost to processes with visible windows when the setting is enabled.


147-151: Good use of ProcessResult properties for result display.

The code properly uses the new properties from the ProcessResult class, improving encapsulation and making the code more maintainable.


156-158: Improved user experience by keeping the window open.

Replacing ChangeQuery() with ReQuery() and returning false allows the user to kill multiple processes without closing the window, which enhances the user experience as mentioned in the PR comments.


163-164: Clear documentation for result ordering.

The comment explicitly states that results are ordered by process name for processes without visible windows, which improves code readability and maintainability.


169-169: Updated condition for "kill all" option.

The condition for adding the quick option to kill all instances correctly uses the new searchTerm variable, maintaining consistency with the refactored code.


181-184: Improved process killing with context.

The code now correctly passes the context to TryKill method and uses ReQuery() to refresh the process list, which provides better error handling and user experience.


192-195: Well-implemented settings panel.

The CreateSettingPanel method properly implements the ISettingProvider interface by returning a new SettingsControl initialized with the view model. This follows the MVVM pattern.

@Jack251970 Jack251970 requested a review from onesounds March 26, 2025 07:41
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.

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

61-64: Removal of the Infrastructure Project Reference

The removal of the project reference to Flow.Launcher.Infrastructure.csproj is an intentional change. It is important to verify that any functionality previously obtained from the Infrastructure project is either now embedded directly in the plugin or is no longer needed. Please confirm that this change does not break any shared functionality that the plugin might have depended on.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f0641a and f2e5006.

📒 Files selected for processing (3)
  • Plugins/Flow.Launcher.Plugin.PluginsManager/Views/PluginsManagerSettings.xaml.cs (2 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Flow.Launcher.Plugin.ProcessKiller.csproj (1 hunks)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Plugins/Flow.Launcher.Plugin.ProcessKiller/Views/SettingsControl.xaml.cs
🔇 Additional comments (3)
Plugins/Flow.Launcher.Plugin.PluginsManager/Views/PluginsManagerSettings.xaml.cs (2)

14-14: Clean code improvement - simplified property access.

Removing the explicit this qualifier makes the code cleaner while maintaining identical functionality. This follows modern C# style conventions where the this keyword is only used when necessary to disambiguate variable names.


10-15: Good refactoring - removing unnecessary class field.

The code now directly assigns the viewModel to DataContext without storing it as a class field. This is a positive change that:

  1. Reduces memory usage (even if minimal)
  2. Simplifies the class structure
  3. Follows the principle of not keeping references you don't need

Since the viewModel is only used to set the DataContext and not referenced elsewhere in the class, this refactoring improves code quality without changing functionality.

Plugins/Flow.Launcher.Plugin.ProcessKiller/Flow.Launcher.Plugin.ProcessKiller.csproj (1)

16-16: Addition of <UseWPF> Property

The inclusion of <UseWPF>true</UseWPF> clearly signals that the project now leverages WPF capabilities, which will support new or enhanced UI components. Please ensure that any required WPF-specific dependencies or resources are properly managed in the project configuration.

@onesounds
Copy link
Contributor

@Jack251970 This PR generally works well as intended. The handling to prevent the window from closing after executing kill (by the way, are there any other plugins that behave this way?) is a bit questionable, but it seems acceptable.

Regarding the behavior of keeping the window open:

It might be worth making this functionality common/shared so that other plugins can use it as well. Depending on the plugin or command, there might be a need for a setting that determines whether to keep the window open or not.

This might need to be provided as a global default option in Flow itself. (There have been many requests for an "always on top" setting, which could be related.)

Considering these two points, if there are no other issues, I think it's fine to merge.

@Jack251970
Copy link
Member

Jack251970 commented Mar 26, 2025

@Jack251970 This PR generally works well as intended. The handling to prevent the window from closing after executing kill (by the way, are there any other plugins that behave this way?) is a bit questionable, but it seems acceptable.

Regarding the behavior of keeping the window open:

It might be worth making this functionality common/shared so that other plugins can use it as well. Depending on the plugin or command, there might be a need for a setting that determines whether to keep the window open or not.

This might need to be provided as a global default option in Flow itself. (There have been many requests for an "always on top" setting, which could be related.)

Considering these two points, if there are no other issues, I think it's fine to merge.

Thanks for your review. The reason I keep window open is that users may want to close many processes at one time. I have changed other results to this behavior like Pin to the topmost (#3203)

@Jack251970
Copy link
Member

Jack251970 commented Mar 26, 2025

Regarding the behavior of keeping the window open:

It might be worth making this functionality common/shared so that other plugins can use it as well. Depending on the plugin or command, there might be a need for a setting that determines whether to keep the window open or not.

This might need to be provided as a global default option in Flow itself. (There have been many requests for an "always on top" setting, which could be related.)

@onesounds Sorry, I think we do not need to provide this in FL settings. For majority of commands, plugin developers can decide whether these options will be triggered twice so that they know if they need to hide main window or not after this action. For example, Copy to clipboard will not be triggered twice because users need to paste the content before copying other results; Kill one process need to be triggered twice because users may want to kill many processes.

Additionally, if we hide main window after triggering Kill one process, users need to open main window every time for each process which can be more painful that just hide main window one time if they just want to kill one processes

@Jack251970 Jack251970 dismissed taooceros’s stale review March 26, 2025 11:36

Already resolved

@Jack251970 Jack251970 merged commit 773fb8d into Flow-Launcher:dev Mar 26, 2025
4 checks passed
@Jack251970
Copy link
Member

@PaulPSta Thanks for your idea!

@onesounds
Copy link
Contributor

onesounds commented Mar 26, 2025

@Jack251970

  1. I'm talking about the default UX here. "When a user selects an item from the list and presses Enter, the item is executed and the FLOW window closes"—this is a common behavior across all plugins, right? (As I asked above, are there any other plugins that behave differently? I’m genuinely asking because I don’t know. If each plugin is handling this on its own, then I guess it’s fine to do it this way too.) If this plugin is the only one doing it differently, then it's essentially changing the default UX, which is what concerns me. Again, if there are other plugins (like the clipboard plugin?) that already do this, then I’m okay with it. There was a discussion in the past about giving plugins the ability to decide whether or not to close the window. I remember having a long conversation with Garulf about this, and you could probably find it if you look it up. I’m not sure if any plugin actually implemented it. I agree that it should vary depending on the functionality of the plugin.

  2. I totally agree with the point that "it’s inconvenient to have to reopen the window every time just to kill a single process." But that said, I think it’s a bit risky to change the UX based solely on that. This change assumes that users will more often want to kill multiple processes rather than just one. But that's a dangerous assumption. It might turn out that more users actually just want to kill a single process—we don’t really know. Imagine a user who’s used to the old behavior, inefficient as it is, and is now confused: "Why doesn't the window close anymore when I press Enter after killing a process?" For that user, a one-step action becomes a two-step UX (pressing ESC after Enter). If it were up to me, I’d consider something like having two separate commands—kill and kills—or having an option like "prevent window from closing after execution," and just setting it to "on" by default.

  3. Regarding always-on-top functionality, there were discussions and several requests around that—like with Everything Toolbar (https://github.com/srwi/EverythingToolbar). In such a case, even if a plugin tries to close the window, Flow itself should not close it.

Anyway, separate from all that, I personally think this PR is fine to merge as-is. As you know, I’m not that familiar with the current implementation, so I just wanted to mention things like 3 as potential future ideas, or 2 in case the behavior differs across plugins, which could make things harder to manage later on.

@Jack251970
Copy link
Member

@onesounds Agreed for 1. I reverted to origin in #3387.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants