public static void AssignItemListPanel(ItemsControl itemsHost)
        {
            XNamespace pns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";

            itemsHost.ItemsPanel = Xaml.FromString <ItemsPanelTemplate>(new XDocument(
                                                                            new XElement(pns + nameof(ItemsPanelTemplate),
                                                                                         new XElement(pns + nameof(VirtualizingStackPanel)))
                                                                            ).ToString());

            itemsHost.Template = Xaml.FromString <ControlTemplate>(new XDocument(
                                                                       new XElement(pns + nameof(ControlTemplate),
                                                                                    new XElement(pns + nameof(ScrollViewer),
                                                                                                 new XAttribute(nameof(ScrollViewer.Focusable), false),
                                                                                                 new XAttribute(nameof(ScrollViewer.HorizontalScrollBarVisibility), ScrollBarVisibility.Disabled),
                                                                                                 new XAttribute(nameof(ScrollViewer.VerticalScrollBarVisibility), ScrollBarVisibility.Auto),
                                                                                                 new XAttribute(nameof(ScrollViewer.CanContentScroll), true),
                                                                                                 new XElement(pns + nameof(ItemsPresenter))))
                                                                       ).ToString());

            itemsHost.ItemTemplate = Xaml.FromString <DataTemplate>(new XDocument(
                                                                        new XElement(pns + nameof(DataTemplate),
                                                                                     new XElement(pns + nameof(CheckBoxEx),
                                                                                                  new XAttribute(nameof(CheckBoxEx.IsChecked), "{Binding Selected}"),
                                                                                                  new XAttribute(nameof(CheckBoxEx.Content), "{Binding Item.Name}"),
                                                                                                  new XAttribute(nameof(CheckBoxEx.Style), $"{{DynamicResource FilterItemtSelectionStyle}}")))
                                                                        ).ToString());
        }
示例#2
0
        private bool UnusedVariables_IsVariableUsedInContainer(string variableName, XmlNode containerNode)
        {
            bool variableUsed = false;

            foreach (XmlNode node in containerNode.SelectNodes(".//*[not(local-name()='Reference') and not(local-name()='DebugSymbol.Symbol') and (string-length(text()) > 0)]"))
            {
                if (Xaml.IsVariableUsed(variableName, node.InnerText))
                {
                    break;
                }
            }

            if (!variableUsed)
            {
                foreach (XmlNode item in containerNode.SelectNodes(".//@*"))
                {
                    if (Xaml.IsVariableUsed(variableName, item.Value))
                    {
                        break;
                    }
                }
            }


            return(variableUsed);
        }
示例#3
0
        public static void ApplyTheme(Application app, ThemeDescription theme, ApplicationMode mode)
        {
            var allLoaded   = true;
            var loadedXamls = new List <ResourceDictionary>();
            var xamlFiles   = Directory.GetFiles(theme.DirectoryPath, "*.xaml", SearchOption.AllDirectories);

            foreach (var xamlFile in xamlFiles)
            {
                try
                {
                    var xaml = Xaml.FromFile(xamlFile);
                    if (xaml is ResourceDictionary xamlDir)
                    {
                        xamlDir.Source = new Uri(xamlFile, UriKind.Absolute);
                        loadedXamls.Add(xamlDir as ResourceDictionary);
                    }
                    else
                    {
                        logger.Error($"Skipping theme file {xamlFile}, it's not resource dictionary.");
                    }
                }
                catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                {
                    logger.Error(e, $"Failed to load xaml {xamlFiles}");
                    allLoaded = false;
                    break;
                }
            }

            if (allLoaded)
            {
                loadedXamls.ForEach(a => app.Resources.MergedDictionaries.Add(a));
            }
        }
示例#4
0
        public void Delay(string strWorkflow, DataTable dtDelay)
        {
            dtDelay.Columns.Add("Path");
            dtDelay.Columns.Add("NodeName");
            dtDelay.Columns.Add("Value");

            Xaml.ParseWorkflowFile(strWorkflow);
            string xPathExpression = "//xaml:Delay | //*[@DelayMS != '{x:Null}' or @DelayBefore != '{x:Null}']";

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes(xPathExpression, Xaml.NamespaceManager))
            {
                string targetName = "";
                if (node.Attributes["DisplayName"] == null)
                {
                    targetName = node.LocalName;
                }
                else
                {
                    targetName = node.Attributes["DisplayName"].Value;
                }
                if (node.Name.Equals("Delay"))
                {
                    dtDelay.Rows.Add(Xaml.GetInternalPath(node), targetName, node.Attributes["Duration"].Value);
                }
                if (node.Attributes["DelayBefore"] != null)
                {
                    dtDelay.Rows.Add(Xaml.GetInternalPath(node), targetName, node.Attributes["DelayBefore"].Value);
                }
                if (node.Attributes["DelayMS"] != null)
                {
                    dtDelay.Rows.Add(Xaml.GetInternalPath(node), targetName, node.Attributes["DelayMS"].Value);
                }
            }
        }
示例#5
0
        private void Designer_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.Escape || (e.Key == Key.Z && Keyboard.Modifiers.HasFlag(ModifierKeys.Control)) || e.Key == Key.Left) &&
                ActionManager.CanUndo)
            {
                Undo();
                return;
            }

            if (((e.Key == Key.Y && Keyboard.Modifiers.HasFlag(ModifierKeys.Control)) || e.Key == Key.Right) &&
                ActionManager.CanRedo)
            {
                Redo();
                return;
            }

            if (e.Key == Key.Delete)
            {
                SelectionManager.Delete();
                return;
            }

            if (e.Key == Key.C && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
            {
                Xaml.Copy();
                return;
            }
        }
