public
Description: WebKit plug-in to prevent automatic loading of Adobe Flash content
Homepage: http://rentzsch.github.com/clicktoflash/
Clone URL: git://github.com/rentzsch/clicktoflash.git
clicktoflash / Plugin / Plugin.m
100755 1944 lines (1564 sloc) 68.096 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
/*
 
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 ];
    
    CGContextSetAlpha( context, pressed ? 0.45 : 0.30 );
    CGContextBeginTransparencyLayer( context, nil );
 
// Draw everything at full size, centered on the origin.
 
NSPoint loc = { -strSize.width / 2, -strSize.height / 2 };
NSRect borderRect = NSMakeRect( loc.x - kFrameXInset, loc.y - kFrameYInset, w, h );
 
    NSBezierPath* fillPath = bezierPathWithRoundedRectCornerRadius( borderRect, 4 );
    [ [ NSColor colorWithCalibratedWhite: 1.0 alpha: 0.45 ] set ];
    [ fillPath fill ];
    
    NSBezierPath* darkBorderPath = bezierPathWithRoundedRectCornerRadius( borderRect, 4 );
    [[NSColor blackColor] set];
    [ darkBorderPath setLineWidth: 3 ];
    [ darkBorderPath stroke ];
    
    NSBezierPath* lightBorderPath = bezierPathWithRoundedRectCornerRadius( NSInsetRect(borderRect, -2, -2), 6 );
    [ [ NSColor colorWithCalibratedWhite: 1.0 alpha: 0.45 ] set ];
    [ lightBorderPath setLineWidth: 2 ];
    [ lightBorderPath stroke ];
    
    [ str drawAtPoint: loc withAttributes: attrs ];
 
// Now restore the graphics state:
 
    CGContextEndTransparencyLayer( context );
    
    [ NSGraphicsContext restoreGraphicsState ];
}
 
- (void) _drawGearIcon
{
    // add the gear for the contextual menu, but only if the view is
    // greater than a certain size
        
    if ([self _gearVisible]) {
        NSRect bounds = [ self bounds ];
 
        float margin = 5.0;
        NSImage *gearImage = [NSImage imageNamed:@"NSActionTemplate"];
        // On systems older than 10.5 we need to supply our own image.
        if (gearImage == nil)
        {
            NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"NSActionTemplate" ofType:@"png"];
            gearImage = [[[NSImage alloc] initWithContentsOfFile:path] autorelease];
        }
 
        if( gearImage ) {
            CGContextRef context = [ [ NSGraphicsContext currentContext ] graphicsPort ];
            
            CGContextSetAlpha( context, 0.25 );
            CGContextBeginTransparencyLayer( context, nil );
            
            NSPoint gearImageCenter = NSMakePoint(NSMinX( bounds ) + ( margin + [gearImage size].width/2 ),
                                                  NSMaxY( bounds ) - ( margin + [gearImage size].height/2 ));
            
            id gradient = [NSClassFromString(@"NSGradient") alloc];
            if (gradient != nil)
            {
                NSColor *startingColor = [NSColor colorWithDeviceWhite:1.0 alpha:1.0];
                NSColor *endingColor = [NSColor colorWithDeviceWhite:1.0 alpha:0.0];
                
                gradient = [gradient initWithStartingColor:startingColor endingColor:endingColor];
                
                // draw gradient behind gear so that it's visible even on dark backgrounds
                [gradient drawFromCenter:gearImageCenter
                                  radius:0.0
                                toCenter:gearImageCenter
                                  radius:[gearImage size].height/2*1.5
                                 options:0];
                
                [gradient release];
            }
            
            // draw the gear image
            [gearImage drawAtPoint:NSMakePoint(gearImageCenter.x - [gearImage size].width/2,
                                               gearImageCenter.y - [gearImage size].height/2)
                          fromRect:NSZeroRect
                         operation:NSCompositeSourceOver
                          fraction:1.0];
 
            CGContextEndTransparencyLayer( context );
       }
    }
}
 
- (void) _drawBackground
{
    NSRect selfBounds = [self bounds];
 
    NSRect fillRect = NSInsetRect(selfBounds, 1.0, 1.0);
    NSRect strokeRect = selfBounds;
 
    NSColor *startingColor = [NSColor colorWithDeviceWhite:1.0 alpha:0.15];
    NSColor *endingColor = [NSColor colorWithDeviceWhite:0.0 alpha:0.15];
 
    // When the mouse is up or outside the view, we want a convex look, so we draw the gradient downward (90+180=270 degrees).
    // When the mouse is down and inside the view, we want a concave look, so we draw the gradient upward (90 degrees).
    id gradient = [NSClassFromString(@"NSGradient") alloc];
    if (gradient != nil)
    {
        gradient = [gradient initWithStartingColor:startingColor endingColor:endingColor];
 
        [gradient drawInBezierPath:[NSBezierPath bezierPathWithRect:fillRect] angle:90.0 + ((mouseIsDown && mouseInside) ? 0.0 : 180.0)];
 
        [gradient release];
    }
    else
    {
//tweak the opacity of the endingColor for compatibility with CTGradient
endingColor = [NSColor colorWithDeviceWhite:0.0 alpha:0.00];
 
gradient = [CTFGradient gradientWithBeginningColor:startingColor
endingColor:endingColor];
 
//angle is reversed compared to NSGradient
[gradient fillBezierPath:[NSBezierPath bezierPathWithRect:fillRect] angle:-90.0 - ((mouseIsDown && mouseInside) ? 0.0 : 180.0)];
 
//CTGradient instances are returned autoreleased - no need for explicit release here
    }
 
    // Draw stroke
    [[NSColor colorWithCalibratedWhite:0.0 alpha:0.50] set];
    [NSBezierPath setDefaultLineWidth:2.0];
    [NSBezierPath setDefaultLineCapStyle:NSSquareLineCapStyle];
    [[NSBezierPath bezierPathWithRect:strokeRect] stroke];
 
    // Draw label
    [ self _drawBadgeWithPressed: mouseIsDown && mouseInside ];
    
    // Draw the gear icon
if ([[CTFUserDefaultsController standardUserDefaults] boolForKey:sDrawGearImageOnlyOnMouseOverHiddenPref]) {
if( mouseInside && !mouseIsDown )
[ self _drawGearIcon ];
} else {
[ self _drawGearIcon ];
}
}
 
- (void) _checkMouseLocation
{
NSPoint mouseLoc = [NSEvent mouseLocation];
 
BOOL nowInside = NSPointInRect(mouseLoc, [_webView bounds]);
if (nowInside) {
mouseInside = YES;
} else {
mouseInside = NO;
}
}
 
- (void) _addTrackingAreaForCTF
{
    if (trackingArea)
        return;
    
    trackingArea = [NSClassFromString(@"NSTrackingArea") alloc];
    if (trackingArea != nil)
    {
        [(MATrackingArea *)trackingArea initWithRect:[self bounds]
                                             options:MATrackingMouseEnteredAndExited | MATrackingActiveInKeyWindow | MATrackingEnabledDuringMouseDrag | MATrackingInVisibleRect
                                               owner:self
                                            userInfo:nil];
        [self addTrackingArea:trackingArea];
    }
    else
    {
        trackingArea = [NSClassFromString(@"MATrackingArea") alloc];
        [(MATrackingArea *)trackingArea initWithRect:[self bounds]
                                             options:MATrackingMouseEnteredAndExited | MATrackingActiveInKeyWindow | MATrackingEnabledDuringMouseDrag | MATrackingInVisibleRect
                                               owner:self
                                            userInfo:nil];
        [MATrackingArea addTrackingArea:trackingArea toView:self];
        usingMATrackingArea = YES;
    }
}
 
- (void) _removeTrackingAreaForCTF
{
    if (trackingArea)
    {
        if (usingMATrackingArea)
        {
            [MATrackingArea removeTrackingArea:trackingArea fromView:self];
        }
        else
        {
            [self removeTrackingArea:trackingArea];
        }
        [trackingArea release];
        trackingArea = nil;
    }
}
 
 
#pragma mark -
#pragma mark YouTube H.264 support
 
 
- (NSDictionary*) _flashVarDictionary: (NSString*) flashvarString
{
    NSMutableDictionary* flashVarsDictionary = [ NSMutableDictionary dictionary ];
    
    NSArray* args = [ flashvarString componentsSeparatedByString: @"&" ];
    
    CTFForEachObject( NSString, oneArg, args ) {
        NSRange sepRange = [ oneArg rangeOfString: @"=" ];
        if( sepRange.location != NSNotFound ) {
            NSString* key = [ oneArg substringToIndex: sepRange.location ];
            NSString* val = [ oneArg substringFromIndex: NSMaxRange( sepRange ) ];
            
            [ flashVarsDictionary setObject: val forKey: key ];
        }
    }
    
    return flashVarsDictionary;
}
 
- (NSDictionary*) _flashVarDictionaryFromYouTubePageHTML: (NSString*) youTubePageHTML
{
NSMutableDictionary* flashVarsDictionary = [ NSMutableDictionary dictionary ];
NSScanner *HTMLScanner = [[NSScanner alloc] initWithString:youTubePageHTML];
 
[HTMLScanner scanUpToString:@"var swfArgs = {" intoString:nil];
BOOL swfArgsFound = [HTMLScanner scanString:@"var swfArgs = {" intoString:nil];
 
if (swfArgsFound) {
NSString *swfArgsString = nil;
[HTMLScanner scanUpToString:@"}" intoString:&swfArgsString];
NSArray *arrayOfSWFArgs = [swfArgsString componentsSeparatedByString:@", "];
CTFForEachObject( NSString, currentArgPairString, arrayOfSWFArgs ) {
NSRange sepRange = [ currentArgPairString rangeOfString:@": "];
if (sepRange.location != NSNotFound) {
NSString *potentialKey = [currentArgPairString substringToIndex:sepRange.location];
NSString *potentialVal = [currentArgPairString substringFromIndex:NSMaxRange(sepRange)];
 
// we might need to strip the surrounding quotes from the keys and values
// (but not always)
NSString *key = nil;
if ([[potentialKey substringToIndex:1] isEqualToString:@"\""]) {
key = [potentialKey substringWithRange:NSMakeRange(1,[potentialKey length] - 2)];
} else {
key = potentialKey;
}
 
NSString *val = nil;
if ([[potentialVal substringToIndex:1] isEqualToString:@"\""]) {
val = [potentialVal substringWithRange:NSMakeRange(1,[potentialVal length] - 2)];
} else {
val = potentialVal;
}
 
[flashVarsDictionary setObject:val forKey:key];
}
}
}
 
[HTMLScanner release];
return flashVarsDictionary;
}
 
- (NSString*) flashvarWithName: (NSString*) argName
{
    return [[[ _flashVars objectForKey: argName ] retain] autorelease];
}
 
/*- (NSString*) _videoId
{
return [ self flashvarWithName: @"video_id" ];
}*/
 
