summaryrefslogtreecommitdiffstats
path: root/webkit/glue/webplugin_impl.cc
blob: 83ee2bc44af993fbad5a31ff6b290146d2509c90 (plain)
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
// Copyright (c) 2006-2008 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.

#include "config.h"

#include "Document.h"
#include "DocumentLoader.h"
#include "Event.h"
#include "EventNames.h"
#include "FloatPoint.h"
#include "FormData.h"
#include "FormState.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoadRequest.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLFormElement.h"
#include "HTMLNames.h"
#include "HTMLPlugInElement.h"
#include "IntRect.h"
#include "KURL.h"
#include "KeyboardEvent.h"
#include "MouseEvent.h"
#include "Page.h"
#include "PlatformContextSkia.h"
#include "PlatformMouseEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformString.h"
#include "PlatformWidget.h"
#include "RenderBox.h"
#include "ResourceHandle.h"
#include "ResourceHandleClient.h"
#include "ResourceResponse.h"
#include "ScriptController.h"
#include "ScriptValue.h"
#include "ScrollView.h"
#include "Widget.h"

#undef LOG
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "net/base/escape.h"
#include "webkit/api/public/WebCursorInfo.h"
#include "webkit/api/public/WebData.h"
#include "webkit/api/public/WebHTTPBody.h"
#include "webkit/api/public/WebInputEvent.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/api/public/WebKitClient.h"
#include "webkit/api/public/WebString.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/api/public/WebURLLoader.h"
#include "webkit/api/public/WebURLLoaderClient.h"
#include "webkit/api/public/WebURLResponse.h"
#include "webkit/glue/chrome_client_impl.h"
#include "webkit/glue/event_conversion.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/multipart_response_delegate.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webplugin_impl.h"
#include "webkit/glue/plugins/plugin_host.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/stacking_order_iterator.h"
#include "webkit/glue/webplugin_delegate.h"
#include "webkit/glue/webview_impl.h"
#include "googleurl/src/gurl.h"

using WebKit::WebCursorInfo;
using WebKit::WebData;
using WebKit::WebHTTPBody;
using WebKit::WebInputEvent;
using WebKit::WebKeyboardEvent;
using WebKit::WebMouseEvent;
using WebKit::WebString;
using WebKit::WebURLError;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderClient;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
using webkit_glue::MultipartResponseDelegate;

// This class handles individual multipart responses. It is instantiated when
// we receive HTTP status code 206 in the HTTP response. This indicates
// that the response could have multiple parts each separated by a boundary
// specified in the response header.
class MultiPartResponseClient : public WebURLLoaderClient {
 public:
  MultiPartResponseClient(WebPluginResourceClient* resource_client)
      : resource_client_(resource_client) {
    Clear();
  }

  virtual void willSendRequest(
      WebURLLoader*, WebURLRequest&, const WebURLResponse&) {}
  virtual void didSendData(
      WebURLLoader*, unsigned long long, unsigned long long) {}

  // Called when the multipart parser encounters an embedded multipart
  // response.
  virtual void didReceiveResponse(
      WebURLLoader*, const WebURLResponse& response) {
    if (!MultipartResponseDelegate::ReadContentRanges(
            response,
            &byte_range_lower_bound_,
            &byte_range_upper_bound_)) {
      NOTREACHED();
      return;
    }

    resource_response_ = response;
  }

  // Receives individual part data from a multipart response.
  virtual void didReceiveData(
      WebURLLoader*, const char* data, int data_size, long long) {
    resource_client_->DidReceiveData(
        data, data_size, byte_range_lower_bound_);
  }

  virtual void didFinishLoading(WebURLLoader*) {}
  virtual void didFail(WebURLLoader*, const WebURLError&) {}

  void Clear() {
    resource_response_.reset();
    byte_range_lower_bound_ = 0;
    byte_range_upper_bound_ = 0;
  }

 private:
  WebURLResponse resource_response_;
  // The lower bound of the byte range.
  int byte_range_lower_bound_;
  // The upper bound of the byte range.
  int byte_range_upper_bound_;
  // The handler for the data.
  WebPluginResourceClient* resource_client_;
};

static std::wstring GetAllHeaders(const WebCore::ResourceResponse& response) {
  std::wstring result;
  const WebCore::String& status = response.httpStatusText();
  if (status.isEmpty())
    return result;

  result.append(L"HTTP ");
  result.append(FormatNumber(response.httpStatusCode()));
  result.append(L" ");
  result.append(webkit_glue::StringToStdWString(status));
  result.append(L"\n");

  WebCore::HTTPHeaderMap::const_iterator it =
      response.httpHeaderFields().begin();
  for (; it != response.httpHeaderFields().end(); ++it) {
    if (!it->first.isEmpty() && !it->second.isEmpty()) {
      result.append(webkit_glue::StringToStdWString(it->first));
      result.append(L": ");
      result.append(webkit_glue::StringToStdWString(it->second));
      result.append(L"\n");
    }
  }

  return result;
}

WebPluginContainer::WebPluginContainer(WebPluginImpl* impl)
    : impl_(impl),
      ignore_response_error_(false) {
}

WebPluginContainer::~WebPluginContainer() {
  impl_->SetContainer(NULL);
  MessageLoop::current()->DeleteSoon(FROM_HERE, impl_);
}

NPObject* WebPluginContainer::GetPluginScriptableObject() {
  return impl_->GetPluginScriptableObject();
}

#if USE(JSC)
bool WebPluginContainer::isPluginView() const {
  return true;
}
#endif


void WebPluginContainer::setFrameRect(const WebCore::IntRect& rect) {
  WebCore::Widget::setFrameRect(rect);
  impl_->setFrameRect(rect);
}

void WebPluginContainer::paint(WebCore::GraphicsContext* gc,
                               const WebCore::IntRect& damage_rect) {
  // In theory, we should call impl_->print(gc); when
  // impl_->webframe_->printing() is true but it still has placement issues so
  // keep that code off for now.
  impl_->paint(gc, damage_rect);
}

void WebPluginContainer::invalidateRect(const WebCore::IntRect& rect) {
  if (parent()) {
    WebCore::IntRect damageRect = convertToContainingWindow(rect);

    // Get our clip rect and intersect with it to ensure we don't
    // invalidate too much.
    WebCore::IntRect clipRect = parent()->windowClipRect();
    damageRect.intersect(clipRect);

    parent()->hostWindow()->repaint(damageRect, true);
  }
}

void WebPluginContainer::setFocus() {
  WebCore::Widget::setFocus();
  impl_->setFocus();
}

void WebPluginContainer::show() {
  setSelfVisible(true);
  impl_->UpdateVisibility();

  WebCore::Widget::show();
}

void WebPluginContainer::hide() {
  setSelfVisible(false);
  impl_->UpdateVisibility();

  WebCore::Widget::hide();
}

void WebPluginContainer::handleEvent(WebCore::Event* event) {
  impl_->handleEvent(event);
}

void WebPluginContainer::frameRectsChanged() {
  WebCore::Widget::frameRectsChanged();
  // This is a hack to tickle re-positioning of the plugin in the case where
  // our parent view was scrolled.
  impl_->setFrameRect(frameRect());
}

// We override this function, to make sure that geometry updates are sent
// over to the plugin. For e.g. when a plugin is instantiated it does
// not have a valid parent. As a result the first geometry update from
// webkit is ignored. This function is called when the plugin eventually
// gets a parent.
void WebPluginContainer::setParentVisible(bool visible) {
  if (isParentVisible() == visible)
    return;  // No change.

  WebCore::Widget::setParentVisible(visible);
  if (!isSelfVisible())
    return;  // This widget has explicitely been marked as not visible.

  impl_->UpdateVisibility();
}

// We override this function so that if the plugin is windowed, we can call
// NPP_SetWindow at the first possible moment.  This ensures that NPP_SetWindow
// is called before the manual load data is sent to a plugin.  If this order is
// reversed, Flash won't load videos.
void WebPluginContainer::setParent(WebCore::ScrollView* view) {
  WebCore::Widget::setParent(view);
  if (view) {
    impl_->setFrameRect(frameRect());
  }
}

void WebPluginContainer::windowCutoutRects(const WebCore::IntRect& bounds,
                                           WTF::Vector<WebCore::IntRect>*
                                           cutouts) const {
  impl_->windowCutoutRects(bounds, cutouts);
}

void WebPluginContainer::didReceiveResponse(
    const WebCore::ResourceResponse& response) {
  set_ignore_response_error(false);

  // Manual loading, so make sure that the plugin receives window geometry
  // before data, or else plugins misbehave.
  frameRectsChanged();

  HttpResponseInfo http_response_info;
  ReadHttpResponseInfo(response, &http_response_info);

  impl_->delegate_->DidReceiveManualResponse(
      http_response_info.url,
      base::SysWideToNativeMB(http_response_info.mime_type),
      base::SysWideToNativeMB(GetAllHeaders(response)),
      http_response_info.expected_length,
      http_response_info.last_modified);
}

void WebPluginContainer::didReceiveData(const char *buffer, int length) {
  impl_->delegate_->DidReceiveManualData(buffer, length);
}

void WebPluginContainer::didFinishLoading() {
  impl_->delegate_->DidFinishManualLoading();
}

void WebPluginContainer::didFail(const WebCore::ResourceError&) {
  if (!ignore_response_error_)
    impl_->delegate_->DidManualLoadFail();
}

void WebPluginContainer::ReadHttpResponseInfo(
    const WebCore::ResourceResponse& response,
    HttpResponseInfo* http_response) {
  std::wstring url = webkit_glue::StringToStdWString(response.url().string());
  http_response->url = WideToASCII(url);

  http_response->mime_type =
      webkit_glue::StringToStdWString(response.mimeType());

  http_response->last_modified =
      static_cast<uint32>(response.lastModifiedDate());
  // If the length comes in as -1, then it indicates that it was not
  // read off the HTTP headers. We replicate Safari webkit behavior here,
  // which is to set it to 0.
  http_response->expected_length =
      static_cast<uint32>(std::max(response.expectedContentLength(), 0LL));
  WebCore::String content_encoding =
      response.httpHeaderField("Content-Encoding");
  if (!content_encoding.isNull() && content_encoding != "identity") {
    // Don't send the compressed content length to the plugin, which only
    // cares about the decoded length.
    http_response->expected_length = 0;
  }
}

PassRefPtr<WebCore::Widget> WebPluginImpl::Create(const GURL& url,
                                       char** argn,
                                       char** argv,
                                       int argc,
                                       WebCore::HTMLPlugInElement* element,
                                       WebFrameImpl* frame,
                                       WebPluginDelegate* delegate,
                                       bool load_manually,
                                       const std::string& mime_type) {
  WebPluginImpl* webplugin = new WebPluginImpl(element, frame, delegate, url,
                                               load_manually, mime_type, argc,
                                               argn, argv);

  if (!delegate->Initialize(url, argn, argv, argc, webplugin, load_manually)) {
    delegate->PluginDestroyed();
    delegate = NULL;
    delete webplugin;
    return NULL;
  }

  WebPluginContainer* container = new WebPluginContainer(webplugin);
  webplugin->SetContainer(container);
  return adoptRef(container);
}

WebPluginImpl::WebPluginImpl(WebCore::HTMLPlugInElement* element,
                             WebFrameImpl* webframe,
                             WebPluginDelegate* delegate,
                             const GURL& plugin_url,
                             bool load_manually,
                             const std::string& mime_type,
                             int arg_count,
                             char** arg_names,
                             char** arg_values)
    : windowless_(false),
      window_(NULL),
      element_(element),
      webframe_(webframe),
      delegate_(delegate),
      widget_(NULL),
      plugin_url_(plugin_url),
      load_manually_(load_manually),
      first_geometry_update_(true),
      mime_type_(mime_type),
      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {

  ArrayToVector(arg_count, arg_names, &arg_names_);
  ArrayToVector(arg_count, arg_values, &arg_values_);
}

WebPluginImpl::~WebPluginImpl() {
}

#if defined(OS_LINUX)
gfx::PluginWindowHandle WebPluginImpl::CreatePluginContainer() {
  WebCore::Frame* frame = element_->document()->frame();
  WebFrameImpl* webframe = WebFrameImpl::FromFrame(frame);
  WebViewImpl* webview = webframe->GetWebViewImpl();
  if (!webview->delegate())
    return 0;
  return webview->delegate()->CreatePluginContainer();
}
#endif

void WebPluginImpl::SetWindow(gfx::PluginWindowHandle window) {
  if (window) {
    DCHECK(!windowless_);  // Make sure not called twice.
    window_ = window;
  } else {
    DCHECK(!window_);  // Make sure not called twice.
    windowless_ = true;
  }
}

void WebPluginImpl::WillDestroyWindow(gfx::PluginWindowHandle window) {
  WebCore::Frame* frame = element_->document()->frame();
  WebFrameImpl* webframe = WebFrameImpl::FromFrame(frame);
  WebViewImpl* webview = webframe->GetWebViewImpl();
  if (!webview->delegate())
    return;
  webview->delegate()->WillDestroyPluginWindow(window);
}

bool WebPluginImpl::CompleteURL(const std::string& url_in,
                                std::string* url_out) {
  if (!frame() || !frame()->document()) {
    NOTREACHED();
    return false;
  }

  WebCore::String str(webkit_glue::StdStringToString(url_in));
  WebCore::String url = frame()->document()->completeURL(str);
  std::wstring wurl = webkit_glue::StringToStdWString(url);
  *url_out = WideToUTF8(wurl);
  return true;
}

bool WebPluginImpl::ExecuteScript(const std::string& url,
                                  const std::wstring& script,
                                  bool notify_needed,
                                  intptr_t notify_data,
                                  bool popups_allowed) {
  // This could happen if the WebPluginContainer was already deleted.
  if (!frame())
    return false;

  // Pending resource fetches should also not trigger a callback.
  webframe_->set_plugin_delegate(NULL);

  WebCore::String script_str(webkit_glue::StdWStringToString(script));

  // Note: the call to executeScript might result in the frame being
  // deleted, so add an extra reference to it in this scope.
  // For KJS, keeping a pointer to the JSBridge is enough, but for V8
  // we also need to addref the frame.
  WTF::RefPtr<WebCore::Frame> cur_frame(frame());

  WebCore::ScriptValue result =
      frame()->loader()->executeScript(script_str, popups_allowed);
  WebCore::String script_result;
  std::wstring wresult;
  bool succ = false;
  if (result.getString(script_result)) {
    succ = true;
    wresult = webkit_glue::StringToStdWString(script_result);
  }

  // delegate_ could be NULL because executeScript caused the container to be
  // deleted.
  if (delegate_)
    delegate_->SendJavaScriptStream(url, wresult, succ, notify_needed,
                                    notify_data);

  return succ;
}

void WebPluginImpl::CancelResource(int id) {
  for (size_t i = 0; i < clients_.size(); ++i) {
    if (clients_[i].id == id) {
      if (clients_[i].loader.get()) {
        clients_[i].loader->cancel();
        RemoveClient(i);
      }
      return;
    }
  }
}

bool WebPluginImpl::SetPostData(WebURLRequest* request,
                                const char *buf,
                                uint32 length) {
  std::vector<std::string> names;
  std::vector<std::string> values;
  std::vector<char> body;
  bool rv = NPAPI::PluginHost::SetPostData(buf, length, &names, &values, &body);

  for (size_t i = 0; i < names.size(); ++i) {
    request->addHTTPHeaderField(webkit_glue::StdStringToWebString(names[i]),
                                webkit_glue::StdStringToWebString(values[i]));
  }

  WebString content_type_header = WebString::fromUTF8("Content-Type");
  const WebString& content_type =
      request->httpHeaderField(content_type_header);
  if (content_type.isEmpty()) {
    request->setHTTPHeaderField(
        content_type_header,
        WebString::fromUTF8("application/x-www-form-urlencoded"));
  }

  WebHTTPBody http_body;
  if (body.size()) {
    http_body.initialize();
    http_body.appendData(WebData(&body[0], body.size()));
  }
  request->setHTTPBody(http_body);

  return rv;
}

RoutingStatus WebPluginImpl::RouteToFrame(const char *method,
                                          bool is_javascript_url,
                                          const char* target, unsigned int len,
                                          const char* buf, bool is_file_data,
                                          bool notify, const char* url,
                                          GURL* completeURL) {
  // If there is no target, there is nothing to do
  if (!target)
    return NOT_ROUTED;

  // This could happen if the WebPluginContainer was already deleted.
  if (!frame())
    return NOT_ROUTED;

  // Take special action for JavaScript URLs
  WebCore::String str_target = target;
  if (is_javascript_url) {
    WebCore::Frame *frameTarget = frame()->tree()->find(str_target);
    // For security reasons, do not allow JavaScript on frames
    // other than this frame.
    if (frameTarget != frame()) {
      // FIXME - might be good to log this into a security
      //         log somewhere.
      return ROUTED;
    }

    // Route javascript calls back to the plugin.
    return NOT_ROUTED;
  }

  // If we got this far, we're routing content to a target frame.
  // Go fetch the URL.

  WebCore::String complete_url_str = frame()->document()->completeURL(
      WebCore::String(url));

  WebCore::KURL complete_url_kurl(complete_url_str);

  if (strcmp(method, "GET") != 0) {
    const WebCore::String& protocol_scheme =
          complete_url_kurl.protocol();
    // We're only going to route HTTP/HTTPS requests
    if ((protocol_scheme != "http") && (protocol_scheme != "https"))
      return INVALID_URL;
  }

  *completeURL = webkit_glue::KURLToGURL(complete_url_kurl);
  WebURLRequest request(webkit_glue::KURLToWebURL(complete_url_kurl));
  request.setHTTPMethod(WebString::fromUTF8(method));
  if (len > 0) {
    if (!is_file_data) {
      if (!SetPostData(&request, buf, len)) {
        // Uhoh - we're in trouble.  There isn't a good way
        // to recover at this point.  Break out.
        ASSERT_NOT_REACHED();
        return ROUTED;
      }
    } else {
      // TODO: Support "file" mode.  For now, just break out
      // since proceeding may do something unintentional.
      ASSERT_NOT_REACHED();
      return ROUTED;
    }
  }
  WebCore::FrameLoadRequest load_request(
      *webkit_glue::WebURLRequestToResourceRequest(&request));
  load_request.setFrameName(str_target);
  WebCore::FrameLoader *loader = frame()->loader();
  // we actually don't know whether usergesture is true or false,
  // passing true since all we can do is assume it is okay.
  loader->loadFrameRequest(
      load_request,
      false,  // lock history
      false,  // lock back forward list
      0,      // event
      0);     // form state

  // load() can cause the frame to go away.
  if (webframe_) {
    WebPluginDelegate* last_plugin = webframe_->plugin_delegate();
    if (last_plugin) {
      last_plugin->DidFinishLoadWithReason(NPRES_USER_BREAK);
      webframe_->set_plugin_delegate(NULL);
    }

    if (notify)
      webframe_->set_plugin_delegate(delegate_);
  }

  return ROUTED;
}

