Example #1
0
        private void SwitchAdaptive(Theme newTheme)
        {
            ThemeFile themeFile = GlobalState.ManagedThemeFile;

            if (newTheme == Theme.Light)
            {
                RegistryHandler.SetColorPrevalence(0);
                currentTaskbarColorActive         = false;
                themeFile.VisualStyles.SystemMode = (nameof(Theme.Light), themeFile.VisualStyles.SystemMode.Item2);
            }
            else if (newTheme == Theme.Dark)
            {
                if (currentComponentTheme != Theme.Dark)
                {
                    themeFile.VisualStyles.SystemMode = (nameof(Theme.Dark), themeFile.VisualStyles.SystemMode.Item2);
                }
                currentComponentTheme = Theme.Dark;
                if (Settings.Component.TaskbarColorOnAdaptive)
                {
                    RegistryHandler.SetColorPrevalence(1);
                    currentTaskbarColorActive = true;
                }
                else if (!Settings.Component.TaskbarColorOnAdaptive && currentTaskbarColorActive)
                {
                    RegistryHandler.SetColorPrevalence(0);
                    currentTaskbarColorActive = false;
                }
            }
            currentComponentTheme = newTheme;
        }
Example #2
0
        public DescriptionEditorView(TextBox TextDescription)
        {
            InitializeComponent();

            _TextDescription = TextDescription;
            Description      = TextDescription.Text;

            PlayniteTools.SetThemeInformation();
            string DescriptionViewFile = ThemeFile.GetFilePath("DescriptionView.html");

            Common.LogDebug(true, $"{DescriptionViewFile}");

            try
            {
                htmlTextView.Visibility   = Visibility.Visible;
                htmlTextView.TemplatePath = DescriptionViewFile;
                htmlTextView.HtmlText     = Description;

                htmlTextView.HtmlFontSize   = (double)resources.GetResource("FontSize");
                htmlTextView.HtmlFontFamily = (FontFamily)resources.GetResource("FontFamily");
                htmlTextView.HtmlForeground = (Color)resources.GetResource("TextColor");
                htmlTextView.LinkForeground = (Color)resources.GetResource("GlyphColor");

                PART_HtmlDescription.Children.Add(htmlTextView);
            }
            catch (Exception ex)
            {
                Common.LogError(ex, false, "Error on creation HtmlTextView");
            }

            DataContext = this;
        }
Example #3
0
        private static object GetIcon(string iconName)
        {
            var resource = ResourceProvider.GetResource(iconName);

            if (resource != null)
            {
                if (resource is string stringIcon)
                {
                    return(Images.GetImageFromFile(ThemeFile.GetFilePath(stringIcon)));
                }
                else if (resource is BitmapImage bitmap)
                {
                    var image = new Image()
                    {
                        Source = bitmap
                    };
                    RenderOptions.SetBitmapScalingMode(image, RenderOptions.GetBitmapScalingMode(bitmap));
                    return(image);
                }
                else if (resource is TextBlock textIcon)
                {
                    return(textIcon);
                }
            }

            return(null);
        }