示例#6
0
        public static bool ApplyTheme(Application app, ThemeDescription theme, ApplicationMode mode)
        {
            if ((new System.Version(theme.ThemeApiVersion).Major != ThemeApiVersion.Major))
            {
                logger.Error($"Failed to apply {theme.Name} theme, unsupported API version {theme.ThemeApiVersion}.");
                return(false);
            }

            var allLoaded       = true;
            var loadedXamls     = new List <ResourceDictionary>();
            var acceptableXamls = new List <string>();
            var defaultRoot     = $"Themes/{mode.GetDescription()}/{DefaultTheme.DirectoryName}/";

            foreach (var dict in app.Resources.MergedDictionaries)
            {
                if (dict.Source.OriginalString.StartsWith("Themes") && dict.Source.OriginalString.EndsWith("xaml"))
                {
                    acceptableXamls.Add(dict.Source.OriginalString.Replace(defaultRoot, "").Replace('/', '\\'));
                }
            }

            foreach (var accXaml in acceptableXamls)
            {
                var xamlPath = Path.Combine(theme.DirectoryPath, accXaml);
                if (!File.Exists(xamlPath))
                {
                    continue;
                }

                try
                {
                    var xaml = Xaml.FromFile(xamlPath);
                    if (xaml is ResourceDictionary xamlDir)
                    {
                        xamlDir.Source = new Uri(xamlPath, UriKind.Absolute);
                        loadedXamls.Add(xamlDir as ResourceDictionary);
                    }
                    else
                    {
                        logger.Error($"Skipping theme file {xamlPath}, it's not resource dictionary.");
                    }
                }
                catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                {
                    logger.Error(e, $"Failed to load xaml {xamlPath}");
                    allLoaded = false;
                    break;
                }
            }

            if (allLoaded)
            {
                loadedXamls.ForEach(a => app.Resources.MergedDictionaries.Add(a));
                return(true);
            }

            return(false);
        }
示例#7
0
        private ItemsPanelTemplate GetItemsPanelTemplate()
        {
            XNamespace pns         = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            XNamespace pctrls      = "clr-namespace:Playnite.DesktopApp.Controls;assembly=Playnite.DesktopApp";
            var        templateDoc = new XDocument(
                new XElement(pns + nameof(ItemsPanelTemplate),
                             new XElement(pctrls + nameof(GridViewPanel))));

            return(Xaml.FromString <ItemsPanelTemplate>(templateDoc.ToString()));
        }
示例#8
0
        public static void SetLanguage(string language)
        {
            var dictionaries = Application.Current.Resources.MergedDictionaries;

            if (CurrentLanguage != SourceLanguageId)
            {
                var currentLang = dictionaries.FirstOrDefault(a => a["LanguageName"] != null && a.Source == null);
                if (currentLang != null)
                {
                    dictionaries.Remove(currentLang);
                }
            }

            var langFile = Path.Combine(PlaynitePaths.LocalizationsPath, language + ".xaml");

            if (File.Exists(langFile) && language != SourceLanguageId)
            {
                ResourceDictionary res = null;
                try
                {
                    res        = Xaml.FromFile <ResourceDictionary>(langFile);
                    res.Source = new Uri(langFile, UriKind.Absolute);
                    // Unstranslated strings are imported as empty entries by Crowdin.
                    // We need to remove them to make sure that origina English text will be displayed instead.
                    foreach (var key in res.Keys)
                    {
                        if (res[key] is string locString && locString.IsNullOrEmpty())
                        {
                            res.Remove(key);
                        }
                    }
                }
                catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                {
                    logger.Error(e, $"Failed to parse localization file {langFile}");
                    return;
                }

                dictionaries.Add(res);

                ApplicationLanguageCultureInfo = new CultureInfo(language.Replace("_", "-"), false);
            }
            else
            {
                ApplicationLanguageCultureInfo = new CultureInfo("en-US", false); // english is the default language
            }

            CurrentLanguage = language;
        }
