Repository navigation
Expand file tree
/
Copy pathDomainListWindowController.m
More file actions
executable file
·465 lines (384 loc) · 16.3 KB
/
Copy pathDomainListWindowController.m
File metadata and controls
executable file
·465 lines (384 loc) · 16.3 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
//
// DomainListWindowController.m
// SelfControl
//
// Created by Charlie Stigler on 2/7/09.
// Copyright 2009 Eyebeam.
// This file is part of SelfControl.
//
// SelfControl is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#import "DomainListWindowController.h"
#import "AppController.h"
#import "SCUIUtilities.h"
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
@implementation DomainListWindowController
- (DomainListWindowController*)init {
if(self = [super initWithWindowNibName:@"DomainList"]) {
defaults_ = [NSUserDefaults standardUserDefaults];
NSArray* curArray = [defaults_ arrayForKey: @"Blocklist"];
if(curArray == nil)
domainList_ = [NSMutableArray arrayWithCapacity: 10];
else
domainList_ = [curArray mutableCopy];
[defaults_ setValue: domainList_ forKey: @"Blocklist"];
}
return self;
}
- (void)awakeFromNib {
NSInteger indexToSelect = [defaults_ boolForKey: @"BlockAsWhitelist"] ? 1 : 0;
[allowlistRadioMatrix_ selectCellAtRow: indexToSelect column: 0];
[self updateWindowTitle];
// Apply frosted glass styling
[self setupFrostedGlassAppearance];
}
- (void)refreshDomainList {
// end any current editing to trigger saving blocklist
if (![NSThread isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
[self refreshDomainList];
});
return;
}
[[self window] makeFirstResponder: self];
domainList_ = [[defaults_ arrayForKey: @"Blocklist"] mutableCopy];
[domainListTableView_ reloadData];
}
- (void)showWindow:(id)sender {
// If displayEntries was provided (e.g., from menu bar during active block),
// use those instead of NSUserDefaults
if (self.displayEntries) {
domainList_ = [self.displayEntries mutableCopy];
[domainListTableView_ reloadData];
}
// In readOnly mode, hide editing UI and show header
if (self.readOnly) {
[self setupReadOnlyAppearance];
} else {
[self setupEditableAppearance];
}
[[self window] makeKeyAndOrderFront: self];
if ([domainList_ count] == 0 && !self.readOnly) {
[self addDomain: self];
}
[self updateWindowTitle];
}
- (IBAction)addDomain:(id)sender
{
[domainList_ addObject:@""];
[defaults_ setValue: domainList_ forKey: @"Blocklist"];
[domainListTableView_ reloadData];
NSIndexSet* rowIndex = [NSIndexSet indexSetWithIndex: [domainList_ count] - 1];
[domainListTableView_ selectRowIndexes: rowIndex
byExtendingSelection: NO];
[domainListTableView_ editColumn: 0 row:((NSInteger)[domainList_ count] - 1)
withEvent:nil
select:YES];
}
- (IBAction)removeDomain:(id)sender
{
NSIndexSet* selected = [domainListTableView_ selectedRowIndexes];
[domainListTableView_ abortEditing];
// This isn't the most efficient way to do this, but the code is much cleaner
// than other methods and the domain blocklist will probably never be large
// enough for it to be an issue.
NSUInteger index = [selected firstIndex];
NSUInteger shift = 0;
while (index != NSNotFound) {
if ((index - shift) >= [domainList_ count])
break;
[domainList_ removeObjectAtIndex: index - shift];
shift++;
index = [selected indexGreaterThanIndex: index];
}
[defaults_ setValue: domainList_ forKey: @"Blocklist"];
[domainListTableView_ reloadData];
[[NSNotificationCenter defaultCenter] postNotificationName: @"SCConfigurationChangedNotification"
object: self];
}
- (NSUInteger)numberOfRowsInTableView:(NSTableView *)aTableView {
return [domainList_ count];
}
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
if (rowIndex < 0 || (NSUInteger)rowIndex + 1 > [domainList_ count]) return nil;
return domainList_[(NSUInteger)rowIndex];
}
- (BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row {
return !self.readOnly;
}
- (void)controlTextDidEndEditing:(NSNotification *)note {
NSInteger editedRow = [domainListTableView_ editedRow];
NSString* editedString = [[[[note userInfo] objectForKey: @"NSFieldEditor"] textStorage] string];
editedString = [editedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// sometimes we get an edited row index that's out-of-bounds for weird reasons,
// e.g. if we're editing an empty row and then start a block, the data will get reloaded
// and the row will not exist by the time this method gets called. We can ignore in that case
if (editedRow >= 0 && editedRow < domainListTableView_.numberOfRows && !editedString.length) {
NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex: (NSUInteger)editedRow];
[domainListTableView_ beginUpdates];
[domainListTableView_ removeRowsAtIndexes: indexSet withAnimation: NSTableViewAnimationSlideUp];
[domainList_ removeObjectAtIndex: (NSUInteger)editedRow];
[defaults_ setValue: domainList_ forKey: @"Blocklist"];
[domainListTableView_ reloadData];
[domainListTableView_ endUpdates];
[[NSNotificationCenter defaultCenter] postNotificationName: @"SCConfigurationChangedNotification"
object: self];
return;
}
}
- (void)tableView:(NSTableView *)aTableView
setObjectValue:(NSString*)newString
forTableColumn:(NSTableColumn *)aTableColumn
row:(NSInteger)rowIndex {
if (rowIndex < 0 || (NSUInteger)rowIndex + 1 > [domainList_ count]) {
return;
}
NSArray<NSString*>* cleanedEntries = [SCMiscUtilities cleanBlocklistEntry: newString];
for (NSUInteger i = 0; i < cleanedEntries.count; i++) {
NSString* entry = cleanedEntries[i];
if (i == 0) {
domainList_[(NSUInteger)rowIndex] = entry;
} else {
[domainList_ insertObject: entry atIndex: (NSUInteger)rowIndex + i];
}
}
[defaults_ setValue: domainList_ forKey: @"Blocklist"];
[domainListTableView_ reloadData];
[[NSNotificationCenter defaultCenter] postNotificationName: @"SCConfigurationChangedNotification"
object: self];
}
- (void)tableView:(NSTableView *)tableView
willDisplayCell:(id)cell
forTableColumn:(NSTableColumn *)tableColumn
row:(int)row {
// Initialize the cell's text color
[cell setTextColor: NSColor.textColor];
NSString* str = [[cell title] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([str isEqual: @""]) return;
// Handle app entries - show them in purple with app name
if ([str hasPrefix:@"app:"]) {
NSString* bundleID = [str substringFromIndex:4];
NSString* appName = [self appNameForBundleID:bundleID];
if (appName) {
[cell setStringValue:[NSString stringWithFormat:@"[App] %@ (%@)", appName, bundleID]];
}
[cell setTextColor:[NSColor systemPurpleColor]];
return;
}
if([defaults_ boolForKey: @"HighlightInvalidHosts"]) {
// Validate the value as either an IP or a hostname. In case of failure,
// we'll make its text color red.
int maskLength = -1;
int portNum = -1;
NSArray* splitString = [str componentsSeparatedByString: @"/"];
str = [splitString[0] lowercaseString];
NSString* stringToSearchForPort = str;
if([splitString count] >= 2) {
maskLength = [splitString[1] intValue];
// If the int value is 0, we couldn't find a valid integer representation
// in the split off string
if(maskLength == 0)
maskLength = -1;
stringToSearchForPort = splitString[1];
}
splitString = [stringToSearchForPort componentsSeparatedByString: @":"];
if(stringToSearchForPort == str) {
str = splitString[0];
}
if([splitString count] >= 2) {
portNum = [splitString[1] intValue];
// If the int value is 0, we couldn't find a valid integer representation
// in the split off string
if(portNum == 0)
portNum = -1;
}
BOOL isIP;
NSString* ipValidationRegex = @"^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
NSPredicate *ipRegexTester = [NSPredicate
predicateWithFormat:@"SELF MATCHES %@",
ipValidationRegex];
isIP = [ipRegexTester evaluateWithObject: str];
if(!isIP) {
NSString* hostnameValidationRegex = @"^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$";
NSPredicate *hostnameRegexTester = [NSPredicate
predicateWithFormat:@"SELF MATCHES %@",
hostnameValidationRegex
];
if(![hostnameRegexTester evaluateWithObject: str] && ![str isEqualToString: @"*"] && ![str isEqualToString: @""]) {
[cell setTextColor: NSColor.redColor];
return;
}
}
// We shouldn't have a mask length if it's not an IP, fail
if(!isIP && maskLength != -1) {
[cell setTextColor: NSColor.redColor];
return;
}
if(([str isEqualToString: @"*"] || [str isEqualToString: @""]) && portNum == -1) {
[cell setTextColor: NSColor.redColor];
return;
}
[cell setTextColor: NSColor.textColor];
}
}
- (IBAction)allowlistOptionChanged:(NSMatrix*)sender {
switch (sender.selectedRow) {
case 0:
[defaults_ setBool: NO forKey: @"BlockAsWhitelist"];
break;
case 1:
[self showAllowlistWarning];
[defaults_ setBool: YES forKey: @"BlockAsWhitelist"];
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName: @"SCConfigurationChangedNotification"
object: self];
// update UI to reflect appropriate list type
AppController* controller = (AppController *)[NSApp delegate];
[controller refreshUserInterface];
[self updateWindowTitle];
}
- (void)showAllowlistWarning {
if(![defaults_ boolForKey: @"WhitelistAlertSuppress"]) {
NSAlert* alert = [NSAlert new];
alert.messageText = NSLocalizedString(@"Are you sure you want an allowlist block?", @"Allowlist block confirmation prompt");
[alert addButtonWithTitle: NSLocalizedString(@"OK", @"OK button")];
alert.informativeText = NSLocalizedString(@"An allowlist block means that everything on the internet BESIDES your specified list will be blocked. This includes the web, email, SSH, and anything else your computer accesses via the internet. This can cause unexpected behavior. If a web site requires resources such as images or scripts from a site that is not on your allowlist, the site may not work properly.", @"allowlist block explanation");
alert.showsSuppressionButton = YES;
[alert runModal];
if (alert.suppressionButton.state == NSOnState) {
[defaults_ setBool: YES forKey: @"WhitelistAlertSuppress"];
}
}
}
- (void)updateWindowTitle {
NSString* listType = [defaults_ boolForKey: @"BlockAsWhitelist"] ? @"Allowlist" : @"Blocklist";
self.window.title = NSLocalizedString(([NSString stringWithFormat: @"Domain %@", listType]), @"Domain list window title");
}
- (void)addHostArray:(NSArray*)arr {
for(NSUInteger i = 0; i < [arr count]; i++) {
// Check for dupes
if(![domainList_ containsObject: arr[i]])
[domainList_ addObject: arr[i]];
}
[defaults_ setValue: domainList_ forKey: @"Blocklist"];
[domainListTableView_ reloadData];
[[NSNotificationCenter defaultCenter] postNotificationName: @"SCConfigurationChangedNotification"
object: self];
}
- (IBAction)importCommonDistractingWebsites:(id)sender {
[self addHostArray: [HostImporter commonDistractingWebsites]];
}
- (IBAction)importNewsAndPublications:(id)sender {
[self addHostArray: [HostImporter newsAndPublications]];
}
- (IBAction)importIncomingMailServersFromThunderbird:(id)sender {
[self addHostArray: [HostImporter incomingMailHostnamesFromThunderbird]];
}
- (IBAction)importOutgoingMailServersFromThunderbird:(id)sender {
[self addHostArray: [HostImporter outgoingMailHostnamesFromThunderbird]];
}
- (IBAction)importIncomingMailServersFromMail:(id)sender {
[self addHostArray: [HostImporter incomingMailHostnamesFromMail]];
}
- (IBAction)importOutgoingMailServersFromMail:(id)sender {
[self addHostArray: [HostImporter outgoingMailHostnamesFromMail]];
}
- (IBAction)importIncomingMailServersFromMailMate:(id)sender {
[self addHostArray: [HostImporter incomingMailHostnamesFromMailMate]];
}
- (IBAction)importOutgoingMailServersFromMailMate:(id)sender {
[self addHostArray: [HostImporter outgoingMailHostnamesFromMailMate]];
}
#pragma mark - App Blocking
- (NSString*)appNameForBundleID:(NSString*)bundleID {
NSString* appPath = [[NSWorkspace sharedWorkspace]
absolutePathForAppBundleWithIdentifier:bundleID];
if (appPath) {
return [[NSFileManager defaultManager] displayNameAtPath:appPath];
}
return nil;
}
- (IBAction)addAppToBlocklist:(id)sender {
NSOpenPanel* panel = [NSOpenPanel openPanel];
panel.allowsMultipleSelection = YES;
panel.canChooseDirectories = NO;
panel.canChooseFiles = YES;
panel.directoryURL = [NSURL fileURLWithPath:@"/Applications"];
panel.message = @"Select applications to block";
panel.prompt = @"Add to Blocklist";
// Only allow .app bundles
if (@available(macOS 11.0, *)) {
panel.allowedContentTypes = @[UTTypeApplication];
} else {
panel.allowedFileTypes = @[@"app"];
}
[panel beginSheetModalForWindow:self.window
completionHandler:^(NSModalResponse result) {
if (result == NSModalResponseOK) {
NSMutableArray* appsToAdd = [NSMutableArray array];
for (NSURL* appURL in panel.URLs) {
NSBundle* appBundle = [NSBundle bundleWithURL:appURL];
NSString* bundleID = appBundle.bundleIdentifier;
if (bundleID) {
NSString* entry = [NSString stringWithFormat:@"app:%@", bundleID];
// Avoid duplicates
if (![self->domainList_ containsObject:entry]) {
[appsToAdd addObject:entry];
}
} else {
NSLog(@"Warning: Could not get bundle ID for %@", appURL);
}
}
if (appsToAdd.count > 0) {
[self addHostArray:appsToAdd];
}
}
}];
}
#pragma mark - Frosted Glass Appearance
- (void)setupFrostedGlassAppearance {
NSWindow* window = [self window];
NSView* contentView = window.contentView;
// Apply window styling for transparency
[SCUIUtilities applyFrostedGlassStyleToWindow:window];
// Create frosted glass background view
NSVisualEffectView* frostedBackground = [SCUIUtilities createFrostedGlassViewWithFrame:contentView.bounds cornerRadius:12.0];
frostedBackground.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
// Insert at the back so all other content appears on top
[contentView addSubview:frostedBackground positioned:NSWindowBelow relativeTo:nil];
// Make content view layer-backed for proper compositing
contentView.wantsLayer = YES;
// Make table view background transparent so frosted glass shows through
domainListTableView_.backgroundColor = NSColor.clearColor;
domainListTableView_.enclosingScrollView.drawsBackground = NO;
// Force shadow recalculation
[window invalidateShadow];
}
- (void)setupReadOnlyAppearance {
// Hide editing UI (radio buttons and "can't be edited" message)
allowlistRadioMatrix_.hidden = YES;
// Find and hide the "can't be edited" label
for (NSView* subview in self.window.contentView.subviews) {
if ([subview isKindOfClass:[NSTextField class]]) {
NSTextField* textField = (NSTextField*)subview;
if ([textField.stringValue containsString:@"can't be edited"]) {
textField.hidden = YES;
break;
}
}
}
}
- (void)setupEditableAppearance {
// Show editing UI
allowlistRadioMatrix_.hidden = NO;
}
@end