Example #4
0
        public ThemeFileViewModel(ThemeFile themeFile)
        {
            this.themeFile = themeFile;

            properties.AddRange(themeFile.Properties.Select(x => new OwnedThemePropertyViewModel(x)));

            classes = themeFile.Classes.Select(x => new ThemeClassViewModel(x, this)).ToList();
            classes.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase));

            var classMap = classes.ToDictionary(x => x.Class);

            foreach (var classViewModel in classes)
            {
                if (classViewModel.Class.BaseClass != null)
                {
                    classViewModel.BaseClass = classMap[classViewModel.Class.BaseClass];
                }
            }

            foreach (var @class in classes)
            {
                if (@class.Name.Equals("globals", StringComparison.OrdinalIgnoreCase))
                {
                    globals = @class;
                    break;
                }
            }

            foreach (var @class in Classes)
            {
                @class.AddInheritedProperties();
            }

            AddDefaultProperties();
        }
        //save theme selection
        private void SaveThemeSettings()
        {
            //disable wallpaper switch
            builder.Config.WallpaperSwitch.Enabled = false;

            //get selected light theme file from combobox
            string selectedLightTheme = (string)ComboBoxLightTheme.SelectedItem;

            try
            {
                ThemeFile selected = themeCollection.FirstOrDefault(t => t.ToString().Contains(selectedLightTheme));
                if (selected != null)
                {
                    builder.Config.WindowsThemeMode.LightThemePath = selected.Path;
                }
            }
            catch
            {
                theme1 = false;
                ComboBoxLightTheme.SelectedItem = null;
            }

            //get selected dark theme file from combobox
            string selectedDarkTheme = (string)ComboBoxDarkTheme.SelectedItem;

            try
            {
                ThemeFile selected = themeCollection.FirstOrDefault(t => t.ToString().Contains(selectedDarkTheme));
                if (selected != null)
                {
                    builder.Config.WindowsThemeMode.DarkThemePath = selected.Path;
                }
            }
            catch
            {
                theme2 = false;
                ComboBoxDarkTheme.SelectedItem = null;
            }

            //enable theme mode
            builder.Config.WindowsThemeMode.Enabled = true;

            //ui changes
            TextBlockUserFeedback.Visibility = Visibility.Visible;

            //apply theme
            try
            {
                builder.Save();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex, "SaveThemeSettings");
            }
            RequestThemeSwitch();
            Trace.WriteLine("Windows Theme Mode settings were applied");
        }
Example #6
0
        public static object GetIcon(string iconName, double imageHeight = 16, double imageWidth = 16)
        {
            if (iconName.IsNullOrEmpty())
            {
                return(null);
            }

            var resource = ResourceProvider.GetResource(iconName);

            if (resource != null)
            {
                if (resource is string stringIcon)
                {
                    return(Images.GetImageFromFile(ThemeFile.GetFilePath(stringIcon), BitmapScalingMode.Fant, imageHeight, imageWidth));
                }
                else if (resource is BitmapImage bitmap)
                {
                    var image = new System.Windows.Controls.Image()
                    {
                        Source = bitmap
                    };
                    RenderOptions.SetBitmapScalingMode(image, RenderOptions.GetBitmapScalingMode(bitmap));
                    return(image);
                }
                else if (resource is TextBlock textIcon)
                {
                    var text = new TextBlock
                    {
                        Text       = textIcon.Text,
                        FontFamily = textIcon.FontFamily,
                        FontStyle  = textIcon.FontStyle
                    };

                    if (textIcon.ReadLocalValue(TextBlock.ForegroundProperty) != DependencyProperty.UnsetValue)
                    {
                        text.Foreground = textIcon.Foreground;
                    }

                    return(text);
                }
            }
            else if (System.IO.File.Exists(iconName))
            {
                return(BitmapExtensions.BitmapFromFile(iconName)?.ToImage());
            }
            else
            {
                var themeFile = ThemeFile.GetFilePath(iconName);
                if (themeFile != null)
                {
                    return(Images.GetImageFromFile(themeFile, BitmapScalingMode.Fant, imageHeight, imageWidth));
                }
            }

            return(null);
        }
Example #7
0
        public void TestPhysicalPath()
        {
            string themeName = "theme1";
            var    site      = new Site("Site1");
            var    theme     = new Theme(site, themeName);
            var    themeFile = new ThemeFile(theme, "style1.css");

            string expected1 = Path.Combine(site.PhysicalPath, "themes", themeName, "style1.css");

            Assert.AreEqual(expected1, themeFile.PhysicalPath, true);
        }
Example #8
0
        public void TestVirtualPath()
        {
            string themeName = "theme1";
            var    site      = new Site("Site1");
            var    theme     = new Theme(site, themeName);
            var    themeFile = new ThemeFile(theme, "style1.css");

            string expected1 = Kooboo.Web.Url.UrlUtility.Combine(site.VirtualPath, "themes", themeName, "style1.css");

            Assert.AreEqual(expected1, themeFile.VirtualPath, true);
        }
