@@ -35,49 +35,48 @@ def flush(self):
35
35
utf8buf = unicodepage .UTF8Converter (preserve_control = True ).to_utf8 (printbuf )
36
36
line_print (utf8buf , self .printer_name )
37
37
38
+ # only needed on Windows
39
+ wait = lambda x : None
38
40
39
41
if plat .system == 'Windows' :
40
- import tempfile
41
- import threading
42
42
import os
43
43
import win32print
44
44
import win32api
45
45
import win32com
46
46
import win32com .shell .shell
47
47
import win32event
48
+ # temp file in temp dir
49
+ printfile = os .path .join (plat .temp_dir , 'pcbasic_print.txt' )
50
+ # handle for last printing process
51
+ handle = - 1
48
52
49
53
def line_print (printbuf , printer_name ):
50
54
""" Print the buffer to a Windows printer. """
55
+ global handle
51
56
if printer_name == '' or printer_name == 'default' :
52
57
printer_name = win32print .GetDefaultPrinter ()
53
- with tempfile .NamedTemporaryFile (mode = 'wb' , prefix = 'pcbasic_' ,
54
- suffix = '.txt' , delete = False ) as f :
58
+ # open a file in our PC-BASIC temporary directory
59
+ # this will get cleaned up on exit
60
+ with open (printfile , 'wb' ) as f :
55
61
# write UTF-8 Byte Order mark to ensure Notepad recognises encoding
56
62
f .write ('\xef \xbb \xbf ' )
57
63
f .write (printbuf )
58
- # flush buffer to ensure it all actually gets printed
59
- f .flush ()
60
- # fMask = SEE_MASK_NOASYNC(0x00000100) + SEE_MASK_NOCLOSEPROCESS
64
+ # fMask = SEE_MASK_NOASYNC(0x00000100) + SEE_MASK_NOCLOSEPROCESS
65
+ try :
61
66
resdict = win32com .shell .shell .ShellExecuteEx (fMask = 256 + 64 ,
62
- lpVerb = 'printto' , lpFile = f . name ,
67
+ lpVerb = 'printto' , lpFile = printfile ,
63
68
lpParameters = '"%s"' % printer_name )
64
69
handle = resdict ['hProcess' ]
65
- # spin off a thread as the WIndows AI timeout doesn't work
66
- # all this fluff just to print a bit of plain text on Windows...
67
- outp = threading .Thread (target = wait_printer , args = (handle , f .name ))
68
- outp .daemon = True
69
- outp .start ()
70
-
71
- def wait_printer (handle , filename ):
72
- """ Wait for the print to finish, then delete temp file. """
73
- # note that this fails to delete the temp file for print jobs on exit
74
- if win32event .WaitForSingleObject (handle , - 1 ) != win32event .WAIT_OBJECT_0 :
75
- logging .warning ('Printing process failed' )
76
- try :
77
- os .remove (filename )
78
- except EnvironmentError as e :
70
+ except WindowsError as e :
79
71
logging .warning ('Error while printing: %s' , str (e ))
72
+ handle = - 1
80
73
74
+ def wait ():
75
+ """ Give printing process some time to complete. """
76
+ try :
77
+ win32event .WaitForSingleObject (handle , 1000 )
78
+ except WindowsError :
79
+ pass
81
80
82
81
elif plat .system == 'Android' :
83
82
0 commit comments