Advertisement
Guest User

browser

a guest
Apr 16th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.98 KB | None | 0 0
  1. import os, sys
  2. # os module provides functions for interacting with the ops
  3. # sys provides info about constants, functions and methods of the Python interpreter
  4. libcef_dll = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), # (__file__)
  5. 'libcef.dll')
  6. if os.path.exists(libcef_dll):
  7. # Import a local module
  8. if (2,7) <= sys.version_info < (2,8):
  9. import cefpython_py27 as cefpython
  10. elif (3,4) <= sys.version_info < (3,4):
  11. import cefpython_py34 as cefpython
  12. else:
  13. raise Exception("Unsupported python version: %s" % sys.version)
  14. else:
  15. # Import an installed package
  16. from cefpython3 import cefpython
  17.  
  18. import thread
  19. import wx
  20. import time
  21. import re
  22. import uuid
  23. import platform
  24. import inspect
  25. import struct
  26. import time
  27. import subprocess
  28.  
  29. def browser_spawn():
  30. time.sleep(2)
  31. # theproc = subprocess.Popen([sys.executable, "eric.py"], shell = True)
  32. # -----------------------------------------------------------------------------
  33. # Globals
  34.  
  35. g_applicationSettings = None
  36. g_browserSettings = None
  37. g_commandLineSwitches = None
  38.  
  39. # Which method to use for message loop processing.
  40. # EVT_IDLE - wx application has priority
  41. # EVT_TIMER - cef browser has priority (default)
  42. # It seems that Flash content behaves better when using a timer.
  43. # Not sure if using EVT_IDLE is correct, it doesn't work on Linux,
  44. # on Windows it works fine. See also the post by Robin Dunn:
  45. # https://groups.google.com/d/msg/wxpython-users/hcNdMEx8u48/MD5Jgbm_k1kJ
  46. USE_EVT_IDLE = False # If False then Timer will be used
  47.  
  48. TEST_EMBEDDING_IN_PANEL = True
  49.  
  50. # -----------------------------------------------------------------------------
  51.  
  52. def GetApplicationPath(file=None):
  53. import re, os, platform
  54. # On Windows after downloading file and calling Browser.GoForward(),
  55. # current working directory is set to %UserProfile%.
  56. # Calling os.path.dirname(os.path.realpath(__file__))
  57. # returns for eg. "C:\Users\user\Downloads". A solution
  58. # is to cache path on first call.
  59. if not hasattr(GetApplicationPath, "dir"): #True if "dir" is name of an attribute of GetApplicationPath
  60. if hasattr(sys, "frozen"): #True if "frozen" is name of an attribute of sys
  61. dir = os.path.dirname(sys.executable)
  62. elif "__file__" in globals():
  63. dir = os.path.dirname(os.path.realpath(__file__))
  64. else:
  65. dir = os.getcwd()
  66. GetApplicationPath.dir = dir
  67. # If file is None return current directory without trailing slash.
  68. if file is None:
  69. file = ""
  70. # Only when relative path.
  71. if not file.startswith("/") and not file.startswith("\\") and (
  72. not re.search(r"^[\w-]+:", file)):
  73. path = GetApplicationPath.dir + os.sep + file
  74. if platform.system() == "Windows":
  75. path = re.sub(r"[/\\]+", re.escape(os.sep), path)
  76. path = re.sub(r"[/\\]+$", "", path)
  77. return path
  78. return str(file)
  79.  
  80. def ExceptHook(excType, excValue, traceObject):
  81. import traceback, os, time, codecs
  82. # This hook does the following: in case of exception write it to
  83. # the "error.log" file, display it to the console, shutdown CEF
  84. # and exit application immediately by ignoring "finally" (os._exit()).
  85. errorMsg = "\n".join(traceback.format_exception(excType, excValue,
  86. traceObject))
  87. errorFile = GetApplicationPath("error.log")
  88. try:
  89. appEncoding = cefpython.g_applicationSettings["string_encoding"]
  90. except:
  91. appEncoding = "utf-8"
  92. if type(errorMsg) == bytes:
  93. errorMsg = errorMsg.decode(encoding=appEncoding, errors="replace")
  94. try:
  95. with codecs.open(errorFile, mode="a", encoding=appEncoding) as fp:
  96. fp.write("\n[%s] %s\n" % (
  97. time.strftime("%Y-%m-%d %H:%M:%S"), errorMsg))
  98. except:
  99. print("[cefhello] WARNING: failed writing to error file: %s" % (
  100. errorFile))
  101. # Convert error message to ascii before printing, otherwise
  102. # you may get error like this:
  103. # | UnicodeEncodeError: 'charmap' codec can't encode characters
  104. errorMsg = errorMsg.encode("ascii", errors="replace")
  105. errorMsg = errorMsg.decode("ascii", errors="replace")
  106. print("\n"+errorMsg+"\n")
  107. cefpython.QuitMessageLoop()
  108. cefpython.Shutdown()
  109. os._exit(1)
  110.  
  111. class MainFrame(wx.Frame):
  112. browser = None
  113. mainPanel = None
  114.  
  115. def GetHandleForBrowser(self):
  116. if self.mainPanel:
  117. return self.mainPanel.GetHandle()
  118. else:
  119. return self.GetHandle()
  120.  
  121. def __init__(self, url=None, popup=False):
  122. if popup:
  123. title = "wxPython Popup"
  124. else:
  125. title = "wxPython CEF 3 example"
  126. wx.Frame.__init__(self, parent=None, id=wx.ID_ANY,
  127. title=title)
  128. size=(800,600)
  129.  
  130. # This is an optional code to enable High DPI support.
  131. if "auto_zooming" in g_applicationSettings \
  132. and g_applicationSettings["auto_zooming"] == "system_dpi":
  133. # This utility function will adjust width/height using
  134. # OS DPI settings. For 800/600 with Win7 DPI settings
  135. # being set to "Larger 150%" will return 1200/900.
  136. size = cefpython.DpiAware.CalculateWindowSize(size[0], size[1])
  137.  
  138. self.SetSize(size)
  139.  
  140. if not url:
  141. url = "http://localhost:5000/"
  142. # Test hash in url.
  143. # url += "#test-hash"
  144.  
  145.  
  146.  
  147. if TEST_EMBEDDING_IN_PANEL:
  148. print("Embedding in a wx.Panel!")
  149. # You also have to set the wx.WANTS_CHARS style for
  150. # all parent panels/controls, if it's deeply embedded.
  151. self.mainPanel = wx.Panel(self, style=wx.WANTS_CHARS)
  152.  
  153. # Global client callbacks must be set before browser is created.
  154. self.clientHandler = ClientHandler()
  155. cefpython.SetGlobalClientCallback("OnCertificateError",
  156. self.clientHandler._OnCertificateError)
  157. cefpython.SetGlobalClientCallback("OnBeforePluginLoad",
  158. self.clientHandler._OnBeforePluginLoad)
  159. cefpython.SetGlobalClientCallback("OnAfterCreated",
  160. self.clientHandler._OnAfterCreated)
  161.  
  162. windowInfo = cefpython.WindowInfo()
  163. windowInfo.SetAsChild(self.GetHandleForBrowser())
  164. self.browser = cefpython.CreateBrowserSync(windowInfo,
  165. browserSettings=g_browserSettings,
  166. navigateUrl=url)
  167.  
  168. self.clientHandler.mainBrowser = self.browser
  169. self.browser.SetClientHandler(self.clientHandler)
  170.  
  171. jsBindings = cefpython.JavascriptBindings(
  172. bindToFrames=False, bindToPopups=True)
  173. jsBindings.SetFunction("PyPrint", PyPrint)
  174. jsBindings.SetProperty("pyProperty", "This was set in Python")
  175. jsBindings.SetProperty("pyConfig", ["This was set in Python",
  176. {"name": "Nested dictionary", "isNested": True},
  177. [1,"2", None]])
  178. self.javascriptExternal = JavascriptExternal(self.browser)
  179. jsBindings.SetObject("external", self.javascriptExternal)
  180. # jsBindings.SetProperty("sources", GetSources())
  181. self.browser.SetJavascriptBindings(jsBindings)
  182.  
  183. if self.mainPanel:
  184. self.mainPanel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
  185. self.mainPanel.Bind(wx.EVT_SIZE, self.OnSize)
  186. else:
  187. self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
  188. self.Bind(wx.EVT_SIZE, self.OnSize)
  189.  
  190. self.Bind(wx.EVT_CLOSE, self.OnClose)
  191. if USE_EVT_IDLE and not popup:
  192. # Bind EVT_IDLE only for the main application frame.
  193. print("Using EVT_IDLE to execute the CEF message loop work")
  194. self.Bind(wx.EVT_IDLE, self.OnIdle)
  195.  
  196.  
  197. def OnSetFocus(self, event):
  198. cefpython.WindowUtils.OnSetFocus(self.GetHandleForBrowser(), 0, 0, 0)
  199.  
  200. def OnSize(self, event):
  201. cefpython.WindowUtils.OnSize(self.GetHandleForBrowser(), 0, 0, 0)
  202.  
  203. def OnClose(self, event):
  204. # Remove all CEF browser references so that browser is closed
  205. # cleanly. Otherwise there may be issues for example with cookies
  206. # not being flushed to disk when closing app immediately
  207. # (Issue 158).
  208. del self.javascriptExternal.mainBrowser
  209. del self.clientHandler.mainBrowser
  210. del self.browser
  211.  
  212. # Destroy wx frame, this will complete the destruction of CEF browser
  213. self.Destroy()
  214.  
  215. # In wx.chromectrl calling browser.CloseBrowser and/or self.Destroy
  216. # may cause crashes when embedding multiple browsers in tab
  217. # (Issue 107). In such case instead of calling CloseBrowser/Destroy
  218. # try this code:
  219. # | self.browser.ParentWindowWillClose()
  220. # | event.Skip()
  221.  
  222. def OnIdle(self, event):
  223. cefpython.MessageLoopWork()
  224.  
  225. def PyPrint(message):
  226. print("[talktown] PyPrint: "+message)
  227.  
  228. class JavascriptExternal:
  229. mainBrowser = None
  230. stringVisitor = None
  231.  
  232. def __init__(self, mainBrowser):
  233. self.mainBrowser = mainBrowser
  234.  
  235. # -------------------------------------------------------------------------
  236. # Cookies
  237. # -------------------------------------------------------------------------
  238.  
  239. class ClientHandler:
  240. mainBrowser = None # May be None for global client callbacks.
  241.  
  242. def __init__(self):
  243. pass
  244.  
  245.  
  246. # -------------------------------------------------------------------------
  247. # DisplayHandler
  248. # -------------------------------------------------------------------------
  249.  
  250. def OnAddressChange(self, browser, frame, url):
  251. print("[talktown] DisplayHandler::OnAddressChange()")
  252. print(" url = %s" % url)
  253.  
  254. def OnTitleChange(self, browser, title):
  255. print("[talktown] DisplayHandler::OnTitleChange()")
  256. print(" title = %s" % title)
  257.  
  258. statusMessageCount = 0
  259. def OnStatusMessage(self, browser, value):
  260. if not value:
  261. # Do not notify in the console about empty statuses.
  262. return
  263. self.statusMessageCount += 1
  264. if self.statusMessageCount > 3:
  265. # Do not spam too much.
  266. return
  267. print("[talktown] DisplayHandler::OnStatusMessage()")
  268. print(" value = %s" % value)
  269.  
  270. def OnConsoleMessage(self, browser, message, source, line):
  271. print("[talktown] DisplayHandler::OnConsoleMessage()")
  272. print(" message = %s" % message)
  273. print(" source = %s" % source)
  274. print(" line = %s" % line)
  275.  
  276.  
  277. # -------------------------------------------------------------------------
  278. # RequestHandler
  279. # -------------------------------------------------------------------------
  280.  
  281. def OnBeforeBrowse(self, browser, frame, request, isRedirect):
  282. print("[talktown] RequestHandler::OnBeforeBrowse()")
  283. print(" url = %s" % request.GetUrl()[:100])
  284. # Handle "magnet:" links.
  285. if request.GetUrl().startswith("magnet:"):
  286. print("[wxpython.p] RequestHandler::OnBeforeBrowse(): "
  287. "magnet link clicked, cancelling browse request")
  288. return True
  289. return False
  290.  
  291. def OnBeforeResourceLoad(self, browser, frame, request):
  292. print("[talktown] RequestHandler::OnBeforeResourceLoad()")
  293. print(" url = %s" % request.GetUrl()[:100])
  294. return False
  295.  
  296. def OnResourceRedirect(self, browser, frame, oldUrl, newUrlOut):
  297. print("[talktown] RequestHandler::OnResourceRedirect()")
  298. print(" old url = %s" % oldUrl[:100])
  299. print(" new url = %s" % newUrlOut[0][:100])
  300.  
  301. def GetAuthCredentials(self, browser, frame, isProxy, host, port, realm,
  302. scheme, callback):
  303. # This callback is called on the IO thread, thus print messages
  304. # may not be visible.
  305. print("[cefhello] RequestHandler::GetAuthCredentials()")
  306. print(" host = %s" % host)
  307. print(" realm = %s" % realm)
  308. callback.Continue(username="test", password="test")
  309. return True
  310.  
  311. def OnQuotaRequest(self, browser, originUrl, newSize, callback):
  312. print("[cefhello] RequestHandler::OnQuotaRequest()")
  313. print(" origin url = %s" % originUrl)
  314. print(" new size = %s" % newSize)
  315. callback.Continue(True)
  316. return True
  317.  
  318. def OnProtocolExecution(self, browser, url, allowExecutionOut):
  319. # There's no default implementation for OnProtocolExecution on Linux,
  320. # you have to make OS system call on your own. You probably also need
  321. # to use LoadHandler::OnLoadError() when implementing this on Linux.
  322. print("[cefhello] RequestHandler::OnProtocolExecution()")
  323. print(" url = %s" % url)
  324. if url.startswith("magnet:"):
  325. print("[cefhello] Magnet link allowed!")
  326. allowExecutionOut[0] = True
  327.  
  328. def _OnBeforePluginLoad(self, browser, url, policyUrl, info):
  329. # This is a global callback set using SetGlobalClientCallback().
  330. # Plugins are loaded on demand, only when website requires it,
  331. # the same plugin may be called multiple times.
  332. # This callback is called on the IO thread, thus print messages
  333. # may not be visible.
  334. print("[cefhello] RequestHandler::_OnBeforePluginLoad()")
  335. print(" url = %s" % url)
  336. print(" policy url = %s" % policyUrl)
  337. print(" info.GetName() = %s" % info.GetName())
  338. print(" info.GetPath() = %s" % info.GetPath())
  339. print(" info.GetVersion() = %s" % info.GetVersion())
  340. print(" info.GetDescription() = %s" % info.GetDescription())
  341. # False to allow, True to block plugin.
  342. return False
  343.  
  344. def _OnCertificateError(self, certError, requestUrl, callback):
  345. # This is a global callback set using SetGlobalClientCallback().
  346. print("[cefhello] RequestHandler::_OnCertificateError()")
  347. print(" certError = %s" % certError)
  348. print(" requestUrl = %s" % requestUrl)
  349. if requestUrl == "https://testssl-expire.disig.sk/index.en.html":
  350. print(" Not allowed!")
  351. return False
  352. if requestUrl \
  353. == "https://testssl-expire.disig.sk/index.en.html?allow=1":
  354. print(" Allowed!")
  355. callback.Continue(True)
  356. return True
  357. return False
  358.  
  359. def OnRendererProcessTerminated(self, browser, status):
  360. print("[cefhello] RequestHandler::OnRendererProcessTerminated()")
  361. statuses = {
  362. cefpython.TS_ABNORMAL_TERMINATION: "TS_ABNORMAL_TERMINATION",
  363. cefpython.TS_PROCESS_WAS_KILLED: "TS_PROCESS_WAS_KILLED",
  364. cefpython.TS_PROCESS_CRASHED: "TS_PROCESS_CRASHED"
  365. }
  366. statusName = "Unknown"
  367. if status in statuses:
  368. statusName = statuses[status]
  369. print(" status = %s" % statusName)
  370.  
  371. def OnPluginCrashed(self, browser, pluginPath):
  372. print("[cefhello] RequestHandler::OnPluginCrashed()")
  373. print(" plugin path = %s" % pluginPath)
  374.  
  375. # -------------------------------------------------------------------------
  376. # LoadHandler
  377. # -------------------------------------------------------------------------
  378.  
  379. def OnLoadingStateChange(self, browser, isLoading, canGoBack,
  380. canGoForward):
  381. print("[cefhello] LoadHandler::OnLoadingStateChange()")
  382. print(" isLoading = %s, canGoBack = %s, canGoForward = %s" \
  383. % (isLoading, canGoBack, canGoForward))
  384.  
  385. def OnLoadStart(self, browser, frame):
  386. print("[cefhello] LoadHandler::OnLoadStart()")
  387. print(" frame url = %s" % frame.GetUrl()[:100])
  388.  
  389. def OnLoadEnd(self, browser, frame, httpStatusCode):
  390. print("[cefhello] LoadHandler::OnLoadEnd()")
  391. print(" frame url = %s" % frame.GetUrl()[:100])
  392. # For file:// urls the status code = 0
  393. print(" http status code = %s" % httpStatusCode)
  394. # Tests for the Browser object methods
  395. self._Browser_LoadUrl(browser)
  396.  
  397. def _Browser_LoadUrl(self, browser):
  398. if browser.GetUrl() == "data:text/html,Test#Browser.LoadUrl":
  399. browser.LoadUrl("file://"+GetApplicationPath("wxpython.html"))
  400.  
  401. def OnLoadError(self, browser, frame, errorCode, errorTextList, failedUrl):
  402. print("[cefhello] LoadHandler::OnLoadError()")
  403. print(" frame url = %s" % frame.GetUrl()[:100])
  404. print(" error code = %s" % errorCode)
  405. print(" error text = %s" % errorTextList[0])
  406. print(" failed url = %s" % failedUrl)
  407. # Handle ERR_ABORTED error code, to handle the following cases:
  408. # 1. Esc key was pressed which calls browser.StopLoad() in OnKeyEvent
  409. # 2. Download of a file was aborted
  410. # 3. Certificate error
  411. if errorCode == cefpython.ERR_ABORTED:
  412. print("[cefhello] LoadHandler::OnLoadError(): Ignoring load "
  413. "error: Esc was pressed or file download was aborted, "
  414. "or there was certificate error")
  415. return;
  416. customErrorMessage = "My custom error message!"
  417. frame.LoadUrl("data:text/html,%s" % customErrorMessage)
  418.  
  419. # -------------------------------------------------------------------------
  420. # LifespanHandler
  421. # -------------------------------------------------------------------------
  422.  
  423. # ** This callback is executed on the IO thread **
  424. # Empty place-holders: popupFeatures, client.
  425. def OnBeforePopup(self, browser, frame, targetUrl, targetFrameName,
  426. popupFeatures, windowInfo, client, browserSettings,
  427. noJavascriptAccess):
  428. print("[cefhello] LifespanHandler::OnBeforePopup()")
  429. print(" targetUrl = %s" % targetUrl)
  430.  
  431. # Custom browser settings for popups:
  432. # > browserSettings[0] = {"plugins_disabled": True}
  433.  
  434. # Set WindowInfo object:
  435. # > windowInfo[0] = cefpython.WindowInfo()
  436.  
  437. # On Windows there are keyboard problems in popups, when popup
  438. # is created using "window.open" or "target=blank". This issue
  439. # occurs only in wxPython. PyGTK or PyQt do not require this fix.
  440. # The solution is to create window explicitilly, and not depend
  441. # on CEF to create window internally.
  442. # If you set allowPopups=True then CEF will create popup window.
  443. # The wx.Frame cannot be created here, as this callback is
  444. # executed on the IO thread. Window should be created on the UI
  445. # thread. One solution is to call cefpython.CreateBrowser()
  446. # which runs asynchronously and can be called on any thread.
  447. # The other solution is to post a task on the UI thread, so
  448. # that cefpython.CreateBrowserSync() can be used.
  449. cefpython.PostTask(cefpython.TID_UI, self._CreatePopup, targetUrl)
  450.  
  451. allowPopups = False
  452. return not allowPopups
  453.  
  454. def _CreatePopup(self, url):
  455. frame = MainFrame(url=url, popup=True)
  456. frame.Show()
  457.  
  458. def _OnAfterCreated(self, browser):
  459. # This is a global callback set using SetGlobalClientCallback().
  460. print("[cefhello] LifespanHandler::_OnAfterCreated()")
  461. print(" browserId=%s" % browser.GetIdentifier())
  462.  
  463. def RunModal(self, browser):
  464. print("[cefhello] LifespanHandler::RunModal()")
  465. print(" browserId=%s" % browser.GetIdentifier())
  466.  
  467. def DoClose(self, browser):
  468. print("[cefhello] LifespanHandler::DoClose()")
  469. print(" browserId=%s" % browser.GetIdentifier())
  470.  
  471. def OnBeforeClose(self, browser):
  472. print("[cefhello] LifespanHandler::OnBeforeClose")
  473. print(" browserId=%s" % browser.GetIdentifier())
  474.  
  475. # -------------------------------------------------------------------------
  476. # JavascriptDialogHandler
  477. # -------------------------------------------------------------------------
  478.  
  479. def OnJavascriptDialog(self, browser, originUrl, acceptLang, dialogType,
  480. messageText, defaultPromptText, callback,
  481. suppressMessage):
  482. print("[cefhello] JavascriptDialogHandler::OnJavascriptDialog()")
  483. print(" originUrl="+originUrl)
  484. print(" acceptLang="+acceptLang)
  485. print(" dialogType="+str(dialogType))
  486. print(" messageText="+messageText)
  487. print(" defaultPromptText="+defaultPromptText)
  488. # If you want to suppress the javascript dialog:
  489. # suppressMessage[0] = True
  490. return False
  491.  
  492. def OnBeforeUnloadJavascriptDialog(self, browser, messageText, isReload,
  493. callback):
  494. print("[cefhello] OnBeforeUnloadJavascriptDialog()")
  495. print(" messageText="+messageText)
  496. print(" isReload="+str(isReload))
  497. # Return True if the application will use a custom dialog:
  498. # callback.Continue(allow=True, userInput="")
  499. # return True
  500. return False
  501.  
  502. def OnResetJavascriptDialogState(self, browser):
  503. print("[cefhello] OnResetDialogState()")
  504.  
  505. def OnJavascriptDialogClosed(self, browser):
  506. print("[cefhello] OnDialogClosed()")
  507.  
  508.  
  509. class MyApp(wx.App):
  510. timer = None
  511. timerID = 1
  512. mainFrame = None
  513.  
  514. def OnInit(self):
  515. if not USE_EVT_IDLE:
  516. print("[cefhello] Using TIMER to run CEF message loop")
  517. self.CreateTimer()
  518. self.mainFrame = MainFrame()
  519. self.SetTopWindow(self.mainFrame)
  520. self.mainFrame.Show()
  521. return True
  522.  
  523. def CreateTimer(self):
  524. # See "Making a render loop":
  525. # http://wiki.wxwidgets.org/Making_a_render_loop
  526. # Another approach is to use EVT_IDLE in MainFrame,
  527. # see which one fits you better.
  528. self.timer = wx.Timer(self, self.timerID)
  529. self.timer.Start(10) # 10ms
  530. wx.EVT_TIMER(self, self.timerID, self.OnTimer)
  531.  
  532. def OnTimer(self, event):
  533. cefpython.MessageLoopWork()
  534.  
  535. def OnExit(self):
  536. # When app.MainLoop() returns, MessageLoopWork() should
  537. # not be called anymore.
  538. print("[cefhello] MyApp.OnExit")
  539. if not USE_EVT_IDLE:
  540. self.timer.Stop()
  541.  
  542.  
  543.  
  544. if __name__ == '__main__':
  545. print('[cefhello] architecture=%s-bit' % (8 * struct.calcsize("P")))
  546. print('[cefhello] wx.version=%s' % wx.version())
  547.  
  548. # Intercept python exceptions. Exit app immediately when exception
  549. # happens on any of the threads.
  550. sys.excepthook = ExceptHook
  551.  
  552. # Application settings
  553. g_applicationSettings = {
  554. # Disk cache
  555. # "cache_path": "webcache/",
  556.  
  557. # CEF Python debug messages in console and in log_file
  558. "debug": True,
  559. # Set it to LOGSEVERITY_VERBOSE for more details
  560. "log_severity": cefpython.LOGSEVERITY_INFO,
  561. # Set to "" to disable logging to a file
  562. "log_file": GetApplicationPath("debug.log"),
  563. # This should be enabled only when debugging
  564. "release_dcheck_enabled": True,
  565.  
  566. # These directories must be set on Linux
  567. "locales_dir_path": cefpython.GetModuleDirectory()+"/locales",
  568. "resources_dir_path": cefpython.GetModuleDirectory(),
  569. # The "subprocess" executable that launches the Renderer
  570. # and GPU processes among others. You may rename that
  571. # executable if you like.
  572. "browser_subprocess_path": "%s/%s" % (
  573. cefpython.GetModuleDirectory(), "subprocess"),
  574.  
  575. }
  576.  
  577. # You can comment out the code below if you do not want High
  578. # DPI support. If you disable it text will look fuzzy on
  579. # high DPI displays.
  580. #
  581. # Enabling High DPI support in app can be done by
  582. # embedding a DPI awareness xml manifest in executable
  583. # (see Issue 112 comment #2), or by calling SetProcessDpiAware
  584. # function. Embedding xml manifest is the most reliable method.
  585. # The downside of calling SetProcessDpiAware is that scrollbar
  586. # in CEF browser is smaller than it should be. This is because
  587. # DPI awareness was set too late, after the CEF dll was loaded.
  588. # To fix that embed DPI awareness xml manifest in the .exe file.
  589. #
  590. # There is one bug when enabling High DPI support - fonts in
  591. # javascript dialogs (alert) are tiny. However, you can implement
  592. # custom javascript dialogs using JavascriptDialogHandler.
  593. #
  594. # Additionally you have to set "auto_zomming" application
  595. # setting. High DPI support is available only on Windows.
  596. # You may set auto_zooming to "system_dpi" and browser
  597. # contents will be zoomed using OS DPI settings. On Win7
  598. # these can be set in: Control Panel > Appearance and
  599. # Personalization > Display.
  600. #
  601. # Example values for auto_zooming are:
  602. # "system_dpi", "0.0" (96 DPI), "1.0" (120 DPI),
  603. # "2.0" (144 DPI), "-1.0" (72 DPI)
  604. # Numeric value means a zoom level.
  605. # Example values that can be set in Win7 DPI settings:
  606. # Smaller 100% (Default) = 96 DPI = 0.0 zoom level
  607. # Medium 125% = 120 DPI = 1.0 zoom level
  608. # Larger 150% = 144 DPI = 2.0 zoom level
  609. # Custom 75% = 72 DPI = -1.0 zoom level
  610. g_applicationSettings["auto_zooming"] = "system_dpi"
  611. print("[cefhello] Calling SetProcessDpiAware")
  612. cefpython.DpiAware.SetProcessDpiAware()
  613.  
  614. # Browser settings. You may have different settings for each
  615. # browser, see the call to CreateBrowserSync.
  616. g_browserSettings = {
  617. # "plugins_disabled": True,
  618. # "file_access_from_file_urls_allowed": True,
  619. # "universal_access_from_file_urls_allowed": True,
  620. }
  621.  
  622. # Command line switches set programmatically
  623. g_commandLineSwitches = {
  624. # "proxy-server": "socks5://127.0.0.1:8888",
  625. # "no-proxy-server": "",
  626. # "enable-media-stream": "",
  627. # "disable-gpu": "",
  628.  
  629. }
  630.  
  631. cefpython.Initialize(g_applicationSettings, g_commandLineSwitches)
  632.  
  633. app = MyApp(False)
  634. app.MainLoop()
  635.  
  636. # Let wx.App destructor do the cleanup before calling
  637. # cefpython.Shutdown(). This is to ensure reliable CEF shutdown.
  638. del app
  639.  
  640. cefpython.Shutdown()
  641.  
  642. browser_spawn()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement