Repository navigation
Expand file tree
/
Copy pathUtilityBoxWindow.cs
More file actions
706 lines (633 loc) · 23.9 KB
/
Copy pathUtilityBoxWindow.cs
File metadata and controls
706 lines (633 loc) · 23.9 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace DesktopNest
{
/// <summary>
/// A compact desktop-resident clock and system-control box. It intentionally
/// avoids continuous hardware polling: the clock updates once per minute and
/// display brightness is read once when the window is loaded.
/// </summary>
public sealed class UtilityBoxWindow : Window
{
private const double CollapsedHeight = 42.0;
private readonly BoxLayoutSetting _layout;
private readonly DispatcherTimer _clockTimer;
private readonly DispatcherTimer _volumeCommitTimer;
private readonly object _brightnessQueueLock = new object();
private Border _surface;
private Grid _body;
private TextBlock _timeText;
private TextBlock _dateText;
private TextBlock _volumeValue;
private TextBlock _brightnessValue;
private Slider _volumeSlider;
private Slider _brightnessSlider;
private Button _lockButton;
private Button _collapseButton;
private Thumb _resizeThumb;
private bool _loaded;
private bool _applyingLayout;
private bool _volumeInitialized;
private bool _brightnessInitialized;
private int _pendingVolume;
private bool _brightnessWorkerRunning;
private int? _pendingBrightness;
private double _boxOpacity;
private bool _controllerClosing;
public UtilityBoxWindow(BoxLayoutSetting layout, double opacity)
{
if (layout == null)
{
throw new ArgumentNullException("layout");
}
_layout = layout;
_boxOpacity = Clamp(opacity, 0.38, 0.92);
DesktopPinEnabled = true;
Title = String.IsNullOrWhiteSpace(layout.Title) ? "时间与系统" : layout.Title;
WindowStyle = WindowStyle.None;
AllowsTransparency = true;
Background = Brushes.Transparent;
ResizeMode = ResizeMode.NoResize;
ShowInTaskbar = true;
ShowActivated = false;
MinWidth = 240;
MinHeight = CollapsedHeight;
FontFamily = new FontFamily("Microsoft YaHei UI");
SnapsToDevicePixels = true;
UseLayoutRounding = true;
Content = BuildContent();
_clockTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMinutes(1)
};
_clockTimer.Tick += delegate { UpdateClock(); };
_volumeCommitTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMilliseconds(90)
};
_volumeCommitTimer.Tick += delegate
{
_volumeCommitTimer.Stop();
AudioService.TrySetMasterVolume(_pendingVolume);
};
SourceInitialized += delegate
{
if (DesktopPinEnabled)
{
DesktopWindowBehavior.ConfigureToolWindow(this);
}
};
Loaded += OnLoaded;
Deactivated += delegate
{
if (_loaded && DesktopPinEnabled)
{
DesktopWindowBehavior.SendToDesktop(this);
}
};
Closed += delegate
{
_loaded = false;
_clockTimer.Stop();
_volumeCommitTimer.Stop();
};
LocationChanged += delegate
{
if (_loaded && !_applyingLayout)
{
CaptureLayoutFromWindow();
RaiseLayoutChanged();
}
};
SizeChanged += delegate
{
if (_loaded && !_applyingLayout)
{
CaptureLayoutFromWindow();
RaiseLayoutChanged();
}
};
}
public event EventHandler LayoutChanged;
public event EventHandler SettingsRequested;
public event EventHandler MoveCompleted;
public BoxLayoutSetting LayoutSetting
{
get { return _layout; }
}
public bool DesktopPinEnabled { get; set; }
public void UpdateOpacity(double opacity)
{
_boxOpacity = Clamp(opacity, 0.38, 0.92);
ApplySurfaceBrush();
}
// Kept parallel with OrganizerBoxWindow's controller-facing API.
public void SetBoxOpacity(double opacity)
{
UpdateOpacity(opacity);
}
/// <summary>
/// Applies a controller-planned batch layout without persisting each
/// intermediate WPF LocationChanged or SizeChanged notification.
/// </summary>
public void RefreshFromLayout()
{
_applyingLayout = true;
try
{
Width = Math.Max(MinWidth, _layout.Width);
double expandedHeight = _layout.ExpandedHeight >= 150
? _layout.ExpandedHeight
: Math.Max(150, _layout.Height);
Height = _layout.Collapsed ? CollapsedHeight : expandedHeight;
Rect workArea = SystemParameters.WorkArea;
Left = IsFinite(_layout.Left)
? _layout.Left
: Math.Max(workArea.Left, workArea.Right - Width - 24);
Top = IsFinite(_layout.Top)
? _layout.Top
: workArea.Top + 24;
}
finally
{
_applyingLayout = false;
}
SetCollapsedVisual(_layout.Collapsed);
UpdateLockVisual();
}
public void CaptureLayoutFromWindow()
{
if (!IsFinite(Left) || !IsFinite(Top))
{
return;
}
_layout.Left = Left;
_layout.Top = Top;
double width = ActualWidth > 0 ? ActualWidth : Width;
double height = ActualHeight > 0 ? ActualHeight : Height;
if (IsFinite(width) && width > 0)
{
_layout.Width = width;
}
if (IsFinite(height) && height > 0)
{
_layout.Height = height;
if (!_layout.Collapsed && height > CollapsedHeight)
{
_layout.ExpandedHeight = height;
}
}
}
public void SetLocked(bool locked)
{
if (_layout.Locked == locked)
{
return;
}
_layout.Locked = locked;
UpdateLockVisual();
RaiseLayoutChanged();
}
public void SetControllerClosing()
{
_controllerClosing = true;
}
protected override void OnClosing(CancelEventArgs e)
{
if (!_controllerClosing && DesktopPinEnabled)
{
e.Cancel = true;
DesktopWindowBehavior.SendToDesktop(this);
}
base.OnClosing(e);
}
private UIElement BuildContent()
{
Grid root = new Grid();
_surface = new Border
{
CornerRadius = new CornerRadius(10),
BorderBrush = CreateBrush(Color.FromArgb(72, 255, 255, 255)),
BorderThickness = new Thickness(1),
Padding = new Thickness(12, 8, 12, 10)
};
ApplySurfaceBrush();
root.Children.Add(_surface);
Grid shell = new Grid();
shell.RowDefinitions.Add(new RowDefinition { Height = new GridLength(26) });
shell.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
_surface.Child = shell;
Grid header = new Grid { Cursor = Cursors.SizeAll };
header.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
header.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
header.MouseLeftButtonDown += OnHeaderMouseLeftButtonDown;
Grid.SetRow(header, 0);
shell.Children.Add(header);
TextBlock title = new TextBlock
{
Text = Title,
Foreground = CreateBrush(Color.FromRgb(231, 238, 248)),
FontSize = 12,
FontWeight = FontWeights.SemiBold,
VerticalAlignment = VerticalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis
};
header.Children.Add(title);
StackPanel tools = new StackPanel
{
Orientation = Orientation.Horizontal,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetColumn(tools, 1);
header.Children.Add(tools);
_lockButton = CreateGlyphButton(DesktopHeaderGlyphs.Unlocked, "锁定位置和大小");
AutomationProperties.SetAutomationId(_lockButton, "LockUtilityBoxButton");
_lockButton.Click += delegate { SetLocked(!_layout.Locked); };
tools.Children.Add(_lockButton);
_collapseButton = CreateGlyphButton(DesktopHeaderGlyphs.Collapse, "折叠收纳盒");
AutomationProperties.SetAutomationId(_collapseButton, "CollapseUtilityBoxButton");
_collapseButton.Click += delegate { SetCollapsed(!_layout.Collapsed); };
tools.Children.Add(_collapseButton);
Button settingsButton = CreateGlyphButton(DesktopHeaderGlyphs.Settings, "设置");
AutomationProperties.SetAutomationId(settingsButton, "UtilityBoxSettingsButton");
settingsButton.Click += delegate
{
EventHandler handler = SettingsRequested;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
};
tools.Children.Add(settingsButton);
_body = new Grid { Margin = new Thickness(0, 4, 0, 0) };
_body.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
_body.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
_body.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
Grid.SetRow(_body, 1);
shell.Children.Add(_body);
StackPanel clock = new StackPanel { Margin = new Thickness(0, 0, 0, 7) };
_timeText = new TextBlock
{
Foreground = Brushes.White,
FontFamily = new FontFamily("Segoe UI Variable Display, Segoe UI"),
FontSize = 28,
FontWeight = FontWeights.Light,
LineHeight = 31
};
clock.Children.Add(_timeText);
_dateText = new TextBlock
{
Foreground = CreateBrush(Color.FromRgb(181, 194, 211)),
FontSize = 11
};
clock.Children.Add(_dateText);
_body.Children.Add(clock);
Grid sliders = new Grid();
sliders.RowDefinitions.Add(new RowDefinition { Height = new GridLength(32) });
sliders.RowDefinitions.Add(new RowDefinition { Height = new GridLength(32) });
Grid.SetRow(sliders, 1);
_body.Children.Add(sliders);
_volumeSlider = CreateSliderRow(sliders, 0, "音量", out _volumeValue);
_volumeSlider.ValueChanged += delegate
{
_volumeValue.Text = ((int)Math.Round(_volumeSlider.Value)).ToString(CultureInfo.InvariantCulture) + "%";
if (_volumeInitialized)
{
_pendingVolume = (int)Math.Round(_volumeSlider.Value);
_volumeCommitTimer.Stop();
_volumeCommitTimer.Start();
}
};
_brightnessSlider = CreateSliderRow(sliders, 1, "亮度", out _brightnessValue);
_brightnessSlider.ValueChanged += delegate
{
_brightnessValue.Text = ((int)Math.Round(_brightnessSlider.Value)).ToString(CultureInfo.InvariantCulture) + "%";
};
_brightnessSlider.AddHandler(Thumb.DragCompletedEvent,
new DragCompletedEventHandler(delegate { CommitBrightnessFromSlider(); }));
_brightnessSlider.PreviewMouseLeftButtonUp += delegate { CommitBrightnessFromSlider(); };
_brightnessSlider.PreviewKeyUp += delegate { CommitBrightnessFromSlider(); };
_brightnessSlider.PreviewMouseWheel += delegate { CommitBrightnessFromSlider(); };
_resizeThumb = Ui.ResizeThumb(17, "拖动调整小工具大小");
_resizeThumb.DragDelta += OnResizeDragDelta;
root.Children.Add(_resizeThumb);
UpdateLockVisual();
return root;
}
private Slider CreateSliderRow(Grid parent, int row, string label, out TextBlock valueText)
{
Grid line = new Grid();
line.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(38) });
line.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
line.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(42) });
Grid.SetRow(line, row);
parent.Children.Add(line);
TextBlock caption = new TextBlock
{
Text = label,
Foreground = CreateBrush(Color.FromRgb(204, 214, 227)),
FontSize = 11,
VerticalAlignment = VerticalAlignment.Center
};
line.Children.Add(caption);
Slider slider = new Slider
{
Minimum = 0,
Maximum = 100,
SmallChange = 2,
LargeChange = 10,
Height = 20,
Margin = new Thickness(3, 0, 7, 0),
VerticalAlignment = VerticalAlignment.Center,
IsSnapToTickEnabled = false
};
Grid.SetColumn(slider, 1);
line.Children.Add(slider);
valueText = new TextBlock
{
Text = "--",
Foreground = Brushes.White,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 11,
TextAlignment = TextAlignment.Right,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetColumn(valueText, 2);
line.Children.Add(valueText);
return slider;
}
private static Button CreateGlyphButton(string glyph, string toolTip)
{
Button button = new Button
{
Width = 24,
Height = 22,
Margin = new Thickness(2, 0, 0, 0),
Padding = new Thickness(0),
BorderThickness = new Thickness(0),
Background = Brushes.Transparent,
Foreground = CreateBrush(Color.FromRgb(205, 216, 231)),
FontSize = 12,
Cursor = Cursors.Hand
};
Ui.SetHeaderGlyph(button, glyph, toolTip);
return button;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (_loaded)
{
UpdateClock();
if (DesktopPinEnabled)
{
DesktopWindowBehavior.SendToDesktop(this);
}
return;
}
RefreshFromLayout();
_loaded = true;
UpdateClock();
_clockTimer.Start();
int volume;
if (AudioService.TryGetMasterVolume(out volume))
{
_volumeSlider.Value = volume;
_volumeValue.Text = volume.ToString(CultureInfo.InvariantCulture) + "%";
}
else
{
_volumeSlider.IsEnabled = false;
_volumeValue.Text = "不可用";
}
_volumeInitialized = true;
// WMI and DDC/CI calls can be slow on some displays, so the only
// automatic brightness read is performed off the UI thread here.
ThreadPool.QueueUserWorkItem(delegate
{
int brightness;
bool available = BrightnessService.TryGetBrightness(out brightness);
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(delegate
{
if (!_loaded)
{
return;
}
if (available)
{
_brightnessSlider.Value = brightness;
_brightnessValue.Text = brightness.ToString(CultureInfo.InvariantCulture) + "%";
_brightnessInitialized = true;
}
else
{
_brightnessSlider.IsEnabled = false;
_brightnessValue.Text = "不可用";
}
}));
});
if (DesktopPinEnabled)
{
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(delegate
{
DesktopWindowBehavior.SendToDesktop(this);
}));
}
}
private void UpdateClock()
{
DateTime now = DateTime.Now;
_timeText.Text = now.ToString("HH:mm", CultureInfo.InvariantCulture);
_dateText.Text = now.ToString("M月d日 dddd", CultureInfo.GetCultureInfo("zh-CN"));
}
private void OnHeaderMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (_layout.Locked || e.ButtonState != MouseButtonState.Pressed)
{
return;
}
if (FindVisualParent<Button>(e.OriginalSource as DependencyObject) != null)
{
return;
}
if (e.ClickCount == 2)
{
SetCollapsed(!_layout.Collapsed);
e.Handled = true;
return;
}
try
{
DragMove();
e.Handled = true;
}
catch
{
}
EventHandler moveCompleted = MoveCompleted;
if (moveCompleted != null)
{
moveCompleted(this, EventArgs.Empty);
}
}
private void OnResizeDragDelta(object sender, DragDeltaEventArgs e)
{
if (_layout.Locked || _layout.Collapsed)
{
return;
}
Width = Math.Max(MinWidth, ActualWidth + e.HorizontalChange);
Height = Math.Max(150, ActualHeight + e.VerticalChange);
}
private void SetCollapsed(bool collapsed)
{
if (_layout.Collapsed == collapsed)
{
return;
}
_applyingLayout = true;
try
{
if (collapsed)
{
_layout.ExpandedHeight = Math.Max(150, ActualHeight);
_layout.Collapsed = true;
Height = CollapsedHeight;
}
else
{
_layout.Collapsed = false;
Height = Math.Max(150, _layout.ExpandedHeight);
}
_layout.Height = Height;
SetCollapsedVisual(collapsed);
}
finally
{
_applyingLayout = false;
}
RaiseLayoutChanged();
}
private void SetCollapsedVisual(bool collapsed)
{
_body.Visibility = collapsed ? Visibility.Collapsed : Visibility.Visible;
_resizeThumb.Visibility = collapsed || _layout.Locked ? Visibility.Collapsed : Visibility.Visible;
Ui.SetHeaderGlyph(
_collapseButton,
collapsed ? DesktopHeaderGlyphs.Expand : DesktopHeaderGlyphs.Collapse,
collapsed ? "展开收纳盒" : "折叠收纳盒");
_surface.Padding = collapsed ? new Thickness(12, 7, 12, 7) : new Thickness(12, 8, 12, 10);
}
private void UpdateLockVisual()
{
if (_lockButton == null)
{
return;
}
Ui.SetHeaderGlyph(
_lockButton,
_layout.Locked ? DesktopHeaderGlyphs.Locked : DesktopHeaderGlyphs.Unlocked,
_layout.Locked ? "解除锁定" : "锁定位置和大小");
if (_resizeThumb != null)
{
_resizeThumb.Visibility = _layout.Locked || _layout.Collapsed
? Visibility.Collapsed
: Visibility.Visible;
}
}
private void CommitBrightnessFromSlider()
{
if (!_brightnessInitialized || !_brightnessSlider.IsEnabled)
{
return;
}
QueueBrightnessSet((int)Math.Round(_brightnessSlider.Value));
}
private void QueueBrightnessSet(int percent)
{
lock (_brightnessQueueLock)
{
_pendingBrightness = Math.Max(0, Math.Min(100, percent));
if (_brightnessWorkerRunning)
{
return;
}
_brightnessWorkerRunning = true;
}
ThreadPool.QueueUserWorkItem(delegate
{
while (true)
{
int? next;
lock (_brightnessQueueLock)
{
next = _pendingBrightness;
_pendingBrightness = null;
if (!next.HasValue)
{
_brightnessWorkerRunning = false;
return;
}
}
BrightnessService.TrySetBrightness(next.Value);
}
});
}
private void ApplySurfaceBrush()
{
if (_surface == null)
{
return;
}
byte alpha = (byte)Math.Round(255.0 * _boxOpacity);
_surface.Background = CreateBrush(Color.FromArgb(alpha, 14, 22, 34));
}
private void RaiseLayoutChanged()
{
EventHandler handler = LayoutChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
private static T FindVisualParent<T>(DependencyObject start) where T : DependencyObject
{
DependencyObject current = start;
while (current != null)
{
T match = current as T;
if (match != null)
{
return match;
}
current = VisualTreeHelper.GetParent(current);
}
return null;
}
private static bool IsFinite(double value)
{
return !Double.IsNaN(value) && !Double.IsInfinity(value);
}
private static double Clamp(double value, double minimum, double maximum)
{
return Math.Max(minimum, Math.Min(maximum, value));
}
private static SolidColorBrush CreateBrush(Color color)
{
SolidColorBrush brush = new SolidColorBrush(color);
if (brush.CanFreeze)
{
brush.Freeze();
}
return brush;
}
}
}