示例#9
0
        /// <summary>
        /// Set in application ressources the common ressources.
        /// </summary>
        /// <param name="pluginFolder"></param>
        public static void Load(string pluginFolder)
        {
            List <string> ListCommonFiles = new List <string>
            {
                Path.Combine(pluginFolder, "Resources\\Common.xaml"),
                Path.Combine(pluginFolder, "Resources\\LiveChartsCommon\\Common.xaml")
            };

            foreach (string CommonFile in ListCommonFiles)
            {
                if (File.Exists(CommonFile))
                {
#if DEBUG
                    logger.Debug($"PluginCommon - Load {CommonFile}");
#endif

                    ResourceDictionary res = null;
                    try
                    {
                        res        = Xaml.FromFile <ResourceDictionary>(CommonFile);
                        res.Source = new Uri(CommonFile, UriKind.Absolute);

                        foreach (var key in res.Keys)
                        {
                            if (res[key] is string locString && locString.IsNullOrEmpty())
                            {
                                res.Remove(key);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogError(ex, "PluginCommon", $"Failed to parse file {CommonFile}");
                        return;
                    }

#if DEBUG
                    logger.Debug($"PluginCommon - res: {JsonConvert.SerializeObject(res)}");
#endif
                    Application.Current.Resources.MergedDictionaries.Add(res);
                }
                else
                {
                    logger.Warn($"PluginCommon - File {CommonFile} not found.");
                    return;
                }
            }
        }
示例#10
0
        private ItemsPanelTemplate GetItemsPanelTemplate()
        {
            XNamespace pns         = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            var        templateDoc = new XDocument(
                new XElement(pns + nameof(ItemsPanelTemplate),
                             new XElement(pns + nameof(FullscreenTilePanel),
                                          new XAttribute("Rows", "{Settings Fullscreen.Rows}"),
                                          new XAttribute("Columns", "{Settings Fullscreen.Columns}"),
                                          new XAttribute("UseHorizontalLayout", "{Settings Fullscreen.HorizontalLayout}"),
                                          new XAttribute("ItemAspectRatio", "{Settings CoverAspectRatio}"),
                                          new XAttribute("ItemSpacing", "{Settings FullscreenItemSpacing}"))));

            var str = templateDoc.ToString();

            return(Xaml.FromString <ItemsPanelTemplate>(str));
        }
示例#11
0
        private static void Import(IEnumerable <string> assets, Dictionary <Slot, Type> xamlTypes)
        {
            foreach (var asset in assets)
            {
                Slot lastSlot;
                Type xamlType;

                try
                {
                    if (!asset.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var xaml  = Xaml.Parse(asset);
                    var slots = Slot.Parse(xaml.classFullName).ToArray();
                    lastSlot = slots.Last();

                    foreach (var xamlSlot in slots.Take(slots.Length - 1))
                    {
                        if (!xamlTypes.TryGetValue(xamlSlot, out xamlType))
                        {
                            xamlType.nested     = new Dictionary <Slot, Type>();
                            xamlTypes[xamlSlot] = xamlType;
                        }

                        xamlTypes = xamlType.nested;
                    }

                    if (!xamlTypes.TryGetValue(lastSlot, out xamlType))
                    {
                        xamlType.nested = new Dictionary <Slot, Type>();
                    }

                    xamlType.names = xaml.names;
                }
                catch (Exception exception)
                {
                    Debug.LogException(exception);
                    continue;
                }

                xamlType.asset      = asset;
                xamlTypes[lastSlot] = xamlType;
            }
        }
示例#12
0
        public void UnusedVariable(string strWorkflow, DataTable dtEmptyCatch)
        {
            dtEmptyCatch.Columns.Add("Path");
            dtEmptyCatch.Columns.Add("Variable Name");

            Xaml.ParseWorkflowFile(strWorkflow);

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//*[xaml:Sequence.Variables] | //*[xaml:Flowchart.Variables] | //*[xaml:StateMachine.Variables]", Xaml.NamespaceManager))
            {
                foreach (XmlNode item in node.SelectNodes("./*/xaml:Variable", Xaml.NamespaceManager))
                {
                    if (UnusedVariables_IsVariableUsedInContainer(item.Attributes["Name"].Value, node))
                    {
                        dtEmptyCatch.Rows.Add(Xaml.GetInternalPath(node), item.Attributes["Name"]);
                    }
                }
            }
        }
示例#13
0
        public static List <PlayniteLanguage> GetLanguagesFromFolder(string path)
        {
            var langs = new List <PlayniteLanguage>()
            {
                new PlayniteLanguage()
                {
                    Id           = SourceLanguageId,
                    LocaleString = "English"
                }
            };

            if (!Directory.Exists(path))
            {
                return(langs);
            }

            foreach (var file in Directory.GetFiles(path, "*.xaml"))
            {
                if (!Regex.IsMatch(file, "[a-zA-Z]+_[a-zA-Z]+"))
                {
                    continue;
                }

                var langPath           = Path.Combine(path, file);
                ResourceDictionary res = null;
                try
                {
                    res = Xaml.FromFile <ResourceDictionary>(langPath);
                }
                catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                {
                    logger.Error(e, $"Failed to parse localization file {file}");
                    continue;
                }

                langs.Add(new PlayniteLanguage()
                {
                    Id           = Path.GetFileNameWithoutExtension(langPath),
                    LocaleString = res["LanguageName"].ToString()
                });
            }

            return(langs.OrderBy(a => a.LocaleString).ToList());
        }
示例#14
0
        public void ArgumentNammingConvension(string strWorkflow, DataTable dtArgument)
        {
            dtArgument.Columns.Add("Path");
            dtArgument.Columns.Add("Argument Name");

            Xaml.ParseWorkflowFile(strWorkflow);
            string xPathExpression        = "//x:Property";
            string variableNammingPattern = "(^(in_|out_|io_)(dt_)*([A-Z][a-z0-9]*)+)";

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes(xPathExpression, Xaml.NamespaceManager))
            {
                var   regex = new Regex(variableNammingPattern);
                Match match = regex.Match(node.Attributes["Name"].Value);
                if (!match.Success)
                {
                    dtArgument.Rows.Add("", node.Attributes["Name"].Value);
                }
            }
        }
示例#15
0
        public void VariableNammingConvension(string strWorkflow, DataTable dtVariable)
        {
            dtVariable.Columns.Add("Path");
            dtVariable.Columns.Add("Variable Name");


            Xaml.ParseWorkflowFile(strWorkflow);
            string xPathExpression        = "//xaml:Variable";
            string variableNammingPattern = "(^(dt_)*([A-Z][a-z0-9]*)+$)";

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes(xPathExpression, Xaml.NamespaceManager))
            {
                var   regex = new Regex(variableNammingPattern);
                Match match = regex.Match(node.Attributes["Name"].Value);
                if (!match.Success)
                {
                    dtVariable.Rows.Add(Xaml.GetInternalPath(node), node.Attributes["Name"].Value);
                }
            }
        }
示例#16
0
        private DataTemplate GetFieldItemTemplate(string command, string tooltip = null)
        {
            XNamespace pns        = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            var        buttonElem = new XElement(pns + nameof(Button),
                                                 new XAttribute("Command", $"{{Binding DataContext.{command}, RelativeSource={{RelativeSource AncestorType=ItemsControl}}}}"),
                                                 new XAttribute("CommandParameter", "{Binding}"),
                                                 new XAttribute("Content", "{Binding Name}"),
                                                 new XAttribute("Style", "{StaticResource PropertyItemButton}"));

            if (!tooltip.IsNullOrEmpty())
            {
                buttonElem.Add(new XAttribute("ToolTip", $"{{Binding {tooltip}}}"));
            }

            var templateDoc = new XDocument(
                new XElement(pns + nameof(DataTemplate), buttonElem)
                );

            return(Xaml.FromString <DataTemplate>(templateDoc.ToString()));
        }
示例#17
0
        public void DeeplyNested(string strWorkflow, DataTable dtNested)
        {
            dtNested.Columns.Add("Path");
            dtNested.Columns.Add("Variable Name");
            dtNested.Columns.Add("Depth");
            int threshold = 10;

            Xaml.ParseWorkflowFile(strWorkflow);


            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//*[@sap2010:WorkflowViewState.IdRef]", Xaml.NamespaceManager))
            {
                XmlNode activityNode = node;
                int     depth        = 0;
                while (activityNode.LocalName != "Activity" && activityNode.LocalName != "State")
                {
                    if (activityNode.LocalName != "FlowStep" && activityNode.Attributes["sap2010:WorkflowViewState.IdRef"] != null)
                    {
                        depth++;
                    }
                    activityNode = activityNode.ParentNode;
                }

                if (depth > threshold)
                {
                    Console.WriteLine(depth);
                    string displayName = string.Empty;
                    if (node.Attributes["DisplayName"] != null)
                    {
                        displayName = node.Attributes["DisplayName"].Value;
                    }
                    else
                    {
                        displayName = node.LocalName;
                    }

                    dtNested.Rows.Add(Xaml.GetInternalPath(node), displayName, "Code has " + depth.ToString() + " nested activities");
                }
            }
        }
示例#18
0
        public void VariableOverridesVariable(string strWorkflow, DataTable dtVarVar)
        {
            dtVarVar.Columns.Add("Path");
            dtVarVar.Columns.Add("Variable Name");

            Xaml.ParseWorkflowFile(strWorkflow);


            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//*/xaml:Variable", Xaml.NamespaceManager))
            {
                string  variableName = node.Attributes["Name"].Value;
                XmlNode cNode        = node.ParentNode.ParentNode;
                foreach (XmlNode dNode in cNode.SelectNodes(".//*/*/xaml:Variable", Xaml.NamespaceManager))
                {
                    string dName = dNode.Attributes["Name"].Value;
                    if (dName.Equals(variableName, StringComparison.OrdinalIgnoreCase))
                    {
                        dtVarVar.Rows.Add(Xaml.GetInternalPath(node), variableName);
                    }
                }
            }
        }
示例#19
0
        public void EmptyCatch(string strWorkflow, DataTable dtEmptyCatch)
        {
            dtEmptyCatch.Columns.Add("Path");
            dtEmptyCatch.Columns.Add("Variable Name");

            Xaml.ParseWorkflowFile(strWorkflow);


            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//xaml:Catch[count(xaml:ActivityAction/*)=1]", Xaml.NamespaceManager))
            {
                string displayName = string.Empty;
                if (node.Attributes["DisplayName"] != null)
                {
                    displayName = node.Attributes["DisplayName"].Value;
                }
                else
                {
                    displayName = node.LocalName;
                }
                dtEmptyCatch.Rows.Add(Xaml.GetInternalPath(node), displayName);
            }
        }
示例#20
0
        public static void ApplyFullscreenButtonPrompts(Application app, FullscreenButtonPrompts prompts)
        {
            if (prompts == FullscreenSettings.DefaultButtonPrompts)
            {
                var defaultXaml = $"{FullscreenSettings.DefaultButtonPrompts.ToString()}.xaml";
                foreach (var dir in PlayniteApplication.CurrentNative.Resources.MergedDictionaries.ToList())
                {
                    if (dir.Source == null)
                    {
                        continue;
                    }

                    if (dir.Source.OriginalString.Contains("ButtonPrompts") &&
                        !dir.Source.OriginalString.EndsWith(defaultXaml))
                    {
                        PlayniteApplication.CurrentNative.Resources.MergedDictionaries.Remove(dir);
                    }
                }
            }
            else
            {
                var promptsPath = Path.Combine(ThemeManager.DefaultTheme.DirectoryPath, "Images", "ButtonPrompts");
                foreach (var dir in Directory.GetDirectories(promptsPath))
                {
                    var dirInfo    = new DirectoryInfo(dir);
                    var promptXaml = Path.Combine(dir, $"{dirInfo.Name}.xaml");
                    if (File.Exists(promptXaml) && dirInfo.Name == prompts.ToString())
                    {
                        var xaml = Xaml.FromFile(promptXaml);
                        if (xaml is ResourceDictionary xamlDir)
                        {
                            xamlDir.Source = new Uri(promptXaml, UriKind.Absolute);
                            PlayniteApplication.CurrentNative.Resources.MergedDictionaries.Add(xamlDir);
                        }
                    }
                }
            }
        }
示例#21
0
        public void VariableOverridesArgument(string strWorkflow, DataTable dtVarArg)
        {
            dtVarArg.Columns.Add("Path");
            dtVarArg.Columns.Add("Variable Name");

            Xaml.ParseWorkflowFile(strWorkflow);


            List <string> argumentNames = new List <string>();

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//*/x:Property/@Name", Xaml.NamespaceManager))
            {
                argumentNames.Add(node.Value);
            }

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//*/xaml:Variable", Xaml.NamespaceManager))
            {
                string variableName = node.Attributes["Name"].Value;
                if (argumentNames.Contains(variableName, StringComparer.OrdinalIgnoreCase))
                {
                    dtVarArg.Rows.Add(Xaml.GetInternalPath(node), variableName);
                }
            }
        }
示例#22
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (Template != null)
            {
                MenuHost = Template.FindName("PART_MenuHost", this) as FrameworkElement;
                if (MenuHost != null)
                {
                    MenuHost.InputBindings.Add(new KeyBinding(mainModel.CloseAdditionalFiltersCommand, new KeyGesture(Key.Back)));
                    MenuHost.InputBindings.Add(new KeyBinding(mainModel.CloseAdditionalFiltersCommand, new KeyGesture(Key.Escape)));
                    MenuHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.ToggleFiltersCommand, Key = Key.F
                    });
                    MenuHost.InputBindings.Add(new XInputBinding(mainModel.CloseAdditionalFiltersCommand, XInputButton.B));
                }

                ButtonBack = Template.FindName("PART_ButtonBack", this) as ButtonBase;
                if (ButtonBack != null)
                {
                    ButtonBack.Command = mainModel.CloseAdditionalFiltersCommand;
                    BindingTools.SetBinding(ButtonBack,
                                            FocusBahaviors.FocusBindingProperty,
                                            mainModel,
                                            nameof(mainModel.FilterAdditionalPanelVisible));
                }

                ItemsHost = Template.FindName("PART_ItemsHost", this) as ItemsControl;
                if (ItemsHost != null)
                {
                    XNamespace pns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
                    ItemsHost.ItemsPanel = Xaml.FromString <ItemsPanelTemplate>(new XDocument(
                                                                                    new XElement(pns + nameof(ItemsPanelTemplate),
                                                                                                 new XElement(pns + nameof(VirtualizingStackPanel)))
                                                                                    ).ToString());
                    ItemsHost.Template = Xaml.FromString <ControlTemplate>(new XDocument(
                                                                               new XElement(pns + nameof(ControlTemplate),
                                                                                            new XElement(pns + nameof(ScrollViewer),
                                                                                                         new XAttribute(nameof(ScrollViewer.Focusable), false),
                                                                                                         new XAttribute(nameof(ScrollViewer.HorizontalScrollBarVisibility), ScrollBarVisibility.Disabled),
                                                                                                         new XAttribute(nameof(ScrollViewer.VerticalScrollBarVisibility), ScrollBarVisibility.Auto),
                                                                                                         new XAttribute(nameof(ScrollViewer.CanContentScroll), true),
                                                                                                         new XElement(pns + nameof(ItemsPresenter))))
                                                                               ).ToString());

                    AssignFilter("LOCGenreLabel", "PART_ButtonGenre", GameField.Genres, nameof(FilterSettings.Genre));
                    AssignFilter("LOCGameReleaseYearTitle", "PART_ButtonReleaseYear", GameField.ReleaseYear, nameof(FilterSettings.ReleaseYear));
                    AssignFilter("LOCDeveloperLabel", "PART_ButtonDeveloper", GameField.Developers, nameof(FilterSettings.Developer));
                    AssignFilter("LOCPublisherLabel", "PART_ButtonPublisher", GameField.Publishers, nameof(FilterSettings.Publisher));
                    AssignFilter("LOCFeatureLabel", "PART_ButtonFeature", GameField.Features, nameof(FilterSettings.Feature));
                    AssignFilter("LOCTagLabel", "PART_ButtonTag", GameField.Tags, nameof(FilterSettings.Tag));
                    AssignFilter("LOCTimePlayed", "PART_ButtonPlayTime", GameField.Playtime, nameof(FilterSettings.PlayTime));
                    AssignFilter("LOCCompletionStatus", "PART_ButtonCompletionStatus", GameField.CompletionStatus, nameof(FilterSettings.CompletionStatuses));
                    AssignFilter("LOCSeriesLabel", "PART_ButtonSeries", GameField.Series, nameof(FilterSettings.Series));
                    AssignFilter("LOCRegionLabel", "PART_ButtonRegion", GameField.Regions, nameof(FilterSettings.Region));
                    AssignFilter("LOCSourceLabel", "PART_ButtonSource", GameField.Source, nameof(FilterSettings.Source));
                    AssignFilter("LOCAgeRatingLabel", "PART_ButtonAgeRating", GameField.AgeRatings, nameof(FilterSettings.AgeRating));
                    AssignFilter("LOCUserScore", "PART_ButtonUserScore", GameField.UserScore, nameof(FilterSettings.UserScore));
                    AssignFilter("LOCCommunityScore", "PART_ButtonCommunityScore", GameField.CommunityScore, nameof(FilterSettings.CommunityScore));
                    AssignFilter("LOCCriticScore", "PART_ButtonCriticScore", GameField.CriticScore, nameof(FilterSettings.CriticScore));
                    AssignFilter("LOCGameLastActivityTitle", "PART_ButtonLastActivity", GameField.LastActivity, nameof(FilterSettings.LastActivity));
                    AssignFilter("LOCAddedLabel", "PART_ButtonAdded", GameField.Added, nameof(FilterSettings.Added));
                    AssignFilter("LOCModifiedLabel", "PART_ButtonModified", GameField.Modified, nameof(FilterSettings.Modified));
                }
            }
        }