NPObject* WebPluginImpl::GetWindowScriptNPObject() {
  if (!frame()) {
    ASSERT_NOT_REACHED();
    return 0;
  }

  return frame()->script()->windowScriptNPObject();
}

NPObject* WebPluginImpl::GetPluginElement() {
  return element_->getNPObject();
}

void WebPluginImpl::SetCookie(const GURL& url,
                              const GURL& policy_url,
                              const std::string& cookie) {
  WebKit::webKitClient()->setCookies(url, policy_url, UTF8ToUTF16(cookie));
}

std::string WebPluginImpl::GetCookies(const GURL& url, const GURL& policy_url) {
  return UTF16ToUTF8(WebKit::webKitClient()->cookies(url, policy_url));
}

void WebPluginImpl::ShowModalHTMLDialog(const GURL& url, int width, int height,
                                        const std::string& json_arguments,
                                        std::string* json_retval) {
  if (webframe_ && webframe_->GetView() &&
      webframe_->GetView()->GetDelegate()) {
    webframe_->GetView()->GetDelegate()->ShowModalHTMLDialog(
        url, width, height, json_arguments, json_retval);
  }
}

void WebPluginImpl::OnMissingPluginStatus(int status) {
  NOTREACHED();
}

void WebPluginImpl::Invalidate() {
  if (widget_)
    widget_->invalidate();
}

void WebPluginImpl::InvalidateRect(const gfx::Rect& rect) {
  if (widget_)
    widget_->invalidateRect(webkit_glue::ToIntRect(rect));
}

WebCore::IntRect WebPluginImpl::windowClipRect() const {
  // This is based on the code in WebCore/plugins/win/PluginViewWin.cpp:
  WebCore::IntRect rect(0, 0, widget_->width(), widget_->height());

  // Start by clipping to our bounds.
  WebCore::IntRect clip_rect = widget_->convertToContainingWindow(
      WebCore::IntRect(0, 0, widget_->width(), widget_->height()));

  // Take our element and get the clip rect from the enclosing layer and
  // frame view.
  WebCore::RenderLayer* layer = element_->renderer()->enclosingLayer();

  // document()->renderer() can be NULL when we receive messages from the
  // plugins while we are destroying a frame.
  if (element_->renderer()->document()->renderer()) {
    WebCore::FrameView* parent_view = element_->document()->view();
    clip_rect.intersect(parent_view->windowClipRectForLayer(layer, true));
  }

  return clip_rect;
}

void WebPluginImpl::windowCutoutRects(
    const WebCore::IntRect& bounds,
    WTF::Vector<WebCore::IntRect>* cutouts) const {
  WebCore::RenderObject* plugin_node = element_->renderer();
  ASSERT(plugin_node);

  // Find all iframes that stack higher than this plugin.
  bool higher = false;
  StackingOrderIterator iterator;
  WebCore::RenderLayer* root = element_->document()->renderer()->
                               enclosingLayer();
  iterator.Reset(bounds, root);

  while (WebCore::RenderObject* ro = iterator.Next()) {
    if (ro == plugin_node) {
      // All nodes after this one are higher than plugin.
      higher = true;
    } else if (higher) {
      // Is this a visible iframe?
      WebCore::Node* n = ro->node();
      if (n && n->hasTagName(WebCore::HTMLNames::iframeTag)) {
        if (!ro->style() || ro->style()->visibility() == WebCore::VISIBLE) {
          WebCore::IntPoint point = roundedIntPoint(ro->localToAbsolute());
          WebCore::RenderBox* rbox = WebCore::toRenderBox(ro);
          WebCore::IntSize size(rbox->width(), rbox->height());
          cutouts->append(WebCore::IntRect(point, size));
        }
      }
    }
  }
}

void WebPluginImpl::setFrameRect(const WebCore::IntRect& rect) {
  if (!parent())
    return;

  // Compute a new position and clip rect for ourselves relative to the
  // containing window.  We ask our delegate to reposition us accordingly.
  WebCore::Frame* frame = element_->document()->frame();
  WebFrameImpl* webframe = WebFrameImpl::FromFrame(frame);
  WebViewImpl* webview = webframe->GetWebViewImpl();
  // It is valid for this function to be invoked in code paths where the
  // the webview is closed.
  if (!webview->delegate()) {
    return;
  }

  WebCore::IntRect window_rect;
  WebCore::IntRect clip_rect;
  std::vector<gfx::Rect> cutout_rects;
  CalculateBounds(rect, &window_rect, &clip_rect, &cutout_rects);

  if (window_) {
    // Notify the window hosting the plugin (the WebViewDelegate) that
    // it needs to adjust the plugin, so that all the HWNDs can be moved
    // at the same time.
    WebPluginGeometry move;
    move.window = window_;
    move.window_rect = webkit_glue::FromIntRect(window_rect);
    move.clip_rect = webkit_glue::FromIntRect(clip_rect);
    move.cutout_rects = cutout_rects;
    move.rects_valid = true;
    move.visible = widget_->isVisible();

    webview->delegate()->DidMove(webview, move);
  }

  // Notify the plugin that its parameters have changed.
  delegate_->UpdateGeometry(webkit_glue::FromIntRect(window_rect),
                            webkit_glue::FromIntRect(clip_rect));

  // Initiate a download on the plugin url. This should be done for the
  // first update geometry sequence. We need to ensure that the plugin
  // receives the geometry update before it starts receiving data.
  if (first_geometry_update_) {
    first_geometry_update_ = false;
    // An empty url corresponds to an EMBED tag with no src attribute.
    if (!load_manually_ && plugin_url_.is_valid()) {
      // The Flash plugin hangs for a while if it receives data before
      // receiving valid plugin geometry. By valid geometry we mean the
      // geometry received by a call to setFrameRect in the Webkit
      // layout code path. To workaround this issue we download the
      // plugin source url on a timer.
      MessageLoop::current()->PostDelayedTask(FROM_HERE,
          method_factory_.NewRunnableMethod(
              &WebPluginImpl::OnDownloadPluginSrcUrl),
          0);
    }
  }
}

