Skip to content

Commit

Permalink
[CastIt] Added a splash page
Browse files Browse the repository at this point in the history
  • Loading branch information
Wolfteam committed Nov 6, 2020
1 parent a7fed65 commit b472fa6
Show file tree
Hide file tree
Showing 13 changed files with 296 additions and 63 deletions.
2 changes: 1 addition & 1 deletion CastIt/Application.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public override void Initialize()
Mvx.IoCProvider.RegisterType<DeviceItemViewModel>();
Mvx.IoCProvider.ConstructAndRegisterSingleton(typeof(SettingsViewModel));

RegisterAppStart<MainViewModel>();
RegisterAppStart<SplashViewModel>();
}

private IMapper CreateMapper()
Expand Down
3 changes: 0 additions & 3 deletions CastIt/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,10 @@
xmlns:views="clr-namespace:MvvmCross.Platforms.Wpf.Views;assembly=MvvmCross.Platforms.Wpf"
x:Name="AppMainWindow"
Title="{x:Static common:AppConstants.AppName}"
MinWidth="{x:Static common:AppConstants.MinWindowWidth}"
MinHeight="{x:Static common:AppConstants.MinWindowHeight}"
AllowsTransparency="True"
Icon="/Resources/favicon.ico"
Loaded="AppMainWindow_Loaded"
MouseDown="Window_MouseDown"
ResizeMode="CanResize"
SizeChanged="AppMainWindow_SizeChanged"
Style="{StaticResource WindowStyle}"
WindowStartupLocation="CenterScreen"
Expand Down
2 changes: 2 additions & 0 deletions CastIt/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ private void AppMainWindow_Loaded(object sender, RoutedEventArgs e)
private void AppMainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
var view = Content as MainPage;
if (view == null)
return;

if (e.NewSize.Height <= AppConstants.MinWindowHeight &&
view.ViewModel.IsExpanded)
Expand Down
9 changes: 9 additions & 0 deletions CastIt/Resources/Resource.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions CastIt/Resources/Resource.es.resx
Original file line number Diff line number Diff line change
Expand Up @@ -531,4 +531,7 @@
<data name="FileCouldntBeOpened" xml:space="preserve">
<value>El archivo no puedo ser abierto</value>
</data>
<data name="Loading" xml:space="preserve">
<value>Cargando</value>
</data>
</root>
3 changes: 3 additions & 0 deletions CastIt/Resources/Resource.resx
Original file line number Diff line number Diff line change
Expand Up @@ -531,4 +531,7 @@
<data name="FileCouldntBeOpened" xml:space="preserve">
<value>File could not be opened</value>
</data>
<data name="Loading" xml:space="preserve">
<value>Loading</value>
</data>
</root>
1 change: 1 addition & 0 deletions CastIt/Setup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ protected override IMvxLogProvider CreateLogProvider()
{$"{typeof(FileItemViewModel).FullName}", "vm_fileitem_.txt"},
{$"{typeof(DeviceItemViewModel).FullName}", "vm_deviceitem_.txt"},
{$"{typeof(DownloadDialogViewModel).FullName}", "vm_download_dialog_.txt"},
{$"{typeof(SplashViewModel).FullName}", "vm_splash_.txt"},
{$"{typeof(CastService).FullName}", "service_cast_.txt"},
{$"{typeof(AppSettingsService).FullName}", "service_appsettings_.txt"},
{$"{typeof(FFMpegService).FullName}", "service_ffmpeg_.txt"},
Expand Down
67 changes: 67 additions & 0 deletions CastIt/ViewModels/BaseViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,73 @@ public string GetText(string key, params string[] args)
?? throw new Exception($"{key} was not found in the resources file");
}