Example #9
0
        private void SwitchLightOnly()
        {
            if (Settings.Component.TaskbarColorOnAdaptive)
            {
                RegistryHandler.SetColorPrevalence(0);
            }
            currentTaskbarColorActive = false;
            ThemeFile themeFile = GlobalState.ManagedThemeFile;

            themeFile.VisualStyles.SystemMode = (nameof(Theme.Light), themeFile.VisualStyles.SystemMode.Item2);
            currentComponentTheme             = Theme.Light;
        }
 private void LoadThemeFile(string themeFile)
 {
     try
     {
         _themeFile = new ThemeFile(themeFile);
         DisplayThemeFile();
     }
     catch (Exception ex)
     {
         Logger.LogException(ex);
         _themeFile = null;
     }
 }
 private void CreateNewThemeFile()
 {
     try
     {
         _themeFile = new ThemeFile();
         DisplayThemeFile();
     }
     catch (Exception ex)
     {
         Logger.LogException(ex);
         _themeFile = null;
     }
 }
Example #12
0
        public static MenuItem AddMenuChild(
            ItemCollection parent,
            string locString,
            RelayCommand command,
            object commandParameter = null,
            object icon             = null)
        {
            var item = new MenuItem
            {
                Command          = command,
                CommandParameter = commandParameter,
                InputGestureText = command?.GestureText
            };

            if (locString.StartsWith("LOC"))
            {
                item.SetResourceReference(MenuItem.HeaderProperty, locString);
            }
            else
            {
                item.Header = locString;
            }

            if (icon != null)
            {
                if (icon is string stringIcon)
                {
                    item.Icon = Images.GetImageFromFile(ThemeFile.GetFilePath(stringIcon));
                }
                else if (icon is BitmapImage bitmap)
                {
                    var image = new Image()
                    {
                        Source = bitmap
                    };
                    RenderOptions.SetBitmapScalingMode(image, RenderOptions.GetBitmapScalingMode(bitmap));
                    item.Icon = image;
                }
                else if (icon is TextBlock textIcon)
                {
                    item.Icon = textIcon;
                }
            }

            parent.Add(item);
            return(item);
        }
Example #13
0
        internal void RevertFiles()
        {
            List <ThemeFileInfo>   themeFileInfoList = ThemeFileInfos.ToList();
            ThemeConfigurationData configuration     =
                ThemeConfigurationDatas.GetFactoryDefaultThemeConfigurationData(_siteThemeTypeId, _siteThemeName);

            themeFileInfoList.ForEach(info =>
            {
                if (info.HasConfiguredVersion)
                {
                    ThemeFiles.DeleteFile(info.ThemeFile.ThemeTypeID,
                                          info.ThemeFile.ThemeContextID, info.ThemeFile.ThemeName,
                                          info.ThemeFile.PropertyName, info.ThemeFile.FileName);

                    return;
                }

                if (info.HasDeletedConfiguredVersion)
                {
                    IEnumerable <ThemeFile> themeFiles = ThemeFiles.DeserializeThemeFiles(configuration,
                                                                                          info.ThemeFile.PropertyName,
                                                                                          configuration.GetCustomValue(info.ThemeFile.PropertyName, String.Empty));
                    ThemeFile themeFile =
                        themeFiles.FirstOrDefault(
                            t =>
                            String.Compare(t.FileName, info.ThemeFile.FileName,
                                           StringComparison.OrdinalIgnoreCase) == 0);

                    if (themeFile != null)
                    {
                        IList <ThemeFile> list = ThemeFiles.DeserializeThemeFiles(_siteThemeTypeId,
                                                                                  _themeContextId, _siteThemeName, info.ThemeFile.PropertyName,
                                                                                  _themeConfigurationData.GetCustomValue(
                                                                                      info.ThemeFile.PropertyName, String.Empty));

                        list.Add(themeFile);

                        string value = ThemeFiles.SerializeThemeFiles(list);

                        _themeConfigurationData.SetCustomValue(
                            info.ThemeFile.PropertyName, value);

                        ThemeConfigurationDatas.Update(_themeConfigurationData);
                    }
                }
            });
        }