void WebPluginImpl::OnDownloadPluginSrcUrl() {
  HandleURLRequestInternal("GET", false, NULL, 0, NULL, false, false,
                           plugin_url_.spec().c_str(), NULL, false,
                           false);
}

void WebPluginImpl::paint(WebCore::GraphicsContext* gc,
                          const WebCore::IntRect& damage_rect) {
  if (gc->paintingDisabled())
    return;

  if (!parent())
    return;

  // Don't paint anything if the plugin doesn't intersect the damage rect.
  if (!widget_->frameRect().intersects(damage_rect))
    return;

  gc->save();

  DCHECK(parent()->isFrameView());
  WebCore::FrameView* view = static_cast<WebCore::FrameView*>(parent());

  // The plugin is positioned in window coordinates, so it needs to be painted
  // in window coordinates.
  WebCore::IntPoint origin = view->windowToContents(WebCore::IntPoint(0, 0));
  gc->translate(static_cast<float>(origin.x()),
                static_cast<float>(origin.y()));

#if defined(OS_WIN) || defined(OS_LINUX)
  // Note that |context| is only used when in windowless mode.
  gfx::NativeDrawingContext context =
      gc->platformContext()->canvas()->beginPlatformPaint();
#elif defined(OS_MACOSX)
  gfx::NativeDrawingContext context = gc->platformContext();
#endif

  WebCore::IntRect window_rect =
      WebCore::IntRect(view->contentsToWindow(damage_rect.location()),
                       damage_rect.size());

  delegate_->Paint(context, webkit_glue::FromIntRect(window_rect));

#if defined(OS_WIN) || defined(OS_LINUX)
  gc->platformContext()->canvas()->endPlatformPaint();
#endif
  gc->restore();
}

void WebPluginImpl::print(WebCore::GraphicsContext* gc) {
  if (gc->paintingDisabled())
    return;

  if (!parent())
    return;

  gc->save();
#if defined(OS_WIN)
  gfx::NativeDrawingContext hdc =
       gc->platformContext()->canvas()->beginPlatformPaint();
  delegate_->Print(hdc);
  gc->platformContext()->canvas()->endPlatformPaint();
#else
  NOTIMPLEMENTED();
#endif
  gc->restore();
}

void WebPluginImpl::setFocus() {
  if (windowless_)
    delegate_->SetFocus();
}

void WebPluginImpl::handleEvent(WebCore::Event* event) {
  if (!windowless_)
    return;

  // Pass events to the plugin.
  // The events we pass are defined at:
  //    http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
  // Don't take the documentation as truth, however.  I've found
  // many cases where mozilla behaves differently than the spec.
  if (event->isMouseEvent())
    handleMouseEvent(static_cast<WebCore::MouseEvent*>(event));
  else if (event->isKeyboardEvent())
    handleKeyboardEvent(static_cast<WebCore::KeyboardEvent*>(event));
}

void WebPluginImpl::handleMouseEvent(WebCore::MouseEvent* event) {
  DCHECK(parent()->isFrameView());
  // We cache the parent FrameView here as the plugin widget could be deleted
  // in the call to HandleEvent. See http://b/issue?id=1362948
  WebCore::FrameView* parent_view = static_cast<WebCore::FrameView*>(parent());

  WebMouseEvent web_event;
  if (!ToWebMouseEvent(*parent_view, *event, &web_event))
    return;

  if (event->type() == WebCore::eventNames().mousedownEvent) {
    // Ensure that the frame containing the plugin has focus.
    WebCore::Frame* containing_frame = webframe_->frame();
    if (WebCore::Page* current_page = containing_frame->page()) {
      current_page->focusController()->setFocusedFrame(containing_frame);
    }
    // Give focus to our containing HTMLPluginElement.
    containing_frame->document()->setFocusedNode(element_);
  }

  // TODO(pkasting): http://b/1119691 This conditional seems exactly backwards,
  // but it matches Safari's code, and if I reverse it, giving focus to a
  // transparent (windowless) plugin fails.
  WebCursorInfo cursor_info;
  if (!delegate_->HandleInputEvent(web_event, &cursor_info))
    event->setDefaultHandled();

  WebCore::Page* page = parent_view->frame()->page();
  if (!page)
    return;

  ChromeClientImpl* chrome_client =
      static_cast<ChromeClientImpl*>(page->chrome()->client());

  // A windowless plugin can change the cursor in response to the WM_MOUSEMOVE
  // event. We need to reflect the changed cursor in the frame view as the
  // mouse is moved in the boundaries of the windowless plugin.
  chrome_client->SetCursorForPlugin(cursor_info);
}

void WebPluginImpl::handleKeyboardEvent(WebCore::KeyboardEvent* event) {
  WebKeyboardEvent web_event;
  if (!ToWebKeyboardEvent(*event, &web_event))
    return;
  // TODO(pkasting): http://b/1119691 See above.
  WebCursorInfo cursor_info;
  if (!delegate_->HandleInputEvent(web_event, &cursor_info))
    event->setDefaultHandled();
}

