-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
294 lines (263 loc) · 10.7 KB
/
Copy pathApp.xaml.cs
File metadata and controls
294 lines (263 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using WindowManager.Services;
using Forms = System.Windows.Forms;
namespace WindowManager;
public partial class App : System.Windows.Application
{
public static LayoutStore Store { get; } = new();
public static bool IsExiting { get; private set; }
private static readonly System.Drawing.Color MenuFore = System.Drawing.Color.FromArgb(236, 236, 241);
private Forms.NotifyIcon? _tray;
private HotkeyManager? _hotkeys;
private Mutex? _mutex;
private EventWaitHandle? _showSignal;
private bool _hiddenTipShown;
protected override void OnStartup(StartupEventArgs e)
{
// wymuszenie języka interfejsu (domyślnie: język systemu) — przed
// utworzeniem jakiegokolwiek okna, bo XAML czyta teksty przez x:Static
int langIdx = Array.IndexOf(e.Args, "--lang");
if (langIdx >= 0 && langIdx + 1 < e.Args.Length)
L.Override(e.Args[langIdx + 1]);
// tryb diagnostyczny: wypisuje wykryte okna do pliku i kończy działanie
int dumpIdx = Array.IndexOf(e.Args, "--dump");
if (dumpIdx >= 0)
{
var sb = new StringBuilder();
foreach (var w in WindowService.Capture("dump").Windows)
sb.AppendLine($"{w.ProcessName} | cmd={w.ShowCmd} | ({w.Left},{w.Top})-({w.Right},{w.Bottom}) | cls={w.ClassName} | exe={w.ExePath} | {w.TitleHint}");
File.WriteAllText(dumpIdx + 1 < e.Args.Length ? e.Args[dumpIdx + 1] : "dump.txt", sb.ToString());
Shutdown();
return;
}
// tryb diagnostyczny: renderuje panel poza ekranem do PNG (bez kradzieży fokusu)
int shotIdx = Array.IndexOf(e.Args, "--shot");
if (shotIdx >= 0)
{
string shotPath = shotIdx + 1 < e.Args.Length ? e.Args[shotIdx + 1] : "shot.png";
SettingsStore.Load();
Store.Load();
if (Store.Layouts.Count == 0)
{
// przykładowe karty tylko do podglądu — nie są zapisywane
Store.Layouts.Add(new Layout { Name = L.SampleWork, SavedAt = DateTime.Now, Windows = Enumerable.Range(0, 5).Select(_ => new SavedWindow { ProcessName = "brave", TitleHint = "Przykład" }).ToList() });
Store.Layouts.Add(new Layout { Name = L.SampleStreaming, SavedAt = DateTime.Now, Windows = Enumerable.Range(0, 3).Select(_ => new SavedWindow { ProcessName = "obs64", TitleHint = "Przykład" }).ToList() });
}
var shotWin = new MainWindow
{
ShowActivated = false,
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = 100,
};
shotWin.Show();
Dispatcher.BeginInvoke(new Action(() =>
{
var rtb = new RenderTargetBitmap((int)shotWin.ActualWidth, (int)shotWin.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(shotWin);
var enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(rtb));
using (var fs = File.Create(shotPath)) enc.Save(fs);
IsExiting = true;
Shutdown();
}), DispatcherPriority.ApplicationIdle);
return;
}
_mutex = new Mutex(true, "WindowManager_SingleInstance", out bool isFirst);
_showSignal = new EventWaitHandle(false, EventResetMode.AutoReset, "WindowManager_ShowSignal");
if (!isFirst)
{
// druga instancja tylko pokazuje okno tej już działającej
_showSignal.Set();
Shutdown();
return;
}
base.OnStartup(e);
ShutdownMode = ShutdownMode.OnExplicitShutdown;
DispatcherUnhandledException += (_, ex) =>
{
Log.Write("Nieobsłużony wyjątek UI: " + ex.Exception);
ex.Handled = true;
};
AppDomain.CurrentDomain.UnhandledException += (_, ex) =>
Log.Write("Wyjątek krytyczny: " + ex.ExceptionObject);
TaskScheduler.UnobservedTaskException += (_, ex) =>
{
Log.Write("Nieobsłużony wyjątek zadania: " + ex.Exception);
ex.SetObserved();
};
SettingsStore.Load();
Store.Load();
SetupTray();
_hotkeys = new HotkeyManager(OnHotkey);
UpdateHotkeys();
Store.Changed += () => { RebuildTrayMenu(); UpdateHotkeys(); };
SettingsStore.Changed += () => { RebuildTrayMenu(); UpdateHotkeys(); };
var icon = CreateAppIcon();
var window = new MainWindow
{
Icon = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()),
};
MainWindow = window;
if (!e.Args.Contains("--tray"))
window.Show();
var listener = new Thread(() =>
{
while (_showSignal.WaitOne())
{
try { Dispatcher.Invoke(ShowMainWindow); }
catch { break; }
}
})
{ IsBackground = true };
listener.Start();
}
private void OnHotkey(int id)
{
if (id >= 1 && id <= Store.Layouts.Count)
ApplyQuiet(Store.Layouts[id - 1]);
}
private void UpdateHotkeys() =>
_hotkeys?.Update(Store.Layouts.Count, SettingsStore.Current.HotkeysEnabled);
/// <summary>Przywraca układ z tray/skrótu — bez panelu; dymek tylko przy problemach.</summary>
public async void ApplyQuiet(Layout layout)
{
try
{
var r = await WindowService.ApplyAsync(layout, SettingsStore.Current.LaunchMissingApps);
if (r.Applied == 0 || r.AccessDenied > 0)
_tray?.ShowBalloonTip(2500, L.AppTitle, WindowService.Describe(layout, r), Forms.ToolTipIcon.Info);
}
catch (Exception ex)
{
Log.Write("Błąd przywracania układu: " + ex);
}
}
private void SetupTray()
{
var menu = new Forms.ContextMenuStrip
{
Renderer = new Forms.ToolStripProfessionalRenderer(new DarkColorTable()) { RoundedEdges = false },
ForeColor = MenuFore,
ShowImageMargin = false,
};
_tray = new Forms.NotifyIcon
{
Icon = CreateAppIcon(),
Text = L.AppTitle,
Visible = true,
ContextMenuStrip = menu,
};
_tray.MouseClick += (_, e) =>
{
if (e.Button == Forms.MouseButtons.Left) ShowMainWindow();
};
RebuildTrayMenu();
}
private void RebuildTrayMenu()
{
if (_tray?.ContextMenuStrip is not { } menu) return;
menu.Items.Clear();
menu.Items.Add(Item(L.TrayOpenPanel, (_, _) => ShowMainWindow()));
if (Store.Layouts.Count > 0)
{
menu.Items.Add(new Forms.ToolStripSeparator());
for (int i = 0; i < Store.Layouts.Count; i++)
{
var l = Store.Layouts[i];
var item = Item(L.TrayApply(l.Name), (_, _) => ApplyQuiet(l));
if (SettingsStore.Current.HotkeysEnabled && i < 9)
item.ShortcutKeyDisplayString = $"Ctrl+Alt+{i + 1}";
menu.Items.Add(item);
}
}
menu.Items.Add(new Forms.ToolStripSeparator());
menu.Items.Add(Item(L.TrayExit, (_, _) => ExitApp()));
}
private static Forms.ToolStripMenuItem Item(string text, EventHandler onClick)
{
var item = new Forms.ToolStripMenuItem(text) { ForeColor = MenuFore };
item.Click += onClick;
return item;
}
public void ShowMainWindow()
{
if (MainWindow is null) return;
MainWindow.Show();
MainWindow.WindowState = WindowState.Normal;
MainWindow.Activate();
}
public void NotifyHiddenToTray()
{
if (_hiddenTipShown) return;
_hiddenTipShown = true;
_tray?.ShowBalloonTip(2500, L.AppTitle, L.HiddenToTrayTip, Forms.ToolTipIcon.Info);
}
public void ExitApp()
{
IsExiting = true;
_hotkeys?.Dispose();
_hotkeys = null;
if (_tray != null)
{
_tray.Visible = false;
_tray.Dispose();
_tray = null;
}
Shutdown();
}
protected override void OnExit(ExitEventArgs e)
{
_hotkeys?.Dispose();
_tray?.Dispose();
_mutex?.Dispose();
base.OnExit(e);
}
private sealed class DarkColorTable : Forms.ProfessionalColorTable
{
private static readonly System.Drawing.Color Bg = System.Drawing.Color.FromArgb(34, 34, 41);
private static readonly System.Drawing.Color Hover = System.Drawing.Color.FromArgb(46, 46, 56);
private static readonly System.Drawing.Color Line = System.Drawing.Color.FromArgb(60, 60, 70);
public override System.Drawing.Color ToolStripDropDownBackground => Bg;
public override System.Drawing.Color ImageMarginGradientBegin => Bg;
public override System.Drawing.Color ImageMarginGradientMiddle => Bg;
public override System.Drawing.Color ImageMarginGradientEnd => Bg;
public override System.Drawing.Color MenuItemSelected => Hover;
public override System.Drawing.Color MenuItemBorder => Hover;
public override System.Drawing.Color MenuBorder => Line;
public override System.Drawing.Color SeparatorDark => Line;
public override System.Drawing.Color SeparatorLight => Line;
}
private static Icon CreateAppIcon()
{
var bmp = new Bitmap(32, 32);
using (var g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(System.Drawing.Color.Transparent);
using var path = new GraphicsPath();
var r = new Rectangle(1, 1, 30, 30);
const int rad = 8;
path.AddArc(r.X, r.Y, rad, rad, 180, 90);
path.AddArc(r.Right - rad, r.Y, rad, rad, 270, 90);
path.AddArc(r.Right - rad, r.Bottom - rad, rad, rad, 0, 90);
path.AddArc(r.X, r.Bottom - rad, rad, rad, 90, 90);
path.CloseFigure();
using var accent = new SolidBrush(System.Drawing.Color.FromArgb(124, 138, 248));
g.FillPath(accent, path);
using var white = new SolidBrush(System.Drawing.Color.FromArgb(235, 255, 255, 255));
g.FillRectangle(white, 7, 7, 8, 18);
g.FillRectangle(white, 17, 7, 8, 8);
g.FillRectangle(white, 17, 17, 8, 8);
}
return Icon.FromHandle(bmp.GetHicon());
}
}