Example #14
0
        private void CreateThemeFile(
            string descriptiveName,
            string imagePath,
            string backgroundColor,
            string mainTextColor,
            string secondaryTextColor,
            string fontFamily = "Georgia",
            int bottomMargin  = 100)
        {
            var file = new ThemeFile();

            var currentFolder = Environment.CurrentDirectory;
            var themePath     = Path.Combine(currentFolder, $"{descriptiveName}.onlyv");

            var theme = new OnlyVTheme();

            theme.Background.Colour = backgroundColor;

            theme.BodyText.Font.Family           = fontFamily;
            theme.BodyText.Font.Colour           = mainTextColor;
            theme.BodyText.DropShadow.Opacity    = 0.3;
            theme.BodyText.DropShadow.Depth      = 7;
            theme.BodyText.DropShadow.BlurRadius = 15;

            theme.TitleText.Font.Family           = fontFamily;
            theme.TitleText.Font.Colour           = secondaryTextColor;
            theme.TitleText.DropShadow.Opacity    = 0.3;
            theme.TitleText.DropShadow.Depth      = 7;
            theme.TitleText.DropShadow.BlurRadius = 15;

            theme.VerseNumbers.Colour = secondaryTextColor;

            theme.Dimensions.BottomMargin = bottomMargin;

            file.Create(themePath, theme, imagePath, overwrite: true);

            var result = file.Read(themePath);

            Assert.IsNotNull(result);

            var s1 = JsonConvert.SerializeObject(result.Theme);
            var s2 = JsonConvert.SerializeObject(theme);

            Assert.AreEqual(s1, s2);
        }
Example #15
0
        public void TestParseFromPhysicalPath()
        {
            string siteName     = "site1";
            string themeName    = "theme1";
            string fileName     = "style1";
            string extension    = ".css";
            string physicalPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sites", siteName, "themes", themeName, fileName + extension);

            var themeFile = new ThemeFile(physicalPath);

            Assert.AreEqual(fileName, themeFile.Name);
            Assert.AreEqual(extension, themeFile.FileExtension);

            Assert.AreEqual(themeName, themeFile.Theme.Name);

            Assert.IsTrue(themeFile.Site.IsDummy);
            Assert.AreEqual(siteName, themeFile.Site.Name);
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static IRenderTheme load(ThemeFile theme, ThemeCallback themeCallback) throws org.oscim.theme.IRenderTheme_ThemeException
        public static IRenderTheme load(ThemeFile theme, ThemeCallback themeCallback)
        {
            IRenderTheme t;

            if (theme.MapsforgeTheme)
            {
                t = Parameters.TEXTURE_ATLAS ? XmlMapsforgeAtlasThemeBuilder.read(theme, themeCallback) : XmlMapsforgeThemeBuilder.read(theme, themeCallback);
            }
            else
            {
                t = Parameters.TEXTURE_ATLAS ? XmlAtlasThemeBuilder.read(theme, themeCallback) : XmlThemeBuilder.read(theme, themeCallback);
            }
            if (t != null)
            {
                t.scaleTextSize(CanvasAdapter.Scale * CanvasAdapter.textScale);
            }
            return(t);
        }
        private void UiHandler()
        {
            //collapse changes saved message
            TextBlockUserFeedback.Visibility = Visibility.Collapsed;

            //give numbers to the steps
            TextBlockStep1.Text = AdmProperties.Resources.ThemeTutorialStep + " 1)";
            TextBlockStep2.Text = AdmProperties.Resources.ThemeTutorialStep + " 2)";
            TextBlockStep3.Text = AdmProperties.Resources.ThemeTutorialStep + " 3)";
            TextBlockStep4.Text = AdmProperties.Resources.ThemeTutorialStep + " 4)";

            //get all themes and select them in the combobox
            if (builder.Config.WindowsThemeMode.LightThemePath != null && builder.Config.WindowsThemeMode.DarkThemePath != null)
            {
                IEnumerable <string> themeNames = themeCollection.Select(t => t.ToString());
                ComboBoxDarkTheme.ItemsSource  = themeNames;
                ComboBoxLightTheme.ItemsSource = themeNames;
                ThemeFile lightSelected = themeCollection.FirstOrDefault(t => t.Path == builder.Config.WindowsThemeMode.LightThemePath);
                ThemeFile darkSelected  = themeCollection.FirstOrDefault(t => t.Path == builder.Config.WindowsThemeMode.DarkThemePath);
                if (lightSelected != null)
                {
                    ComboBoxLightTheme.SelectedItem = lightSelected.ToString();
                }
                if (darkSelected != null)
                {
                    ComboBoxDarkTheme.SelectedItem = darkSelected.ToString();
                }
            }

            if (builder.Config.WindowsThemeMode.MonitorActiveTheme)
            {
                CheckBoxMonitorActiveTheme.IsChecked = true;
            }

            //check if Windows Theme Mode is enabled
            if (builder.Config.WindowsThemeMode.Enabled)
            {
                ToggleSwitchThemeMode.IsOn = true;
            }
            else
            {
                DisableThemeMode();
            }
        }
        /// <param name="theme">         an input theme containing valid render theme XML data. </param>
        /// <param name="themeCallback"> the theme callback. </param>
        /// <returns> a new RenderTheme which is created by parsing the XML data from the input theme. </returns>
        /// <exception cref="ThemeException"> if an error occurs while parsing the render theme XML. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static IRenderTheme read(ThemeFile theme, ThemeCallback themeCallback) throws org.oscim.theme.IRenderTheme.ThemeException
        public static IRenderTheme read(ThemeFile theme, ThemeCallback themeCallback)
        {
            IDictionary <object, TextureRegion> outputMap    = new Dictionary <object, TextureRegion>();
            IList <TextureAtlas>          atlasList          = new List <TextureAtlas>();
            XmlMapsforgeAtlasThemeBuilder renderThemeHandler = new XmlMapsforgeAtlasThemeBuilder(theme, themeCallback, outputMap, atlasList);

            try
            {
                (new XMLReaderAdapter()).parse(renderThemeHandler, theme.RenderThemeAsStream);
            }
            catch (Exception e)
            {
                throw new ThemeException(e.Message);
            }

            TextureAtlasUtils.createTextureRegions(renderThemeHandler.bitmapMap, outputMap, atlasList, true, CanvasAdapter.platform == Platform.IOS);

            return(replaceThemeSymbols(renderThemeHandler.mRenderTheme, outputMap));
        }
Example #19
0
        private void ApplyFormatting(BibleTextImage bibleTextImage, string themePath)
        {
            var cacheEntry = ThemeFile.Read(themePath);

            OnlyVTheme  theme;
            ImageSource backgroundImage;

            if (cacheEntry == null)
            {
                // must use default...
                theme           = new OnlyVTheme();
                backgroundImage = BitmapHelper.ConvertBitmap(Properties.Resources.Blue);
            }
            else
            {
                theme           = cacheEntry.Theme;
                backgroundImage = cacheEntry.BackgroundImage;
            }

            ApplyFormatting(bibleTextImage, theme, backgroundImage);
        }
        /// <summary>
        /// Check if the given theme is a Mapsforge one.
        /// </summary>
        public static bool isMapsforgeTheme(ThemeFile theme)
        {
            try
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean isMapsforgeTheme = new java.util.concurrent.atomic.AtomicBoolean(false);
                AtomicBoolean isMapsforgeTheme = new AtomicBoolean(false);
                try
                {
                    (new XMLReaderAdapter()).parse(new DefaultHandlerAnonymousInnerClassHelper(isMapsforgeTheme), theme.RenderThemeAsStream);
                }
                catch (SAXTerminationException)
                {
                    // Do nothing
                }
                return(isMapsforgeTheme.get());
            }
            catch (Exception e)
            {
                log.error(e.Message, e);
                return(false);
            }
        }
