forked from cztomczak/cefpython
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcefpython.pyx
More file actions
1202 lines (1075 loc) · 48.6 KB
/
Copy pathcefpython.pyx
File metadata and controls
1202 lines (1075 loc) · 48.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2012 CEF Python, see the Authors file.
# All rights reserved. Licensed under BSD 3-clause license.
# Project website: https://github.com/cztomczak/cefpython
# IMPORTANT notes:
#
# - cdef/cpdef functions returning something other than a Python object
# should have in its declaration "except *", otherwise exceptions are
# ignored. Those cdef/cpdef that return "object" have "except *" by
# default. The setup/compile.py script will check for functions missing
# "except *" and will display an error message about that, but it's
# not perfect and won't detect all cases.
#
# - TODO: add checking for "except * with gil" in functions with the
# "public" keyword
#
# - about acquiring/releasing GIL lock, see discussion here:
# https://groups.google.com/forum/?fromgroups=#!topic/cython-users/jcvjpSOZPp0
#
# - <CefRefPtr[ClientHandler]?>new ClientHandler()
# <...?> means to throw an error if the cast is not allowed
#
# - in client handler callbacks (or others that are called from C++ and
# use "except * with gil") must embrace all code in try..except otherwise
# the error will be ignored, only printed to the output console, this is the
# default behavior of Cython, to remedy this you are supposed to add "except *"
# in function declaration, unfortunately it does not work, some conflict with
# CEF threading, see topic at cython-users for more details:
# https://groups.google.com/d/msg/cython-users/CRxWoX57dnM/aufW3gXMhOUJ.
#
# - Note that acquiring the GIL is a blocking thread-synchronising operation,
# and therefore potentially costly. It might not be worth releasing the GIL
# for minor calculations. Usually, I/O operations and substantial
# computations in parallel code will benefit from it.
#
# - In regards to GIL locks see Issue #102 "Remove GIL to avoid deadlocks when
# calling CEF functions".
#
# - CTags requires all functions/methods imported in .pxd files to be preceded with "cdef",
# otherwise they are not indexed.
#
# - __del__ method does not exist in Extension Types (cdef class),
# you have to use __dealloc__ instead, try to remember that as
# defining __del__ will not raise any warning and could lead to
# memory leaks.
#
# - CefString.c_str() is safe to use only on Windows, on Ubuntu 64bit
# for a "Pers" string it returns: "P\x00e\x00r\x00s\x00", which is
# most probably not what you expected.
#
# - You can rename methods when importing in pxd files:
# | cdef cppclass _Object "Object":
#
# - Supporting operators that are not yet supported:
# | RetValue& Assign "operator="(T* p)
# | object.Assign(T*)
# In the same way you can import function with a different name, this one
# imports a static method Create() while adding a prefix "CefSome_":
# | cdef extern from "..":
# | static CefRefPtr[CefSome] CefSome_Create "CefSome::Create"()
#
# - Declaring C++ classes in Cython. Storing python callbacks
# in a C++ class using Py_INCREF, Py_DECREF. Calling from
# C++ using PyObject_CallMethod.
# | http://stackoverflow.com/a/17070382/623622
# Disadvantage: when calling python callback from the C++ class
# declared in Cython there is no easy way to propagate the python
# exceptions when they occur during execution of the callback.
#
# - | cdef char* other_c_string = py_string
# This is a very fast operation after which other_c_string points
# to the byte string buffer of the Python string itself. It is
# tied to the life time of the Python string. When the Python
# string is garbage collected, the pointer becomes invalid.
#
# - When defining cpdef functions returning "cpp_bool":
# | cpdef cpp_bool myfunc() except *:
# Always do an additional cast when returning value, even when
# variable is defined as py_bool:
# | cdef py_bool returnValue
# | return bool(returnValue)
# Otherwise compiler warnings appear:
# | cefpython.cpp(26533) : warning C4800: 'int' : forcing value
# | to bool 'true' or 'false' (performance warning)
# Lots of these warnings results in ignoring them, but sometimes
# they are shown for a good reason. For example when you forget
# to return a value in a function.
#
# - Always import bool from libcpp as cpp_bool, if you import it as
# "bool" in a pxd file, then Cython will complain about bool casts
# like "bool(1)" being invalid, in pyx files.
#
# - malloc example code:
# from libc.stdlib cimport malloc, free
# cdef RECT* rect = <RECT*>malloc(sizeof(RECT))
# free(rect)
#
# All .pyx files need to be included in this file.
# Includes being made in other .pyx files are allowed to help
# IDE completion, but will be removed during cython compilation.
include "compile_time_constants.pxi"
# -----------------------------------------------------------------------------
# IMPORTS
# noinspection PyUnresolvedReferences
import os
import sys
# noinspection PyUnresolvedReferences
import cython
# noinspection PyUnresolvedReferences
import platform
# noinspection PyUnresolvedReferences
import traceback
# noinspection PyUnresolvedReferences
import time
# noinspection PyUnresolvedReferences
import types
# noinspection PyUnresolvedReferences
import re
# noinspection PyUnresolvedReferences
import copy
# noinspection PyUnresolvedReferences
import inspect # used by JavascriptBindings.__SetObjectMethods()
# noinspection PyUnresolvedReferences
import urllib
# noinspection PyUnresolvedReferences
import json
# noinspection PyUnresolvedReferences
import datetime
# noinspection PyUnresolvedReferences
import random
# noinspection PyUnresolvedReferences
import struct
# noinspection PyUnresolvedReferences
import base64
# noinspection PyUnresolvedReferences
from urllib import parse as urlparse
from urllib.parse import quote as urlparse_quote
# noinspection PyUnresolvedReferences
from urllib.parse import urlencode as urllib_urlencode
# noinspection PyUnresolvedReferences
from cpython.version cimport PY_MAJOR_VERSION
# noinspection PyUnresolvedReferences
import weakref
# We should allow multiple string types: str, unicode, bytes.
# PyToCefString() can handle them all.
# Important:
# If you set it to basestring, Cython will accept exactly(!)
# str/unicode in Py2 and str in Py3. This won't work in Py3
# as we might want to pass bytes as well. Also it will
# reject string subtypes, so using it in publi API functions
# would be a bad idea.
ctypedef object py_string
# You can't use "void" along with cpdef function returning None, it is
# planned to be added to Cython in the future, creating this virtual
# type temporarily. If you change it later to "void" then don't forget
# to add "except *".
ctypedef object py_void
# noinspection PyUnresolvedReferences
from cpython cimport PyLong_FromVoidPtr
# noinspection PyUnresolvedReferences
from cpython cimport bool as py_bool
# noinspection PyUnresolvedReferences
from libcpp cimport bool as cpp_bool
# noinspection PyUnresolvedReferences
from libcpp.map cimport map as cpp_map
# noinspection PyUnresolvedReferences
from multimap cimport multimap as cpp_multimap
# noinspection PyUnresolvedReferences
from libcpp.pair cimport pair as cpp_pair
# noinspection PyUnresolvedReferences
from libcpp.vector cimport vector as cpp_vector
# noinspection PyUnresolvedReferences
from libcpp.string cimport string as cpp_string
# noinspection PyUnresolvedReferences
from wstring cimport wstring as cpp_wstring
# noinspection PyUnresolvedReferences
from libcpp.memory cimport unique_ptr
# noinspection PyUnresolvedReferences
from libc.string cimport strlen
# noinspection PyUnresolvedReferences
from libc.string cimport memcpy
# preincrement and dereference must be "as" otherwise not seen.
# noinspection PyUnresolvedReferences
from cython.operator cimport preincrement as preinc, dereference as deref
# noinspection PyUnresolvedReferences
# from cython.operator cimport address as addr # Address of an c++ object?
# noinspection PyUnresolvedReferences
from libc.stdlib cimport calloc, malloc, free
# noinspection PyUnresolvedReferences
from libc.stdlib cimport atoi
# When pyx file cimports * from a pxd file and that pxd cimports * from another pxd
# then these names will be visible in pyx file.
# Circular imports are allowed in form "cimport ...", but won't work if you do
# "from ... cimport *", this is important to know in pxd files.
# noinspection PyUnresolvedReferences
from libc.stdint cimport uint64_t
# noinspection PyUnresolvedReferences
from libc.stdint cimport uintptr_t
# noinspection PyUnresolvedReferences
ctypedef uintptr_t WindowHandle
# noinspection PyUnresolvedReferences
cimport ctime
include "platform_cimports.pxi"
from cpp_utils cimport *
from task cimport *
from cef_string cimport *
cdef extern from *:
# noinspection PyUnresolvedReferences
ctypedef CefString ConstCefString "const CefString"
# cannot cimport *, that would cause name conflicts with constants
# noinspection PyUnresolvedReferences
from cef_types cimport (
CefSettings, CefBrowserSettings, CefRect, CefSize, CefPoint,
CefKeyEvent, CefMouseEvent, CefScreenInfo,
PathKey, PK_DIR_EXE, PK_DIR_MODULE,
cef_log_severity_t,
)
# noinspection PyUnresolvedReferences
from cef_ptr cimport CefRefPtr
from cef_task cimport *
from cef_platform cimport *
from cef_app cimport *
from cef_browser cimport *
# noinspection PyUnresolvedReferences
cimport cef_browser_static
from cef_client cimport *
from client_handler cimport *
from cef_frame cimport *
from cef_time cimport *
from cef_values cimport *
from cefpython_app cimport *
from cef_process_message cimport *
from cef_request_handler cimport *
from cef_request cimport *
from cef_cookie cimport *
from cef_string_visitor cimport *
# noinspection PyUnresolvedReferences
cimport cef_cookie_manager_namespace
from cookie_visitor cimport *
from string_visitor cimport *
from cef_callback cimport *
from cef_response cimport *
from cef_resource_handler cimport *
from resource_handler cimport *
from cef_urlrequest cimport *
from web_request_client cimport *
from cef_command_line cimport *
from cef_request_context cimport *
from cef_request_context_handler cimport *
from request_context_handler cimport *
from cef_jsdialog_handler cimport *
from cef_path_util cimport *
from cef_drag_data cimport *
from cef_image cimport *
from main_message_loop cimport *
# noinspection PyUnresolvedReferences
from cef_views cimport *
from cef_log cimport *
from cef_file_util cimport *
# -----------------------------------------------------------------------------
# GLOBAL VARIABLES
g_debug = False
# When put None here and assigned a local dictionary in Initialize(), later
# while running app this global variable was garbage collected, see topic:
# https://groups.google.com/d/topic/cython-users/0dw3UASh7HY/discussion
# The string_encoding key must be set early here and also in Initialize.
g_applicationSettings = {"string_encoding": "utf-8"}
g_commandLineSwitches = {}
g_browser_settings = {}
# If ApplicationSettings.unique_request_context_per_browser is False
# then a shared request context is used for all browsers. Otherwise
# a unique one is created for each call to CreateBrowserSync.
# noinspection PyUnresolvedReferences
cdef CefRefPtr[CefRequestContext] g_shared_request_context
cdef unique_ptr[MainMessageLoopExternalPump] g_external_message_pump
cdef py_bool g_MessageLoop_called = False
cdef py_bool g_MessageLoopWork_called = False
cdef py_bool g_cef_initialized = False
cdef py_bool g_context_initialized = False
cdef list g_pending_browsers = []
IF UNAME_SYSNAME == "Linux":
# Keeps ctypes callback objects alive for the duration of gtk_main() and
# any pending one-shot GLib timers (Xwayland XReparentWindow scheduling).
g_linux_reparent_callbacks = []
cdef dict g_globalClientCallbacks = {}
# -----------------------------------------------------------------------------
include "cef_types.pyx"
include "utils.pyx"
include "string_utils.pyx"
IF UNAME_SYSNAME == "Windows":
include "string_utils_win.pyx"
include "time_utils.pyx"
include "browser.pyx"
include "frame.pyx"
include "settings.pyx"
IF UNAME_SYSNAME == "Windows":
include "window_utils_win.pyx"
include "dpi_aware_win.pyx"
ELIF UNAME_SYSNAME == "Linux":
include "window_utils_linux.pyx"
ELIF UNAME_SYSNAME == "Darwin":
include "window_utils_mac.pyx"
include "task.pyx"
include "javascript_bindings.pyx"
include "virtual_keys.pyx"
include "window_info.pyx"
include "process_message_utils.pyx"
include "javascript_callback.pyx"
include "python_callback.pyx"
include "request.pyx"
include "cookie.pyx"
include "string_visitor.pyx"
include "network_error.pyx"
include "paint_buffer.pyx"
include "callback.pyx"
include "response.pyx"
include "web_request.pyx"
include "command_line.pyx"
include "app.pyx"
include "drag_data.pyx"
include "helpers.pyx"
include "image.pyx"
# Handlers
include "handlers/accessibility_handler.pyx"
include "handlers/browser_process_handler.pyx"
include "handlers/context_menu_handler.pyx"
include "handlers/cookie_access_filter.pyx"
include "handlers/display_handler.pyx"
include "handlers/focus_handler.pyx"
include "handlers/javascript_dialog_handler.pyx"
include "handlers/keyboard_handler.pyx"
include "handlers/lifespan_handler.pyx"
include "handlers/load_handler.pyx"
include "handlers/render_handler.pyx"
include "handlers/resource_handler.pyx"
include "handlers/request_handler.pyx"
include "handlers/v8context_handler.pyx"
include "handlers/v8function_handler.pyx"
# -----------------------------------------------------------------------------
# Utility functions to provide settings to the C++ browser process code.
cdef public void cefpython_GetDebugOptions(
cpp_bool* debug
) noexcept with gil:
# Called from subprocess/cefpython_app.cpp -> CefPythonApp constructor.
try:
debug[0] = <cpp_bool>bool(g_debug)
except:
(exc_type, exc_value, exc_trace) = sys.exc_info()
sys.excepthook(exc_type, exc_value, exc_trace)
cdef public cpp_bool ApplicationSettings_GetBool(const char* key
) except * with gil:
# Called from client_handler/client_handler.cpp for example
cdef object pyKey = CharToPyString(key)
if pyKey in g_applicationSettings:
return bool(g_applicationSettings[pyKey])
return False
cdef public cpp_bool ApplicationSettings_GetBoolFromDict(const char* key1,
const char* key2) except * with gil:
cdef object pyKey1 = CharToPyString(key1)
cdef object pyKey2 = CharToPyString(key2)
cdef object dictValue # Yet to be checked whether it is `dict`
if pyKey1 in g_applicationSettings:
dictValue = g_applicationSettings[pyKey1]
if type(dictValue) != dict:
return False
if pyKey2 in dictValue:
return bool(dictValue[pyKey2])
return False
cdef public cpp_string ApplicationSettings_GetString(const char* key
) except * with gil:
cdef object pyKey = CharToPyString(key)
cdef cpp_string cppString
if pyKey in g_applicationSettings:
cppString = PyStringToChar(AnyToPyString(g_applicationSettings[pyKey]))
return cppString
cdef public int CommandLineSwitches_GetInt(const char* key) except * with gil:
cdef object pyKey = CharToPyString(key)
if pyKey in g_commandLineSwitches:
return int(g_commandLineSwitches[pyKey])
return 0
# -----------------------------------------------------------------------------
# If you've built custom binaries with tcmalloc hook enabled on
# Linux, then do not to run any of the CEF code until Initialize()
# is called. See Issue #73 in the CEF Python Issue Tracker.
def Initialize(applicationSettings=None, commandLineSwitches=None, **kwargs):
# applicationSettings and commandLineSwitches argument
# names are kept for backward compatibility.
application_settings = applicationSettings
command_line_switches = commandLineSwitches
# Alternative names for existing parameters
if "settings" in kwargs:
assert not applicationSettings, "Bad arguments"
application_settings = kwargs["settings"]
del kwargs["settings"]
if "switches" in kwargs:
assert not command_line_switches, "Bad arguments"
command_line_switches = kwargs["switches"]
del kwargs["switches"]
for kwarg in kwargs:
raise Exception("Invalid argument: "+kwarg)
if command_line_switches:
# Make a copy as commandLineSwitches is a reference only
# that might get destroyed later.
global g_commandLineSwitches
for key in command_line_switches:
g_commandLineSwitches[key] = copy.deepcopy(
command_line_switches[key])
# Use g_commandLineSwitches if you need to modify or access
# command line switches inside this function.
del command_line_switches
del commandLineSwitches
if not application_settings:
application_settings = {}
# Debug settings need to be set before Debug() is called
# and before the CefPythonApp class is instantiated.
global g_debug
if "--debug" in sys.argv:
application_settings["debug"] = True
application_settings["log_file"] = os.path.join(os.getcwd(),
"debug.log")
application_settings["log_severity"] = LOGSEVERITY_INFO
sys.argv.remove("--debug")
if "debug" in application_settings:
g_debug = bool(application_settings["debug"])
if "log_severity" in application_settings:
if application_settings["log_severity"] <= LOGSEVERITY_INFO:
g_debug = True
Debug("Initialize() called")
# Additional initialization on Mac, see util_mac.mm.
IF UNAME_SYSNAME == "Darwin":
MacInitialize()
# ------------------------------------------------------------------------
# CEF Python only options
# ------------------------------------------------------------------------
if "debug" not in application_settings:
application_settings["debug"] = False
if "log_severity" not in application_settings:
# By default show only errors. Don't show on Linux X server non-fatal
# errors like "WARNING:x11_util.cc(1409)] X error received".
application_settings["log_severity"] = LOGSEVERITY_ERROR
if "string_encoding" not in application_settings:
application_settings["string_encoding"] = "utf-8"
if "unique_request_context_per_browser" not in application_settings:
application_settings["unique_request_context_per_browser"] = False
if "downloads_enabled" not in application_settings:
application_settings["downloads_enabled"] = True
if "remote_debugging_port" not in application_settings:
application_settings["remote_debugging_port"] = 0
if "app_user_model_id" in application_settings:
g_commandLineSwitches["app-user-model-id"] =\
application_settings["app_user_model_id"]
# ------------------------------------------------------------------------
# Paths
# ------------------------------------------------------------------------
cdef str module_dir = GetModuleDirectory()
if platform.system() == "Darwin":
if "framework_dir_path" not in application_settings:
application_settings["framework_dir_path"] = os.path.join(
module_dir, "Chromium Embedded Framework.framework")
if "locales_dir_path" not in application_settings:
if platform.system() != "Darwin":
application_settings["locales_dir_path"] = os.path.join(
module_dir, "locales")
if "resources_dir_path" not in application_settings:
application_settings["resources_dir_path"] = module_dir
if platform.system() == "Darwin":
# "framework_dir_path" will always be set, see code above.
application_settings["resources_dir_path"] = os.path.join(
application_settings["framework_dir_path"],
"Resources")
if "browser_subprocess_path" not in application_settings:
application_settings["browser_subprocess_path"] = os.path.join(
module_dir, "subprocess")
# ------------------------------------------------------------------------
# Mouse context menu
# ------------------------------------------------------------------------
if "context_menu" not in application_settings:
application_settings["context_menu"] = {}
menuItems = ["enabled", "navigation", "print", "view_source",
"external_browser", "devtools"]
for item in menuItems:
if item not in application_settings["context_menu"]:
application_settings["context_menu"][item] = True
# ------------------------------------------------------------------------
# Remote debugging port.
# ------------------------------------------------------------------------
# If value is 0 we will generate a random port. To disable
# remote debugging set value to -1.
if application_settings["remote_debugging_port"] == 0:
# Generate a random port.
application_settings["remote_debugging_port"] =\
random.randint(49152, 65535)
elif application_settings["remote_debugging_port"] == -1:
# Disable remote debugging
application_settings["remote_debugging_port"] = 0
# ------------------------------------------------------------------------
# CEF options - default values
# ------------------------------------------------------------------------
if not "multi_threaded_message_loop" in application_settings:
application_settings["multi_threaded_message_loop"] = False
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# Fix GPUCache/ folder creation when using in-memory cache (Issue #419)
# ------------------------------------------------------------------------
if not "cache_path" in application_settings:
application_settings["cache_path"] = ""
if not application_settings["cache_path"]:
g_commandLineSwitches["disable-gpu-shader-disk-cache"] = ""
IF UNAME_SYSNAME == "Linux":
# Detect Wayland/X11 mode and apply switches BEFORE gtk_init so we
# know whether to open a GTK/X11 display connection at all.
_linux_apply_initialize_defaults(application_settings,
g_commandLineSwitches)
# In X11/Xwayland mode, open a GDK display connection before
# CefInitialize so the Ozone X11 backend can use it.
# In native Wayland mode, no GTK/X11 connection is needed or wanted.
if not _g_linux_wayland_mode:
_linux_gtk_init()
cdef CefRefPtr[CefApp] cefApp = <CefRefPtr[CefApp]?>new CefPythonApp()
IF UNAME_SYSNAME == "Windows":
cdef HINSTANCE hInstance = GetModuleHandle(NULL)
cdef CefMainArgs cefMainArgs = CefMainArgs(hInstance)
ELIF UNAME_SYSNAME == "Linux":
# Build a complete argv so the browser process sees all switches.
# OnBeforeChildProcessLaunch only reaches child processes; switches
# like --in-process-gpu and --single-process must be in the browser
# process's own command line to take effect.
_cefMainArgvPyList = [sys.executable.encode('utf-8')]
for _cefArgK, _cefArgV in g_commandLineSwitches.items():
if _cefArgV:
_cefMainArgvPyList.append(
("--{}={}".format(_cefArgK, _cefArgV)).encode('utf-8'))
else:
_cefMainArgvPyList.append(
("--{}".format(_cefArgK)).encode('utf-8'))
cdef int _cefMainArgc = len(_cefMainArgvPyList)
cdef char** _cefMainArgvC = \
<char**>malloc(_cefMainArgc * sizeof(char*))
cdef bytes _cefMainArgvItem
cdef int _cefMainArgvI
for _cefMainArgvI in range(_cefMainArgc):
_cefMainArgvItem = _cefMainArgvPyList[_cefMainArgvI]
_cefMainArgvC[_cefMainArgvI] = _cefMainArgvItem
cdef CefMainArgs cefMainArgs = CefMainArgs(_cefMainArgc, _cefMainArgvC)
# _cefMainArgvPyList keeps the bytes alive; freed below after
# CefInitialize() has processed the command line.
ELIF UNAME_SYSNAME == "Darwin":
# TODO: use the CefMainArgs(int argc, char** argv) constructor.
cdef CefMainArgs cefMainArgs
cdef int exitCode = 1
# NOTE: CefExecuteProcess shall not be called here. It should
# be called only in the subprocess main.cpp.
# Make a copy as applicationSettings is a reference only
# that might get destroyed later.
global g_applicationSettings
for key in application_settings:
g_applicationSettings[key] = copy.deepcopy(application_settings[key])
cdef CefSettings cefApplicationSettings
IF UNAME_SYSNAME == "Linux":
# On Linux, leave no_sandbox=0 so Chrome's startup code registers the
# Mojo IPC bootstrap fd (GlobalDescriptors key 7) for every subprocess.
# Setting no_sandbox=1 would cause BasicStartupComplete() to append
# --no-sandbox before fd registration, causing all subprocesses to crash
# with "Failed global descriptor lookup: 7". Sandbox behaviour is instead
# controlled via --disable-setuid-sandbox / --disable-namespace-sandbox
# command-line switches passed by the caller.
pass
ELSE:
# On Windows/macOS the sandbox helper binary is not shipped with
# cefpython, so disable sandboxing entirely.
cefApplicationSettings.no_sandbox = 1
SetApplicationSettings(application_settings, &cefApplicationSettings)
# External message pump
if GetAppSetting("external_message_pump")\
and not g_external_message_pump.get():
Debug("Create external message pump")
global g_external_message_pump
# Using .reset() here to assign new instance was causing
# MainMessageLoopExternalPump destructor to be called. Strange.
g_external_message_pump = MainMessageLoopExternalPump.Create()
Debug("CefInitialize()")
cdef cpp_bool ret
with nogil:
ret = CefInitialize(cefMainArgs, cefApplicationSettings, cefApp, NULL)
IF UNAME_SYSNAME == "Linux":
free(_cefMainArgvC)
global g_cef_initialized
g_cef_initialized = True
if not ret:
Debug("CefInitialize() failed")
# Pump the message loop until OnContextInitialized fires. This
# guarantees that CreateBrowserSync() can be called immediately after
# Initialize() without hitting the deferred-creation path or getting
# a null browser from CefBrowserHost::CreateBrowserSync().
# Use a generous ceiling (30s) for CI environments where utility
# subprocesses (storage service) crash and delay context initialization.
if ret:
# On Linux, skip this pump entirely. Empirical testing shows manual
# CefDoMessageLoopWork() *does* fire OnContextInitialized within 2-3s
# on both Ozone X11 and Ozone Wayland in the current cefpython
# configuration, so the historical "needs gtk_main()" claim is no
# longer accurate — but we still skip it deliberately to keep
# Initialize() non-blocking on Linux. The user enters
# cef.MessageLoop() (gtk_main on X11, GLib loop on Wayland) right
# after Initialize() returns; OnContextInitialized fires there and
# BrowserProcessHandler_OnContextInitialized drains
# g_pending_browsers. This avoids a 2-3s startup latency hit on
# the common case and a 30s block in edge cases.
# On Windows/macOS, pump up to 30s as before.
IF UNAME_SYSNAME != "Linux":
for _ in range(3000):
with nogil:
CefDoMessageLoopWork()
if g_context_initialized:
break
time.sleep(0.01)
if not g_context_initialized:
Debug("CefInitialize() WARNING: OnContextInitialized not received"
" within 30 seconds")
# Compile-time Linux guard: _g_linux_wayland_mode is defined in
# window_utils_linux.pyx, which is only included in the Linux build,
# so this whole block must be excluded on Windows/macOS or Cython
# fails with "undeclared name not builtin: _g_linux_wayland_mode".
IF UNAME_SYSNAME == "Linux":
if not _g_linux_wayland_mode:
WindowUtils.InstallX11ErrorHandlers()
return ret
def CreateBrowser(**kwargs):
"""Create browser asynchronously. TODO. """
CreateBrowserSync(**kwargs)
def CreateBrowserSync(windowInfo=None,
browserSettings=None,
navigateUrl="",
window_title="",
**kwargs):
# Alternative names for existing parameters
if "window_info" in kwargs:
windowInfo = kwargs["window_info"]
del kwargs["window_info"]
if "settings" in kwargs:
browserSettings = kwargs["settings"]
del kwargs["settings"]
if "url" in kwargs:
navigateUrl = kwargs["url"]
del kwargs["url"]
for kwarg in kwargs:
raise Exception("Invalid argument: "+kwarg)
Debug("CreateBrowserSync() called")
# No CefCurrentlyOn(TID_UI) assert here. cefpython defers the real
# browser creation until OnContextInitialized fires (see below), so
# this function is reached before BrowserThread::UI is fully
# established — at which point CefCurrentlyOn() returns false and
# logs a WARNING (libcef/common/task_impl.cc). CEF's own
# CefBrowserHost::CreateBrowserSync() runs CONTEXT_STATE_VALID()
# plus its own thread checks internally, so a Python-side assert
# would only catch the same condition with a worse error message.
# Defer browser creation until OnContextInitialized fires.
#
# CefBrowserContext initialization is asynchronous: it is not finished
# when CefInitialize() returns, especially when external_message_pump
# is in use (our default — see _linux_apply_initialize_defaults). The
# OnContextInitialized callback is the documented signal that the
# browser context is ready (see upstream CEF commit 691c9c2 "Wait for
# CefBrowserContext initialization", 2021-04-14, issue #2969 — added
# the explicit wait when Chrome runtime introduced async Profile init).
#
# Calling CefBrowserHost::CreateBrowserSync before that point lets the
# renderer come up before its host bindings are wired, and the
# browser-process side then rejects the renderer's first IPC message
# with a "blink.mojom.WidgetHost" / "Message N rejected by interface"
# mojo error. The visible symptom is a blank page.
#
# Strategy:
# * Windows / macOS: cefpython.Initialize() already pumps up to 30s
# waiting for OnContextInitialized. If a caller reaches
# CreateBrowserSync earlier anyway (slow CI, custom Initialize
# override), pump another 30s here before giving up.
# * Linux (X11 and Wayland Ozone backends): skip the local pump,
# mirroring Initialize(). The deferred path always works: queue
# the request and let BrowserProcessHandler_OnContextInitialized
# drain it once cef.MessageLoop() starts the GLib loop.
# When this falls through still uninitialised, queue the request in
# g_pending_browsers for the OnContextInitialized handler to drain
# once the loop is actually running.
if not g_context_initialized:
Debug("CreateBrowserSync(): OnContextInitialized not yet received,"
" pumping message loop")
IF UNAME_SYSNAME != "Linux":
for _ in range(3000):
with nogil:
CefDoMessageLoopWork()
if g_context_initialized:
break
time.sleep(0.01)
if not g_context_initialized:
Debug("CreateBrowserSync() deferred until OnContextInitialized")
g_pending_browsers.append({
"windowInfo": windowInfo,
"browserSettings": browserSettings,
"navigateUrl": navigateUrl,
"window_title": window_title,
})
return None
"""
# CEF views
# noinspection PyUnresolvedReferences
cdef CefRefPtr[CefWindow] cef_window
# noinspection PyUnresolvedReferences
cdef CefRefPtr[CefBoxLayout] cef_box_layout
cdef CefBoxLayoutSettings cef_box_layout_settings
cdef CefRefPtr[CefPanel] cef_panel
if not windowInfo and browserSettings \
and "window_title" in browserSettings:
# noinspection PyUnresolvedReferences
cef_window = CefWindow.CreateTopLevelWindow(
<CefRefPtr[CefWindowDelegate]?>NULL)
Debug("CefWindow.GetChildViewCount = "
+str(cef_window.get().GetChildViewCount()))
cef_window.get().CenterWindow(CefSize(800, 600))
cef_window.get().SetBounds(CefRect(0, 0, 800, 600))
# noinspection PyUnresolvedReferences
#cef_box_layout = cef_window.get().SetToBoxLayout(
# cef_box_layout_settings)
#cef_box_layout.get().SetFlexForView(cef_window, 1)
cef_window.get().SetToFillLayout()
# noinspection PyUnresolvedReferences
cef_panel = CefPanel.CreatePanel(<CefRefPtr[CefPanelDelegate]?>NULL)
cef_window.get().AddChildView(cef_panel)
cef_window.get().Layout()
cef_window.get().SetVisible(True)
cef_window.get().Show()
cef_window.get().RequestFocus()
windowInfo = WindowInfo()
windowInfo.SetAsChild(cef_window.get().GetWindowHandle())
Debug("CefWindow handle = "
+str(<uintptr_t>cef_window.get().GetWindowHandle()))
"""
# Only title was set in hello_world.py example
if windowInfo and not windowInfo.windowType:
windowInfo.SetAsChild(0)
# No window info provided
if not windowInfo:
windowInfo = WindowInfo()
windowInfo.SetAsChild(0)
elif not isinstance(windowInfo, WindowInfo):
raise Exception("CreateBrowserSync() failed: windowInfo: invalid object")
# On Linux, when no parent window is given, provide a top-level window
# so callers need no toolkit-specific code (same API as Windows/Mac).
_linux_toplevel_state = None
IF UNAME_SYSNAME == "Linux":
if windowInfo.windowType == "child" and windowInfo.parentWindowHandle == 0:
if _g_linux_wayland_mode:
# Native Wayland: CEF creates its own xdg_toplevel surface.
# Pass parent=0 with default bounds; no GTK window is needed.
_linux_toplevel_state = {'wayland': True}
windowInfo.SetAsChild(0, [0, 0, _LINUX_DEFAULT_WIDTH,
_LINUX_DEFAULT_HEIGHT])
else:
_linux_toplevel_state = _linux_create_toplevel(
window_title or "CEF Browser")
windowInfo.SetAsChild(
_linux_toplevel_state['xid'],
[0, 0, _linux_toplevel_state['width'],
_linux_toplevel_state['height']])
if window_title and windowInfo.parentWindowHandle == 0:
windowInfo.windowName = window_title
# Browser settings
if not browserSettings:
browserSettings = {}
# CEF Python only settings
if "inherit_client_handlers_for_popups" not in browserSettings:
browserSettings["inherit_client_handlers_for_popups"] = True
cdef CefBrowserSettings cefBrowserSettings
SetBrowserSettings(browserSettings, &cefBrowserSettings)
cdef CefWindowInfo cefWindowInfo
SetCefWindowInfo(cefWindowInfo, windowInfo)
cdef CefString cefNavigateUrl
PyToCefString(navigateUrl, cefNavigateUrl)
Debug("CefBrowser::CreateBrowserSync()")
cdef CefRefPtr[ClientHandler] clientHandler =\
<CefRefPtr[ClientHandler]?>new ClientHandler()
cdef CefRefPtr[CefBrowser] cefBrowser
# Request context - part 1/2.
createSharedRequestContext = bool(not g_shared_request_context.get())
cdef CefRefPtr[CefRequestContext] cefRequestContext
cdef CefRefPtr[RequestContextHandler] requestContextHandler =\
<CefRefPtr[RequestContextHandler]?>new RequestContextHandler(
cefBrowser)
if g_applicationSettings["unique_request_context_per_browser"]:
cefRequestContext = CefRequestContext.CreateContext(
CefRequestContext.GetGlobalContext(),
<CefRefPtr[CefRequestContextHandler]?>requestContextHandler)
elif createSharedRequestContext:
cefRequestContext = CefRequestContext.CreateContext(
CefRequestContext.GetGlobalContext(),
<CefRefPtr[CefRequestContextHandler]?>requestContextHandler)
g_shared_request_context.Assign(cefRequestContext.get())
else:
cefRequestContext.Assign(g_shared_request_context.get())
cdef CefRefPtr[CefDictionaryValue] extra_info
# CEF browser creation.
with nogil:
cefBrowser = cef_browser_static.CreateBrowserSync(
cefWindowInfo, <CefRefPtr[CefClient]?>clientHandler,
cefNavigateUrl, cefBrowserSettings, extra_info,
cefRequestContext)
if not cefBrowser or not cefBrowser.get():
Debug("CefBrowser::CreateBrowserSync() failed")
return None
else:
Debug("CefBrowser::CreateBrowserSync() succeeded")
Debug("CefBrowser window handle = "
+str(<uintptr_t>cefBrowser.get().GetHost().get().GetWindowHandle()))
# Make a copy as browserSettings is a reference only that might
# get destroyed later.
global g_browser_settings
cdef int browser_id = cefBrowser.get().GetIdentifier()
g_browser_settings[browser_id] = {}
for key in browserSettings:
g_browser_settings[browser_id][key] =\
copy.deepcopy(browserSettings[key])
# Request context - part 2/2.
if g_applicationSettings["unique_request_context_per_browser"]:
requestContextHandler.get().SetBrowser(cefBrowser)
else:
if createSharedRequestContext:
requestContextHandler.get().SetBrowser(cefBrowser)
cdef PyBrowser pyBrowser = GetPyBrowser(cefBrowser)
pyBrowser.SetUserData("__outerWindowHandle",
int(windowInfo.parentWindowHandle))
"""
if cef_window.get():
cef_window.get().ReorderChildView(cef_panel, -1)
cef_window.get().Layout()
cef_window.get().Show()
cef_window.get().RequestFocus()
"""
if windowInfo.parentWindowHandle == 0\
and windowInfo.windowType == "child"\
and windowInfo.windowName:
# Set window title in hello_world.py example
IF UNAME_SYSNAME == "Linux":
# X11 title setting uses XStoreName which requires an X11 display.
# Skip on native Wayland; CEF's Ozone backend propagates the page
# title to the compositor via xdg_toplevel_set_title automatically.
if not _g_linux_wayland_mode:
x11.SetX11WindowTitle(cefBrowser,
PyStringToChar(windowInfo.windowName))
ELIF UNAME_SYSNAME == "Darwin":
MacSetWindowTitle(cefBrowser,
PyStringToChar(windowInfo.windowName))
IF UNAME_SYSNAME == "Linux":
if windowInfo._linux_embed_info:
_linux_schedule_xembed(pyBrowser, windowInfo._linux_embed_info)
if _linux_toplevel_state is not None:
if _linux_toplevel_state.get('wayland'):
# Native Wayland top-level: register a DoClose callback that
# quits the GLib loop. On Wayland, CloseHostWindow() is a
# compile-time no-op, so we must exit the loop ourselves when
# DoClose fires (either from CloseBrowser() or xdg_toplevel.close).
_linux_register_wayland_close_handler(pyBrowser)
# When SUPPORTS_OZONE_X11 is compiled, CreateHostWindow() creates
# both an X11/XWayland shell window (empty) and a Wayland
# xdg_toplevel with the actual browser content. Hide the empty
# X11 shell so only the content-bearing Wayland window is visible.
x11.HideX11ShellWindow(cefBrowser)
else:
# X11/XWayland top-level: attach GTK resize and close callbacks.
_linux_register_window_callbacks(pyBrowser, _linux_toplevel_state)
return pyBrowser
def MessageLoop():
Debug("MessageLoop()")
if not g_MessageLoop_called:
global g_MessageLoop_called
g_MessageLoop_called = True
IF UNAME_SYSNAME == "Linux":
_linux_message_loop()
ELSE:
with nogil:
CefRunMessageLoop()
def MessageLoopWork():
# Perform a single iteration of CEF message loop processing.
# This function is used to integrate the CEF message loop
# into an existing application message loop.
# Anything that can block for a significant amount of time
# and is thread-safe should release the GIL:
# https://groups.google.com/d/msg/cython-users/jcvjpSOZPp0/KHpUEX8IhnAJ
# GIL must be released here otherwise we will get dead lock
# when calling from c++ to python.
if not g_MessageLoopWork_called:
global g_MessageLoopWork_called
g_MessageLoopWork_called = True
with nogil: