work on binary files:
[openerp-client.git] / bin / printer / printer.py
blob3ab2699f498e173a7c94308038381c60b242ae97
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
6 # $Id$
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 ##############################################################################
31 # ------------------------------------------------------------------- #
32 # Module printer
33 # ------------------------------------------------------------------- #
35 # Supported formats: pdf
37 # Print or open a previewer
40 import os, base64, options, sys
41 import gc
42 import common
43 import time
44 import gtk
46 class Printer(object):
48 def __init__(self):
49 self.openers = {
50 'pdf': self._findPDFOpener,
51 'html': self._findHTMLOpener,
52 'doc': self._findHTMLOpener,
53 'xls': self._findHTMLOpener,
54 'sxw': self._findSXWOpener,
57 def _findInPath(self, progs):
58 lstprogs = progs[:]
59 found = {}
60 path = [dir for dir in os.environ['PATH'].split(':')
61 if os.path.isdir(dir)]
62 for dir in path:
63 content = os.listdir(dir)
64 for prog in progs[:]:
65 if prog in content:
66 return os.path.join(dir, prog)#prog
68 progs.remove(prog)
69 found[prog] = os.path.join(dir, prog)
70 for prog in lstprogs:
71 if prog in found:
72 return found[prog]
73 return ''
75 def _findHTMLOpener(self):
76 import webbrowser
77 def opener(fn):
78 webbrowser.open('file://'+fn)
79 return opener
81 def __opener(self, fnct):
82 pid = os.fork()
83 if not pid:
84 pid = os.fork()
85 if not pid:
86 fnct()
87 time.sleep(0.1)
88 sys.exit(0)
89 os.waitpid(pid, 0)
91 def _findPDFOpener(self):
92 if os.uname()[0] == 'Darwin' :
93 def opener(fn):
94 self.__opener( lambda: os.system('/usr/bin/open -a Preview ' + fn) )
95 return opener
96 if os.name == 'nt':
97 if options.options['printer.preview']:
98 if options.options['printer.softpath'] == 'none':
99 return lambda fn: os.startfile(fn)
100 else:
101 return lambda fn: os.system(options.options['printer.softpath'] + ' ' + fn)
102 else:
103 return lambda fn: print_w32_filename(fn)
104 else:
105 if options.options['printer.preview']:
106 if options.options['printer.softpath'] == 'none':
107 prog = self._findInPath(['evince', 'xpdf', 'gpdf', 'kpdf', 'epdfview', 'acroread', 'open'])
108 def opener(fn):
109 self.__opener( lambda: os.execv(prog, (os.path.basename(prog), fn) ))
110 return opener
111 else:
112 def opener(fn):
113 self.__opener( lambda: os.execv(options.options['printer.softpath'], (os.path.basename(options.options['printer.softpath']), fn)) )
114 return opener
115 else:
116 return lambda fn: print_linux_filename(fn)
118 def _findSXWOpener(self):
119 if os.name == 'nt':
120 return lambda fn: os.startfile(fn)
121 else:
122 if options.options['printer.softpath_html'] == 'none':
123 prog = self._findInPath(['ooffice', 'ooffice2', 'openoffice', 'soffice'])
124 def opener(fn):
125 pid = os.fork()
126 if not pid:
127 pid = os.fork()
128 if not pid:
129 os.execv(prog, (os.path.basename(prog),fn))
130 time.sleep(0.1)
131 sys.exit(0)
132 os.waitpid(pid, 0)
133 return opener
134 else:
135 def opener(fn):
136 pid = os.fork()
137 if not pid:
138 pid = os.fork()
139 if not pid:
140 os.execv(options.options['printer.softpath_html'], (os.path.basename(options.options['printer.softpath_html']),fn))
141 time.sleep(0.1)
142 sys.exit(0)
143 os.waitpid(pid, 0)
144 return opener
146 def print_file(self, fname, ftype, preview=False):
147 app_to_run = None
148 try:
149 filetypes = eval( options.options['extensions.filetype'] )
150 (app, app_print) = filetypes[ftype]
151 if options.options['printer.preview'] or preview:
152 app_to_run = app
153 else:
154 app_to_run = app_print
155 except:
156 pass
158 if app_to_run:
159 def open_file( cmd, filename ):
160 cmd = cmd % filename
161 pid = os.fork()
162 if not pid:
163 pid = os.fork()
164 if not pid:
165 prog, args = cmd.split(' ', 1)
166 args = [os.path.basename(prog)] + args.split(' ')
167 try:
168 os.execvp(prog, args)
169 except:
170 pass
171 time.sleep(0.1)
172 sys.exit(0)
173 os.waitpid(pid, 0)
175 if sys.platform in ['win32','nt']:
176 if app_to_run:
177 open_file( app_to_run, fname )
178 else:
179 os.startfile( fname )
180 else:
181 open_file( app_to_run, fname )
182 else:
183 finderfunc = self.openers.get(ftype)
184 if not finderfunc:
185 raise Exception(_('Unable to handle %s filetype') % ftype)
186 opener = finderfunc()
187 opener(fname)
188 gc.collect()
191 printer = Printer()
193 def print_linux_filename(filename):
194 common.message(_('Linux Automatic Printing not implemented.\nUse preview option !'))
196 def print_w32_filename(filename):
197 import win32api
198 win32api.ShellExecute (0, "print", filename, None, ".", 0)
200 def print_data(data):
201 if 'result' not in data:
202 common.message(_('Error no report'))
203 if data.get('code','normal')=='zlib':
204 import zlib
205 content = zlib.decompress(base64.decodestring(data['result']))
206 else:
207 content = base64.decodestring(data['result'])
209 if data['format'] in printer.openers.keys():
210 import tempfile
211 if data['format']=='html' and os.name=='nt':
212 data['format']='doc'
213 (fileno, fp_name) = tempfile.mkstemp('.'+data['format'], 'tinyerp_')
214 fp = file(fp_name, 'wb+')
215 fp.write(content)
216 fp.close()
217 os.close(fileno)
218 printer.print_file(fp_name, data['format'])
219 else:
220 fname = common.file_selection(_('Save As...'), filename='report.' + data['format'],
221 action=gtk.FILE_CHOOSER_ACTION_SAVE)
222 if fname:
223 try:
224 fp = file(fname,'wb+')
225 fp.write(content)
226 fp.close()
227 except:
228 common.message(_('Error writing the file!'))
231 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: