Debian Codegraph @

contrib/pcl3/doc/notes.tex

raw
1 %******************************************************************************
2 % File: @(#)$Id: notes.tex,v 1.11 2001/02/24 06:00:16 Martin Rel $
3 % Contents: Notes an writing a ghostscript device driver
4 % This is a TeX file using the LaTeX package.
5 % Author: Martin Lottermoser, Greifswaldstrasse 28, 38124 Braunschweig,
6 % Germany. E-mail: [email protected].
7 %
8 %******************************************************************************
9 %
10 % Copyright (C) 2000, 2001 by Martin Lottermoser
11 % All rights reserved
12 %
13 %******************************************************************************
14
15 \documentclass[twoside,a4paper]{article}
16
17 % Macros to extract RCS information
18 \def\RCScontents$#1:#2 ${\ignorespaces#2}
19 \def\RCSDate$#1: #2/#3/#4 #5${#2--#3--#4}
20
21 % Extracted RCS information.
22 \setbox0=\hbox{\RCScontents$Locker: $}
23 \ifdim\wd0=0pt
24 \edef\Revision{\RCScontents$Revision: 1.11 $}
25 \edef\Date{\RCSDate$Date: 2001/02/24 06:00:16 $}
26 \def\BottomInfo{Version \Revision}
27 \else
28 \edef\Revision{\RCScontents$Revision: 1.11 $+}
29 \def\Date{\today}
30 \def\BottomInfo{Version of \Date}
31 \def\draft{}
32 \fi
33
34 % Title page information
35 \author{Martin Lottermoser\cr
36 {\tt [email protected]}\cr
37 Greifswaldstra{\ss}e 28\cr
38 38124 Braunschweig\cr
39 Germany}
40 \title{Notes on Writing a {\it Ghostscript\/} Device Driver for Printers}
41 \date{Version \Revision\ (\Date)}
42
43 % 25mm margins for A4
44 \textwidth=160truemm
45 \evensidemargin=-0.4truemm \oddsidemargin=\evensidemargin
46 \topmargin=-0.4truemm
47 \textheight=247truemm
48 \advance\textheight by -\headheight
49 \advance\textheight by -\headsep
50 \advance\textheight by -\footskip
51
52 % Page layout
53 \pagestyle{myheadings}
54 \makeatletter
55 \markboth{\@title}{\@title}
56 \def\@oddfoot{{\tiny\sl \BottomInfo\/}\hfil}
57 \makeatother
58
59 % Paragraph layout
60 \setlength{\parindent}{0mm }
61 \setlength{\parskip}{1.5mm plus 0.5mm minus 0.5mm }
62
63 %******************************************************************************
64
65 % Normal underscore
66 \catcode`\_=\active
67 \newcommand{\normalUS}{\catcode`\_=\active \def_{\char`\_}}
68 \catcode`\_=8
69
70 % My version of LaTeX does not know that cmtt has braces and substitutes them
71 % from cmsy.
72 \newcommand{\lb}{\char"7B}
73 \newcommand{\rb}{\char"7D}
74
75 % Abbreviations
76 \newcommand{\gs}{\textit{ghostscript\/}}
77 \newcommand{\Gs}{\textit{Ghostscript\/}}
78
79 % Markup
80 \newenvironment{note}{\begin{quote}\small}{\end{quote}}
81 \newenvironment{program}{\begin{quote}
82 \normalUS\ttfamily\obeylines\obeyspaces\parskip=0mm \parindent=0mm }%
83 {\end{quote}}
84 \newcommand{\ps}[1]{{\sffamily\bfseries #1}} % PostScript names in the text
85 \renewcommand{\d}[1]{{\bfseries #1}} % definition of a concept or name
86 \newcommand{\prog}[1]{\texttt{#1}}
87 \newcommand{\file}[1]{\texttt{#1}} % file names
88
89 \bibliographystyle{plain}
90
91 \hyphenation{ghost-script}
92
93 \newif\ifdraft \draftfalse
94 \expandafter\ifx\csname draft\endcsname\relax\else \drafttrue \fi
95
96 %******************************************************************************
97
98 \begin{document}
99 \maketitle
100
101 \tableofcontents
102
103 %******************************************************************************
104
105 \section{Introduction}
106
107 This document contains remarks which I consider useful for persons implementing
108 a \gs\ device driver for printers.
109 It is based on my experiences and in particular the mistakes I made in
110 implementing the \textit{hpdj/pcl3\/} driver~\cite{hpdj,pcl3}.
111 And yes, I have made lots of mistakes,
112 and I do not guarantee anything about the accuracy of this document either.
113
114 The topics covered in this document can be arranged in the following
115 categories:
116 \begin{itemize}
117 \item Suggestions on how to approach the implementation of a \gs\ device
118 driver
119 \item Information which is in my opinion necessary for properly implementing
120 a driver but which I could not find in \gs's documentation
121 \item Information I have collected for convenience
122 \item Parts which logically belong into the design documentation for
123 the \textit{hpdj/pcl3\/} driver but which have wider applicability
124 \end{itemize}
125
126 As the title indicates,
127 this is not an exhaustive introduction on how to write a \gs\ device driver.
128 You will need to access other documentation as well
129 (and, of course, do some thinking of your own),
130 preferably before reading this paper.
131
132 This document is still largely incomplete. %???
133
134 %==============================================================================
135
136 \subsection{The Most Important Advice on Writing a \Gs\ Device Driver}
137
138 \begin{center}
139 \bigskip
140 \begin{picture}(120, 30)
141 \put(60,15){\oval(120,30)}
142 \put(60,15){\makebox(0,0){\hfil\Large\em Don't do it!\/\hfil}}
143 \end{picture}
144 \bigskip
145 \end{center}
146
147 You should disregard this advice only if all of the following conditions are
148 true:
149 \begin{itemize}
150 \item You are prepared to spend a substantial amount of time on this task.
151 \item You have or are prepared to acquire sufficient knowledge of PostScript
152 to find relevant information in the
153 {\it PostScript Language Reference\/}~\cite{PostScript3},
154 hereafter abbreviated as ``PLR3''.
155 You must know chapters~6 and~7 (excluding sections~6.3 and~7.1) pretty well.
156 \item You either know \gs's internal APIs (in particular~\cite{Drivers6.01})
157 and programming conventions or are prepared to learn them.
158 (Obvious, of course, but I still thought I'd better mention it.)
159 \item You can read large amounts\footnote{%
160 % Aladdin gs 5.50: 243089 lines for *.c and *.h, 32914 for *.ps.
161 % loc gave 168705 NLOC for *.c and *.h.
162 \Gs\ has roughly 250,000~lines of C and 33,000~lines of PostScript
163 code~[gs~5.50].}
164 of source code (C and PostScript) written by another person and
165 locate and understand those sections which are relevant to a problem you
166 have encountered.
167 If you wish to write a reliable driver,
168 you will have to do this much more often than you expect.
169 \item In view of in particular the amount of time you will have to spend and
170 the amount of frustration you will experience,
171 the driver you have in mind will offer new functionality which is worth
172 this effort.
173 I would not expect this to be the case unless you have a sufficiently large
174 group of users.
175 \end{itemize}
176 If you conclude from this that my own experiences in writing \gs\ device
177 drivers were not entirely pleasant, you are right.
178 In particular,
179 I have serious doubts about whether the result justifies the effort I put into
180 it.
181 This document is an attempt to improve the result-to-effort ratio by making
182 my experience available to others.
183
184 %==============================================================================
185
186 \subsection{Restrictions}
187
188 This document concerns itself only with printer drivers.
189 By this I mean devices with the following properties:
190 \begin{itemize}
191 \item From the point of view of PostScript, we are dealing with a page device.
192 \item Processing in the driver can be split into two phases:
193 \begin{itemize}
194 \item creating a rasterized representation (pixmap) of the entire page in
195 memory,
196 \item converting it into another format appropriate for a particular kind
197 of hardware or software external to \gs, and
198 sending the converted data to a file.
199 \end{itemize}
200 \item From the point of view of \gs, we are dealing with a device derived
201 from the {\it prn\/} device.
202 \end{itemize}
203
204 %==============================================================================
205
206 \subsection{Conventions}
207
208 A word or group of words \d{in this type} has a special meaning.
209 The meaning is sometimes explained at the point where the term is denoted in
210 this manner,
211 but the main purpose is to alert the reader to the existence of a special
212 meaning connected with these words in the context of PostScript or \gs.
213
214 A reference like ``[gs~$n.m$]'' accompanying a statement means that I have
215 checked this statement to be true for \gs\ version~$n.m$.
216 These are typically statements about bugs in \gs\ or
217 information I could not find in \gs's documentation
218 but which I obtained from the source code or by experiment.
219
220 %******************************************************************************
221
222 \section{General Approach}
223
224 %==============================================================================
225
226 \subsection{PostScript First}
227
228 You should base your implementation on those properties of your driver which
229 will be visible in PostScript.
230
231 One reason is that \gs\ is changing fairly rapidly.
232 Although some effort is made to remain backward-compatible,
233 you cannot expect this to be always possible.
234 If you base your design on PostScript concepts,
235 the result is much more likely to be able to adapt easily to changes in \gs.
236 The same applies in areas where \gs\ does not yet correctly or entirely support
237 the PostScript language definition.
238
239 The second reason is that the PostScript language is well documented and offers
240 a reasonably broad range of concepts for you to use.
241 A description of similar coverage at the level of \gs's driver API does not
242 exist.
243 You will have to fill conceptual gaps in the latter from the former.
244
245 Finally, you should not dismiss the possibility that you might later want to
246 write a similar driver for another PostScript interpreter.
247 Everything which depends on PostScript only could then be reused unchanged,
248 although I would expect this to happen more on the level of structure and
249 concepts then with actual lines of code.
250
251 %==============================================================================
252
253 \subsection{Architecture}
254
255 It is almost certain that you'll find that a large part of what you need to
256 implement is entirely independent of the printer you wish to drive
257 and could be used for other drivers as well.
258 This is due to a gap between the functionality offered by the \gs\ kernel and
259 the functionality needed by most printer drivers.
260 This gap is only partly closed by the abstract \textit{prn\/} device
261 and this has led to a certain amount of duplicated code in \gs\ drivers.
262
263 One solution to this problem is to reuse code from another driver.
264 This is easiest to do if this functionality has been implemented in terms of an
265 abstract \gs\ device derived from the \textit{prn\/} device.
266 Your driver can then use this device instead of \textit{prn\/} as its base
267 device.
268 The \textit{pcl3\/} driver contains such an intermediate component in the
269 \textit{eprn\/} (``extended \textit{prn\/}'') device.
270 Its implementation has about
271 4700~brutto and 2400~netto lines of code. % pcl3 3.0.2
272 This gives you an impression of the size of the functionality gap you would
273 otherwise have to bridge on your own,
274 although admittedly not everything implemented in \textit{eprn\/} is
275 absolutely essential for every printer driver.
276
277 Independent of whether \textit{eprn\/} suits your needs or not,
278 you should always implement the universal part of your functionality
279 in a reusable form.
280
281 At the other end of your implementation you should consider encapsulating
282 printer-specific routines in a form which is largely independent of \gs.
283 This also makes it easier to reuse this code in other contexts.
284 The correct level of abstraction for this API is almost certainly near the
285 point where your driver has obtained a pixmap for the page to be printed and
286 has to convert it into the printer's language.
287
288 If you introduce these two layers of functionality,
289 the ``real'' driver will just be the intermediate layer connecting these two.
290 \begin{note}
291 In the implementation of my \textit{pcl3\/} driver about
292 47~\% of the code belongs to the high-level \textit{eprn\/} device,
293 21~\% can be found in the printer-specific backend,
294 and 32~\% are contained in the intermediate layer.
295 % This is based on NLOCs. BLOC-based values are even better: 49%, 24%, and
296 % 27%. This reflects the more extensive documentation I've provided in the
297 % reusable parts.
298 % (BLOC, NLOC) as of pcl3 3.0.2: (4658, 2361), (2263, 1084), (2620, 1616).
299 This means that roughly two thirds of the code could be reused
300 in other contexts!
301 \end{note}
302
303 %******************************************************************************
304
305 \section{Properties of an Output Device in PostScript}
306
307 %==============================================================================
308
309 \subsection{Definition}
310
311 A PostScript interpreter may support several \d{output devices}.
312 A \d{page device} is a special kind of output device.
313 Its state is characterized by \d{page device parameters}.
314
315 The \d{current (output) device} is part of the graphics state and can be
316 inspected with \ps{currentpagedevice}.
317 A new page device can be selected by calling \ps{setpagedevice}%
318 \footnote{%
319 For devices which are not page devices, other methods have to be
320 employed.
321 The null device, for example, is installed by calling \ps{nulldevice}.}
322 and passing the device name as a value for the \ps{OutputDevice} page device
323 parameter.%
324 \footnote{%
325 This does work with \gs\ but it produces a drastically reduced page device
326 dictionary without, e.g., \ps{HWResolution}~[gs~5.50, gs~6.50].
327 The official \gs\ interface for switching output devices from PostScript
328 is via the non-standard \ps{selectdevice} operator~\cite{Use5.50}.}
329 This resets all page device parameters to the default values appropriate for
330 the new device.
331
332 %==============================================================================
333
334 \subsection{Identity and Basic Properties}
335
336 An output device is identified by its name.
337 If the interpreter supports several output devices,
338 the \ps{OutputDevice} resource category should contain an entry for each device,
339 indexed by its name and listing the associated properties in an
340 \d{output device dictionary}.%
341 \footnote{\Gs\ does not list its available devices in the \ps{OutputDevice}
342 resource category~[gs~5.50, gs~6.50].
343 Furthermore, although defining an output device dictionary as an external
344 resource makes it visible to \ps{resourcestatus} and \ps{findresource},
345 \gs\ versions before~6.50 will not list it with \ps{resourceforall} unless
346 you execute \ps{findresource} first~[gs~5.50, gs~6.01].
347 This makes \ps{resourceforall} useless.
348 However, you can obtain the list of supported devices from \gs's
349 non-standard \ps{devicenames} operator.
350 }
351 Section~6.4 of PLR3 contains a list of these properties:
352 \begin{itemize}
353 \item media classes
354 \item page sizes
355 \item resolutions
356 \item process colour models
357 \item trapping details dictionary types
358 \end{itemize}
359 It is possible (but there is no corresponding statement in PLR3)
360 that a PostScript program relies on the assumption that,
361 if a value is listed as supported,
362 it is supported independent of the values chosen for other parameters
363 unless the meaning of the property in question restricts it explicitly to a
364 particular situation (this is only the case for \ps{DeviceN}).
365 This is a possible rule for separating output devices.
366
367 Therefore, if you have constraints among the values you wish to support
368 (e.g., \ps{DeviceGray} can be used at 600\,ppi but \ps{DeviceCMYK} is only
369 possible at 300\,ppi),
370 you should consider implementing these groups of unconstrained values
371 in different output devices.
372 This might be inconvenient, though,
373 and I myself have usually disregarded this advice.
374
375 %==============================================================================
376
377 \subsection{Process Colour Models}
378
379 PostScript defines six \d{process colour models}:
380 \begin{quote}
381 \ps{DeviceGray},
382 \ps{DeviceRGB}, \ps{DeviceRGBK},
383 \ps{DeviceCMY}, \ps{DeviceCMYK},
384 \ps{DeviceN}.
385 \end{quote}
386 A process colour model defines the \d{colorants} used by a device.
387 \ps{DeviceN} is a parameterized process colour model which has to be
388 supplemented by an explicit list of colorants (page device parameter
389 \ps{SeparationColorNames}).
390 Normally each device has one \d{native process colour model},
391 but it may support others.\footnote{
392 For example, a monochrome device capable of producing separations might
393 support the process colour model
394 \ps{DeviceCMYK}~\cite[page~424]{PostScript3}.}
395
396 Each process colour model has an underlying \d{native colour space}.
397 Because some process colour models are based on the same colour space
398 only the following four colour spaces act as native colour spaces:
399 \begin{quote}
400 \ps{DeviceGray},
401 \ps{DeviceRGB},
402 \ps{DeviceCMYK},
403 \ps{DeviceN}.
404 \end{quote}
405 The colour spaces \ps{DeviceGray}, \ps{DeviceRGB}, and \ps{DeviceCMYK} are
406 called \d{device colour spaces}.
407 The colour space \ps{DeviceN} is \emph{not\/} a device colour space
408 but one of the \d{special colour spaces}.
409
410 Note that a designation like ``\ps{DeviceRGB}'' can therefore denote a
411 colour space, a native colour space or a process colour model.
412 You have to find out which before you will be able to correctly understand
413 the statement containing such a name.
414
415 %==============================================================================
416
417 \subsection{Media Selection}
418
419 \subsubsection{Media Sources}
420
421 PostScript assumes the output device to have several \d{media sources},
422 each identified by an integer (\d{position number}).
423 You will have to decide how to associate these numbers with input trays or
424 whatever your printer supports.
425
426 Properties of the media currently present in a tray can be stored in the
427 \ps{InputAttributes} dictionary in the page device dictionary and are
428 accessed during \d{media selection}.
429
430 If the printer is capable of providing information on the properties of media
431 currently available in its input trays,
432 \ps{InputAttributes} should therefore be initialized appropriately
433 by the driver.
434
435 %------------------------------------------------------------------------------
436
437 \subsubsection{The Process}
438
439 PostScript's media selection process composes an \d{input media request} from
440 those among the page device parameters
441 \ps{PageSize}, \ps{MediaColor}, \ps{MediaWeight}, \ps{MediaType},
442 \ps{MediaClass}, and \ps{InsertSheet}
443 which are not \ps{null} (some devices may add others) and
444 tries to find a matching entry in \ps{InputAttributes}.
445 Apart from \ps{MatchAll}, only those parameters which a device
446 considers for inclusion in a media request should appear in an
447 \ps{InputAttributes} entry.
448
449 An entry in \ps{InputAttributes} \d{matches} the request if
450 \begin{itemize}
451 \item it contains matching entries (equal values, in the case of
452 \ps{PageSize} with a tolerance of 5~bp) for all parameters in the
453 request and
454 \item either
455 \begin{itemize}
456 \item does not have a \ps{MatchAll} entry which is \ps{true} or
457 \item does have a \ps{MatchAll} entry which is \ps{true} and
458 does not contain any entries in addition to \ps{MatchAll} and those
459 present in the media request.
460 \end{itemize}
461 \end{itemize}
462 Formally, you can define a relation ``$\leq$'' between two media requests or
463 \ps{InputAttributes} entries $a$ and~$b$ as follows:
464 \begin{displaymath}
465 a \leq b \quad :\Longleftrightarrow \quad
466 \vtop{\advance\hsize by -4cm
467 All parameters present in $a$ (except for \ps{MatchAll} in an
468 \ps{InputAttributes} entry) are also present in~$b$ and have matching
469 values.}
470 \end{displaymath}
471 The match rule can then be rephrased in the following manner:
472 \begin{quote}
473 An \ps{InputAttributes} entry~$e$ matches the input media request~$r$
474 if and only if $r \leq e$
475 except when \ps{MatchAll} is defined and \ps{true} in~$e$.
476 In the latter case one needs $r = e$.
477 \end{quote}
478 A media request is therefore a set of minimal requirements a media source must
479 satisfy in order for the document to be printed from that source.
480
481 Exceptions are possible if no match is found,
482 the \ps{Policies} dictionary permits ignoring at least one parameter in the
483 request,
484 and a matching request $r' < r$ can be formed.
485 PLR3 demands that in this case the interpreter must set the ignored
486 page device parameters to \ps{null}\footnote{%
487 \Gs\ does not currently do it [gs~6.01].}.
488 The only exception is \ps{PageSize} which will be set to the value present
489 in the \ps{InputAttributes} entry selected.
490 The state of the device thus becomes as if the document had originally
491 requested~$r'$.
492
493 %------------------------------------------------------------------------------
494
495 \subsubsection{Selection Parameters Which are also Configuration Parameters}
496
497 Let a ``configuration parameter'' be a page device parameter which influences
498 the way the output device adapts to the medium,
499 while a ``selection parameter'' is a parameter considered for inclusion in a
500 media request.
501 The 6~standard selection parameters can then be classified as follows:
502 \begin{itemize}
503 \item
504 also a configuration parameter:
505 \ps{PageSize},
506 \ps{MediaClass},
507 % Explicitly defined to be an "arbitrary string representing attributes
508 % of the medium that may require special action by the output device"
509 % (PLR3 p. 402).
510 \item
511 not a configuration parameter:
512 \ps{InsertSheet},
513 \ps{MediaType},
514 \item
515 possibly a configuration parameter:
516 \ps{MediaColor} (probably not),
517 \ps{MediaWeight} (probably yes).
518 \end{itemize}
519
520 If a particular selection parameter is also a configuration parameter,
521 it must be set correctly for the medium chosen by the media selection process.
522 Assuming the correct value to be non-null and disregarding the
523 \ps{PageSize} parameter,
524 this is the case if and only if the parameter is correctly specified in the
525 \ps{InputAttributes} entry \emph{and\/} the documents requests the same value:
526 \begin{itemize}
527 \item
528 If the parameter is not specified in \ps{InputAttributes} and a match
529 results, the value in the page device dictionary will be \ps{null}.
530 \item
531 If the parameter is not correctly specified in \ps{InputAttributes},
532 the parameter's value in the page device dictionary will either be this
533 incorrect value or \ps{null}.
534 \item
535 If the parameter is correctly specified in \ps{InputAttributes},
536 the document requests a different value,
537 and a match results,
538 the value will also become \ps{null}.
539 \end{itemize}
540 The \ps{PageSize} parameter is different because instead of being set to
541 \ps{null} when the request cannot be satisfied it is set to the value
542 belonging to the \ps{InputAttributes} entry chosen.
543 In my opinion this behaviour would have been desirable for all
544 configuration parameters considered for selection.
545
546 I wish to draw two conclusions from this dicussion:
547 \begin{itemize}
548 \item
549 If the output device uses a selection parameter for configuration,
550 the interpreter should be configured such that the \ps{InputAttributes}
551 entries contain the correct values
552 and the \ps{Policies} dictionary should not permit the request to be
553 ignored.
554 \item
555 As already mentioned in a footnote,
556 \gs's behaviour with respect to non-matching parameters is not
557 currently~[gs~6.01] PostScript-conforming,
558 hence the preceding discussion does not really apply.
559 However, I am not aware of any statement in the documentation that this
560 was a deliberate implementation decision,
561 hence this behaviour cannot be relied upon.
562
563 Therefore I still conclude that
564 a \gs\ device should not use selection parameters for configuration
565 unless the driver can sense these media properties.
566
567 The reason is that the typical execution environment for \gs\ is a
568 single-user PC with a dedicated printer completely controlled by the user.
569 If this user inserts media with properties the driver needs to know,
570 it is unreasonable to require the parameter to be set in two places.
571 \end{itemize}
572
573 %------------------------------------------------------------------------------
574
575 \subsubsection{User Interaction via \ps{Policies}}
576
577 The user may set a policy code of~2 in the \ps{Policies} dictionary.
578 This indicates that a mismatch should result in some kind of device-specific
579 interaction with an external entity,
580 for example asking a human operator to insert media of the size requested and
581 waiting for confirmation.
582 This is not supported by \gs\ and results in a
583 \ps{configurationerror}~[gs~5.50] just as for a policy value of~0.
584 Should it be implemented one day, this will hopefully be independent of
585 the \gs\ device in question.
586 You should therefore ignore this feature.
587
588 %------------------------------------------------------------------------------
589
590 \subsubsection{Automatic Switch to Manual Feed}
591
592 A user might wish to tell the interpreter something like the following:
593 ``I have put A4 sheets into the input tray where they can be fed automatically,
594 but I am prepared to feed certain other sizes manually''.
595 The second part of this statement cannot be easily expressed in
596 \ps{InputAttributes} for two reasons.
597
598 The first and more important one is that you cannot request additional actions
599 (like setting \ps{ManualFeed} to \ps{true}) to be performed automatically if a
600 particular media source is selected and certain conditions are met.\footnote{%
601 One might consider (mis)using the \ps{Install} procedure for this purpose
602 provided it can determine which source has been selected.
603 However, there is no standard way for that,
604 and in addition PLR3 does not say whether it is permitted for
605 \ps{Install} to call \ps{setpagedevice}.
606 This is a problem because the latter calls \ps{Install} again.}
607 The only choices I see are
608 to make manual feed implicit in the media source by convention or
609 to provoke a \ps{PageSize} mismatch.
610 The first possibility must be supported by the driver,
611 the second requires the user to choose a \ps{PageSize} recovery policy of~2,
612 possibly combined with a \ps{PolicyReport} procedure setting \ps{ManualFeed} to
613 \ps{true}.
614
615 The second problem arises if ``certain other sizes'' refers to a list or range
616 of page sizes.
617 Lists can only be supported by distributing the individual sizes over several
618 media sources one at a time,
619 ranges are permissible with \gs~[gs~5.50] but not in standard PostScript.
620 If you want to make it possible for the user to specify lists in this
621 situation,
622 you must reserve an unlimited set of position numbers for this
623 special purpose.
624
625 One possible solution to both problems is therefore to let the driver interpret
626 all negative position numbers as meaning ``manual feed''.
627
628 In deciding how to implement your driver you should, however,
629 not forget that \ps{InputAttributes} only states which media are currently
630 available according to the user.
631 The driver still has to check whether the requested size is acceptable to the
632 printer.
633 This reduces the usefulness of specifying lists or ranges for manual feed.
634 In fact, if one uses \gs's ability to accept a range for \ps{PageSize},
635 a single position number with an implied manual feed is probably sufficient.
636 This is definitely the case if the device supports custom page sizes in such a
637 way that the total set of supported sizes can be expressed as a single
638 connected range of media extensions.
639
640 %==============================================================================
641
642 \subsection{Setting up Default User Space} \label{PsUserSpace}
643
644 The PostScript language asserts that default user space is set up in a certain
645 manner in relation to the medium printed on.
646 PostScript programs may rely on this relationship.
647 Most printers, however, can neither control nor react to how the media have
648 been put into their input trays.
649 In what follows I assume that this is the case for the printer in question.
650
651 Concerning the extension (height and width irrespective of orientation) of
652 media,
653 the \ps{PageSize} entry in the \ps{InputAttributes} dictionary is available for
654 telling a PostScript interpreter about the media present in an input tray.
655 This is, however, not sufficient for the interpreter to correctly set up
656 default user space:
657 even assuming a sheet to be unmarked and to have indistinguishable sides
658 this merely reduces the 8~possibilities of putting it into the input tray to
659 two inequivalent ways (unless it is a square sheet).
660 They are usually described by reference to the feeding direction as
661 ``short edge first'' and ``long edge first''.
662 Both lead to equivalent \ps{PageSize} entries in \ps{InputAttributes}.
663
664 The implementation of a PostScript output device for such a printer must
665 therefore be accompanied by rules stating what the ``right'' ways for putting
666 media into input trays are.
667 In order to prevent printing beyond the edges of a sheet,
668 the minimum is to state whether the interpreter assumes media will be fed short
669 edge first or long edge first.
670 A more detailed rule would add a description of default user space on
671 a sheet lying in the input tray.
672 This enables the user in addition to reliably position the output with respect
673 to matter already on the medium (e.g., a watermark).
674
675 \begin{note}
676 At least three versions of the {\it PostScript Language Reference
677 Supplement\/}~\cite{PSSupplement2017,PSSupplement3010,PSSupplement3011}
678 impose special rules
679 for the location of default user space when printing on envelopes.
680 In my opinion these rules are undesirable because they require
681 \textit{the program generating a PostScript page\/} to know
682 whether printing will be done on envelopes or on ordinary paper
683 of the same size.
684 As this has nothing to do with the layout of text within the page,
685 the program should not need to know this.
686 But even worse, the rules are chosen such that if one requests landscape
687 orientation (which is usually desired for envelopes) the standard rule
688 governing the behaviour of \ps{setpagedevice} (rotate by $+90^\circ$)
689 actually produces output standing on its head when applied to an envelope
690 having the flap along its longer edge!
691
692 If, on the other hand, a printer has particular requirements for feeding
693 envelopes and this does not produce the desired result when keeping to
694 PostScript's default rules,
695 the output device should deal with this problem, possibly triggered by a
696 page device parameter or by imposing the rule that certain page sizes are
697 always interpreted as envelopes.
698
699 My advice is therefore to ignore these rules,
700 but you should form your own conclusion based on your printer's requirements.
701 \end{note}
702
703 All this applies only to a default state for default user space.
704 This state is characterized by requesting a page in portrait orientation
705 ($\hbox{width} < \hbox{height}$)%
706 \footnote{It is also assumed that the size requested is available,
707 otherwise the media selection process might influence the location and
708 scale of default user space (\ps{PageSize} recovery policies~3 and~4).}
709 and omitting requests for any of the page device parameters
710 \ps{LeadingEdge}, \ps{Orientation}, \ps{ImageShift},
711 \ps{PageOffset}, \ps{Margins}, \ps{Tumble}, \ps{MirrorPrint},
712 and possibly others.
713 The resulting structure on the sheet is sometimes called the
714 \d{canonical page in portrait orientation},
715 but you should think of this situation as the set of conditions
716 under which the statement about the position of default user space
717 on a sheet in the input tray is valid.
718
719 Most of the parameters just mentioned are defined in terms of their effect
720 with respect to this default orientation.
721 For example,
722 on receiving a \ps{PageSize} request for landscape orientation the interpreter
723 must rotate default user space 90~degrees counterclockwise with respect to
724 its position for portrait orientation and shift the origin into the
725 new lower left corner.
726
727 The parameter \ps{LeadingEdge} makes it possible for the user to tell the
728 interpreter that a sheet has been put into the input tray in a non-standard
729 way.
730 Note that different devices can differ in which of the 4~possibilities is the
731 default:
732 for an interpreter assuming a short-edge orientation in the input tray it will
733 be either~0 or~2,
734 while a long-edge-oriented one will have~1 or~3 as its default.
735 This argument can be reversed:
736 specifying which of these values is the default assumed by the interpreter
737 together with the information which side of the sheet will be printed on
738 uniquely selects one of the 8 possible orientations in the input tray as the
739 ``right'' one for the default situation.
740
741 The parameter \ps{Orientation} should only be supported by devices
742 with media of continuously variable page sizes (printing to roll-fed media,
743 screen displays or file formats):
744 the values~1 and~3 cannot be supported on cut-sheet media,
745 and the user can achieve the effect of~2 by choosing a \ps{LeadingEdge} value
746 differing by~2 from its default.
747
748 You must decide which of these parameters will be supported by your driver.
749 Note that some are automatically available for every \gs\ device.
750
751 %==============================================================================
752
753 \subsection{Device Coordinates}
754
755 The rules of PostScript about the relative positioning of default user space
756 and the medium are intended to ensure that a PostScript program need not know
757 about the device coordinate system.
758 This information is, however, still accessible to the program:
759 the operator \ps{defaultmatrix}, for example,
760 returns the default transformation matrix for the device,
761 and with this information a PostScript program can unambiguously determine the
762 position of the device coordinate system with respect to default user space.
763 Hence the following discussion indeed belongs under the heading of
764 PostScript-visible properties of the output device.
765
766 When writing your driver you must choose a device coordinate system.
767 This is no problem; just do it.
768 However, I am not aware of any statement in PLR3 which states that the
769 device coordinate system is a fixed property of the output device.
770 ``Fixed'' in this context means ``fixed with respect to the feeding direction''
771 or equivalently ``fixed with respect to the default of default user space''.
772 If you therefore wish to switch your device coordinate system if the user
773 requests landscape orientation or on any other occasion the user executes
774 \ps{setpagedevice},
775 this is perfectly legitimate.
776 You might even do it in such a manner that \ps{defaultmatrix} returns the
777 same value under all circumstances.
778 This freedom is actually desirable,
779 because it means that you can choose whatever convention for device coordinates
780 is the simplest for you to implement depending on the current set of
781 page device parameters.
782
783 However, if you look at the description of the \ps{PageOffset} and \ps{Margins}
784 parameters you'll find statements that for \ps{PageOffset}
785 ``the repositioning is typically accomplished by altering the current
786 transformation matrix, although on some devices it may instead be accomplished
787 by device-dependent means that are independent of the graphics state
788 (in particular, of the CTM)''~\cite[page 415]{PostScript3} and that
789 for \ps{Margins} the latter case is the typical one.
790 (Incidentally, as both parameters have to be specified with respect to the
791 direction of the axes of the device coordinate system,
792 your driver's documentation should tell the user where these axes point to.)
793 If your device coordinates are fixed with respect to the default default user
794 space,
795 you will have to modify the default transformation matrix,
796 and conversely if you wish the influence of such parameters not to be visible
797 in the CTM you must shift your device coordinates.
798
799 Concerning \ps{PageOffset} and \ps{Margins} these discussions are, however,
800 slightly academic because \gs\ implements these parameters for all devices
801 and does it via modifications of the default transformation matrix
802 in both cases~[gs~5.50].
803 At least for \ps{Margins} you can easily override this behaviour but I wouldn't.
804
805 %==============================================================================
806
807 \subsection{Other Standard Page Device Parameters Describing Device
808 Capabilities}
809
810 The following page device parameters defined in PLR3 refer to special
811 hardware functionality:
812 \begin{quote}
813 \ps{InsertSheet}, \ps{ManualFeed}, \ps{TraySwitch},
814 various parameters for roll-fed media,
815 \ps{Duplex},
816 \ps{Collate}, \ps{Jog}, \ps{OutputFaceUp},
817 \ps{MaxSeparations}, \ps{SeparationColorNames}.
818 \end{quote}
819 Absence of one of these parameters indicates that the feature is not
820 supported by the device.
821 The converse is not true.
822 You will have to decide which of these features you can support.
823
824 In addition, there exist also position numbers for media destinations
825 (keys in \ps{OutputAttributes}),
826 similar to the numbers for media sources.
827 If your printer has several output destinations your driver should
828 support them as well.
829
830 %==============================================================================
831
832 \subsection{Non-Standard Page Device Parameters}
833
834 If your driver is going to offer functionality which cannot be expressed in
835 terms of standard page device parameters,
836 you will have to define new ones.
837
838 You should take some care not to choose parameter names which can collide with
839 other definitions.
840 At the least you should check the current edition of the
841 {\it PostScript Language Reference Supplement\/}~\cite{PSSupplement3011}
842 in order to find out whether there is already a semi-standard parameter
843 for this functionality or one having the intended name but another meaning.
844
845 %******************************************************************************
846
847 \section{General Properties of a \Gs\ Device}
848
849 Unless there is an explicit reference to a different version,
850 everything which follows in this and subsequent sections is based on
851 \gs\ version 5.50.
852
853 %==============================================================================
854
855 \subsection{Definitions}
856
857 A \gs\ device driver defines one or more \d{ghostscript devices}.
858 A ghostscript device is identified by its name (1~to~8 letters, digits or
859 underscores, starting with a letter~\cite{Drivers5.50}\footnote{%
860 These restrictions are probably the combined result of restrictions from
861 the C~language and from some file systems.
862 Effectively, this means that you can ignore at least the length restriction
863 on almost all platforms.}) and characterized by a
864 C~variable which must be called {\tt gs\_\textit{name}\_device}.
865 % No italic correction for "name" here; it looks worse.
866 This is the \d{device structure instance},
867 its type is the \d{device structure}.
868 The device structure instance is a prototype for the data structure
869 (\d{device instance}, sometimes also called \d{driver instance})
870 which is actually used when a device is installed in the graphics state.
871
872 \ifdraft
873 ??? Forwarding device, band device,
874 life cycle (at which point in a multi-function open call is the device open?
875 Will partially opened devices be closed?)
876 \fi
877
878 %==============================================================================
879
880 \subsection{Relation to Output Devices}
881
882 There is a one-to-one correspondence between ghostscript devices and
883 PostScript output devices supported by \gs.
884
885 Technically, this can be inconvenient if your driver implements lots of
886 different output devices and you do not wish to clutter \gs's device list
887 with all these names.
888 In that case you should introduce sub-devices based on particular parameter
889 values.
890 My \textit{hpdj\/} driver for example uses \texttt{hpdj} as the device name but
891 in addition selects a particular printer model with the
892 page device parameter \ps{Model}.
893 As the latter determines which process colour models and page sizes are
894 supported by the driver,
895 this parameter in fact distinguishes between output devices within one
896 ghostscript device.
897
898 If you choose to implement such sub-devices you should try to simulate the
899 behaviour of \ps{setpagedevice} for \ps{OutputDevice}
900 (initialization with default values)
901 whenever the output device is changed.
902 Your \prog{put\_params} implementation should therefore check for the
903 sub-device-changing parameters first.
904 However, you should only reset those parameters which the user can override.
905 %??? This does not apply to the resolution when set from the
906 % command line [gs~6.01].
907
908 %==============================================================================
909
910 \subsection{Device Structure}
911
912 \ifdraft
913 ??? Dynamic memory
914 \fi
915
916 %------------------------------------------------------------------------------
917
918 \subsubsection{Device Procedures}
919
920 Among the variables in the device structure are several dealing with functions:
921 \begin{itemize}
922 \item The \prog{static\_procs} variable points to a static table of
923 type \prog{gx\_device\_procs} containing pointers to functions.
924 It is common to all device instances of the same type.
925 \item \prog{page\_procs} is of type \prog{gx\_page\_device\_procs}.
926 This is a table of pointers to functions peculiar to page devices.
927 \item The \d{device procedure table} \prog{procs} is also of
928 type \prog{gx\_device\_procs}
929 (but not a pointer to that type as \prog{static\_procs} is).
930 The entries in this table (or the functions pointed to) are the
931 \d{device procedures}.
932 \end{itemize}
933
934 The function \prog{gx\_device\_set\_procs()} checks whether
935 \prog{static\_procs} is \prog{NULL} or not. % gsdevice.c
936 If it is not,
937 the table pointed to is copied over \prog{procs} and
938 \prog{static\_procs} is set to \prog{NULL}.
939
940 More important, however, is that almost all \prog{NULL} entries in the
941 device procedure table are overwritten with default values.
942 This is done by \prog{gx\_device\_fill\_in\_procs()}.
943 It first calls \prog{gx\_device\_set\_procs()}
944 and then replaces null entries for all device procedures except
945 \prog{fill\_rectangle}~[gs~5.50].\footnote{
946 The entries for \prog{image\_data} and \prog{end\_image} are always
947 overwritten with non-null default values
948 even if they are non-null to begin with.}
949
950 The list of device procedures is frequently growing.
951 In \gs\ version~5.50 this table has 43~entries.
952 Check the definition of \prog{gx\_device\_proc\_struct()} in \file{gxdevcli.h}
953 for the current list.
954
955 A device procedure should be called by using the \prog{dev\_proc()} macro:
956 it takes a pointer to a device instance and the name of a device
957 procedure table field as arguments and is expanded into the entry in the
958 device procedure table.
959
960 While entries in \prog{*static\_procs} may not change,
961 the device procedures in \prog{procs} can change during a device's lifetime.
962 The macro \prog{set\_dev\_proc()} is intended for this purpose.
963 %???
964 %The \textit{prn\/} device, for example,
965 %sets a number of device procedures for rendering when the device is opened
966 %(\prog{gdev\_prn_\allocate()}) and restores the old values when the device is
967 %closed (\prog{gdev\_prn\_tear\_down()}).
968
969 %==============================================================================
970
971 \subsection{\Gs\ Devices in PostScript}
972
973 \subsubsection{Type, \Gs\ Initialization and State}
974
975 \Gs\ introduces a new basic type \ps{devicetype} for representing ghostscript
976 device (structure) instances.
977 Instances of this type are composite objects. % See 'ref_type' in iref.h.
978
979 % See gs_init.ps.
980 On initialization,
981 \gs\ repeatedly executes the \ps{.getdevice} operator to obtain
982 all known device structure instances.
983 It then creates a dictionary \ps{devicedict} in \ps{systemdict} containing
984 for each device an array of length~2;
985 the first entry is the device structure instance, % from 'gx_device_list[]'
986 the second is \ps{null}\footnote{
987 Actually, the PostScript initialization code sets the second entry to be
988 \ps{null} if the device is not writable and
989 makes it a copy of the first if it is.
990 However, the implementation of \ps{.getdevice} (\prog{zgetdevice()})
991 always returns a read-only object~[gs~5.50]. % See zdevice.c.
992 % Also tested with gs 5.50 and gs 5.10 binaries.
993 }.
994 Entries in \ps{devicedict} have the string returned by \ps{.devicename} as a
995 key (\prog{dname} field in the device structure). % See zdevice.c.
996
997 The device instance current in the graphics state
998 can be obtained with the operator
999 \ps{currentdevice} implemented in \prog{zcurrentdevice()}.
1000
1001 %------------------------------------------------------------------------------
1002
1003 \subsubsection{Switching Devices}
1004
1005 The procedure \ps{selectdevice} calls first \ps{finddevice} and then
1006 \ps{setdevice}. % Actually, it also calls \ps{.setdefaultscreen}.
1007
1008 The procedure \ps{finddevice} looks into \ps{devicedict} to find a device by
1009 its name and checks the second entry in the array.
1010 If it is \ps{null},
1011 the entry is replaced by the result of \ps{copydevice} applied to the first
1012 entry.
1013 In all cases, this second entry is returned.
1014
1015 \ifdraft
1016 ??? TEST: What happens on multiple selection?
1017 \fi
1018
1019 \ps{copydevice} is a \gs\ operator implemented in \prog{zcopydevice()}.
1020 % See zdevice.c.
1021 The latter calls \prog{gs\_copydevice()} % gsdevice.c
1022 which allocates storage for a new device instance,
1023 calls \prog{gx\_device\_init()} and sets the device variable \prog{is\_open}
1024 to \prog{false}.
1025 The function \prog{gx\_device\_init()} copies the source device instance
1026 storage into the new instance with the exception of the \prog{memory} variable.
1027
1028 The procedure \ps{setdevice} calls the operator \ps{.setdevice} implemented
1029 in \prog{zsetdevice()}. % zdevice.c
1030 This function calls \prog{gs\_setdevice\_no\_erase()} and clears the
1031 underlying page device. % macro clear_pagedevice()
1032
1033 \ifdraft
1034 ??? What happens with the old device?
1035 \fi
1036
1037 The function \prog{gs\_setdevice\_no\_erase()} first checks whether the device
1038 is already open.
1039 If not, it calls \prog{gx\_device\_fill\_in\_procs()} and the
1040 \prog{open\_device} device procedure and finally it sets \prog{is\_open = true}.
1041 Then it calls \prog{gs\_setdevice\_no\_init()}, \prog{gs\_initmatrix()} and
1042 \prog{gs\_initclip()}.
1043
1044 \prog{gs\_setdevice\_no\_init()} sets the colour mapping procedures
1045 in the graphics state from the device's colour mapping procedures
1046 (calling \prog{gx\_set\_cmap\_procs()}).
1047
1048 %******************************************************************************
1049
1050 \section{\Gs\ Device Parameters}
1051
1052 The variables in a device instance determine the values of its
1053 \d{device parameters}.
1054 These parameters are a subset of the
1055 page device parameters of the corresponding PostScript output device.
1056 The connection between the two and the way in which the device parameters may
1057 be accessed is an area where \gs's documentation is particularly reticent.
1058
1059 %==============================================================================
1060
1061 \subsection{Parameter Dictionaries}
1062
1063 A device parameter is identified by a string, its name.
1064 If a device supports a particular parameter,
1065 it associates a typed value with this name.
1066 \Gs\ has an internal API for dealing with collections of such name-value pairs.
1067
1068 %------------------------------------------------------------------------------
1069
1070 \subsubsection{Types for Parameters}
1071
1072 The name of a parameter is of type \prog{gs\_param\_name}
1073 which is defined as \prog{const char~*}.
1074
1075 Each parameter has a type associated with it which is stored in an instance
1076 of type \prog{gs\_param\_type}:
1077 \begin{program} % gsparam.h
1078 typedef enum \lb
1079 \ /* Scalar */
1080 \ gs_param_type_null, gs_param_type_bool, gs_param_type_int,
1081 \ gs_param_type_long, gs_param_type_float,
1082 \ /* Homogenous collection */
1083 \ gs_param_type_string, gs_param_type_name,
1084 \ gs_param_type_int_array, gs_param_type_float_array,
1085 \ gs_param_type_string_array, gs_param_type_name_array,
1086 \ /* Heterogenous collection */
1087 \ gs_param_type_dict, gs_param_type_dict_int_keys, gs_param_type_array
1088 \rb\ gs_param_type;
1089 \end{program}
1090 In addition, there is a macro \prog{gs\_param\_type\_any} which resolves to
1091 an expression of this type and which can be used to denote any type.
1092
1093 \ifdraft
1094 ???
1095 What is the concept of ``type'' here? PostScript, C, a mixture of both?
1096 Add description of collections.
1097 \fi
1098
1099 The type \prog{gs\_param\_value} is used to store values of parameters.
1100 It is a \prog{union} of the following C~types:
1101 \begin{quote}
1102 \prog{bool}, \prog{int}, \prog{long}, \prog{float},
1103 \prog{gs\_param\_string}, % twice
1104 \prog{gs\_param\_int\_array}, \prog{gs\_param\_float\_array},
1105 \prog{gs\_param\_string\_array}, % twice
1106 \prog{gs\_param\_collection}
1107 \end{quote}
1108
1109 Finally, the type \prog{gs\_param\_typed\_value} combines a type description
1110 with a value:
1111 \begin{program} % gsparam.h
1112 typedef struct gs_param_typed_value_s \lb
1113 \ gs_param_value value;
1114 \ gs_param_type type;
1115 \rb\ gs_param_typed_value;
1116 \end{program}
1117
1118 %------------------------------------------------------------------------------
1119
1120 \subsubsection{Type and Operations for Parameter Collections}
1121
1122 A \d{parameter dictionary} represents an unordered collection of
1123 instances of type \prog{gs\_param\_typed\_value}
1124 and is of the C~type \prog{gs\_param\_list}
1125 % (also known as \prog{struct gs\_param\_list\_s})
1126 or of a type having the same initial storage layout as this type.
1127 This is the same convention as used to simulate type inheritance for
1128 device structures:
1129 \prog{gs\_param\_list} should be
1130 considered as an abstract base class defining access routines for
1131 parameter dictionaries
1132 while its derived types provide implementations for the routines and storage
1133 for the parameters.
1134 This abstract interface is declared in \file{gsparam.h}.
1135
1136 Concrete implementations of this abstract interface are the following types:
1137 \begin{quote}\begin{flushleft}
1138 \prog{gs\_c\_param\_list}, % gsparam.h
1139 \prog{dict\_param\_list}, % iparam.h
1140 \prog{array\_param\_list}, % iparam.h
1141 \prog{stack\_param\_list}, % iparam.h
1142 \prog{printer\_param\_list\_t} % gdevpsdf.c
1143 \end{flushleft}\end{quote}
1144 The only one of interest to implementors of device drivers is
1145 \prog{stack\_param\_list} because it is used to represent objects on the
1146 operand stack.
1147 \ifdraft
1148 ??? More about it later?
1149 \fi
1150
1151 There exists a macro \prog{gs\_param\_list\_common} to obtain the list of
1152 declarations common to all parameter dictionary types.
1153 It resolves to:
1154 \begin{program}
1155 const gs_param_list_procs *procs;
1156 gs_memory_t *memory; % Actually, the semicolon is not part of the macro.
1157 \end{program}
1158 The \prog{procs} member points to a table of pointers to the
1159 implementation's access methods.
1160 This table contains the following members\footnote{
1161 I am not aware of any official description for the semantics or behaviour of
1162 these functions at the level of abstraction for \prog{gs\_param\_list};
1163 the comments in \file{gsparam.h} are insufficient for this purpose.
1164 These descriptions are therefore heavily based on the actual implementation
1165 for \prog{iparam\_list} which is an abstract type between
1166 \prog{gs\_param\_list} and a number of concrete implementations
1167 including \prog{stack\_param\_list}.
1168 }:
1169 \begin{itemize}
1170 \item \prog{int (*xmit\_typed)(gs\_param\_list *, gs\_param\_name,
1171 gs\_param\_typed\_value *);}
1172
1173 This routine is used to ``transmit'' a value.
1174 This means either to put a value into the dictionary (writing)
1175 or to extract it (reading).
1176 Which direction is chosen depends on the function pointed to,
1177 i.e., unless you modify this pointer you can either read or write the
1178 parameter dictionary but not both.
1179
1180 A reading implementation of \prog{xmit\_typed} returns zero if the
1181 parameter value was successfully extracted,
1182 one if the parameter does not exist,
1183 and a negative value on error.
1184 A writing implementation returns zero or one on success and
1185 a negative value on error.
1186
1187 The reading implementation of \prog{xmit\_typed} for
1188 \prog{stack\_param\_list} % Actually, for 'iparam_list'.
1189 keeps track of which parameter was accessed and what the result was.
1190 % See comments in iparam.h and the 'results' field in 'iparam_list'
1191 % [gs 5.50].
1192
1193 \ifdraft
1194 ??? Discuss selective writing.
1195 \fi
1196 \item \prog{int (*signal\_error)(gs\_param\_list *, gs\_param\_name, int);}
1197
1198 This routine is used to associate an error code (the last argument) with
1199 the parameter designated.
1200 A parameter dictionary can for example store this code in the list together
1201 with the parameter's value.
1202 The function must \emph{never\/} be called for a
1203 non-existent parameter [gs~5.50].
1204 % Looking at iparam.c, this should give a core.
1205
1206 This routine is in particular intended to be used by functions extracting
1207 values from a parameter dictionary and discovering that
1208 the type is incorrect or the value is outside the permissible range.
1209 \item \prog{int (*commit)(gs\_param\_list *);}
1210
1211 This function is used to perform some final processing after extracting
1212 all interesting values from a parameter dictionary.
1213 It can for example check that all the parameters present have been
1214 extracted,
1215 i.e., that there are no unknown parameters left in the dictionary.
1216 % ref_param_read_commit() does this if it has been requested.
1217 % If there are undefined parameters, their 'result' codes are set to
1218 % 'e_undefined'.
1219
1220 The routine returns zero on success and a negative value on error.
1221 \item \prog{int (*next\_key)(gs\_param\_list *, gs\_param\_enumerator\_t *,
1222 gs\_param\_key\_t *);}
1223
1224 This routine is useful for debugging because it can be used to iterate over
1225 all entries in a parameter dictionary.
1226 The second argument points to an iterator which stores the last position
1227 accessed;
1228 it must have been initialized by calling
1229 \prog{void param\_init\_enumerator(gs\_param\_enumerator\_t *)} before
1230 the first call to this function.
1231 The third argument
1232 (the type is an alias for \prog{gs\_param\_string}) % gs 6.50
1233 will receive the name of the next parameter if there is
1234 one (return code is zero),
1235 otherwise the return code is~1 (no more parameters) or negative (error).
1236 \item In addition, there are the members
1237 \prog{begin\_xmit\_collection},
1238 \prog{end\_xmit\_collection},
1239 \prog{request},
1240 \prog{requested},
1241 and
1242 \prog{get\_policy}.
1243 \end{itemize}
1244
1245 %------------------------------------------------------------------------------
1246
1247 \subsubsection{Interface for Drivers}
1248
1249 The methods in parameter dictionaries are not particularly interesting
1250 from the point of view of writing a driver,
1251 but there are some functions on top of this interface which are.
1252
1253
1254 \paragraph{Reading.}
1255
1256 For reading a value from a parameter dictionary, the basic routine is:
1257 \begin{program}
1258 int param_read_requested_typed(gs_param_list *, gs_param_name,
1259 \ gs_param_typed_value *);
1260 \end{program}
1261 This function expects a requested type to have been filled into the
1262 \prog{type} field of the entry pointed to be the third argument.
1263 It calls the \prog{xmit\_typed} function.
1264 If the latter returns a non-zero exit code, this code is returned.
1265 Otherwise the function checks for a mismatch between the requested and
1266 the actual type
1267 and tries to convert between the two if necessary and possible.
1268 For example, if the actual parameter is of type \prog{gs\_param\_type\_int}
1269 its value can also be extracted as \prog{gs\_param\_type\_long}
1270 or \prog{gs\_param\_type\_float}. % See param_coerce_typed().
1271 If the types do not match,
1272 a value of \prog{gs\_error\_typecheck} is returned.
1273 Otherwise the result is returned via the \prog{value} field in the
1274 third argument.
1275
1276 There is a macro \prog{param\_read\_typed()} which effectively calls
1277 \prog{param\_read\_requested\_typed()} with the value
1278 \prog{gs\_param\_type\_any} and
1279 can be used to fetch a parameter value irrespective of its type.
1280 The \prog{type} field in the third argument will contain the actual type.
1281
1282 Implemented on top of \prog{param\_read\_requested\_typed()} there are several
1283 functions \prog{param\_read\_\textit{type}()} which request and return a value
1284 of a specific type.
1285 For an \prog{int}, the routine is:
1286 \begin{program}
1287 int param_read_int(gs_param_list *, gs_param_name, int *);
1288 \end{program}
1289 These functions should be used in preference to the others.
1290
1291
1292 \paragraph{Writing.}
1293
1294 For writing a parameter there is a macro \prog{param\_write\_typed()} which
1295 should be called as if it were the following function:
1296 \begin{program}
1297 int param_write_typed(gs_param_list *, gs_param_name,
1298 \ gs_param_typed_value *);
1299 \end{program}
1300 The macro is mapped to a call to \prog{xmit\_typed} and returns its return code.
1301
1302 Again there is a layer of type-specific functions on top of this basic
1303 interface.
1304 For an \prog{int}, the routine is:
1305 \begin{program}
1306 int param_write_int(gs_param_list *, gs_param_name, const int *);
1307 \end{program}
1308 These functions should be preferred.
1309
1310
1311 \paragraph{Other Functions.}
1312
1313 The macros \prog{param\_signal\_error()}, \prog{param\_commit()} and
1314 \prog{param\_get\_next\_key()}
1315 can be called as if they were the following functions:
1316 \begin{program}
1317 int param_signal_error(gs_param_list *, gs_param_name, int);
1318 int param_commit(gs_param_list *);
1319 int param_get_next_key(gs_param_list *, gs_param_enumerator_t *,
1320 \ gs_param_key_t *);
1321 \end{program}
1322 They call the dictionary's \prog{signal\_error}, \prog{commit} and
1323 \prog{next\_key} routines, respectively.
1324
1325 %==============================================================================
1326
1327
1328 \subsection{The Parameter Device Procedures}
1329
1330 To be described. % ???
1331
1332 %==============================================================================
1333
1334 \subsection{Default Parameters}
1335
1336 \subsubsection{All Devices}
1337
1338 The function \prog{gx\_default\_get\_params()} writes the following
1339 parameters into the parameter list it received as an argument~[gs~5.50]:
1340 % See gsdparam.c and gxdevcli.h.
1341 \begin{quote} % ??? Find a better solution.
1342 \normalUS
1343 \def\a{$^*$} % asterisk
1344 \halign{\quad\prog{#}\hfil\quad& \prog{#}\hfil\quad&
1345 \vtop{\raggedright\hsize=5cm #\strut}\hfil\cr
1346 % ??? Improve baseline distance.
1347 \omit\quad Name\hfil & \omit Type and device variable or value\hfil &
1348 Remarks\cr
1349 \noalign{\smallskip\nointerlineskip
1350 \hbox{\dimen0=\hsize \advance\dimen0 by -2em
1351 \quad \vrule depth 0.4pt height 0pt width \dimen0}
1352 \smallskip}
1353 .HWMargins\a& float HWMargins[4]&\cr
1354 .IgnoreNumCopies\a& bool IgnoreNumCopies&\cr
1355 .MarginsHWResolution& float MarginsHWResolution[2]&\cr
1356 .MediaSize\a& float MediaSize[2]&\cr
1357 BitsPerPixel& int color_info.depth&\cr
1358 BlueValues& (int)(color_info.max_color + 1)&
1359 only set if \prog{color\_info.num\_components} is larger than 1.\cr
1360 ColorValues& (long)(1L << color_info.depth)&
1361 only set if \prog{color\_info.num\_components} is larger than 1.\cr
1362 Colors& int color_info.num_components& \cr
1363 GraphicsAlphaBits& int&
1364 a value returned by the device procedure \prog{get_alpha_bits}\cr
1365 GrayValues& (int)(color_info.max_gray + 1)&\cr
1366 GreenValues& (int)(color_info.max_color + 1)&
1367 only set if \prog{color\_info.num\_components} is larger than 1.\cr
1368 HWColorMap& & returned as a string\cr % ???
1369 HWResolution\a& float HWResolution[2]& \cr
1370 HWSize\a& float [2]&
1371 initialized with \prog{width} and \prog{height} (in this order)\cr
1372 ImagingBBox\a& \textrm{null or} float ImagingBBox[4]&
1373 the type depends on \prog{bool ImagingBBox_set}\cr
1374 Margins\a& float Margins[2]& \cr
1375 Name& const char *dname& treated as a string\cr
1376 NumCopies\a& \textrm{null or} int NumCopies&
1377 only read or written if \prog{NumCopies\_set} is not negative.
1378 The null value is returned if \prog{NumCopies\_set} is zero.\cr
1379 OutputDevice& const char *dname& treated as a name\cr
1380 PageCount& long PageCount& \cr
1381 PageSize\a& float MediaSize[2]&
1382 only set if \prog{PAGESIZE_IS_MEDIASIZE} was defined during
1383 compilation which it is~[gs~5.50].\cr
1384 ProcessColorModel& \vtop{\raggedright\hsize=5cm
1385 \textrm{a name derived from
1386 \prog{color\_info.num\_components},
1387 see section~\ref{NativeColourSpaces}}\strut}\hfil\cr
1388 RedValues& (int)(color_info.max_color + 1)&
1389 only set if \prog{color\_info.num\_components} is larger than 1.\cr
1390 TextAlphaBits& int&
1391 a value returned by the device procedure \prog{get_alpha_bits}\cr
1392 }
1393 \end{quote}
1394
1395 The function \prog{gx\_default\_put\_params()} reads the same parameters from
1396 its arguments list,
1397 but copies only some of them into the device instance.
1398 These writable parameters are marked with an asterisk in the preceding list.
1399 The others are accessed in order to check that they are defined at all,
1400 that they have the right type or that their value satisfies certain constraints.
1401 For example,
1402 \ps{PageCount} must be defined and
1403 be either \ps{null} or a \prog{long} value agreeing with the value present
1404 in the \prog{PageCount} field in the device instance.
1405
1406 In addition the default put procedure also accesses \prog{\%MediaSource} and
1407 \prog{\%MediaDestination} but only to check that these parameters have values
1408 of integer type.
1409
1410 Before \prog{gx\_default\_put\_params()} actually modifies any parameters it
1411 calls \prog{param\_commit()} for the parameter list after having called all
1412 the necessary routines for reading the known parameters
1413 into temporary variables.
1414 If the commit routine returns a negative value,
1415 processing terminates without making changes in the device structure.
1416
1417 %------------------------------------------------------------------------------
1418
1419 \subsubsection{The \textit{prn\/} Device}
1420
1421 The function \prog{gdev\_prn\_get\_params()} first calls
1422 \prog{gx\_default\_get\_params()} and then writes the following parameters
1423 into the parameter list it received as an argument:
1424 \begin{quote} % ??? Find a better solution.
1425 \normalUS
1426 \def\a{$^*$}
1427 \halign{\quad\prog{#}\hfil\quad& \prog{#}\hfil\quad&
1428 \vtop{\raggedright\hsize=5cm #\strut}\hfil\cr
1429 % ??? Improve baseline distance.
1430 \omit\quad Name\hfil & \omit Type and device variable or value\hfil &
1431 Remarks\cr
1432 \noalign{\smallskip\nointerlineskip
1433 \hbox{\dimen0=\hsize \advance\dimen0 by -2em
1434 \quad \vrule depth 0.4pt height 0pt width \dimen0}
1435 \smallskip}
1436 BandBufferSpace& long space_params.band.BandBufferSpace& \cr
1437 BandHeight& int space_params.band.BandHeight& \cr
1438 BandWidth& int space_params.band.BandWidth& \cr
1439 BufferSpace& long space_params.BufferSpace& \cr
1440 Duplex\a& \textrm{null or} bool Duplex&
1441 only read or written if \prog{Duplex\_set} is not negative.
1442 A null value is returned if \prog{Duplex\_set} is zero.\cr
1443 MaxBitmap& long space_params.MaxBitmap&\cr
1444 OpenOutputFile\a& bool OpenOutputFile&\cr
1445 OutputFile\a& char fname[]& treated as a string\cr
1446 ReopenPerPage\a& bool ReopenPerPage&\cr
1447 }
1448 \end{quote}
1449 The function \prog{gdev\_prn\_put\_params()} accesses the same parameters
1450 as \prog{gx\_default\_get\_params()}
1451 and finally calls \prog{gx\_default\_put\_params()}.
1452 Only those parameters marked with an asterisk, however,
1453 are usually copied into the device instance.
1454 The others will be copied only
1455 if the field \prog{space\_params.params\_\-are\_\-read\_\-only} is \prog{false}
1456 (then they must also satisfy some constraints),
1457 otherwise their values must agree with those in the device instance.
1458
1459 In addition the put function also accesses
1460 \prog{InputAttributes} and \prog{OutputAttributes}
1461 and checks that they are dictionaries if defined.
1462
1463 %==============================================================================
1464
1465 \subsection{The Basic Access Routines in PostScript}
1466
1467 A device's parameters can be read with \ps{getdeviceprops} and modified by
1468 \ps{putdeviceprops}~\cite{Language5.50}.
1469 The first is based on the operator \ps{.getdeviceparams},
1470 the second on \ps{.putdeviceparams}.
1471
1472 %------------------------------------------------------------------------------
1473
1474 \subsubsection{Reading}
1475
1476 The operator \ps{.getdeviceparams} accepts either a \ps{null} value or a
1477 dictionary of keys\footnote{Values are simply duplicates of the keys.}.
1478 In the second case, only the specified device parameters are fetched.
1479 The operator puts a mark object on the stack and on top of it the
1480 names and values of those parameters which it could find.
1481 If the caller requested a parameter which cannot be found
1482 that request will be ignored without indicating an error.
1483
1484 \ifdraft
1485 ??? CHECK
1486 \fi
1487
1488 This operator is implemented in \prog{zgetdeviceparams()} which calls
1489 \prog{zget\_device\_params()},
1490 a function introduced to reduce duplicate code.
1491 % See zdevice.c.
1492 This function first prepares an instance of type \prog{stack\_param\_list}
1493 by connecting it with the operand stack
1494 and then calls \prog{gs\_get\_device\_or\_hardware\_params()} for the device
1495 with this list.
1496
1497 \ifdraft
1498 ??? Discuss selection.
1499 \fi
1500
1501 The function \prog{gs\_get\_device\_or\_hardware\_params()} calls
1502 \prog{gx\_device\_set\_procs()},
1503 supplies default values for some device procedures if necessary,
1504 and finally passes the parameter list to the \prog{get\_params} procedure.
1505
1506 %------------------------------------------------------------------------------
1507
1508 \subsubsection{Writing}
1509
1510 The operator \ps{.putdeviceparams} is implemented in \prog{zputdeviceparams()}.
1511 Its behaviour with respect to unrecognized keys has to be requested as
1512 either to ignore them or to generate an \ps{undefined} error
1513 (as \ps{putdeviceprops} does).
1514
1515 The implementation first prepares an instance of type \prog{stack\_param\_list}
1516 and then calls \prog{gs\_put\-device\-params()} for the device
1517 with this list.
1518 If the return code is negative (error), the function returns.
1519 Otherwise, some special processing is done under certain circumstances
1520 and finally the macro \prog{clear\_\-page\-device()} is called for the graphics
1521 state.
1522
1523 \ifdraft
1524 ??? Add description of error processing for undefined values.
1525 \fi
1526
1527 The function \prog{gs\_putdeviceparams()} calls
1528 \prog{gx\_device\_set\_procs()},
1529 supplies default values for some device procedures if necessary,
1530 and then calls the \prog{put\_params} procedure with the parameter list.
1531 The return code from \prog{gs\_putdeviceparams()} is the code returned by the
1532 device procedure provided it is negative or the device was closed before the
1533 call or it is still open afterwards;
1534 otherwise (no error and the device was open before and is closed afterwards)
1535 the return code is always~1.
1536
1537 %==============================================================================
1538
1539 \subsection{Connection with Page Device Parameters}
1540
1541 %------------------------------------------------------------------------------
1542
1543 \subsubsection{The Implementation of \ps{currentpagedevice}}
1544
1545 The procedure \ps{currentpagedevice} first calls the operator
1546 \ps{.currentpagedevice} which is implemented in \prog{zcurrentpagedevice()}.
1547 If the current device is a page device or acts as a forwarding device
1548 for a page device,
1549 this function returns the dictionary parameter \prog{pagedevice} from
1550 \gs's graphics state.
1551
1552 If the dictionary returned is empty, \ps{currentpagedevice}
1553 creates a new dictionary from all
1554 parameters returned by \ps{.getdeviceparams} for the page device plus
1555 the following ``required attributes''~[gs~5.50]:
1556 \begin{quote}
1557 % See definition of .requiredattrs in gs_setpd.ps.
1558 \ps{PageOffset},
1559 \ps{InputAttributes},
1560 \ps{\%MediaSource},
1561 \ps{OutputAttributes},
1562 \ps{\%MediaDestination},
1563 \ps{Install},
1564 \ps{BeginPage},
1565 \ps{EndPage},
1566 \ps{Policies}.
1567 \end{quote}
1568 The default values for these parameters are overridden if \ps{.getdeviceparams}
1569 returns values for them.
1570 % Remark in gs_setpd.ps 5.50, line 199-200:
1571 % In case of duplicate keys, .dicttomark takes the entry
1572 % lower on the stack, so we can just append the defaults here.
1573 Before returning the resulting dictionary,
1574 \ps{currentpagedevice} also calls \ps{.setpagedevice} (\prog{zsetpagedevice()})
1575 which sets \prog{pagedevice} in the graphics state.
1576
1577 If, on the other hand, \ps{.currentpagedevice} returns a dictionary of non-zero
1578 length,
1579 \ps{currentpagedevice} creates and returns a new dictionary constructed from
1580 this and the current values for \ps{.MediaSize} and \ps{PageCount}.
1581 % Definition of .dynamicppkeys in gs_setpd.ps.
1582 If your driver modifies other device parameters except as requested through
1583 \ps{setpagedevice},
1584 these modifications will therefore not be visible in PostScript.
1585
1586 \ifdraft
1587 ??? Describe when the data are refreshed.
1588 \fi
1589
1590 %------------------------------------------------------------------------------
1591
1592 \subsubsection{The Implementation of \ps{setpagedevice}}
1593
1594 \ifdraft
1595 \Gs's implementation of \ps{setpagedevice} is fairly complex.
1596 This document lists only some of its properties,
1597 the reader should check the file \file{gs\_setpd.ps} for details.
1598
1599 ???
1600 \else
1601 To be described.
1602 \fi
1603
1604 %==============================================================================
1605
1606 \ifdraft
1607 \subsection{???}
1608
1609 CLI, overriding, multiple access, \prog{Duplex\_set} problem.
1610 \fi
1611
1612 %******************************************************************************
1613
1614 \section{Pages and Media}
1615
1616 \subsection{Device Coordinates} \label{DevCoord}
1617
1618 \Gs's documentation~\cite[section ``Coordinates and types'']{Drivers5.50}
1619 gives the impression that a driver can choose any location for the origin
1620 and orientation of its device coordinate system provided coordinate values
1621 fit into an \prog{int}.
1622 This is misleading.
1623
1624 Printer drivers based on the \textit{prn\/} device use an internal
1625 pixmap-generating device (a ``memory'' or a ``command list'' device)
1626 for scan conversion.
1627 The device coordinate system for this pixmap uses $x$-values in the range
1628 $[0, \hbox{width}-1]$ and $y$-values in the range $[0, \hbox{height}-1]$.
1629 % ??? Reference.
1630 The width and height values are set from the page size and the resolution
1631 (see \prog{gx\_device\_set\_width\_height()}) % gsdevice.c
1632 and are available in the device instance as the \prog{width} and \prog{height}
1633 fields.
1634 Anything falling outside this area is clipped. % Where? ???
1635 This clipping happens in addition to the clipping established at PostScript
1636 level.
1637 Therefore you should never put your device coordinate origin in the interior
1638 of the imageable area or outside of the page area.
1639 It also means that the imageable area must be contained in the page area:
1640 the \textit{prn\/} device cannot support ``Extra''
1641 sizes~\cite[Appendix~B]{PPD4.3}.\footnote{
1642 A better way would have been to set width and height from page size,
1643 resolution and the hardware margins.
1644 Not only would this have achieved support for ``Extra'' sizes via negative
1645 margins,
1646 it would also almost certainly have forced \gs\ to interpret hardware margins
1647 with respect to device space (see section~\ref{HardwareMargins}).}
1648
1649 Where a driver's device coordinate system is located on the printed page
1650 depends on where the driver puts the pixels from the pixmap.
1651 It extracts these values by calling one of the following functions to obtain
1652 one or more scan lines (all $x$~pixels for one $y$~value,
1653 $x = 0$ lying in the first byte of the scan line):
1654 \begin{quote}
1655 % Checked with gs 5.50.
1656 \tt\raggedright \parindent=-2em \advance\leftskip by 2em
1657 \noindent\kern-2em
1658 int gdev\_prn\_copy\_scan\_lines(gx\_device\_printer *pdev, int y,
1659 byte *str, \penalty-5 uint size);
1660
1661 int gdev\_prn\_get\_bits(gx\_device\_printer *pdev, int y,
1662 byte *str, \penalty-5 byte **actual\_data);
1663 \end{quote}
1664
1665 In most cases the printer's native I/O~interface for raster data
1666 will print a small group of pixel lines,
1667 clear its memory for the next group
1668 and advance the paper by the distance covered.
1669 It will not usually be possible to move backwards.
1670 Hence the first pixel line sent is the one closest to the medium's
1671 \d{leading edge},
1672 that edge which enters the printer first.\footnote{
1673 Ah, you noticed the logical gap?
1674 Well, if you find a printer which feeds paper with one edge first and
1675 then starts printing from one of the other edges,
1676 send me a message and I'll be surprised.}
1677 It is also to be expected that the printer prints the pixel line entirely,
1678 starting at the left margin of the imageable area and proceeding to the right.
1679 A convenient position for the device coordinate system is therefore
1680 with the origin in the top left corner\footnote{
1681 ``Top'' is defined as where the first pixel line is printed (leading edge),
1682 and ``left'' is the edge to the left if you hold the sheet with the
1683 leading edge up and the printed side towards you.}
1684 of the imageable area,
1685 the $x$~axis pointing to the right and the $y$~axis downwards.
1686 The driver can then extract scan lines from the pixmap in the order of
1687 increasing~$y$,
1688 does not need to reverse the order of pixels within the line,
1689 and need not insert or remove pixels at the beginning of raster lines.
1690 With the choice of device coordinates as just described
1691 the leading edge is then the edge close to the $y = 0$ line in device space.
1692
1693 It is occasionally helpful to distinguish explicitly between the two systems
1694 of device coordinates:
1695 pixmap device coordinates are fixed with respect to the pixmap
1696 (I call this the \d{pixmap device space})
1697 and the ``real'' device coordinates should be thought of as being attached to
1698 the sheet printed.
1699 The relation between them is established by the driver's source code and the
1700 printer's native I/O~interface.
1701 When programming for \gs\ you usually deal with pixmap device space,
1702 except when setting up the default user space.
1703
1704 %==============================================================================
1705
1706 \subsection{Device Space and Default User Space}
1707
1708 Having fixed the relation between the pixmap's device coordinates and the
1709 printer's interface you still have to set up the default matrix to establish
1710 the correct relation between default user space and
1711 (``real'') device coordinates.
1712
1713 %------------------------------------------------------------------------------
1714
1715 \subsubsection{The \ps{defaultmatrix} Operator}
1716 % Description derived from gs 5.50, checked with gs 6.50.
1717
1718 \Gs\ implements \ps{defaultmatrix} in \prog{zdefaultmatrix()} % zmatrix.c
1719 which calls \prog{gs\_defaultmatrix()}.
1720 The latter function first checks whether the parameter \prog{ctm\_default\_set}
1721 in the graphics state is set or not. % See gscoord.c.
1722 If it is, the function returns the value of \prog{ctm\_default} in the
1723 graphics state.
1724 If it is not set,
1725 the function obtains the current device from the graphics state,
1726 calls \prog{gs\_deviceinitialmatrix()} for this device,
1727 and performs an additional shift of the coordinate system based on the
1728 values for the \prog{Margins} array in the device instance:
1729 \begin{program}
1730 pmat->tx +=
1731 \ dev->Margins[0] * dev->HWResolution[0] / dev->MarginsHWResolution[0];
1732 pmat->ty +=
1733 \ dev->Margins[1] * dev->HWResolution[1] / dev->MarginsHWResolution[1];
1734 \end{program}
1735
1736 The function \prog{gs\_deviceinitialmatrix()} % gsdevice.c
1737 first checks whether the
1738 device procedure \prog{get\_initial\_matrix} has been filled in or not
1739 and inserts \prog{gx\_default\_get\_initial\_matrix()} in the procedure list
1740 if not.
1741 It then calls the device procedure \prog{get\_initial\_matrix}.
1742
1743 Looking from default user space,
1744 the default procedure \prog{gx\_default\_get\_initial\_matrix()} returns a
1745 matrix putting the origin in the top left corner of the page,
1746 the $x$~axis pointing to the right and the $y$~axis downwards.
1747 % See gdevdflt.c.
1748
1749 The graphics state parameter \prog{ctm\_default} is set in
1750 \prog{gs\_setdefaultmatrix()} only. % gscoord.c
1751 This function in turn is called only from \prog{zsetdefaultmatrix()} which
1752 is the implementation of the \ps{.setdefaultmatrix} operator.
1753 This operator is always (and usually only) called during execution of
1754 \ps{setpagedevice} with the value of the CTM valid
1755 after the possible execution of the \ps{Install} procedure.
1756
1757 This is the connection between \ps{defaultmatrix} and the
1758 \prog{get\_initial\_matrix} device procedure.
1759 One implication of this relation is that,
1760 if \ps{setpagedevice} is called at least once,
1761 the default matrix will remain fixed until the next call to
1762 \ps{setpagedevice}.\footnote{
1763 Note that at least one function of the \gs\ kernel
1764 (\prog{gx\_default\_clip\_box()})
1765 calls the \prog{get\_initial\_matrix} procedure directly
1766 instead of calling \prog{gs\_deviceinitialmatrix()} [gs~6.50].
1767 I have not investigated whether this could have unwanted consequences.}
1768
1769 The conclusions to be drawn from this are the following:
1770 \begin{itemize}
1771 \item You need to write your own \prog{get\_initial\_matrix} procedure only
1772 if the device coordinate origin is not in the upper left corner of the
1773 page area as seen from default user space.
1774 \item The driver should not change the default CTM except when
1775 \ps{setpagedevice} is called.
1776
1777 This means that all parameters the \prog{get\_initial\_matrix} procedure
1778 needs to define default user space should be changed only in the
1779 \prog{put\_params} device procedure.
1780 \item Your implementation of \prog{get\_initial\_matrix} should ignore
1781 \prog{Margins} and any transformation already taken care of in
1782 \ps{setpagedevice} (like \ps{PageOffset}).
1783 \end{itemize}
1784
1785 \ifdraft
1786 ??? Discuss the soft-tumble problem and its solution.
1787 \fi
1788
1789 %------------------------------------------------------------------------------
1790
1791 \subsubsection{The Imageable Area and the Device Coordinate Origin}
1792 \label{HardwareMargins}
1793
1794 The imageable area of a ghostscript device is described by the \prog{HWMargins}
1795 device variable.
1796 This is an array of four \prog{float}s,
1797 interpreted as distances in~bp from the edges of the page.\footnote{
1798 The ``canonical margin order'' in \gs, used for several such variables,
1799 is: left, bottom, right, and top,
1800 but this does not tell you which coordinate system defines these directions.
1801 This documentation is missing for several other device structure fields
1802 which require a reference system for their interpretation.
1803 In the case of \prog{HWMargins} one apparently has to look from default user
1804 space (see \prog{gs\_initclip()} in \file{gspath.c}).
1805 In contrast, the standard \texttt{*HWMargins} parameter in PPD files
1806 is explicitly defined with respect to the
1807 feeding direction~\cite[page~114]{PPD4.3}.}
1808 These values can be set by calling:
1809 \begin{program}
1810 void gx_device_set_margins(gx_device *dev, const float *margins,
1811 \ bool move_origin);
1812 \end{program}
1813 If you specify \prog{true} for \prog{move\_origin},
1814 \gs\ will in addition use the left and top margin values to set the
1815 \prog{Margins} array in such a manner that
1816 the device coordinate origin will be in the top left corner of the imageable
1817 area.
1818 As explained in section~\ref{DevCoord},
1819 the resulting effect is usually desirable.
1820 However, the way used to achieve it is wrong:
1821 the \prog{Margins} array contains the value of the \ps{Margins} page device
1822 parameter which was introduced to compensate for mechanical misalignments
1823 in a device.
1824 I take this to mean that a value of zero means that no misalignment exists,
1825 a contradiction with the situation achieved by
1826 \prog{gx\_device\_set\_margins()}.
1827 Of course one could tell the user that
1828 when setting \ps{Margins} s/he should take the imageable area into account,
1829 but this becomes a nuisance if the imageable area depends on the
1830 page size.
1831 This is for example the case for Hewlett-Packard's DeskJet printers.
1832
1833 If you want to position your device coordinate origin in the top left corner
1834 of the imageable area and to leave \ps{Margins} with its standard meaning,
1835 you will therefore have to implement the desired shift of the device coordinate
1836 origin in your driver's \prog{get\_initial\_matrix} device procedure.
1837 This procedure will need to know the top and left margins in device space.
1838
1839 %------------------------------------------------------------------------------
1840
1841 \subsubsection{Landscape Orientation}
1842
1843 As explained in section~\ref{PsUserSpace},
1844 the PostScript language requires that
1845 if a user requests landscape orientation
1846 (a \ps{PageSize} value with $\hbox{width} > \hbox{height}$ in a
1847 \ps{setpagedevice} request)
1848 the output device must rotate default user space by $+90^\circ$ with respect
1849 to portrait orientation for the same medium.\footnote{
1850 I would not consider this rule to be binding for an output device printing
1851 on media of continuously variable dimensions.
1852 In particular, it is certainly inappropriate for a screen viewer and for most
1853 if not all file formats.
1854 But the behaviour is essential for every device printing on
1855 media of discrete sizes.}
1856 However, the only ghostscript drivers I know of which actually do it are
1857 \textit{cljet5\/}~[gs~5.50] and my own \textit{hpdj/pcl3\/} driver.
1858 % I have done an automated check on most of the 137 devices present in gs 5.10
1859 % as compiled for Debian 2.1 (package gs 5.10-1). The exceptions were the
1860 % screen and file devices lvga256, vgalib, cgmmono, cgm8, and cgm24. The only
1861 % device where an exchange of width and height in the PageSize device parameter
1862 % led to a defaultmatrix with a different orientation was hpdj (cljet5 was not
1863 % among the devices compiled into the excutable).
1864 % Incidentally, hpdj is capable of this only since hpdj 2.2 but at least gave
1865 % an error message before that.
1866 % I have also searched through the gs 5.50 source code for drivers which set
1867 % their own get_initial_matrix() device procedure. I found
1868 % mem_get_initial_matrix(), clj_get_initial_matrix(), pm_get_initial_matrix(),
1869 % win_dib_get_initial_matrix(), and x_get_initial_matrix(). Only
1870 % clj_get_initial_matrix() treats rotation.
1871 % In addition, I have looked for the string "landscape" (irrespective of
1872 % upper/lower case) and found nothing suggestive except in the MS Windows
1873 % viewer gdevwpr2.c where it says: "...does try to set the printer page size
1874 % from the PostScript PageSize, but it isn't working reliably at the moment".
1875
1876 Your driver can determine that landscape orientation has been requested by
1877 examining the \prog{MediaSize[]} array.
1878 It contains the requested page size in~bp with respect to default user
1879 space.\footnote{
1880 This interpretation is not documented with the variable's definition
1881 but can be deduced from the fact that it receives the value of the
1882 \ps{PageSize} page device parameter (\prog{gx\_default\_put\_params()}).}
1883 If it is a case of landscape orientation
1884 ($\hbox{\prog{MediaSize[0]}} > \hbox{\prog{MediaSize[1]}}$),
1885 you must include a rotation by $+90^\circ$ in your \prog{get\_initial\_matrix}
1886 device procedure and you must modify the \prog{width} and \prog{height}
1887 fields appropriately.
1888
1889 Unfortunately, \gs's functions \prog{gx\_device\_set\_width\_height()},
1890 \prog{gx\_device\_set\_resolution()} and \prog{gx\_device\_set\_media\_size()}
1891 all assume that device space and default user space have the same notion about
1892 what is ``vertical'' and what is ``horizontal''.
1893 Hence you must update \prog{width} and \prog{height} directly and guard against
1894 some other instance calling any of these functions and producing inappropriate
1895 values.
1896 The only reliable way I know for this
1897 is to check for this condition in the \prog{open\_device} device procedure and,
1898 if necessary, to reassign \prog{width} and \prog{height} there.
1899 Doing this requires reallocation of storage in the \textit{prn\/} device.
1900
1901 \ifdraft
1902 ??? Problem of the initial matrix routine having the necessary information
1903 \fi
1904
1905 The same problems arise if your driver supports the \ps{LeadingEdge} page
1906 device parameter because in that case arbitrary orientations of default user
1907 space with respect to device space are possible.
1908
1909 %==============================================================================
1910
1911 \subsection{Media Sources and Destinations}
1912
1913 \Gs~[gs~5.50] sets the page device parameters \ps{\%MediaSource} and
1914 \ps{\%MediaDestination} to the position numbers determined for media source and
1915 media destination respectively
1916 during the process of media selection.
1917
1918 If your driver supports different media sources or destinations,
1919 its \prog{put\_params} routine should fetch the values of these parameters.
1920
1921 \Gs\ does support the \ps{MediaPosition} page device parameter for
1922 media selection~[gs~5.50, gs~6.01],
1923 but not by default as a device parameter
1924 (i.e., you must set it with \ps{setpagedevice}, not from the command line),
1925 and you can't use it to select negative position numbers
1926 (this gives a \ps{rangecheck}~[gs~6.01]).
1927
1928 %==============================================================================
1929
1930 \ifdraft
1931 \subsection{To be Discussed} %???
1932
1933 media sizes, InputAttributes
1934 \fi
1935
1936 %******************************************************************************
1937
1938 \section{\Gs's Colour Treatment}
1939
1940 %==============================================================================
1941
1942 \subsection{Native Colour Spaces} \label{NativeColourSpaces}
1943
1944 \Gs\ does not support \ps{DeviceN} as a native colour space~[gs~5.50].
1945 The other three possible spaces are supported;
1946 this information is encoded in the \prog{color\_info.num\_components}
1947 device parameter
1948 which can be \prog{1} for \ps{DeviceGray},
1949 \prog{3} for \ps{DeviceRGB} and \prog{4} in the case of \ps{DeviceCMYK}.
1950
1951 Note that \prog{gx\_default\_get\_params()} returns these colour space names
1952 as the value of the device parameter
1953 \ps{ProcessColorModel} which will be inappropriate if the device uses, e.g.,
1954 the process colour model \ps{DeviceCMY}.
1955 Your driver cannot correct this because
1956 \prog{gx\_default\_put\_params()} signals an error if this
1957 page device parameter has another value than the native colour space name
1958 belonging to the current \prog{color\_info.num\_components} value.
1959 % Source code inspection in gs 5.50.
1960
1961 %==============================================================================
1962
1963 \ifdraft
1964
1965 \subsection{Internal Colour Representation}
1966
1967 \subsubsection{Colour in the Native Colour Space}
1968
1969 Colour specifications in a PostScript program can be given in any of the
1970 supported colour spaces.
1971 They are then converted into the native colour space as specified by the
1972 PostScript language definition.
1973 This part is standard and results in certain real numbers
1974 in the range $[0, 1]$.
1975
1976 ??? What are the device colours? Where does \gs\ apply transfer functions?
1977
1978 For \gs, these
1979 \prog{color\_info.num\_components} floating point numbers are first
1980 converted into instances of type \prog{frac},
1981 an integer type % (\prog{short}~[gs~6.50]) % gxfrac.h
1982 with the range zero to
1983 $f_1 := 32760 = 2^3 \times 3^2 \times 5 \times 7 \times 13$.
1984 This value is chosen in order to be able to represent
1985 ``almost all common fractions'' % gxfrac.h [gs 6.50]
1986 of~1 exactly.
1987 The conversions between \prog{float} and \prog{frac} are defined as follows:
1988 \begin{program} % gxfrac.h in gs 5.50 and 6.50
1989 \#define frac_1 ((frac)0x7ff8)
1990 \#define frac_1_float ((float)frac_1)
1991 \#define frac2float(fr) ((fr) / frac_1_float)
1992 \#define float2frac(fl) ((frac)(((fl) + 0.5 / frac_1_float) * frac_1_float))
1993 \end{program}
1994 Assuming infinite precision for floating point arithmetic,
1995 the conversion from a \prog{float}~$x$ to a \prog{frac}~$f$ is therefore
1996 simply:
1997 $$
1998 f = \left\lfloor x f_1 + {1 \over 2} \right\rfloor
1999 $$
2000 Looking at the pre-images of the possible results we find that
2001 this map divides the interval $[0, 1]$ into $f_1 + 1$~pieces of unequal length:
2002 the first and the last piece have length $1 / 2 f_1$,
2003 the others have length $1/f_1$.
2004
2005 \ifdraft
2006 ??? Discuss the resulting problems, present the correct solution.
2007 \fi
2008
2009 ???
2010 are then converted into \d{(device) colour values},
2011 instances of type \prog{gx\_color\_value}.
2012 This is an unsigned integer type
2013 (at present, it is \prog{unsigned short}~\cite{Drivers6.01}),
2014 and the conversion maps zero to zero and one to
2015 the value of the macro \prog{gx\_max\_color\_value}\footnote{
2016 This is equal to $2^{\hbox{\prog{gx\_color\_value\_bits}}} - 1$
2017 where \prog{gx\_color\_value\_bits} is
2018 $8 \times \hbox{\prog{sizeof(gx\_color\_value)}}$ [gs~6.50].}.
2019 % gxcvalue.h
2020
2021 %------------------------------------------------------------------------------
2022
2023 \subsubsection{???}
2024
2025 ??? gx\_color\_index, depth
2026
2027 %------------------------------------------------------------------------------
2028
2029 ??? mapping functions (what is called depending on the native colour space)
2030
2031 %==============================================================================
2032
2033 \subsection{Intensity Rendering}
2034
2035 ??? \Gs's dithering implementation, 3 possibilities
2036
2037 %==============================================================================
2038
2039 \subsection{Process Colour Models}
2040
2041 ??? Example for DeviceCMY.
2042
2043 \fi % draft
2044
2045 %******************************************************************************
2046
2047 \addcontentsline{toc}{section}{\numberline{}References}\nobreak
2048 \bibliography{Informatik,ghostscript}
2049
2050 %******************************************************************************
2051
2052 \end{document}