/
Plugin.m
executable file
·1943 lines (1564 loc) · 66.5 KB
/
Plugin.m
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
The MIT License
Copyright (c) 2008-2009 ClickToFlash Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#import "Plugin.h"
#import "CTFUserDefaultsController.h"
#import "CTFPreferencesDictionary.h"
#import "MATrackingArea.h"
#import "CTFMenubarMenuController.h"
#import "CTFsIFRSupport.h"
#import "CTFUtilities.h"
#import "CTFWhitelist.h"
#import "NSBezierPath-RoundedRectangle.h"
#import "CTFGradient.h"
#import "SparkleManager.h"
#define LOGGING_ENABLED 0
#ifndef NSAppKitVersionNumber10_5
#define NSAppKitVersionNumber10_5 949
#endif
// MIME types
static NSString *sFlashOldMIMEType = @"application/x-shockwave-flash";
static NSString *sFlashNewMIMEType = @"application/futuresplash";
// CTFUserDefaultsController keys
static NSString *sUseYouTubeH264DefaultsKey = @"useYouTubeH264";
static NSString *sUseYouTubeHDH264DefaultsKey = @"useYouTubeHDH264";
static NSString *sAutoLoadInvisibleFlashViewsKey = @"autoLoadInvisibleViews";
static NSString *sPluginEnabled = @"pluginEnabled";
static NSString *sApplicationWhitelist = @"applicationWhitelist";
static NSString *sDrawGearImageOnlyOnMouseOverHiddenPref = @"drawGearImageOnlyOnMouseOver";
static NSString *sDisableVideoElement = @"disableVideoElement";
static NSString *sYouTubeAutoPlay = @"enableYouTubeAutoPlay";
// Info.plist key for app developers
static NSString *sCTFOptOutKey = @"ClickToFlashOptOut";
BOOL usingMATrackingArea = NO;
@interface CTFClickToFlashPlugin (Internal)
- (void) _convertTypesForFlashContainer;
- (void) _convertTypesForFlashContainerAfterDelay;
- (void) _convertToMP4ContainerUsingHD: (NSNumber*) useHD;
- (void) _convertToMP4ContainerAfterDelayUsingHD: (NSNumber*) useHD;
- (void) _prepareForConversion;
- (void) _revertToOriginalOpacityAttributes;
- (void) _drawBackground;
- (BOOL) _isOptionPressed;
- (BOOL) _isCommandPressed;
- (void) _checkMouseLocation;
- (void) _addTrackingAreaForCTF;
- (void) _removeTrackingAreaForCTF;
- (NSMenuItem*) _addContextualMenuItemWithTitle: (NSString*) title action: (SEL) selector;
- (void) _loadContent: (NSNotification*) notification;
- (void) _loadContentForWindow: (NSNotification*) notification;
- (NSDictionary*) _flashVarDictionary: (NSString*) flashvarString;
- (NSDictionary*) _flashVarDictionaryFromYouTubePageHTML: (NSString*) youTubePageHTML;
- (void)_didRetrieveEmbeddedPlayerFlashVars:(NSDictionary *)flashVars;
- (void)_getEmbeddedPlayerFlashVarsAndCheckForVariantsWithVideoId:(NSString *)videoId;
- (NSString*) flashvarWithName: (NSString*) argName;
- (void) _checkForH264VideoVariants;
- (BOOL) _hasH264Version;
- (BOOL) _useH264Version;
- (BOOL) _hasHDH264Version;
- (BOOL) _useHDH264Version;
- (NSString *)launchedAppBundleIdentifier;
@end
#pragma mark -
#pragma mark Whitelist Utility Functions
@implementation CTFClickToFlashPlugin
#pragma mark -
#pragma mark Class Methods
+ (NSView *)plugInViewWithArguments:(NSDictionary *)arguments
{
return [[[self alloc] initWithArguments:arguments] autorelease];
}
#pragma mark -
#pragma mark Initialization and Superclass Overrides
- (id) initWithArguments:(NSDictionary *)arguments
{
self = [super init];
if (self) {
_hasH264Version = NO;
_hasHDH264Version = NO;
_contextMenuIsVisible = NO;
_embeddedYouTubeView = NO;
_isSIFR = NO;
_youTubeAutoPlay = NO;
_delayingTimer = nil;
defaultWhitelist = [NSArray arrayWithObjects: @"com.apple.frontrow",
@"com.apple.dashboard.client",
@"com.apple.ScreenSaver.Engine",
@"com.hulu.HuluDesktop",
@"com.riverfold.WiiTransfer",
@"com.bitcartel.pandorajam",
@"com.adobe.flexbuilder",
@"com.Zattoo.prefs",
@"fr.understudy.HuluPlayer",
@"com.apple.iWeb",
@"com.realmacsoftware.rapidweaverpro",
@"com.realmacsoftware.littlesnapper",
nil];
if (![[CTFUserDefaultsController standardUserDefaults] objectForKey:sAutoLoadInvisibleFlashViewsKey]) {
// Default to auto-loading invisible flash views.
[[CTFUserDefaultsController standardUserDefaults] setBool:YES forKey:sAutoLoadInvisibleFlashViewsKey];
}
if (![[CTFUserDefaultsController standardUserDefaults] objectForKey:sPluginEnabled]) {
// Default to enable the plugin
[[CTFUserDefaultsController standardUserDefaults] setBool:YES forKey:sPluginEnabled];
}
[self setLaunchedAppBundleIdentifier:[self launchedAppBundleIdentifier]];
[self setWebView:[[[arguments objectForKey:WebPlugInContainerKey] webFrame] webView]];
[self setContainer:[arguments objectForKey:WebPlugInContainingElementKey]];
[self _migrateWhitelist];
[self _migratePrefsToExternalFile];
[self _uniquePrefsFileWhitelist];
[self _addApplicationWhitelistArrayToPrefsFile];
// Get URL
NSURL *base = [arguments objectForKey:WebPlugInBaseURLKey];
[self setBaseURL:[base absoluteString]];
[self setHost:[base host]];
[self setAttributes:[arguments objectForKey:WebPlugInAttributesKey]];
NSString *srcAttribute = [[self attributes] objectForKey:@"src"];
if (srcAttribute) {
[self setSrc:srcAttribute];
} else {
NSString *dataAttribute = [[self attributes] objectForKey:@"data"];
if (dataAttribute) [self setSrc:dataAttribute];
}
// set tooltip
if ([self src]) {
int srcLength = [[self src] length];
if ([[self src] length] > 200) {
NSString *srcStart = [[self src] substringToIndex:150];
NSString *srcEnd = [[self src] substringFromIndex:(srcLength-50)];
NSString *shortenedSrc = [NSString stringWithFormat:@"%@…%@",srcStart,srcEnd];
[self setToolTip:shortenedSrc];
} else {
[self setToolTip:[self src]];
}
}
// Read in flashvars (needed to determine YouTube videos)
NSString* flashvars = [[self attributes] objectForKey: @"flashvars" ];
if( flashvars != nil )
_flashVars = [ [ self _flashVarDictionary: flashvars ] retain ];
// check whether it's from YouTube and get the video_id
_fromYouTube = [[self host] isEqualToString:@"www.youtube.com"]
|| [[self host] isEqualToString:@"www.youtube-nocookie.com"]
|| ( flashvars != nil && [flashvars rangeOfString: @"www.youtube.com"].location != NSNotFound )
|| ( flashvars != nil && [flashvars rangeOfString: @"www.youtube-nocookie.com"].location != NSNotFound )
|| ([self src] != nil && [[self src] rangeOfString: @"youtube.com"].location != NSNotFound )
|| ([self src] != nil && [[self src] rangeOfString: @"youtube-nocookie.com"].location != NSNotFound );
if (_fromYouTube) {
// Check wether autoplay is wanted
if ([[CTFUserDefaultsController standardUserDefaults] objectForKey:sYouTubeAutoPlay]) {
if ([[self host] isEqualToString:@"www.youtube.com"]
|| [[self host] isEqualToString:@"www.youtube-nocookie.com"]) {
_youTubeAutoPlay = YES;
} else {
_youTubeAutoPlay = [[[self _flashVarDictionary:[self src]] objectForKey:@"autoplay"] isEqualToString:@"1"];
}
} else {
_youTubeAutoPlay = NO;
}
NSString *videoId = [ self flashvarWithName: @"video_id" ];
if (videoId != nil) {
[self setVideoId:videoId];
// this retrieves new data from the internets, but the NSURLConnection
// methods already spawn separate threads for the data retrieval,
// so no need to spawn a separate thread
[self _checkForH264VideoVariants];
} else {
// it's an embedded YouTube flash view; scrub the URL to
// determine the video_id, then get the source of the YouTube
// page to get the Flash vars
_embeddedYouTubeView = YES;
NSString *videoIdFromURL = nil;
NSScanner *URLScanner = [[NSScanner alloc] initWithString:[self src]];
[URLScanner scanUpToString:@"youtube.com/v/" intoString:nil];
if ([URLScanner scanString:@"youtube.com/v/" intoString:nil]) {
// URL is in required format, next characters are the id
[URLScanner scanUpToString:@"&" intoString:&videoIdFromURL];
if (videoIdFromURL) [self setVideoId:videoIdFromURL];
} else {
[URLScanner setScanLocation:0];
[URLScanner scanUpToString:@"youtube-nocookie.com/v/" intoString:nil];
if ([URLScanner scanString:@"youtube-nocookie.com/v/" intoString:nil]) {
[URLScanner scanUpToString:@"&" intoString:&videoIdFromURL];
if (videoIdFromURL) [self setVideoId:videoIdFromURL];
}
}
[URLScanner release];
if (videoIdFromURL) {
// this block of code introduces a situation where we have to download
// additional data from the internets, so we want to spin this off
// to another thread to prevent blocking of the Safari user interface
// this method is a stub for calling the real method on a different thread
[self _getEmbeddedPlayerFlashVarsAndCheckForVariantsWithVideoId:videoIdFromURL];
}
}
}
_fromFlickr = [[self host] rangeOfString:@"flickr.com"].location != NSNotFound;
#if LOGGING_ENABLED
NSLog( @"arguments = %@", arguments );
NSLog( @"flashvars = %@", _flashVars );
#endif
// check whether plugin is disabled, load all content as normal if so
CTFUserDefaultsController *standardUserDefaults = [CTFUserDefaultsController standardUserDefaults];
BOOL pluginEnabled = [standardUserDefaults boolForKey:sPluginEnabled ];
NSString *hostAppBundleID = [[NSBundle mainBundle] bundleIdentifier];
BOOL hostAppIsInDefaultWhitelist = [defaultWhitelist containsObject:hostAppBundleID];
BOOL hostAppIsInUserWhitelist = [[standardUserDefaults arrayForKey:sApplicationWhitelist] containsObject:hostAppBundleID];
BOOL hostAppWhitelistedInInfoPlist = NO;
if ([[[NSBundle mainBundle] infoDictionary] objectForKey:sCTFOptOutKey]) hostAppWhitelistedInInfoPlist = YES;
if ( (! pluginEnabled) || (hostAppIsInDefaultWhitelist || hostAppIsInUserWhitelist || hostAppWhitelistedInInfoPlist) ) {
_isLoadingFromWhitelist = YES;
[self _convertTypesForContainer];
return self;
}
// Plugin is enabled and the host is not white-listed. Kick off Sparkle.
NSString *pathToRelaunch = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:[self launchedAppBundleIdentifier]];
[[SparkleManager sharedManager] setPathToRelaunch:pathToRelaunch];
[[SparkleManager sharedManager] startAutomaticallyCheckingForUpdates];
// Set up main menus
[ CTFMenubarMenuController sharedController ]; // trigger the menu items to be added
// Check for sIFR
if ([self _isSIFRText: arguments]) {
_isSIFR = YES;
if ([self _shouldAutoLoadSIFR]) {
_isLoadingFromWhitelist = YES;
[self _convertTypesForContainer];
return self;
}
else if ([self _shouldDeSIFR]) {
_isLoadingFromWhitelist = YES;
[self performSelector:@selector(_disableSIFR) withObject:nil afterDelay:0];
return self;
}
}
if ( [ [ CTFUserDefaultsController standardUserDefaults ] boolForKey: sAutoLoadInvisibleFlashViewsKey ]
&& [ self isConsideredInvisible ] ) {
// auto-loading is on and this view meets the size constraints
_isLoadingFromWhitelist = YES;
[self _convertTypesForContainer];
return self;
}
BOOL loadFromWhiteList = [self _isHostWhitelisted];
// Check the SWF src URL itself against the whitelist (allows embbeded videos from whitelisted sites to play, e.g. YouTube)
if( !loadFromWhiteList )
{
if (srcAttribute) {
NSURL* swfSrc = [NSURL URLWithString:srcAttribute];
if( [self _isWhiteListedForHostString:[swfSrc host] ] )
{
loadFromWhiteList = YES;
}
}
}
// Handle if this is loading from whitelist
if(loadFromWhiteList && ![self _isOptionPressed]) {
_isLoadingFromWhitelist = YES;
if (_fromYouTube) {
// we do this because checking for H.264 variants is handled
// on another thread, so the results of that check may not have
// been returned yet; if the user has this site on a whitelist
// and the results haven't been returned, then the *Flash* will
// load (ewwwwwww!) instead of the H.264, even if the user's
// preferences are for the H.264
// the _checkForH264VideoVariants method will manually fire
// this timer if it finishes before the 3 seconds are up
_delayingTimer = [NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:@selector(_convertTypesForContainer)
userInfo:nil
repeats:NO];
} else {
[self _convertTypesForContainer];
}
return self;
}
// send a notification so that all flash objects can be tracked
// we only want to track it if we don't auto-load it
[[CTFMenubarMenuController sharedController] registerView: self];
// Observe various things:
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
// Observe for additions to the whitelist:
[self _addWhitelistObserver];
[center addObserver: self
selector: @selector( _loadContent: )
name: kCTFLoadAllFlashViews
object: nil ];
[center addObserver: self
selector: @selector( _loadContentForWindow: )
name: kCTFLoadFlashViewsForWindow
object: nil ];
[center addObserver: self
selector: @selector( _loadInvisibleContentForWindow: )
name: kCTFLoadInvisibleFlashViewsForWindow
object: nil ];
// if a Flash view has style attributes that make it transparent, the CtF
// view will similarly be transparent; we want to make it temporarily
// visible, and then restore the original attributes so that we don't
// have any display issues once the Flash view is loaded
// Should we apply this to the parent?
// That seems to be problematic.
// well, in my experience w/CSS, to get a layout to work a lot of the
// time, you need to create parent objects and apply styles to parents,
// so it seemed reasonable to check both self and parent for potential
// problems with opacity
NSMutableDictionary *originalOpacityDict = [NSMutableDictionary dictionary];
NSString *opacityResetString = @"; opacity: 1.000 !important; -moz-opacity: 1 !important; filter: alpha(opacity=1) !important;";
NSString *originalWmode = [[self container] getAttribute:@"wmode"];
NSString *originalStyle = [[self container] getAttribute:@"style"];
NSString *originalParentWmode = [(DOMElement *)[[self container] parentNode] getAttribute:@"wmode"];
NSString *originalParentStyle = [(DOMElement *)[[self container] parentNode] getAttribute:@"style"];
if (originalWmode != nil && [originalWmode length] > 0u && ![originalWmode isEqualToString:@"opaque"]) {
[originalOpacityDict setObject:originalWmode forKey:@"self-wmode"];
[[self container] setAttribute:@"wmode" value:@"opaque"];
}
if (originalStyle != nil && [originalStyle length] > 0u && ![originalStyle hasSuffix:opacityResetString]) {
[originalOpacityDict setObject:originalStyle forKey:@"self-style"];
[originalOpacityDict setObject:[originalStyle stringByAppendingString:opacityResetString] forKey:@"modified-self-style"];
[[self container] setAttribute:@"style" value:[originalStyle stringByAppendingString:opacityResetString]];
}
if (originalParentWmode != nil && [originalParentWmode length] > 0u && ![originalParentWmode isEqualToString:@"opaque"]) {
[originalOpacityDict setObject:originalParentWmode forKey:@"parent-wmode"];
[(DOMElement *)[[self container] parentNode] setAttribute:@"wmode" value:@"opaque"];
}
if (originalParentStyle != nil && [originalParentStyle length] > 0u && ![originalParentStyle hasSuffix:opacityResetString]) {
[originalOpacityDict setObject:originalParentStyle forKey:@"parent-style"];
[originalOpacityDict setObject:[originalParentStyle stringByAppendingString:opacityResetString] forKey:@"modified-parent-style"];
[(DOMElement *)[[self container] parentNode] setAttribute:@"style" value:[originalParentStyle stringByAppendingString:opacityResetString]];
}
[self setOriginalOpacityAttributes:originalOpacityDict];
[self _checkMouseLocation];
[self _addTrackingAreaForCTF];
}
return self;
}
- (void)webPlugInDestroy
{
[self _removeTrackingAreaForCTF];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self _abortAlert]; // to be on the safe side
// notify that this ClickToFlash plugin is going away
[[CTFMenubarMenuController sharedController] unregisterView:self];
[self setContainer:nil];
[self setHost:nil];
[self setWebView:nil];
[self setBaseURL:nil];
[self setAttributes:nil];
[self setOriginalOpacityAttributes:nil];
[_flashVars release];
_flashVars = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
for (int i = 0; i < 2; ++i) {
[connections[i] release];
connections[i] = nil;
}
}
- (void) dealloc
{
// Just in case...
[self webPlugInDestroy];
#if LOGGING_ENABLED
NSLog(@"ClickToFlash:\tdealloc");
#endif
[super dealloc];
}
- (void) _migratePrefsToExternalFile
{
NSArray *parasiticDefaultsNameArray = [NSArray arrayWithObjects:@"ClickToFlash_pluginEnabled",
@"ClickToFlash_useYouTubeH264",
@"ClickToFlash_autoLoadInvisibleViews",
@"ClickToFlash_sifrMode",
@"ClickToFlash_checkForUpdatesOnFirstLoad",
@"ClickToFlash_siteInfo",
nil];
NSArray *externalDefaultsNameArray = [NSArray arrayWithObjects:@"pluginEnabled",
@"useYouTubeH264",
@"autoLoadInvisibleViews",
@"sifrMode",
@"checkForUpdatesOnFirstLoad",
@"siteInfo",
nil];
NSMutableDictionary *externalFileDefaults = [[CTFUserDefaultsController standardUserDefaults] dictionaryRepresentation];
[[NSUserDefaults standardUserDefaults] addSuiteNamed:@"com.github.rentzsch.clicktoflash"];
unsigned int i;
for (i = 0; i < [parasiticDefaultsNameArray count]; i++) {
NSString *currentParasiticDefault = [parasiticDefaultsNameArray objectAtIndex:i];
id prefValue = [[NSUserDefaults standardUserDefaults] objectForKey:currentParasiticDefault];
if (prefValue) {
NSString *externalPrefDefaultName = [externalDefaultsNameArray objectAtIndex:i];
id existingExternalPref = [[CTFUserDefaultsController standardUserDefaults] objectForKey:externalPrefDefaultName];
if (! existingExternalPref) {
// don't overwrite existing external preferences
[externalFileDefaults setObject:prefValue forKey:externalPrefDefaultName];
} else {
if ([currentParasiticDefault isEqualToString:@"ClickToFlash_siteInfo"]) {
// merge the arrays of whitelisted sites, in case they're not identical
NSMutableArray *combinedWhitelist = [NSMutableArray arrayWithArray:prefValue];
[combinedWhitelist addObjectsFromArray:existingExternalPref];
[externalFileDefaults setObject:combinedWhitelist forKey:externalPrefDefaultName];
// because people named Kevin Ballard messed up their preferences file and somehow
// managed to retain ClickToFlash_siteInfo in their com.github plist file
[externalFileDefaults removeObjectForKey:currentParasiticDefault];
}
}
// eliminate the parasitic default, regardless of whether we transferred them or not
[[NSUserDefaults standardUserDefaults] removeObjectForKey:currentParasiticDefault];
}
}
[[NSUserDefaults standardUserDefaults] removeSuiteNamed:@"com.github.rentzsch.clicktoflash"];
}
- (void) _uniquePrefsFileWhitelist
{
NSArray *siteInfoArray = [[CTFUserDefaultsController standardUserDefaults] arrayForKey:@"siteInfo"];
NSSet *siteInfoSet = [NSSet setWithArray:siteInfoArray];
[[CTFUserDefaultsController standardUserDefaults] setValue:[siteInfoSet allObjects] forKeyPath:@"values.siteInfo"];
}
- (void) _addApplicationWhitelistArrayToPrefsFile
{
CTFUserDefaultsController *standardUserDefaults = [CTFUserDefaultsController standardUserDefaults];
NSArray *applicationWhitelist = [standardUserDefaults arrayForKey:sApplicationWhitelist];
if (! applicationWhitelist) {
// add an empty array to the plist file so people know exactly where to
// whitelist apps
[standardUserDefaults setObject:[NSArray array] forKey:sApplicationWhitelist];
}
}
- (void) drawRect:(NSRect)rect
{
if(!_isLoadingFromWhitelist)
[self _drawBackground];
}
- (BOOL) _gearVisible
{
NSRect bounds = [ self bounds ];
return NSWidth( bounds ) > 32 && NSHeight( bounds ) > 32;
}
- (BOOL) mouseEventIsWithinGearIconBorders:(NSEvent *)event
{
float margin = 5.0;
float gearImageHeight = 16.0;
float gearImageWidth = 16.0;
BOOL xCoordWithinGearImage = NO;
BOOL yCoordWithinGearImage = NO;
// if the view is 32 pixels or smaller in either direction,
// the gear image is not drawn, so we shouldn't pop-up the contextual
// menu on a single-click either
if ( [ self _gearVisible ] ) {
float viewHeight = NSHeight( [ self bounds ] );
NSPoint mouseLocation = [event locationInWindow];
NSPoint localMouseLocation = [self convertPoint:mouseLocation fromView:nil];
xCoordWithinGearImage = ( (localMouseLocation.x >= (0 + margin)) &&
(localMouseLocation.x <= (0 + margin + gearImageWidth)) );
yCoordWithinGearImage = ( (localMouseLocation.y >= (viewHeight - margin - gearImageHeight)) &&
(localMouseLocation.y <= (viewHeight - margin)) );
}
return (xCoordWithinGearImage && yCoordWithinGearImage);
}
- (void) mouseDown:(NSEvent *)event
{
if ([self mouseEventIsWithinGearIconBorders:event]) {
_contextMenuIsVisible = YES;
[NSMenu popUpContextMenu:[self menuForEvent:event] withEvent:event forView:self];
} else {
mouseIsDown = YES;
mouseInside = YES;
[self setNeedsDisplay:YES];
// Track the mouse so that we can undo our pressed-in look if the user drags the mouse outside the view, and reinstate it if the user drags it back in.
//[self _addTrackingAreaForCTF];
// Now that we track the mouse for mouse-over when the mouse is up
// for drawing the gear only on mouse-over, we don't need to add it here.
}
}
- (void) mouseEntered:(NSEvent *)event
{
mouseInside = YES;
[self setNeedsDisplay:YES];
}
- (void) mouseExited:(NSEvent *)event
{
mouseInside = NO;
[self setNeedsDisplay:YES];
}
- (void) mouseUp:(NSEvent *)event
{
mouseIsDown = NO;
// Display immediately because we don't want to end up drawing after we've swapped in the Flash movie.
[self display];
// We're done tracking.
//[self _removeTrackingAreaForCTF];
// Now that we track the mouse for mouse-over when the mouse is up
// for drawing the gear only on mouse-over, we don't remove it here.
if (mouseInside && (! _contextMenuIsVisible) ) {
if ([self _isCommandPressed]) {
if ([self _isOptionPressed]) {
[self removeFlash:self];
} else {
[self hideFlash:self];
}
} else if ([self _isOptionPressed] && ![self _isHostWhitelisted]) {
[self _askToAddCurrentSiteToWhitelist];
} else {
[self _convertTypesForContainer];
}
} else {
_contextMenuIsVisible = NO;
}
}
- (BOOL) _isOptionPressed
{
BOOL isOptionPressed = (([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0);
return isOptionPressed;
}
- (BOOL) _isCommandPressed
{
BOOL isCommandPressed = (([[NSApp currentEvent] modifierFlags] & NSCommandKeyMask) != 0);
return isCommandPressed;
}
- (BOOL) isConsideredInvisible
{
int height = (int)([[self webView] frame].size.height);
int width = (int)([[self webView] frame].size.width);
if ( (height <= maxInvisibleDimension) && (width <= maxInvisibleDimension) )
{
return YES;
}
NSDictionary *attributes = [self attributes];
if ( attributes != nil )
{
NSString *heightObject = [attributes objectForKey:@"height"];
NSString *widthObject = [attributes objectForKey:@"width"];
if ( heightObject != nil && widthObject != nil )
{
height = [heightObject intValue];
width = [widthObject intValue];
if ( (height <= maxInvisibleDimension) && (width <= maxInvisibleDimension) )
{
return YES;
}
}
}
return NO;
}
#pragma mark -
#pragma mark Contextual menu
- (NSMenuItem *) _addContextualMenuItemWithTitle: (NSString*) title action: (SEL) selector {
NSMenuItem * menuItem = [[[NSMenuItem alloc] initWithTitle: title action:selector keyEquivalent:@""] autorelease];
[menuItem setTarget: self];
[[self menu] addItem: menuItem];
return menuItem;
}
/*
Build contextual menu
*/
- (NSMenu*) menuForEvent: (NSEvent*) event
{
NSMenuItem * menuItem;
[self setMenu: [[[NSMenu alloc] initWithTitle:CtFLocalizedString( @"ClickTo Flash Contextual menu", @"Title of Contextual Menu")] autorelease]];
[self _addContextualMenuItemWithTitle:CtFLocalizedString( @"Load Flash", @"Contextual Menu Item: Load Flash" )
action: @selector( loadFlash: )];
if (_fromYouTube && [self _hasH264Version]) {
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Load H.264", @"Load H.264 contextual menu item" )
action: @selector( loadH264: )];
if ([self _hasHDH264Version]) {
if ([self _useHDH264Version]) {
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Load H.264 SD Version", @"Load Smaller Version contextual menu item (alternate for the standard Load H.264 item when the default uses the 'HD' version)" )
action: @selector( loadH264SD: ) ];
}
else {
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Load H.264 HD Version", @"Load Larger Version contextual menu item (alternate for the standard item when the default uses the non-'HD' version)" )
action: @selector( loadH264HD: ) ];
}
[menuItem setAlternate:YES];
[menuItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
}
}
if ([[CTFMenubarMenuController sharedController] multipleFlashViewsExistForWindow:[self window]]) {
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Load All on this Page", @"Load All on this Page contextual menu item" )
action: @selector( loadAllOnPage: )];
}
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Hide Flash", @"Hide Flash contextual menu item (sets display:none)")
action: @selector( hideFlash:)];
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Remove Flash", @"Remove Flash contextual menu item (sets visibility: hidden)")
action: @selector( removeFlash: )];
[menuItem setAlternate:YES];
[menuItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
[[self menu] addItem: [NSMenuItem separatorItem]];
if (_fromYouTube) {
if (_embeddedYouTubeView) {
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Load YouTube.com page for this video", @"Load YouTube page contextual menu item" )
action: @selector( loadYouTubePage: )];
}
if ([self _hasH264Version]) {
// menu item and alternate for full screen viewing in QuickTime Player
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Play Fullscreen in QuickTime Player", @"Open Fullscreen in QT Player contextual menu item" )
action: @selector( openFullscreenInQTPlayer: )];
if ([self _hasHDH264Version]) {
if ([self _useHDH264Version]) {
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Play Smaller Version Fullscreen in QuickTime Player", @"Open Smaller Version Fullscreen in QT Player contextual menu item (alternate for the standard item when the default uses the 'HD' version)" )
action: @selector( openFullscreenInQTPlayerSD: ) ];
}
else {
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Play Larger Version Fullscreen in QuickTime Player", @"Open Larger Version Fullscreen in QT Player contextual menu item (alternate for the standard item when the default uses the non-'HD' version)" )
action: @selector( openFullscreenInQTPlayerHD: ) ];
}
[menuItem setAlternate:YES];
[menuItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
}
// menu item and alternate for downloading movie file
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Download H.264", @"Download H.264 menu item" )
action: @selector( downloadH264: )];
if ([self _hasHDH264Version]) {
if ([self _useHDH264Version]) {
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Download SD H.264", @"Download small size H.264 menu item (alternate for the standard item when the default uses the 'HD' version)" )
action: @selector( downloadH264SD: ) ];
}
else {
menuItem = [self _addContextualMenuItemWithTitle: CtFLocalizedString( @"Download HD H.264", @"Download large size H.264 menu item (alternate for the standard item when the default uses the non-'HD' version)" )
action: @selector( downloadH264HD: ) ];
}
[menuItem setAlternate:YES];
[menuItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
}
}
if (_embeddedYouTubeView || [self _hasH264Version]) {
[[self menu] addItem: [NSMenuItem separatorItem]];
}
}
if ([self host] && ![self _isHostWhitelisted]) {
[self _addContextualMenuItemWithTitle: [NSString stringWithFormat:CtFLocalizedString( @"Add %@ to Whitelist", @"Add <sitename> to Whitelist contextual menu item" ), [self host]]
action: @selector( addToWhitelist: )];
[[self menu] addItem: [NSMenuItem separatorItem]];
}
[self _addContextualMenuItemWithTitle: CtFLocalizedString( @"ClickToFlash Preferences...", @"Preferences contextual menu item" )
action: @selector( editWhitelist: )];
return [self menu];
}
- (BOOL) validateMenuItem: (NSMenuItem *)menuItem
{
return YES;
}
#pragma mark -
#pragma mark Loading
- (IBAction)removeFlash: (id) sender;
{
DOMCSSStyleDeclaration *style = [[self container] style];
[style setProperty:@"display" value:@"none" priority:@"important"];
}
- (IBAction)hideFlash: (id) sender;
{
DOMCSSStyleDeclaration *style = [[self container] style];
[style setProperty:@"visibility" value:@"hidden" priority:@"important"];
}
- (IBAction)loadFlash:(id)sender;
{
[self _convertTypesForFlashContainer];
}
- (IBAction)loadH264:(id)sender;
{
[self _convertToMP4ContainerUsingHD:nil];
}
- (IBAction) loadH264SD:(id)sender;
{
[self _convertToMP4ContainerUsingHD:[NSNumber numberWithBool:NO]];
}
- (IBAction) loadH264HD:(id)sender;
{
[self _convertToMP4ContainerUsingHD:[NSNumber numberWithBool:YES]];
}
- (IBAction)loadAllOnPage:(id)sender
{
[[CTFMenubarMenuController sharedController] loadFlashForWindow: [self window]];
}
- (void) _loadContent: (NSNotification*) notification
{
[self _convertTypesForContainer];
}
- (void) _loadContentForWindow: (NSNotification*) notification
{
if( [ notification object ] == [ self window ] )
[ self _convertTypesForContainer ];
}
- (void) _loadInvisibleContentForWindow: (NSNotification*) notification
{
if( [ notification object ] == [ self window ] && [ self isConsideredInvisible ] ) {
[ self _convertTypesForContainer ];
}
}
#pragma mark -
#pragma mark Drawing
- (NSString*) badgeLabelText
{
if( [ self _useHDH264Version ] ) {
return CtFLocalizedString( @"HD H.264", @"HD H.264 badge text" );
} else if( [ self _useH264Version ] ) {
if (_receivedAllResponses) {
return CtFLocalizedString( @"H.264", @"H.264 badge text" );
} else {
return CtFLocalizedString( @"H.264…", @"H.264 badge waiting text" );
}
} else if( _fromYouTube && _videoId) {
// we check the video ID too because if it's a flash ad on YouTube.com,
// we don't want to identify it as an actual YouTube video -- but if
// the flash object actually has a video ID parameter, it means its
// a bona fide YouTube video
if (_receivedAllResponses) {
return CtFLocalizedString( @"YouTube", @"YouTube badge text" );
} else {
return CtFLocalizedString( @"YouTube…", @"YouTube badge waiting text" );
}
} else if( _isSIFR ) {
return CtFLocalizedString( @"sIFR Flash", @"sIFR Flash badge text" );
} else {
return CtFLocalizedString( @"Flash", @"Flash badge text" );
}
}
- (void) _drawBadgeWithPressed: (BOOL) pressed
{
// What and how are we going to draw?
const float kFrameXInset = 10;
const float kFrameYInset = 4;
const float kMinMargin = 11;
const float kMinHeight = 6;
NSString* str = [ self badgeLabelText ];
NSShadow *superAwesomeShadow = [[NSShadow alloc] init];
[superAwesomeShadow setShadowOffset:NSMakeSize(2.0, -2.0)];
[superAwesomeShadow setShadowColor:[NSColor whiteColor]];
[superAwesomeShadow autorelease];
NSDictionary* attrs = [ NSDictionary dictionaryWithObjectsAndKeys:
[ NSFont boldSystemFontOfSize: 20 ], NSFontAttributeName,
[ NSNumber numberWithInt: -1 ], NSKernAttributeName,
[ NSColor blackColor ], NSForegroundColorAttributeName,
superAwesomeShadow, NSShadowAttributeName,
nil ];
// Set up for drawing.
NSRect bounds = [ self bounds ];
// How large would this text be?
NSSize strSize = [ str sizeWithAttributes: attrs ];
float w = strSize.width + kFrameXInset * 2;
float h = strSize.height + kFrameYInset * 2;
// Compute a scale factor based on the view's size.
float maxW = NSWidth( bounds ) - kMinMargin;
// the 9/10 factor here is to account for the 60% vertical top-biasing
float maxH = _fromFlickr ? NSHeight( bounds )*9/10 - kMinMargin : NSHeight( bounds ) - kMinMargin;
float minW = kMinHeight * w / h;
BOOL rotate = NO;
if( maxW <= minW ) // too narrow in width, so rotate it
rotate = YES;
if( rotate ) { // swap the dimensions to scale into
float temp = maxW;
maxW = maxH;
maxH = temp;
}
if( maxH <= kMinHeight ) {
// Too short in height for full margin.
// Draw at the smallest size, with less margin,
// unless even that would get clipped off.
if( maxH + kMinMargin < kMinHeight )
return;
maxH = kMinHeight;
}
float scaleFactor = 1.0;
if( maxW < w )
scaleFactor = maxW / w;
if( maxH < h && maxH / h < scaleFactor )
scaleFactor = maxH / h;
// Apply the scale, and a transform so the result is centered in the view.
[ NSGraphicsContext saveGraphicsState ];
NSAffineTransform* xform = [ NSAffineTransform transform ];
// vertical top-bias by 60% here
if (_fromFlickr) {
[ xform translateXBy: NSWidth( bounds ) / 2 yBy: NSHeight( bounds ) / 10 * 6 ];
} else {
[ xform translateXBy: NSWidth( bounds ) / 2 yBy: NSHeight( bounds ) / 2 ];
}
[ xform scaleBy: scaleFactor ];
if( rotate )
[ xform rotateByDegrees: 90 ];
[ xform concat ];
CGContextRef context = [ [ NSGraphicsContext currentContext ] graphicsPort ];