NPObject* WebPluginImpl::GetPluginScriptableObject() {
  return delegate_->GetPluginScriptableObject();
}

WebPluginResourceClient* WebPluginImpl::GetClientFromLoader(
    WebURLLoader* loader) {
  for (size_t i = 0; i < clients_.size(); ++i) {
    if (clients_[i].loader.get() == loader)
      return clients_[i].client;
  }

  NOTREACHED();
  return 0;
}


void WebPluginImpl::willSendRequest(WebURLLoader* loader,
                                    WebURLRequest& request,
                                    const WebURLResponse&) {
  WebPluginResourceClient* client = GetClientFromLoader(loader);
  if (client)
    client->WillSendRequest(request.url());
}

void WebPluginImpl::didSendData(WebURLLoader* loader,
                                unsigned long long bytes_sent,
                                unsigned long long total_bytes_to_be_sent) {
}

void WebPluginImpl::didReceiveResponse(WebURLLoader* loader,
                                       const WebURLResponse& response) {
  static const int kHttpPartialResponseStatusCode = 206;
  static const int kHttpResponseSuccessStatusCode = 200;

  WebPluginResourceClient* client = GetClientFromLoader(loader);
  if (!client)
    return;

  const WebCore::ResourceResponse& resource_response =
      *webkit_glue::WebURLResponseToResourceResponse(&response);

  WebPluginContainer::HttpResponseInfo http_response_info;
  WebPluginContainer::ReadHttpResponseInfo(resource_response,
                                           &http_response_info);

  bool cancel = false;
  bool request_is_seekable = true;
  if (client->IsMultiByteResponseExpected()) {
    if (response.httpStatusCode() == kHttpPartialResponseStatusCode) {
      HandleHttpMultipartResponse(response, client);
      return;
    } else if (response.httpStatusCode() == kHttpResponseSuccessStatusCode) {
      // If the client issued a byte range request and the server responds with
      // HTTP 200 OK, it indicates that the server does not support byte range
      // requests.
      // We need to emulate Firefox behavior by doing the following:-
      // 1. Destroy the plugin instance in the plugin process. Ensure that
      //    existing resource requests initiated for the plugin instance
      //    continue to remain valid.
      // 2. Create a new plugin instance and notify it about the response
      //    received here.
      if (!ReinitializePluginForResponse(loader)) {
        NOTREACHED();
        return;
      }

      // The server does not support byte range requests. No point in creating
      // seekable streams.
      request_is_seekable = false;

      delete client;
      client = NULL;

      // Create a new resource client for this request.
      for (size_t i = 0; i < clients_.size(); ++i) {
        if (clients_[i].loader.get() == loader) {
          WebPluginResourceClient* resource_client =
              delegate_->CreateResourceClient(clients_[i].id,
                                              plugin_url_.spec().c_str(),
                                              false, 0, NULL);
          clients_[i].client = resource_client;
          client = resource_client;
          break;
        }
      }

      DCHECK(client != NULL);
    }
  }

  client->DidReceiveResponse(
      base::SysWideToNativeMB(http_response_info.mime_type),
      base::SysWideToNativeMB(GetAllHeaders(resource_response)),
      http_response_info.expected_length,
      http_response_info.last_modified, request_is_seekable, &cancel);

  if (cancel) {
    loader->cancel();
    RemoveClient(loader);
    return;
  }

  // Bug http://b/issue?id=925559. The flash plugin would not handle the HTTP
  // error codes in the stream header and as a result, was unaware of the
  // fate of the HTTP requests issued via NPN_GetURLNotify. Webkit and FF
  // destroy the stream and invoke the NPP_DestroyStream function on the
  // plugin if the HTTP request fails.
  const GURL& url = response.url();
  if (url.SchemeIs("http") || url.SchemeIs("https")) {
    if (response.httpStatusCode() < 100 || response.httpStatusCode() >= 400) {
      // The plugin instance could be in the process of deletion here.
      // Verify if the WebPluginResourceClient instance still exists before
      // use.
      WebPluginResourceClient* resource_client = GetClientFromLoader(loader);
      if (resource_client) {
        loader->cancel();
        resource_client->DidFail();
        RemoveClient(loader);
      }
    }
  }
}

void WebPluginImpl::didReceiveData(WebURLLoader* loader,
                                   const char *buffer,
                                   int length, long long) {
  WebPluginResourceClient* client = GetClientFromLoader(loader);
  if (!client)
    return;
  MultiPartResponseHandlerMap::iterator index =
      multi_part_response_map_.find(client);
  if (index != multi_part_response_map_.end()) {
    MultipartResponseDelegate* multi_part_handler = (*index).second;
    DCHECK(multi_part_handler != NULL);
    multi_part_handler->OnReceivedData(buffer, length);
  } else {
    client->DidReceiveData(buffer, length, 0);
  }
}

void WebPluginImpl::didFinishLoading(WebURLLoader* loader) {
  WebPluginResourceClient* client = GetClientFromLoader(loader);
  if (client) {
    MultiPartResponseHandlerMap::iterator index =
        multi_part_response_map_.find(client);
    if (index != multi_part_response_map_.end()) {
      delete (*index).second;
      multi_part_response_map_.erase(index);

      WebView* web_view = webframe_->GetView();
      web_view->GetDelegate()->DidStopLoading(web_view);
    }
    client->DidFinishLoading();
  }

  RemoveClient(loader);
}

void WebPluginImpl::didFail(WebURLLoader* loader,
                            const WebURLError&) {
  WebPluginResourceClient* client = GetClientFromLoader(loader);
  if (client)
    client->DidFail();

  RemoveClient(loader);
}

void WebPluginImpl::RemoveClient(size_t i) {
  clients_.erase(clients_.begin() + i);
}

void WebPluginImpl::RemoveClient(WebURLLoader* loader) {
  for (size_t i = 0; i < clients_.size(); ++i) {
    if (clients_[i].loader.get() == loader) {
      RemoveClient(i);
      return;
    }
  }
}

void WebPluginImpl::SetContainer(WebPluginContainer* container) {
  if (container == NULL) {
    TearDownPluginInstance(NULL);
  }
  widget_ = container;
}