Example #21
0
        IEnumerable <IThemeFile> BuildDirectoriesRecursively(string path, IThemeFile parent = null)
        {
            // Recurse directories
            var themeDirectory = _fileSystem.GetDirectoryInfo(path);

            foreach (var directory in themeDirectory.GetDirectories())
            {
                // Add directory
                var themeFile = new ThemeFile
                {
                    Name        = directory.Name,
                    FullName    = directory.FullName,
                    Parent      = parent,
                    IsDirectory = true
                };

                // Add files to directory
                foreach (var file in directory.GetFiles())
                {
                    themeFile.Children.Add(new ThemeFile()
                    {
                        Name     = file.Name,
                        FullName = file.FullName,
                        Parent   = themeFile
                    });
                }

                // Add current file as a child of the parent
                parent?.Children.Add(themeFile);

                // Recurse until we've processed all directories
                BuildDirectoriesRecursively(directory.FullName, themeFile);
            }

            return(parent?.Children ?? null);
        }
Example #22
0
        protected override void HandleSwitch(Theme newTheme, SwitchEventArgs e)
        {
            string oldTheme = Enum.GetName(typeof(Theme), currentComponentTheme);

            newTheme = newTheme == Theme.Dark ? Theme.Dark : Theme.Light;
            ThemeFile themeFile = GlobalState.ManagedThemeFile;

            if (Settings.Component.Mode == Mode.DarkOnly)
            {
                themeFile.VisualStyles.AppMode = (nameof(Theme.Dark), themeFile.VisualStyles.AppMode.Item2);
                currentComponentTheme          = Theme.Dark;
            }
            else if (Settings.Component.Mode == Mode.LightOnly)
            {
                themeFile.VisualStyles.AppMode = (nameof(Theme.Light), themeFile.VisualStyles.AppMode.Item2);
                currentComponentTheme          = Theme.Light;
            }
            else
            {
                themeFile.VisualStyles.AppMode = (Enum.GetName(typeof(Theme), newTheme), themeFile.VisualStyles.AppMode.Item2);
                currentComponentTheme          = newTheme;
            }
            Logger.Info($"update info - previous: {oldTheme}, now: {Enum.GetName(typeof(Theme), currentComponentTheme)}, mode: {Enum.GetName(typeof(Mode), Settings.Component.Mode)}");
        }
 public XmlMapsforgeAtlasThemeBuilder(ThemeFile theme, IDictionary <object, TextureRegion> regionMap, IList <TextureAtlas> atlasList) : this(theme, null, regionMap, atlasList)
 {
 }