public abstract class BaseViewModel<TParameter> : MvxViewModel<TParameter>, IBaseViewModel
{
#region Members
public List<MvxSubscriptionToken> SubscriptionTokens = new List<MvxSubscriptionToken>();
#endregion

#region Properties
public ITextProvider TextProvider { get; }
public IMvxMessenger Messenger { get; }
public IMvxLog Logger { get; }
public string this[string key]
=> TextProvider.GetText(string.Empty, string.Empty, key)
?? throw new Exception($"{key} was not found in the resources file");
#endregion

protected BaseViewModel(
ITextProvider textProvider,
IMvxMessenger messenger,
IMvxLog logger)
{
TextProvider = textProvider;
Messenger = messenger;
Logger = logger;

RegisterMessages();
SetCommands();
}

public virtual void SetCommands()
{
}

public virtual void RegisterMessages()
{
SubscriptionTokens.Add(Messenger.Subscribe<AppLanguageChangedMessage>(_ => RaiseAllPropertiesChanged()));
}

public override void ViewAppeared()
{
base.ViewAppeared();
if (SubscriptionTokens.Count == 0)
{
RegisterMessages();
}
}

public override void ViewDestroy(bool viewFinishing = true)
{
base.ViewDestroy(viewFinishing);
if (!viewFinishing)
return;
foreach (var token in SubscriptionTokens)
{
token.Dispose();
}
SubscriptionTokens.Clear();
}

public string GetText(string key)
=> TextProvider.GetText(string.Empty, string.Empty, key)
?? throw new Exception($"{key} was not found in the resources file");

public string GetText(string key, params string[] args)
=> TextProvider.GetText(string.Empty, string.Empty, key, args)
?? throw new Exception($"{key} was not found in the resources file");
}