WebCore::ScrollView* WebPluginImpl::parent() const {
  if (widget_)
    return widget_->parent();

  return NULL;
}

void WebPluginImpl::CalculateBounds(const WebCore::IntRect& frame_rect,
                                    WebCore::IntRect* window_rect,
                                    WebCore::IntRect* clip_rect,
                                    std::vector<gfx::Rect>* cutout_rects) {
  DCHECK(parent()->isFrameView());
  WebCore::FrameView* view = static_cast<WebCore::FrameView*>(parent());

  *window_rect =
      WebCore::IntRect(view->contentsToWindow(frame_rect.location()),
                                              frame_rect.size());
  // Calculate a clip-rect so that we don't overlap the scrollbars, etc.
  *clip_rect = windowClipRect();
  clip_rect->move(-window_rect->x(), -window_rect->y());

  cutout_rects->clear();
  WTF::Vector<WebCore::IntRect> rects;
  widget_->windowCutoutRects(frame_rect, &rects);
  // Convert to gfx::Rect and subtract out the plugin position.
  for (size_t i = 0; i < rects.size(); i++) {
    gfx::Rect r = webkit_glue::FromIntRect(rects[i]);
    r.Offset(-frame_rect.x(), -frame_rect.y());
    cutout_rects->push_back(r);
  }
}

void WebPluginImpl::HandleURLRequest(const char *method,
                                     bool is_javascript_url,
                                     const char* target, unsigned int len,
                                     const char* buf, bool is_file_data,
                                     bool notify, const char* url,
                                     intptr_t notify_data, bool popups_allowed) {
  HandleURLRequestInternal(method, is_javascript_url, target, len, buf,
                           is_file_data, notify, url, notify_data,
                           popups_allowed, true);
}

void WebPluginImpl::HandleURLRequestInternal(
    const char *method, bool is_javascript_url, const char* target,
    unsigned int len, const char* buf, bool is_file_data, bool notify,
    const char* url, intptr_t notify_data, bool popups_allowed,
    bool use_plugin_src_as_referrer) {
  // For this request, we either route the output to a frame
  // because a target has been specified, or we handle the request
  // here, i.e. by executing the script if it is a javascript url
  // or by initiating a download on the URL, etc. There is one special
  // case in that the request is a javascript url and the target is "_self",
  // in which case we route the output to the plugin rather than routing it
  // to the plugin's frame.
  GURL complete_url;
  int routing_status = RouteToFrame(method, is_javascript_url, target, len,
                                    buf, is_file_data, notify, url,
                                    &complete_url);
  if (routing_status == ROUTED) {
    // The delegate could have gone away because of this call.
    if (delegate_)
      delegate_->URLRequestRouted(url, notify, notify_data);
    return;
  }

  if (is_javascript_url) {
    std::string original_url = url;

    // Convert the javascript: URL to javascript by unescaping. WebCore uses
    // decode_string for this, so we do, too.
    std::string escaped_script = original_url.substr(strlen("javascript:"));
    WebCore::String script = WebCore::decodeURLEscapeSequences(
        WebCore::String(escaped_script.data(),
                                  static_cast<int>(escaped_script.length())));

    ExecuteScript(original_url, webkit_glue::StringToStdWString(script), notify,
                  notify_data, popups_allowed);
  } else {
    std::string complete_url_string;
    CompleteURL(url, &complete_url_string);

    int resource_id = GetNextResourceId();
    WebPluginResourceClient* resource_client =
        delegate_->CreateResourceClient(resource_id, complete_url_string,
                                        notify, notify_data, NULL);

    // If the RouteToFrame call returned a failure then inform the result
    // back to the plugin asynchronously.
    if ((routing_status == INVALID_URL) ||
        (routing_status == GENERAL_FAILURE)) {
      resource_client->DidFail();
      return;
    }

    InitiateHTTPRequest(resource_id, resource_client, method, buf, len,
                        GURL(complete_url_string), NULL,
                        use_plugin_src_as_referrer);
  }
}

int WebPluginImpl::GetNextResourceId() {
  static int next_id = 0;
  return ++next_id;
}

bool WebPluginImpl::InitiateHTTPRequest(int resource_id,
                                        WebPluginResourceClient* client,
                                        const char* method, const char* buf,
                                        int buf_len,
                                        const GURL& url,
                                        const char* range_info,
                                        bool use_plugin_src_as_referrer) {
  if (!client) {
    NOTREACHED();
    return false;
  }

  ClientInfo info;
  info.id = resource_id;
  info.client = client;
  info.request.initialize();
  info.request.setURL(url);
  info.request.setRequestorProcessID(delegate_->GetProcessId());
  info.request.setTargetType(WebURLRequest::TargetIsObject);
  info.request.setHTTPMethod(WebString::fromUTF8(method));

  if (range_info) {
    info.request.addHTTPHeaderField(WebString::fromUTF8("Range"),
                                    WebString::fromUTF8(range_info));
  }

  WebCore::String referrer;
  // GetURL/PostURL requests initiated explicitly by plugins should specify the
  // plugin SRC url as the referrer if it is available.
  if (use_plugin_src_as_referrer && !plugin_url_.spec().empty()) {
    referrer = webkit_glue::StdStringToString(plugin_url_.spec());
  } else {
    referrer = frame()->loader()->outgoingReferrer();
  }

  if (!WebCore::FrameLoader::shouldHideReferrer(webkit_glue::GURLToKURL(url),
                                                referrer)) {
    info.request.setHTTPHeaderField(WebString::fromUTF8("Referer"),
                                    webkit_glue::StringToWebString(referrer));
  }

  if (strcmp(method, "POST") == 0) {
    // Adds headers or form data to a request.  This must be called before
    // we initiate the actual request.
    SetPostData(&info.request, buf, buf_len);
  }

  // Sets the routing id to associate the ResourceRequest with the RenderView.
  WebCore::ResourceResponse response;
  frame()->loader()->client()->dispatchWillSendRequest(
      NULL,
      0,
      *webkit_glue::WebURLRequestToMutableResourceRequest(&info.request),
      response);

  info.loader.reset(WebKit::webKitClient()->createURLLoader());
  if (!info.loader.get())
    return false;
  info.loader->loadAsynchronously(info.request, this);

  clients_.push_back(info);
  return true;
}

