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
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define PEPPER_APIS_ENABLED 1
#include "chrome/renderer/webplugin_delegate_pepper.h"
#include <string>
#include <vector>
#if defined(OS_LINUX)
#include <unistd.h>
#endif
#include "base/file_path.h"
#include "base/file_util.h"
#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif
#include "base/md5.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/metrics/stats_counters.h"
#include "base/path_service.h"
#include "base/process_util.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_cftyperef.h"
#endif
#include "base/scoped_ptr.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/task.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/renderer/pepper_widget.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#if defined(OS_LINUX)
#include "chrome/renderer/renderer_sandbox_support_linux.h"
#endif
#include "chrome/renderer/webplugin_delegate_proxy.h"
#include "gfx/blit.h"
#if defined(OS_WIN)
#include "gfx/codec/jpeg_codec.h"
#include "gfx/gdi_util.h"
#include "printing/units.h"
#include "skia/ext/vector_platform_device.h"
#endif
#include "printing/native_metafile.h"
#include "third_party/npapi/bindings/npapi_extensions.h"
#include "third_party/npapi/bindings/npapi_extensions_private.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h"
#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/npapi/plugin_constants_win.h"
#include "webkit/plugins/npapi/plugin_instance.h"
#include "webkit/plugins/npapi/plugin_lib.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/plugin_host.h"
#include "webkit/plugins/npapi/plugin_stream_url.h"
#if defined(ENABLE_GPU)
#include "webkit/plugins/npapi/plugin_constants_win.h"
#endif
#if defined(ENABLE_GPU)
using gpu::Buffer;
#endif
using webkit::npapi::WebPlugin;
using webkit::npapi::WebPluginDelegate;
using webkit::npapi::WebPluginResourceClient;
using WebKit::WebCursorInfo;
using WebKit::WebKeyboardEvent;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebMouseWheelEvent;
namespace {
// Implementation artifacts for a context
struct Device2DImpl {
TransportDIB* dib;
};
struct Device3DImpl {
#if defined(ENABLE_GPU)
gpu::CommandBuffer* command_buffer;
#endif
bool dynamically_created;
};
const int32 kDefaultCommandBufferSize = 1024 * 1024;
} // namespace
static const float kPointsPerInch = 72.0;
#if defined(OS_WIN)
// Exported by pdf.dll
typedef bool (*RenderPDFPageToDCProc)(
const unsigned char* pdf_buffer, int buffer_size, int page_number, HDC dc,
int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y,
int bounds_width, int bounds_height, bool fit_to_bounds,
bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds);
#endif // defined(OS_WIN)
WebPluginDelegatePepper* WebPluginDelegatePepper::Create(
const FilePath& filename,
const std::string& mime_type,
const base::WeakPtr<RenderView>& render_view) {
scoped_refptr<webkit::npapi::PluginLib> plugin_lib(
webkit::npapi::PluginLib::CreatePluginLib(filename));
if (plugin_lib.get() == NULL)
return NULL;
NPError err = plugin_lib->NP_Initialize();
if (err != NPERR_NO_ERROR)
return NULL;
scoped_refptr<webkit::npapi::PluginInstance> instance(
plugin_lib->CreateInstance(mime_type));
return new WebPluginDelegatePepper(render_view,
instance.get());
}
void WebPluginDelegatePepper::didChooseFile(
const WebKit::WebVector<WebKit::WebString>& file_names) {
if (file_names.isEmpty()) {
current_choose_file_callback_(NULL, 0, current_choose_file_user_data_);
} else {
// Construct a bunch of 8-bit strings for the callback.
std::vector<std::string> file_strings;
file_strings.resize(file_names.size());
for (size_t i = 0; i < file_names.size(); i++)
file_strings[i] = file_names[0].utf8();
// Construct an array of pointers to each of the strings.
std::vector<const char*> pointers_to_strings;
pointers_to_strings.resize(file_strings.size());
for (size_t i = 0; i < file_strings.size(); i++)
pointers_to_strings[i] = file_strings[i].c_str();
current_choose_file_callback_(
&pointers_to_strings[0],
static_cast<int>(pointers_to_strings.size()),
current_choose_file_user_data_);
}
}
bool WebPluginDelegatePepper::Initialize(
const GURL& url,
const std::vector<std::string>& arg_names,
const std::vector<std::string>& arg_values,
WebPlugin* plugin,
bool load_manually) {
plugin_ = plugin;
instance_->set_web_plugin(plugin_);
int argc = 0;
scoped_array<char*> argn(new char*[arg_names.size()]);
scoped_array<char*> argv(new char*[arg_names.size()]);
for (size_t i = 0; i < arg_names.size(); ++i) {
argn[argc] = const_cast<char*>(arg_names[i].c_str());
argv[argc] = const_cast<char*>(arg_values[i].c_str());
argc++;
}
bool start_result = instance_->Start(
url, argn.get(), argv.get(), argc, load_manually);
if (!start_result)
return false;
plugin_url_ = url.spec();
return true;
}
void WebPluginDelegatePepper::DestroyInstance() {
if (instance_ && (instance_->npp()->ndata != NULL)) {
// Shutdown all streams before destroying so that
// no streams are left "in progress". Need to do
// this before calling set_web_plugin(NULL) because the
// instance uses the helper to do the download.
instance_->CloseStreams();
window_.window = NULL;
instance_->NPP_SetWindow(&window_);
instance_->NPP_Destroy();
instance_->set_web_plugin(NULL);
instance_ = 0;
}
// Destroy the nested GPU plugin only after first destroying the underlying
// Pepper plugin. This is so the Pepper plugin does not attempt to issue
// rendering commands after the GPU plugin has stopped processing them and
// responding to them.
if (nested_delegate_) {
#if defined(ENABLE_GPU)
if (command_buffer_) {
nested_delegate_->DestroyCommandBuffer(command_buffer_);
command_buffer_ = NULL;
}
#endif
nested_delegate_->PluginDestroyed();
nested_delegate_ = NULL;
}
}
void WebPluginDelegatePepper::UpdateGeometry(
const gfx::Rect& window_rect,
const gfx::Rect& clip_rect) {
// Only resend to the instance if the geometry has changed.
if (window_rect == window_rect_ && clip_rect == clip_rect_)
return;
clip_rect_ = clip_rect;
cutout_rects_.clear();
if (window_rect_ == window_rect)
return;
window_rect_ = window_rect;
// TODO(brettw) figure out how to tell the plugin that the size changed and it
// needs to repaint?
SkBitmap new_committed;
new_committed.setConfig(SkBitmap::kARGB_8888_Config,
window_rect_.width(), window_rect_.height());
new_committed.allocPixels();
committed_bitmap_ = new_committed;
// Forward the new geometry to the nested plugin instance.
if (nested_delegate_)
nested_delegate_->UpdateGeometry(window_rect, clip_rect);
#if defined(ENABLE_GPU)
#if defined(OS_MACOSX)
// Send the new window size to the command buffer service code so it
// can allocate a new backing store. The handle to the new backing
// store is sent back to the browser asynchronously.
if (command_buffer_) {
command_buffer_->SetWindowSize(window_rect_.size());
}
#endif // OS_MACOSX
#endif // ENABLE_GPU
if (!instance())
return;
ForwardSetWindow();
}
NPObject* WebPluginDelegatePepper::GetPluginScriptableObject() {
return instance_->GetPluginScriptableObject();
}
void WebPluginDelegatePepper::DidFinishLoadWithReason(
const GURL& url, NPReason reason, int notify_id) {
instance()->DidFinishLoadWithReason(url, reason, notify_id);
}
int WebPluginDelegatePepper::GetProcessId() {
// We are in process, so the plugin pid is this current process pid.
return base::GetCurrentProcId();
}
void WebPluginDelegatePepper::SendJavaScriptStream(
const GURL& url,
const std::string& result,
bool success,
int notify_id) {
instance()->SendJavaScriptStream(url, result, success, notify_id);
}
void WebPluginDelegatePepper::DidReceiveManualResponse(
const GURL& url, const std::string& mime_type,
const std::string& headers, uint32 expected_length, uint32 last_modified) {
instance()->DidReceiveManualResponse(url, mime_type, headers,
expected_length, last_modified);
}
void WebPluginDelegatePepper::DidReceiveManualData(const char* buffer,
int length) {
instance()->DidReceiveManualData(buffer, length);
}
void WebPluginDelegatePepper::DidFinishManualLoading() {
instance()->DidFinishManualLoading();
}
void WebPluginDelegatePepper::DidManualLoadFail() {
instance()->DidManualLoadFail();
}
FilePath WebPluginDelegatePepper::GetPluginPath() {
return instance()->plugin_lib()->plugin_info().path;
}
void WebPluginDelegatePepper::RenderViewInitiatedPaint() {
// Broadcast event to all 2D contexts.
Graphics2DMap::iterator iter2d(&graphic2d_contexts_);
while (!iter2d.IsAtEnd()) {
iter2d.GetCurrentValue()->RenderViewInitiatedPaint();
iter2d.Advance();
}
}
void WebPluginDelegatePepper::RenderViewFlushedPaint() {
// Broadcast event to all 2D contexts.
Graphics2DMap::iterator iter2d(&graphic2d_contexts_);
while (!iter2d.IsAtEnd()) {
iter2d.GetCurrentValue()->RenderViewFlushedPaint();
iter2d.Advance();
}
}
WebPluginResourceClient* WebPluginDelegatePepper::CreateResourceClient(
unsigned long resource_id, const GURL& url, int notify_id) {
return instance()->CreateStream(resource_id, url, std::string(), notify_id);
}
WebPluginResourceClient* WebPluginDelegatePepper::CreateSeekableResourceClient(
unsigned long resource_id, int range_request_id) {
return instance()->GetRangeRequest(range_request_id);
}
bool WebPluginDelegatePepper::StartFind(const string16& search_text,
bool case_sensitive,
int identifier) {
if (!GetFindExtensions())
return false;
find_identifier_ = identifier;
GetFindExtensions()->startFind(
instance()->npp(), UTF16ToUTF8(search_text).c_str(), case_sensitive);
return true;
}
void WebPluginDelegatePepper::SelectFindResult(bool forward) {
GetFindExtensions()->selectFindResult(instance()->npp(), forward);
}
void WebPluginDelegatePepper::StopFind() {
find_identifier_ = -1;
GetFindExtensions()->stopFind(instance()->npp());
}
void WebPluginDelegatePepper::NumberOfFindResultsChanged(int total,
bool final_result) {
DCHECK(find_identifier_ != -1);
render_view_->reportFindInPageMatchCount(
find_identifier_, total, final_result);
}
void WebPluginDelegatePepper::SelectedFindResultChanged(int index) {
render_view_->reportFindInPageSelection(
find_identifier_, index + 1, WebKit::WebRect());
}
bool WebPluginDelegatePepper::ChooseFile(const char* mime_types,
int mode,
NPChooseFileCallback callback,
void* user_data) {
if (!render_view_ || !callback)
return false;
if (current_choose_file_callback_)
return false; // Reentrant call to browse, only one can be outstanding
// per plugin.
// TODO(brettw) do something with the mime types!
current_choose_file_callback_ = callback;
current_choose_file_user_data_ = user_data;
ViewHostMsg_RunFileChooser_Params ipc_params;
switch (mode) {
case NPChooseFile_Open:
ipc_params.mode = ViewHostMsg_RunFileChooser_Params::Open;
break;
case NPChooseFile_OpenMultiple:
ipc_params.mode = ViewHostMsg_RunFileChooser_Params::OpenMultiple;
break;
case NPChooseFile_Save:
ipc_params.mode = ViewHostMsg_RunFileChooser_Params::Save;
break;
default:
return false;
}
return render_view_->ScheduleFileChooser(ipc_params, this);
}
NPWidgetExtensions* WebPluginDelegatePepper::GetWidgetExtensions() {
return PepperWidget::GetWidgetExtensions();
}
#define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, np_name) \
COMPILE_ASSERT(int(WebCursorInfo::webkit_name) == int(np_name), \
mismatching_enums)
COMPILE_ASSERT_MATCHING_ENUM(TypePointer, NPCursorTypePointer);
COMPILE_ASSERT_MATCHING_ENUM(TypeCross, NPCursorTypeCross);
COMPILE_ASSERT_MATCHING_ENUM(TypeHand, NPCursorTypeHand);
COMPILE_ASSERT_MATCHING_ENUM(TypeIBeam, NPCursorTypeIBeam);
COMPILE_ASSERT_MATCHING_ENUM(TypeWait, NPCursorTypeWait);
COMPILE_ASSERT_MATCHING_ENUM(TypeHelp, NPCursorTypeHelp);
COMPILE_ASSERT_MATCHING_ENUM(TypeEastResize, NPCursorTypeEastResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthResize, NPCursorTypeNorthResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastResize, NPCursorTypeNorthEastResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestResize, NPCursorTypeNorthWestResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeSouthResize, NPCursorTypeSouthResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastResize, NPCursorTypeSouthEastResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestResize, NPCursorTypeSouthWestResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeWestResize, NPCursorTypeWestResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthSouthResize,
NPCursorTypeNorthSouthResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeEastWestResize, NPCursorTypeEastWestResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastSouthWestResize,
NPCursorTypeNorthEastSouthWestResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestSouthEastResize,
NPCursorTypeNorthWestSouthEastResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeColumnResize, NPCursorTypeColumnResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeRowResize, NPCursorTypeRowResize);
COMPILE_ASSERT_MATCHING_ENUM(TypeMiddlePanning, NPCursorTypeMiddlePanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeEastPanning, NPCursorTypeEastPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthPanning, NPCursorTypeNorthPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthEastPanning,
NPCursorTypeNorthEastPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeNorthWestPanning,
NPCursorTypeNorthWestPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeSouthPanning, NPCursorTypeSouthPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeSouthEastPanning,
NPCursorTypeSouthEastPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeSouthWestPanning,
NPCursorTypeSouthWestPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeWestPanning, NPCursorTypeWestPanning);
COMPILE_ASSERT_MATCHING_ENUM(TypeMove, NPCursorTypeMove);
COMPILE_ASSERT_MATCHING_ENUM(TypeVerticalText, NPCursorTypeVerticalText);
COMPILE_ASSERT_MATCHING_ENUM(TypeCell, NPCursorTypeCell);
COMPILE_ASSERT_MATCHING_ENUM(TypeContextMenu, NPCursorTypeContextMenu);
COMPILE_ASSERT_MATCHING_ENUM(TypeAlias, NPCursorTypeAlias);
COMPILE_ASSERT_MATCHING_ENUM(TypeProgress, NPCursorTypeProgress);
COMPILE_ASSERT_MATCHING_ENUM(TypeNoDrop, NPCursorTypeNoDrop);
COMPILE_ASSERT_MATCHING_ENUM(TypeCopy, NPCursorTypeCopy);
COMPILE_ASSERT_MATCHING_ENUM(TypeNone, NPCursorTypeNone);
COMPILE_ASSERT_MATCHING_ENUM(TypeNotAllowed, NPCursorTypeNotAllowed);
COMPILE_ASSERT_MATCHING_ENUM(TypeZoomIn, NPCursorTypeZoomIn);
COMPILE_ASSERT_MATCHING_ENUM(TypeZoomOut, NPCursorTypeZoomOut);
bool WebPluginDelegatePepper::SetCursor(NPCursorType type) {
cursor_.reset(new WebCursorInfo(static_cast<WebCursorInfo::Type>(type)));
return true;
}
NPError NPMatchFontWithFallback(NPP instance,
const NPFontDescription* description,
NPFontID* id) {
#if defined(OS_LINUX)
int fd = renderer_sandbox_support::MatchFontWithFallback(
description->face, description->weight >= 700, description->italic,
description->charset);
if (fd == -1)
return NPERR_GENERIC_ERROR;
*id = fd;
return NPERR_NO_ERROR;
#else
NOTIMPLEMENTED();
return NPERR_GENERIC_ERROR;
#endif
}
NPError GetFontTable(NPP instance,
NPFontID id,
uint32_t table,
void* output,
size_t* output_length) {
#if defined(OS_LINUX)
bool rv = renderer_sandbox_support::GetFontTable(
id, table, static_cast<uint8_t*>(output), output_length);
return rv ? NPERR_NO_ERROR : NPERR_GENERIC_ERROR;
#else
NOTIMPLEMENTED();
return NPERR_GENERIC_ERROR;
#endif
}
NPError NPDestroyFont(NPP instance, NPFontID id) {
#if defined(OS_LINUX)
close(id);
return NPERR_NO_ERROR;
#else
NOTIMPLEMENTED();
return NPERR_GENERIC_ERROR;
#endif
}
NPFontExtensions g_font_extensions = {
NPMatchFontWithFallback,
GetFontTable,
NPDestroyFont
};
NPFontExtensions* WebPluginDelegatePepper::GetFontExtensions() {
return &g_font_extensions;
}
void WebPluginDelegatePepper::SetZoomFactor(float scale, bool text_only) {
NPPExtensions* extensions = NULL;
instance()->NPP_GetValue(NPPVPepperExtensions, &extensions);
if (extensions && extensions->zoom)
extensions->zoom(instance()->npp(), scale, text_only);
}
bool WebPluginDelegatePepper::HasSelection() const {
return !GetSelectedText(false).empty();
}
string16 WebPluginDelegatePepper::GetSelectionAsText() const {
return GetSelectedText(false);
}
string16 WebPluginDelegatePepper::GetSelectionAsMarkup() const {
return GetSelectedText(true);
}
string16 WebPluginDelegatePepper::GetSelectedText(bool html) const {
NPPExtensions* extensions = NULL;
instance_->NPP_GetValue(NPPVPepperExtensions, &extensions);
if (!extensions || !extensions->getSelection)
return string16();
void* text;
NPSelectionType type = html ? NPSelectionTypeHTML : NPSelectionTypePlainText;
NPP npp = instance_->npp();
if (extensions->getSelection(npp, &type, &text) != NPERR_NO_ERROR)
return string16();
string16 rv = UTF8ToUTF16(static_cast<char*>(text));
webkit::npapi::PluginHost::Singleton()->host_functions()->memfree(text);
return rv;
}
NPError WebPluginDelegatePepper::Device2DQueryCapability(int32 capability,
int32* value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DQueryConfig(
const NPDeviceContext2DConfig* request,
NPDeviceContext2DConfig* obtain) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DInitializeContext(
const NPDeviceContext2DConfig* config,
NPDeviceContext2D* context) {
if (!render_view_) {
return NPERR_GENERIC_ERROR;
}
// This is a windowless plugin, so set it to have no handle. Defer this
// until we know the plugin will use the 2D device. If it uses the 3D device
// it will have a window handle.
plugin_->SetWindow(gfx::kNullPluginWindow);
scoped_ptr<Graphics2DDeviceContext> g2d(new Graphics2DDeviceContext(this));
NPError status = g2d->Initialize(window_rect_, config, context);
if (NPERR_NO_ERROR == status) {
context->reserved = reinterpret_cast<void *>(
graphic2d_contexts_.Add(g2d.release()));
}
return status;
}
NPError WebPluginDelegatePepper::Device2DSetStateContext(
NPDeviceContext2D* context,
int32 state,
intptr_t value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DGetStateContext(
NPDeviceContext2D* context,
int32 state,
intptr_t* value) {
if (state == NPExtensionsReservedStateSharedMemory) {
if (!context)
return NPERR_INVALID_PARAM;
Graphics2DDeviceContext* ctx = GetGraphicsContext(context);
if (!ctx)
return NPERR_INVALID_PARAM;
*value = reinterpret_cast<intptr_t>(ctx->transport_dib());
return NPERR_NO_ERROR;
} else if (state == NPExtensionsReservedStateSharedMemoryChecksum) {
if (!context)
return NPERR_INVALID_PARAM;
// Bytes per pixel.
static const int kBytesPixel = 4;
int32 row_count = context->dirty.bottom - context->dirty.top;
int32 stride = context->dirty.right - context->dirty.left;
size_t length = row_count * stride * kBytesPixel;
MD5Digest md5_result; // 128-bit digest
MD5Sum(context->region, length, &md5_result);
std::string hex_md5 = MD5DigestToBase16(md5_result);
// Return the least significant 8 characters (i.e. 4 bytes)
// of the 32 character hexadecimal result as an int.
int int_val;
DCHECK_EQ(hex_md5.length(), 32u);
base::HexStringToInt(hex_md5.begin() + 24, hex_md5.end(), &int_val);
*value = int_val;
return NPERR_NO_ERROR;
}
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device2DFlushContext(
NPP id,
NPDeviceContext2D* context,
NPDeviceFlushContextCallbackPtr callback,
void* user_data) {
if (!context)
return NPERR_INVALID_PARAM;
Graphics2DDeviceContext* ctx = graphic2d_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved));
if (!ctx)
return NPERR_INVALID_PARAM; // TODO(brettw) call callback.
return ctx->Flush(&committed_bitmap_, context, callback, id, user_data);
}
NPError WebPluginDelegatePepper::Device2DDestroyContext(
NPDeviceContext2D* context) {
if (!context || !graphic2d_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved))) {
return NPERR_INVALID_PARAM;
}
graphic2d_contexts_.Remove(reinterpret_cast<intptr_t>(context->reserved));
memset(context, 0, sizeof(NPDeviceContext2D));
return NPERR_NO_ERROR;
}
Graphics2DDeviceContext* WebPluginDelegatePepper::GetGraphicsContext(
NPDeviceContext2D* context) {
return graphic2d_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved));
}
NPError WebPluginDelegatePepper::Device3DQueryCapability(int32 capability,
int32* value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DQueryConfig(
const NPDeviceContext3DConfig* request,
NPDeviceContext3DConfig* obtain) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DInitializeContext(
const NPDeviceContext3DConfig* config,
NPDeviceContext3D* context) {
if (!context)
return NPERR_GENERIC_ERROR;
#if defined(ENABLE_GPU)
// Check to see if the GPU plugin is already initialized and fail if so.
if (nested_delegate_)
return NPERR_GENERIC_ERROR;
// Create an instance of the GPU plugin that is responsible for 3D
// rendering.
nested_delegate_ = new WebPluginDelegateProxy(
"application/vnd.google.chrome.gpu-plugin", render_view_);
// TODO(apatrick): should the GPU plugin be attached to plugin_?
if (nested_delegate_->Initialize(GURL(),
std::vector<std::string>(),
std::vector<std::string>(),
plugin_,
false)) {
plugin_->SetAcceptsInputEvents(true);
// Ensure the window has the correct size before initializing the
// command buffer.
nested_delegate_->UpdateGeometry(window_rect_, clip_rect_);
// Ask the GPU plugin to create a command buffer and return a proxy.
command_buffer_ = nested_delegate_->CreateCommandBuffer();
if (command_buffer_) {
// Initialize the proxy command buffer.
if (command_buffer_->Initialize(config->commandBufferSize)) {
// Get the initial command buffer state.
gpu::CommandBuffer::State state = command_buffer_->GetState();
// Initialize the 3D context.
context->reserved = NULL;
context->waitForProgress = true;
Buffer ring_buffer = command_buffer_->GetRingBuffer();
context->commandBuffer = ring_buffer.ptr;
context->commandBufferSize = state.num_entries;
context->repaintCallback = NULL;
Synchronize3DContext(context, state);
ScheduleHandleRepaint(instance_->npp(), context);
#if defined(OS_MACOSX)
command_buffer_->SetWindowSize(window_rect_.size());
#endif // OS_MACOSX
// Make sure the nested delegate shows up in the right place
// on the page.
SendNestedDelegateGeometryToBrowser(window_rect_, clip_rect_);
// Save the implementation information (the CommandBuffer).
Device3DImpl* impl = new Device3DImpl;
impl->command_buffer = command_buffer_;
impl->dynamically_created = false;
context->reserved = impl;
return NPERR_NO_ERROR;
}
nested_delegate_->DestroyCommandBuffer(command_buffer_);
command_buffer_ = NULL;
}
}
nested_delegate_->PluginDestroyed();
nested_delegate_ = NULL;
#endif // ENABLE_GPU
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DSetStateContext(
NPDeviceContext3D* context,
int32 state,
intptr_t value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DGetStateContext(
NPDeviceContext3D* context,
int32 state,
intptr_t* value) {
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::Device3DFlushContext(
NPP id,
NPDeviceContext3D* context,
NPDeviceFlushContextCallbackPtr callback,
void* user_data) {
if (!context)
return NPERR_GENERIC_ERROR;
#if defined(ENABLE_GPU)
gpu::CommandBuffer::State state;
if (context->waitForProgress) {
if (callback) {
command_buffer_->AsyncFlush(
context->putOffset,
method_factory3d_.NewRunnableMethod(
&WebPluginDelegatePepper::Device3DUpdateState,
id,
context,
callback,
user_data));
} else {
state = command_buffer_->Flush(context->putOffset);
Synchronize3DContext(context, state);
}
} else {
if (callback) {
command_buffer_->AsyncGetState(
method_factory3d_.NewRunnableMethod(
&WebPluginDelegatePepper::Device3DUpdateState,
id,
context,
callback,
user_data));
} else {
state = command_buffer_->GetState();
Synchronize3DContext(context, state);
}
}
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DDestroyContext(
NPDeviceContext3D* context) {
if (!context)
return NPERR_GENERIC_ERROR;
#if defined(ENABLE_GPU)
// Prevent any async flush callbacks from being invoked after the context
// has been destroyed.
method_factory3d_.RevokeAll();
// TODO(apatrick): this will be much simpler when we switch to the new device
// API. There should be no need for the Device3DImpl and the context will
// always be destroyed dynamically.
Device3DImpl* impl = static_cast<Device3DImpl*>(context->reserved);
bool dynamically_created = impl->dynamically_created;
delete impl;
context->reserved = NULL;
if (dynamically_created) {
delete context;
}
if (nested_delegate_) {
if (command_buffer_) {
nested_delegate_->DestroyCommandBuffer(command_buffer_);
command_buffer_ = NULL;
}
nested_delegate_->PluginDestroyed();
nested_delegate_ = NULL;
}
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DCreateBuffer(
NPDeviceContext3D* context,
size_t size,
int32* id) {
if (!context)
return NPERR_GENERIC_ERROR;
#if defined(ENABLE_GPU)
*id = command_buffer_->CreateTransferBuffer(size);
if (*id < 0)
return NPERR_GENERIC_ERROR;
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DDestroyBuffer(
NPDeviceContext3D* context,
int32 id) {
if (!context)
return NPERR_GENERIC_ERROR;
#if defined(ENABLE_GPU)
command_buffer_->DestroyTransferBuffer(id);
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DMapBuffer(
NPDeviceContext3D* context,
int32 id,
NPDeviceBuffer* np_buffer) {
if (!context)
return NPERR_GENERIC_ERROR;
#if defined(ENABLE_GPU)
Buffer gpu_buffer;
if (id == NP3DCommandBufferId) {
gpu_buffer = command_buffer_->GetRingBuffer();
} else {
gpu_buffer = command_buffer_->GetTransferBuffer(id);
}
np_buffer->ptr = gpu_buffer.ptr;
np_buffer->size = gpu_buffer.size;
if (!np_buffer->ptr)
return NPERR_GENERIC_ERROR;
#endif // ENABLE_GPU
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DGetNumConfigs(int32* num_configs) {
if (!num_configs)
return NPERR_GENERIC_ERROR;
*num_configs = 1;
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DGetConfigAttribs(
int32 config,
int32* attrib_list) {
// Only one config available currently.
if (config != 0)
return NPERR_GENERIC_ERROR;
if (attrib_list) {
for (int32* attrib_pair = attrib_list; *attrib_pair; attrib_pair += 2) {
switch (attrib_pair[0]) {
case NP3DAttrib_BufferSize:
attrib_pair[1] = 32;
break;
case NP3DAttrib_AlphaSize:
case NP3DAttrib_BlueSize:
case NP3DAttrib_GreenSize:
case NP3DAttrib_RedSize:
attrib_pair[1] = 8;
break;
case NP3DAttrib_DepthSize:
attrib_pair[1] = 24;
break;
case NP3DAttrib_StencilSize:
attrib_pair[1] = 8;
break;
case NP3DAttrib_SurfaceType:
attrib_pair[1] = 0;
break;
default:
return NPERR_GENERIC_ERROR;
}
}
}
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DCreateContext(
int32 config,
const int32* attrib_list,
NPDeviceContext3D** context) {
if (!context)
return NPERR_GENERIC_ERROR;
// Only one config available currently.
if (config != 0)
return NPERR_GENERIC_ERROR;
// For now, just use the old API to initialize the context.
NPDeviceContext3DConfig old_config;
old_config.commandBufferSize = kDefaultCommandBufferSize;
if (attrib_list) {
for (const int32* attrib_pair = attrib_list; *attrib_pair;
attrib_pair += 2) {
switch (attrib_pair[0]) {
case NP3DAttrib_CommandBufferSize:
old_config.commandBufferSize = attrib_pair[1];
break;
default:
return NPERR_GENERIC_ERROR;
}
}
}
*context = new NPDeviceContext3D;
Device3DInitializeContext(&old_config, *context);
// Flag the context as dynamically created by the browser. TODO(apatrick):
// take this out when all contexts are dynamically created.
Device3DImpl* impl = static_cast<Device3DImpl*>((*context)->reserved);
impl->dynamically_created = true;
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DRegisterCallback(
NPP id,
NPDeviceContext3D* context,
int32 callback_type,
NPDeviceGenericCallbackPtr callback,
void* callback_data) {
if (!context)
return NPERR_GENERIC_ERROR;
switch (callback_type) {
case NP3DCallback_Repaint:
context->repaintCallback = reinterpret_cast<NPDeviceContext3DRepaintPtr>(
callback);
break;
default:
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::Device3DSynchronizeContext(
NPP id,
NPDeviceContext3D* context,
NPDeviceSynchronizationMode mode,
const int32* input_attrib_list,
int32* output_attrib_list,
NPDeviceSynchronizeContextCallbackPtr callback,
void* callback_data) {
if (!context)
return NPERR_GENERIC_ERROR;
// Copy input attributes into context.
if (input_attrib_list) {
for (const int32* attrib_pair = input_attrib_list;
*attrib_pair;
attrib_pair += 2) {
switch (attrib_pair[0]) {
case NP3DAttrib_PutOffset:
context->putOffset = attrib_pair[1];
break;
default:
return NPERR_GENERIC_ERROR;
}
}
}
// Use existing flush mechanism for now.
if (mode != NPDeviceSynchronizationMode_Cached) {
context->waitForProgress = mode == NPDeviceSynchronizationMode_Flush;
Device3DFlushContext(id, context, callback, callback_data);
}
// Copy most recent output attributes from context.
// To read output attributes after the completion of an asynchronous flush,
// invoke SynchronizeContext again with mode
// NPDeviceSynchronizationMode_Cached from the callback function.
if (output_attrib_list) {
for (int32* attrib_pair = output_attrib_list;
*attrib_pair;
attrib_pair += 2) {
switch (attrib_pair[0]) {
case NP3DAttrib_CommandBufferSize:
attrib_pair[1] = context->commandBufferSize;
break;
case NP3DAttrib_GetOffset:
attrib_pair[1] = context->getOffset;
break;
case NP3DAttrib_PutOffset:
attrib_pair[1] = context->putOffset;
break;
case NP3DAttrib_Token:
attrib_pair[1] = context->token;
break;
default:
return NPERR_GENERIC_ERROR;
}
}
}
return NPERR_NO_ERROR;
}
NPError WebPluginDelegatePepper::DeviceAudioQueryCapability(int32 capability,
int32* value) {
// TODO(neb,cpu) implement QueryCapability
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::DeviceAudioQueryConfig(
const NPDeviceContextAudioConfig* request,
NPDeviceContextAudioConfig* obtain) {
// TODO(neb,cpu) implement QueryConfig
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::DeviceAudioInitializeContext(
const NPDeviceContextAudioConfig* config,
NPDeviceContextAudio* context) {
if (!render_view_) {
return NPERR_GENERIC_ERROR;
}
scoped_ptr<AudioDeviceContext> audio(new AudioDeviceContext());
NPError status = audio->Initialize(render_view_->audio_message_filter(),
config, context);
if (NPERR_NO_ERROR == status) {
context->reserved =
reinterpret_cast<void *>(audio_contexts_.Add(audio.release()));
}
return status;
}
NPError WebPluginDelegatePepper::DeviceAudioSetStateContext(
NPDeviceContextAudio* context,
int32 state,
intptr_t value) {
// TODO(neb,cpu) implement SetStateContext
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::DeviceAudioGetStateContext(
NPDeviceContextAudio* context,
int32 state,
intptr_t* value) {
if (state == NPExtensionsReservedStateSharedMemory) {
if (!context)
return NPERR_INVALID_PARAM;
AudioDeviceContext* ctx = audio_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved));
if (!ctx)
return NPERR_INVALID_PARAM;
*value = reinterpret_cast<intptr_t>(ctx->shared_memory());
return NPERR_NO_ERROR;
} else if (state == NPExtensionsReservedStateSharedMemorySize) {
if (!context)
return NPERR_INVALID_PARAM;
AudioDeviceContext* ctx = audio_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved));
if (!ctx)
return NPERR_INVALID_PARAM;
*value = static_cast<intptr_t>(ctx->shared_memory_size());
return NPERR_NO_ERROR;
} else if (state == NPExtensionsReservedStateSyncChannel) {
if (!context)
return NPERR_INVALID_PARAM;
AudioDeviceContext* ctx = audio_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved));
if (!ctx)
return NPERR_INVALID_PARAM;
*value = reinterpret_cast<intptr_t>(ctx->socket());
return NPERR_NO_ERROR;
}
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::DeviceAudioFlushContext(
NPP id,
NPDeviceContextAudio* context,
NPDeviceFlushContextCallbackPtr callback,
void* user_data) {
// TODO(neb,cpu) implement FlushContext
return NPERR_GENERIC_ERROR;
}
NPError WebPluginDelegatePepper::DeviceAudioDestroyContext(
NPDeviceContextAudio* context) {
if (!context || !audio_contexts_.Lookup(
reinterpret_cast<intptr_t>(context->reserved))) {
return NPERR_INVALID_PARAM;
}
audio_contexts_.Remove(reinterpret_cast<intptr_t>(context->reserved));
memset(context, 0, sizeof(NPDeviceContextAudio));
return NPERR_NO_ERROR;
}
bool WebPluginDelegatePepper::PrintSupportsPrintExtension() {
return GetPrintExtensions() != NULL;
}
int WebPluginDelegatePepper::PrintBegin(const gfx::Rect& printable_area,
int printer_dpi) {
int32 num_pages = 0;
NPPPrintExtensions* print_extensions = GetPrintExtensions();
if (print_extensions) {
NPRect np_printable_area = {0};
np_printable_area.left = printable_area.x();
np_printable_area.top = printable_area.y();
np_printable_area.right = np_printable_area.left + printable_area.width();
np_printable_area.bottom = np_printable_area.top + printable_area.height();
if (NPERR_NO_ERROR == print_extensions->printBegin(instance()->npp(),
&np_printable_area,
printer_dpi,
&num_pages)) {
current_printable_area_ = printable_area;
current_printer_dpi_ = printer_dpi;
}
}
#if defined (OS_LINUX)
num_pages_ = num_pages;
pdf_output_done_ = false;
#endif // (OS_LINUX)
return num_pages;
}
bool WebPluginDelegatePepper::VectorPrintPage(int page_number,
WebKit::WebCanvas* canvas) {
NPPPrintExtensions* print_extensions = GetPrintExtensions();
if (!print_extensions)
return false;
#if defined(OS_WIN)
// For Windows, we need the PDF DLL to render the output PDF to a DC.
FilePath pdf_path;
PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path);
HMODULE pdf_module = GetModuleHandle(pdf_path.value().c_str());
if (!pdf_module)
return false;
RenderPDFPageToDCProc render_proc =
reinterpret_cast<RenderPDFPageToDCProc>(
GetProcAddress(pdf_module, "RenderPDFPageToDC"));
if (!render_proc)
return false;
#endif // defined(OS_WIN)
unsigned char* pdf_output = NULL;
int32 output_size = 0;
NPPrintPageNumberRange page_range;
#if defined(OS_LINUX)
// On Linux we will try and output all pages as PDF in the first call to
// PrintPage. This is a temporary hack.
// TODO(sanjeevr): Remove this hack and fix this by changing the print
// interfaces for WebFrame and WebPlugin.
if (page_number != 0)
return pdf_output_done_;
page_range.firstPageNumber = 0;
page_range.lastPageNumber = num_pages_ - 1;
#else // defined(OS_LINUX)
page_range.firstPageNumber = page_range.lastPageNumber = page_number;
#endif // defined(OS_LINUX)
NPError err = print_extensions->printPagesAsPDF(instance()->npp(),
&page_range, 1,
&pdf_output, &output_size);
if (err != NPERR_NO_ERROR)
return false;
bool ret = false;
#if defined(OS_LINUX)
// On Linux we need to get the backing PdfPsMetafile and write the bits
// directly.
cairo_t* context = canvas->beginPlatformPaint();
printing::NativeMetafile* metafile =
printing::NativeMetafile::FromCairoContext(context);
DCHECK(metafile);
if (metafile) {
ret = metafile->SetRawData(pdf_output, output_size);
if (ret)
pdf_output_done_ = true;
}
canvas->endPlatformPaint();
#elif defined(OS_MACOSX)
printing::NativeMetafile metafile;
// Create a PDF metafile and render from there into the passed in context.
if (metafile.Init(pdf_output, output_size)) {
// Flip the transform.
CGContextSaveGState(canvas);
CGContextTranslateCTM(canvas, 0, current_printable_area_.height());
CGContextScaleCTM(canvas, 1.0, -1.0);
ret = metafile.RenderPage(1, canvas, current_printable_area_.ToCGRect(),
true, false, true, true);
CGContextRestoreGState(canvas);
}
#elif defined(OS_WIN)
// On Windows, we now need to render the PDF to the DC that backs the
// supplied canvas.
skia::VectorPlatformDevice& device =
static_cast<skia::VectorPlatformDevice&>(
canvas->getTopPlatformDevice());
HDC dc = device.getBitmapDC();
gfx::Size size_in_pixels;
size_in_pixels.set_width(
printing::ConvertUnit(current_printable_area_.width(),
static_cast<int>(kPointsPerInch),
current_printer_dpi_));
size_in_pixels.set_height(
printing::ConvertUnit(current_printable_area_.height(),
static_cast<int>(kPointsPerInch),
current_printer_dpi_));
// We need to render using the actual printer DPI (rendering to a smaller
// set of pixels leads to a blurry output). However, we need to counter the
// scaling up that will happen in the browser.
XFORM xform = {0};
xform.eM11 = xform.eM22 = kPointsPerInch / current_printer_dpi_;
ModifyWorldTransform(dc, &xform, MWT_LEFTMULTIPLY);
ret = render_proc(pdf_output, output_size, 0, dc, current_printer_dpi_,
current_printer_dpi_, 0, 0, size_in_pixels.width(),
size_in_pixels.height(), true, false, true, true);
#endif // defined(OS_WIN)
webkit::npapi::PluginHost::Singleton()->host_functions()->memfree(
pdf_output);
return ret;
}
bool WebPluginDelegatePepper::PrintPage(int page_number,
WebKit::WebCanvas* canvas) {
NPPPrintExtensions* print_extensions = GetPrintExtensions();
if (!print_extensions)
return false;
// First try and use vector print.
if (VectorPrintPage(page_number, canvas))
return true;
DCHECK(!current_printable_area_.IsEmpty());
// Calculate the width and height needed for the raster image.
NPRect np_printable_area = {0};
np_printable_area.left = current_printable_area_.x();
np_printable_area.top = current_printable_area_.y();
np_printable_area.right =
current_printable_area_.x() + current_printable_area_.width();
np_printable_area.bottom =
current_printable_area_.y() + current_printable_area_.height();
gfx::Size size_in_pixels;
if (!CalculatePrintedPageDimensions(page_number, print_extensions,
&size_in_pixels)) {
return false;
}
// Now print the page onto a 2d device context.
scoped_ptr<Graphics2DDeviceContext> g2d(new Graphics2DDeviceContext(this));
NPDeviceContext2DConfig config;
NPDeviceContext2D context;
gfx::Rect surface_rect(size_in_pixels);
NPError err = g2d->Initialize(surface_rect, &config, &context);
if (err != NPERR_NO_ERROR) {
NOTREACHED();
return false;
}
err = print_extensions->printPageRaster(instance()->npp(), page_number,
&context);
if (err != NPERR_NO_ERROR)
return false;
SkBitmap committed;
committed.setConfig(SkBitmap::kARGB_8888_Config, size_in_pixels.width(),
size_in_pixels.height());
committed.allocPixels();
err = g2d->Flush(&committed, &context, NULL, instance()->npp(), NULL);
if (err != NPERR_NO_ERROR) {
NOTREACHED();
return false;
}
// Draw the printed image into the supplied canvas.
SkIRect src_rect;
src_rect.set(0, 0, size_in_pixels.width(), size_in_pixels.height());
SkRect dest_rect;
dest_rect.set(SkIntToScalar(current_printable_area_.x()),
SkIntToScalar(current_printable_area_.y()),
SkIntToScalar(current_printable_area_.x() +
current_printable_area_.width()),
SkIntToScalar(current_printable_area_.y() +
current_printable_area_.height()));
bool draw_to_canvas = true;
#if defined(OS_WIN)
// Since this is a raster output, the size of the bitmap can be
// huge (especially at high printer DPIs). On Windows, this can
// result in a HUGE EMF (on Mac and Linux the output goes to PDF
// which appears to Flate compress the bitmap). So, if this bitmap
// is larger than 20 MB, we save the bitmap as a JPEG into the EMF
// DC. Note: We chose JPEG over PNG because JPEG compression seems
// way faster (about 4 times faster).
static const int kCompressionThreshold = 20 * 1024 * 1024;
if (committed.getSize() > kCompressionThreshold) {
DrawJPEGToPlatformDC(committed, current_printable_area_, canvas);
draw_to_canvas = false;
}
#endif // defined(OS_WIN)
#if defined(OS_MACOSX)
draw_to_canvas = false;
DrawSkBitmapToCanvas(committed, canvas, current_printable_area_,
current_printable_area_.height());
// See comments in the header file.
last_printed_page_ = committed;
#else // defined(OS_MACOSX)
if (draw_to_canvas)
canvas->drawBitmapRect(committed, &src_rect, dest_rect);
#endif // defined(OS_MACOSX)
return true;
}
void WebPluginDelegatePepper::PrintEnd() {
NPPPrintExtensions* print_extensions = GetPrintExtensions();
if (print_extensions)
print_extensions->printEnd(instance()->npp());
current_printable_area_ = gfx::Rect();
current_printer_dpi_ = -1;
#if defined(OS_MACOSX)
last_printed_page_ = SkBitmap();
#elif defined(OS_LINUX)
num_pages_ = 0;
pdf_output_done_ = false;
#endif // defined(OS_LINUX)
}
WebPluginDelegatePepper::WebPluginDelegatePepper(
const base::WeakPtr<RenderView>& render_view,
webkit::npapi::PluginInstance *instance)
: render_view_(render_view),
plugin_(NULL),
instance_(instance),
nested_delegate_(NULL),
current_printer_dpi_(-1),
#if defined (OS_LINUX)
num_pages_(0),
pdf_output_done_(false),
#endif // (OS_LINUX)
#if defined(ENABLE_GPU)
command_buffer_(NULL),
method_factory3d_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
#endif
find_identifier_(-1),
current_choose_file_callback_(NULL),
current_choose_file_user_data_(NULL) {
// For now we keep a window struct, although it isn't used.
memset(&window_, 0, sizeof(window_));
// All Pepper plugins are windowless and transparent.
// TODO(sehr): disable resetting these NPPVs by plugins.
instance->set_windowless(true);
instance->set_transparent(true);
}
WebPluginDelegatePepper::~WebPluginDelegatePepper() {
DestroyInstance();
if (render_view_)
render_view_->OnPepperPluginDestroy(this);
}
void WebPluginDelegatePepper::ForwardSetWindow() {
window_.clipRect.top = clip_rect_.y();
window_.clipRect.left = clip_rect_.x();
window_.clipRect.bottom = clip_rect_.y() + clip_rect_.height();
window_.clipRect.right = clip_rect_.x() + clip_rect_.width();
window_.height = window_rect_.height();
window_.width = window_rect_.width();
window_.x = window_rect_.x();
window_.y = window_rect_.y();
window_.type = NPWindowTypeDrawable;
instance()->NPP_SetWindow(&window_);
}
void WebPluginDelegatePepper::PluginDestroyed() {
delete this;
}
void WebPluginDelegatePepper::Paint(WebKit::WebCanvas* canvas,
const gfx::Rect& rect) {
if (nested_delegate_) {
// TODO(apatrick): The GPU plugin will render to an offscreen render target.
// Need to copy it to the screen here.
} else {
// Blit from background_context to context.
if (!committed_bitmap_.isNull()) {
#if defined(OS_MACOSX)
DrawSkBitmapToCanvas(committed_bitmap_, canvas, window_rect_,
static_cast<int>(CGBitmapContextGetHeight(canvas)));
#else
gfx::Point origin(window_rect_.origin().x(), window_rect_.origin().y());
canvas->drawBitmap(committed_bitmap_,
SkIntToScalar(window_rect_.origin().x()),
SkIntToScalar(window_rect_.origin().y()));
#endif
}
}
}
void WebPluginDelegatePepper::Print(gfx::NativeDrawingContext context) {
NOTIMPLEMENTED();
}
void WebPluginDelegatePepper::InstallMissingPlugin() {
NOTIMPLEMENTED();
}
void WebPluginDelegatePepper::SetFocus(bool focused) {
if (!focused)
return;
NPPepperEvent npevent;
npevent.type = NPEventType_Focus;
npevent.size = sizeof(npevent);
// TODO(sehr): what timestamp should this have?
npevent.timeStampSeconds = 0.0;
// Currently this API only supports gaining focus.
npevent.u.focus.value = 1;
instance()->NPP_HandleEvent(&npevent);
}
// Anonymous namespace for functions converting WebInputEvents to NPAPI types.
namespace {
NPEventTypes ConvertEventTypes(WebInputEvent::Type wetype) {
switch (wetype) {
case WebInputEvent::MouseDown:
return NPEventType_MouseDown;
case WebInputEvent::MouseUp:
return NPEventType_MouseUp;
case WebInputEvent::MouseMove:
return NPEventType_MouseMove;
case WebInputEvent::MouseEnter:
return NPEventType_MouseEnter;
case WebInputEvent::MouseLeave:
return NPEventType_MouseLeave;
case WebInputEvent::MouseWheel:
return NPEventType_MouseWheel;
case WebInputEvent::RawKeyDown:
return NPEventType_RawKeyDown;
case WebInputEvent::KeyDown:
return NPEventType_KeyDown;
case WebInputEvent::KeyUp:
return NPEventType_KeyUp;
case WebInputEvent::Char:
return NPEventType_Char;
case WebInputEvent::Undefined:
default:
return NPEventType_Undefined;
}
}
void BuildKeyEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebKeyboardEvent* key_event =
reinterpret_cast<const WebKeyboardEvent*>(event);
npevent->u.key.modifier = key_event->modifiers;
npevent->u.key.normalizedKeyCode = key_event->windowsKeyCode;
}
void BuildCharEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebKeyboardEvent* key_event =
reinterpret_cast<const WebKeyboardEvent*>(event);
npevent->u.character.modifier = key_event->modifiers;
// For consistency, check that the sizes of the texts agree.
DCHECK(sizeof(npevent->u.character.text) == sizeof(key_event->text));
DCHECK(sizeof(npevent->u.character.unmodifiedText) ==
sizeof(key_event->unmodifiedText));
for (size_t i = 0; i < WebKeyboardEvent::textLengthCap; ++i) {
npevent->u.character.text[i] = key_event->text[i];
npevent->u.character.unmodifiedText[i] = key_event->unmodifiedText[i];
}
}
void BuildMouseEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebMouseEvent* mouse_event =
reinterpret_cast<const WebMouseEvent*>(event);
npevent->u.mouse.modifier = mouse_event->modifiers;
npevent->u.mouse.button = mouse_event->button;
npevent->u.mouse.x = mouse_event->x;
npevent->u.mouse.y = mouse_event->y;
npevent->u.mouse.clickCount = mouse_event->clickCount;
}
void BuildMouseWheelEvent(const WebInputEvent* event, NPPepperEvent* npevent) {
const WebMouseWheelEvent* mouse_wheel_event =
reinterpret_cast<const WebMouseWheelEvent*>(event);
npevent->u.wheel.modifier = mouse_wheel_event->modifiers;
npevent->u.wheel.deltaX = mouse_wheel_event->deltaX;
npevent->u.wheel.deltaY = mouse_wheel_event->deltaY;
npevent->u.wheel.wheelTicksX = mouse_wheel_event->wheelTicksX;
npevent->u.wheel.wheelTicksY = mouse_wheel_event->wheelTicksY;
npevent->u.wheel.scrollByPage = mouse_wheel_event->scrollByPage;
}
} // namespace
bool WebPluginDelegatePepper::HandleInputEvent(const WebInputEvent& event,
WebCursorInfo* cursor_info) {
NPPepperEvent npevent;
npevent.type = ConvertEventTypes(event.type);
npevent.size = sizeof(npevent);
npevent.timeStampSeconds = event.timeStampSeconds;
switch (npevent.type) {
case NPEventType_Undefined:
return false;
case NPEventType_MouseDown:
case NPEventType_MouseUp:
case NPEventType_MouseMove:
case NPEventType_MouseEnter:
case NPEventType_MouseLeave:
BuildMouseEvent(&event, &npevent);
break;
case NPEventType_MouseWheel:
BuildMouseWheelEvent(&event, &npevent);
break;
case NPEventType_RawKeyDown:
case NPEventType_KeyDown:
case NPEventType_KeyUp:
BuildKeyEvent(&event, &npevent);
break;
case NPEventType_Char:
BuildCharEvent(&event, &npevent);
break;
case NPEventType_Minimize:
case NPEventType_Focus:
case NPEventType_Device:
// NOTIMPLEMENTED();
break;
}
bool rv = instance()->NPP_HandleEvent(&npevent) != 0;
if (cursor_.get())
*cursor_info = *cursor_;
return rv;
}
#if defined(ENABLE_GPU)
void WebPluginDelegatePepper::ScheduleHandleRepaint(
NPP npp, NPDeviceContext3D* context) {
command_buffer_->SetNotifyRepaintTask(method_factory3d_.NewRunnableMethod(
&WebPluginDelegatePepper::ForwardHandleRepaint,
npp,
context));
}
void WebPluginDelegatePepper::ForwardHandleRepaint(
NPP npp, NPDeviceContext3D* context) {
if (context->repaintCallback)
context->repaintCallback(npp, context);
ScheduleHandleRepaint(npp, context);
}
void WebPluginDelegatePepper::Synchronize3DContext(
NPDeviceContext3D* context,
const gpu::CommandBuffer::State& state) {
context->getOffset = state.get_offset;
context->putOffset = state.put_offset;
context->token = state.token;
context->error = static_cast<NPDeviceContext3DError>(state.error);
}
void WebPluginDelegatePepper::Device3DUpdateState(
NPP npp,
NPDeviceContext3D* context,
NPDeviceFlushContextCallbackPtr callback,
void* user_data) {
if (command_buffer_) {
Synchronize3DContext(context, command_buffer_->GetLastState());
if (callback)
callback(npp, context, NPERR_NO_ERROR, user_data);
}
}
#endif // ENABLE_GPU
void WebPluginDelegatePepper::SendNestedDelegateGeometryToBrowser(
const gfx::Rect& window_rect,
const gfx::Rect& clip_rect) {
// Inform the browser about the location of the plugin on the page.
// It appears that initially the plugin does not get laid out correctly --
// possibly due to lazy creation of the nested delegate.
if (!nested_delegate_ ||
!nested_delegate_->GetPluginWindowHandle() ||
!render_view_) {
return;
}
webkit::npapi::WebPluginGeometry geom;
geom.window = nested_delegate_->GetPluginWindowHandle();
geom.window_rect = window_rect;
geom.clip_rect = clip_rect;
// Rects_valid must be true for this to work in the Gtk port;
// hopefully not having the cutout rects will not cause incorrect
// clipping.
geom.rects_valid = true;
geom.visible = true;
render_view_->DidMovePlugin(geom);
}
bool WebPluginDelegatePepper::CalculatePrintedPageDimensions(
int page_number,
NPPPrintExtensions* print_extensions,
gfx::Size* page_dimensions) {
int32 width_in_pixels = 0;
int32 height_in_pixels = 0;
NPError err = print_extensions->getRasterDimensions(
instance()->npp(), page_number, &width_in_pixels, &height_in_pixels);
if (err != NPERR_NO_ERROR)
return false;
DCHECK(width_in_pixels && height_in_pixels);
page_dimensions->SetSize(width_in_pixels, height_in_pixels);
return true;
}
NPPPrintExtensions* WebPluginDelegatePepper::GetPrintExtensions() {
NPPPrintExtensions* ret = NULL;
NPPExtensions* extensions = NULL;
instance()->NPP_GetValue(NPPVPepperExtensions, &extensions);
if (extensions && extensions->getPrintExtensions)
ret = extensions->getPrintExtensions(instance()->npp());
return ret;
}
NPPFindExtensions* WebPluginDelegatePepper::GetFindExtensions() {
NPPFindExtensions* ret = NULL;
NPPExtensions* extensions = NULL;
instance()->NPP_GetValue(NPPVPepperExtensions, &extensions);
if (extensions && extensions->getFindExtensions)
ret = extensions->getFindExtensions(instance()->npp());
return ret;
}
#if defined(OS_WIN)
bool WebPluginDelegatePepper::DrawJPEGToPlatformDC(
const SkBitmap& bitmap,
const gfx::Rect& printable_area,
WebKit::WebCanvas* canvas) {
skia::VectorPlatformDevice& device =
static_cast<skia::VectorPlatformDevice&>(
canvas->getTopPlatformDevice());
HDC dc = device.getBitmapDC();
// TODO(sanjeevr): This is a temporary hack. If we output a JPEG
// to the EMF, the EnumEnhMetaFile call fails in the browser
// process. The failure also happens if we output nothing here.
// We need to investigate the reason for this failure and fix it.
// In the meantime this temporary hack of drawing an empty
// rectangle in the DC gets us by.
Rectangle(dc, 0, 0, 0, 0);
// Ideally we should add JPEG compression to the VectorPlatformDevice class
// However, Skia currently has no JPEG compression code and we cannot
// depend on gfx/jpeg_codec.h in Skia. So we do the compression here.
SkAutoLockPixels lock(bitmap);
DCHECK(bitmap.getConfig() == SkBitmap::kARGB_8888_Config);
const uint32_t* pixels =
static_cast<const uint32_t*>(bitmap.getPixels());
std::vector<unsigned char> compressed_image;
base::TimeTicks start_time = base::TimeTicks::Now();
bool encoded = gfx::JPEGCodec::Encode(
reinterpret_cast<const unsigned char*>(pixels),
gfx::JPEGCodec::FORMAT_BGRA, bitmap.width(), bitmap.height(),
static_cast<int>(bitmap.rowBytes()), 100, &compressed_image);
UMA_HISTOGRAM_TIMES("PepperPluginPrint.RasterBitmapCompressTime",
base::TimeTicks::Now() - start_time);
if (!encoded) {
NOTREACHED();
return false;
}
BITMAPINFOHEADER bmi = {0};
gfx::CreateBitmapHeader(bitmap.width(), bitmap.height(), &bmi);
bmi.biCompression = BI_JPEG;
bmi.biSizeImage = compressed_image.size();
bmi.biHeight = -bmi.biHeight;
StretchDIBits(dc, printable_area.x(), printable_area.y(),
printable_area.width(), printable_area.height(),
0, 0, bitmap.width(), bitmap.height(),
&compressed_image.front(),
reinterpret_cast<const BITMAPINFO*>(&bmi),
DIB_RGB_COLORS, SRCCOPY);
return true;
}
#endif // OS_WIN
#if defined(OS_MACOSX)
void WebPluginDelegatePepper::DrawSkBitmapToCanvas(
const SkBitmap& bitmap, WebKit::WebCanvas* canvas,
const gfx::Rect& dest_rect,
int canvas_height) {
SkAutoLockPixels lock(bitmap);
DCHECK(bitmap.getConfig() == SkBitmap::kARGB_8888_Config);
base::mac::ScopedCFTypeRef<CGDataProviderRef> data_provider(
CGDataProviderCreateWithData(
NULL, bitmap.getAddr32(0, 0),
bitmap.rowBytes() * bitmap.height(), NULL));
base::mac::ScopedCFTypeRef<CGImageRef> image(
CGImageCreate(
bitmap.width(), bitmap.height(),
8, 32, bitmap.rowBytes(),
mac_util::GetSystemColorSpace(),
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,
data_provider, NULL, false, kCGRenderingIntentDefault));
// Flip the transform
CGContextSaveGState(canvas);
CGContextTranslateCTM(canvas, 0, canvas_height);
CGContextScaleCTM(canvas, 1.0, -1.0);
CGRect bounds;
bounds.origin.x = dest_rect.x();
bounds.origin.y = canvas_height - dest_rect.y() - dest_rect.height();
bounds.size.width = dest_rect.width();
bounds.size.height = dest_rect.height();
CGContextDrawImage(canvas, bounds, image);
CGContextRestoreGState(canvas);
}
#endif // defined(OS_MACOSX)
|