示例#23
0
        public XamlToolsControl()
        {
            InitializeComponent();

            VisualizeTagsCommand = new RelayCommand(Execute.Safely(_ => OpenTagVisualizer(NodeVisualizer.ToTags(ConvertToNodes(Xaml.ToStream())))));
            VisualizeTreeCommand = new RelayCommand(Execute.Safely(_ => OpenTreeVisualizer(NodeVisualizer.ToTree(ConvertToNodes(Xaml.ToStream())))));
        }
示例#24
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            if (Template != null)
            {
                ViewHost = Template.FindName("PART_ViewHost", this) as FrameworkElement;
                if (ViewHost != null)
                {
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.OpenMainMenuCommand, Key = Key.F1
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.PrevFilterViewCommand, Key = Key.F2
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.NextFilterViewCommand, Key = Key.F3
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.OpenSearchCommand, Key = Key.Y
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.ToggleFiltersCommand, Key = Key.F
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.SwitchToDesktopCommand, Key = Key.F11
                    });

                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.PrevFilterViewCommand, XInputButton.LeftShoulder));
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.NextFilterViewCommand, XInputButton.RightShoulder));
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.OpenSearchCommand, XInputButton.Y));
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.ToggleFiltersCommand, XInputButton.RightStick));
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.OpenMainMenuCommand, XInputButton.Back));
                }

                MainHost = Template.FindName("PART_MainHost", this) as FrameworkElement;
                if (MainHost != null)
                {
                    BindingTools.SetBinding(MainHost, FrameworkElement.WidthProperty, mainModel, nameof(FullscreenAppViewModel.ViewportWidth));
                    BindingTools.SetBinding(MainHost, FrameworkElement.HeightProperty, mainModel, nameof(FullscreenAppViewModel.ViewportHeight));
                }

                AssignButtonWithCommand(ref ButtonProgramUpdate, "PART_ButtonProgramUpdate", mainModel.OpenUpdatesCommand);
                AssignButtonWithCommand(ref ButtonMainMenu, "PART_ButtonMainMenu", mainModel.OpenMainMenuCommand);
                AssignButtonWithCommand(ref ButtonNotifications, "PART_ButtonNotifications", mainModel.OpenNotificationsMenuCommand);

                if (ButtonProgramUpdate != null)
                {
                    BindingTools.SetBinding(ButtonProgramUpdate,
                                            Button.VisibilityProperty,
                                            mainModel,
                                            nameof(mainModel.UpdatesAvailable),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ImageBackground = Template.FindName("PART_ImageBackground", this) as FadeImage;
                if (ImageBackground != null)
                {
                    SetBackgroundBinding();
                    SetBackgroundEffect();
                }

                TextClock = Template.FindName("PART_TextClock", this) as TextBlock;
                if (TextClock != null)
                {
                    BindingTools.SetBinding(TextClock, TextBlock.TextProperty, mainModel.CurrentTime, nameof(ObservableTime.Time));
                    BindingTools.SetBinding(
                        TextClock,
                        TextBlock.VisibilityProperty,
                        mainModel.AppSettings.Fullscreen,
                        nameof(FullscreenSettings.ShowClock),
                        converter: new Converters.BooleanToVisibilityConverter());
                }

                TextBatteryPercentage = Template.FindName("PART_TextBatteryPercentage", this) as TextBlock;
                if (TextBatteryPercentage != null)
                {
                    BindingTools.SetBinding(TextBatteryPercentage,
                                            TextBlock.TextProperty,
                                            mainModel.PowerStatus,
                                            nameof(ObservablePowerStatus.PercentCharge),
                                            stringFormat: "{0}%");
                    BindingTools.SetBinding(TextBatteryPercentage,
                                            TextBlock.VisibilityProperty,
                                            mainModel.AppSettings.Fullscreen,
                                            nameof(FullscreenSettings.ShowBatteryPercentage),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ElemBatteryStatus = Template.FindName("PART_ElemBatteryStatus", this) as FrameworkElement;
                if (ElemBatteryStatus != null)
                {
                    BindingTools.SetBinding(
                        ElemBatteryStatus,
                        TextBlock.VisibilityProperty,
                        mainModel.AppSettings.Fullscreen,
                        nameof(FullscreenSettings.ShowBattery),
                        converter: new Converters.BooleanToVisibilityConverter());
                }

                TextProgressTooltip = Template.FindName("PART_TextProgressTooltip", this) as TextBlock;
                if (TextProgressTooltip != null)
                {
                    BindingTools.SetBinding(TextProgressTooltip, TextBlock.TextProperty, mainModel, nameof(FullscreenAppViewModel.ProgressStatus));
                    BindingTools.SetBinding(TextProgressTooltip,
                                            TextBlock.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.ProgressActive),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ElemProgressIndicator = Template.FindName("PART_ElemProgressIndicator", this) as FrameworkElement;
                if (ElemProgressIndicator != null)
                {
                    BindingTools.SetBinding(ElemProgressIndicator,
                                            ToggleButton.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.ProgressActive),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ElemExtraFilterActive = Template.FindName("PART_ElemExtraFilterActive", this) as FrameworkElement;
                if (ElemExtraFilterActive != null)
                {
                    BindingTools.SetBinding(ElemExtraFilterActive,
                                            FrameworkElement.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.IsExtraFilterActive),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ElemSearchActive = Template.FindName("PART_ElemSearchActive", this) as FrameworkElement;
                if (ElemSearchActive != null)
                {
                    BindingTools.SetBinding(ElemSearchActive,
                                            FrameworkElement.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.IsSearchActive),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ListGameItems = Template.FindName("PART_ListGameItems", this) as ListBox;
                if (ListGameItems != null)
                {
                    XNamespace pns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
                    ListGameItems.ItemsPanel = Xaml.FromString <ItemsPanelTemplate>(new XDocument(
                                                                                        new XElement(pns + nameof(ItemsPanelTemplate),
                                                                                                     new XElement(pns + nameof(FullscreenTilePanel),
                                                                                                                  new XAttribute(nameof(FullscreenTilePanel.Rows), "{Settings Fullscreen.Rows}"),
                                                                                                                  new XAttribute(nameof(FullscreenTilePanel.Columns), "{Settings Fullscreen.Columns}"),
                                                                                                                  new XAttribute(nameof(FullscreenTilePanel.UseHorizontalLayout), "{Settings Fullscreen.HorizontalLayout}"),
                                                                                                                  new XAttribute(nameof(FullscreenTilePanel.ItemAspectRatio), "{Settings CoverAspectRatio}"),
                                                                                                                  new XAttribute(nameof(FullscreenTilePanel.ItemSpacing), "{Settings FullscreenItemSpacing}")))
                                                                                        ).ToString());

                    ListGameItems.ItemTemplate = Xaml.FromString <DataTemplate>(new XDocument(
                                                                                    new XElement(pns + nameof(DataTemplate),
                                                                                                 new XElement(pns + nameof(GameListItem),
                                                                                                              new XAttribute(nameof(GameListItem.Style), "{StaticResource ListGameItemTemplate}")))
                                                                                    ).ToString());

                    ListGameItems.SetResourceReference(ListBoxEx.ItemContainerStyleProperty, "ListGameItemStyle");

                    BindingTools.SetBinding(ListGameItems,
                                            ListBox.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.GameListVisible),
                                            converter: new Converters.BooleanToVisibilityConverter());
                    BindingTools.SetBinding(ListGameItems,
                                            ListBox.SelectedItemProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.SelectedGame),
                                            BindingMode.TwoWay);
                    BindingTools.SetBinding(ListGameItems,
                                            ListBox.ItemsSourceProperty,
                                            mainModel,
                                            $"{nameof(FullscreenAppViewModel.GamesView)}.{nameof(FullscreenCollectionView.CollectionView)}");
                    BindingTools.SetBinding(ListGameItems,
                                            FocusBahaviors.FocusBindingProperty,
                                            mainModel,
                                            nameof(mainModel.GameListFocused));
                }

                AssignButtonWithCommand(ref ButtonInstall, "PART_ButtonInstall", mainModel.ActivateSelectedCommand);
                if (ButtonInstall != null)
                {
                    BindingTools.SetBinding(
                        ButtonInstall,
                        ButtonBase.VisibilityProperty,
                        mainModel,
                        $"{nameof(FullscreenAppViewModel.SelectedGame)}.{nameof(GamesCollectionViewEntry.IsInstalled)}",
                        converter: new InvertedBooleanToVisibilityConverter(),
                        fallBackValue: Visibility.Collapsed);
                }

                AssignButtonWithCommand(ref ButtonPlay, "PART_ButtonPlay", mainModel.ActivateSelectedCommand);
                if (ButtonPlay != null)
                {
                    ButtonPlay.Command = mainModel.ActivateSelectedCommand;
                    BindingTools.SetBinding(
                        ButtonPlay,
                        ButtonBase.VisibilityProperty,
                        mainModel,
                        $"{nameof(FullscreenAppViewModel.SelectedGame)}.{nameof(GamesCollectionViewEntry.IsInstalled)}",
                        converter: new Converters.BooleanToVisibilityConverter(),
                        fallBackValue: Visibility.Collapsed);
                }

                AssignButtonWithCommand(ref ButtonDetails, "PART_ButtonDetails", mainModel.ToggleGameDetailsCommand);
                if (ButtonDetails != null)
                {
                    BindingTools.SetBinding(
                        ButtonDetails,
                        ButtonBase.VisibilityProperty,
                        mainModel,
                        nameof(FullscreenAppViewModel.GameDetailsButtonVisible),
                        converter: new Converters.BooleanToVisibilityConverter());
                }

                AssignButtonWithCommand(ref ButtonGameOptions, "PART_ButtonGameOptions", mainModel.OpenGameMenuCommand);
                if (ButtonGameOptions != null)
                {
                    BindingTools.SetBinding(
                        ButtonGameOptions,
                        ButtonBase.VisibilityProperty,
                        mainModel,
                        nameof(FullscreenAppViewModel.GameDetailsButtonVisible),
                        converter: new Converters.BooleanToVisibilityConverter());
                    ButtonGameOptions.SetResourceReference(ButtonEx.InputHintProperty, "ButtonPromptStart");
                }

                AssignButtonWithCommand(ref ButtonSearch, "PART_ButtonSearch", mainModel.OpenSearchCommand);
                ButtonSearch?.SetResourceReference(ButtonEx.InputHintProperty, "ButtonPromptY");
                AssignButtonWithCommand(ref ButtonFilter, "PART_ButtonFilter", mainModel.ToggleFiltersCommand);
                ButtonFilter?.SetResourceReference(ButtonEx.InputHintProperty, "ButtonPromptRS");

                ElemFilters = Template.FindName("PART_ElemFilters", this) as FrameworkElement;
                if (ElemFilters != null)
                {
                    BindingTools.SetBinding(ElemFilters,
                                            FrameworkElement.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.FilterPanelVisible),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ElemFiltersAdditional = Template.FindName("PART_ElemFiltersAdditional", this) as FrameworkElement;
                if (ElemFiltersAdditional != null)
                {
                    BindingTools.SetBinding(ElemFiltersAdditional,
                                            FrameworkElement.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.FilterAdditionalPanelVisible),
                                            converter: new Converters.BooleanToVisibilityConverter());
                }

                ContentFilterItems = Template.FindName("PART_ContentFilterItems", this) as ContentControl;
                if (ContentFilterItems != null)
                {
                    BindingTools.SetBinding(ContentFilterItems,
                                            ContentControl.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.SubFilterVisible),
                                            converter: new Converters.BooleanToVisibilityConverter());
                    BindingTools.SetBinding(ContentFilterItems,
                                            ContentControl.ContentProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.SubFilterControl));
                }

                ElemGameDetails = Template.FindName("PART_ElemGameDetails", this) as FrameworkElement;
                if (ElemGameDetails != null)
                {
                    BindingTools.SetBinding(ElemGameDetails,
                                            FrameworkElement.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.GameDetailsVisible),
                                            converter: new Converters.BooleanToVisibilityConverter());
                    BindingTools.SetBinding(ElemGameDetails,
                                            FrameworkElement.DataContextProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.SelectedGame));
                }

                ElemGameStatus = Template.FindName("PART_ElemGameStatus", this) as FrameworkElement;
                if (ElemGameStatus != null)
                {
                    BindingTools.SetBinding(ElemGameStatus,
                                            FrameworkElement.VisibilityProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.GameStatusVisible),
                                            converter: new Converters.BooleanToVisibilityConverter());
                    BindingTools.SetBinding(ElemGameStatus,
                                            FrameworkElement.DataContextProperty,
                                            mainModel,
                                            nameof(FullscreenAppViewModel.SelectedGame));
                }

                SetListCommandBindings();

                ControlTemplateTools.InitializePluginControls(
                    mainModel.Extensions,
                    Template,
                    this,
                    ApplicationMode.Fullscreen,
                    mainModel,
                    $"{nameof(FullscreenAppViewModel.SelectedGameDetails)}.{nameof(GameDetailsViewModel.Game)}.{nameof(GameDetailsViewModel.Game.Game)}");
            }
        }
示例#25
0
        public void RepeatedActivityName(string strWorkflow, DataTable dtRepeatedActivitiesName)
        {
            dtRepeatedActivitiesName.Columns.Add("Path");
            dtRepeatedActivitiesName.Columns.Add("Variable Name");

            int threshold = 1;

            Xaml.ParseWorkflowFile(strWorkflow);

            Dictionary <string, List <XmlNode> > dicActivityname = new Dictionary <string, List <XmlNode> >();

            foreach (XmlNode node in Xaml.XmlDocument.DocumentElement.SelectNodes("//*[@sap2010:WorkflowViewState.IdRef]", Xaml.NamespaceManager))
            {
                if (node.LocalName.Equals("FlowStep") || node.LocalName.Equals("Catch"))
                {
                    continue;
                }
                string displayName = string.Empty;
                if (node.Attributes["DisplayName"] != null)
                {
                    displayName = node.Attributes["DisplayName"].Value;
                }
                else
                {
                    displayName = node.LocalName;
                }



                if (dicActivityname.ContainsKey(displayName) && node.LocalName != "Sequence")
                {
                    dicActivityname[displayName].Add(node);
                }
                else
                {
                    dicActivityname[displayName] = new List <XmlNode>()
                    {
                        node
                    }
                };
            }

            foreach (string disName in dicActivityname.Keys)
            {
                if (dicActivityname[disName].Count > threshold)
                {
                    foreach (XmlNode xmlNode in dicActivityname[disName])
                    {
                        string targetName = "";
                        if (xmlNode.Attributes["DisplayName"] == null)
                        {
                            targetName = xmlNode.LocalName;
                        }
                        else
                        {
                            targetName = xmlNode.Attributes["DisplayName"].Value;
                        }


                        dtRepeatedActivitiesName.Rows.Add(Xaml.GetInternalPath(xmlNode), targetName);
                    }
                }
            }
        }
