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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
|
/* HBQueueController
This file is part of the HandBrake source code.
Homepage: <http://handbrake.fr/>.
It may be used under the terms of the GNU General Public License. */
#import "HBQueueController.h"
#import "HBAppDelegate.h"
#import "HBQueue.h"
#import "HBQueueWorker.h"
#import "HBQueueTableViewController.h"
#import "HBQueueDetailsViewController.h"
#import "HBQueueInfoViewController.h"
#import "HBQueueMultiSelectionViewController.h"
#import "HBPreferencesKeys.h"
#import "NSArray+HBAdditions.h"
@import HandBrakeKit;
@interface HBQueueController () <NSToolbarItemValidation, NSMenuItemValidation, NSUserNotificationCenterDelegate, HBQueueTableViewControllerDelegate, HBQueueDetailsViewControllerDelegate>
@property (nonatomic) NSSplitViewController *splitViewController;
@property (nonatomic) HBQueueTableViewController *tableViewController;
@property (nonatomic) NSViewController *containerViewController;
@property (nonatomic) HBQueueInfoViewController *infoViewController;
@property (nonatomic) HBQueueMultiSelectionViewController *multiSelectionViewController;
/// Whether the window is visible or occluded,
/// useful to avoid updating the UI needlessly
@property (nonatomic) BOOL visible;
@property (nonatomic) IBOutlet NSToolbarItem *ripToolbarItem;
@property (nonatomic) IBOutlet NSToolbarItem *pauseToolbarItem;
@property (nonatomic, readonly) dispatch_queue_t sendQueue;
@end
@interface HBQueueController (TouchBar) <NSTouchBarProvider, NSTouchBarDelegate>
- (void)_touchBar_updateButtonsState;
- (void)_touchBar_validateUserInterfaceItems;
- (IBAction)_touchBar_toggleStartCancel:(id)sender;
@end
@implementation HBQueueController
- (instancetype)initWithQueue:(HBQueue *)queue
{
NSParameterAssert(queue);
if (self = [super initWithWindowNibName:@"Queue"])
{
_queue = queue;
_sendQueue = dispatch_queue_create("fr.handbrake.SendToQueue", DISPATCH_QUEUE_SERIAL);
NSUserNotificationCenter.defaultUserNotificationCenter.delegate = self;
[NSNotificationCenter.defaultCenter addObserverForName:HBQueueLowSpaceAlertNotification object:_queue queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
[self queueLowDiskSpaceAlert];
}];
[NSNotificationCenter.defaultCenter addObserverForName:HBQueueDidCompleteNotification object:_queue queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
[self queueCompletedAlerts];
}];
[NSNotificationCenter.defaultCenter addObserverForName:HBQueueDidCompleteItemNotification object:_queue queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
// Run the per item notification and actions
HBQueueJobItem *item = note.userInfo[HBQueueItemNotificationItemKey];
if (item.state == HBQueueItemStateCompleted)
{
[self sendToExternalApp:item];
}
if (item.state == HBQueueItemStateCompleted || item.state == HBQueueItemStateFailed)
{
[self itemCompletedAlerts:item];
}
}];
}
return self;
}
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window
{
return _queue.undoManager;
}
- (void)windowDidLoad
{
if (@available (macOS 10.12, *))
{
self.window.tabbingMode = NSWindowTabbingModeDisallowed;
}
#if defined(__MAC_11_0)
if (@available (macOS 11, *))
{
self.window.toolbarStyle = NSWindowToolbarStyleUnified;
self.window.titlebarSeparatorStyle = NSTitlebarSeparatorStyleLine;
}
#endif
// Set up the child view controllers
_splitViewController = [[NSSplitViewController alloc] init];
_splitViewController.view.wantsLayer = YES;
[_splitViewController.view setFrameSize:NSMakeSize(780, 500)];
_splitViewController.splitView.vertical = YES;
_tableViewController = [[HBQueueTableViewController alloc] initWithQueue:self.queue delegate:self];
_containerViewController = [[HBQueueDetailsViewController alloc] init];
_infoViewController = [[HBQueueInfoViewController alloc] initWithDelegate:self];
_multiSelectionViewController = [[HBQueueMultiSelectionViewController alloc] init];
NSSplitViewItem *tableItem = [NSSplitViewItem splitViewItemWithViewController:_tableViewController];
tableItem.minimumThickness = 160;
[_splitViewController addSplitViewItem:tableItem];
NSSplitViewItem *detailsItem = [NSSplitViewItem splitViewItemWithViewController:_containerViewController];
detailsItem.canCollapse = YES;
detailsItem.minimumThickness = 240;
[_splitViewController addSplitViewItem:detailsItem];
_splitViewController.splitView.autosaveName = @"HBQueueSplitViewAutosave";
_splitViewController.splitView.identifier = @"HBQueueSplitViewIdentifier";
self.window.contentViewController = _splitViewController;
self.window.frameAutosaveName = @"HBQueueWindowFrameAutosave";
[self.window setFrameFromString:@"HBQueueWindowFrameAutosave"];
// Set up observers
[NSNotificationCenter.defaultCenter addObserverForName:HBQueueDidChangeStateNotification object:_queue queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
[self updateUI];
}];
[self updateUI];
[self tableViewDidSelectItemsAtIndexes:[NSIndexSet indexSet]];
}
- (void)updateUI
{
[self updateToolbarButtonsState];
[self.window.toolbar validateVisibleItems];
if (@available(macOS 10.12.2, *))
{
[self _touchBar_updateButtonsState];
[self _touchBar_validateUserInterfaceItems];
}
NSString *subtitle;
if (self.queue.pendingItemsCount == 0)
{
self.window.title = NSLocalizedString(@"Queue", @"Queue window title");
subtitle = NSLocalizedString(@"No encode pending", @"Queue status");
}
else
{
if (self.queue.pendingItemsCount == 1)
{
subtitle = [NSString stringWithFormat: NSLocalizedString(@"%lu encode pending", @"Queue status"), (unsigned long)self.queue.pendingItemsCount];
}
else
{
subtitle = [NSString stringWithFormat: NSLocalizedString(@"%lu encodes pending", @"Queue status"), (unsigned long)self.queue.pendingItemsCount];
}
#if defined(__MAC_11_0)
if (@available(macOS 11, *)) {} else
{
#endif
self.window.title = [NSString stringWithFormat: NSLocalizedString(@"Queue (%@)", @"Queue window title"), subtitle];
#if defined(__MAC_11_0)
}
#endif
}
#if defined(__MAC_11_0)
if (@available(macOS 11, *))
{
self.window.subtitle = subtitle;
}
#endif
}
#pragma mark Toolbar
- (void)updateToolbarButtonsState
{
if (self.queue.canResume)
{
_pauseToolbarItem.image = [NSImage imageNamed: @"encode"];
_pauseToolbarItem.label = NSLocalizedString(@"Resume", @"Toolbar Pause Item");
_pauseToolbarItem.toolTip = NSLocalizedString(@"Resume Encoding", @"Toolbar Pause Item");
}
else
{
_pauseToolbarItem.image = [NSImage imageNamed:@"pauseencode"];
_pauseToolbarItem.label = NSLocalizedString(@"Pause", @"Toolbar Pause Item");
_pauseToolbarItem.toolTip = NSLocalizedString(@"Pause Encoding", @"Toolbar Pause Item");
}
if (self.queue.isEncoding)
{
_ripToolbarItem.image = [NSImage imageNamed:@"stopencode"];
_ripToolbarItem.label = NSLocalizedString(@"Stop", @"Toolbar Start/Stop Item");
_ripToolbarItem.toolTip = NSLocalizedString(@"Stop Encoding", @"Toolbar Start/Stop Item");
}
else
{
_ripToolbarItem.image = [NSImage imageNamed: @"encode"];
_ripToolbarItem.label = NSLocalizedString(@"Start", @"Toolbar Start/Stop Item");
_pauseToolbarItem.toolTip = NSLocalizedString(@"Start Encoding", @"Toolbar Start/Stop Item");
}
}
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
SEL action = menuItem.action;
if (action == @selector(toggleStartCancel:))
{
if (self.queue.isEncoding)
{
menuItem.title = NSLocalizedString(@"Stop Encoding", @"Queue -> start/stop menu");
return YES;
}
else
{
menuItem.title = NSLocalizedString(@"Start Encoding", @"Queue -> start/stop menu");
return self.queue.canEncode;
}
}
if (action == @selector(togglePauseResume:))
{
if (self.queue.canPause)
{
menuItem.title = NSLocalizedString(@"Pause Encoding", @"Queue -> pause/resume menu");
}
else
{
menuItem.title = NSLocalizedString(@"Resume Encoding", @"Queue -> pause/resume men");
}
return self.queue.canPause || self.queue.canResume;
}
if (action == @selector(removeAll:) || action == @selector(resetAll:))
{
return self.queue.items.count > 0;
}
if (action == @selector(resetFailed:))
{
return self.queue.failedItemsCount > 0;
}
if (action == @selector(removeCompleted:))
{
return self.queue.completedItemsCount > 0;
}
return YES;
}
- (BOOL)validateUserIterfaceItemForAction:(SEL)action
{
if (action == @selector(toggleStartCancel:) || action == @selector(_touchBar_toggleStartCancel:))
{
return self.queue.isEncoding || self.queue.canEncode;
}
if (action == @selector(togglePauseResume:))
{
return self.queue.canPause || self.queue.canResume;
}
return NO;
}
- (BOOL)validateToolbarItem:(NSToolbarItem *)theItem
{
SEL action = theItem.action;
return [self validateUserIterfaceItemForAction:action];
}
- (void)windowDidChangeOcclusionState:(NSNotification *)notification
{
self.visible = self.window.occlusionState & NSWindowOcclusionStateVisible ? YES : NO;
}
#pragma mark - Private queue editing methods
/**
* Delete encodes from the queue window and accompanying array
* Also handling first cancelling the encode if in fact its currently encoding.
*/
- (void)removeQueueItemsAtIndexes:(NSIndexSet *)indexes
{
if (indexes.count)
{
NSMutableIndexSet *mutableIndexes = [indexes mutableCopy];
// if this is a currently encoding job, we need to be sure to alert the user,
// to let them decide to cancel it first, then if they do, we can come back and
// remove it
NSIndexSet *workingIndexes = [self.queue.items HB_indexesOfObjectsUsingBlock:^BOOL(HBQueueJobItem *item) {
return item.state == HBQueueItemStateWorking;
}];
NSIndexSet *workingSelectedIndexes = [workingIndexes HB_intersectionWith:indexes];
[mutableIndexes removeIndexes:workingSelectedIndexes];
if (workingSelectedIndexes.count)
{
NSString *alertTitle = [NSString stringWithFormat:NSLocalizedString(@"Stop This Encode and Remove It?", @"Queue Stop Alert -> stop and remove message")];
// Which window to attach the sheet to?
NSWindow *targetWindow = self.window;
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:alertTitle];
[alert setInformativeText:NSLocalizedString(@"Your movie will be lost if you don't continue encoding.", @"Queue Stop Alert -> stop and remove informative text")];
[alert addButtonWithTitle:NSLocalizedString(@"Keep Encoding", @"Queue Stop Alert -> stop and remove first button")];
[alert addButtonWithTitle:NSLocalizedString(@"Stop Encoding and Delete", @"Queue Stop Alert -> stop and remove second button")];
#if defined(__MAC_11_0)
if (@available(macOS 11, *))
{
alert.buttons.lastObject.hasDestructiveAction = true;
}
#endif
[alert setAlertStyle:NSAlertStyleCritical];
[alert beginSheetModalForWindow:targetWindow completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertSecondButtonReturn)
{
[self.queue cancelItemsAtIndexes:workingSelectedIndexes];
[self.queue removeItemsAtIndexes:workingSelectedIndexes];
}
}];
}
// remove the non working items immediately
[self.queue removeItemsAtIndexes:mutableIndexes];
}
}
- (void)doEditQueueItem:(HBQueueJobItem *)item
{
[self.queue prepareItemForEditingAtIndex:[self.queue.items indexOfObject:item]];
[self.delegate openJob:[item.job copy] completionHandler:^(BOOL result) {
NSInteger index = [self.queue.items indexOfObject:item];
if (index != NSNotFound)
{
[self.queue resetItemsAtIndexes:[NSIndexSet indexSetWithIndex:index]];
if (result)
{
// Now that source is loaded and settings applied, delete the queue item from the queue
[self.queue removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:index]];
}
else
{
NSBeep();
}
}
else
{
item.state = HBQueueItemStateReady;
}
}];
}
/**
* Send the selected queue item back to the main window for rescan and possible edit.
*/
- (void)editQueueItem:(HBQueueJobItem *)item
{
// if this is a currently encoding item, we need to be sure to alert the user,
// to let them decide to cancel it first, then if they do, we can come back and
// remove it
if (item.state == HBQueueItemStateWorking)
{
NSString *alertTitle = [NSString stringWithFormat:NSLocalizedString(@"Stop This Encode and Edit It?", @"Queue Edit Alert -> stop and edit message")];
// Which window to attach the sheet to?
NSWindow *docWindow = self.window;
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:alertTitle];
[alert setInformativeText:NSLocalizedString(@"Your movie will be lost if you don't continue encoding.", @"Queue Edit Alert -> stop and edit informative text")];
[alert addButtonWithTitle:NSLocalizedString(@"Keep Encoding", @"Queue Edit Alert -> stop and edit first button")];
[alert addButtonWithTitle:NSLocalizedString(@"Stop Encoding and Edit", @"Queue Edit Alert -> stop and edit second button")];
#if defined(__MAC_11_0)
if (@available(macOS 11, *))
{
alert.buttons.lastObject.hasDestructiveAction = true;
}
#endif
[alert setAlertStyle:NSAlertStyleCritical];
[alert beginSheetModalForWindow:docWindow completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertSecondButtonReturn)
{
[self doEditQueueItem:item];
}
}];
}
else if (item.state != HBQueueItemStateWorking && item.state != HBQueueItemStateRescanning)
{
[self doEditQueueItem:item];
}
}
- (void)resetQueueItemsAtIndexes:(NSIndexSet *)indexes
{
[self.queue resetItemsAtIndexes:indexes];
}
#pragma mark - Encode Done Actions
NSString * const HBQueueItemNotificationPathKey = @"HBQueueItemNotificationPathKey";
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
// Show the file in Finder when a done notification was clicked.
NSString *path = notification.userInfo[HBQueueItemNotificationPathKey];
if ([path isKindOfClass:[NSString class]] && path.length)
{
NSURL *fileURL = [NSURL fileURLWithPath:path];
[NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[fileURL]];
}
}
- (void)showNotificationWithTitle:(NSString *)title description:(NSString *)description url:(NSURL *)fileURL playSound:(BOOL)playSound
{
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = title;
notification.informativeText = description;
notification.soundName = playSound ? NSUserNotificationDefaultSoundName : nil;
notification.hasActionButton = YES;
notification.actionButtonTitle = NSLocalizedString(@"Show", @"Notification -> Show in Finder");
notification.userInfo = @{ HBQueueItemNotificationPathKey: fileURL.path };
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}
/**
* Sends the URL to the external app
* selected in the preferences.
*
* @param job the job of the file to send
*/
- (void)sendToExternalApp:(HBQueueJobItem *)item
{
// This end of encode action is called as each encode rolls off of the queue
if ([NSUserDefaults.standardUserDefaults boolForKey:HBSendToAppEnabled] == YES)
{
NSURL *outputURL = item.outputURL;
NSString *completeOutputPath = item.completeOutputURL.path;
dispatch_async(_sendQueue, ^{
#ifdef __SANDBOX_ENABLED__
BOOL accessingSecurityScopedResource = [outputURL startAccessingSecurityScopedResource];
#endif
NSWorkspace *workspace = NSWorkspace.sharedWorkspace;
NSString *app = [workspace fullPathForApplication:[NSUserDefaults.standardUserDefaults objectForKey:HBSendToApp]];
if (app)
{
if (![workspace openFile:completeOutputPath withApplication:app])
{
[HBUtilities writeToActivityLog:"Failed to send file to: %s", app];
}
}
else
{
[HBUtilities writeToActivityLog:"Send file to: app not found"];
}
#ifdef __SANDBOX_ENABLED__
if (accessingSecurityScopedResource)
{
[outputURL stopAccessingSecurityScopedResource];
}
#endif
});
}
}
/**
* Runs the alert for a single job
*/
- (void)itemCompletedAlerts:(HBQueueJobItem *)item
{
NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
// Both the Notification and Sending to tagger can be done as encodes roll off the queue
if ([ud integerForKey:HBAlertWhenDone] == HBDoneActionNotification ||
[ud integerForKey:HBAlertWhenDone] == HBDoneActionAlertAndNotification)
{
// If Play System Alert has been selected in Preferences
bool playSound = [ud boolForKey:HBAlertWhenDoneSound];
NSString *title;
NSString *description;
if (item.state == HBQueueItemStateCompleted)
{
title = NSLocalizedString(@"Put down that cocktail…", @"Queue notification alert message");
description = [NSString stringWithFormat:NSLocalizedString(@"Your encode %@ is done!", @"Queue done notification message"),
item.outputFileName];
}
else
{
title = NSLocalizedString(@"Encode failed", @"Queue done notification failed message");
description = [NSString stringWithFormat:NSLocalizedString(@"Your encode %@ couldn't be completed.", @"Queue done notification message"),
item.outputFileName];
}
[self showNotificationWithTitle:title
description:description
url:item.completeOutputURL
playSound:playSound];
}
}
/**
* Runs the global queue completed alerts
*/
- (void)queueCompletedAlerts
{
NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
// If Play System Alert has been selected in Preferences
if ([ud boolForKey:HBAlertWhenDoneSound] == YES)
{
NSBeep();
}
// If Alert Window or Window and Notification has been selected
if ([ud integerForKey:HBAlertWhenDone] == HBDoneActionAlert ||
[ud integerForKey:HBAlertWhenDone] == HBDoneActionAlertAndNotification)
{
// On Screen Notification
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:NSLocalizedString(@"Put down that cocktail…", @"Queue done alert message")];
[alert setInformativeText:NSLocalizedString(@"Your HandBrake queue is done!", @"Queue done alert informative text")];
[NSApp requestUserAttention:NSCriticalRequest];
[alert runModal];
}
// If sleep has been selected
if ([ud integerForKey:HBAlertWhenDone] == HBDoneActionSleep)
{
// Sleep
NSAppleScript *scriptObject = [[NSAppleScript alloc] initWithSource:
@"tell application \"System Events\" to sleep"];
[scriptObject executeAndReturnError:NULL];
}
// If Shutdown has been selected
if ([ud integerForKey:HBAlertWhenDone] == HBDoneActionShutDown)
{
// Shut Down
NSAppleScript *scriptObject = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to shut down"];
[scriptObject executeAndReturnError:NULL];
}
}
- (void)queueLowDiskSpaceAlert
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:NSLocalizedString(@"Your destination disk is almost full.", @"Queue -> disk almost full alert message")];
[alert setInformativeText:NSLocalizedString(@"You need to make more space available on your destination disk.",@"Queue -> disk almost full alert informative text")];
[NSApp requestUserAttention:NSCriticalRequest];
[alert runModal];
}
- (void)remindUserOfSleepOrShutdown
{
NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
if ([ud integerForKey:HBAlertWhenDone] == HBDoneActionSleep)
{
// Warn that computer will sleep after encoding
NSBeep();
[NSApp requestUserAttention:NSCriticalRequest];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:NSLocalizedString(@"The computer will sleep after encoding is done.", @"Queue Done Alert -> sleep message")];
[alert setInformativeText:NSLocalizedString(@"You have selected to sleep the computer after encoding. To turn off sleeping, go to the HandBrake preferences.", @"Queue Done Alert -> sleep informative text")];
[alert addButtonWithTitle:NSLocalizedString(@"OK", @"Queue Done Alert -> sleep first button")];
[alert addButtonWithTitle:NSLocalizedString(@"Preferences…", @"Queue Done Alert -> sleep second button")];
NSInteger response = [alert runModal];
if (response == NSAlertSecondButtonReturn)
{
[self.delegate showPreferencesWindow:nil];
}
[self promptForAppleEventAuthorization];
}
else if ([ud integerForKey:HBAlertWhenDone] == HBDoneActionShutDown)
{
// Warn that computer will shut down after encoding
NSBeep();
[NSApp requestUserAttention:NSCriticalRequest];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:NSLocalizedString(@"The computer will shut down after encoding is done.", @"Queue Done Alert -> shut down message")];
[alert setInformativeText:NSLocalizedString(@"You have selected to shut down the computer after encoding. To turn off shut down, go to the HandBrake preferences.", @"Queue Done Alert -> shut down informative text")];
[alert addButtonWithTitle:NSLocalizedString(@"OK", @"Queue Done Alert -> shut down first button")];
[alert addButtonWithTitle:NSLocalizedString(@"Preferences…", @"Queue Done Alert -> shut down second button")];
NSInteger response = [alert runModal];
if (response == NSAlertSecondButtonReturn)
{
[self.delegate showPreferencesWindow:nil];
}
[self promptForAppleEventAuthorization];
}
}
- (void)promptForAppleEventAuthorization
{
HBPrivacyConsentState result = [HBUtilities determinePermissionToAutomateTarget:@"com.apple.systemevents" promptIfNeeded:YES];
if (result != HBPrivacyConsentStateGranted)
{
[HBUtilities writeToActivityLog:"Failed to get permission to automate system events"];
}
}
#pragma mark - UI Actions
/**
* Rip: puts up an alert before ultimately calling doRip
*/
- (IBAction)toggleStartCancel:(id)sender
{
// Rip or Cancel ?
if (self.queue.isEncoding)
{
[self cancelRip:sender];
}
// If there are pending items in the queue, then this is a rip the queue
else if (self.queue.canEncode)
{
// We check to see if we need to warn the user that the computer will go to sleep
// or shut down when encoding is finished
[self remindUserOfSleepOrShutdown];
[self.queue start];
}
}
/**
* Starts or cancels the processing of items depending on the current state
* Displays an alert asking user if the want to cancel encoding of current item.
*/
- (IBAction)cancelRip:(id)sender
{
// Which window to attach the sheet to?
NSWindow *window = self.window;
if ([sender respondsToSelector:@selector(window)])
{
window = [sender window];
}
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:NSLocalizedString(@"You are currently encoding. What would you like to do?", @"Queue Alert -> cancel rip message")];
[alert setInformativeText:NSLocalizedString(@"Select Continue Encoding to dismiss this dialog without making changes.", @"Queue Alert -> cancel rip informative text")];
[alert addButtonWithTitle:NSLocalizedString(@"Continue Encoding", @"Queue Alert -> cancel rip first button")];
[alert addButtonWithTitle:NSLocalizedString(@"Skip Current Job", @"Queue Alert -> cancel rip second button")];
#if defined(__MAC_11_0)
if (@available(macOS 11, *))
{
alert.buttons.lastObject.hasDestructiveAction = true;
}
#endif
[alert addButtonWithTitle:NSLocalizedString(@"Stop After Current Job", @"Queue Alert -> cancel rip third button")];
[alert addButtonWithTitle:NSLocalizedString(@"Stop All", @"Queue Alert -> cancel rip fourth button")];
#if defined(__MAC_11_0)
if (@available(macOS 11, *))
{
alert.buttons.lastObject.hasDestructiveAction = true;
}
#endif
[alert setAlertStyle:NSAlertStyleCritical];
[alert beginSheetModalForWindow:window completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertSecondButtonReturn)
{
[self.queue cancelCurrentAndContinue];
}
else if (returnCode == NSAlertThirdButtonReturn)
{
[self.queue finishCurrentAndStop];
}
else if (returnCode == NSAlertThirdButtonReturn + 1)
{
[self.queue cancelCurrentAndStop];
}
}];
}
/**
* Toggles the pause/resume state of libhb
*/
- (IBAction)togglePauseResume:(id)sender
{
if (self.queue.canResume)
{
[self.queue resume];
}
else if (self.queue.canPause)
{
[self.queue pause];
}
}
- (IBAction)toggleDetails:(id)sender
{
NSSplitViewItem *detailsItem = self.splitViewController.splitViewItems[1];
detailsItem.animator.collapsed = !detailsItem.isCollapsed;
}
#pragma mark - table view controller delegate
- (void)tableViewDidSelectItemsAtIndexes:(NSIndexSet *)indexes
{
NSUInteger count = indexes.count;
if (count != 1)
{
self.multiSelectionViewController.count = count;
[self switchToViewController:self.multiSelectionViewController];
}
else
{
NSArray<id<HBQueueItem>> *items = [self.queue.items objectsAtIndexes:indexes];
self.infoViewController.item = items.firstObject;
[self switchToViewController:self.infoViewController];
}
}
- (void)switchToViewController:(NSViewController *)viewController
{
NSViewController *firstChild = self.containerViewController.childViewControllers.firstObject;
if (firstChild != viewController)
{
if (firstChild)
{
[firstChild.view removeFromSuperviewWithoutNeedingDisplay];
[firstChild removeFromParentViewController];
}
[self.containerViewController addChildViewController:viewController];
viewController.view.frame = self.containerViewController.view.bounds;
viewController.view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
[self.containerViewController.view addSubview:viewController.view];
}
}
- (void)tableViewEditItem:(id<HBQueueItem>)item
{
if ([item isKindOfClass:[HBQueueJobItem class]])
{
[self editQueueItem:item];
}
}
- (void)tableViewRemoveItemsAtIndexes:(nonnull NSIndexSet *)indexes
{
[self removeQueueItemsAtIndexes:indexes];
}
- (void)tableViewResetItemsAtIndexes:(nonnull NSIndexSet *)indexes {
[self resetQueueItemsAtIndexes:indexes];
}
- (void)detailsViewEditItem:(nonnull id<HBQueueItem>)item
{
if ([item isKindOfClass:[HBQueueJobItem class]])
{
[self editQueueItem:item];
}
}
- (void)detailsViewResetItem:(nonnull id<HBQueueItem>)item
{
if ([item isKindOfClass:[HBQueueJobItem class]])
{
NSUInteger index = [self.queue.items indexOfObject:item];
[self resetQueueItemsAtIndexes:[NSIndexSet indexSetWithIndex:index]];
}
}
- (IBAction)resetAll:(id)sender
{
[self.queue resetAllItems];
}
- (IBAction)resetFailed:(id)sender
{
[self.queue resetFailedItems];
}
- (IBAction)removeAll:(id)sender
{
[self.queue removeNotWorkingItems];
}
- (IBAction)removeCompleted:(id)sender
{
[self.queue removeCompletedItems];
}
@end
@implementation HBQueueController (TouchBar)
@dynamic touchBar;
static NSTouchBarItemIdentifier HBTouchBarMain = @"fr.handbrake.queueWindowTouchBar";
static NSTouchBarItemIdentifier HBTouchBarRip = @"fr.handbrake.rip";
static NSTouchBarItemIdentifier HBTouchBarPause = @"fr.handbrake.pause";
- (NSTouchBar *)makeTouchBar
{
NSTouchBar *bar = [[NSTouchBar alloc] init];
bar.delegate = self;
bar.defaultItemIdentifiers = @[HBTouchBarRip, HBTouchBarPause];
bar.customizationIdentifier = HBTouchBarMain;
bar.customizationAllowedItemIdentifiers = @[HBTouchBarRip, HBTouchBarPause];
return bar;
}
- (IBAction)_touchBar_toggleStartCancel:(id)sender
{
[self toggleStartCancel:self];
}
- (NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
{
if ([identifier isEqualTo:HBTouchBarRip])
{
NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
item.customizationLabel = NSLocalizedString(@"Start/Stop Encoding", @"Touch bar");
NSButton *button = [NSButton buttonWithImage:[NSImage imageNamed:NSImageNameTouchBarPlayTemplate] target:self action:@selector(_touchBar_toggleStartCancel:)];
item.view = button;
return item;
}
else if ([identifier isEqualTo:HBTouchBarPause])
{
NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
item.customizationLabel = NSLocalizedString(@"Pause/Resume Encoding", @"Touch bar");
NSButton *button = [NSButton buttonWithImage:[NSImage imageNamed:NSImageNameTouchBarPauseTemplate] target:self action:@selector(togglePauseResume:)];
item.view = button;
return item;
}
return nil;
}
- (void)_touchBar_updateButtonsState
{
NSButton *ripButton = (NSButton *)[[self.touchBar itemForIdentifier:HBTouchBarRip] view];
NSButton *pauseButton = (NSButton *)[[self.touchBar itemForIdentifier:HBTouchBarPause] view];
if (self.queue.isEncoding)
{
ripButton.image = [NSImage imageNamed:NSImageNameTouchBarRecordStopTemplate];
}
else
{
ripButton.image = [NSImage imageNamed:NSImageNameTouchBarPlayTemplate];
}
if (self.queue.canResume)
{
pauseButton.image = [NSImage imageNamed:NSImageNameTouchBarPlayTemplate];
}
else
{
pauseButton.image = [NSImage imageNamed:NSImageNameTouchBarPauseTemplate];
}
}
- (void)_touchBar_validateUserInterfaceItems
{
for (NSTouchBarItemIdentifier identifier in self.touchBar.itemIdentifiers) {
NSTouchBarItem *item = [self.touchBar itemForIdentifier:identifier];
NSView *view = item.view;
if ([view isKindOfClass:[NSButton class]]) {
NSButton *button = (NSButton *)view;
BOOL enabled = [self validateUserIterfaceItemForAction:button.action];
button.enabled = enabled;
}
}
}
@end
|