2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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.
18 using System.Collections.Concurrent;
19 using System.ComponentModel;
20 using System.Globalization;
21 using System.Runtime.InteropServices;
23 using System.Threading;
24 using System.Threading.Tasks;
26 using Tizen.Applications.CoreBackend;
28 namespace Tizen.Applications
31 /// This class represents an application controlled lifecycles by the backend system.
33 /// <since_tizen> 3 </since_tizen>
34 public class CoreApplication : Application
36 private readonly ICoreBackend _backend;
37 private readonly ICoreTask _task;
38 private bool _disposedValue = false;
40 private static System.Timers.Timer sTimer;
43 /// Initializes the CoreApplication class.
45 /// <param name="backend">The backend instance implementing ICoreBacked interface.</param>
46 /// <since_tizen> 3 </since_tizen>
47 public CoreApplication(ICoreBackend backend)
54 /// Initializes the CoreApplication class.
56 /// <param name="backend">The backend instance implementing ICoreBackend interface.</param>
57 /// <param name="task">The backend instance implmenting ICoreTask interface.</param>
58 /// <since_tizen> 10 </since_tizen>
59 [EditorBrowsable(EditorBrowsableState.Never)]
60 public CoreApplication(ICoreBackend backend, ICoreTask task)
67 /// Occurs when the application is launched.
69 /// <since_tizen> 3 </since_tizen>
70 public event EventHandler Created;
73 /// Occurs when the application is about to shutdown.
75 /// <since_tizen> 3 </since_tizen>
76 public event EventHandler Terminated;
79 /// Occurs whenever the application receives the appcontrol message.
81 /// <since_tizen> 3 </since_tizen>
82 public event EventHandler<AppControlReceivedEventArgs> AppControlReceived;
85 /// Occurs when the system memory is low.
87 /// <since_tizen> 3 </since_tizen>
88 public event EventHandler<LowMemoryEventArgs> LowMemory;
91 /// Occurs when the system battery is low.
93 /// <since_tizen> 3 </since_tizen>
94 public event EventHandler<LowBatteryEventArgs> LowBattery;
97 /// Occurs when the system language is chagned.
99 /// <since_tizen> 3 </since_tizen>
100 public event EventHandler<LocaleChangedEventArgs> LocaleChanged;
103 /// Occurs when the region format is changed.
105 /// <since_tizen> 3 </since_tizen>
106 public event EventHandler<RegionFormatChangedEventArgs> RegionFormatChanged;
109 /// Occurs when the device orientation is changed.
111 /// <since_tizen> 3 </since_tizen>
112 public event EventHandler<DeviceOrientationEventArgs> DeviceOrientationChanged;
115 /// The backend instance.
117 /// <since_tizen> 3 </since_tizen>
118 protected ICoreBackend Backend { get { return _backend; } }
121 /// Runs the application's main loop.
123 /// <param name="args">Arguments from commandline.</param>
124 /// <since_tizen> 3 </since_tizen>
125 public override void Run(string[] args)
129 _backend.AddEventHandler(EventType.Created, OnCreate);
130 _backend.AddEventHandler(EventType.Terminated, OnTerminate);
131 _backend.AddEventHandler<AppControlReceivedEventArgs>(EventType.AppControlReceived, OnAppControlReceived);
132 _backend.AddEventHandler<LowMemoryEventArgs>(EventType.LowMemory, OnLowMemory);
133 _backend.AddEventHandler<LowBatteryEventArgs>(EventType.LowBattery, OnLowBattery);
134 _backend.AddEventHandler<LocaleChangedEventArgs>(EventType.LocaleChanged, OnLocaleChanged);
135 _backend.AddEventHandler<RegionFormatChangedEventArgs>(EventType.RegionFormatChanged, OnRegionFormatChanged);
136 _backend.AddEventHandler<DeviceOrientationEventArgs>(EventType.DeviceOrientationChanged, OnDeviceOrientationChanged);
138 string[] argsClone = new string[args == null ? 1 : args.Length + 1];
139 if (args != null && args.Length > 1)
141 args.CopyTo(argsClone, 1);
143 argsClone[0] = string.Empty;
147 ICoreTaskBackend backend = (ICoreTaskBackend)_backend;
148 backend.SetCoreTask(_task);
149 backend.Run(argsClone);
153 _backend.Run(argsClone);
158 /// Exits the main loop of the application.
160 /// <since_tizen> 3 </since_tizen>
161 public override void Exit()
167 /// Overrides this method if want to handle behavior when the application is launched.
168 /// If base.OnCreated() is not called, the event 'Created' will not be emitted.
170 /// <since_tizen> 3 </since_tizen>
171 protected virtual void OnCreate()
175 TizenUISynchronizationContext.Initialize();
178 if (!GlobalizationMode.Invariant)
180 string locale = ULocale.GetDefaultLocale();
181 ChangeCurrentUICultureInfo(locale);
182 ChangeCurrentCultureInfo(locale);
186 Log.Warn(LogTag, "Run in invariant mode");
189 Created?.Invoke(this, EventArgs.Empty);
193 /// Overrides this method if want to handle behavior when the application is terminated.
194 /// If base.OnTerminate() is not called, the event 'Terminated' will not be emitted.
196 /// <since_tizen> 3 </since_tizen>
197 protected virtual void OnTerminate()
199 Terminated?.Invoke(this, EventArgs.Empty);
203 /// Overrides this method if want to handle behavior when the application receives the appcontrol message.
204 /// If base.OnAppControlReceived() is not called, the event 'AppControlReceived' will not be emitted.
206 /// <param name="e"></param>
207 /// <since_tizen> 3 </since_tizen>
208 protected virtual void OnAppControlReceived(AppControlReceivedEventArgs e)
210 AppControlReceived?.Invoke(this, e);
214 /// Overrides this method if want to handle behavior when the system memory is low.
215 /// If base.OnLowMemory() is not called, the event 'LowMemory' will not be emitted.
217 /// <param name="e">The low memory event argument</param>
218 /// <since_tizen> 3 </since_tizen>
219 protected virtual void OnLowMemory(LowMemoryEventArgs e)
221 LowMemory?.Invoke(this, e);
222 double interval = new Random().Next(10 * 1000);
224 interval = 10 * 1000;
226 sTimer = new System.Timers.Timer(interval);
227 sTimer.Elapsed += OnTimedEvent;
228 sTimer.AutoReset = false;
229 sTimer.Enabled = true;
232 private static void OnTimedEvent(Object source, ElapsedEventArgs e)
238 /// Overrides this method if want to handle behavior when the system battery is low.
239 /// If base.OnLowBattery() is not called, the event 'LowBattery' will not be emitted.
241 /// <param name="e">The low battery event argument</param>
242 /// <since_tizen> 3 </since_tizen>
243 protected virtual void OnLowBattery(LowBatteryEventArgs e)
245 LowBattery?.Invoke(this, e);
249 /// Overrides this method if want to handle behavior when the system language is changed.
250 /// If base.OnLocaleChanged() is not called, the event 'LocaleChanged' will not be emitted.
252 /// <param name="e">The locale changed event argument</param>
253 /// <since_tizen> 3 </since_tizen>
254 protected virtual void OnLocaleChanged(LocaleChangedEventArgs e)
256 if (!GlobalizationMode.Invariant)
258 ChangeCurrentUICultureInfo(e.Locale);
261 LocaleChanged?.Invoke(this, e);
265 /// Overrides this method if want to handle behavior when the region format is changed.
266 /// If base.OnRegionFormatChanged() is not called, the event 'RegionFormatChanged' will not be emitted.
268 /// <param name="e">The region format changed event argument</param>
269 /// <since_tizen> 3 </since_tizen>
270 protected virtual void OnRegionFormatChanged(RegionFormatChangedEventArgs e)
272 if (!GlobalizationMode.Invariant)
274 ChangeCurrentCultureInfo(e.Region);
277 RegionFormatChanged?.Invoke(this, e);
281 /// Overrides this method if want to handle behavior when the device orientation is changed.
282 /// If base.OnRegionFormatChanged() is not called, the event 'RegionFormatChanged' will not be emitted.
284 /// <param name="e">The device orientation changed event argument</param>
285 /// <since_tizen> 3 </since_tizen>
286 protected virtual void OnDeviceOrientationChanged(DeviceOrientationEventArgs e)
288 DeviceOrientationChanged?.Invoke(this, e);
292 /// Dispatches an asynchronous message to the main loop of the CoreTask.
294 /// <param name="runner">The runner callaback.</param>
295 /// <exception cref="ArgumentNullException">Thrown when the runner is null.</exception>
296 /// <since_tizen> 10 </since_tizen>
297 [EditorBrowsable(EditorBrowsableState.Never)]
298 public void Post(Action runner)
302 throw new ArgumentNullException(nameof(runner));
305 GSourceManager.Post(runner);
309 /// Dispatches an asynchronous message to the main loop of the CoreTask.
311 /// <typeparam name="T">The type of the result.</typeparam>
312 /// <param name="runner">The runner callback.</param>
313 /// <exception cref="ArgumentNullException">Thrown when the runner is null.</exception>
314 /// <returns>A task with the result.</returns>
315 /// <since_tizen> 10 </since_tizen>
316 [EditorBrowsable(EditorBrowsableState.Never)]
317 public async Task<T> Post<T>(Func<T> runner)
321 throw new ArgumentNullException(nameof(runner));
324 var task = new TaskCompletionSource<T>();
325 GSourceManager.Post(() => { task.SetResult(runner()); });
326 return await task.Task.ConfigureAwait(false);
330 /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
332 /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
333 /// <since_tizen> 3 </since_tizen>
334 protected override void Dispose(bool disposing)
343 _disposedValue = true;
345 base.Dispose(disposing);
348 private CultureInfo ConvertCultureInfo(string locale)
350 ULocale pLocale = new ULocale(locale);
351 string cultureName = CultureInfoHelper.GetCultureName(pLocale.Locale.Replace("_", "-"));
353 if (!string.IsNullOrEmpty(cultureName))
357 return new CultureInfo(cultureName);
359 catch (CultureNotFoundException)
361 Log.Error(LogTag, "CultureNotFoundException occurs. CultureName: " + cultureName);
367 return new CultureInfo(pLocale.LCID);
369 catch (ArgumentOutOfRangeException)
371 return GetFallbackCultureInfo(pLocale);
373 catch (CultureNotFoundException)
375 return GetFallbackCultureInfo(pLocale);
379 private void ChangeCurrentCultureInfo(string locale)
381 CultureInfo cultureInfo = ConvertCultureInfo(locale);
382 if (cultureInfo != null)
384 CultureInfo.CurrentCulture = cultureInfo;
388 Log.Error(LogTag, "CultureInfo is null. locale: " + locale);
392 private void ChangeCurrentUICultureInfo(string locale)
394 CultureInfo cultureInfo = ConvertCultureInfo(locale);
395 if (cultureInfo != null)
397 CultureInfo.CurrentUICulture = cultureInfo;
401 Log.Error(LogTag, "CultureInfo is null. locale: " + locale);
405 private bool ExistCultureInfo(string locale)
407 foreach (var cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures))
409 if (cultureInfo.Name == locale)
418 private CultureInfo GetCultureInfo(string locale)
420 if (!ExistCultureInfo(locale))
427 return new CultureInfo(locale);
429 catch (CultureNotFoundException)
435 private CultureInfo GetFallbackCultureInfo(ULocale uLocale)
437 CultureInfo fallbackCultureInfo = null;
438 string locale = string.Empty;
440 if (uLocale.Locale != null)
442 locale = uLocale.Locale.Replace("_", "-");
443 fallbackCultureInfo = GetCultureInfo(locale);
446 if (fallbackCultureInfo == null && uLocale.Language != null && uLocale.Script != null && uLocale.Country != null)
448 locale = uLocale.Language + "-" + uLocale.Script + "-" + uLocale.Country;
449 fallbackCultureInfo = GetCultureInfo(locale);
452 if (fallbackCultureInfo == null && uLocale.Language != null && uLocale.Script != null)
454 locale = uLocale.Language + "-" + uLocale.Script;
455 fallbackCultureInfo = GetCultureInfo(locale);
458 if (fallbackCultureInfo == null && uLocale.Language != null && uLocale.Country != null)
460 locale = uLocale.Language + "-" + uLocale.Country;
461 fallbackCultureInfo = GetCultureInfo(locale);
464 if (fallbackCultureInfo == null && uLocale.Language != null)
466 locale = uLocale.Language;
467 fallbackCultureInfo = GetCultureInfo(locale);
470 if (fallbackCultureInfo == null)
474 fallbackCultureInfo = new CultureInfo("en");
476 catch (CultureNotFoundException e)
478 Log.Error(LogTag, "Failed to create CultureInfo. err = " + e.Message);
482 return fallbackCultureInfo;
486 internal static class GlobalizationMode
488 private static int _invariant = -1;
490 internal static bool Invariant
494 if (_invariant == -1)
496 string value = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT");
497 _invariant = value != null ? (value.Equals("1") ? 1 : 0) : 0;
500 return _invariant != 0;
505 internal class ULocale
507 private const int ULOC_FULLNAME_CAPACITY = 157;
508 private const int ULOC_LANG_CAPACITY = 12;
509 private const int ULOC_SCRIPT_CAPACITY = 6;
510 private const int ULOC_COUNTRY_CAPACITY = 4;
511 private const int ULOC_VARIANT_CAPACITY = ULOC_FULLNAME_CAPACITY;
513 internal ULocale(string locale)
515 Locale = Canonicalize(locale);
516 Language = GetLanguage(Locale);
517 Script = GetScript(Locale);
518 Country = GetCountry(Locale);
519 Variant = GetVariant(Locale);
520 LCID = GetLCID(Locale);
523 internal string Locale { get; private set; }
524 internal string Language { get; private set; }
525 internal string Script { get; private set; }
526 internal string Country { get; private set; }
527 internal string Variant { get; private set; }
528 internal int LCID { get; private set; }
530 private string Canonicalize(string localeName)
532 // Get the locale name from ICU
533 StringBuilder sb = new StringBuilder(ULOC_FULLNAME_CAPACITY);
534 if (Interop.BaseUtilsi18n.Canonicalize(localeName, sb, sb.Capacity) <= 0)
539 return sb.ToString();
542 private string GetLanguage(string locale)
544 // Get the language name from ICU
545 StringBuilder sb = new StringBuilder(ULOC_LANG_CAPACITY);
546 if (Interop.BaseUtilsi18n.GetLanguage(locale, sb, sb.Capacity, out int bufSizeLanguage) != 0)
551 return sb.ToString();
554 private string GetScript(string locale)
556 // Get the script name from ICU
557 StringBuilder sb = new StringBuilder(ULOC_SCRIPT_CAPACITY);
558 if (Interop.BaseUtilsi18n.GetScript(locale, sb, sb.Capacity) <= 0)
563 return sb.ToString();
566 private string GetCountry(string locale)
570 // Get the country name from ICU
571 StringBuilder sb = new StringBuilder(ULOC_COUNTRY_CAPACITY);
572 if (Interop.BaseUtilsi18n.GetCountry(locale, sb, sb.Capacity, out err) <= 0)
577 return sb.ToString();
580 private string GetVariant(string locale)
582 // Get the variant name from ICU
583 StringBuilder sb = new StringBuilder(ULOC_VARIANT_CAPACITY);
584 if (Interop.BaseUtilsi18n.GetVariant(locale, sb, sb.Capacity) <= 0)
589 return sb.ToString();
592 private int GetLCID(string locale)
594 // Get the LCID from ICU
595 uint lcid = Interop.BaseUtilsi18n.GetLCID(locale);
599 internal static string GetDefaultLocale()
601 IntPtr stringPtr = IntPtr.Zero;
602 if (Interop.BaseUtilsi18n.GetDefault(out stringPtr) != 0)
607 if (stringPtr == IntPtr.Zero)
612 return Marshal.PtrToStringAnsi(stringPtr);