示例#26
0
        public TestResourceProvider()
        {
            var engSource = Path.Combine(PlaynitePaths.LocalizationsPath, PlaynitePaths.EngLocSourceFileName);

            engStringResource = Xaml.FromFile <ResourceDictionary>(engSource);
        }
示例#27
0
        public static AddonLoadError ApplyTheme(Application app, ThemeManifest theme, ApplicationMode mode)
        {
            if (theme.Id.IsNullOrEmpty())
            {
                logger.Error($"Theme {theme.Name}, doesn't have ID.");
                return(AddonLoadError.Uknown);
            }

            var apiVesion = mode == ApplicationMode.Desktop ? DesktopApiVersion : FullscreenApiVersion;

            if (!theme.ThemeApiVersion.IsNullOrEmpty())
            {
                var themeVersion = new Version(theme.ThemeApiVersion);
                if (themeVersion.Major != apiVesion.Major || themeVersion > apiVesion)
                {
                    logger.Error($"Failed to apply {theme.Name} theme, unsupported API version {theme.ThemeApiVersion}.");
                    return(AddonLoadError.SDKVersion);
                }
            }

            var acceptableXamls = new List <string>();
            var defaultRoot     = $"Themes/{mode.GetDescription()}/{DefaultTheme.DirectoryName}/";

            foreach (var dict in app.Resources.MergedDictionaries)
            {
                if (dict.Source.OriginalString.StartsWith(defaultRoot))
                {
                    acceptableXamls.Add(dict.Source.OriginalString.Replace(defaultRoot, "").Replace('/', '\\'));
                }
            }

            var allLoaded = true;

            foreach (var accXaml in acceptableXamls)
            {
                var xamlPath = Path.Combine(theme.DirectoryPath, accXaml);
                if (!File.Exists(xamlPath))
                {
                    continue;
                }

                try
                {
                    var xaml = Xaml.FromFile(xamlPath);
                }
                catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                {
                    logger.Error(e, $"Failed to load xaml {xamlPath}");
                    allLoaded = false;
                    break;
                }
            }

            if (!allLoaded)
            {
                return(AddonLoadError.Uknown);
            }

            try
            {
                var cursorFile = ThemeFile.GetFilePath("cursor.cur");
                if (cursorFile.IsNullOrEmpty())
                {
                    cursorFile = ThemeFile.GetFilePath("cursor.ani");
                }

                if (!cursorFile.IsNullOrEmpty())
                {
                    Mouse.OverrideCursor = new Cursor(cursorFile, true);
                }
            }
            catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
            {
                logger.Error(e, "Failed to set custom mouse cursor.");
            }

            var themeRoot = $"Themes\\{mode.GetDescription()}\\{theme.DirectoryName}\\";

            // This is sad that we have to do this, but it fixes issues like #2328
            // We need to remove all loaded theme resources and reload them in specific order:
            //      default/1.xaml -> theme/1.xaml -> default/2.xaml -> theme/2.xaml etc.
            //
            // We can't just load custom theme files at the end or insert them in already loaded pool of resources
            // because styling with static references won't reload data from custom theme files.
            // That's why we also have to create new instances of default styles.
            foreach (var defaultRes in app.Resources.MergedDictionaries.ToList())
            {
                if (defaultRes.Source.OriginalString.StartsWith(defaultRoot))
                {
                    app.Resources.MergedDictionaries.Remove(defaultRes);
                }
            }

            foreach (var themeXamlFile in acceptableXamls)
            {
                var defaultPath = Path.Combine(PlaynitePaths.ThemesProgramPath, mode.GetDescription(), "Default", themeXamlFile);
                var defaultXaml = Xaml.FromFile(defaultPath);
                if (defaultXaml is ResourceDictionary xamlDir)
                {
                    xamlDir.Source = new Uri(defaultPath, UriKind.Absolute);
                    app.Resources.MergedDictionaries.Add(xamlDir);
                }

                var xamlPath = Path.Combine(theme.DirectoryPath, themeXamlFile);
                if (!File.Exists(xamlPath))
                {
                    continue;
                }

                var xaml = Xaml.FromFile(xamlPath);
                if (xaml is ResourceDictionary themeDir)
                {
                    themeDir.Source = new Uri(xamlPath, UriKind.Absolute);
                    app.Resources.MergedDictionaries.Add(themeDir);
                }
                else
                {
                    logger.Error($"Skipping theme file {xamlPath}, it's not resource dictionary.");
                }
            }

            return(AddonLoadError.None);
        }
        public static void SetPluginLanguage(string pluginFolder, string language, bool DefaultLoad = false)
        {
            // Load default for missing
            if (!DefaultLoad)
            {
                SetPluginLanguage(pluginFolder, "LocSource", true);
            }


            var dictionaries   = Application.Current.Resources.MergedDictionaries;
            var langFile       = Path.Combine(pluginFolder, "localization\\" + language + ".xaml");
            var langFileCommon = Path.Combine(pluginFolder, "localization\\Common\\" + language + ".xaml");


            // Load localization common
            if (File.Exists(langFileCommon))
            {
#if DEBUG
                logger.Debug($"PluginCommon - Parse plugin localization file {langFileCommon}.");
#endif

                ResourceDictionary res = null;
                try
                {
                    res        = Xaml.FromFile <ResourceDictionary>(langFileCommon);
                    res.Source = new Uri(langFileCommon, UriKind.Absolute);

                    foreach (var key in res.Keys)
                    {
                        if (res[key] is string locString && locString.IsNullOrEmpty())
                        {
                            res.Remove(key);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, $"PluginCommon - Failed to parse localization file {langFileCommon}.");
                    return;
                }

                dictionaries.Add(res);
            }
            else
            {
                logger.Warn($"PluginCommon - File {langFileCommon} not found.");
            }


            // Load localization
            if (File.Exists(langFile))
            {
#if DEBUG
                logger.Debug($"PluginCommon - Parse plugin localization file {langFile}.");
#endif

                ResourceDictionary res = null;
                try
                {
                    res        = Xaml.FromFile <ResourceDictionary>(langFile);
                    res.Source = new Uri(langFile, UriKind.Absolute);

                    foreach (var key in res.Keys)
                    {
                        if (res[key] is string locString && locString.IsNullOrEmpty())
                        {
                            res.Remove(key);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, $"PluginCommon - Failed to parse localization file {langFile}.");
                    return;
                }

                dictionaries.Add(res);
            }
            else
            {
                logger.Warn($"PluginCommon - File {langFile} not found.");
            }
        }
示例#29
0
 private void UpdateXaml()
 {
     Xaml.Display(Root.WriteXaml());
 }