/
electron_api_power_monitor_mac.mm
101 lines (80 loc) · 2.65 KB
/
electron_api_power_monitor_mac.mm
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
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_power_monitor.h"
#include <vector>
#import <ApplicationServices/ApplicationServices.h>
#import <Cocoa/Cocoa.h>
@interface MacLockMonitor : NSObject {
@private
std::vector<electron::api::PowerMonitor*> emitters;
}
- (void)addEmitter:(electron::api::PowerMonitor*)monitor_;
@end
@implementation MacLockMonitor
- (id)init {
if ((self = [super init])) {
NSDistributedNotificationCenter* distCenter =
[NSDistributedNotificationCenter defaultCenter];
// A notification that the screen was locked.
[distCenter addObserver:self
selector:@selector(onScreenLocked:)
name:@"com.apple.screenIsLocked"
object:nil];
// A notification that the screen was unlocked by the user.
[distCenter addObserver:self
selector:@selector(onScreenUnlocked:)
name:@"com.apple.screenIsUnlocked"
object:nil];
// A notification that the workspace posts before the machine goes to sleep.
[distCenter addObserver:self
selector:@selector(isSuspending:)
name:NSWorkspaceWillSleepNotification
object:nil];
// A notification that the workspace posts when the machine wakes from
// sleep.
[distCenter addObserver:self
selector:@selector(isResuming:)
name:NSWorkspaceDidWakeNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)addEmitter:(electron::api::PowerMonitor*)monitor_ {
self->emitters.push_back(monitor_);
}
- (void)isSuspending:(NSNotification*)notify {
for (auto* emitter : self->emitters) {
emitter->Emit("suspend");
}
}
- (void)isResuming:(NSNotification*)notify {
for (auto* emitter : self->emitters) {
emitter->Emit("resume");
}
}
- (void)onScreenLocked:(NSNotification*)notification {
for (auto* emitter : self->emitters) {
emitter->Emit("lock-screen");
}
}
- (void)onScreenUnlocked:(NSNotification*)notification {
for (auto* emitter : self->emitters) {
emitter->Emit("unlock-screen");
}
}
@end
namespace electron {
namespace api {
static MacLockMonitor* g_lock_monitor = nil;
void PowerMonitor::InitPlatformSpecificMonitors() {
if (!g_lock_monitor)
g_lock_monitor = [[MacLockMonitor alloc] init];
[g_lock_monitor addEmitter:this];
}
} // namespace api
} // namespace electron