Example #24
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);
        }
Example #25
0
 public ThemeViewer(ThemeFile themeFile)
 {
     theme = themeFile;
     InitializeComponent();
     tabControl1.TabPages.Remove(tabPage4);
 }
Example #26
0
        public static object ResolveUiItemIcon(object icon)
        {
            if (icon == null)
            {
                return(null);
            }

            if (icon is string stringIcon)
            {
                var resource = ResourceProvider.GetResource(stringIcon);
                if (resource != null)
                {
                    if (resource is BitmapImage bitmap)
                    {
                        var image = new System.Windows.Controls.Image()
                        {
                            Source = bitmap
                        };
                        RenderOptions.SetBitmapScalingMode(image, RenderOptions.GetBitmapScalingMode(bitmap));
                        return(image);
                    }
                    else if (resource is TextBlock textIcon)
                    {
                        var text = new TextBlock
                        {
                            Text       = textIcon.Text,
                            FontFamily = textIcon.FontFamily,
                            FontStyle  = textIcon.FontStyle
                        };

                        if (textIcon.ReadLocalValue(TextBlock.ForegroundProperty) != DependencyProperty.UnsetValue)
                        {
                            text.Foreground = textIcon.Foreground;
                        }

                        return(text);
                    }
                }
                else if (System.IO.File.Exists(stringIcon))
                {
                    return(BitmapExtensions.BitmapFromFile(stringIcon)?.ToImage());
                }
                else
                {
                    var themeFile = ThemeFile.GetFilePath(stringIcon);
                    if (themeFile != null)
                    {
                        return(Images.GetImageFromFile(themeFile, BitmapScalingMode.Fant, double.NaN, double.NaN));
                    }

                    var dbFile = GameDatabase.Instance.GetFileAsImage(stringIcon);
                    if (dbFile != null)
                    {
                        return(dbFile.ToImage());
                    }
                }
            }
            else
            {
                return(icon);
            }

            return(null);
        }
