-
Notifications
You must be signed in to change notification settings - Fork 15.1k
/
electron_api_web_contents.cc
4632 lines (4026 loc) · 164 KB
/
electron_api_web_contents.cc
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
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/navigation_controller_impl.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::JavaScriptDialogType> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
content::JavaScriptDialogType val) {
switch (val) {
case content::JAVASCRIPT_DIALOG_TYPE_ALERT:
return gin::ConvertToV8(isolate, "alert");
case content::JAVASCRIPT_DIALOG_TYPE_CONFIRM:
return gin::ConvertToV8(isolate, "confirm");
case content::JAVASCRIPT_DIALOG_TYPE_PROMPT:
return gin::ConvertToV8(isolate, "prompt");
}
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
auto ui_task_runner = content::GetUIThreadTaskRunner({});
if (!ui_task_runner->RunsTasksInCurrentSequence()) {
ui_task_runner->PostTask(
FROM_HERE, base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle), bitmap));
return;
}
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
// Get transparent for guest view
options.Get("transparent", &guest_transparent_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
bool initially_shown = true;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}