Skip to content

Fix cast object of type 'System.Windows.Media.Color' to type 'System.Windows.Expression' exception#4302

Open
Jack251970 wants to merge 5 commits intodevfrom
copilot/fix-cast-exception-bug
Open

Fix cast object of type 'System.Windows.Media.Color' to type 'System.Windows.Expression' exception#4302
Jack251970 wants to merge 5 commits intodevfrom
copilot/fix-cast-exception-bug

Conversation

@Jack251970
Copy link
Member

@Jack251970 Jack251970 commented Feb 27, 2026

This pull request improves how brush and resource values are handled for theme styling in Flow.Launcher.Core/Resource/Theme.cs, focusing on safer management of mutable objects and resource references. The main changes enhance the way caret and background brushes are assigned, ensuring that brushes are properly frozen when possible, and that dynamic resources are referenced correctly.

Resolve #4298.

Copilot AI and others added 2 commits February 27, 2026 14:39
…validation on Windows theme change

Co-authored-by: Jack251970 <53996452+Jack251970@users.noreply.github.com>
Copilot AI review requested due to automatic review settings February 27, 2026 14:48
@prlabeler prlabeler bot added the bug Something isn't working label Feb 27, 2026
@github-actions github-actions bot added this to the 2.2.0 milestone Feb 27, 2026
@gitstream-cm
Copy link

gitstream-cm bot commented Feb 27, 2026

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

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 2 files

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60b92c5 and 5635783.

📒 Files selected for processing (1)
  • Flow.Launcher/MainWindow.xaml.cs

📝 Walkthrough

Walkthrough

Replace unsafe direct brush/style assignments with guarded creation and freezing of brushes, add a helper to derive caret brush values safely, make CopyStyle static, and conditionally refresh the frame on theme change only for System color scheme. (≈33 words)

Changes

Cohort / File(s) Summary
Theme resource and brush handling
Flow.Launcher.Core/Resource/Theme.cs
Added GetNewCaretValue(object) to compute caret brush from Foreground (handles DynamicResource, SolidColorBrush, others). Replace direct CaretBrush setter additions with conditional use of the helper. Create and Freeze SolidColorBrush instances before assigning to style/setter/background. Use safer null-conditional Foreground access. Change CopyStyle to static and adapt usages.
Main window theme refresh
Flow.Launcher/MainWindow.xaml.cs
Modify ActualApplicationThemeChanged handler to call RefreshFrameAsync only when the color scheme is System (conditional refresh).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • jjw24
  • onesounds
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main bug being fixed: the System.InvalidCastException involving Color and Expression type mismatch. It matches the core issue #4298 that the PR is designed to resolve.
Description check ✅ Passed The description is clearly related to the changeset, explaining the improvements to brush and resource handling in Theme.cs and referencing the linked issue #4298 that motivated the changes.
Linked Issues check ✅ Passed The PR successfully addresses the core objectives from #4298: it implements safer brush/resource handling by freezing brushes, uses correct dynamic resource key resolution, and limits theme refreshes to relevant scenarios.
Out of Scope Changes check ✅ Passed All changes are focused on fixing the InvalidCastException through safer brush/resource management and conditional theme refresh logic, with no unrelated modifications introduced.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch copilot/fix-cast-exception-bug

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This pull request suppresses a spurious error dialog that appears when users change Windows themes or accent colors. The error is caused by a WPF framework bug where SystemResources.InvalidateTreeResources incorrectly attempts to clone Color structs as if they were Freezable or Expression objects, resulting in an InvalidCastException that the application cannot prevent.

Changes:

  • Added IsRecoverableSystemResourceException method to detect the specific WPF system resource invalidation exception
  • Integrated the new exception check into ErrorReporting.Report to suppress the error dialog while still logging the exception
  • Added comprehensive documentation explaining the WPF framework issue

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
Flow.Launcher/Helper/ExceptionHelper.cs Added new method to detect InvalidCastException from WPF's SystemResources.InvalidateTreeResources
Flow.Launcher/Helper/ErrorReporting.cs Integrated the new exception check to prevent error dialog from being shown

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

…ource invalidation on Windows theme change"

