ronantakizawa/codereview-bench huggingface dataset:
Repository: files-community/Files
File: src/Files.App.Controls/Sidebar/ISidebarItemModel.cs (C#)

Code before:
		/// </summary>
		IconSource? IconSource { get; }

		/// <summary>
		/// Item decorator for the given item.
		/// </summary>
		FrameworkElement? ItemDecorator { get => null; }

		/// <summary>
		/// Determines whether the SidebarItem is expanded and the children are visible 
		/// or if it is collapsed and children are not visible.
		/// </summary>
		bool IsExpanded { get; set; }

		/// <summary>
		/// The text of this item that will be rendered as the label of the SidebarItem
		/// </summary>
		string Text { get; }

		/// <summary>
		/// The tooltip used when hovering over this item in the sidebar
		/// </summary>
		object ToolTip { get; }

		/// <summary>
		/// Indicates whether the children should have be indentet or not.
		bool PaddedItem { get; }
		/// </summary>
	}
}


Review comment (suggestion):
```suggestion
		/// Indicates whether the children should have an indentation or not.
```

Code after:
		/// </summary>
		IconSource? IconSource { get; }

		/// <summary>
		/// Item decorator for the given item.
		/// </summary>
		FrameworkElement? ItemDecorator { get => null; }

		/// <summary>
		/// Determines whether the SidebarItem is expanded and the children are visible 
		/// or if it is collapsed and children are not visible.
		/// </summary>
		bool IsExpanded { get; set; }

		/// <summary>
		/// The text of this item that will be rendered as the label of the SidebarItem
		/// </summary>
		string Text { get; }

		/// <summary>
		/// The tooltip used when hovering over this item in the sidebar
		/// </summary>
		object ToolTip { get; }

		/// <summary>
		/// Indicates whether the children should have an indentation or not.
		/// </summary>
		bool PaddedItem { get; }
	}
}
Repository: files-community/Files
File: src/Files.App.Controls/Sidebar/SidebarItem.cs (C#)

Code before:
					SetFlyoutOpen(false);
					break;
				case SidebarDisplayMode.Minimal:
					UpdateExpansionState(useAnimations);
					SetFlyoutOpen(false);
					break;
				case SidebarDisplayMode.Compact:
					UpdateExpansionState(useAnimations);
					UpdateSelectionState();
					break;
			}
			if (!IsInFlyout)
			{
				VisualStateManager.GoToState(this, DisplayMode == SidebarDisplayMode.Compact ? "Compact" : "NonCompact", true);
			}
		}

		private void UpdateSelectionState()
		{
			VisualStateManager.GoToState(this, ShouldShowSelectionIndicator() ? "Selected" : "Unselected", true);
			UpdatePointerState();
		}

		private void UpdateIcon()
		{
			Icon = Item?.IconSource?.CreateIconElement(); 
			if (Icon is not null)
				AutomationProperties.SetAccessibilityView(Icon, AccessibilityView.Raw);
		}

		private bool ShouldShowSelectionIndicator()
		{
			if (IsExpanded && CollapseEnabled)
			{
				return IsSelected;
			}
			else
			{
				return IsSelected || hasChildSelection;
			}
		}

		private void UpdatePointerState(bool isPointerDown = false)
		{
			var useSelectedState = ShouldShowSelectionIndicator();
			if (isPointerDown)
			{
				VisualStateManager.GoToState(this, useSelectedState ? "PressedSelected" : "Pressed", true);
			}
			else if (isPointerOver)
			{

Review comment (suggestion):
```suggestion
			Icon = Item?.IconSource?.CreateIconElement();
```

Code after:
					SetFlyoutOpen(false);
					break;
				case SidebarDisplayMode.Minimal:
					UpdateExpansionState(useAnimations);
					SetFlyoutOpen(false);
					break;
				case SidebarDisplayMode.Compact:
					UpdateExpansionState(useAnimations);
					UpdateSelectionState();
					break;
			}
			if (!IsInFlyout)
			{
				VisualStateManager.GoToState(this, DisplayMode == SidebarDisplayMode.Compact ? "Compact" : "NonCompact", true);
			}
		}

		private void UpdateSelectionState()
		{
			VisualStateManager.GoToState(this, ShouldShowSelectionIndicator() ? "Selected" : "Unselected", true);
			UpdatePointerState();
		}

		private void UpdateIcon()
		{
			Icon = Item?.IconSource?.CreateIconElement();
			if (Icon is not null)
				AutomationProperties.SetAccessibilityView(Icon, AccessibilityView.Raw);
		}

		private bool ShouldShowSelectionIndicator()
		{
			if (IsExpanded && CollapseEnabled)
			{
				return IsSelected;
			}
			else
			{
				return IsSelected || hasChildSelection;
			}
		}

		private void UpdatePointerState(bool isPointerDown = false)
		{
			var useSelectedState = ShouldShowSelectionIndicator();
			if (isPointerDown)
			{
				VisualStateManager.GoToState(this, useSelectedState ? "PressedSelected" : "Pressed", true);
			}
			else if (isPointerOver)
			{
Repository: files-community/Files
File: src/Files.App.Controls/Sidebar/ISidebarItemModel.cs (C#)

Code before:

		/// <summary>
		/// Item decorator for the given item.
		/// </summary>
		FrameworkElement? ItemDecorator { get => null; }

		/// <summary>
		/// Determines whether the SidebarItem is expanded and the children are visible 
		/// or if it is collapsed and children are not visible.
		/// </summary>
		bool IsExpanded { get; set; }

		/// <summary>
		/// The text of this item that will be rendered as the label of the SidebarItem
		/// </summary>
		string Text { get; }

		/// <summary>
		/// The tooltip used when hovering over this item in the sidebar
		/// </summary>
		object ToolTip { get; }

		/// <summary>
		/// Indicates whether the children should have an indentation or not.
		bool PaddedItem { get; }
		/// </summary>
	}
}


Review comment (suggestion):
```suggestion
		/// </summary>
		bool PaddedItem { get; }
```

Code after:

		/// <summary>
		/// Item decorator for the given item.
		/// </summary>
		FrameworkElement? ItemDecorator { get => null; }

		/// <summary>
		/// Determines whether the SidebarItem is expanded and the children are visible 
		/// or if it is collapsed and children are not visible.
		/// </summary>
		bool IsExpanded { get; set; }

		/// <summary>
		/// The text of this item that will be rendered as the label of the SidebarItem
		/// </summary>
		string Text { get; }

		/// <summary>
		/// The tooltip used when hovering over this item in the sidebar
		/// </summary>
		object ToolTip { get; }

		/// <summary>
		/// Indicates whether the children should have an indentation or not.
		/// </summary>
		bool PaddedItem { get; }
	}
}
Repository: files-community/Files
File: src/Files.App/ViewModels/UserControls/Previews/ShellPreviewViewModel.cs (C#)

Code before:
				}
			}
			else if (msg is PInvoke.WM_DESTROY)
			{
				if (_previewHandler is not null)
				{
					_previewHandler.Dispose();
					_previewHandler = null;
				}
			}

			return PInvoke.DefWindowProc(hwnd, msg, wParam, lParam);
		}

		public unsafe void LoadPreview(UIElement presenter)
		{
			var parent = MainWindow.Instance.WindowHandle;
			var hInst = PInvoke.GetModuleHandle(default(PWSTR));
			var szClassName = $"{GetType().Name}-{Guid.NewGuid()}";
			var szWindowName = $"Preview";

			fixed (char* pszClassName = szClassName)
			{
				_windProc = new(WndProc);
				var pWindProc = Marshal.GetFunctionPointerForDelegate(_windProc);
				var pfnWndProc = (delegate* unmanaged[Stdcall]<HWND, uint, WPARAM, LPARAM, LRESULT>)pWindProc;

				_windowClass = new WNDCLASSEXW()
				{
					cbSize = (uint)sizeof(WNDCLASSEXW),
					lpfnWndProc = pfnWndProc,
					hInstance = hInst,
					lpszClassName = pszClassName,
					style = 0,
					hIcon = default,
					hIconSm = default,
					hCursor = default,
					hbrBackground = default,
					lpszMenuName = null,
					cbClsExtra = 0,
					cbWndExtra = 0,
				};

				PInvoke.RegisterClassEx(_windowClass);

				fixed (char* pszWindowName = szWindowName)
				{
					_hWnd = PInvoke.CreateWindowEx(
						WINDOW_EX_STYLE.WS_EX_LAYERED | WINDOW_EX_STYLE.WS_EX_COMPOSITED,
						pszClassName,
						pszWindowName,

Review comment (refactor):
I would like to avoid using `GetFunctionPointerForDelegate`. Instead, marking `WndProc` as static and `UnmanagedCallersOnly` and taking a function pointer from it directly.
While we don't need to do it immediately in this PR as it may require some refactor to `WndProc.`

Code after:
				}
			}
			else if (msg is PInvoke.WM_DESTROY)
			{
				if (_previewHandler is not null)
				{
					_previewHandler.Dispose();
					_previewHandler = null;
				}
			}

			return PInvoke.DefWindowProc(hwnd, msg, wParam, lParam);
		}

		public unsafe void LoadPreview(UIElement presenter)
		{
			var parent = MainWindow.Instance.WindowHandle;
			var hInst = PInvoke.GetModuleHandle(default(PWSTR));
			var szClassName = $"{nameof(ShellPreviewViewModel)}-{Guid.NewGuid()}";
			var szWindowName = $"Preview";

			fixed (char* pszClassName = szClassName)
			{
				_windProc = new(WndProc);
				var pWindProc = Marshal.GetFunctionPointerForDelegate(_windProc);
				var pfnWndProc = (delegate* unmanaged[Stdcall]<HWND, uint, WPARAM, LPARAM, LRESULT>)pWindProc;

				_windowClass = new WNDCLASSEXW()
				{
					cbSize = (uint)sizeof(WNDCLASSEXW),
					lpfnWndProc = pfnWndProc,
					hInstance = hInst,
					lpszClassName = pszClassName,
					style = 0,
					hIcon = default,
					hIconSm = default,
					hCursor = default,
					hbrBackground = default,
					lpszMenuName = null,
					cbClsExtra = 0,
					cbWndExtra = 0,
				};

				PInvoke.RegisterClassEx(_windowClass);

				fixed (char* pszWindowName = szWindowName)
				{
					_hWnd = PInvoke.CreateWindowEx(
						WINDOW_EX_STYLE.WS_EX_LAYERED | WINDOW_EX_STYLE.WS_EX_COMPOSITED,
						pszClassName,
						pszWindowName,
Repository: files-community/Files
File: src/Files.App/Actions/Open/OpenSettingsFileAction.cs (C#)

Code before:
// Licensed under the MIT License.

using Windows.Storage;
using Windows.System;

namespace Files.App.Actions
{
	internal sealed partial class OpenSettingsFileAction :  IAction
	{
		public string Label
			=> Strings.EditSettingsFile.GetLocalizedResource();

		public string Description
			=> Strings.EditSettingsFileDescription.GetLocalizedResource();

		public HotKey HotKey
			=> new(Keys.OemComma, KeyModifiers.CtrlShift);

		public RichGlyph Glyph
			=> new("\uE8DA");

		public async Task ExecuteAsync(object? parameter = null)
		{
			await SafetyExtensions.IgnoreExceptions(async () =>
			{
				var settingsJsonFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/settings/user_settings.json"));
				if (!await Launcher.LaunchFileAsync(settingsJsonFile))
					await ContextMenu.InvokeVerb("open", settingsJsonFile.Path);
			});
		}
	}
}


Review comment (suggestion):
Let's avoid hardcoding.

```suggestion
				var settingsJsonFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appdata:///local/{Constants.LocalSettings.SettingsFolderName}/{Constants.LocalSettings.UserSettingsFileName}"));
```

Code after:
// Licensed under the MIT License.

using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Windows.Foundation.Metadata;
using Windows.Storage;
using Windows.System;

namespace Files.App.Actions
{
	internal sealed partial class OpenSettingsFileAction : IAction
	{
		public string Label
			=> Strings.EditSettingsFile.GetLocalizedResource();

		public string Description
			=> Strings.EditSettingsFileDescription.GetLocalizedResource();

		public HotKey HotKey
			=> new(Keys.OemComma, KeyModifiers.CtrlShift);

		public RichGlyph Glyph
			=> new("\uE8DA");

		public async Task ExecuteAsync(object? parameter = null)
		{
			try
			{
				var settingsJsonFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appdata:///local/{Constants.LocalSettings.SettingsFolderName}/{Constants.LocalSettings.UserSettingsFileName}"));
				if (!await Launcher.LaunchFileAsync(settingsJsonFile))
					await ContextMenu.InvokeVerb("open", settingsJsonFile.Path);
			}
			catch (Exception ex)
			{
				// Only show the error dialog if no other popups are open
				if (!VisualTreeHelper.GetOpenPopupsForXamlRoot(MainWindow.Instance.Content.XamlRoot).Any())
				{
					var errorDialog = new ContentDialog()
					{
						Title = Strings.FailedToOpenSettingsFile.GetLocalizedResource(),
						Content = ex.Message,
						PrimaryButtonText = Strings.OK.GetLocalizedResource(),
					};

					if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
						errorDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot;

					await errorDialog.TryShowAsync();
				}
			}
		}
Repository: files-community/Files
File: src/Files.App/Data/Items/EncodingItem.cs (C#)

Code before:

namespace Files.App.Data.Items
{
    /// <summary>
    /// Represents a text encoding in the application.
    /// </summary>
    public sealed class EncodingItem
    {

        public Encoding? Encoding { get; set; }

        /// <summary>
        /// Gets the encoding name. e.g. English (United States)
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="EncodingItem"/> class.
        /// </summary>
        /// <param name="code">The code of the language.</param>
        public EncodingItem(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                Encoding = null;
                Name = "ArchiveEncodingSystemDefault".GetLocalizedResource();
            }
            else
            {
                Encoding = Encoding.GetEncoding(code);
                Name = Encoding.EncodingName;
            }
        }

        public override string ToString() => Name;
    }
}


Review comment (suggestion):
```suggestion
                Name = Strings.Default.GetLocalizedResource();
```

Code after:

namespace Files.App.Data.Items
{
    /// <summary>
    /// Represents a text encoding in the application.
    /// </summary>
    public sealed class EncodingItem
    {

        public Encoding? Encoding { get; set; }

        /// <summary>
        /// Gets the encoding name. e.g. English (United States)
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="EncodingItem"/> class.
        /// </summary>
        /// <param name="code">The code of the language.</param>
        public EncodingItem(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                Encoding = null;
                Name = Strings.Default.GetLocalizedResource();
            }
            else
            {
                Encoding = Encoding.GetEncoding(code);
                Name = Encoding.EncodingName;
            }
        }

        public override string ToString() => Name;
    }
}
Repository: files-community/Files
File: src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.cs (C#)

Code before:
			get => detectedEncoding;
			set { 
				SetProperty(ref detectedEncoding, value);
				RefreshEncodingOptions();
			}
		}

		private bool showPathSelection;
		public bool ShowPathSelection
		{
			get => showPathSelection;
			set => SetProperty(ref showPathSelection, value);
		}

		public DisposableArray? Password { get; private set; }

		public EncodingItem[] EncodingOptions { get; set; } = EncodingItem.Defaults;
		public EncodingItem SelectedEncoding { get; set; }
		void RefreshEncodingOptions()
		{
			if (detectedEncoding != null)
			{
				EncodingOptions = EncodingItem.Defaults
				.Prepend(new EncodingItem(
					detectedEncoding, 
					detectedEncoding.EncodingName + Strings.EncodingDetected.GetLocalizedResource())
				)
				.ToArray();
			}
			else
			{
				EncodingOptions = EncodingItem.Defaults;
			}
			SelectedEncoding = EncodingOptions.FirstOrDefault();
		}

		

		public IRelayCommand PrimaryButtonClickCommand { get; private set; }

		public ICommand SelectDestinationCommand { get; private set; }

		public DecompressArchiveDialogViewModel(IStorageFile archive)
		{
			this.archive = archive;
			destinationFolderPath = DefaultDestinationFolderPath();
			SelectedEncoding = EncodingOptions[0];

			// Create commands
			SelectDestinationCommand = new AsyncRelayCommand(SelectDestinationAsync);
			PrimaryButtonClickCommand = new RelayCommand<DisposableArray>(password => Password = password);

Review comment (suggestion):
```suggestion
					string.Format(Strings.EncodingDetected.GetLocalizedResource(), detectedEncoding.EncodingName)
```

Code after:
			get => detectedEncoding;
			set { 
				SetProperty(ref detectedEncoding, value);
				RefreshEncodingOptions();
			}
		}

		private bool showPathSelection;
		public bool ShowPathSelection
		{
			get => showPathSelection;
			set => SetProperty(ref showPathSelection, value);
		}

		public DisposableArray? Password { get; private set; }

		public EncodingItem[] EncodingOptions { get; set; } = EncodingItem.Defaults;
		public EncodingItem SelectedEncoding { get; set; }
		void RefreshEncodingOptions()
		{
			if (detectedEncoding != null)
			{
				EncodingOptions = EncodingItem.Defaults
				.Prepend(new EncodingItem(
					detectedEncoding, 
					string.Format(Strings.EncodingDetected.GetLocalizedResource(), detectedEncoding.EncodingName)
				))
				.ToArray();
			}
			else
			{
				EncodingOptions = EncodingItem.Defaults;
			}
			SelectedEncoding = EncodingOptions.FirstOrDefault();
		}

		

		public IRelayCommand PrimaryButtonClickCommand { get; private set; }

		public ICommand SelectDestinationCommand { get; private set; }

		public DecompressArchiveDialogViewModel(IStorageFile archive)
		{
			this.archive = archive;
			destinationFolderPath = DefaultDestinationFolderPath();
			SelectedEncoding = EncodingOptions[0];

			// Create commands
			SelectDestinationCommand = new AsyncRelayCommand(SelectDestinationAsync);
			PrimaryButtonClickCommand = new RelayCommand<DisposableArray>(password => Password = password);
Repository: files-community/Files
File: src/Files.App/Views/Shells/ModernShellPage.xaml.cs (C#)

Code before:
					new NavigationArguments()
					{
						NavPathParam = navigationPath,
						AssociatedTabInstance = this
					},
					new SuppressNavigationTransitionInfo());
			}

			ToolbarViewModel.PathControlDisplayText = ShellViewModel.WorkingDirectory;
		}

		private async void FilterTextBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
		{
			if (args.Reason is AutoSuggestionBoxTextChangeReason.UserInput)
			{
				ShellViewModel.FilesAndFoldersFilter = sender.Text;
				await ShellViewModel.ApplyFilesAndFoldersChangesAsync();
			}

		}

		private void FilterTextBox_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
		{
			if (e.Key is VirtualKey.Escape &&
				SlimContentPage is BaseGroupableLayoutPage svb &&
				svb.IsLoaded)
				SlimContentPage.ItemManipulationModel.FocusFileList();
		}
	}
}


Review comment (suggestion):
```suggestion
				SlimContentPage is BaseGroupableLayoutPage { IsLoaded: true } svb)
```

Code after:
					new NavigationArguments()
					{
						NavPathParam = navigationPath,
						AssociatedTabInstance = this
					},
					new SuppressNavigationTransitionInfo());
			}

			ToolbarViewModel.PathControlDisplayText = ShellViewModel.WorkingDirectory;
		}

		private async void FilterTextBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
		{
			if (args.Reason is AutoSuggestionBoxTextChangeReason.UserInput)
			{
				ShellViewModel.FilesAndFoldersFilter = sender.Text;
				await ShellViewModel.ApplyFilesAndFoldersChangesAsync();
			}

		}

		private void FilterTextBox_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
		{
			if (e.Key is VirtualKey.Escape &&
				SlimContentPage is BaseGroupableLayoutPage { IsLoaded: true } svb)
				SlimContentPage.ItemManipulationModel.FocusFileList();
		}
	}
}
Repository: files-community/Files
File: src/Files.App.Controls/BladeView/BladeItem.cs (C#)

Code before:
							FontStyle = textBlock.FontStyle
						};

						measuringBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
						maxWidth = Math.Max(maxWidth, measuringBlock.DesiredSize.Width);
					}
				}
				else
				{
					// Fallback: estimate based on item count and average text width
					var itemCount = listView.Items.Count;
					if (itemCount > 0)
					{
						// Estimate average filename length and multiply by character width
						var estimatedCharWidth = 8; // Approximate pixel width per character
						var estimatedMaxLength = Math.Min(50, Math.Max(20, itemCount * 2)); // Heuristic
						maxWidth = estimatedCharWidth * estimatedMaxLength;
					}
				}

				return maxWidth;
			}
			catch (Exception ex)
			{
				Debug.WriteLine($"Error measuring content width: {ex.Message}");
				// Fallback calculation
				return 200; // Default reasonable width
			}
		}
		private List<TextBlock> GetTextBlocksFromVisualTree(DependencyObject parent)
		{
			var textBlocks = new List<TextBlock>();

			if (parent == null)
				return textBlocks;

			try
			{
				var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
				for (int i = 0; i < childrenCount; i++)
				{
					var child = VisualTreeHelper.GetChild(parent, i);

					if (child is TextBlock textBlock)
					{
						textBlocks.Add(textBlock);
					}

					// Recursively search child elements
					textBlocks.AddRange(GetTextBlocksFromVisualTree(child));
				}

Review comment (suggestion):
```suggestion

		private List<TextBlock> GetTextBlocksFromVisualTree(DependencyObject parent)
```

Code after:
						maxWidth = Math.Max(maxWidth, measuringBlock.DesiredSize.Width);
					}
				}
				else
				{
					// Fallback: estimate based on item count and average text width
					var itemCount = listView.Items.Count;
					if (itemCount > 0)
					{
						// Estimate average filename length and multiply by character width
						var estimatedCharWidth = 8; // Approximate pixel width per character
						var estimatedMaxLength = Math.Min(50, Math.Max(20, itemCount * 2)); // Heuristic
						maxWidth = estimatedCharWidth * estimatedMaxLength;
					}
				}

				return maxWidth;
			}
			catch (Exception)
			{
				// Fallback calculation
				return 200; // Default reasonable width
			}
		}

		private List<TextBlock> GetTextBlocksFromVisualTree(DependencyObject parent)
		{
			var textBlocks = new List<TextBlock>();

			if (parent == null)
				return textBlocks;

			var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
			for (int i = 0; i < childrenCount; i++)
			{
				var child = VisualTreeHelper.GetChild(parent, i);

				if (child is TextBlock textBlock)
				{
					textBlocks.Add(textBlock);
				}

				// Recursively search child elements
				textBlocks.AddRange(GetTextBlocksFromVisualTree(child));
			}

			return textBlocks;
		}

		private void BladeResizer_PointerEntered(object sender, PointerRoutedEventArgs e)
		{