- (NSString*) _videoHash
{
    return [ self flashvarWithName: @"t" ];
}
 
- (void)_checkForH264VideoVariants
{
for (int i = 0; i < 2; ++i) {
NSMutableURLRequest *request;
NSString * URLString;
if (i == 0) { URLString = [self H264URLString]; }
else { URLString = [self H264HDURLString]; }
 
request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:URLString]];
 
if (request != nil) {
[request setHTTPMethod:@"HEAD"];
connections[i] = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
}
}
 
expectedResponses = 2;
_receivedAllResponses = NO;
}
 
- (void)finishedWithConnection:(NSURLConnection *)connection
{
BOOL didReceiveAllResponses = YES;
 
for (int i = 0; i < 2; ++i) {
if (connection == connections[i]) {
[connection cancel];
[connection release];
connections[i] = nil;
} else if (connections[i])
didReceiveAllResponses = NO;
}
 
if (didReceiveAllResponses) _receivedAllResponses = YES;
 
[self setNeedsDisplay:YES];
}
 
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSHTTPURLResponse *)response
{
int statusCode = [response statusCode];
 
if (statusCode == 200) {
if (connection == connections[0])
[self _setHasH264Version:YES];
else
[self _setHasHDH264Version:YES];
}
 
[self finishedWithConnection:connection];
}
 
- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
[self finishedWithConnection:connection];
}
 
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse
{
/* We need to fix the redirects to make sure the method they use
is HEAD. */
if ([[request HTTPMethod] isEqualTo:@"HEAD"])
return request;
 
NSMutableURLRequest *newRequest = [request mutableCopy];
[newRequest setHTTPMethod:@"HEAD"];
 
return [newRequest autorelease];
}
 
- (BOOL) _useH264Version
{
    return [ self _hasH264Version ]
&& [ [ CTFUserDefaultsController standardUserDefaults ] boolForKey: sUseYouTubeH264DefaultsKey ]
&& [ [ CTFUserDefaultsController standardUserDefaults ] boolForKey: sPluginEnabled ];
}
 
- (BOOL) _useHDH264Version
{
return [ self _hasHDH264Version ]
&& [ [ CTFUserDefaultsController standardUserDefaults ] boolForKey: sUseYouTubeH264DefaultsKey ]
&& [ [ CTFUserDefaultsController standardUserDefaults ] boolForKey: sUseYouTubeHDH264DefaultsKey ]
&& [ [ CTFUserDefaultsController standardUserDefaults ] boolForKey: sPluginEnabled ];
}
 
 
- (BOOL)_isVideoElementAvailable
{
if ( [[CTFUserDefaultsController standardUserDefaults] boolForKey:sDisableVideoElement] )
return NO;
 
/* <video> element compatibility was added to WebKit in or shortly before version 525. */
 
    NSBundle* webKitBundle;
    webKitBundle = [ NSBundle bundleForClass: [ WebView class ] ];
    if (webKitBundle) {
/* ref. http://lists.apple.com/archives/webkitsdk-dev/2008/Nov/msg00003.html:
* CFBundleVersion is 5xxx.y on WebKits built to run on Leopard, 4xxx.y on Tiger.
* Unspecific builds (such as the ones in OmniWeb) get xxx.y numbers without a prefix.
*/
int normalizedVersion;
float wkVersion = [ (NSString*) [ [ webKitBundle infoDictionary ]
valueForKey: @"CFBundleVersion" ]
floatValue ];
if (wkVersion > 4000)
normalizedVersion = (int)wkVersion % 1000;
else
normalizedVersion = wkVersion;
 
// unfortunately, versions of WebKit above 531.5 also introduce a nasty
// scrolling bug with video elements that cause them to be unviewable;
// this bug was fixed shortly after being reported by @simX, so we can
// now re-enable it for correct WebKit versions
//
// this bug actually only affected certain machines that had graphics
// cards with a certain max texture size, and it was partially fixed, but
// still didn't work for MacBooks with embedded graphics, and we could
// detect that if we really wanted, but that would require importing
// the OpenGL framework, which we probably shouldn't do, so we'll just
// wholesale disable for certain WebKit versions
//
// https://bugs.webkit.org/show_bug.cgi?id=28705
 
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) {
// Snowy Leopard; this bug doesn't seem to be exhibited here
return (normalizedVersion >= 525);
} else {
// this bug was introduced in version 531.5, but has been fixed in
// 532 and above
 
return ((normalizedVersion >= 532) ||
((normalizedVersion >= 525) && (normalizedVersion < 531.5))
);
}
}
return NO;
}
 
 
- (void) _convertElementForMP4: (DOMElement*) element atURL: (NSString*) URLString
{
// some tags (OBJECT) want a data attribute, and some want a src attribute
// for some reason, though, some cloned elements are not reporting themselves
// as OBJECT tags, even though they are; more investigation on this is needed,
// but for now, setting both the data and the src attribute corrects the problem
// (see bug #294)
 
[ element setAttribute: @"data" value: URLString ];
[ element setAttribute: @"src" value: URLString ];
[ element setAttribute: @"type" value: @"video/mp4" ];
    [ element setAttribute: @"scale" value: @"aspect" ];
    if (_youTubeAutoPlay) {
[ element setAttribute: @"autoplay" value: @"true" ];
} else {
[ element setAttribute: @"autoplay" value: @"false" ];
}
    [ element setAttribute: @"cache" value: @"false" ];
[ element setAttribute: @"bgcolor" value: @"transparent" ];
    [ element setAttribute: @"flashvars" value: nil ];
}
 
