<commit_before>﻿using Playnite.Common;
using Playnite.Extensions;
using Playnite.SDK;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media;
using System.Xaml;
using System.Diagnostics;
using System.Text.RegularExpressions;
using CommandLine;

namespace Playnite.Extensions.Markup
{
    public class ThemeFile : MarkupExtension
    {
        private static FileInfo lastUserTheme = null;
        private static bool? lastUserThemeFound = null;

        internal ThemeManifest CurrentTheme { get; set; }
        internal ThemeManifest DefaultTheme { get; set; }

        public string RelativePath { get; set; }

        public ThemeFile(ApplicationMode mode)
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                DefaultTheme = GetDesignTimeDefaultTheme(mode);
            }
            else
            {
                DefaultTheme = ThemeManager.DefaultTheme;
                CurrentTheme = ThemeManager.CurrentTheme;
            }
        }

        public ThemeFile(string path, ApplicationMode mode) : this(mode)
        {
            RelativePath = path;
        }

        public static ThemeManifest GetDesignTimeDefaultTheme(ApplicationMode mode)
        {
            if (lastUserThemeFound == null)
            {
                if (Process.GetCurrentProcess().TryGetParentId(out var parentId))
                {
                    var proc = Process.GetProcessById(parentId);
                    var cmdline = proc.GetCommandLine();
                    var regEx = Regex.Match(cmdline, @"([^""]+\.sln?)""");
                    if (regEx.Success)
                    {
                        var spath = regEx.Groups[1].Value;
                        if (spath.Contains($"Themes\\{mode.GetDescription()}"))
                        {
                            lastUserTheme = new FileInfo(spath);
                            lastUserThemeFound = true;
                        }
                    }
                }
            }

            if (lastUserThemeFound == true)
            {
                return new ThemeManifest()
                {
                    DirectoryName = lastUserTheme.DirectoryName,
                    DirectoryPath = lastUserTheme.Directory.FullName,
                    Name = "Default"
                };
            }

            lastUserThemeFound = false;
            var defaultTheme = "Default";
            var projectName = mode == ApplicationMode.Fullscreen ? "Playnite.FullscreenApp" : "Playnite.DesktopApp";
            var slnPath = Path.Combine(Environment.GetEnvironmentVariable("PLAYNITE_SLN", EnvironmentVariableTarget.User), projectName);
            var themePath = Path.Combine(slnPath, "Themes", ThemeManager.GetThemeRootDir(mode), defaultTheme);
            return new ThemeManifest()
            {
                DirectoryName = defaultTheme,
                DirectoryPath = themePath,
                Name = defaultTheme
            };
        }

        public static string GetFilePath(string relPath, bool checkExistance = true)
        {
            return GetFilePath(relPath, ThemeManager.DefaultTheme, ThemeManager.CurrentTheme, checkExistance);
        }

        public static string GetFilePath(string relPath, ThemeManifest defaultTheme, bool checkExistance = true)
        {
            return GetFilePath(relPath, defaultTheme, ThemeManager.CurrentTheme, checkExistance);
        }

        public static string GetFilePath(string relPath, ThemeManifest defaultTheme, ThemeManifest currentTheme, bool checkExistance = true)
        {
            var relativePath = Paths.FixSeparators(relPath).TrimStart(new char[] { Path.DirectorySeparatorChar });

            if (currentTheme != null)
            {
                var themePath = Path.Combine(currentTheme.DirectoryPath, relativePath);
                if (File.Exists(themePath) && checkExistance)
                {
                    return themePath;
                }
                else if (!checkExistance)
                {
                    return themePath;
                }
            }

            if (defaultTheme != null)
            {
                var defaultPath = Path.Combine(defaultTheme.DirectoryPath, relativePath);
                if (File.Exists(defaultPath) && checkExistance)
                {
                    return defaultPath;
                }
                else if (!checkExistance)
                {
                    return defaultPath;
                }
            }

            return null;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            string path = GetFilePath(RelativePath, DefaultTheme, CurrentTheme);
            if (path.IsNullOrEmpty())
            {
                return null;
            }

            var provider = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            var type = IProvideValueTargetExtensions.GetTargetType(provider);
            var converter = TypeDescriptor.GetConverter(type);
            return converter.ConvertFrom(path);
        }
    }
}<commit_msg>Crash when loading theme file reference<commit_after>﻿using Playnite.Common;
using Playnite.Extensions;
using Playnite.SDK;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media;
using System.Xaml;
using System.Diagnostics;
using System.Text.RegularExpressions;
using CommandLine;

