Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hotkey to cycle to the next power schema #32

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions Petrroll.Helpers/ObservableCollectionWhereShim.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static ObservableCollectionWhereSwitchableShim<C, T> WhereObservableSwitc

public class ObservableCollectionWhereSwitchableShim<C, T> : ObservableCollectionWhereShim<C, T>, IEnumerable<T> where C : INotifyCollectionChanged, ICollection<T> where T : INotifyPropertyChanged
{
protected IEnumerable<T> currentlySwichtedCollection => (FilterOn) ? filteredCollection : BaseCollection;
protected IEnumerable<T> currentlySwitchedCollection => (FilterOn) ? filteredCollection : BaseCollection;

#region Constructor
public ObservableCollectionWhereSwitchableShim(C baseCollection, Func<T, bool> predicate, bool filterOn) : base(baseCollection, predicate)
Expand Down Expand Up @@ -96,12 +96,12 @@ private void addFilteredElements()
#endregion

#region OtherMethods
public override int Count => currentlySwichtedCollection.Count();
public override bool Contains(T item) => currentlySwichtedCollection.Contains(item);
public override void CopyTo(T[] array, int arrayIndex) => currentlySwichtedCollection.ToList().CopyTo(array, arrayIndex);
public override int Count => currentlySwitchedCollection.Count();
public override bool Contains(T item) => currentlySwitchedCollection.Contains(item);
public override void CopyTo(T[] array, int arrayIndex) => currentlySwitchedCollection.ToList().CopyTo(array, arrayIndex);

public override IEnumerator<T> GetEnumerator() => currentlySwichtedCollection.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => currentlySwichtedCollection.GetEnumerator();
public override IEnumerator<T> GetEnumerator() => currentlySwitchedCollection.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => currentlySwitchedCollection.GetEnumerator();
#endregion
}

Expand Down Expand Up @@ -147,7 +147,7 @@ protected virtual void Sch_PropertyChanged(object sender, PropertyChangedEventAr
else if (oldNumberOfItems > numberOfFilteredItems)
{
#if DEBUG
Console.WriteLine($"DC:Added:{sender}");
Console.WriteLine($"DC:Added:{sender}");
#endif
var changeIndex = BaseCollection.Take(BaseCollection.IndexOf(sender)).Count(Predicate);
RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, sender, changeIndex));
Expand Down
36 changes: 30 additions & 6 deletions PowerSwitcher.TrayApp/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ private void Application_Startup(object sender, StartupEventArgs e)
if (!tryToCreateMutex()) return;

var configurationManager = new ConfigurationManagerXML<PowerSwitcherSettings>(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Petrroll", "PowerSwitcher", "PowerSwitcherSettings.xml"
));

Expand All @@ -44,6 +44,7 @@ private void Application_Startup(object sender, StartupEventArgs e)

Configuration.Data.PropertyChanged += Configuration_PropertyChanged;
if (Configuration.Data.ShowOnShortcutSwitch) { registerHotkeyFromConfiguration(); }
if (Configuration.Data.CycleNextSchemaSwitch) { registerHotkeyFromConfiguration(true); }

TrayApp.CreateAltMenu();
}
Expand All @@ -66,24 +67,47 @@ private void Configuration_PropertyChanged(object sender, System.ComponentModel.
if (Configuration.Data.ShowOnShortcutSwitch) { registerHotkeyFromConfiguration(); }
else { unregisterHotkeyFromConfiguration(); }
}

if(e.PropertyName == nameof(PowerSwitcherSettings.CycleNextSchemaSwitch))
{
if (Configuration.Data.CycleNextSchemaSwitch) { registerHotkeyFromConfiguration(true); }
else { unregisterHotkeyFromConfiguration(true); }
}

}