- (void) _convertElementForVideoElement: (DOMElement*) element atURL: (NSString*) URLString
{
    [ element setAttribute: @"src" value: URLString ];
[ element setAttribute: @"autobuffer" value:@"autobuffer"];
if (_youTubeAutoPlay) {
[ element setAttribute: @"autoplay" value:@"autoplay" ];
} else {
if ( [element hasAttribute:@"autoplay"] )
[ element removeAttribute:@"autoplay" ];
}
[ element setAttribute: @"controls" value:@"controls"];
[ element setAttribute:@"width" value:@"100%"];
}
 
 
/*
The useHD parameter indicates whether we want to override the default behaviour to use or not use HD.
Passing nil invokes the default behaviour based on user preferences and HD availability.
*/
- (void) _convertToMP4ContainerUsingHD: (NSNumber*) useHD
{
[self _revertToOriginalOpacityAttributes];
 
// Delay this until the end of the event loop, because it may cause self to be deallocated
[self _prepareForConversion];
[self performSelector:@selector(_convertToMP4ContainerAfterDelayUsingHD:) withObject:useHD afterDelay:0.0];
}
 
- (void) _convertToMP4ContainerAfterDelayUsingHD: (NSNumber*) useHDNumber
{
BOOL useHD = [ self _useHDH264Version ];
if (useHDNumber) {
useHD = [useHDNumber boolValue];
}
 
NSString * URLString;
if ( useHD && [ self _hasHDH264Version ] ) {
URLString = [ self H264HDURLString ];
}
else {
URLString = [ self H264URLString ];
}
 
DOMDocument* document = [[self container] ownerDocument];
DOMElement* videoElement;
if ([ self _isVideoElementAvailable ]) {
videoElement = [document createElement:@"video"];
[ self _convertElementForVideoElement: videoElement atURL: URLString ];
    } else {
videoElement = (DOMElement*) [ [self container] cloneNode: NO ];
[ self _convertElementForMP4: videoElement atURL: URLString ];
}
 
// Put links for going to the YouTube page and downloading the video file beneath the video as these vanish once CtF is invoked and it's hard to bookmark the YouTube link otherwise.
NSString * linkCSS = @"margin:0px 0.5em;padding:0px;border:0px none;";
DOMElement* YouTubeLinkElement = [document createElement: @"a"];
[YouTubeLinkElement setAttribute: @"href" value: [self YouTubePageURLString]];
[YouTubeLinkElement setAttribute: @"style" value: linkCSS];
[YouTubeLinkElement setAttribute: @"class" value: @"clicktoflash-link youtube"];
[YouTubeLinkElement setTextContent:CtFLocalizedString(@"Go to YouTube page", @"Text of link to YouTube page appearing beneath the video")];
 
DOMElement* downloadLinkElement = [document createElement: @"a"];
[downloadLinkElement setAttribute: @"href" value: URLString];
[downloadLinkElement setAttribute: @"style" value: linkCSS];
[downloadLinkElement setAttribute: @"class" value: @"clicktoflash-link h264download"];
[downloadLinkElement setTextContent:CtFLocalizedString(@"Download video file", @"Text of link to H.264 Download appearing beneath the video")];
 
NSString * divCSS = @"margin:auto;padding:0px;border:0px none;text-align:center;display:block;float:none;";
DOMElement* linkContainerElement = [document createElement: @"div"];
[linkContainerElement setAttribute: @"style" value: divCSS];
[linkContainerElement setAttribute: @"class" value: @"clicktoflash-linkcontainer"];
if ( ![[self baseURL] hasPrefix: [self YouTubePageURLString]]) {
[linkContainerElement appendChild:YouTubeLinkElement];
}
[linkContainerElement appendChild:downloadLinkElement];
 
if ( [self _hasHDH264Version] && !useHD) {
// offer additional link for HD download if available
NSString * extraLinkCSS = @"margin:0px;padding:0px;border:0px none;";
DOMElement * extraDownloadLinkElement = [document createElement: @"a"];
[extraDownloadLinkElement setAttribute: @"href" value: [self H264HDURLString]];
[extraDownloadLinkElement setAttribute: @"style" value: extraLinkCSS];
[extraDownloadLinkElement setAttribute: @"class" value: @"clicktoflash-link h264download"];
[extraDownloadLinkElement setTextContent: CtFLocalizedString(@"(Larger Size)", @"Text of link to additional Large Size H.264 Download appearing beneath the video after the standard link")];
[linkContainerElement appendChild: extraDownloadLinkElement];
}
 
DOMNode * widthNode = [[[self container] attributes ] getNamedItem:@"width"];
NSString * width = @"100%"; // default to 100% width
if (widthNode != nil) {
// width is already set explicitly, preserve that
width = [widthNode nodeValue];
if ( [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[width characterAtIndex:[width length] - 1]] ) {
// add 'px' if existing width is just a number (ends with a digit)
width = [width stringByAppendingString:@"px"];
}
}
NSString * widthCSS = [NSString stringWithFormat:@"%@width:%@;", divCSS, width];
 
DOMElement* CtFContainerElement = [document createElement: @"div"];
[CtFContainerElement setAttribute: @"style" value: widthCSS];
[CtFContainerElement setAttribute: @"class" value: @"clicktoflash-container"];
[CtFContainerElement appendChild: videoElement];
[CtFContainerElement appendChild: linkContainerElement];
 
 
    // Just to be safe, since we are about to replace our containing element
    [[self retain] autorelease];
    
    // Replace self with element.
[[[self container] parentNode] replaceChild:CtFContainerElement oldChild:[self container]];
 
    [self setContainer:nil];
}
 
- (NSString *)launchedAppBundleIdentifier
{
NSString *appBundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
 
if ([appBundleIdentifier isEqualToString:@"com.apple.Safari"]) {
// additional tests need to be performed, because this can indicate
// either WebKit *or* Safari; according to @bdash on Twitter, we need
// to check whether the framework bundle that we're using is
// contained within WebKit.app or not
 
// however, the user may have renamed the bundle, so we have to get
// its path, then get its bundle identifier
 
NSString *privateFrameworksPath = [[NSBundle bundleForClass:[WebView class]] privateFrameworksPath];
 
NSScanner *pathScanner = [[NSScanner alloc] initWithString:privateFrameworksPath];
NSString *pathString = nil;
[pathScanner scanUpToString:@".app" intoString:&pathString];
NSBundle *testBundle = [[NSBundle alloc] initWithPath:[pathString stringByAppendingPathExtension:@"app"]];
NSString *testBundleIdentifier = [testBundle bundleIdentifier];
[testBundle release];
[pathScanner release];
 
 
// Safari uses the framework inside /System/Library/Frameworks/ , and
// since there's no ".app" extension in that path, the resulting
// bundle identifier will be nil; however, if it's WebKit, there *will*
// be a ".app" in the frameworks path, and we'll get a valid bundle
// identifier to launch with
 
if (testBundleIdentifier != nil) appBundleIdentifier = testBundleIdentifier;
}
 
return appBundleIdentifier;
}
 
