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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
|
/*
* Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if ENABLE(NETSCAPE_PLUGIN_API)
#import "WebNetscapePluginView.h"
#import "WebDataSourceInternal.h"
#import "WebDefaultUIDelegate.h"
#import "WebFrameInternal.h"
#import "WebFrameView.h"
#import "WebKitErrorsPrivate.h"
#import "WebKitLogging.h"
#import "WebNetscapeContainerCheckPrivate.h"
#import "WebKitNSStringExtras.h"
#import "WebKitSystemInterface.h"
#import "WebNSDataExtras.h"
#import "WebNSDictionaryExtras.h"
#import "WebNSObjectExtras.h"
#import "WebNSURLExtras.h"
#import "WebNSURLRequestExtras.h"
#import "WebNSViewExtras.h"
#import "WebNetscapePluginPackage.h"
#import "WebBaseNetscapePluginStream.h"
#import "WebPluginContainerCheck.h"
#import "WebNetscapeContainerCheckContextInfo.h"
#import "WebNetscapePluginEventHandler.h"
#import "WebNullPluginView.h"
#import "WebPreferences.h"
#import "WebPluginRequest.h"
#import "WebViewInternal.h"
#import "WebUIDelegatePrivate.h"
#import <Carbon/Carbon.h>
#import <runtime/JSLock.h>
#import <WebCore/npruntime_impl.h>
#import <WebCore/CookieJar.h>
#import <WebCore/CString.h>
#import <WebCore/DocumentLoader.h>
#import <WebCore/Element.h>
#import <WebCore/Frame.h>
#import <WebCore/FrameLoader.h>
#import <WebCore/FrameTree.h>
#import <WebCore/HTMLPlugInElement.h>
#import <WebCore/Page.h>
#import <WebCore/PluginMainThreadScheduler.h>
#import <WebCore/ScriptController.h>
#import <WebCore/SoftLinking.h>
#import <WebCore/WebCoreObjCExtras.h>
#import <WebCore/WebCoreURLResponse.h>
#import <WebKit/DOMPrivate.h>
#import <WebKit/WebUIDelegate.h>
#import <runtime/InitializeThreading.h>
#import <wtf/Assertions.h>
#import <objc/objc-runtime.h>
using std::max;
#define LoginWindowDidSwitchFromUserNotification @"WebLoginWindowDidSwitchFromUserNotification"
#define LoginWindowDidSwitchToUserNotification @"WebLoginWindowDidSwitchToUserNotification"
using namespace WebCore;
using namespace WebKit;
static inline bool isDrawingModelQuickDraw(NPDrawingModel drawingModel)
{
#ifndef NP_NO_QUICKDRAW
return drawingModel == NPDrawingModelQuickDraw;
#else
return false;
#endif
};
@interface WebNetscapePluginView (Internal)
- (NPError)_createPlugin;
- (void)_destroyPlugin;
- (NSBitmapImageRep *)_printedPluginBitmap;
- (void)_redeliverStream;
- (BOOL)_shouldCancelSrcStream;
@end
static WebNetscapePluginView *currentPluginView = nil;
typedef struct OpaquePortState* PortState;
static const double ThrottledTimerInterval = 0.25;
class PluginTimer : public TimerBase {
public:
typedef void (*TimerFunc)(NPP npp, uint32 timerID);
PluginTimer(NPP npp, uint32 timerID, uint32 interval, NPBool repeat, TimerFunc timerFunc)
: m_npp(npp)
, m_timerID(timerID)
, m_interval(interval)
, m_repeat(repeat)
, m_timerFunc(timerFunc)
{
}
void start(bool throttle)
{
ASSERT(!isActive());
double timeInterval = m_interval / 1000.0;
if (throttle)
timeInterval = max(timeInterval, ThrottledTimerInterval);
if (m_repeat)
startRepeating(timeInterval);
else
startOneShot(timeInterval);
}
private:
virtual void fired()
{
m_timerFunc(m_npp, m_timerID);
if (!m_repeat)
delete this;
}
NPP m_npp;
uint32 m_timerID;
uint32 m_interval;
NPBool m_repeat;
TimerFunc m_timerFunc;
};
#ifndef NP_NO_QUICKDRAW
// QuickDraw is not available in 64-bit
typedef struct {
GrafPtr oldPort;
GDHandle oldDevice;
Point oldOrigin;
RgnHandle oldClipRegion;
RgnHandle oldVisibleRegion;
RgnHandle clipRegion;
BOOL forUpdate;
} PortState_QD;
#endif /* NP_NO_QUICKDRAW */
typedef struct {
CGContextRef context;
} PortState_CG;
@class NSTextInputContext;
@interface NSResponder (AppKitDetails)
- (NSTextInputContext *)inputContext;
@end
@interface WebNetscapePluginView (ForwardDeclarations)
- (void)setWindowIfNecessary;
- (NPError)loadRequest:(NSMutableURLRequest *)request inTarget:(const char *)cTarget withNotifyData:(void *)notifyData sendNotification:(BOOL)sendNotification;
@end
@implementation WebNetscapePluginView
+ (void)initialize
{
JSC::initializeThreading();
#ifndef BUILDING_ON_TIGER
WebCoreObjCFinalizeOnMainThread(self);
#endif
WKSendUserChangeNotifications();
}
#pragma mark EVENTS
- (BOOL)superviewsHaveSuperviews
{
NSView *contentView = [[self window] contentView];
NSView *view;
for (view = self; view != nil; view = [view superview]) {
if (view == contentView) {
return YES;
}
}
return NO;
}
// The WindowRef created by -[NSWindow windowRef] has a QuickDraw GrafPort that covers
// the entire window frame (or structure region to use the Carbon term) rather then just the window content.
// We can remove this when <rdar://problem/4201099> is fixed.
- (void)fixWindowPort
{
#ifndef NP_NO_QUICKDRAW
ASSERT(isDrawingModelQuickDraw(drawingModel));
NSWindow *currentWindow = [self currentWindow];
if ([currentWindow isKindOfClass:objc_getClass("NSCarbonWindow")])
return;
float windowHeight = [currentWindow frame].size.height;
NSView *contentView = [currentWindow contentView];
NSRect contentRect = [contentView convertRect:[contentView frame] toView:nil]; // convert to window-relative coordinates
CGrafPtr oldPort;
GetPort(&oldPort);
SetPort(GetWindowPort((WindowRef)[currentWindow windowRef]));
MovePortTo(static_cast<short>(contentRect.origin.x), /* Flip Y */ static_cast<short>(windowHeight - NSMaxY(contentRect)));
PortSize(static_cast<short>(contentRect.size.width), static_cast<short>(contentRect.size.height));
SetPort(oldPort);
#endif
}
#ifndef NP_NO_QUICKDRAW
static UInt32 getQDPixelFormatForBitmapContext(CGContextRef context)
{
UInt32 byteOrder = CGBitmapContextGetBitmapInfo(context) & kCGBitmapByteOrderMask;
if (byteOrder == kCGBitmapByteOrderDefault)
switch (CGBitmapContextGetBitsPerPixel(context)) {
case 16:
byteOrder = kCGBitmapByteOrder16Host;
break;
case 32:
byteOrder = kCGBitmapByteOrder32Host;
break;
}
switch (byteOrder) {
case kCGBitmapByteOrder16Little:
return k16LE555PixelFormat;
case kCGBitmapByteOrder32Little:
return k32BGRAPixelFormat;
case kCGBitmapByteOrder16Big:
return k16BE555PixelFormat;
case kCGBitmapByteOrder32Big:
return k32ARGBPixelFormat;
}
ASSERT_NOT_REACHED();
return 0;
}
static inline void getNPRect(const CGRect& cgr, NPRect& npr)
{
npr.top = static_cast<uint16>(cgr.origin.y);
npr.left = static_cast<uint16>(cgr.origin.x);
npr.bottom = static_cast<uint16>(CGRectGetMaxY(cgr));
npr.right = static_cast<uint16>(CGRectGetMaxX(cgr));
}
#endif
static inline void getNPRect(const NSRect& nr, NPRect& npr)
{
npr.top = static_cast<uint16>(nr.origin.y);
npr.left = static_cast<uint16>(nr.origin.x);
npr.bottom = static_cast<uint16>(NSMaxY(nr));
npr.right = static_cast<uint16>(NSMaxX(nr));
}
- (PortState)saveAndSetNewPortStateForUpdate:(BOOL)forUpdate
{
ASSERT([self currentWindow] != nil);
// Use AppKit to convert view coordinates to NSWindow coordinates.
NSRect boundsInWindow = [self convertRect:[self bounds] toView:nil];
NSRect visibleRectInWindow = [self convertRect:[self visibleRect] toView:nil];
// Flip Y to convert NSWindow coordinates to top-left-based window coordinates.
float borderViewHeight = [[self currentWindow] frame].size.height;
boundsInWindow.origin.y = borderViewHeight - NSMaxY(boundsInWindow);
visibleRectInWindow.origin.y = borderViewHeight - NSMaxY(visibleRectInWindow);
#ifndef NP_NO_QUICKDRAW
WindowRef windowRef = (WindowRef)[[self currentWindow] windowRef];
ASSERT(windowRef);
// Look at the Carbon port to convert top-left-based window coordinates into top-left-based content coordinates.
if (isDrawingModelQuickDraw(drawingModel)) {
// If drawing with QuickDraw, fix the window port so that it has the same bounds as the NSWindow's
// content view. This makes it easier to convert between AppKit view and QuickDraw port coordinates.
[self fixWindowPort];
::Rect portBounds;
CGrafPtr port = GetWindowPort(windowRef);
GetPortBounds(port, &portBounds);
PixMap *pix = *GetPortPixMap(port);
boundsInWindow.origin.x += pix->bounds.left - portBounds.left;
boundsInWindow.origin.y += pix->bounds.top - portBounds.top;
visibleRectInWindow.origin.x += pix->bounds.left - portBounds.left;
visibleRectInWindow.origin.y += pix->bounds.top - portBounds.top;
}
#endif
window.type = NPWindowTypeWindow;
window.x = (int32)boundsInWindow.origin.x;
window.y = (int32)boundsInWindow.origin.y;
window.width = static_cast<uint32>(NSWidth(boundsInWindow));
window.height = static_cast<uint32>(NSHeight(boundsInWindow));
// "Clip-out" the plug-in when:
// 1) it's not really in a window or off-screen or has no height or width.
// 2) window.x is a "big negative number" which is how WebCore expresses off-screen widgets.
// 3) the window is miniaturized or the app is hidden
// 4) we're inside of viewWillMoveToWindow: with a nil window. In this case, superviews may already have nil
// superviews and nil windows and results from convertRect:toView: are incorrect.
NSWindow *realWindow = [self window];
if (window.width <= 0 || window.height <= 0 || window.x < -100000
|| realWindow == nil || [realWindow isMiniaturized]
|| [NSApp isHidden]
|| ![self superviewsHaveSuperviews]
|| [self isHiddenOrHasHiddenAncestor]) {
// The following code tries to give plug-ins the same size they will eventually have.
// The specifiedWidth and specifiedHeight variables are used to predict the size that
// WebCore will eventually resize us to.
// The QuickTime plug-in has problems if you give it a width or height of 0.
// Since other plug-ins also might have the same sort of trouble, we make sure
// to always give plug-ins a size other than 0,0.
if (window.width <= 0)
window.width = specifiedWidth > 0 ? specifiedWidth : 100;
if (window.height <= 0)
window.height = specifiedHeight > 0 ? specifiedHeight : 100;
window.clipRect.bottom = window.clipRect.top;
window.clipRect.left = window.clipRect.right;
} else {
getNPRect(visibleRectInWindow, window.clipRect);
}
// Save the port state, set up the port for entry into the plugin
PortState portState;
switch (drawingModel) {
#ifndef NP_NO_QUICKDRAW
case NPDrawingModelQuickDraw: {
// Set up NS_Port.
::Rect portBounds;
CGrafPtr port = GetWindowPort(windowRef);
GetPortBounds(port, &portBounds);
nPort.qdPort.port = port;
nPort.qdPort.portx = (int32)-boundsInWindow.origin.x;
nPort.qdPort.porty = (int32)-boundsInWindow.origin.y;
window.window = &nPort;
PortState_QD *qdPortState = (PortState_QD*)malloc(sizeof(PortState_QD));
portState = (PortState)qdPortState;
GetGWorld(&qdPortState->oldPort, &qdPortState->oldDevice);
qdPortState->oldOrigin.h = portBounds.left;
qdPortState->oldOrigin.v = portBounds.top;
qdPortState->oldClipRegion = NewRgn();
GetPortClipRegion(port, qdPortState->oldClipRegion);
qdPortState->oldVisibleRegion = NewRgn();
GetPortVisibleRegion(port, qdPortState->oldVisibleRegion);
RgnHandle clipRegion = NewRgn();
qdPortState->clipRegion = clipRegion;
CGContextRef currentContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
if (currentContext && WKCGContextIsBitmapContext(currentContext)) {
// We use WKCGContextIsBitmapContext here, because if we just called CGBitmapContextGetData
// on any context, we'd log to the console every time. But even if WKCGContextIsBitmapContext
// returns true, it still might not be a context we need to create a GWorld for; for example
// transparency layers will return true, but return 0 for CGBitmapContextGetData.
void* offscreenData = CGBitmapContextGetData(currentContext);
if (offscreenData) {
// If the current context is an offscreen bitmap, then create a GWorld for it.
::Rect offscreenBounds;
offscreenBounds.top = 0;
offscreenBounds.left = 0;
offscreenBounds.right = CGBitmapContextGetWidth(currentContext);
offscreenBounds.bottom = CGBitmapContextGetHeight(currentContext);
GWorldPtr newOffscreenGWorld;
QDErr err = NewGWorldFromPtr(&newOffscreenGWorld,
getQDPixelFormatForBitmapContext(currentContext), &offscreenBounds, 0, 0, 0,
static_cast<char*>(offscreenData), CGBitmapContextGetBytesPerRow(currentContext));
ASSERT(newOffscreenGWorld && !err);
if (!err) {
if (offscreenGWorld)
DisposeGWorld(offscreenGWorld);
offscreenGWorld = newOffscreenGWorld;
SetGWorld(offscreenGWorld, NULL);
port = offscreenGWorld;
nPort.qdPort.port = port;
boundsInWindow = [self bounds];
// Generate a QD origin based on the current affine transform for currentContext.
CGAffineTransform offscreenMatrix = CGContextGetCTM(currentContext);
CGPoint origin = {0,0};
CGPoint axisFlip = {1,1};
origin = CGPointApplyAffineTransform(origin, offscreenMatrix);
axisFlip = CGPointApplyAffineTransform(axisFlip, offscreenMatrix);
// Quartz bitmaps have origins at the bottom left, but the axes may be inverted, so handle that.
origin.x = offscreenBounds.left - origin.x * (axisFlip.x - origin.x);
origin.y = offscreenBounds.bottom + origin.y * (axisFlip.y - origin.y);
nPort.qdPort.portx = static_cast<int32>(-boundsInWindow.origin.x + origin.x);
nPort.qdPort.porty = static_cast<int32>(-boundsInWindow.origin.y - origin.y);
window.x = 0;
window.y = 0;
window.window = &nPort;
// Use the clip bounds from the context instead of the bounds we created
// from the window above.
getNPRect(CGRectOffset(CGContextGetClipBoundingBox(currentContext), -origin.x, origin.y), window.clipRect);
}
}
}
MacSetRectRgn(clipRegion,
window.clipRect.left + nPort.qdPort.portx, window.clipRect.top + nPort.qdPort.porty,
window.clipRect.right + nPort.qdPort.portx, window.clipRect.bottom + nPort.qdPort.porty);
// Clip to the dirty region if drawing to a window. When drawing to another bitmap context, do not clip.
if ([NSGraphicsContext currentContext] == [[self currentWindow] graphicsContext]) {
// Clip to dirty region so plug-in does not draw over already-drawn regions of the window that are
// not going to be redrawn this update. This forces plug-ins to play nice with z-index ordering.
if (forUpdate) {
RgnHandle viewClipRegion = NewRgn();
// Get list of dirty rects from the opaque ancestor -- WebKit does some tricks with invalidation and
// display to enable z-ordering for NSViews; a side-effect of this is that only the WebHTMLView
// knows about the true set of dirty rects.
NSView *opaqueAncestor = [self opaqueAncestor];
const NSRect *dirtyRects;
NSInteger dirtyRectCount, dirtyRectIndex;
[opaqueAncestor getRectsBeingDrawn:&dirtyRects count:&dirtyRectCount];
for (dirtyRectIndex = 0; dirtyRectIndex < dirtyRectCount; dirtyRectIndex++) {
NSRect dirtyRect = [self convertRect:dirtyRects[dirtyRectIndex] fromView:opaqueAncestor];
if (!NSEqualSizes(dirtyRect.size, NSZeroSize)) {
// Create a region for this dirty rect
RgnHandle dirtyRectRegion = NewRgn();
SetRectRgn(dirtyRectRegion, static_cast<short>(NSMinX(dirtyRect)), static_cast<short>(NSMinY(dirtyRect)), static_cast<short>(NSMaxX(dirtyRect)), static_cast<short>(NSMaxY(dirtyRect)));
// Union this dirty rect with the rest of the dirty rects
UnionRgn(viewClipRegion, dirtyRectRegion, viewClipRegion);
DisposeRgn(dirtyRectRegion);
}
}
// Intersect the dirty region with the clip region, so that we only draw over dirty parts
SectRgn(clipRegion, viewClipRegion, clipRegion);
DisposeRgn(viewClipRegion);
}
}
// Switch to the port and set it up.
SetPort(port);
PenNormal();
ForeColor(blackColor);
BackColor(whiteColor);
SetOrigin(nPort.qdPort.portx, nPort.qdPort.porty);
SetPortClipRegion(nPort.qdPort.port, clipRegion);
if (forUpdate) {
// AppKit may have tried to help us by doing a BeginUpdate.
// But the invalid region at that level didn't include AppKit's notion of what was not valid.
// We reset the port's visible region to counteract what BeginUpdate did.
SetPortVisibleRegion(nPort.qdPort.port, clipRegion);
InvalWindowRgn(windowRef, clipRegion);
}
qdPortState->forUpdate = forUpdate;
break;
}
#endif /* NP_NO_QUICKDRAW */
case NPDrawingModelCoreGraphics: {
if (![self canDraw]) {
portState = NULL;
break;
}
ASSERT([NSView focusView] == self);
CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
PortState_CG *cgPortState = (PortState_CG *)malloc(sizeof(PortState_CG));
portState = (PortState)cgPortState;
cgPortState->context = context;
#ifndef NP_NO_CARBON
if (eventModel != NPEventModelCocoa) {
// Update the plugin's window/context
nPort.cgPort.window = windowRef;
nPort.cgPort.context = context;
window.window = &nPort.cgPort;
}
#endif /* NP_NO_CARBON */
// Save current graphics context's state; will be restored by -restorePortState:
CGContextSaveGState(context);
// Clip to the dirty region if drawing to a window. When drawing to another bitmap context, do not clip.
if ([NSGraphicsContext currentContext] == [[self currentWindow] graphicsContext]) {
// Get list of dirty rects from the opaque ancestor -- WebKit does some tricks with invalidation and
// display to enable z-ordering for NSViews; a side-effect of this is that only the WebHTMLView
// knows about the true set of dirty rects.
NSView *opaqueAncestor = [self opaqueAncestor];
const NSRect *dirtyRects;
NSInteger count;
[opaqueAncestor getRectsBeingDrawn:&dirtyRects count:&count];
Vector<CGRect, 16> convertedDirtyRects;
convertedDirtyRects.resize(count);
for (int i = 0; i < count; ++i)
reinterpret_cast<NSRect&>(convertedDirtyRects[i]) = [self convertRect:dirtyRects[i] fromView:opaqueAncestor];
CGContextClipToRects(context, convertedDirtyRects.data(), count);
}
break;
}
case NPDrawingModelCoreAnimation:
// Just set the port state to a dummy value.
portState = (PortState)1;
break;
default:
ASSERT_NOT_REACHED();
portState = NULL;
break;
}
return portState;
}
- (PortState)saveAndSetNewPortState
{
return [self saveAndSetNewPortStateForUpdate:NO];
}
- (void)restorePortState:(PortState)portState
{
ASSERT([self currentWindow]);
ASSERT(portState);
switch (drawingModel) {
#ifndef NP_NO_QUICKDRAW
case NPDrawingModelQuickDraw: {
PortState_QD *qdPortState = (PortState_QD *)portState;
WindowRef windowRef = (WindowRef)[[self currentWindow] windowRef];
CGrafPtr port = GetWindowPort(windowRef);
SetPort(port);
if (qdPortState->forUpdate)
ValidWindowRgn(windowRef, qdPortState->clipRegion);
SetOrigin(qdPortState->oldOrigin.h, qdPortState->oldOrigin.v);
SetPortClipRegion(port, qdPortState->oldClipRegion);
if (qdPortState->forUpdate)
SetPortVisibleRegion(port, qdPortState->oldVisibleRegion);
DisposeRgn(qdPortState->oldClipRegion);
DisposeRgn(qdPortState->oldVisibleRegion);
DisposeRgn(qdPortState->clipRegion);
SetGWorld(qdPortState->oldPort, qdPortState->oldDevice);
break;
}
#endif /* NP_NO_QUICKDRAW */
case NPDrawingModelCoreGraphics: {
ASSERT([NSView focusView] == self);
CGContextRef context = ((PortState_CG *)portState)->context;
ASSERT(!nPort.cgPort.context || (context == nPort.cgPort.context));
CGContextRestoreGState(context);
break;
}
case NPDrawingModelCoreAnimation:
ASSERT(portState == (PortState)1);
break;
default:
ASSERT_NOT_REACHED();
break;
}
}
- (BOOL)sendEvent:(void*)event isDrawRect:(BOOL)eventIsDrawRect
{
if (![self window])
return NO;
ASSERT(event);
if (!_isStarted)
return NO;
ASSERT([_pluginPackage.get() pluginFuncs]->event);
// Make sure we don't call NPP_HandleEvent while we're inside NPP_SetWindow.
// We probably don't want more general reentrancy protection; we are really
// protecting only against this one case, which actually comes up when
// you first install the SVG viewer plug-in.
if (inSetWindow)
return NO;
Frame* frame = core([self webFrame]);
if (!frame)
return NO;
Page* page = frame->page();
if (!page)
return NO;
// Can only send drawRect (updateEvt) to CoreGraphics plugins when actually drawing
ASSERT((drawingModel != NPDrawingModelCoreGraphics) || !eventIsDrawRect || [NSView focusView] == self);
PortState portState = NULL;
if (isDrawingModelQuickDraw(drawingModel) || (drawingModel != NPDrawingModelCoreAnimation && eventIsDrawRect)) {
// In CoreGraphics mode, the port state only needs to be saved/set when redrawing the plug-in view.
// The plug-in is not allowed to draw at any other time.
portState = [self saveAndSetNewPortStateForUpdate:eventIsDrawRect];
// We may have changed the window, so inform the plug-in.
[self setWindowIfNecessary];
}
#if !defined(NDEBUG) && !defined(NP_NO_QUICKDRAW)
// Draw green to help debug.
// If we see any green we know something's wrong.
// Note that PaintRect() only works for QuickDraw plugins; otherwise the current QD port is undefined.
if (isDrawingModelQuickDraw(drawingModel) && eventIsDrawRect) {
ForeColor(greenColor);
const ::Rect bigRect = { -10000, -10000, 10000, 10000 };
PaintRect(&bigRect);
ForeColor(blackColor);
}
#endif
// Temporarily retain self in case the plug-in view is released while sending an event.
[[self retain] autorelease];
BOOL acceptedEvent;
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
acceptedEvent = [_pluginPackage.get() pluginFuncs]->event(plugin, event);
}
[self didCallPlugInFunction];
if (portState) {
if ([self currentWindow])
[self restorePortState:portState];
if (portState != (PortState)1)
free(portState);
}
return acceptedEvent;
}
- (void)windowFocusChanged:(BOOL)hasFocus
{
_eventHandler->windowFocusChanged(hasFocus);
}
- (void)sendDrawRectEvent:(NSRect)rect
{
ASSERT(_eventHandler);
CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]);
_eventHandler->drawRect(context, rect);
}
- (void)stopTimers
{
[super stopTimers];
if (_eventHandler)
_eventHandler->stopTimers();
if (!timers)
return;
HashMap<uint32, PluginTimer*>::const_iterator end = timers->end();
for (HashMap<uint32, PluginTimer*>::const_iterator it = timers->begin(); it != end; ++it) {
PluginTimer* timer = it->second;
timer->stop();
}
}
- (void)startTimers
{
[super startTimers];
// If the plugin is completely obscured (scrolled out of view, for example), then we will
// send null events at a reduced rate.
_eventHandler->startTimers(_isCompletelyObscured);
if (!timers)
return;
HashMap<uint32, PluginTimer*>::const_iterator end = timers->end();
for (HashMap<uint32, PluginTimer*>::const_iterator it = timers->begin(); it != end; ++it) {
PluginTimer* timer = it->second;
ASSERT(!timer->isActive());
timer->start(_isCompletelyObscured);
}
}
- (void)focusChanged
{
// We need to null check the event handler here because
// the plug-in view can resign focus after it's been stopped
// and the event handler has been deleted.
if (_eventHandler)
_eventHandler->focusChanged(_hasFocus);
}
- (void)mouseDown:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->mouseDown(theEvent);
}
- (void)mouseUp:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->mouseUp(theEvent);
}
- (void)mouseEntered:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->mouseEntered(theEvent);
}
- (void)mouseExited:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->mouseExited(theEvent);
// Set cursor back to arrow cursor. Because NSCursor doesn't know about changes that the plugin made, we could get confused about what we think the
// current cursor is otherwise. Therefore we have no choice but to unconditionally reset the cursor when the mouse exits the plugin.
[[NSCursor arrowCursor] set];
}
// We can't name this method mouseMoved because we don't want to override
// the NSView mouseMoved implementation.
- (void)handleMouseMoved:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->mouseMoved(theEvent);
}
- (void)mouseDragged:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->mouseDragged(theEvent);
}
- (void)scrollWheel:(NSEvent *)theEvent
{
if (!_isStarted) {
[super scrollWheel:theEvent];
return;
}
if (!_eventHandler->scrollWheel(theEvent))
[super scrollWheel:theEvent];
}
- (void)keyUp:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->keyUp(theEvent);
}
- (void)keyDown:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->keyDown(theEvent);
}
- (void)flagsChanged:(NSEvent *)theEvent
{
if (!_isStarted)
return;
_eventHandler->flagsChanged(theEvent);
}
- (void)sendModifierEventWithKeyCode:(int)keyCode character:(char)character
{
if (!_isStarted)
return;
_eventHandler->syntheticKeyDownWithCommandModifier(keyCode, character);
}
#pragma mark WEB_NETSCAPE_PLUGIN
- (BOOL)isNewWindowEqualToOldWindow
{
if (window.x != lastSetWindow.x)
return NO;
if (window.y != lastSetWindow.y)
return NO;
if (window.width != lastSetWindow.width)
return NO;
if (window.height != lastSetWindow.height)
return NO;
if (window.clipRect.top != lastSetWindow.clipRect.top)
return NO;
if (window.clipRect.left != lastSetWindow.clipRect.left)
return NO;
if (window.clipRect.bottom != lastSetWindow.clipRect.bottom)
return NO;
if (window.clipRect.right != lastSetWindow.clipRect.right)
return NO;
if (window.type != lastSetWindow.type)
return NO;
switch (drawingModel) {
#ifndef NP_NO_QUICKDRAW
case NPDrawingModelQuickDraw:
if (nPort.qdPort.portx != lastSetPort.qdPort.portx)
return NO;
if (nPort.qdPort.porty != lastSetPort.qdPort.porty)
return NO;
if (nPort.qdPort.port != lastSetPort.qdPort.port)
return NO;
break;
#endif /* NP_NO_QUICKDRAW */
case NPDrawingModelCoreGraphics:
if (nPort.cgPort.window != lastSetPort.cgPort.window)
return NO;
if (nPort.cgPort.context != lastSetPort.cgPort.context)
return NO;
break;
case NPDrawingModelCoreAnimation:
if (window.window != lastSetWindow.window)
return NO;
break;
default:
ASSERT_NOT_REACHED();
break;
}
return YES;
}
-(void)tellQuickTimeToChill
{
#ifndef NP_NO_QUICKDRAW
ASSERT(isDrawingModelQuickDraw(drawingModel));
// Make a call to the secret QuickDraw API that makes QuickTime calm down.
WindowRef windowRef = (WindowRef)[[self window] windowRef];
if (!windowRef) {
return;
}
CGrafPtr port = GetWindowPort(windowRef);
::Rect bounds;
GetPortBounds(port, &bounds);
WKCallDrawingNotification(port, &bounds);
#endif /* NP_NO_QUICKDRAW */
}
- (void)updateAndSetWindow
{
// A plug-in can only update if it's (1) already been started (2) isn't stopped
// and (3) is able to draw on-screen. To meet condition (3) the plug-in must not
// be hidden and be attached to a window. There are two exceptions to this rule:
//
// Exception 1: QuickDraw plug-ins must be manually told when to stop writing
// bits to the window backing store, thus to do so requires a new call to
// NPP_SetWindow() with an empty NPWindow struct.
//
// Exception 2: CoreGraphics plug-ins expect to have their drawable area updated
// when they are moved to a background tab, via a NPP_SetWindow call. This is
// accomplished by allowing -saveAndSetNewPortStateForUpdate to "clip-out" the window's
// clipRect. Flash is curently an exception to this. See 6453738.
//
if (!_isStarted)
return;
#ifdef NP_NO_QUICKDRAW
if (![self canDraw])
return;
#else
if (drawingModel == NPDrawingModelQuickDraw)
[self tellQuickTimeToChill];
else if (drawingModel == NPDrawingModelCoreGraphics && ![self canDraw] && _isFlash) {
// The Flash plug-in does not expect an NPP_SetWindow call from WebKit in this case.
// See Exception 2 above.
return;
}
#endif // NP_NO_QUICKDRAW
BOOL didLockFocus = [NSView focusView] != self && [self lockFocusIfCanDraw];
PortState portState = [self saveAndSetNewPortState];
if (portState) {
[self setWindowIfNecessary];
[self restorePortState:portState];
if (portState != (PortState)1)
free(portState);
} else if (drawingModel == NPDrawingModelCoreGraphics)
[self setWindowIfNecessary];
if (didLockFocus)
[self unlockFocus];
}
- (void)setWindowIfNecessary
{
if (!_isStarted)
return;
if (![self isNewWindowEqualToOldWindow]) {
// Make sure we don't call NPP_HandleEvent while we're inside NPP_SetWindow.
// We probably don't want more general reentrancy protection; we are really
// protecting only against this one case, which actually comes up when
// you first install the SVG viewer plug-in.
NPError npErr;
ASSERT(!inSetWindow);
inSetWindow = YES;
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
npErr = [_pluginPackage.get() pluginFuncs]->setwindow(plugin, &window);
}
[self didCallPlugInFunction];
inSetWindow = NO;
#ifndef NDEBUG
switch (drawingModel) {
#ifndef NP_NO_QUICKDRAW
case NPDrawingModelQuickDraw:
LOG(Plugins, "NPP_SetWindow (QuickDraw): %d, port=0x%08x, window.x:%d window.y:%d window.width:%d window.height:%d",
npErr, (int)nPort.qdPort.port, (int)window.x, (int)window.y, (int)window.width, (int)window.height);
break;
#endif /* NP_NO_QUICKDRAW */
case NPDrawingModelCoreGraphics:
LOG(Plugins, "NPP_SetWindow (CoreGraphics): %d, window=%p, context=%p, window.x:%d window.y:%d window.width:%d window.height:%d window.clipRect size:%dx%d",
npErr, nPort.cgPort.window, nPort.cgPort.context, (int)window.x, (int)window.y, (int)window.width, (int)window.height,
window.clipRect.right - window.clipRect.left, window.clipRect.bottom - window.clipRect.top);
break;
case NPDrawingModelCoreAnimation:
LOG(Plugins, "NPP_SetWindow (CoreAnimation): %d, window=%p window.x:%d window.y:%d window.width:%d window.height:%d",
npErr, window.window, nPort.cgPort.context, (int)window.x, (int)window.y, (int)window.width, (int)window.height);
break;
default:
ASSERT_NOT_REACHED();
break;
}
#endif /* !defined(NDEBUG) */
lastSetWindow = window;
lastSetPort = nPort;
}
}
+ (void)setCurrentPluginView:(WebNetscapePluginView *)view
{
currentPluginView = view;
}
+ (WebNetscapePluginView *)currentPluginView
{
return currentPluginView;
}
- (BOOL)createPlugin
{
// Open the plug-in package so it remains loaded while our plugin uses it
[_pluginPackage.get() open];
// Initialize drawingModel to an invalid value so that we can detect when the plugin does not specify a drawingModel
drawingModel = (NPDrawingModel)-1;
// Initialize eventModel to an invalid value so that we can detect when the plugin does not specify an event model.
eventModel = (NPEventModel)-1;
NPError npErr = [self _createPlugin];
if (npErr != NPERR_NO_ERROR) {
LOG_ERROR("NPP_New failed with error: %d", npErr);
[self _destroyPlugin];
[_pluginPackage.get() close];
return NO;
}
if (drawingModel == (NPDrawingModel)-1) {
#ifndef NP_NO_QUICKDRAW
// Default to QuickDraw if the plugin did not specify a drawing model.
drawingModel = NPDrawingModelQuickDraw;
#else
// QuickDraw is not available, so we can't default to it. Instead, default to CoreGraphics.
drawingModel = NPDrawingModelCoreGraphics;
#endif
}
if (eventModel == (NPEventModel)-1) {
// If the plug-in did not specify a drawing model we default to Carbon when it is available.
#ifndef NP_NO_CARBON
eventModel = NPEventModelCarbon;
#else
eventModel = NPEventModelCocoa;
#endif // NP_NO_CARBON
}
#ifndef NP_NO_CARBON
if (eventModel == NPEventModelCocoa && isDrawingModelQuickDraw(drawingModel)) {
LOG(Plugins, "Plugin can't use use Cocoa event model with QuickDraw drawing model: %@", _pluginPackage.get());
[self _destroyPlugin];
[_pluginPackage.get() close];
return NO;
}
#endif // NP_NO_CARBON
#ifndef BUILDING_ON_TIGER
if (drawingModel == NPDrawingModelCoreAnimation) {
void *value = 0;
if ([_pluginPackage.get() pluginFuncs]->getvalue(plugin, NPPVpluginCoreAnimationLayer, &value) == NPERR_NO_ERROR && value) {
// The plug-in gives us a retained layer.
_pluginLayer.adoptNS((CALayer *)value);
[self setWantsLayer:YES];
LOG(Plugins, "%@ is using Core Animation drawing model with layer %@", _pluginPackage.get(), _pluginLayer.get());
}
ASSERT(_pluginLayer);
}
#endif
// Create the event handler
_eventHandler.set(WebNetscapePluginEventHandler::create(self));
return YES;
}
#ifndef BUILDING_ON_TIGER
- (void)setLayer:(CALayer *)newLayer
{
[super setLayer:newLayer];
if (newLayer && _pluginLayer) {
_pluginLayer.get().frame = [newLayer frame];
_pluginLayer.get().autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
[newLayer addSublayer:_pluginLayer.get()];
}
}
#endif
- (void)loadStream
{
if ([self _shouldCancelSrcStream])
return;
if (_loadManually) {
[self _redeliverStream];
return;
}
// If the OBJECT/EMBED tag has no SRC, the URL is passed to us as "".
// Check for this and don't start a load in this case.
if (_sourceURL && ![_sourceURL.get() _web_isEmpty]) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_sourceURL.get()];
[request _web_setHTTPReferrer:core([self webFrame])->loader()->outgoingReferrer()];
[self loadRequest:request inTarget:nil withNotifyData:nil sendNotification:NO];
}
}
- (BOOL)shouldStop
{
// If we're already calling a plug-in function, do not call NPP_Destroy(). The plug-in function we are calling
// may assume that its instance->pdata, or other memory freed by NPP_Destroy(), is valid and unchanged until said
// plugin-function returns.
// See <rdar://problem/4480737>.
if (pluginFunctionCallDepth > 0) {
shouldStopSoon = YES;
return NO;
}
return YES;
}
- (void)destroyPlugin
{
// To stop active streams it's necessary to invoke stop() on a copy
// of streams. This is because calling WebNetscapePluginStream::stop() also has the side effect
// of removing a stream from this hash set.
Vector<RefPtr<WebNetscapePluginStream> > streamsCopy;
copyToVector(streams, streamsCopy);
for (size_t i = 0; i < streamsCopy.size(); i++)
streamsCopy[i]->stop();
[[_pendingFrameLoads.get() allKeys] makeObjectsPerformSelector:@selector(_setInternalLoadDelegate:) withObject:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self];
// Setting the window type to 0 ensures that NPP_SetWindow will be called if the plug-in is restarted.
lastSetWindow.type = (NPWindowType)0;
#ifndef BUILDING_ON_TIGER
_pluginLayer = 0;
#endif
[self _destroyPlugin];
[_pluginPackage.get() close];
_eventHandler.clear();
}
- (NPEventModel)eventModel
{
return eventModel;
}
- (NPP)plugin
{
return plugin;
}
- (void)setAttributeKeys:(NSArray *)keys andValues:(NSArray *)values
{
ASSERT([keys count] == [values count]);
// Convert the attributes to 2 C string arrays.
// These arrays are passed to NPP_New, but the strings need to be
// modifiable and live the entire life of the plugin.
// The Java plug-in requires the first argument to be the base URL
if ([_MIMEType.get() isEqualToString:@"application/x-java-applet"]) {
cAttributes = (char **)malloc(([keys count] + 1) * sizeof(char *));
cValues = (char **)malloc(([values count] + 1) * sizeof(char *));
cAttributes[0] = strdup("DOCBASE");
cValues[0] = strdup([_baseURL.get() _web_URLCString]);
argsCount++;
} else {
cAttributes = (char **)malloc([keys count] * sizeof(char *));
cValues = (char **)malloc([values count] * sizeof(char *));
}
BOOL isWMP = [[[_pluginPackage.get() bundle] bundleIdentifier] isEqualToString:@"com.microsoft.WMP.defaultplugin"];
unsigned i;
unsigned count = [keys count];
for (i = 0; i < count; i++) {
NSString *key = [keys objectAtIndex:i];
NSString *value = [values objectAtIndex:i];
if ([key _webkit_isCaseInsensitiveEqualToString:@"height"]) {
specifiedHeight = [value intValue];
} else if ([key _webkit_isCaseInsensitiveEqualToString:@"width"]) {
specifiedWidth = [value intValue];
}
// Avoid Window Media Player crash when these attributes are present.
if (isWMP && ([key _webkit_isCaseInsensitiveEqualToString:@"SAMIStyle"] || [key _webkit_isCaseInsensitiveEqualToString:@"SAMILang"])) {
continue;
}
cAttributes[argsCount] = strdup([key UTF8String]);
cValues[argsCount] = strdup([value UTF8String]);
LOG(Plugins, "%@ = %@", key, value);
argsCount++;
}
}
- (uint32)checkIfAllowedToLoadURL:(const char*)urlCString frame:(const char*)frameNameCString
callbackFunc:(void (*)(NPP npp, uint32 checkID, NPBool allowed, void* context))callbackFunc
context:(void*)context
{
if (!_containerChecksInProgress)
_containerChecksInProgress = [[NSMutableDictionary alloc] init];
NSString *frameName = frameNameCString ? [NSString stringWithCString:frameNameCString encoding:NSISOLatin1StringEncoding] : nil;
++_currentContainerCheckRequestID;
WebNetscapeContainerCheckContextInfo *contextInfo = [[WebNetscapeContainerCheckContextInfo alloc] initWithCheckRequestID:_currentContainerCheckRequestID
callbackFunc:callbackFunc
context:context];
WebPluginContainerCheck *check = [WebPluginContainerCheck checkWithRequest:[self requestWithURLCString:urlCString]
target:frameName
resultObject:self
selector:@selector(_containerCheckResult:contextInfo:)
controller:self
contextInfo:contextInfo];
[contextInfo release];
[_containerChecksInProgress setObject:check forKey:[NSNumber numberWithInt:_currentContainerCheckRequestID]];
[check start];
return _currentContainerCheckRequestID;
}
- (void)_containerCheckResult:(PolicyAction)policy contextInfo:(id)contextInfo
{
ASSERT([contextInfo isKindOfClass:[WebNetscapeContainerCheckContextInfo class]]);
void (*pluginCallback)(NPP npp, uint32, NPBool, void*) = [contextInfo callback];
if (!pluginCallback) {
ASSERT_NOT_REACHED();
return;
}
pluginCallback([self plugin], [contextInfo checkRequestID], (policy == PolicyUse), [contextInfo context]);
}
- (void)cancelCheckIfAllowedToLoadURL:(uint32)checkID
{
WebPluginContainerCheck *check = (WebPluginContainerCheck *)[_containerChecksInProgress objectForKey:[NSNumber numberWithInt:checkID]];
if (!check)
return;
[check cancel];
[_containerChecksInProgress removeObjectForKey:[NSNumber numberWithInt:checkID]];
}
// WebPluginContainerCheck automatically calls this method after invoking our _containerCheckResult: selector.
// It works this way because calling -[WebPluginContainerCheck cancel] allows it to do it's teardown process.
- (void)_webPluginContainerCancelCheckIfAllowedToLoadRequest:(id)webPluginContainerCheck
{
ASSERT([webPluginContainerCheck isKindOfClass:[WebPluginContainerCheck class]]);
WebPluginContainerCheck *check = (WebPluginContainerCheck *)webPluginContainerCheck;
ASSERT([check contextInfo] && [[check contextInfo] isKindOfClass:[WebNetscapeContainerCheckContextInfo class]]);
[self cancelCheckIfAllowedToLoadURL:[[check contextInfo] checkRequestID]];
}
#ifdef BUILDING_ON_TIGER
// The Tiger compiler requires these two methods be present. Otherwise it doesn't think WebNetscapePluginView
// conforms to the WebPluginContainerCheckController protocol.
- (WebView *)webView
{
return [super webView];
}
- (WebFrame *)webFrame
{
return [super webFrame];
}
#endif
#pragma mark NSVIEW
- (id)initWithFrame:(NSRect)frame
pluginPackage:(WebNetscapePluginPackage *)pluginPackage
URL:(NSURL *)URL
baseURL:(NSURL *)baseURL
MIMEType:(NSString *)MIME
attributeKeys:(NSArray *)keys
attributeValues:(NSArray *)values
loadManually:(BOOL)loadManually
element:(PassRefPtr<WebCore::HTMLPlugInElement>)element
{
self = [super initWithFrame:frame pluginPackage:pluginPackage URL:URL baseURL:baseURL MIMEType:MIME attributeKeys:keys attributeValues:values loadManually:loadManually element:element];
if (!self)
return nil;
_pendingFrameLoads.adoptNS([[NSMutableDictionary alloc] init]);
// load the plug-in if it is not already loaded
if (![pluginPackage load]) {
[self release];
return nil;
}
return self;
}
- (id)initWithFrame:(NSRect)frame
{
ASSERT_NOT_REACHED();
return nil;
}
- (void)fini
{
#ifndef NP_NO_QUICKDRAW
if (offscreenGWorld)
DisposeGWorld(offscreenGWorld);
#endif
for (unsigned i = 0; i < argsCount; i++) {
free(cAttributes[i]);
free(cValues[i]);
}
free(cAttributes);
free(cValues);
ASSERT(!_eventHandler);
if (timers) {
deleteAllValues(*timers);
delete timers;
}
[_containerChecksInProgress release];
}
- (void)disconnectStream:(WebNetscapePluginStream*)stream
{
streams.remove(stream);
}
- (void)dealloc
{
ASSERT(!_isStarted);
ASSERT(!plugin);
[self fini];
[super dealloc];
}
- (void)finalize
{
ASSERT_MAIN_THREAD();
ASSERT(!_isStarted);
[self fini];
[super finalize];
}
- (void)drawRect:(NSRect)rect
{
if (drawingModel == NPDrawingModelCoreAnimation)
return;
if (!_isStarted)
return;
if ([NSGraphicsContext currentContextDrawingToScreen])
[self sendDrawRectEvent:rect];
else {
NSBitmapImageRep *printedPluginBitmap = [self _printedPluginBitmap];
if (printedPluginBitmap) {
// Flip the bitmap before drawing because the QuickDraw port is flipped relative
// to this view.
CGContextRef cgContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState(cgContext);
NSRect bounds = [self bounds];
CGContextTranslateCTM(cgContext, 0.0f, NSHeight(bounds));
CGContextScaleCTM(cgContext, 1.0f, -1.0f);
[printedPluginBitmap drawInRect:bounds];
CGContextRestoreGState(cgContext);
}
}
}
- (NPObject *)createPluginScriptableObject
{
if (![_pluginPackage.get() pluginFuncs]->getvalue || !_isStarted)
return NULL;
NPObject *value = NULL;
NPError error;
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
error = [_pluginPackage.get() pluginFuncs]->getvalue(plugin, NPPVpluginScriptableNPObject, &value);
}
[self didCallPlugInFunction];
if (error != NPERR_NO_ERROR)
return NULL;
return value;
}
- (void)willCallPlugInFunction
{
ASSERT(plugin);
// Could try to prevent infinite recursion here, but it's probably not worth the effort.
pluginFunctionCallDepth++;
}
- (void)didCallPlugInFunction
{
ASSERT(pluginFunctionCallDepth > 0);
pluginFunctionCallDepth--;
// If -stop was called while we were calling into a plug-in function, and we're no longer
// inside a plug-in function, stop now.
if (pluginFunctionCallDepth == 0 && shouldStopSoon) {
shouldStopSoon = NO;
[self stop];
}
}
-(void)pluginView:(NSView *)pluginView receivedResponse:(NSURLResponse *)response
{
ASSERT(_loadManually);
ASSERT(!_manualStream);
_manualStream = WebNetscapePluginStream::create(core([self webFrame])->loader());
}
- (void)pluginView:(NSView *)pluginView receivedData:(NSData *)data
{
ASSERT(_loadManually);
ASSERT(_manualStream);
_dataLengthReceived += [data length];
if (!_isStarted)
return;
if (!_manualStream->plugin()) {
// Check if the load should be cancelled
if ([self _shouldCancelSrcStream]) {
NSURLResponse *response = [[self dataSource] response];
NSError *error = [[NSError alloc] _initWithPluginErrorCode:WebKitErrorPlugInWillHandleLoad
contentURL:[response URL]
pluginPageURL:nil
pluginName:nil // FIXME: Get this from somewhere
MIMEType:[response MIMEType]];
[[self dataSource] _documentLoader]->cancelMainResourceLoad(error);
[error release];
return;
}
_manualStream->setRequestURL([[[self dataSource] request] URL]);
_manualStream->setPlugin([self plugin]);
ASSERT(_manualStream->plugin());
_manualStream->startStreamWithResponse([[self dataSource] response]);
}
if (_manualStream->plugin())
_manualStream->didReceiveData(0, static_cast<const char *>([data bytes]), [data length]);
}
- (void)pluginView:(NSView *)pluginView receivedError:(NSError *)error
{
ASSERT(_loadManually);
_error = error;
if (!_isStarted) {
return;
}
_manualStream->destroyStreamWithError(error);
}
- (void)pluginViewFinishedLoading:(NSView *)pluginView
{
ASSERT(_loadManually);
ASSERT(_manualStream);
if (_isStarted)
_manualStream->didFinishLoading(0);
}
- (NSTextInputContext *)inputContext
{
return nil;
}
@end
@implementation WebNetscapePluginView (WebNPPCallbacks)
- (void)evaluateJavaScriptPluginRequest:(WebPluginRequest *)JSPluginRequest
{
// FIXME: Is this isStarted check needed here? evaluateJavaScriptPluginRequest should not be called
// if we are stopped since this method is called after a delay and we call
// cancelPreviousPerformRequestsWithTarget inside of stop.
if (!_isStarted) {
return;
}
NSURL *URL = [[JSPluginRequest request] URL];
NSString *JSString = [URL _webkit_scriptIfJavaScriptURL];
ASSERT(JSString);
NSString *result = [[self webFrame] _stringByEvaluatingJavaScriptFromString:JSString forceUserGesture:[JSPluginRequest isCurrentEventUserGesture]];
// Don't continue if stringByEvaluatingJavaScriptFromString caused the plug-in to stop.
if (!_isStarted) {
return;
}
if ([JSPluginRequest frameName] != nil) {
// FIXME: If the result is a string, we probably want to put that string into the frame.
if ([JSPluginRequest sendNotification]) {
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
[_pluginPackage.get() pluginFuncs]->urlnotify(plugin, [URL _web_URLCString], NPRES_DONE, [JSPluginRequest notifyData]);
}
[self didCallPlugInFunction];
}
} else if ([result length] > 0) {
// Don't call NPP_NewStream and other stream methods if there is no JS result to deliver. This is what Mozilla does.
NSData *JSData = [result dataUsingEncoding:NSUTF8StringEncoding];
RefPtr<WebNetscapePluginStream> stream = WebNetscapePluginStream::create([NSURLRequest requestWithURL:URL], plugin, [JSPluginRequest sendNotification], [JSPluginRequest notifyData]);
RetainPtr<NSURLResponse> response(AdoptNS, [[NSURLResponse alloc] initWithURL:URL
MIMEType:@"text/plain"
expectedContentLength:[JSData length]
textEncodingName:nil]);
stream->startStreamWithResponse(response.get());
stream->didReceiveData(0, static_cast<const char*>([JSData bytes]), [JSData length]);
stream->didFinishLoading(0);
}
}
- (void)webFrame:(WebFrame *)webFrame didFinishLoadWithReason:(NPReason)reason
{
ASSERT(_isStarted);
WebPluginRequest *pluginRequest = [_pendingFrameLoads.get() objectForKey:webFrame];
ASSERT(pluginRequest != nil);
ASSERT([pluginRequest sendNotification]);
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
[_pluginPackage.get() pluginFuncs]->urlnotify(plugin, [[[pluginRequest request] URL] _web_URLCString], reason, [pluginRequest notifyData]);
}
[self didCallPlugInFunction];
[_pendingFrameLoads.get() removeObjectForKey:webFrame];
[webFrame _setInternalLoadDelegate:nil];
}
- (void)webFrame:(WebFrame *)webFrame didFinishLoadWithError:(NSError *)error
{
NPReason reason = NPRES_DONE;
if (error != nil)
reason = WebNetscapePluginStream::reasonForError(error);
[self webFrame:webFrame didFinishLoadWithReason:reason];
}
- (void)loadPluginRequest:(WebPluginRequest *)pluginRequest
{
NSURLRequest *request = [pluginRequest request];
NSString *frameName = [pluginRequest frameName];
WebFrame *frame = nil;
NSURL *URL = [request URL];
NSString *JSString = [URL _webkit_scriptIfJavaScriptURL];
ASSERT(frameName || JSString);
if (frameName) {
// FIXME - need to get rid of this window creation which
// bypasses normal targeted link handling
frame = kit(core([self webFrame])->loader()->findFrameForNavigation(frameName));
if (frame == nil) {
WebView *currentWebView = [self webView];
NSDictionary *features = [[NSDictionary alloc] init];
WebView *newWebView = [[currentWebView _UIDelegateForwarder] webView:currentWebView
createWebViewWithRequest:nil
windowFeatures:features];
[features release];
if (!newWebView) {
if ([pluginRequest sendNotification]) {
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
[_pluginPackage.get() pluginFuncs]->urlnotify(plugin, [[[pluginRequest request] URL] _web_URLCString], NPERR_GENERIC_ERROR, [pluginRequest notifyData]);
}
[self didCallPlugInFunction];
}
return;
}
frame = [newWebView mainFrame];
core(frame)->tree()->setName(frameName);
[[newWebView _UIDelegateForwarder] webViewShow:newWebView];
}
}
if (JSString) {
ASSERT(frame == nil || [self webFrame] == frame);
[self evaluateJavaScriptPluginRequest:pluginRequest];
} else {
[frame loadRequest:request];
if ([pluginRequest sendNotification]) {
// Check if another plug-in view or even this view is waiting for the frame to load.
// If it is, tell it that the load was cancelled because it will be anyway.
WebNetscapePluginView *view = [frame _internalLoadDelegate];
if (view != nil) {
ASSERT([view isKindOfClass:[WebNetscapePluginView class]]);
[view webFrame:frame didFinishLoadWithReason:NPRES_USER_BREAK];
}
[_pendingFrameLoads.get() _webkit_setObject:pluginRequest forUncopiedKey:frame];
[frame _setInternalLoadDelegate:self];
}
}
}
- (NPError)loadRequest:(NSMutableURLRequest *)request inTarget:(const char *)cTarget withNotifyData:(void *)notifyData sendNotification:(BOOL)sendNotification
{
NSURL *URL = [request URL];
if (!URL)
return NPERR_INVALID_URL;
// Don't allow requests to be loaded when the document loader is stopping all loaders.
if ([[self dataSource] _documentLoader]->isStopping())
return NPERR_GENERIC_ERROR;
NSString *target = nil;
if (cTarget) {
// Find the frame given the target string.
target = [NSString stringWithCString:cTarget encoding:NSISOLatin1StringEncoding];
}
WebFrame *frame = [self webFrame];
// don't let a plugin start any loads if it is no longer part of a document that is being
// displayed unless the loads are in the same frame as the plugin.
if ([[self dataSource] _documentLoader] != core([self webFrame])->loader()->activeDocumentLoader() &&
(!cTarget || [frame findFrameNamed:target] != frame)) {
return NPERR_GENERIC_ERROR;
}
NSString *JSString = [URL _webkit_scriptIfJavaScriptURL];
if (JSString != nil) {
if (![[[self webView] preferences] isJavaScriptEnabled]) {
// Return NPERR_GENERIC_ERROR if JS is disabled. This is what Mozilla does.
return NPERR_GENERIC_ERROR;
} else if (cTarget == NULL && _mode == NP_FULL) {
// Don't allow a JavaScript request from a standalone plug-in that is self-targetted
// because this can cause the user to be redirected to a blank page (3424039).
return NPERR_INVALID_PARAM;
}
} else {
if (!FrameLoader::canLoad(URL, String(), core([self webFrame])->document()))
return NPERR_GENERIC_ERROR;
}
if (cTarget || JSString) {
// Make when targetting a frame or evaluating a JS string, perform the request after a delay because we don't
// want to potentially kill the plug-in inside of its URL request.
if (JSString && target && [frame findFrameNamed:target] != frame) {
// For security reasons, only allow JS requests to be made on the frame that contains the plug-in.
return NPERR_INVALID_PARAM;
}
bool currentEventIsUserGesture = false;
if (_eventHandler)
currentEventIsUserGesture = _eventHandler->currentEventIsUserGesture();
WebPluginRequest *pluginRequest = [[WebPluginRequest alloc] initWithRequest:request
frameName:target
notifyData:notifyData
sendNotification:sendNotification
didStartFromUserGesture:currentEventIsUserGesture];
[self performSelector:@selector(loadPluginRequest:) withObject:pluginRequest afterDelay:0];
[pluginRequest release];
} else {
RefPtr<WebNetscapePluginStream> stream = WebNetscapePluginStream::create(request, plugin, sendNotification, notifyData);
streams.add(stream.get());
stream->start();
}
return NPERR_NO_ERROR;
}
-(NPError)getURLNotify:(const char *)URLCString target:(const char *)cTarget notifyData:(void *)notifyData
{
LOG(Plugins, "NPN_GetURLNotify: %s target: %s", URLCString, cTarget);
NSMutableURLRequest *request = [self requestWithURLCString:URLCString];
return [self loadRequest:request inTarget:cTarget withNotifyData:notifyData sendNotification:YES];
}
-(NPError)getURL:(const char *)URLCString target:(const char *)cTarget
{
LOG(Plugins, "NPN_GetURL: %s target: %s", URLCString, cTarget);
NSMutableURLRequest *request = [self requestWithURLCString:URLCString];
return [self loadRequest:request inTarget:cTarget withNotifyData:NULL sendNotification:NO];
}
- (NPError)_postURL:(const char *)URLCString
target:(const char *)target
len:(UInt32)len
buf:(const char *)buf
file:(NPBool)file
notifyData:(void *)notifyData
sendNotification:(BOOL)sendNotification
allowHeaders:(BOOL)allowHeaders
{
if (!URLCString || !len || !buf) {
return NPERR_INVALID_PARAM;
}
NSData *postData = nil;
if (file) {
// If we're posting a file, buf is either a file URL or a path to the file.
NSString *bufString = (NSString *)CFStringCreateWithCString(kCFAllocatorDefault, buf, kCFStringEncodingWindowsLatin1);
if (!bufString) {
return NPERR_INVALID_PARAM;
}
NSURL *fileURL = [NSURL _web_URLWithDataAsString:bufString];
NSString *path;
if ([fileURL isFileURL]) {
path = [fileURL path];
} else {
path = bufString;
}
postData = [NSData dataWithContentsOfFile:[path _webkit_fixedCarbonPOSIXPath]];
CFRelease(bufString);
if (!postData) {
return NPERR_FILE_NOT_FOUND;
}
} else {
postData = [NSData dataWithBytes:buf length:len];
}
if ([postData length] == 0) {
return NPERR_INVALID_PARAM;
}
NSMutableURLRequest *request = [self requestWithURLCString:URLCString];
[request setHTTPMethod:@"POST"];
if (allowHeaders) {
if ([postData _web_startsWithBlankLine]) {
postData = [postData subdataWithRange:NSMakeRange(1, [postData length] - 1)];
} else {
NSInteger location = [postData _web_locationAfterFirstBlankLine];
if (location != NSNotFound) {
// If the blank line is somewhere in the middle of postData, everything before is the header.
NSData *headerData = [postData subdataWithRange:NSMakeRange(0, location)];
NSMutableDictionary *header = [headerData _webkit_parseRFC822HeaderFields];
unsigned dataLength = [postData length] - location;
// Sometimes plugins like to set Content-Length themselves when they post,
// but WebFoundation does not like that. So we will remove the header
// and instead truncate the data to the requested length.
NSString *contentLength = [header objectForKey:@"Content-Length"];
if (contentLength != nil)
dataLength = MIN((unsigned)[contentLength intValue], dataLength);
[header removeObjectForKey:@"Content-Length"];
if ([header count] > 0) {
[request setAllHTTPHeaderFields:header];
}
// Everything after the blank line is the actual content of the POST.
postData = [postData subdataWithRange:NSMakeRange(location, dataLength)];
}
}
if ([postData length] == 0) {
return NPERR_INVALID_PARAM;
}
}
// Plug-ins expect to receive uncached data when doing a POST (3347134).
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setHTTPBody:postData];
return [self loadRequest:request inTarget:target withNotifyData:notifyData sendNotification:sendNotification];
}
- (NPError)postURLNotify:(const char *)URLCString
target:(const char *)target
len:(UInt32)len
buf:(const char *)buf
file:(NPBool)file
notifyData:(void *)notifyData
{
LOG(Plugins, "NPN_PostURLNotify: %s", URLCString);
return [self _postURL:URLCString target:target len:len buf:buf file:file notifyData:notifyData sendNotification:YES allowHeaders:YES];
}
-(NPError)postURL:(const char *)URLCString
target:(const char *)target
len:(UInt32)len
buf:(const char *)buf
file:(NPBool)file
{
LOG(Plugins, "NPN_PostURL: %s", URLCString);
// As documented, only allow headers to be specified via NPP_PostURL when using a file.
return [self _postURL:URLCString target:target len:len buf:buf file:file notifyData:NULL sendNotification:NO allowHeaders:file];
}
-(NPError)newStream:(NPMIMEType)type target:(const char *)target stream:(NPStream**)stream
{
LOG(Plugins, "NPN_NewStream");
return NPERR_GENERIC_ERROR;
}
-(NPError)write:(NPStream*)stream len:(SInt32)len buffer:(void *)buffer
{
LOG(Plugins, "NPN_Write");
return NPERR_GENERIC_ERROR;
}
-(NPError)destroyStream:(NPStream*)stream reason:(NPReason)reason
{
LOG(Plugins, "NPN_DestroyStream");
// This function does a sanity check to ensure that the NPStream provided actually
// belongs to the plug-in that provided it, which fixes a crash in the DivX
// plug-in: <rdar://problem/5093862> | http://bugs.webkit.org/show_bug.cgi?id=13203
if (!stream || WebNetscapePluginStream::ownerForStream(stream) != plugin) {
LOG(Plugins, "Invalid NPStream passed to NPN_DestroyStream: %p", stream);
return NPERR_INVALID_INSTANCE_ERROR;
}
WebNetscapePluginStream* browserStream = static_cast<WebNetscapePluginStream*>(stream->ndata);
browserStream->cancelLoadAndDestroyStreamWithError(browserStream->errorForReason(reason));
return NPERR_NO_ERROR;
}
- (const char *)userAgent
{
NSString *userAgent = [[self webView] userAgentForURL:_baseURL.get()];
if (_isSilverlight) {
// Silverlight has a workaround for a leak in Safari 2. This workaround is
// applied when the user agent does not contain "Version/3" so we append it
// at the end of the user agent.
userAgent = [userAgent stringByAppendingString:@" Version/3.2.1"];
}
return [userAgent UTF8String];
}
-(void)status:(const char *)message
{
if (!message) {
LOG_ERROR("NPN_Status passed a NULL status message");
return;
}
CFStringRef status = CFStringCreateWithCString(NULL, message, kCFStringEncodingUTF8);
if (!status) {
LOG_ERROR("NPN_Status: the message was not valid UTF-8");
return;
}
LOG(Plugins, "NPN_Status: %@", status);
WebView *wv = [self webView];
[[wv _UIDelegateForwarder] webView:wv setStatusText:(NSString *)status];
CFRelease(status);
}
-(void)invalidateRect:(NPRect *)invalidRect
{
LOG(Plugins, "NPN_InvalidateRect");
[self invalidatePluginContentRect:NSMakeRect(invalidRect->left, invalidRect->top,
(float)invalidRect->right - invalidRect->left, (float)invalidRect->bottom - invalidRect->top)];
}
- (void)invalidateRegion:(NPRegion)invalidRegion
{
LOG(Plugins, "NPN_InvalidateRegion");
NSRect invalidRect = NSZeroRect;
switch (drawingModel) {
#ifndef NP_NO_QUICKDRAW
case NPDrawingModelQuickDraw:
{
::Rect qdRect;
GetRegionBounds((NPQDRegion)invalidRegion, &qdRect);
invalidRect = NSMakeRect(qdRect.left, qdRect.top, qdRect.right - qdRect.left, qdRect.bottom - qdRect.top);
}
break;
#endif /* NP_NO_QUICKDRAW */
case NPDrawingModelCoreGraphics:
{
CGRect cgRect = CGPathGetBoundingBox((NPCGRegion)invalidRegion);
invalidRect = *(NSRect*)&cgRect;
break;
}
default:
ASSERT_NOT_REACHED();
break;
}
[self invalidatePluginContentRect:invalidRect];
}
-(void)forceRedraw
{
LOG(Plugins, "forceRedraw");
[self invalidatePluginContentRect:[self bounds]];
[[self window] displayIfNeeded];
}
- (NPError)getVariable:(NPNVariable)variable value:(void *)value
{
switch (variable) {
case NPNVWindowNPObject:
{
Frame* frame = core([self webFrame]);
NPObject* windowScriptObject = frame ? frame->script()->windowScriptNPObject() : 0;
// Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess>
if (windowScriptObject)
_NPN_RetainObject(windowScriptObject);
void **v = (void **)value;
*v = windowScriptObject;
return NPERR_NO_ERROR;
}
case NPNVPluginElementNPObject:
{
if (!_element)
return NPERR_GENERIC_ERROR;
NPObject *plugInScriptObject = _element->getNPObject();
// Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess>
if (plugInScriptObject)
_NPN_RetainObject(plugInScriptObject);
void **v = (void **)value;
*v = plugInScriptObject;
return NPERR_NO_ERROR;
}
case NPNVpluginDrawingModel:
{
*(NPDrawingModel *)value = drawingModel;
return NPERR_NO_ERROR;
}
#ifndef NP_NO_QUICKDRAW
case NPNVsupportsQuickDrawBool:
{
*(NPBool *)value = TRUE;
return NPERR_NO_ERROR;
}
#endif /* NP_NO_QUICKDRAW */
case NPNVsupportsCoreGraphicsBool:
{
*(NPBool *)value = TRUE;
return NPERR_NO_ERROR;
}
case NPNVsupportsOpenGLBool:
{
*(NPBool *)value = FALSE;
return NPERR_NO_ERROR;
}
case NPNVsupportsCoreAnimationBool:
{
#ifdef BUILDING_ON_TIGER
*(NPBool *)value = FALSE;
#else
*(NPBool *)value = TRUE;
#endif
return NPERR_NO_ERROR;
}
#ifndef NP_NO_CARBON
case NPNVsupportsCarbonBool:
{
*(NPBool *)value = TRUE;
return NPERR_NO_ERROR;
}
#endif /* NP_NO_CARBON */
case NPNVsupportsCocoaBool:
{
*(NPBool *)value = TRUE;
return NPERR_NO_ERROR;
}
case WKNVBrowserContainerCheckFuncs:
{
*(WKNBrowserContainerCheckFuncs **)value = browserContainerCheckFuncs();
return NPERR_NO_ERROR;
}
default:
break;
}
return NPERR_GENERIC_ERROR;
}
- (NPError)setVariable:(NPPVariable)variable value:(void *)value
{
switch (variable) {
case NPPVpluginDrawingModel:
{
// Can only set drawing model inside NPP_New()
if (self != [[self class] currentPluginView])
return NPERR_GENERIC_ERROR;
// Check for valid, supported drawing model
NPDrawingModel newDrawingModel = (NPDrawingModel)(uintptr_t)value;
switch (newDrawingModel) {
// Supported drawing models:
#ifndef NP_NO_QUICKDRAW
case NPDrawingModelQuickDraw:
#endif
case NPDrawingModelCoreGraphics:
#ifndef BUILDING_ON_TIGER
case NPDrawingModelCoreAnimation:
#endif
drawingModel = newDrawingModel;
return NPERR_NO_ERROR;
// Unsupported (or unknown) drawing models:
default:
LOG(Plugins, "Plugin %@ uses unsupported drawing model: %d", _eventHandler.get(), drawingModel);
return NPERR_GENERIC_ERROR;
}
}
case NPPVpluginEventModel:
{
// Can only set event model inside NPP_New()
if (self != [[self class] currentPluginView])
return NPERR_GENERIC_ERROR;
// Check for valid, supported event model
NPEventModel newEventModel = (NPEventModel)(uintptr_t)value;
switch (newEventModel) {
// Supported event models:
#ifndef NP_NO_CARBON
case NPEventModelCarbon:
#endif
case NPEventModelCocoa:
eventModel = newEventModel;
return NPERR_NO_ERROR;
// Unsupported (or unknown) event models:
default:
LOG(Plugins, "Plugin %@ uses unsupported event model: %d", _eventHandler.get(), eventModel);
return NPERR_GENERIC_ERROR;
}
}
default:
return NPERR_GENERIC_ERROR;
}
}
- (uint32)scheduleTimerWithInterval:(uint32)interval repeat:(NPBool)repeat timerFunc:(void (*)(NPP npp, uint32 timerID))timerFunc
{
if (!timerFunc)
return 0;
if (!timers)
timers = new HashMap<uint32, PluginTimer*>;
uint32 timerID;
do {
timerID = ++currentTimerID;
} while (timers->contains(timerID) || timerID == 0);
PluginTimer* timer = new PluginTimer(plugin, timerID, interval, repeat, timerFunc);
timers->set(timerID, timer);
if (_shouldFireTimers)
timer->start(_isCompletelyObscured);
return timerID;
}
- (void)unscheduleTimer:(uint32)timerID
{
if (!timers)
return;
if (PluginTimer* timer = timers->take(timerID))
delete timer;
}
- (NPError)popUpContextMenu:(NPMenu *)menu
{
NSEvent *currentEvent = [NSApp currentEvent];
// NPN_PopUpContextMenu must be called from within the plug-in's NPP_HandleEvent.
if (!currentEvent)
return NPERR_GENERIC_ERROR;
[NSMenu popUpContextMenu:(NSMenu *)menu withEvent:currentEvent forView:self];
return NPERR_NO_ERROR;
}
- (NPError)getVariable:(NPNURLVariable)variable forURL:(const char*)url value:(char**)value length:(uint32*)length
{
switch (variable) {
case NPNURLVCookie: {
if (!value)
break;
NSURL *URL = [self URLWithCString:url];
if (!URL)
break;
if (Frame* frame = core([self webFrame])) {
String cookieString = cookies(frame->document(), URL);
CString cookieStringUTF8 = cookieString.utf8();
if (cookieStringUTF8.isNull())
return NPERR_GENERIC_ERROR;
*value = static_cast<char*>(NPN_MemAlloc(cookieStringUTF8.length()));
memcpy(*value, cookieStringUTF8.data(), cookieStringUTF8.length());
if (length)
*length = cookieStringUTF8.length();
return NPERR_NO_ERROR;
}
break;
}
case NPNURLVProxy: {
#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
if (!value)
break;
NSURL *URL = [self URLWithCString:url];
if (!URL)
break;
CString proxiesUTF8 = proxiesForURL(URL);
*value = static_cast<char*>(NPN_MemAlloc(proxiesUTF8.length()));
memcpy(*value, proxiesUTF8.data(), proxiesUTF8.length());
if (length)
*length = proxiesUTF8.length();
return NPERR_NO_ERROR;
#else
break;
#endif
}
}
return NPERR_GENERIC_ERROR;
}
- (NPError)setVariable:(NPNURLVariable)variable forURL:(const char*)url value:(const char*)value length:(uint32)length
{
switch (variable) {
case NPNURLVCookie: {
NSURL *URL = [self URLWithCString:url];
if (!URL)
break;
String cookieString = String::fromUTF8(value, length);
if (!cookieString)
break;
if (Frame* frame = core([self webFrame])) {
setCookies(frame->document(), URL, cookieString);
return NPERR_NO_ERROR;
}
break;
}
case NPNURLVProxy:
// Can't set the proxy for a URL.
break;
}
return NPERR_GENERIC_ERROR;
}
- (NPError)getAuthenticationInfoWithProtocol:(const char*)protocolStr host:(const char*)hostStr port:(int32)port scheme:(const char*)schemeStr realm:(const char*)realmStr
username:(char**)usernameStr usernameLength:(uint32*)usernameLength
password:(char**)passwordStr passwordLength:(uint32*)passwordLength
{
if (!protocolStr || !hostStr || !schemeStr || !realmStr || !usernameStr || !usernameLength || !passwordStr || !passwordLength)
return NPERR_GENERIC_ERROR;
CString username;
CString password;
if (!getAuthenticationInfo(protocolStr, hostStr, port, schemeStr, realmStr, username, password))
return NPERR_GENERIC_ERROR;
*usernameLength = username.length();
*usernameStr = static_cast<char*>(NPN_MemAlloc(username.length()));
memcpy(*usernameStr, username.data(), username.length());
*passwordLength = password.length();
*passwordStr = static_cast<char*>(NPN_MemAlloc(password.length()));
memcpy(*passwordStr, password.data(), password.length());
return NPERR_NO_ERROR;
}
- (char*)resolveURL:(const char*)url forTarget:(const char*)target
{
WebCore::CString location = [self resolvedURLStringForURL:url target:target];
if (location.isNull())
return 0;
// We use strdup here because the caller needs to free it with NPN_MemFree (which calls free).
return strdup(location.data());
}
@end
@implementation WebNetscapePluginView (Internal)
- (BOOL)_shouldCancelSrcStream
{
ASSERT(_isStarted);
// Check if we should cancel the load
NPBool cancelSrcStream = 0;
if ([_pluginPackage.get() pluginFuncs]->getvalue &&
[_pluginPackage.get() pluginFuncs]->getvalue(plugin, NPPVpluginCancelSrcStream, &cancelSrcStream) == NPERR_NO_ERROR && cancelSrcStream)
return YES;
return NO;
}
- (NPError)_createPlugin
{
plugin = (NPP)calloc(1, sizeof(NPP_t));
plugin->ndata = self;
ASSERT([_pluginPackage.get() pluginFuncs]->newp);
// NPN_New(), which creates the plug-in instance, should never be called while calling a plug-in function for that instance.
ASSERT(pluginFunctionCallDepth == 0);
PluginMainThreadScheduler::scheduler().registerPlugin(plugin);
_isFlash = [[[_pluginPackage.get() bundle] bundleIdentifier] isEqualToString:@"com.macromedia.Flash Player.plugin"];
_isSilverlight = [[[_pluginPackage.get() bundle] bundleIdentifier] isEqualToString:@"com.microsoft.SilverlightPlugin"];
[[self class] setCurrentPluginView:self];
NPError npErr = [_pluginPackage.get() pluginFuncs]->newp((char *)[_MIMEType.get() cString], plugin, _mode, argsCount, cAttributes, cValues, NULL);
[[self class] setCurrentPluginView:nil];
LOG(Plugins, "NPP_New: %d", npErr);
return npErr;
}
- (void)_destroyPlugin
{
PluginMainThreadScheduler::scheduler().unregisterPlugin(plugin);
NPError npErr;
npErr = ![_pluginPackage.get() pluginFuncs]->destroy(plugin, NULL);
LOG(Plugins, "NPP_Destroy: %d", npErr);
if (Frame* frame = core([self webFrame]))
frame->script()->cleanupScriptObjectsForPlugin(self);
free(plugin);
plugin = NULL;
}
- (NSBitmapImageRep *)_printedPluginBitmap
{
#ifdef NP_NO_QUICKDRAW
return nil;
#else
// Cannot print plugins that do not implement NPP_Print
if (![_pluginPackage.get() pluginFuncs]->print)
return nil;
// This NSBitmapImageRep will share its bitmap buffer with a GWorld that the plugin will draw into.
// The bitmap is created in 32-bits-per-pixel ARGB format, which is the default GWorld pixel format.
NSBitmapImageRep *bitmap = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:window.width
pixelsHigh:window.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSAlphaFirstBitmapFormat
bytesPerRow:0
bitsPerPixel:0] autorelease];
ASSERT(bitmap);
// Create a GWorld with the same underlying buffer into which the plugin can draw
::Rect printGWorldBounds;
SetRect(&printGWorldBounds, 0, 0, window.width, window.height);
GWorldPtr printGWorld;
if (NewGWorldFromPtr(&printGWorld,
k32ARGBPixelFormat,
&printGWorldBounds,
NULL,
NULL,
0,
(Ptr)[bitmap bitmapData],
[bitmap bytesPerRow]) != noErr) {
LOG_ERROR("Could not create GWorld for printing");
return nil;
}
/// Create NPWindow for the GWorld
NPWindow printNPWindow;
printNPWindow.window = &printGWorld; // Normally this is an NP_Port, but when printing it is the actual CGrafPtr
printNPWindow.x = 0;
printNPWindow.y = 0;
printNPWindow.width = window.width;
printNPWindow.height = window.height;
printNPWindow.clipRect.top = 0;
printNPWindow.clipRect.left = 0;
printNPWindow.clipRect.right = window.width;
printNPWindow.clipRect.bottom = window.height;
printNPWindow.type = NPWindowTypeDrawable; // Offscreen graphics port as opposed to a proper window
// Create embed-mode NPPrint
NPPrint npPrint;
npPrint.mode = NP_EMBED;
npPrint.print.embedPrint.window = printNPWindow;
npPrint.print.embedPrint.platformPrint = printGWorld;
// Tell the plugin to print into the GWorld
[self willCallPlugInFunction];
{
JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
[_pluginPackage.get() pluginFuncs]->print(plugin, &npPrint);
}
[self didCallPlugInFunction];
// Don't need the GWorld anymore
DisposeGWorld(printGWorld);
return bitmap;
#endif
}
- (void)_redeliverStream
{
if ([self dataSource] && _isStarted) {
// Deliver what has not been passed to the plug-in up to this point.
if (_dataLengthReceived > 0) {
NSData *data = [[[self dataSource] data] subdataWithRange:NSMakeRange(0, _dataLengthReceived)];
_dataLengthReceived = 0;
[self pluginView:self receivedData:data];
if (![[self dataSource] isLoading]) {
if (_error)
[self pluginView:self receivedError:_error.get()];
else
[self pluginViewFinishedLoading:self];
}
}
}
}
@end
#endif
|