private void unregisterHotkeyFromConfiguration()
private void unregisterHotkeyFromConfiguration(bool isCycleNextSchemaSwitch = false)
{
HotKeyManager.Unregister(new HotKey(Configuration.Data.ShowOnShortcutKey, Configuration.Data.ShowOnShortcutKeyModifier));
if(isCycleNextSchemaSwitch)
HotKeyManager.Unregister(new HotKey(Configuration.Data.CycleNextSchemaKey, Configuration.Data.CycleNextSchemaKeyModifier));
else
HotKeyManager.Unregister(new HotKey(Configuration.Data.ShowOnShortcutKey, Configuration.Data.ShowOnShortcutKeyModifier));
}

private bool registerHotkeyFromConfiguration()
private bool registerHotkeyFromConfiguration(bool isCycleNextSchemaSwitch = false)
{
var newHotKey = new HotKey(Configuration.Data.ShowOnShortcutKey, Configuration.Data.ShowOnShortcutKeyModifier);
HotKey newHotKey = null;
if(isCycleNextSchemaSwitch)
newHotKey = new HotKey(Configuration.Data.CycleNextSchemaKey, Configuration.Data.CycleNextSchemaKeyModifier);
else
newHotKey = new HotKey(Configuration.Data.ShowOnShortcutKey, Configuration.Data.ShowOnShortcutKeyModifier);

bool success = HotKeyManager.Register(newHotKey);
if(!success) { HotKeyFailed = true; return false; }
newHotKey.HotKeyFired += (this.MainWindow as MainWindow).ToggleWindowVisibility;

if (isCycleNextSchemaSwitch)
newHotKey.HotKeyFired += CycleNextPowerSchema;
Copy link
Author

@objecttothis objecttothis May 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@petrroll The hotkey press is correctly switching the schema to the next power schema. The problem is that it doesn't show you what schema it switched you to. What I would like to do is modify MainWindow.ToggleWindowVisibility() to sort of act as a toast notification and disappear on its own after, say, 5 seconds. I can call `newHotKey.HotKeyFired += (this.MainWindow as MainWindow).ToggleWindowVisibility; as it currently is, and it shows the new schema, but it doesn't hide the window unless the user manually clicks somewhere on the screen. I played around with adding an optional timeout parameter but Visual Studio complained about that. I also couldn't figure out how to trigger the HideWithAnimation() function after the timeout period. I'm open to ideas about the best way to implement some sort of indicator notification of what power schema it just got changed to and then letting it disappear... if there is somewhere in the code where you are already doing this, please let me know.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I vaguely remember the fly-out logic was somehow buggy w.r.t. to timeout parameters. The best way to approach it might be to use winrt API for proper notifications. I.e. instead of creating your own toast-like notification just use native Windows Notification API.

Not sure how much identity the current packaging schema provides and what's the state of invoking notifications without it, but remember that https://github.com/File-New-Project/EarTrumpet was doing something with winRT APIs so it might be a good place to start. Or you might wait until project reunion comes with notifications API (won't need app identity at all): https://github.com/microsoft/ProjectReunion

else
newHotKey.HotKeyFired += (this.MainWindow as MainWindow).ToggleWindowVisibility;

return true;
}

private void CycleNextPowerSchema()
{
PowerManager.CycleNextPowerSchema();
}

private bool tryToCreateMutex()
{
var assembly = Assembly.GetExecutingAssembly();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Petrroll.Helpers;
using PowerSwitcher.TrayApp.Services;
using System;
using System.Windows.Forms;
using System.Windows.Input;

namespace PowerSwitcher.TrayApp.Configuration
Expand All @@ -18,12 +19,15 @@ public class PowerSwitcherSettings : ObservableObject
//TODO: Fix so that it can be changed during runtime
public Key ShowOnShortcutKey { get; set; } = Key.L;
public KeyModifier ShowOnShortcutKeyModifier { get; set; } = KeyModifier.Shift | KeyModifier.Win;

bool showOnShortcutSwitch = false;
public bool ShowOnShortcutSwitch { get { return showOnShortcutSwitch; } set { showOnShortcutSwitch = value; RaisePropertyChangedEvent(nameof(ShowOnShortcutSwitch)); } }

public Key CycleNextSchemaKey { get; set; } = Key.N;
public KeyModifier CycleNextSchemaKeyModifier { get; set; } = KeyModifier.Shift | KeyModifier.Win;
bool cycleNextSchemaSwitch = false;
public bool CycleNextSchemaSwitch { get { return cycleNextSchemaSwitch; } set { cycleNextSchemaSwitch = value; RaisePropertyChangedEvent(nameof(CycleNextSchemaSwitch)); } }

bool showOnlyDefaultSchemas = false;
public bool ShowOnlyDefaultSchemas { get { return showOnlyDefaultSchemas; } set { showOnlyDefaultSchemas = value; RaisePropertyChangedEvent(nameof(ShowOnlyDefaultSchemas)); } }

}
}
11 changes: 1 addition & 10 deletions PowerSwitcher.TrayApp/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
using PowerSwitcher.TrayApp.Extensions;
using PowerSwitcher.TrayApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace PowerSwitcher.TrayApp
{
Expand Down
15 changes: 12 additions & 3 deletions PowerSwitcher.TrayApp/Resources/AppStrings.Designer.cs

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

59 changes: 31 additions & 28 deletions PowerSwitcher.TrayApp/Resources/AppStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple

There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -153,7 +153,10 @@
<data name="ShowOnlyDefaultSchemas" xml:space="preserve">
<value>Show only default power schemas</value>
</data>
<data name="ToggleOnShowrtcutSwitch" xml:space="preserve">
<data name="ToggleOnShortcutSwitch" xml:space="preserve">
<value>Enable shortcut for flyout toggle</value>
</data>
<data name="ToggleCycleNextSchemaSwitch" xml:space="preserve">
<value>Enable shortcut for cycling next schema</value>
</data>
</root>
6 changes: 3 additions & 3 deletions PowerSwitcher.TrayApp/Services/GlobalShortcutService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class HotKey
public event Action HotKeyFired;

public int VirtualKeyCode => KeyInterop.VirtualKeyFromKey(Key);
public int Id => VirtualKeyCode + ((int)KeyModifiers* 0x10000);
public int Id => VirtualKeyCode + ((int)KeyModifiers* 0x10000);

public HotKey(Key k, KeyModifier keyModifiers)
{
Expand Down Expand Up @@ -72,10 +72,10 @@ public void Unregister(HotKey hotkey)
{
if (!_dictHotKeyToCalBackProc.ContainsKey(hotkey.Id)) { throw new InvalidOperationException($"Trying to unregister not-registred Hotkey {hotkey.Id}"); }

var success = UnregisterHotKey(IntPtr.Zero, hotkey.Id);
var success = UnregisterHotKey(IntPtr.Zero, hotkey.Id);
if (!success) { throw new PowerSwitcherWrappersException($"UnregisterHotKey() failed|{Marshal.GetLastWin32Error()}"); }

_dictHotKeyToCalBackProc.Remove(hotkey.Id);
_dictHotKeyToCalBackProc.Remove(hotkey.Id);
}

public const int WmHotKey = 0x0312;
Expand Down
19 changes: 18 additions & 1 deletion PowerSwitcher.TrayApp/TrayApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,16 @@ public void CreateAltMenu()
onlyDefaultSchemasItem.Checked = configuration.Data.ShowOnlyDefaultSchemas;
onlyDefaultSchemasItem.Click += OnlyDefaultSchemas_Click;

var enableShortcutsToggleItem = contextMenuSettings.MenuItems.Add($"{AppStrings.ToggleOnShowrtcutSwitch} ({configuration.Data.ShowOnShortcutKeyModifier} + {configuration.Data.ShowOnShortcutKey})");
var enableShortcutsToggleItem = contextMenuSettings.MenuItems.Add($"{AppStrings.ToggleOnShortcutSwitch} ({configuration.Data.ShowOnShortcutKeyModifier} + {configuration.Data.ShowOnShortcutKey})");
enableShortcutsToggleItem.Enabled = !(Application.Current as App).HotKeyFailed;
enableShortcutsToggleItem.Checked = configuration.Data.ShowOnShortcutSwitch;
enableShortcutsToggleItem.Click += EnableShortcutsToggleItem_Click;

var enableCycleNextToggleItem = contextMenuSettings.MenuItems.Add($"{AppStrings.ToggleCycleNextSchemaSwitch} ({configuration.Data.CycleNextSchemaKeyModifier} + {configuration.Data.CycleNextSchemaKey})");
enableCycleNextToggleItem.Enabled = !(Application.Current as App).HotKeyFailed;
enableCycleNextToggleItem.Checked = configuration.Data.CycleNextSchemaSwitch;
enableCycleNextToggleItem.Click += EnableCycleNextToggleItem_Click;

var aboutItem = contextMenuRootItems.Add($"{AppStrings.About} ({Assembly.GetEntryAssembly().GetName().Version})");
aboutItem.Click += About_Click;

Expand Down Expand Up @@ -111,6 +116,18 @@ private void EnableShortcutsToggleItem_Click(object sender, EventArgs e)
configuration.Save();
}

private void EnableCycleNextToggleItem_Click(object sender, EventArgs e)
{
WF.MenuItem enableCycleNextToggleItem = (WF.MenuItem)sender;

configuration.Data.CycleNextSchemaSwitch = !configuration.Data.CycleNextSchemaSwitch;
enableCycleNextToggleItem.Checked = configuration.Data.CycleNextSchemaSwitch;
enableCycleNextToggleItem.Enabled = !(Application.Current as App).HotKeyFailed;

configuration.Save();
}


private void AutomaticHideItem_Click(object sender, EventArgs e)
{
WF.MenuItem automaticHideItem = (WF.MenuItem)sender;
Expand Down
24 changes: 19 additions & 5 deletions PowerSwitcher/PowerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public interface IPowerManager : INotifyPropertyChanged, IDisposable

void SetPowerSchema(IPowerSchema schema);
void SetPowerSchema(Guid guid);

void CycleNextPowerSchema();
}

public class PowerManager : ObservableObject, IPowerManager
Expand Down Expand Up @@ -53,10 +55,10 @@ public void UpdateSchemas()
{
var originalSchema = Schemas.FirstOrDefault(sch => sch.Guid == newSchema.Guid);
if (originalSchema == null) { insertNewSchema(newSchemas, newSchema); originalSchema = newSchema; }

if (newSchema.Guid == currSchemaGuid && originalSchema?.IsActive != true)
{ setNewCurrSchema(originalSchema); }

if (originalSchema?.Name != newSchema.Name)
{ ((PowerSchema)originalSchema).Name = newSchema.Name; }
}
Expand Down Expand Up @@ -125,8 +127,20 @@ private void powerChangedEvent(PowerPlugStatus newStatus)
RaisePropertyChangedEvent(nameof(CurrentPowerStatus));
}

public void CycleNextPowerSchema()
{
var nextSchemaIndex = (Schemas.IndexOf(CurrentSchema) + 1);
if ((nextSchemaIndex + 1) > Schemas.Count)
nextSchemaIndex = 0;

var nextPowerSchema = Schemas[nextSchemaIndex];

SetPowerSchema(nextPowerSchema);
}


#region IDisposable Support
private bool disposedValue = false;
private bool disposedValue = false;

protected virtual void Dispose(bool disposing)
{
Expand All @@ -143,8 +157,8 @@ public void Dispose()
{
Dispose(true);

//No destructor so isn't required (yet)
// GC.SuppressFinalize(this);
//No destructor so isn't required (yet)
// GC.SuppressFinalize(this);
}

#endregion
Expand Down