public abstract class BaseViewModelResult<TResult> : MvxViewModelResult<TResult>, IBaseViewModel
{
#region Members
Expand Down
42 changes: 7 additions & 35 deletions CastIt/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

namespace CastIt.ViewModels
{
public class MainViewModel : BaseViewModel, IMainViewModel
public class MainViewModel : BaseViewModel<List<PlayListItemViewModel>>, IMainViewModel
{
#region Members
private const int NoStreamSelectedId = -1;
Expand Down Expand Up @@ -66,7 +66,6 @@ public class MainViewModel : BaseViewModel, IMainViewModel
private readonly CancellationTokenSource _webServerCancellationToken = new CancellationTokenSource();

private readonly MvxInteraction _closeApp = new MvxInteraction();
private readonly MvxInteraction<(double, double)> _setWindowWidthAndHeight = new MvxInteraction<(double, double)>();
private readonly MvxInteraction _openSubTitleFileDialog = new MvxInteraction();
private readonly MvxInteraction<PlayListItemViewModel> _beforeDeletingPlayList = new MvxInteraction<PlayListItemViewModel>();
#endregion
Expand Down Expand Up @@ -246,8 +245,6 @@ public int CurrentFileQuality
#region Interactors
public IMvxInteraction CloseApp
=> _closeApp;
public IMvxInteraction<(double, double)> SetWindowWidthAndHeight
=> _setWindowWidthAndHeight;
public IMvxInteraction OpenSubTitleFileDialog
=> _openSubTitleFileDialog;
public IMvxInteraction<PlayListItemViewModel> BeforeDeletingPlayList
Expand Down Expand Up @@ -279,25 +276,18 @@ public MainViewModel(
}

#region Methods

public override void Prepare(List<PlayListItemViewModel> parameter)
{
PlayLists.AddRange(parameter.OrderBy(pl => pl.Position));
}

public override async Task Initialize()
{
IsExpanded = _settingsService.IsPlayListExpanded;
Logger.Info($"{nameof(Initialize)}: Initializing cast service...");
_castService.Init();

Logger.Info($"{nameof(Initialize)}: Getting all playlists...");
var playLists = await _playListsService.GetAllPlayLists();
PlayLists.AddRange(playLists.OrderBy(pl => pl.Position));
foreach (var playlist in playLists)
{
var files = await _playListsService.GetAllFiles(playlist.Id);
playlist.Items.AddRange(files.OrderBy(f => f.Position));
}

foreach (var pl in PlayLists)
{
pl.SetPositionIfChanged();
}
//This needs to happen after the playlist/files are initialized, otherwise, you will be sending a lot of ws msgs
Logger.Info($"{nameof(Initialize)}: Initializing web server...");
_appWebServer.Init(this, _webServerCancellationToken.Token);
Expand All @@ -314,21 +304,6 @@ public override async Task Initialize()
_castService.OnVolumeChanged += OnVolumeChanged;
_castService.OnFileLoadFailed += OnFileLoadFailed;

Logger.Info($"{nameof(Initialize)}: Applying app theme and accent color...");
WindowsUtils.ChangeTheme(_settingsService.AppTheme, _settingsService.AccentColor);

Logger.Info($"{nameof(Initialize)}: Deleting old preview / log files...");
try
{
FileUtils.DeleteFilesInDirectory(FileUtils.GetPreviewsPath(), DateTime.Now.AddDays(-1));
FileUtils.DeleteFilesInDirectory(FileUtils.GetLogsPath(), DateTime.Now.AddDays(-3));
}
catch (Exception e)
{
Logger.Error(e, $"{nameof(Initialize)}: Error occurred while trying to delete previews");
_telemetryService.TrackError(e);
}

InitializeOrUpdateFileWatcher(false);

Logger.Info($"{nameof(Initialize)}: Completed");
Expand Down Expand Up @@ -405,9 +380,6 @@ public override void RegisterMessages()
public override void ViewAppeared()
{
base.ViewAppeared();
var tuple = (_settingsService.WindowWidth, _settingsService.WindowHeight);
_setWindowWidthAndHeight.Raise(tuple);

Logger.Info($"{nameof(ViewAppeared)}: Creating the file duration task..");
DurationTaskNotifier = MvxNotifyTask.Create(SetFileDurations());
string path = FileUtils.GetFFMpegPath();
Expand Down
109 changes: 109 additions & 0 deletions CastIt/ViewModels/SplashViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using CastIt.Common.Utils;
using CastIt.Interfaces;
using CastIt.ViewModels.Items;
using MvvmCross.Logging;
using MvvmCross.Navigation;
using MvvmCross.Plugin.Messenger;
using MvvmCross.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;

namespace CastIt.ViewModels
{
public class SplashViewModel : BaseViewModel
{
private readonly IMvxNavigationService _navigationService;
private readonly ITelemetryService _telemetryService;
private readonly IAppSettingsService _settingsService;
private readonly IPlayListsService _playListsService;
private readonly Timer _timer;

private string _loadingText;

private readonly MvxInteraction _beforeNavigatingToMainViewModel = new MvxInteraction();

public string LoadingText
{
get => _loadingText;
set => SetProperty(ref _loadingText, value);
}

public IMvxInteraction BeforeNavigatingToMainViewModel
=> _beforeNavigatingToMainViewModel;

public SplashViewModel(
ITextProvider textProvider,
IMvxMessenger messenger,
IMvxLogProvider logProvider,
IMvxNavigationService navigationService,
ITelemetryService telemetryService,
IAppSettingsService settingsService,
IPlayListsService playListsService) : base(textProvider, messenger, logProvider.GetLogFor<SplashViewModel>())
{
_navigationService = navigationService;
_telemetryService = telemetryService;
_settingsService = settingsService;
_playListsService = playListsService;

_timer = new Timer(800)
{
AutoReset = false
};
_timer.Elapsed += TimerElapsed;
}

public override Task Initialize()
{
LoadingText = $"{GetText("Loading")}...";
Logger.Info($"{nameof(Initialize)}: Applying app theme and accent color...");
WindowsUtils.ChangeTheme(_settingsService.AppTheme, _settingsService.AccentColor);

Logger.Info($"{nameof(Initialize)}: Deleting old preview / log files...");
try
{
FileUtils.DeleteFilesInDirectory(FileUtils.GetPreviewsPath(), DateTime.Now.AddDays(-1));
FileUtils.DeleteFilesInDirectory(FileUtils.GetLogsPath(), DateTime.Now.AddDays(-3));
}
catch (Exception e)
{
Logger.Error(e, $"{nameof(Initialize)}: Error occurred while trying to delete previews");
_telemetryService.TrackError(e);
}
return base.Initialize();
}

public override void ViewAppeared()
{
base.ViewAppeared();
_timer.Start();
}

public (double, double) GetWindowWidthAndHeight()
{
return (_settingsService.WindowWidth, _settingsService.WindowHeight);
}

private async void TimerElapsed(object sender, ElapsedEventArgs e)
{
_timer.Stop();
_timer.Elapsed -= TimerElapsed;
_timer.Dispose();

Logger.Info($"{nameof(Initialize)}: Getting all playlists...");
var playLists = await _playListsService.GetAllPlayLists();
foreach (var playlist in playLists)
{
var files = await _playListsService.GetAllFiles(playlist.Id);
playlist.Items.AddRange(files.OrderBy(f => f.Position));
playlist.SetPositionIfChanged();
}

Logger.Info($"{nameof(Initialize)}: Navigating to main view model...");
await _navigationService.Navigate<MainViewModel, List<PlayListItemViewModel>>(playLists);
_beforeNavigatingToMainViewModel.Raise();
}
}
}
24 changes: 0 additions & 24 deletions CastIt/Views/MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ public partial class MainPage : MvxWpfView<MainViewModel>
//TODO: IF YOU DRAG OUT OF THE WINDOW, THE SEPARATORS ARE SHOWN

private IMvxInteraction _closeAppRequest;
private IMvxInteraction<(double, double)> _setWindowWithAndHeightRequest;
private IMvxInteraction _openSubTitleFileDialogRequest;
private IMvxInteraction<PlayListItemViewModel> _beforeDeletingPlayListRequest;

Expand All @@ -36,20 +35,6 @@ public IMvxInteraction CloseAppRequest
}
}

public IMvxInteraction<(double, double)> SetWindowWithAndHeightRequest
{
get => _setWindowWithAndHeightRequest;
set
{
if (_setWindowWithAndHeightRequest != null)
_setWindowWithAndHeightRequest.Requested -= SetWindowWidthAndHeight;

_setWindowWithAndHeightRequest = value;
if (value != null)
_setWindowWithAndHeightRequest.Requested += SetWindowWidthAndHeight;
}
}

public IMvxInteraction OpenSubTitleFileDialogRequest
{
get => _openSubTitleFileDialogRequest;
Expand Down Expand Up @@ -83,7 +68,6 @@ public MainPage()
InitializeComponent();

var set = this.CreateBindingSet<MainPage, MainViewModel>();
set.Bind(this).For(v => v.SetWindowWithAndHeightRequest).To(vm => vm.SetWindowWidthAndHeight).OneWay();
set.Bind(this).For(v => v.CloseAppRequest).To(vm => vm.CloseApp).OneWay();
set.Bind(this).For(v => v.OpenSubTitleFileDialogRequest).To(vm => vm.OpenSubTitleFileDialog).OneWay();
set.Bind(this).For(v => v.BeforeDeletingPlayListRequest).To(vm => vm.BeforeDeletingPlayList).OneWay();
Expand All @@ -94,14 +78,6 @@ public Dictionary<PlayListItemViewModel, int> GetTabsPosition()
=> PlayListTabControl.GetOrderedHeaders()
.ToDictionary(a => (a.Content as PlayListItemViewModel), a => a.LogicalIndex);

private void SetWindowWidthAndHeight(object sender, MvxValueEventArgs<(double, double)> e)
{
//TODO: SOMETIMES, THE INTERACTION IS NOT BEING RAISED
var window = System.Windows.Application.Current.MainWindow;
window.Width = e.Value.Item1;
window.Height = e.Value.Item2;
}

private void OpenSubtitleFileDialog(object sender, EventArgs e)
{
var allowedFormats = AppConstants.AllowedSubtitleFormatsString;
Expand Down
Loading

0 comments on commit b472fa6

Please sign in to comment.