1010
1111import platform
1212if platform .architecture ()[0 ] != "32bit" :
13- raise Exception ("Unsupported architecture: %s" % (
14- platform .architecture ()[0 ]))
13+ raise Exception ("Only 32bit architecture is supported" )
1514
1615import sys
17- if sys .hexversion >= 0x02070000 and sys .hexversion < 0x03000000 :
18- import cefpython_py27 as cefpython
19- elif sys .hexversion >= 0x03000000 and sys .hexversion < 0x04000000 :
20- import cefpython_py32 as cefpython
21- else :
22- raise Exception ("Unsupported python version: %s" % sys .version )
16+ try :
17+ # Import local PYD file (portable zip).
18+ if sys .hexversion >= 0x02070000 and sys .hexversion < 0x03000000 :
19+ import cefpython_py27 as cefpython
20+ elif sys .hexversion >= 0x03000000 and sys .hexversion < 0x04000000 :
21+ import cefpython_py32 as cefpython
22+ else :
23+ raise Exception ("Unsupported python version: %s" % sys .version )
24+ except ImportError :
25+ # Import from package (installer exe).
26+ from cefpython1 import cefpython
2327
2428import cefwindow
2529
3337import imp
3438import inspect
3539import pprint
40+ import time
41+ import imp
3642
3743DEBUG = True
3844
3945# TODO: example of creating popup windows from python,
4046# call WindowInfo.SetAsPopup().
4147# TODO: example of creating modal windows from python.
4248
43- def CefAdvanced ():
49+ def GetApplicationPath (file = None ):
50+ import re , os
51+ # If file is None return current directory without trailing slash.
52+ if file is None :
53+ file = ""
54+ # Only when relative path.
55+ if not file .startswith ("/" ) and not file .startswith ("\\ " ) and (
56+ not re .search (r"^[\w-]+:" , file )):
57+ if hasattr (sys , "frozen" ):
58+ path = os .path .dirname (sys .executable )
59+ elif "__file__" in globals ():
60+ path = os .path .dirname (os .path .realpath (__file__ ))
61+ else :
62+ path = os .getcwd ()
63+ path = path + os .sep + file
64+ path = re .sub (r"[/\\]+" , re .escape (os .sep ), path )
65+ path = re .sub (r"[/\\]+$" , "" , path )
66+ return path
67+ return str (file )
68+
69+ def ExceptHook (type , value , traceObject ):
70+ import traceback , os , time
4471 # This hook does the following: in case of exception display it,
4572 # write to error.log, shutdown CEF and exit application.
46- sys .excepthook = cefpython .ExceptHook
73+ error = "\n " .join (traceback .format_exception (type , value , traceObject ))
74+ with open (GetApplicationPath ("error.log" ), "a" ) as file :
75+ file .write ("\n [%s] %s\n " % (time .strftime ("%Y-%m-%d %H:%M:%S" ), error ))
76+ print ("\n " + error + "\n " )
77+ cefpython .QuitMessageLoop ()
78+ cefpython .Shutdown ()
79+ # So that "finally" does not execute.
80+ os ._exit (1 )
4781
82+ def InitDebugging ():
4883 # Whether to print & log debug messages, log file is "debug.log".
4984 if DEBUG :
5085 cefpython .g_debug = True
86+ cefpython .g_debugFile = GetApplicationPath ("debug.log" )
5187 cefwindow .g_debug = True
5288
89+ def CefAdvanced ():
90+ sys .excepthook = ExceptHook
91+ InitDebugging ()
92+
5393 appSettings = dict ()
54- appSettings ["log_file" ] = cefpython . GetRealPath ("debug.log" )
94+ appSettings ["log_file" ] = GetApplicationPath ("debug.log" )
5595
5696 # LOGSEVERITY_INFO - less debug oput.
5797 # LOGSEVERITY_DISABLE - will not create "debug.log" file.
@@ -89,7 +129,8 @@ def CefAdvanced():
89129 windowInfo = cefpython .WindowInfo ()
90130 windowInfo .SetAsChild (windowHandle )
91131 browser = cefpython .CreateBrowserSync (
92- windowInfo , browserSettings , "cefadvanced.html" )
132+ windowInfo , browserSettings = browserSettings ,
133+ navigateUrl = GetApplicationPath ("cefadvanced.html" ))
93134 browser .SetUserData ("outerWindowHandle" , windowInfo .parentWindowHandle )
94135 browser .SetClientHandler (ClientHandler ())
95136 browser .SetJavascriptBindings (javascriptBindings )
@@ -137,7 +178,7 @@ def Rebind(self):
137178 # Reload all application modules, next rebind javascript bindings.
138179 # Called from: OnKeyEvent > F5.
139180
140- currentDir = cefpython . GetRealPath ()
181+ currentDir = GetApplicationPath ()
141182
142183 for mod in sys .modules .values ():
143184 if mod and mod .__name__ != "__main__" :
@@ -152,11 +193,9 @@ def Rebind(self):
152193 print ("WARNING: reloading module failed: %s. "
153194 "Exception: %s" % (mod .__name__ , exc ))
154195
155- if DEBUG :
156- # These modules have been reloaded, we need to set
157- # debug variables again.
158- cefpython .g_debug = True
159- cefwindow .g_debug = True
196+ # cefpython & cefwindow modules have been reloaded,
197+ # we need to re-initialize debugging.
198+ InitDebugging ()
160199
161200 self .Bind ()
162201 self .javascriptBindings .Rebind ()
@@ -227,7 +266,7 @@ def OnKeyEvent(self, browser, eventType, keyCode, modifiers, isSystemKey,
227266 return False
228267
229268 def OnConsoleMessage (self , browser , message , source , line ):
230- appdir = cefpython . GetRealPath ().replace ("\\ " , "/" )
269+ appdir = GetApplicationPath ().replace ("\\ " , "/" )
231270 if appdir [1 ] == ":" :
232271 appdir = appdir [0 ].upper () + appdir [1 :]
233272 source = source .replace ("file:///" , "" )
@@ -253,7 +292,7 @@ def OnUncaughtException(self, browser, frame, exception, stackTrace):
253292 # get rid of the "file://d:/.../cefpython/".
254293 url = re .sub (r"^file:/+" , "" , url )
255294 url = re .sub (r"[/\\]+" , re .escape (os .sep ), url )
256- url = re .sub (r"%s" % re .escape (cefpython . GetRealPath ()),
295+ url = re .sub (r"%s" % re .escape (GetApplicationPath ()),
257296 "" , url , flags = re .IGNORECASE )
258297 url = re .sub (r"^%s" % re .escape (os .sep ), "" , url )
259298 raise Exception ("%s.\n "
@@ -267,31 +306,51 @@ def OnTitleChange(self, browser, title):
267306 # return False
268307 return True
269308
309+ def ModuleExists (module ):
310+ try :
311+ imp .find_module (module )
312+ return True
313+ except ImportError :
314+ return False
315+
270316class Python :
271317 browser = None
272318
273319 def SaveImage (self , outfile , format ):
274- outfile = cefpython .GetRealPath (outfile )
275- try :
276- from PIL import Image
277- except :
278- print ("PIL library not available, can't save image" )
279- return
320+ outfile = GetApplicationPath (outfile )
280321 (width , height ) = self .browser .GetSize (cefpython .PET_VIEW )
281322 buffer = self .browser .GetImage (cefpython .PET_VIEW , width , height )
323+ if ModuleExists ("PIL" ):
324+ self .__SaveImageWithPil (buffer , width , height , outfile , format )
325+ elif ModuleExists ("pygame" ):
326+ self .__SaveImageWithPygame (buffer , width , height , outfile )
327+ else :
328+ print ("Could not save image, no image library found (PIL, pygame)" )
329+ if os .path .exists (outfile ):
330+ os .system (outfile )
331+
332+ def __SaveImageWithPil (self , buffer , width , height , outfile , format ):
333+ from PIL import Image
282334 image = Image .fromstring (
283335 "RGBA" , (width ,height ),
284336 buffer .GetString (mode = "rgba" , origin = "top-left" ),
285337 "raw" , "RGBA" , 0 , 1 )
286338 image .save (outfile , format )
287- os .system (outfile )
339+
340+ def __SaveImageWithPygame (self , buffer , width , height , outfile ):
341+ import pygame
342+ # Format "PNG" is read from the filename.
343+ surface = pygame .image .frombuffer (
344+ buffer .GetString (mode = "rgba" , origin = "top-left" ),
345+ (width , height ), "RGBA" )
346+ pygame .image .save (surface , outfile )
288347
289348 def ExecuteJavascript (self , jsCode ):
290349 self .browser .GetMainFrame ().ExecuteJavascript (jsCode )
291350
292351 def LoadUrl (self ):
293352 self .browser .GetMainFrame ().LoadUrl (
294- cefpython . GetRealPath ("cefsimple.html" ))
353+ GetApplicationPath ("cefsimple.html" ))
295354
296355 def Version (self ):
297356 return sys .version
@@ -389,7 +448,8 @@ def CreateSecondBrowser(self):
389448 windowInfo2 = cefpython .WindowInfo ()
390449 windowInfo2 .SetAsChild (windowHandle2 )
391450 browser2 = cefpython .CreateBrowserSync (
392- windowInfo2 , browserSettings = {}, navigateURL = "cefsimple.html" )
451+ windowInfo2 , browserSettings = {},
452+ navigateUrl = GetApplicationPath ("cefsimple.html" ))
393453 browser2 .SetUserData ("outerWindowHandle" , windowHandle2 )
394454
395455 def GetUnicodeString (self ):
0 commit comments