This reverts commit 372f142.
Refactored caret and background brush assignment to avoid sharing mutable instances and ensure proper resource referencing. Added GetNewCaretValue helper for safe caret brush creation. Brushes for backgrounds are now frozen for performance. Improved foreground value retrieval and dynamic resource key extraction. Made some methods static for clarity and consistency. Enhances resource management and reliability in theme handling.
@prlabeler prlabeler bot added Code Refactor enhancement New feature or request labels Feb 28, 2026
@coderabbitai coderabbitai bot removed bug Something isn't working enhancement New feature or request labels Feb 28, 2026
@Jack251970 Jack251970 changed the title Suppress spurious error dialog on Windows theme/accent color change Fix cast object of type 'System.Windows.Media.Color' to type 'System.Windows.Expression' exception Feb 28, 2026
@Jack251970 Jack251970 requested a review from Copilot February 28, 2026 07:17
@prlabeler prlabeler bot added the bug Something isn't working label Feb 28, 2026
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
Flow.Launcher.Core/Resource/Theme.cs (1)

814-819: ⚠️ Potential issue | 🟡 Minor

Remove ToString() when looking up DynamicResource keys in ResourceDictionary.

At line 814, converting dynamicResource.ResourceKey to string via ToString() violates WPF resource lookup semantics. ResourceDictionary requires matching the actual key object (e.g., ComponentResourceKey), not its string representation. This inconsistency is evident at line 260, where the code correctly preserves ResourceKey object identity.

Proposed fix
- var resourceKey = dynamicResource.ResourceKey.ToString();
+ var resourceKey = dynamicResource.ResourceKey;

- if (Resources.Contains(resourceKey))
+ if (resourceKey != null && Resources.Contains(resourceKey))
{
    var colorResource = Resources[resourceKey];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Flow.Launcher.Core/Resource/Theme.cs` around lines 814 - 819, The code is
converting dynamicResource.ResourceKey to a string before lookup which breaks
WPF resource key identity; in the Theme.cs block around the dynamicResource
handling, stop calling ToString() and use the ResourceKey object directly when
checking and retrieving from the ResourceDictionary (i.e., replace the use of
var resourceKey = dynamicResource.ResourceKey.ToString() and subsequent
Resources.Contains(resourceKey)/Resources[resourceKey] calls with checks that
use dynamicResource.ResourceKey itself so ComponentResourceKey and other
non-string keys resolve correctly).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@Flow.Launcher.Core/Resource/Theme.cs`:
- Around line 814-819: The code is converting dynamicResource.ResourceKey to a
string before lookup which breaks WPF resource key identity; in the Theme.cs
block around the dynamicResource handling, stop calling ToString() and use the
ResourceKey object directly when checking and retrieving from the
ResourceDictionary (i.e., replace the use of var resourceKey =
dynamicResource.ResourceKey.ToString() and subsequent
Resources.Contains(resourceKey)/Resources[resourceKey] calls with checks that
use dynamicResource.ResourceKey itself so ComponentResourceKey and other
non-string keys resolve correctly).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 372f142 and 60b92c5.

📒 Files selected for processing (1)
  • Flow.Launcher.Core/Resource/Theme.cs

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Jack251970 Jack251970 enabled auto-merge February 28, 2026 07:29
Previously, the theme was refreshed on every theme change event.
Now, `_theme.RefreshFrameAsync()` is only called if the color
scheme setting is set to "System", preventing unnecessary
refreshes in other scenarios.
@gitstream-cm
Copy link

gitstream-cm bot commented Feb 28, 2026

🥷 Code experts: jjw24

jjw24, Jack251970 have most 👩‍💻 activity in the files.
Jack251970, jjw24 have most 🧠 knowledge in the files.

See details

Flow.Launcher.Core/Resource/Theme.cs

Activity based on git-commit:

jjw24 Jack251970
FEB
JAN
DEC
NOV
OCT 12 additions & 2 deletions
SEP 2 additions & 2 deletions

Knowledge based on git-blame:
jjw24: 99%
Jack251970: 1%

Flow.Launcher/MainWindow.xaml.cs

Activity based on git-commit:

jjw24 Jack251970
FEB
JAN
DEC
NOV 1 additions & 1 deletions
OCT 8 additions & 7 deletions
SEP 1547 additions & 49 deletions

Knowledge based on git-blame:
Jack251970: 100%

✨ Comment /gs review for LinearB AI review. Learn how to automate it here.

@coderabbitai coderabbitai bot removed the bug Something isn't working label Feb 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Unable to cast object of type 'System.Windows.Media.Color' to type 'System.Windows.Expression'

3 participants