- (NSString *)YouTubePageURLString
{
return [ NSString stringWithFormat: @"http://www.youtube.com/watch?v=%@", [self videoId] ];
}
 
- (NSString *)H264URLString
{
    return [ NSString stringWithFormat: @"http://www.youtube.com/get_video?fmt=18&video_id=%@&t=%@",
[self videoId], [ self _videoHash ] ];
}
 
- (NSString *)H264HDURLString
{
    return [ NSString stringWithFormat: @"http://www.youtube.com/get_video?fmt=22&video_id=%@&t=%@",
[self videoId], [ self _videoHash ] ];
}
 
 
 
- (void) downloadH264UsingHD: (BOOL) useHD {
NSString * src;
if ( useHD && [self _hasHDH264Version]) {
src = [ self H264HDURLString ];
} else {
src = [ self H264URLString ];
}
 
[[NSWorkspace sharedWorkspace] openURLs: [NSArray arrayWithObject:[NSURL URLWithString:src]]
withAppBundleIdentifier: [self launchedAppBundleIdentifier]
options: NSWorkspaceLaunchDefault
additionalEventParamDescriptor: [NSAppleEventDescriptor nullDescriptor]
launchIdentifiers: nil];
}
 
 
- (IBAction)downloadH264:(id)sender
{
BOOL wantHD = [[CTFUserDefaultsController standardUserDefaults] boolForKey:sUseYouTubeHDH264DefaultsKey];
[self downloadH264UsingHD: wantHD];
}
 
- (IBAction)downloadH264SD:(id)sender {
[self downloadH264UsingHD: NO];
}
 
- (IBAction)downloadH264HD:(id)sender {
[self downloadH264UsingHD: YES];
}
 
 
- (IBAction)loadYouTubePage:(id)sender
{
    [_webView setMainFrameURL:[self YouTubePageURLString]];
}
 
 
- (void)openFullscreenInQTPlayerUsingHD:(BOOL) useHD {
NSString * src;
if (useHD && [self _hasHDH264Version]) {
src = [ self H264HDURLString ];
} else {
src = [ self H264URLString ];
}
 
NSString *scriptSource = nil;
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) {
// Snowy Leopard
scriptSource = [NSString stringWithFormat:
@"tell application \"QuickTime Player\"\nactivate\nopen URL \"%@\"\nrepeat while (front document is not presenting)\ndelay 1\npresent front document\nend repeat\nrepeat while (playing of front document is false)\ndelay 1\nplay front document\nend repeat\nend tell",src];
} else {
scriptSource = [NSString stringWithFormat:
@"tell application \"QuickTime Player\"\nactivate\ngetURL \"%@\"\nrepeat while (display state of front document is not presentation)\ndelay 1\npresent front document scale screen\nend repeat\nrepeat while (playing of front document is false)\ndelay 1\nplay front document\nend repeat\nend tell",src];
}
NSAppleScript *openInQTPlayerScript = [[NSAppleScript alloc] initWithSource:scriptSource];
[openInQTPlayerScript executeAndReturnError:nil];
[openInQTPlayerScript release];
}
 
- (IBAction)openFullscreenInQTPlayer:(id)sender;
{
BOOL useHD = [[CTFUserDefaultsController standardUserDefaults] boolForKey:sUseYouTubeHDH264DefaultsKey];
 
[self openFullscreenInQTPlayerUsingHD: useHD];
}
 
- (IBAction)openFullscreenInQTPlayerSD:(id)sender{
[self openFullscreenInQTPlayerUsingHD: NO];
}
 
- (IBAction)openFullscreenInQTPlayerHD:(id)sender{
[self openFullscreenInQTPlayerUsingHD: YES];
}
 
 
- (void)_didRetrieveEmbeddedPlayerFlashVars:(NSDictionary *)flashVars
{
if (flashVars)
{
_flashVars = [flashVars retain];
NSString *videoId = [self flashvarWithName:@"video_id"];
[self setVideoId:videoId];
}
 
[self _checkForH264VideoVariants];
}
 
- (void)_retrieveEmbeddedPlayerFlashVarsAndCheckForVariantsWithVideoId:(NSString *)videoId
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
NSURL *YouTubePageURL = [NSURL URLWithString: [self YouTubePageURLString]];
NSError *pageSourceError = nil;
NSString *pageSourceString = [NSString stringWithContentsOfURL:YouTubePageURL
usedEncoding:nil
error:&pageSourceError];
NSDictionary *flashVars = nil;
if (pageSourceString && !pageSourceError) {
flashVars = [self _flashVarDictionaryFromYouTubePageHTML:pageSourceString];
}
 
[self performSelectorOnMainThread:@selector(_didRetrieveEmbeddedPlayerFlashVars:)
withObject:flashVars
waitUntilDone:NO];
 
[pool drain];
}
 
- (void)_getEmbeddedPlayerFlashVarsAndCheckForVariantsWithVideoId:(NSString *)videoId
{
[NSThread detachNewThreadSelector:@selector(_retrieveEmbeddedPlayerFlashVarsAndCheckForVariantsWithVideoId:)
toTarget:self
withObject:videoId];
}
 
 
#pragma mark -
#pragma mark DOM Conversion
 
 
- (void) _convertTypesForElement:(DOMElement *)element
{
    NSString *type = [element getAttribute:@"type"];
 
    if ([type isEqualToString:sFlashOldMIMEType] || [type length] == 0) {
        [element setAttribute:@"type" value:sFlashNewMIMEType];
    }
}
 
- (void) _convertTypesForContainer
{
    if ([self _useH264Version])
        [self _convertToMP4ContainerUsingHD: nil];
    else
        [self _convertTypesForFlashContainer];
}
 
- (void) _convertTypesForFlashContainer
{
[self _revertToOriginalOpacityAttributes];
 
// Delay this until the end of the event loop, because it may cause self to be deallocated
[self _prepareForConversion];
[self performSelector:@selector(_convertTypesForFlashContainerAfterDelay) withObject:nil afterDelay:0.0];
}
 
- (void) _convertTypesForFlashContainerAfterDelay
{
    DOMNodeList *nodeList = nil;
    NSUInteger i;
 
    [self _convertTypesForElement:[self container]];
 
    nodeList = [[self container] getElementsByTagName:@"object"];
    for (i = 0; i < [nodeList length]; i++) {
        [self _convertTypesForElement:(DOMElement *)[nodeList item:i]];
    }
 
    nodeList = [[self container] getElementsByTagName:@"embed"];
    for (i = 0; i < [nodeList length]; i++) {
        [self _convertTypesForElement:(DOMElement *)[nodeList item:i]];
    }
    
    // Remove & reinsert the node to persuade the plugin system to notice the type change:
    id parent = [[self container] parentNode];
    id successor = [[self container] nextSibling];
 
DOMElement *theContainer = [[self container] retain];
    [parent removeChild:theContainer];
    [parent insertBefore:theContainer refChild:successor];
[theContainer release];
    [self setContainer:nil];
}
 