void WebPluginImpl::CancelDocumentLoad() {
  if (frame()->loader()->activeDocumentLoader()) {
    widget_->set_ignore_response_error(true);
    frame()->loader()->activeDocumentLoader()->stopLoading();
  }
}

void WebPluginImpl::InitiateHTTPRangeRequest(const char* url,
                                             const char* range_info,
                                             intptr_t existing_stream,
                                             bool notify_needed,
                                             intptr_t notify_data) {
  int resource_id = GetNextResourceId();
  std::string complete_url_string;
  CompleteURL(url, &complete_url_string);

  WebPluginResourceClient* resource_client =
      delegate_->CreateResourceClient(resource_id, complete_url_string,
                                      notify_needed, notify_data,
                                      existing_stream);
  InitiateHTTPRequest(resource_id, resource_client, "GET", NULL, 0,
                      GURL(complete_url_string), range_info, true);
}

void WebPluginImpl::HandleHttpMultipartResponse(
    const WebURLResponse& response,
    WebPluginResourceClient* client) {
  std::string multipart_boundary;
  if (!MultipartResponseDelegate::ReadMultipartBoundary(
          response, &multipart_boundary)) {
    NOTREACHED();
    return;
  }

  WebView* web_view = webframe_->GetView();
  web_view->GetDelegate()->DidStartLoading(web_view);

  MultiPartResponseClient* multi_part_response_client =
      new MultiPartResponseClient(client);

  MultipartResponseDelegate* multi_part_response_handler =
      new MultipartResponseDelegate(multi_part_response_client, NULL,
                                    response,
                                    multipart_boundary);
  multi_part_response_map_[client] = multi_part_response_handler;
}

bool WebPluginImpl::ReinitializePluginForResponse(
    WebURLLoader* loader) {
  WebFrameImpl* web_frame = WebFrameImpl::FromFrame(frame());
  if (!web_frame)
    return false;

  WebViewImpl* web_view = web_frame->GetWebViewImpl();
  if (!web_view)
    return false;

  WebPluginContainer* container_widget = widget_;

  // Destroy the current plugin instance.
  TearDownPluginInstance(loader);

  widget_ = container_widget;
  webframe_ = web_frame;

  WebViewDelegate* webview_delegate = web_view->GetDelegate();
  std::string actual_mime_type;
  WebPluginDelegate* plugin_delegate =
      webview_delegate->CreatePluginDelegate(web_view, plugin_url_,
                                             mime_type_, std::string(),
                                             &actual_mime_type);

  char** arg_names = new char*[arg_names_.size()];
  char** arg_values = new char*[arg_values_.size()];

  for (unsigned int index = 0; index < arg_names_.size(); ++index) {
    arg_names[index] = const_cast<char*>(arg_names_[index].c_str());
    arg_values[index] = const_cast<char*>(arg_values_[index].c_str());
  }

  bool init_ok = plugin_delegate->Initialize(plugin_url_, arg_names,
                                             arg_values, arg_names_.size(),
                                             this, load_manually_);
  delete[] arg_names;
  delete[] arg_values;

  if (!init_ok) {
    widget_ = NULL;
    // TODO(iyengar) Should we delete the current plugin instance here?
    return false;
  }

  mime_type_ = actual_mime_type;
  delegate_ = plugin_delegate;
  // Force a geometry update to occur to ensure that the plugin becomes
  // visible.
  widget_->frameRectsChanged();
  // The plugin move sequences accumulated via DidMove are sent to the browser
  // whenever the renderer paints. Force a paint here to ensure that changes
  // to the plugin window are propagated to the browser.
  widget_->invalidateRect(widget_->frameRect());
  return true;
}

void WebPluginImpl::ArrayToVector(int total_values, char** values,
                                  std::vector<std::string>* value_vector) {
  DCHECK(value_vector != NULL);
  for (int index = 0; index < total_values; ++index) {
    value_vector->push_back(values[index]);
  }
}

void WebPluginImpl::TearDownPluginInstance(
    WebURLLoader* loader_to_ignore) {
  // The frame maintains a list of JSObjects which are related to this
  // plugin.  Tell the frame we're gone so that it can invalidate all
  // of those sub JSObjects.
  if (frame()) {
    ASSERT(widget_);
    frame()->script()->cleanupScriptObjectsForPlugin(widget_);
  }

  if (delegate_) {
    // Call PluginDestroyed() first to prevent the plugin from calling us back
    // in the middle of tearing down the render tree.
    delegate_->PluginDestroyed();
    delegate_ = NULL;
  }

  // Cancel any pending requests because otherwise this deleted object will
  // be called by the ResourceDispatcher.
  std::vector<ClientInfo>::iterator client_index = clients_.begin();
  while (client_index != clients_.end()) {
    ClientInfo& client_info = *client_index;

    if (loader_to_ignore == client_info.loader) {
      client_index++;
      continue;
    }

    if (client_info.loader.get())
      client_info.loader->cancel();

    WebPluginResourceClient* resource_client = client_info.client;
    client_index = clients_.erase(client_index);
    if (resource_client)
      resource_client->DidFail();
  }

  // This needs to be called now and not in the destructor since the
  // webframe_ might not be valid anymore.
  webframe_->set_plugin_delegate(NULL);
  webframe_ = NULL;
  method_factory_.RevokeAll();
}

void WebPluginImpl::UpdateVisibility() {
  if (!window_)
    return;

  WebCore::Frame* frame = element_->document()->frame();
  WebFrameImpl* webframe = WebFrameImpl::FromFrame(frame);
  WebViewImpl* webview = webframe->GetWebViewImpl();
  if (!webview->delegate())
    return;

  WebPluginGeometry move;
  move.window = window_;
  move.window_rect = gfx::Rect();
  move.clip_rect = gfx::Rect();
  move.rects_valid = false;
  move.visible = widget_->isVisible();

  webview->delegate()->DidMove(webview, move);
}