namespace Playnite.Extensions.Markup
{
    public class ThemeFile : MarkupExtension
    {
        private static readonly ILogger logger = LogManager.GetLogger();
        private static FileInfo lastUserTheme = null;
        private static bool? lastUserThemeFound = null;

        internal ThemeManifest CurrentTheme { get; set; }
        internal ThemeManifest DefaultTheme { get; set; }

        public string RelativePath { get; set; }

        public ThemeFile(ApplicationMode mode)
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                DefaultTheme = GetDesignTimeDefaultTheme(mode);
            }
            else
            {
                DefaultTheme = ThemeManager.DefaultTheme;
                CurrentTheme = ThemeManager.CurrentTheme;
            }
        }

        public ThemeFile(string path, ApplicationMode mode) : this(mode)
        {
            RelativePath = path;
        }

        public static ThemeManifest GetDesignTimeDefaultTheme(ApplicationMode mode)
        {
            if (lastUserThemeFound == null)
            {
                if (Process.GetCurrentProcess().TryGetParentId(out var parentId))
                {
                    var proc = Process.GetProcessById(parentId);
                    var cmdline = proc.GetCommandLine();
                    var regEx = Regex.Match(cmdline, @"([^""]+\.sln?)""");
                    if (regEx.Success)
                    {
                        var spath = regEx.Groups[1].Value;
                        if (spath.Contains($"Themes\\{mode.GetDescription()}"))
                        {
                            lastUserTheme = new FileInfo(spath);
                            lastUserThemeFound = true;
                        }
                    }
                }
            }

            if (lastUserThemeFound == true)
            {
                return new ThemeManifest()
                {
                    DirectoryName = lastUserTheme.DirectoryName,
                    DirectoryPath = lastUserTheme.Directory.FullName,
                    Name = "Default"
                };
            }

            lastUserThemeFound = false;
            var defaultTheme = "Default";
            var projectName = mode == ApplicationMode.Fullscreen ? "Playnite.FullscreenApp" : "Playnite.DesktopApp";
            var slnPath = Path.Combine(Environment.GetEnvironmentVariable("PLAYNITE_SLN", EnvironmentVariableTarget.User), projectName);
            var themePath = Path.Combine(slnPath, "Themes", ThemeManager.GetThemeRootDir(mode), defaultTheme);
            return new ThemeManifest()
            {
                DirectoryName = defaultTheme,
                DirectoryPath = themePath,
                Name = defaultTheme
            };
        }

        public static string GetFilePath(string relPath, bool checkExistance = true)
        {
            return GetFilePath(relPath, ThemeManager.DefaultTheme, ThemeManager.CurrentTheme, checkExistance);
        }

        public static string GetFilePath(string relPath, ThemeManifest defaultTheme, bool checkExistance = true)
        {
            return GetFilePath(relPath, defaultTheme, ThemeManager.CurrentTheme, checkExistance);
        }

        public static string GetFilePath(string relPath, ThemeManifest defaultTheme, ThemeManifest currentTheme, bool checkExistance = true)
        {
            var relativePath = Paths.FixSeparators(relPath).TrimStart(new char[] { Path.DirectorySeparatorChar });

            if (currentTheme != null)
            {
                var themePath = Path.Combine(currentTheme.DirectoryPath, relativePath);
                if (File.Exists(themePath) && checkExistance)
                {
                    return themePath;
                }
                else if (!checkExistance)
                {
                    return themePath;
                }
            }

            if (defaultTheme != null)
            {
                var defaultPath = Path.Combine(defaultTheme.DirectoryPath, relativePath);
                if (File.Exists(defaultPath) && checkExistance)
                {
                    return defaultPath;
                }
                else if (!checkExistance)
                {
                    return defaultPath;
                }
            }

            return null;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            string path = GetFilePath(RelativePath, DefaultTheme, CurrentTheme);
            if (path.IsNullOrEmpty())
            {
                return null;
            }

            var provider = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            var type = IProvideValueTargetExtensions.GetTargetType(provider);
            var converter = TypeDescriptor.GetConverter(type);

            try
            {
                return converter.ConvertFrom(path);
            }
            catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
            {
                logger.Error(e, $"Failed to provide value for theme file {path}");
                return null;
            }
        }
    }
}
{'fraction_non_alphanumeric': 0.07650468123049488, 'fraction_numerical': 0.00017833259028087384, 'mean_word_length': 1.703953712632594, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3098778', 'n_tokens_mistral': 2703, 'n_tokens_neox': 2584, 'n_words': 582}