- (void) _prepareForConversion
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
 
// notify that this ClickToFlash plugin is going away
[[CTFMenubarMenuController sharedController] unregisterView: self];
 
[ self _abortAlert ];
}
 
- (void) _revertToOriginalOpacityAttributes
{
NSString *selfWmode = [[self originalOpacityAttributes] objectForKey:@"self-wmode"];
if (selfWmode != nil ) {
[[self container] setAttribute:@"wmode" value:selfWmode];
}
 
NSString *currentStyle = [[self container] getAttribute:@"style"];
NSString *originalSelfStyle = [[self originalOpacityAttributes] objectForKey:@"self-style"];
if (originalSelfStyle != nil ) {
if ([currentStyle isEqualToString:[[self originalOpacityAttributes] objectForKey:@"modified-self-style"]]) {
[[self container] setAttribute:@"style" value:originalSelfStyle];
}
}
 
NSString *parentWmode = [[self originalOpacityAttributes] objectForKey:@"parent-wmode"];
if (parentWmode != nil ) {
[(DOMElement *)[[self container] parentNode] setAttribute:@"wmode" value:parentWmode];
}
 
NSString *currentParentStyle = [(DOMElement *)[[self container] parentNode] getAttribute:@"style"];
NSString *originalParentStyle = [[self originalOpacityAttributes] objectForKey:@"parent-style"];
if (originalParentStyle != nil ) {
if ([currentParentStyle isEqualToString:[[self originalOpacityAttributes] objectForKey:@"modified-parent-style"]]) {
[(DOMElement *)[[self container] parentNode] setAttribute:@"style" value:originalParentStyle];
}
}
}
 
- (WebView *)webView
{
    return _webView;
}
- (void)setWebView:(WebView *)newValue
{
    // Not retained, because the WebView owns the plugin, so we'll get a retain cycle.
    _webView = newValue;
}
 
- (DOMElement *)container
{
    return _container;
}
- (void)setContainer:(DOMElement *)newValue
{
    [newValue retain];
    [_container release];
    _container = newValue;
}
 
- (NSString *)host
{
    return _host;
}
- (void)setHost:(NSString *)newValue
{
    [newValue retain];
    [_host release];
    _host = newValue;
}
 
- (NSString *)baseURL
{
    return _baseURL;
}
- (void)setBaseURL:(NSString *)newValue
{
    [newValue retain];
    [_baseURL release];
    _baseURL = newValue;
}
 
- (NSDictionary *)attributes
{
    return _attributes;
}
- (void)setAttributes:(NSDictionary *)newValue
{
    [newValue retain];
    [_attributes release];
    _attributes = newValue;
}
 
- (NSDictionary *)originalOpacityAttributes
{
    return _originalOpacityAttributes;
}
- (void)setOriginalOpacityAttributes:(NSDictionary *)newValue
{
    [newValue retain];
    [_originalOpacityAttributes release];
    _originalOpacityAttributes = newValue;
}
 
- (NSString *)src
{
    return _src;
}
- (void)setSrc:(NSString *)newValue
{
    [newValue retain];
    [_src release];
    _src = newValue;
}
 
- (NSString *)videoId
{
    return [[_videoId retain] autorelease];
}
- (void)setVideoId:(NSString *)newValue
{
    [newValue retain];
    [_videoId release];
    _videoId = newValue;
}
 
- (BOOL)_hasH264Version
{
return (_fromYouTube && _hasH264Version);
}
 
- (void)_setHasH264Version:(BOOL)newValue
{
_hasH264Version = newValue;
[self setNeedsDisplay:YES];
}
 
- (BOOL)_hasHDH264Version
{
return (_fromYouTube && _hasHDH264Version);
}
 
- (void)_setHasHDH264Version:(BOOL)newValue
{
_hasHDH264Version = newValue;
[self setNeedsDisplay:YES];
}
 
- (void)setLaunchedAppBundleIdentifier:(NSString *)newValue
{
    [newValue retain];
    [_launchedAppBundleIdentifier release];
    _launchedAppBundleIdentifier = newValue;
}
@end