2 * Copyright(c) 2021 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #define ExternalThemeEnabled
23 using System.Collections.Generic;
24 using System.ComponentModel;
25 using System.Diagnostics;
26 using System.Diagnostics.CodeAnalysis;
27 using Tizen.NUI.BaseComponents;
32 /// This static module provides methods that can manage NUI <see cref="Theme"/>.
35 /// To apply custom theme to the application, try <see cref="ApplyTheme(Theme)"/>.
37 /// var customTheme = new Theme(res + "customThemeFile.xaml");
38 /// ThemeManager.ApplyTheme(customTheme);
41 /// <summary></summary>
42 /// <since_tizen> 9 </since_tizen>
43 public static class ThemeManager
45 private static Theme baseTheme; // The base theme. It includes all styles including structures (Size, Position, Policy) of components.
46 private static Theme platformTheme; // The platform theme. This may include color and image information without structure detail.
47 private static Theme userTheme; // The user custom theme.
48 private static Theme themeForUpdate; // platformTheme + userTheme. It is used when the component need to update according to theme change.
49 private static Theme themeForInitialize; // baseTheme + platformTheme + userTheme. It is used when the component is created.
50 private static readonly List<Theme> cachedPlatformThemes = new List<Theme>(); // Themes provided by framework.
51 private static readonly List<IThemeCreator> packages = new List<IThemeCreator>();// This is to store base theme creators by packages.
52 private static bool platformThemeEnabled = false;
56 ExternalThemeManager.Initialize();
57 AddPackageTheme(DefaultThemeCreator.Instance);
61 /// An event invoked after the theme has changed by <see cref="ApplyTheme(Theme)"/>.
63 /// <since_tizen> 9 </since_tizen>
64 public static event EventHandler<ThemeChangedEventArgs> ThemeChanged;
67 /// Internal one should be called before calling public ThemeChanged
69 internal static WeakEvent<EventHandler<ThemeChangedEventArgs>> ThemeChangedInternal = new WeakEvent<EventHandler<ThemeChangedEventArgs>>();
72 /// The current theme Id.
73 /// It returns null when no theme is applied.
75 [EditorBrowsable(EditorBrowsableState.Never)]
76 public static string ThemeId
82 /// The current platform theme Id.
83 /// Note that it returns null when the platform theme is disabled.
84 /// If the <seealso cref="NUIApplication.ThemeOptions.PlatformThemeEnabled"/> is given, it can be one of followings in tizen 6.5:
85 /// <list type="bullet">
87 /// <description>org.tizen.default-light-theme</description>
90 /// <description>org.tizen.default-dark-theme</description>
94 [EditorBrowsable(EditorBrowsableState.Never)]
95 public static string PlatformThemeId
97 get => platformTheme?.Id;
101 /// To support deprecated StyleManager.
102 /// NOTE that, please remove this after remove Tizen.NUI.Components.StyleManager
104 internal static Theme BaseTheme
110 UpdateThemeForInitialize();
115 /// To support deprecated StyleManager.
116 /// NOTE that, please remove this after remove Tizen.NUI.Components.StyleManager
118 internal static Theme CurrentTheme
120 get => userTheme ?? baseTheme;
124 UpdateThemeForInitialize();
125 NotifyThemeChanged();
129 internal static bool PlatformThemeEnabled
131 get => platformThemeEnabled;
134 if (platformThemeEnabled == value) return;
136 platformThemeEnabled = value;
138 if (platformThemeEnabled)
140 ApplyExternalPlatformTheme(ExternalThemeManager.CurrentThemeId, ExternalThemeManager.CurrentThemeVersion);
145 internal static bool ApplicationThemeChangeSensitive { get; set; } = false;
148 /// Apply custom theme to the NUI.
149 /// This will change the appearance of the existing components with property <seealso cref="View.ThemeChangeSensitive"/> on.
150 /// This also affects all components created afterwards.
152 /// <param name="theme">The theme instance to be applied.</param>
153 /// <exception cref="ArgumentNullException">Thrown when the given theme is null.</exception>
154 /// <since_tizen> 9 </since_tizen>
155 public static void ApplyTheme(Theme theme)
157 var newTheme = (Theme)theme?.Clone() ?? throw new ArgumentNullException(nameof(theme));
159 if (string.IsNullOrEmpty(newTheme.Id))
161 newTheme.Id = "NONAME";
164 userTheme = newTheme;
165 UpdateThemeForInitialize();
166 UpdateThemeForUpdate();
167 NotifyThemeChanged();
171 /// Change tizen theme.
172 /// User may change this to one of platform installed one.
174 /// <param name="themeId">The installed theme Id.</param>
175 /// <returns>true on success, false when it failed to find installed theme with given themeId.</returns>
176 /// <exception cref="ArgumentNullException">Thrown when the given themeId is null.</exception>
177 [EditorBrowsable(EditorBrowsableState.Never)]
178 public static bool ApplyPlatformTheme(string themeId)
180 if (themeId == null) throw new ArgumentNullException(nameof(themeId));
182 return ExternalThemeManager.SetTheme(themeId);
186 /// Load a style with style name in the current theme.
187 /// For components, the default style name of a component is a component name with namespace (e.g. Tizen.NUI.Components.Button).
189 /// <param name="styleName">The style name.</param>
190 /// <exception cref="ArgumentNullException">Thrown when the given styleName is null.</exception>
191 /// <since_tizen> 9 </since_tizen>
192 public static ViewStyle GetStyle(string styleName)
194 if (styleName == null) throw new ArgumentNullException(nameof(styleName));
195 return GetStyleWithoutClone(styleName)?.Clone();
199 /// Load a style with view type in the current theme.
200 /// If it failed to find a style with the given type, it will try with it's parent type until it succeeds.
202 /// <param name="viewType"> The type of the view. Full name of the given type will be a key to find a style in the current theme. (e.g. Tizen.NUI.Components.Button) </param>
203 /// <exception cref="ArgumentNullException">Thrown when the given viewType is null.</exception>
204 /// <since_tizen> 9 </since_tizen>
205 public static ViewStyle GetStyle(Type viewType)
207 if (viewType == null) throw new ArgumentNullException(nameof(viewType));
208 return GetStyleWithoutClone(viewType)?.Clone();
212 /// Load a platform style with style name in the current theme.
213 /// It returns null when the platform theme is disabled. <see cref="NUIApplication.ThemeOptions.PlatformThemeEnabled" />.
215 /// <param name="styleName">The style name.</param>
216 /// <exception cref="ArgumentNullException">Thrown when the given styleName is null.</exception>
217 [EditorBrowsable(EditorBrowsableState.Never)]
218 public static ViewStyle GetPlatformStyle(string styleName)
220 if (styleName == null) throw new ArgumentNullException(nameof(styleName));
221 return platformTheme?.GetStyle(styleName)?.Clone();
225 /// Load a platform style with view type in the current theme.
226 /// It returns null when the platform theme is disabled. <see cref="NUIApplication.ThemeOptions.PlatformThemeEnabled" />.
228 /// <param name="viewType"> The type of the view. Full name of the given type will be a key to find a style in the current theme. (e.g. Tizen.NUI.Components.Button) </param>
229 /// <exception cref="ArgumentNullException">Thrown when the given viewType is null.</exception>
230 [EditorBrowsable(EditorBrowsableState.Never)]
231 public static ViewStyle GetPlatformStyle(Type viewType)
233 if (viewType == null) throw new ArgumentNullException(nameof(viewType));
234 return platformTheme?.GetStyle(viewType)?.Clone();
238 /// Load a style with style name in the current theme.
240 /// <param name="styleName">The style name.</param>
241 internal static ViewStyle GetStyleWithoutClone(string styleName) => userTheme?.GetStyle(styleName);
244 /// Load a style with View type in the current theme.
246 /// <param name="viewType">The type of View.</param>
247 internal static ViewStyle GetStyleWithoutClone(Type viewType) => userTheme?.GetStyle(viewType);
250 /// Load a style with style name in the current theme.
252 /// <param name="styleName">The style name.</param>
253 internal static ViewStyle GetUpdateStyleWithoutClone(string styleName) => themeForUpdate?.GetStyle(styleName);
256 /// Load a style with View type in the current theme.
258 /// <param name="viewType">The type of View.</param>
259 internal static ViewStyle GetUpdateStyleWithoutClone(Type viewType) => themeForUpdate?.GetStyle(viewType);
262 /// Load a initial component style.
264 internal static ViewStyle GetInitialStyleWithoutClone(string styleName) => themeForInitialize.GetStyle(styleName);
267 /// Load a initial component style.
269 internal static ViewStyle GetInitialStyleWithoutClone(Type viewType) => themeForInitialize.GetStyle(viewType);
272 /// Get a platform installed theme.
274 /// <param name="themeId">The theme id.</param>
275 internal static Theme LoadPlatformTheme(string themeId)
277 Debug.Assert(themeId != null);
279 // Check if it is already loaded.
280 int index = cachedPlatformThemes.FindIndex(x => string.Equals(x.Id, themeId, StringComparison.OrdinalIgnoreCase));
283 Tizen.Log.Info("NUI", $"Hit cache.");
284 var found = cachedPlatformThemes[index];
285 // If the cached is not a full set, update it.
286 if (found.PackageCount < packages.Count)
288 UpdatePlatformTheme(found);
289 Tizen.Log.Info("NUI", $"Update cache.");
294 var newTheme = CreatePlatformTheme(themeId);
295 if (newTheme != null)
297 cachedPlatformThemes.Add(newTheme);
298 Tizen.Log.Info("NUI", $"Platform theme has been loaded successfully.");
304 /// !!! This is for internal use in fhub-nui. Please do not open it.
305 /// Set a theme to be used as fallback.
306 /// The fallback theme is set to profile specified theme by default.
308 /// <param name="fallbackTheme">The theme instance to be applied as a fallback.</param>
309 [EditorBrowsable(EditorBrowsableState.Never)]
310 internal static void ApplyFallbackTheme(Theme fallbackTheme)
312 Debug.Assert(fallbackTheme != null);
313 BaseTheme = (Theme)fallbackTheme?.Clone();
317 /// Apply an external platform theme.
319 /// <param name="id">The external theme id.</param>
320 /// <param name="version">The external theme version.</param>
321 internal static void ApplyExternalPlatformTheme(string id, string version)
323 #if ExternalThemeEnabled
324 Debug.Assert(baseTheme != null);
326 // If the given theme is invalid, do nothing.
327 if (string.IsNullOrEmpty(id))
332 // If no platform theme has been applied and the base theme can cover the given one, do nothing.
333 if (platformTheme == null && baseTheme.HasSameIdAndVersion(id, version))
335 Tizen.Log.Info("NUI", "The base theme can cover platform theme: Skip loading.");
339 // If the given theme is already applied, do nothing.
340 if (platformTheme != null && platformTheme.HasSameIdAndVersion(id, version))
342 Tizen.Log.Info("NUI", "Platform theme is already applied: Skip loading.");
346 var loaded = LoadPlatformTheme(id);
350 Tizen.Log.Info("NUI", $"{loaded.Id} has been applied successfully.");
351 platformTheme = loaded;
352 UpdateThemeForInitialize();
353 UpdateThemeForUpdate();
354 NotifyThemeChanged(true);
359 internal static void AddPackageTheme(IThemeCreator themeCreator)
361 if (packages.Contains(themeCreator))
366 Tizen.Log.Info("NUI", $"AddPackageTheme({themeCreator.GetType().Assembly.GetName().Name})");
367 packages.Add(themeCreator);
370 var packageBaseTheme = themeCreator.Create();
371 Debug.Assert(packageBaseTheme != null);
373 if (baseTheme == null) baseTheme = packageBaseTheme;
374 else baseTheme.MergeWithoutClone(packageBaseTheme);
375 baseTheme.PackageCount++;
377 #if ExternalThemeEnabled
378 if (platformThemeEnabled)
380 Tizen.Log.Info("NUI", $"Platform theme is enabled");
381 if (platformTheme != null)
383 UpdatePlatformTheme(platformTheme);
387 if (!baseTheme.HasSameIdAndVersion(ExternalThemeManager.CurrentThemeId, ExternalThemeManager.CurrentThemeVersion))
389 var loaded = LoadPlatformTheme(ExternalThemeManager.CurrentThemeId);
392 platformTheme = loaded;
396 UpdateThemeForUpdate();
399 UpdateThemeForInitialize();
402 internal static void Preload()
404 #if ExternalThemeEnabled
405 Debug.Assert(baseTheme != null);
407 if (string.IsNullOrEmpty(ExternalThemeManager.CurrentThemeId)) return;
409 LoadPlatformTheme(ExternalThemeManager.CurrentThemeId);
413 // TODO Please make it private after removing Tizen.NUI.Components.StyleManager.
414 internal static void UpdateThemeForUpdate()
416 if (userTheme == null)
418 themeForUpdate = platformTheme;
422 if (platformTheme == null)
424 themeForUpdate = userTheme;
428 themeForUpdate = new Theme();
429 themeForUpdate.Merge(platformTheme);
430 themeForUpdate.MergeWithoutClone(userTheme);
433 // TODO Please make it private after removing Tizen.NUI.Components.StyleManager.
434 internal static void UpdateThemeForInitialize()
436 if (platformTheme == null && userTheme == null)
438 themeForInitialize = baseTheme;
442 themeForInitialize = new Theme();
443 themeForInitialize.Merge(baseTheme);
445 if (userTheme == null)
447 if (platformTheme != null) themeForInitialize.MergeWithoutClone(platformTheme);
451 if (platformTheme != null) themeForInitialize.Merge(platformTheme);
452 themeForInitialize.MergeWithoutClone(userTheme);
456 private static void UpdatePlatformTheme(Theme theme)
458 var sharedResourcePath = ExternalThemeManager.GetSharedResourcePath(theme.Id);
460 if (sharedResourcePath == null)
465 for (var i = theme.PackageCount; i < packages.Count; i++)
467 theme.MergeWithoutClone(CreatePlatformTheme(sharedResourcePath, packages[i].GetType().Assembly.GetName().Name));
469 theme.PackageCount = packages.Count;
472 private static Theme CreatePlatformTheme(string id)
474 var sharedResourcePath = ExternalThemeManager.GetSharedResourcePath(id);
476 if (sharedResourcePath == null)
481 var newTheme = new Theme()
486 foreach (var packageCreator in packages)
488 newTheme.MergeWithoutClone(CreatePlatformTheme(sharedResourcePath, packageCreator.GetType().Assembly.GetName().Name));
490 newTheme.PackageCount = packages.Count;
495 [SuppressMessage("Microsoft.Design", "CA1031: Do not catch general exception types", Justification = "This method is to handle external resources that may throw an exception but ignorable. This method should not interrupt the main stream.")]
496 private static Theme CreatePlatformTheme(string sharedResourcePath, string assemblyName)
498 ExternalThemeManager.SharedResourcePath = sharedResourcePath;
501 return new Theme(sharedResourcePath + assemblyName + ".Theme.xaml");
503 catch (System.IO.FileNotFoundException)
505 Tizen.Log.Info("NUI", $"[Ignorable] Current tizen theme does not have NUI theme.");
509 Tizen.Log.Info("NUI", $"[Ignorable] {e.GetType().Name} occurred while applying tizen theme to {assemblyName}: {e.Message}");
515 private static void AddToPlatformThemes(Theme theme)
517 int index = cachedPlatformThemes.FindIndex(x => x.Id.Equals(theme.Id, StringComparison.OrdinalIgnoreCase));
520 Tizen.Log.Info("NUI", $"Existing {theme.Id} item is overwritten");
521 cachedPlatformThemes[index] = theme;
525 cachedPlatformThemes.Add(theme);
526 Tizen.Log.Info("NUI", $"New {theme.Id} is saved.");
530 private static void NotifyThemeChanged(bool platformThemeUpdated = false)
532 Debug.Assert(baseTheme != null);
534 var platformThemeId = platformTheme?.Id;
535 var userThemeId = userTheme?.Id;
536 ThemeChangedInternal.Invoke(null, new ThemeChangedEventArgs(userThemeId, platformThemeId, platformThemeUpdated));
537 ThemeChanged?.Invoke(null, new ThemeChangedEventArgs(userThemeId, platformThemeId, platformThemeUpdated));