XEmacs 21.4.2 "Developer-Friendly Unix APIs".
[chise/xemacs-chise.git.1] / lisp / printer.el
1 ;;; printer.el --- support for hard-copy printing in XEmacs
2
3 ;; Copyright (C) 2000 Ben Wing.
4 ;; Copyright (C) 2000 Kirill Katsnelson.
5
6 ;; Maintainer: XEmacs Development Team
7 ;; Keywords: printer, printing, internal, dumped
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24 ;; 02111-1307, USA.
25
26 ;;; Synched up with: Not in FSF.
27
28 ;;; Authorship:
29
30 ;; Created 2000 by Ben Wing, to provide the high-level interface onto the
31 ;; print support implemented by Kirill Katsnelson.
32
33 ;;; Commentary:
34
35 ;; This file is dumped with XEmacs.
36
37 \f
38 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
39 ;;                          generic printing code                        ;;
40 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
41
42 ;; #### should be named print-buffer, but that's currently in
43 ;; lpr-buffer with some horrible definition: print-buffer == "print with
44 ;; headings", lpr-buffer == "print without headings", and the headings are
45 ;; generated by calling the external program "pr"!  This is major stone-age
46 ;; here!
47 ;;
48 ;; I propose junking that package entirely and creating a unified,
49 ;; modern API here that will work well with modern GUI's on top of it,
50 ;; and with various different actual implementations (e.g. lpr or the
51 ;; pretty-print package on Unix, built-in msprinter support on
52 ;; Windows), where the workings of a particular implementation is
53 ;; hidden from the user and there is a consistent set of options to
54 ;; control how to print, which works across all implementations.
55 ;;
56 ;; The code here currently only really supports Windows.
57
58 (defgroup printing nil
59   "Generic printing support."
60   :group 'wp)
61
62 (defcustom printer-name nil
63   "*Name of printer to print to.
64 If nil, use default.
65 Under Windows, use `mswindows-printer-list' to get names of installed
66 printers."
67   :type 'string
68   :group 'printing)
69
70 (defstruct Print-context pageno window start-time printer-name)
71
72 (defvar printer-current-device nil)
73
74 (defun Printer-get-device ()
75   (or printer-current-device (setq printer-current-device
76                                    (make-device 'msprinter printer-name))))
77
78 (defun Printer-clear-device ()
79   (setq printer-current-device nil))
80
81 (defcustom printer-page-header '((face bold date) nil (face bold buffer-name))
82 "*Controls printed page header.
83
84 This can be:
85 - nil.  Header is not printed.
86 - An fbound symbol or lambda expression.  The function is called with
87    one parameter, a print-context object, every time the headers need
88    to be set up.  It can use the function `print-context-property' to
89    query the properties of this object.  The return value is treated as
90    if it was literally specified: i.e. it will be reprocessed.
91 - A list of up to three elements, for left, center and right portions
92    of the header.  Each of these can be
93    - nil, not to print the portion
94    - A string, which will be printed literally.
95    - A predefined symbol, on of the following:
96      printer-name     Name of printer being printed to
97      short-file-name  File name only, no path
98      long-file-name   File name with its path
99      buffer-name      Buffer name
100      date             Date current when printing started
101      time             Time current when printing started
102      page             Current printout page number, 1-based
103      user-id          User logon id
104      user-name        User full name
105    - A list of three elements: (face FACE-NAME EXPR).  EXPR is any of the
106      items given here.  The item will be displayed in the given face.
107    - A cons of an extent and any of the items given here.  The item will
108      be displayed using the extent's face, begin-glyph and end-glyph
109      properties.
110    - A list, each element of which is any of the items given here.
111      Each element of the list is rendered in sequence.  For example,
112      '(\"Page \" page) is rendered as \"Page 5\" on the fifth page.
113    - An fbound symbol or lambda expression, called with one parameter,
114      a print-context object, as above.  The return value is treated as
115      if it was literally specified: i.e. it will be reprocessed."
116   :type 'sexp
117   :group 'printing)
118
119 (defcustom printer-page-footer '(nil (face bold ("Page " page)))
120 "*Controls printed page footer.
121
122 Format is the same as `printer-page-header'."
123   :type 'sexp
124   :group 'printing)
125
126 (defun generate-header-element (element context)
127     (cond ((null element) nil)
128           ((stringp element) (insert element))
129           ((memq element '(printer-name
130                            short-file-name long-file-name buffer-name
131                            date time page user-id user-name))
132            (insert (print-context-property context element)))
133           ((and (consp element) (eq 'face (car element)))
134            (let ((p (point)))
135              (generate-header-element (third element) context)
136              (let ((x (make-extent p (point))))
137                (set-extent-face x (second element)))))
138           ((and (consp element) (extentp (car element)))
139            (let ((p (point)))
140              (generate-header-element (cdr element) context)
141              (let ((x (make-extent p (point))))
142                (set-extent-face x (extent-face (car element)))
143                (set-extent-begin-glyph x (extent-begin-glyph (car element)))
144                (set-extent-end-glyph x (extent-end-glyph (car element))))))
145           ((listp element)
146            (mapcar #'(lambda (el) (generate-header-element el context))
147                    element))
148           ((functionp element)
149            (generate-header-element (funcall element context) context))
150           (t (error 'invalid-argument "Unknown header element" element))))
151
152 (defun generate-header-line (spec context)
153   (let* ((left (first spec))
154          (middle (second spec))
155          (right (third spec))
156          (left-start (point))
157          (middle-start (progn (generate-header-element left context)
158                               (point)))
159          (right-start (progn (generate-header-element middle context)
160                              (point)))
161          (right-end (progn (generate-header-element right context)
162                            (point)))
163          (left-width (- middle-start left-start))
164          (middle-width (- right-start middle-start))
165          (right-width (- right-end right-start))
166          (winwidth (- (window-width (Print-context-window context)) 1))
167          (spaces1 (max (- (/ (- winwidth middle-width) 2) left-width) 0))
168          (spaces2 (max (- (- winwidth right-width)
169                           (+ left-width spaces1 middle-width))
170                        0)))
171     (goto-char right-start)
172     (insert-char ?\  spaces2)
173     (goto-char middle-start)
174     (insert-char ?\  spaces1)))
175
176 (defun print-context-property (print-context prop)
177   "Return property PROP of PRINT-CONTEXT.
178
179 Valid properties are
180
181 print-buffer     Buffer being printed
182 print-window     Window on printer device containing print buffer
183 print-frame      Frame on printer device corresponding to current page
184 print-device     Device referring to printer
185 print-start-time Time current when printing started (`current-time' format)
186 print-page       Current printout page number, 1-based
187 printer-name     Name of printer being printed to
188 short-file-name  File name only, no path
189 long-file-name   File name with its path
190 buffer-name      Buffer name
191 date             Date current when printing started (as a string)
192 time             Time current when printing started (as a string)
193 page             Current printout page number, 1-based (as a string)
194 user-id          User logon id (as a string)
195 user-name        User full name"
196   (let* ((window (Print-context-window print-context))
197          (pageno (Print-context-pageno print-context))
198          (start-time (Print-context-start-time print-context))
199          (printer-name (Print-context-printer-name print-context))
200          (buffer (window-buffer window)))
201     (case prop
202       (print-buffer buffer)
203       (print-window window)
204       (print-frame (window-frame window))
205       (print-device (frame-device (window-frame window)))
206       (print-start-time start-time)
207       (print-page pageno)
208       (printer-name printer-name)
209       (short-file-name (let ((name (buffer-file-name buffer)))
210                          (if name (file-name-nondirectory name) "")))
211       (long-file-name (let ((name (buffer-file-name buffer)))
212                         (or name "")))
213       (buffer-name (buffer-name buffer))
214       (date (format-time-string "%x" start-time))
215       (time (format-time-string "%X" start-time))
216       (page (format "%d" pageno))
217       (user-id (format "%d" (user-uid)))
218       (user-name (format "%d" (user-login-name)))
219       (t (error 'invalid-argument "Unrecognized print-context property"
220                 prop)))))
221
222 (defun generic-page-setup ()
223   "Display the Page Setup dialog box.
224 Changes made are recorded internally."
225   (interactive)
226   (let* ((d (Printer-get-device))
227          (props
228           (condition-case err
229               (make-dialog-box 'page-setup :device d
230                                :properties default-msprinter-frame-plist)
231             (error
232              (Printer-clear-device)
233              (signal (car err) (cdr err))))))
234     (while props
235       (setq default-msprinter-frame-plist
236             (plist-put default-msprinter-frame-plist (car props) (cadr props)))
237       (setq props (cddr props)))))
238
239 (defun generic-print-buffer (&optional buffer display-print-dialog)
240   "Print buffer BUFFER using a printing method appropriate to the O.S. being run.
241 Under Unix, `lpr' is normally used to spool out a no-frills version of the
242 buffer, or the `ps-print' package is used to pretty-print the buffer to a
243 PostScript printer.  Under MS Windows, the built-in printing support is used.
244
245 If DISPLAY-PRINT-DIALOG is t, the print dialog will first be
246 displayed, allowing the user to select various printing settings
247 \(e.g. which printer to print to, the range of pages, number of copies,
248 modes such landscape/portrait/2-up/4-up [2 or 4 (small!) logical pages
249 per physical page], etc.).  At this point the user can cancel the printing
250 operation using the dialog box, and `generic-print-buffer' will not print
251 anything.  When called interactively, use a prefix arg to suppress the
252 display of the print dialog box.
253
254 If BUFFER is nil or omitted, the current buffer is used."
255   (interactive (list nil (not current-prefix-arg)))
256   (if (or (not (valid-specifier-tag-p 'msprinter))
257           (not display-print-dialog))
258       (generic-print-region (point-min buffer) (point-max buffer) buffer)
259     (let* ((d (Printer-get-device))
260            (props (condition-case err
261                       (make-dialog-box 'print :device d)
262                     (error
263                      (Printer-clear-device)
264                      (signal (car err) (cdr err))))))
265       (and props (generic-print-region (point-min buffer)
266                                        (point-max buffer) buffer
267                                        d props)))))
268
269 (defun generic-print-region (start end &optional buffer print-device props)
270   "Print region using a printing method appropriate to the O.S. being run.
271 The region between START and END of BUFFER (defaults to the current
272 buffer) is printed.
273
274 Under Unix, `lpr' is normally used to spool out a no-frills version of the
275 buffer, or the `ps-print' package is used to pretty-print the buffer to a
276 PostScript printer.  Under MS Windows, the built-in printing support is used.
277
278 Optional PRINT-DEVICE is a device, already created, to use to do the
279 printing.  This is typically used when this function was invoked from
280 `generic-print-buffer' and it displayed a dialog box.  That function created
281 the device, and then the dialog box stuffed it with the user's selections
282 of how the buffer should be printed.
283
284 PROPS, if given, is typically the plist returned from the call to
285 `make-dialog-box' that displayed the Print box.  It contains properties
286 relevant to us when we print.  
287
288 Recognized properties are the same as those in `make-dialog-box':
289
290   name       Printer device name.  If omitted, the current system-selected
291              printer will be used.
292   from-page  First page to print, 1-based. If omitted, printing starts from
293              the beginning.
294   to-page    Last page to print, inclusive, If omitted, printing ends at
295              the end.
296   copies     Number of copies to print.  If omitted, one copy is printed."
297   (cond ((valid-specifier-tag-p 'msprinter)
298          (let (d f header-buffer footer-buffer)
299            (setq buffer (decode-buffer buffer))
300            (unwind-protect
301                (progn
302                  (setq d (or print-device (Printer-get-device)))
303                  (setq f (make-frame
304                           (list* 'name (concat
305                                         (substitute ?_ ?. (buffer-name buffer))
306                                         " - XEmacs")
307                                  '(menubar-visible-p
308                                    nil
309                                    has-modeline-p nil
310                                    default-toolbar-visible-p nil
311                                    default-gutter-visible-p nil
312                                    minibuffer none
313                                    modeline-shadow-thickness 0
314                                    vertical-scrollbar-visible-p nil
315                                    horizontal-scrollbar-visible-p nil))
316                           d))
317                  (let* ((w (frame-root-window f))
318                         (vertdpi (cdr (device-system-metric d 'device-dpi)))
319                         (pixel-vertical-clip-threshold (/ vertdpi 2))
320                         (from-page (plist-get props 'from-page 1))
321                         (to-page (plist-get props 'to-page))
322                         (copies (plist-get props 'copies 1))
323                         (context (make-Print-context
324                                   :start-time (current-time)
325                                   ;; #### bogus! we need accessors for
326                                   ;; print-settings objects.
327                                   :printer-name
328                                   (or (plist-get props 'name)
329                                       printer-name
330                                       (mswindows-get-default-printer))))
331                         header-window
332                         footer-window)
333
334                    (when printer-page-header
335                      (let ((window-min-height 2))
336                        (setq header-window w)
337                        (setq w (split-window w 2)))
338                      (setq header-buffer (generate-new-buffer " *header*"))
339                      (set-window-buffer header-window header-buffer))
340
341                    (when printer-page-footer
342                      (let ((window-min-height 2))
343                        (setq footer-window
344                              (split-window w (- (window-height w) 2))))
345                      (setq footer-buffer (generate-new-buffer " *footer*"))
346                      (set-window-buffer footer-window footer-buffer))
347
348                    (setf (Print-context-window context) w)
349
350                    ;; loop, printing one copy of document per loop
351                    (while (> copies 0)
352                      (let ((last-end 0) ; bufpos at end of previous page
353                            reached-end  ; t if we've reached the end of the
354                                         ; text we're printing
355                            (pageno 1))
356                        (set-window-buffer w buffer)
357                        (set-window-start w start)
358
359                        ;; loop, printing one page per loop
360                        (while (and (not reached-end)
361                                    ;; stop at end of region of text or
362                                    ;; outside of ranges of pages given
363                                    (or (not to-page) (<= pageno to-page)))
364
365                          (setf (Print-context-pageno context) pageno)
366
367                          ;; only actually print the page if it's in the
368                          ;; range.
369                          (when (>= pageno from-page)
370                            (when printer-page-header
371                              (with-current-buffer header-buffer
372                                (erase-buffer)
373                                (generate-header-line printer-page-header
374                                                      context)
375                                (goto-char (point-min))
376                                (set-window-start header-window (point-min))))
377
378                            (when printer-page-footer
379                              (with-current-buffer footer-buffer
380                                (erase-buffer)
381                                (insert "\n")
382                                (generate-header-line printer-page-footer
383                                                      context)
384                                (goto-char (point-min))
385                                (set-window-start footer-window (point-min))))
386
387                            (redisplay-frame f t)
388                            (print-job-eject-page f)
389                            )
390                          ;; but use the GUARANTEE argument to `window-end'
391                          ;; so that we get the right value even if we
392                          ;; didn't do a redisplay.
393                          (let ((this-end (window-end w t))
394                                (pixvis (window-last-line-visible-height w)))
395                            ;; in case we get stuck somewhere, bow out
396                            ;; rather than printing an infinite number of
397                            ;; pages.  #### this will fail with an image
398                            ;; bigger than an entire page.  but we really
399                            ;; need this check here.  we should be more
400                            ;; clever in our check, to deal with this case.
401                            (if (or (= this-end last-end)
402                                    ;; #### fuckme!  window-end returns a value
403                                    ;; outside of the valid range of buffer
404                                    ;; positions!!!
405                                    (>= this-end end))
406                                (setq reached-end t)
407                              (setq last-end this-end)
408                              (set-window-start w this-end)
409                              (if pixvis
410                                  (save-selected-window
411                                    (select-window w)
412                                    ;; #### scroll-down should take a
413                                    ;; window arg.
414                                    (let ((window-pixel-scroll-increment
415                                           pixvis))
416                                      (scroll-down 1))))))
417                          (setq pageno (1+ pageno))))
418                      (setq copies (1- copies)))))
419              (and f (delete-frame f))
420              (and header-buffer (kill-buffer header-buffer))
421              (and footer-buffer (kill-buffer footer-buffer))
422              )))
423         ((and (not (eq system-type 'windows-nt))
424               (fboundp 'lpr-region))
425          (lpr-region buffer))
426         (t (error "No print support available"))))