Skip to content

Commit

Permalink
(Add) Auto-detect when the machine is idle [Alpha State] #88
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkl58 committed Mar 1, 2022
1 parent b272797 commit 168c631
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 9 deletions.
72 changes: 71 additions & 1 deletion NotEnoughAV1Encodes/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,18 @@ namespace NotEnoughAV1Encodes
{
public partial class MainWindow : MetroWindow
{
/// <summary>Prevents Race Conditions on Startup</summary>
private bool startupLock = true;

/// <summary>Encoding the Queue in Parallel or not</summary>
private bool QueueParallel;

/// <summary>State of the Program [0 = IDLE; 1 = Encoding; 2 = Paused]</summary>
private int ProgramState;

private Settings settingsDB = new();
private Video.VideoDB videoDB = new();
private int ProgramState;

private string uid;
private CancellationTokenSource cancellationTokenSource;
public VideoSettings PresetSettings = new();
Expand Down Expand Up @@ -1069,6 +1076,54 @@ private void AddToQueue(string identifier, bool skipSubs)
File.WriteAllText(Path.Combine(Global.AppData, "NEAV1E", "Queue", videoDB.InputFileName + "_" + identifier + ".json"), JsonConvert.SerializeObject(queueElement, Formatting.Indented));
}

private void AutoPauseResume()
{
TimeSpan idleTime = win32.IdleDetection.GetInputIdleTime();
double time = idleTime.TotalSeconds;

Debug.WriteLine("AutoPauseResume() => " + time.ToString() + " Seconds");
if (ProgramState is 1)
{
// Pause
if (time < 40.0)
{
Dispatcher.Invoke(() => ImageStartStop.Source = new BitmapImage(new Uri(@"/NotEnoughAV1Encodes;component/resources/img/resume.png", UriKind.Relative)));
Dispatcher.Invoke(() => LabelStartPauseButton.Content = LocalizedStrings.Instance["Resume"]);
Dispatcher.Invoke(() => Title = "NEAV1E - " + LocalizedStrings.Instance["ToggleSwitchAutoPauseResume"] + " => Paused");

// Pause all PIDs
foreach (int pid in Global.LaunchedPIDs)
{
Suspend.SuspendProcessTree(pid);
}

ProgramState = 2;
}
}
else if (ProgramState is 2)
{
Dispatcher.Invoke(() => Title = "NEAV1E - " + LocalizedStrings.Instance["ToggleSwitchAutoPauseResume"] + " => Paused - System IDLE since " + time.ToString() + " seconds");
// Resume
if (time > 60.0)
{
Dispatcher.Invoke(() => ImageStartStop.Source = new BitmapImage(new Uri(@"/NotEnoughAV1Encodes;component/resources/img/pause.png", UriKind.Relative)));
Dispatcher.Invoke(() => LabelStartPauseButton.Content = LocalizedStrings.Instance["Pause"]);
Dispatcher.Invoke(() => Title = "NEAV1E - " + LocalizedStrings.Instance["ToggleSwitchAutoPauseResume"] + " => Encoding");

// Resume all PIDs
if (ProgramState is 2)
{
foreach (int pid in Global.LaunchedPIDs)
{
Resume.ResumeProcessTree(pid);
}
}

ProgramState = 1;
}
}
}

private void Shutdown()
{
if (settingsDB.ShutdownAfterEncode)
Expand Down Expand Up @@ -1764,6 +1819,15 @@ private async Task MainStartAsync(CancellationToken _cancelToken)
taskBarTimer.Interval = 3000; // every 3s
taskBarTimer.Start();

// Starts Timer for Auto Pause Resume functionality
System.Timers.Timer pauseResumeTimer = new();
if (settingsDB.AutoResumePause)
{
pauseResumeTimer.Elapsed += (sender, e) => { AutoPauseResume(); };
pauseResumeTimer.Interval = 20000; // check every 10s
pauseResumeTimer.Start();
}

using SemaphoreSlim concurrencySemaphore = new(WorkerCountQueue);
// Creates a tasks list
List<Task> tasks = new();
Expand Down Expand Up @@ -1891,6 +1955,12 @@ private async Task MainStartAsync(CancellationToken _cancelToken)
ButtonRemoveSelectedQueueItem.IsEnabled = true;
ButtonEditSelectedItem.IsEnabled = true;

// Stop Timer for Auto Pause Resume functionality
if (settingsDB.AutoResumePause)
{
pauseResumeTimer.Stop();
}

// Stop TaskbarItem Progressbar
taskBarTimer.Stop();
Dispatcher.Invoke(() => TaskbarItemInfo.ProgressValue = 1.0);
Expand Down
6 changes: 4 additions & 2 deletions NotEnoughAV1Encodes/Views/ProgramSettings.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,20 @@

</Grid>
</GroupBox>
<GroupBox Margin="10,10,536,0" Height="249" VerticalAlignment="Top">
<GroupBox Margin="10,10,536,0" Height="334" VerticalAlignment="Top">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="55"/>
<RowDefinition Height="55"/>
<RowDefinition Height="55"/>
<RowDefinition Height="55"/>
<RowDefinition Height="55"/>
</Grid.RowDefinitions>
<mah:ToggleSwitch Grid.Row="0" x:Name="ToggleSwitchDeleteTempFiles" Header="{lex:Loc}" Height="54" Margin="10,0,0,0" Width="100" VerticalAlignment="Top"/>
<mah:ToggleSwitch Grid.Row="1" x:Name="ToggleSwitchShutdown" Header="{lex:Loc}" Height="53" Margin="10,0,0,0" Width="100" VerticalAlignment="Top"/>
<mah:ToggleSwitch Grid.Row="2" x:Name="ToggleSwitchOverrideWorkerCount" Header="{lex:Loc}" Height="53" Margin="10,0,0,0" Width="100" VerticalAlignment="Top"/>
<mah:ToggleSwitch Grid.Row="3" x:Name="ToggleSwitchLogging" Header="{lex:Loc}" Height="53" Margin="10,0,0,0" Width="100" VerticalAlignment="Top"/>
<mah:ToggleSwitch Grid.Row="4" x:Name="ToggleSwitchAutoPauseResume" Header="{lex:Loc}" Height="53" Margin="10,0,0,0" Width="100" VerticalAlignment="Top" ToolTip="{lex:Loc ToggleSwitchAutoPauseResumeTooltip}"/>
</Grid>
</GroupBox>
<GroupBox x:Name="GroupBoxBackroundImage" Header="{lex:Loc}" Margin="0,137,10,0" Height="122" VerticalAlignment="Top" mah:ControlsHelper.ContentCharacterCasing="Normal" HorizontalAlignment="Right" Width="237">
Expand All @@ -88,7 +90,7 @@
<Button x:Name="ButtonSelectTempPathReset" Content="{lex:Loc ButtonResetBGImage}" HorizontalAlignment="Left" Margin="10,0,0,9" VerticalAlignment="Bottom" Height="21" Width="101" mah:ControlsHelper.ContentCharacterCasing="Normal" Click="ButtonSelectTempPathReset_Click"/>
</Grid>
</GroupBox>
<GroupBox Margin="10,264,536,90">
<GroupBox Margin="269,264,252,0" Height="80" VerticalAlignment="Top">
<Grid>
<Label x:Name="LabelProcessPriority" Content="{lex:Loc}" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Center" FontWeight="Normal" Height="28" RenderTransformOrigin="0.393,0.581" Width="107"/>
<ComboBox x:Name="ComboBoxProcessPriority" HorizontalAlignment="Left" Margin="117,0,0,0" VerticalAlignment="Center" Width="117" Height="29">
Expand Down
6 changes: 4 additions & 2 deletions NotEnoughAV1Encodes/Views/ProgramSettings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ public partial class ProgramSettings : MetroWindow
public ProgramSettings(Settings settingsDB)
{
InitializeComponent();
ToggleSwitchOverrideWorkerCount.IsOn = settingsDB.OverrideWorkerCount;
ToggleSwitchDeleteTempFiles.IsOn = settingsDB.DeleteTempFiles;
ToggleSwitchAutoPauseResume.IsOn = settingsDB.AutoResumePause;
ToggleSwitchShutdown.IsOn = settingsDB.ShutdownAfterEncode;
ToggleSwitchOverrideWorkerCount.IsOn = settingsDB.OverrideWorkerCount;
ToggleSwitchLogging.IsOn = settingsDB.Logging;
ComboBoxAccentTheme.SelectedIndex = settingsDB.AccentTheme;
ComboBoxBaseTheme.SelectedIndex = settingsDB.BaseTheme;
Expand Down Expand Up @@ -84,9 +85,10 @@ private void ButtonUpdater_Click(object sender, RoutedEventArgs e)

private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
settingsDBTemp.OverrideWorkerCount = ToggleSwitchOverrideWorkerCount.IsOn;
settingsDBTemp.DeleteTempFiles = ToggleSwitchDeleteTempFiles.IsOn;
settingsDBTemp.AutoResumePause = ToggleSwitchAutoPauseResume.IsOn;
settingsDBTemp.ShutdownAfterEncode = ToggleSwitchShutdown.IsOn;
settingsDBTemp.OverrideWorkerCount = ToggleSwitchOverrideWorkerCount.IsOn;
settingsDBTemp.Logging = ToggleSwitchLogging.IsOn;
settingsDBTemp.BaseTheme = ComboBoxBaseTheme.SelectedIndex;
settingsDBTemp.AccentTheme = ComboBoxAccentTheme.SelectedIndex;
Expand Down
2 changes: 2 additions & 0 deletions NotEnoughAV1Encodes/resources/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public class Settings
public string TempPath { get; set; } = Path.GetTempPath();
/// <summary>Toggles Logging functionality</summary>
public bool Logging { get; set; } = true;
/// <summary>Toggles Auto Resume Pause functionality</summary>
public bool AutoResumePause { get; set; } = false;
/// <summary>Toggles Process Priority (false => low)</summary>
public bool PriorityNormal { get; set; } = true;
/// <summary>CultureInfo for Language (Default: en-US)</summary>
Expand Down
18 changes: 18 additions & 0 deletions NotEnoughAV1Encodes/resources/lang/Strings.Designer.cs

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

10 changes: 8 additions & 2 deletions NotEnoughAV1Encodes/resources/lang/Strings.de.resx
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ButtonClose" xml:space="preserve">
<value>Schließen</value>
Expand Down Expand Up @@ -472,6 +472,12 @@
<data name="ToggleSwitchAdvancedSettings" xml:space="preserve">
<value>Erweiterte Einstellungen</value>
</data>
<data name="ToggleSwitchAutoPauseResume" xml:space="preserve">
<value>Autom. Pausierung / Fortsetz.</value>
</data>
<data name="ToggleSwitchAutoPauseResumeTooltip" xml:space="preserve">
<value>Automatische Pausierung und Fortsetzung wenn das System mehr als 1 Minute IDLE ist</value>
</data>
<data name="ToggleSwitchDeleteTempFiles" xml:space="preserve">
<value>Temp Dateien löschen</value>
</data>
Expand Down
10 changes: 8 additions & 2 deletions NotEnoughAV1Encodes/resources/lang/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ButtonClose" xml:space="preserve">
<value>Close</value>
Expand Down Expand Up @@ -475,6 +475,12 @@
<data name="ToggleSwitchAdvancedSettings" xml:space="preserve">
<value>Advanced Settings</value>
</data>
<data name="ToggleSwitchAutoPauseResume" xml:space="preserve">
<value>Auto Pause / Resume</value>
</data>
<data name="ToggleSwitchAutoPauseResumeTooltip" xml:space="preserve">
<value>Automatically Pauses and Resumes Encoding if System is IDLE for more than 1 minute</value>
</data>
<data name="ToggleSwitchDeleteTempFiles" xml:space="preserve">
<value>Delete Temp Files</value>
</data>
Expand Down
36 changes: 36 additions & 0 deletions NotEnoughAV1Encodes/win32/IdleDetection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace NotEnoughAV1Encodes.win32
{
internal class IdleDetection
{
public static TimeSpan GetInputIdleTime()
{
var plii = new NativeMethods.LastInputInfo();
plii.cbSize = (UInt32)Marshal.SizeOf(plii);

if (NativeMethods.GetLastInputInfo(ref plii))
{
return TimeSpan.FromMilliseconds(Environment.TickCount64 - plii.dwTime);
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}

private static class NativeMethods
{
public struct LastInputInfo
{
public UInt32 cbSize;
public UInt32 dwTime;
}

[DllImport("user32.dll")]
public static extern bool GetLastInputInfo(ref LastInputInfo plii);
}
}
}

0 comments on commit 168c631

Please sign in to comment.