Example #27
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.ToggleGameDetailsCommand, Key = Key.Back
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.ToggleGameDetailsCommand, Key = Key.Escape
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.SelectPrevGameCommand, Key = Key.F2
                    });
                    ViewHost.InputBindings.Add(new KeyBinding()
                    {
                        Command = mainModel.SelectNextGameCommand, Key = Key.F3
                    });
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.ToggleGameDetailsCommand, XInputButton.B));
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.SelectPrevGameCommand, XInputButton.LeftShoulder));
                    ViewHost.InputBindings.Add(new XInputBinding(mainModel.SelectNextGameCommand, XInputButton.RightShoulder));

                    BindingTools.SetBinding(ViewHost,
                                            FocusBahaviors.FocusBindingProperty,
                                            mainModel,
                                            nameof(mainModel.GameDetailsFocused));
                }

                ButtonContext = Template.FindName("PART_ButtonContext", this) as ButtonBase;
                if (ButtonContext != null)
                {
                    BindingTools.SetBinding(
                        ButtonContext,
                        ButtonBase.CommandProperty,
                        mainModel,
                        $"{nameof(mainModel.SelectedGameDetails)}.{nameof(mainModel.SelectedGameDetails.ContextActionCommand)}");
                    BindingTools.SetBinding(
                        ButtonContext,
                        ButtonBase.ContentProperty,
                        mainModel,
                        $"{nameof(mainModel.SelectedGameDetails)}.{nameof(mainModel.SelectedGameDetails.ContextActionDescription)}");
                }

                ButtonOptions = Template.FindName("PART_ButtonOptions", this) as ButtonBase;
                if (ButtonOptions != null)
                {
                    ButtonOptions.Command = mainModel.OpenGameMenuCommand;
                }

                ImageCover = Template.FindName("PART_ImageCover", this) as Image;
                if (ImageCover != null)
                {
                    var sourceBinding = new PriorityBinding();
                    sourceBinding.Bindings.Add(new Binding()
                    {
                        Path      = new PropertyPath(nameof(GamesCollectionViewEntry.CoverImageObject)),
                        Converter = new NullToDependencyPropertyUnsetConverter()
                    });
                    sourceBinding.Bindings.Add(new Binding()
                    {
                        Path      = new PropertyPath(nameof(GamesCollectionViewEntry.DefaultCoverImageObject)),
                        Converter = new NullToDependencyPropertyUnsetConverter()
                    });

                    BindingOperations.SetBinding(ImageCover, Image.SourceProperty, sourceBinding);
                }

                ImageBackground = Template.FindName("PART_ImageBackground", this) as FadeImage;
                if (ImageBackground != null)
                {
                    BindingTools.SetBinding(ImageBackground,
                                            FadeImage.SourceProperty,
                                            nameof(GamesCollectionViewEntry.DisplayBackgroundImageObject));
                }

                HtmlDescription = Template.FindName("PART_HtmlDescription", this) as HtmlTextView;
                if (HtmlDescription != null)
                {
                    BindingTools.SetBinding(HtmlDescription,
                                            HtmlTextView.HtmlTextProperty,
                                            nameof(GamesCollectionViewEntry.Description));
                    HtmlDescription.TemplatePath = ThemeFile.GetFilePath("DescriptionView.html");
                }

                ControlTemplateTools.InitializePluginControls(
                    mainModel.Extensions,
                    Template,
                    this,
                    ApplicationMode.Fullscreen,
                    mainModel,
                    $"{nameof(FullscreenAppViewModel.SelectedGameDetails)}.{nameof(GameDetailsViewModel.Game)}.{nameof(GameDetailsViewModel.Game.Game)}");
            }
        }
Example #28
0
        private void LoadThemes()
        {
            Themes = Theme.FindThemes();
            // if no themes were found, add the default theme
            if (Themes.Count == 0)
            {
                Themes.Add(new Theme());
            }
            // find the user's current theme in the themes list
            Theme activeTheme = Themes.FirstOrDefault(t => t.FileName.ToLower().Trim() == ThemeFile.ToLower().Trim());

            // if the user's current theme is unable to be located, then use the first theme.
            if (activeTheme == null)
            {
                activeTheme = Themes[0];
            }
            // set the current theme to the theme located
            Theme = activeTheme;
        }
        /// <param name="theme"> an input theme containing valid render theme XML data. </param>
        /// <returns> a new RenderTheme which is created by parsing the XML data from the input theme. </returns>
        /// <exception cref="ThemeException"> if an error occurs while parsing the render theme XML. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static IRenderTheme read(ThemeFile theme) throws org.oscim.theme.IRenderTheme.ThemeException
        public static IRenderTheme read(ThemeFile theme)
        {
            return(read(theme, null));
        }
 public XmlMapsforgeAtlasThemeBuilder(ThemeFile theme, ThemeCallback themeCallback, IDictionary <object, TextureRegion> regionMap, IList <TextureAtlas> atlasList) : base(theme, themeCallback)
 {
     this.regionMap = regionMap;
     this.atlasList = atlasList;
 }
Example #31
0
 public ThemeViewer(ThemeFile themeFile)
 {
     theme = themeFile;
     InitializeComponent();
     tabControl1.TabPages.Remove(tabPage4);
 }