[NUI] Update theme system
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI / src / public / Theme / ThemeManager.cs
1 /*
2  * Copyright(c) 2021 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 #if !PROFILE_TV
19 #define ExternalThemeEnabled
20 #endif
21
22 using System;
23 using System.Collections.Generic;
24 using System.ComponentModel;
25 using System.Diagnostics;
26 using System.Diagnostics.CodeAnalysis;
27 using Tizen.NUI.BaseComponents;
28
29 namespace Tizen.NUI
30 {
31     /// <summary>
32     /// This static module provides methods that can manage NUI <see cref="Theme"/>.
33     /// </summary>
34     /// <example>
35     /// To apply custom theme to the application, try <see cref="ApplyTheme(Theme)"/>.
36     /// <code>
37     /// var customTheme = new Theme(res + "customThemeFile.xaml");
38     /// ThemeManager.ApplyTheme(customTheme);
39     /// </code>
40     /// </example>
41     /// <summary></summary>
42     /// <since_tizen> 9 </since_tizen>
43     public static class ThemeManager
44     {
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;
53
54         static ThemeManager()
55         {
56             ExternalThemeManager.Initialize();
57             AddPackageTheme(DefaultThemeCreator.Instance);
58         }
59
60         /// <summary>
61         /// An event invoked after the theme has changed by <see cref="ApplyTheme(Theme)"/>.
62         /// </summary>
63         /// <since_tizen> 9 </since_tizen>
64         public static event EventHandler<ThemeChangedEventArgs> ThemeChanged;
65
66         /// <summary>
67         /// Internal one should be called before calling public ThemeChanged
68         /// </summary>
69         internal static WeakEvent<EventHandler<ThemeChangedEventArgs>> ThemeChangedInternal = new WeakEvent<EventHandler<ThemeChangedEventArgs>>();
70
71         /// <summary>
72         /// The current theme Id.
73         /// It returns null when no theme is applied.
74         /// </summary>
75         [EditorBrowsable(EditorBrowsableState.Never)]
76         public static string ThemeId
77         {
78             get => userTheme?.Id;
79         }
80
81         /// <summary>
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">
86         /// <item>
87         /// <description>org.tizen.default-light-theme</description>
88         /// </item>
89         /// <item>
90         /// <description>org.tizen.default-dark-theme</description>
91         /// </item>
92         /// </list>
93         /// </summary>
94         [EditorBrowsable(EditorBrowsableState.Never)]
95         public static string PlatformThemeId
96         {
97             get => platformTheme?.Id;
98         }
99
100         /// <summary>
101         /// To support deprecated StyleManager.
102         /// NOTE that, please remove this after remove Tizen.NUI.Components.StyleManager
103         /// </summary>
104         internal static Theme BaseTheme
105         {
106             get => baseTheme;
107             set
108             {
109                 baseTheme = value;
110                 UpdateThemeForInitialize();
111             }
112         }
113
114         /// <summary>
115         /// To support deprecated StyleManager.
116         /// NOTE that, please remove this after remove Tizen.NUI.Components.StyleManager
117         /// </summary>
118         internal static Theme CurrentTheme
119         {
120             get => userTheme ?? baseTheme;
121             set
122             {
123                 userTheme = value;
124                 UpdateThemeForInitialize();
125                 NotifyThemeChanged();
126             }
127         }
128
129         internal static bool PlatformThemeEnabled
130         {
131             get => platformThemeEnabled;
132             set
133             {
134                 if (platformThemeEnabled == value) return;
135
136                 platformThemeEnabled = value;
137
138                 if (platformThemeEnabled)
139                 {
140                     ApplyExternalPlatformTheme(ExternalThemeManager.CurrentThemeId, ExternalThemeManager.CurrentThemeVersion);
141                 }
142             }
143         }
144
145         internal static bool ApplicationThemeChangeSensitive { get; set; } = false;
146
147         /// <summary>
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.
151         /// </summary>
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)
156         {
157             var newTheme = (Theme)theme?.Clone() ?? throw new ArgumentNullException(nameof(theme));
158
159             if (string.IsNullOrEmpty(newTheme.Id))
160             {
161                 newTheme.Id = "NONAME";
162             }
163
164             userTheme = newTheme;
165             UpdateThemeForInitialize();
166             UpdateThemeForUpdate();
167             NotifyThemeChanged();
168         }
169
170         /// <summary>
171         /// Change tizen theme.
172         /// User may change this to one of platform installed one.
173         /// </summary>
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)
179         {
180             if (themeId == null) throw new ArgumentNullException(nameof(themeId));
181
182             return ExternalThemeManager.SetTheme(themeId);
183         }
184
185         /// <summary>
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).
188         /// </summary>
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)
193         {
194             if (styleName == null) throw new ArgumentNullException(nameof(styleName));
195             return GetStyleWithoutClone(styleName)?.Clone();
196         }
197
198         /// <summary>
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.
201         /// </summary>
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)
206         {
207             if (viewType == null) throw new ArgumentNullException(nameof(viewType));
208             return GetStyleWithoutClone(viewType)?.Clone();
209         }
210
211         /// <summary>
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" />.
214         /// </summary>
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)
219         {
220             if (styleName == null) throw new ArgumentNullException(nameof(styleName));
221             return platformTheme?.GetStyle(styleName)?.Clone();
222         }
223
224         /// <summary>
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" />.
227         /// </summary>
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)
232         {
233             if (viewType == null) throw new ArgumentNullException(nameof(viewType));
234             return platformTheme?.GetStyle(viewType)?.Clone();
235         }
236
237         /// <summary>
238         /// Load a style with style name in the current theme.
239         /// </summary>
240         /// <param name="styleName">The style name.</param>
241         internal static ViewStyle GetStyleWithoutClone(string styleName) => userTheme?.GetStyle(styleName);
242
243         /// <summary>
244         /// Load a style with View type in the current theme.
245         /// </summary>
246         /// <param name="viewType">The type of View.</param>
247         internal static ViewStyle GetStyleWithoutClone(Type viewType) => userTheme?.GetStyle(viewType);
248
249         /// <summary>
250         /// Load a style with style name in the current theme.
251         /// </summary>
252         /// <param name="styleName">The style name.</param>
253         internal static ViewStyle GetUpdateStyleWithoutClone(string styleName) => themeForUpdate?.GetStyle(styleName);
254
255         /// <summary>
256         /// Load a style with View type in the current theme.
257         /// </summary>
258         /// <param name="viewType">The type of View.</param>
259         internal static ViewStyle GetUpdateStyleWithoutClone(Type viewType) => themeForUpdate?.GetStyle(viewType);
260
261         /// <summary>
262         /// Load a initial component style.
263         /// </summary>
264         internal static ViewStyle GetInitialStyleWithoutClone(string styleName) => themeForInitialize.GetStyle(styleName);
265
266         /// <summary>
267         /// Load a initial component style.
268         /// </summary>
269         internal static ViewStyle GetInitialStyleWithoutClone(Type viewType) => themeForInitialize.GetStyle(viewType);
270
271         /// <summary>
272         /// Get a platform installed theme.
273         /// </summary>
274         /// <param name="themeId">The theme id.</param>
275         internal static Theme LoadPlatformTheme(string themeId)
276         {
277             Debug.Assert(themeId != null);
278
279             // Check if it is already loaded.
280             int index = cachedPlatformThemes.FindIndex(x => string.Equals(x.Id, themeId, StringComparison.OrdinalIgnoreCase));
281             if (index >= 0)
282             {
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)
287                 {
288                     UpdatePlatformTheme(found);
289                     Tizen.Log.Info("NUI", $"Update cache.");
290                 }
291                 return found;
292             }
293
294             var newTheme = CreatePlatformTheme(themeId);
295             if (newTheme != null)
296             {
297                 cachedPlatformThemes.Add(newTheme);
298                 Tizen.Log.Info("NUI", $"Platform theme has been loaded successfully.");
299             }
300             return newTheme;
301         }
302
303         /// <summary>
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.
307         /// </summary>
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)
311         {
312             Debug.Assert(fallbackTheme != null);
313             BaseTheme = (Theme)fallbackTheme?.Clone();
314         }
315
316         /// <summary>
317         /// Apply an external platform theme.
318         /// </summary>
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)
322         {
323 #if ExternalThemeEnabled
324             Debug.Assert(baseTheme != null);
325
326             // If the given theme is invalid, do nothing.
327             if (string.IsNullOrEmpty(id))
328             {
329                 return;
330             }
331
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))
334             {
335                 Tizen.Log.Info("NUI", "The base theme can cover platform theme: Skip loading.");
336                 return;
337             }
338
339             // If the given theme is already applied, do nothing.
340             if (platformTheme != null && platformTheme.HasSameIdAndVersion(id, version))
341             {
342                 Tizen.Log.Info("NUI", "Platform theme is already applied: Skip loading.");
343                 return;
344             }
345
346             var loaded = LoadPlatformTheme(id);
347
348             if (loaded != null)
349             {
350                 Tizen.Log.Info("NUI", $"{loaded.Id} has been applied successfully.");
351                 platformTheme = loaded;
352                 UpdateThemeForInitialize();
353                 UpdateThemeForUpdate();
354                 NotifyThemeChanged(true);
355             }
356 #endif
357         }
358
359         internal static void AddPackageTheme(IThemeCreator themeCreator)
360         {
361             if (packages.Contains(themeCreator))
362             {
363                 return;
364             }
365
366             Tizen.Log.Info("NUI", $"AddPackageTheme({themeCreator.GetType().Assembly.GetName().Name})");
367             packages.Add(themeCreator);
368
369             // Base theme
370             var packageBaseTheme = themeCreator.Create();
371             Debug.Assert(packageBaseTheme != null);
372
373             if (baseTheme == null) baseTheme = packageBaseTheme;
374             else baseTheme.MergeWithoutClone(packageBaseTheme);
375             baseTheme.PackageCount++;
376
377 #if ExternalThemeEnabled
378             if (platformThemeEnabled)
379             {
380                 Tizen.Log.Info("NUI", $"Platform theme is enabled");
381                 if (platformTheme != null)
382                 {
383                     UpdatePlatformTheme(platformTheme);
384                 }
385                 else
386                 {
387                     if (!baseTheme.HasSameIdAndVersion(ExternalThemeManager.CurrentThemeId, ExternalThemeManager.CurrentThemeVersion))
388                     {
389                         var loaded = LoadPlatformTheme(ExternalThemeManager.CurrentThemeId);
390                         if (loaded != null)
391                         {
392                             platformTheme = loaded;
393                         }
394                     }
395                 }
396                 UpdateThemeForUpdate();
397             }
398 #endif
399             UpdateThemeForInitialize();
400         }
401
402         internal static void Preload()
403         {
404 #if ExternalThemeEnabled
405             Debug.Assert(baseTheme != null);
406
407             if (string.IsNullOrEmpty(ExternalThemeManager.CurrentThemeId)) return;
408
409             LoadPlatformTheme(ExternalThemeManager.CurrentThemeId);
410 #endif
411         }
412
413         // TODO Please make it private after removing Tizen.NUI.Components.StyleManager.
414         internal static void UpdateThemeForUpdate()
415         {
416             if (userTheme == null)
417             {
418                 themeForUpdate = platformTheme;
419                 return;
420             }
421
422             if (platformTheme == null)
423             {
424                 themeForUpdate = userTheme;
425                 return;
426             }
427
428             themeForUpdate = new Theme();
429             themeForUpdate.Merge(platformTheme);
430             themeForUpdate.MergeWithoutClone(userTheme);
431         }
432
433         // TODO Please make it private after removing Tizen.NUI.Components.StyleManager.
434         internal static void UpdateThemeForInitialize()
435         {
436             if (platformTheme == null && userTheme == null)
437             {
438                 themeForInitialize = baseTheme;
439                 return;
440             }
441
442             themeForInitialize = new Theme();
443             themeForInitialize.Merge(baseTheme);
444
445             if (userTheme == null)
446             {
447                 if (platformTheme != null) themeForInitialize.MergeWithoutClone(platformTheme);
448             }
449             else
450             {
451                 if (platformTheme != null) themeForInitialize.Merge(platformTheme);
452                 themeForInitialize.MergeWithoutClone(userTheme);
453             }
454         }
455
456         private static void UpdatePlatformTheme(Theme theme)
457         {
458             var sharedResourcePath = ExternalThemeManager.GetSharedResourcePath(theme.Id);
459
460             if (sharedResourcePath == null)
461             {
462                 return;
463             }
464
465             for (var i = theme.PackageCount; i < packages.Count; i++)
466             {
467                 theme.MergeWithoutClone(CreatePlatformTheme(sharedResourcePath, packages[i].GetType().Assembly.GetName().Name));
468             }
469             theme.PackageCount = packages.Count;
470         }
471
472         private static Theme CreatePlatformTheme(string id)
473         {
474             var sharedResourcePath = ExternalThemeManager.GetSharedResourcePath(id);
475
476             if (sharedResourcePath == null)
477             {
478                 return null;
479             }
480
481             var newTheme = new Theme()
482             {
483                 Id = id
484             };
485
486             foreach (var packageCreator in packages)
487             {
488                 newTheme.MergeWithoutClone(CreatePlatformTheme(sharedResourcePath, packageCreator.GetType().Assembly.GetName().Name));
489             }
490             newTheme.PackageCount = packages.Count;
491
492             return newTheme;
493         }
494
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)
497         {
498             ExternalThemeManager.SharedResourcePath = sharedResourcePath;
499             try
500             {
501                 return new Theme(sharedResourcePath + assemblyName + ".Theme.xaml");
502             }
503             catch (System.IO.FileNotFoundException)
504             {
505                 Tizen.Log.Info("NUI", $"[Ignorable] Current tizen theme does not have NUI theme.");
506             }
507             catch (Exception e)
508             {
509                 Tizen.Log.Info("NUI", $"[Ignorable] {e.GetType().Name} occurred while applying tizen theme to {assemblyName}: {e.Message}");
510             }
511
512             return new Theme();
513         }
514
515         private static void AddToPlatformThemes(Theme theme)
516         {
517             int index = cachedPlatformThemes.FindIndex(x => x.Id.Equals(theme.Id, StringComparison.OrdinalIgnoreCase));
518             if (index >= 0)
519             {
520                 Tizen.Log.Info("NUI", $"Existing {theme.Id} item is overwritten");
521                 cachedPlatformThemes[index] = theme;
522             }
523             else
524             {
525                 cachedPlatformThemes.Add(theme);
526                 Tizen.Log.Info("NUI", $"New {theme.Id} is saved.");
527             }
528         }
529
530         private static void NotifyThemeChanged(bool platformThemeUpdated = false)
531         {
532             Debug.Assert(baseTheme != null);
533
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));
538         }
539     }
540 }