![]() |
The renderer API | ![]() |
All coordinates passed to a renderer are integers of type SI, the basic length unit of the typesetter. The constant PIXEL (defined as 256 in
renderer.hpp
and
pencil.hpp
) is the number of SI units in one dot of the typesetting resolution: when a document is typeset at dpi dots per inch, one inch corresponds to dpi*PIXEL units (see for instance make_eps in
Typeset/Boxes/Basic/boxes.cpp
, which computes inch= dpi * PIXEL).
The logical \(y\)-axis points upwards, as in TeX and PostScript, whereas the device \(y\)-axis of screens and images points downwards. The conversion between both systems is done by the encode and decode routines below, which also flip the sign of \(y\). Rectangles are therefore usually written as (x1, y1, x2, y2) with x1<x2 and y1<y2 in logical coordinates, and become (x1, y2) (top left) and (x2, y1) (bottom right) after decoding.
A renderer has a current origin (ox, oy), expressed in SI. All drawing routines receive coordinates relative to this origin. Boxes exploit this: when a box is redrawn, it calls ren->move_origin (x0, y0) with its own offset before painting its children and moves the origin back afterwards, so that each box paints itself in its own local coordinates.
void set_origin (SI x, SI y)
Set the origin to (x, y), or add (dx, dy) to it. These routines are not virtual: the origin is pure bookkeeping, and the concrete renderers take it into account in decode and friends.
The relation between logical units and device pixels is described by the following public fields of renderer_rep:
The number of SI units in one device pixel.
The number of SI units in one logical screen pixel, that is pixel_ratio * pixel. On a high-density (e.g. Retina) display a logical pixel covers several device pixels.
The device pixel ratio passed to the constructor renderer_rep (bool screen_flag, double pixel_ratio= 1).
The zoom factor, including the pixel ratio.
The shrinking factor: the integer number of typesetting dots which are merged into one device pixel. It is the rounded value of pixel_ratio * std_shrinkf / zoomf.
Extra thickening used when anti-aliasing characters, (shrinkf >> 1) * PIXEL.
A hack: -1, or the size of a pixel to be used when rendering patterns (see ?).
Whether the renderer draws on the screen. Some boxes behave differently on screen and on paper (for instance they check for interruptions only on the screen).
The global variable std_shrinkf (defined in
renderer.cpp
and equal to 5) is the standard shrinking factor: at a zoom of \(100\%\), one screen pixel corresponds to five dots of the typesetting resolution. The editor keeps its own zoom factor in edit_interface_rep::zoomf and derives from it
magf = zoomf / std_shrinkf;
pixel = (SI) tm_round ((std_shrinkf * PIXEL) / zoomf); |
(see edit_interface_rep::set_zoom_factor in
Edit/Interface/edit_interface.cpp
).
Set zoomf to pixel_ratio * zoom and recompute shrinkf, thicken, pixel and retina_pixel. The origin and the clipping rectangle are rescaled so that they keep designating the same device pixels: they are first multiplied by the old zoom factor and then divided by the new one. If safe is set and the current shrinkf is inconsistent with zoomf, a warning Invalid zoom is printed.
The Qt renderer overrides this method: with Qt 6 it multiplies zoom by zoom_multiplier (used by QTMImpressIconEngine to scale icons), and with older versions of Qt it multiplies by the global retina_factor and sets retina_pixel= pixel * retina_factor.
void reset_zoom_factor ()
reset_zoom_factor is set_zoom_factor (std_shrinkf); with pixel_ratio = 1 this sets pixel = PIXEL, so that one device pixel is one SI-dot. set_shrinking_factor (sf) sets the zoom to std_shrinkf / sf.
The function double normal_zoom (double zoom) rounds a zoom factor down to the largest value of the form \(320 / n\) (with \(n\) a positive integer) which does not exceed it, up to a small tolerance.
renderer.hpp
declares a few global parameters for high density screens: retina_factor (the MacOS style integer factor), retina_zoom (the GNU/Linux and Windows style zoom), retina_icons, retina_scale and the flags retina_manual, retina_iman, with accessors get_retina_factor, set_retina_factor, etc. When compiling against Qt 6 (QT_VERSION >= 0x060000) these are compile-time constants equal to one, and the setters just print Unexpected call to set_retina_…: with Qt 6 the device pixel ratio is passed explicitly to each renderer through pixel_ratio instead (see the_qt_renderer (double pixel_ratio) and qt_simple_widget_rep::repaint_invalid_regions).
virtual void decode (SI& x, SI& y)
Convert logical coordinates (relative to the origin) into device pixel coordinates. The integer version adds the origin, divides by pixel rounding towards \(- \infty\), and negates \(y\):
x += ox; y += oy;
if (x>=0) x= x/pixel; else x= (x-pixel+1)/pixel;
if (y>=0) y= -(y/pixel); else y= -((y-pixel+1)/pixel); |
The floating point version returns rx= (x+ox)/pixel - 0.5 and ry= -((y+oy)/pixel - 0.5); it is used by the anti-aliased primitives of the Qt renderer, which address pixel centers.
virtual void encode (SI& x, SI& y)
The inverse conversion: x= x*pixel - ox and y= (-y)*pixel - oy. Window toolkits use it to translate the rectangles to be repainted into logical coordinates before calling the widget's handle_repaint.
void round (SI& x, SI& y)
void inner_round (SI& x1, SI& y1, SI& x2, SI& y2)
Round a point, respectively a rectangle, to the grid of (logical) pixels, taking the origin into account. outer_round enlarges the rectangle to the smallest pixel-aligned rectangle containing it and inner_round shrinks it to the largest one it contains. The grid used is that of retina_pixel. The friends abs_round, abs_inner_round and abs_outer_round do the same with respect to an absolute grid of PIXEL units, ignoring the origin.
The visible region is the rectangle (cx1, cy1, cx2, cy2). Contrary to the arguments of the drawing routines, these fields are stored in absolute coordinates, i.e. with the origin added, so that they remain valid when the origin is moved.
virtual void get_clipping (SI &x1, SI &y1, SI &x2, SI &y2)
Get or set the clipping rectangle, in coordinates relative to the current origin. The default set_clipping applies outer_round and stores the result in cx1, …, cy2. Concrete renderers override it to also clip the underlying device (QPainter::setClipRect, a PostScript gsave/clip, a PDF q/W sequence, etc.).
The restore flag tells the renderer that the new rectangle is a previous clipping region which is being restored, rather than a new, smaller one. This matters for the printers, whose clipping is a stack of graphics states: printer_rep::set_clipping emits a grestore when restore is true and a gsave followed by a new clip path otherwise; the PDF renderer does the same with Q and q, keeping track of the nesting in clip_level. Callers must therefore always pair a narrowing call with a restoring call.
Intersect the current clipping rectangle with the given one. The typical usage, from clip_box_rep in
Typeset/Boxes/Modifier/change_boxes.cpp
, is
void
clip_box_rep::pre_display (renderer &ren) {
ren->get_clipping (old_clip_x1, old_clip_y1, old_clip_x2, old_clip_y2);
ren->extra_clipping (x1, y1, x2, y2);
}
void
clip_box_rep::post_display (renderer &ren) {
ren->set_clipping (
old_clip_x1, old_clip_y1, old_clip_x2, old_clip_y2, true);
} |
void clip (SI x1, SI y1, SI x2, SI y2)
clip pushes the current clipping rectangle on clip_stack and sets a new one; unclip pops it and restores it (with restore= true). They are used by the implementations of set_transformation and reset_transformation.
Test whether the rectangle intersects the clipping region. Boxes use this test on their ink extents in order to skip invisible parts of the box tree.
virtual void set_transformation (frame fr)
Install a linear transformation (a frame, see
Graphics/Types/frame.hpp
) for subsequent drawing, and remove it again. This is used by transformed_box_rep::pre_display and post_display for rotated and scaled boxes. The default implementation does nothing. The Qt and PDF renderers conjugate the frame with the logical-to-device conversion, apply the result to the device (QPainter::setTransform, respectively the PDF operator cm inside q…Q), and push the transformed clipping rectangle with clip. Only linear frames are supported (this is asserted).
Colors are values of type color (a packed RGBA value, see
Graphics/Colors/colors.hpp
), built with rgb_color and decomposed with get_rgb_color. The alpha component is honored by the screen renderers; the PostScript renderer blends it with the current background color since PostScript has no transparency. The global function get_reverse_colors indicates reverse video mode, in which the renderers invert colors with reverse (int& r, int& g, int& b).
A pencil (
Graphics/Renderer/pencil.hpp
) is a reference counted, immutable description of how lines and glyphs are drawn: a color or a brush, a width in SI, a cap style (cap_square, cap_flat, cap_round), a join style (join_bevel, join_miter, join_round) and a miter limit. Its kind, returned by get_type (), is one of pencil_none (draw nothing), pencil_simple (color and width only), pencil_standard (color with explicit cap and join) and pencil_brush (the pencil paints with a pattern brush). The default width is std_shrinkf * PIXEL, i.e. one screen pixel at the standard zoom. Pencils are built from a color, a brush or a tree with an alpha value; since they are immutable, set_width and set_cap return new pencils.
A brush (
Graphics/Renderer/brush.hpp
) describes how areas are filled. Its kind is brush_none, brush_color or brush_pattern. A pattern brush is built from a pattern tree (pattern url width height [color]) and an alpha value; get_pattern_url resolves the image file, looking in $TEXMACS_PATTERN_PATH and relative to the current buffer, and get_pattern_data computes the image size in SI for a given pixel size. A brush built from the tree "" or "none", or from a fully transparent color, is of kind brush_none.
virtual pencil get_pencil () = 0
Get and set the pencil used by draw, line, lines, arc, and, for the color, by fill, fill_arc and polygon. Implementations translate the pencil into device state (a QPen and QBrush, a PostScript color and line width, etc.) at this point. A color converts implicitly into a pencil, so ren->set_pencil (black) is common.
virtual brush get_brush ()
Get and set the brush used for filling. The default implementations simply go through the pencil: set_brush (b) calls set_pencil (b->get_color ()) and get_brush () returns get_pencil ()->get_brush (). basic_renderer_rep keeps a separate fg_brush and resets the pencil to pencil (b); the Qt and PDF renderers also support pattern brushes for fills.
virtual brush get_background () = 0
Get and set the background brush used by clear and clear_pattern. A tree converts implicitly into a brush, so the editor simply writes ren->set_background (bg) with the value of the bg-color environment variable.
Boxes which temporarily change the state are expected to restore it. For example art_box_rep::pre_display saves get_background () and get_pencil (), and post_display restores them.
In all the routines below, coordinates are logical and relative to the current origin.
virtual void line (SI x1, SI y1, SI x2, SI y2) = 0
Draw a line segment, respectively an open polyline through the points (x[i], y[i]), with the current pencil. The Qt renderer draws them anti-aliased; for a closed polyline (first and last points equal) it forces round caps.
Fill a rectangle with the pencil color. This is not anti-aliased. The Qt implementation widens rectangles that are thinner than one pixel to exactly one pixel, so that thin rules never disappear.
Fill a rectangle with the color of the current background brush. Pattern backgrounds are handled by clear_pattern.
virtual void clear_pattern (SI mx1, SI my1, SI mx2, SI my2, SI x1, SI y1, SI x2, SI y2)
Clear the rectangle (x1, y1, x2, y2) with the current background brush. For a color brush this is clear; for a brush_none nothing happens. For a pattern brush, the pattern image is loaded as a scalable with load_scalable_image and tiled over the rectangle with draw_scalable, under an additional clipping. The mother rectangle (mx1, my1, mx2, my2) fixes the phase of the tiling and the meaning of percentages in the pattern sizes (100%, 50@, etc.), so that a background image stays attached to the page when only a part of the page is repainted. The four argument version uses the rectangle itself as the mother rectangle.
Paint the neutral background of the device itself, behind the page. This is called by edit_interface_rep::draw_background before the page background. It is a no-op for printers and for Qt 5; with Qt 6 the Qt renderer paints a checkerboard pattern (the image neutral-pattern.png if it can be found), which shows through transparent page backgrounds. Although declared pure virtual,
renderer.cpp
also provides an empty body.
virtual void arc (SI x1, SI y1, SI x2, SI y2, int alpha, int delta) = 0
Draw, respectively fill, the arc of the ellipse inscribed in the rectangle (x1, y1, x2, y2), starting at angle alpha and spanning delta. As in X11, angles are expressed in \(1 / 64\) of a degree, counterclockwise; callers typically write 90<<6 for a right angle (see
Typeset/Boxes/Basic/rubber_boxes.cpp
). The Qt renderer converts them to the \(1 / 16\) degrees of QPainter::drawArc and to degrees for QPainterPath::arcTo.
Fill a closed polygon with the current brush (or pencil color). In the Qt renderer the convex flag actually selects the fill rule: Qt::OddEvenFill when it is true and Qt::WindingFill otherwise.
Fill a triangle. The default calls polygon; the Qt version rounds the vertices to integer pixels and disables anti-aliasing, which gives crisp joins for the beveled borders drawn by
Typeset/Boxes/Modifier/highlight_boxes.cpp
.
virtual void draw_rectangles (rectangles rs)
draw_rectangles fills each rectangle of the list. draw_selection draws a selection: the interior of the region is filled with the pencil color at roughly \(1 / 16\) of its opacity and the one-pixel wide border with the opaque color. The editor (
edit_repaint.cpp
) uses draw_selection for the selections with Qt, Qtwk, SDL, Vue and Cocoa, and for the spelling errors with Qt, Qtwk and Cocoa only; draw_rectangles otherwise (always with X11).
Draw a spacial object (
Graphics/Spacial/spacial.hpp
) by calling obj->draw (this).
Fonts are described in the fonts document; here we only describe the interface with the renderer. There is exactly one text primitive:
Draw the glyph with index char_code of the bitmap font fn with its origin at (x, y), using the current pencil. font_glyphs (
Graphics/Bitmap_fonts/bitmap_font.hpp
) gives access to the rasterized glyphs through glyph& get (int char_code); its res_name identifies the font and its size, which the printers use to build font resources.
The path of a piece of text from the box tree to the device is as follows.
text_box_rep::display (in
Typeset/Boxes/Basic/text_boxes.cpp
) sets the pencil and calls fn->draw (ren, str, 0, 0) on its font.
font_rep::draw (renderer ren, string s, SI x, SI y, SI xk, bool ext) (in
Graphics/Fonts/font.cpp
) decides at which resolution to render. If ren->zoomf == 1.0 or the renderer is a printer, it calls draw_fixed directly. Otherwise it uses a magnified font zoomed_fn= magnify (ren->zoomf) (cached as long as the zoom does not change) and temporarily reconfigures the renderer: the origin and clipping are multiplied by the zoom, zoomf is set to 1.0, shrinkf to std_shrinkf, pixel and retina_pixel to std_shrinkf * PIXEL, and brushpx to the old pixel size (so that pattern pencils keep their on-screen scale). After drawing, all these fields are restored. The code is marked as a low level rendering hack: renderers must not cache anything derived from these fields across calls to draw.
draw_fixed of the concrete font (for instance
Plugins/Freetype/tt_font.cpp
,
Plugins/Freetype/unicode_font.cpp
,
Graphics/Fonts/virtual_font.cpp
or the poor_*.cpp fonts) computes glyph positions and calls ren->draw (c, fng, x, y) for each glyph.
The renderer draws the glyph. Screen renderers rasterize it: the Qt renderer calls shrink (glyph, std_shrinkf, std_shrinkf, xo, yo, pixel_ratio) to obtain an anti-aliased glyph at screen resolution, converts it into a colored QImage (or QTMPixmapOrImage), and caches the result in the static table character_image, keyed by a basic_character (glyph index, font, shrinking factor, foreground and background color). Glyphs drawn with a pencil_brush pencil are handled by qt_renderer_rep::draw_bis, which uses the glyph as an alpha mask over the pattern. Printers embed fonts instead, see the renderer implementations.
One font bypasses the glyph interface: qt_font_rep::draw_fixed (
Plugins/Qt/qt_font.cpp
) recovers the Qt renderer with ren->get_handle () and calls the extra method qt_renderer_rep::draw (const QFont& qfn, const QString& s, SI x, SI y, double zoom), which renders the string with QPainter::drawText.
A picture (
Graphics/Pictures/picture.hpp
) is a reference counted rectangular array of pixels with an origin. Its kind is picture_native (a picture of the GUI toolkit: a qt_picture_rep wrapping a QImage, an x_picture_rep wrapping an X11 Pixmap, an ns_picture_rep wrapping an NSBitmapImageRep, a mupdf_picture_rep wrapping an MuPDF pixmap, or the texture gpu_picture_rep of the Vue GPU path), picture_raster (a portable raster_picture_rep<C> wrapping a raster<C>, by default with true_color pixels) or picture_lazy. Pixels are accessed with get_pixel and set_pixel in coordinates relative to the origin (get_origin_x, get_origin_y); as_raster_picture and as_native_picture convert between the representations. Each picture has a unique identifier, get_unique_id (), which the PDF renderer uses to cache exported pictures.
The header also declares a library of operations on pictures used to implement graphical effects: composition (compose, draw_on with a composition_mode), geometric operations (shift, magnify, crop), pens and morphological operations (gaussian_pen_picture, blur, outlines, thicken, erode), noise and distortions, and color operations. The class effect_rep (
Graphics/Pictures/effect.hpp
) combines them: effect build_effect (tree description) parses an effect and picture apply (array<picture> pics, SI pixel) computes the resulting picture from pictures of its arguments.
Pictures on disk are loaded with load_picture (url u, int w, int h, tree eff, int pixel) and, with caching, cached_load_picture; the entries of the cache are reserved and released with picture_cache_reserve and picture_cache_release. load_xpm loads the xpm icons of the interface. save_picture writes a picture to a file, and picture_as_eps converts it to EPS.
Draw a picture with its origin at (x, y) and the given opacity. The default implementation fails with rendering pictures is not supported, so every renderer on which images may appear must override it. The Qt renderer converts the picture with as_native_picture and calls QPainter::drawImage; the printers encode it as an image in the output file.
A scalable (
Graphics/Pictures/scalable.hpp
) is an image that is independent of the resolution, with logical and physical extents and a method draw (renderer ren, SI x, SI y, int alpha). The only implementation is scalable_image_rep, created by load_scalable_image (url file_name, SI w, SI h, tree eff, SI pixel), which represents an image file with a size and an optional effect. Its draw method loads a picture at the renderer's current pixel size with cached_load_picture and calls draw_picture.
The default implementation calls im->draw (this, x, y, alpha), i.e. it rasterizes. Printers override it in order to embed the original file without rasterization when possible: the PostScript renderer inserts the PostScript code of the image, and the PDF renderer embeds the image file (only if no effect is attached; otherwise it falls back on the default).
It is possible to redirect drawing into a picture. This is used for graphical effects, for exporting snippets as bitmaps and for rendering icons.
Return a renderer which draws on p. It must be deleted with delete_renderer or tm_delete when drawing is finished. This function, as well as native_picture, load_picture, as_native_picture and save_picture, is provided by the GUI back-end (
Plugins/Qt/qt_picture.cpp
,
Plugins/X11/x_picture.cpp
,
Plugins/NS/ns_picture.mm
, or
Plugins/MuPDF/mupdf_picture.cpp
for SDL, Vue and the Qt builds with MuPDF);
renderer.cpp
only contains failing stubs for builds without any of QTTEXMACS, X11TEXMACS, SDLTEXMACS, VUETEXMACS and AQUATEXMACS. For Qt without MuPDF the returned renderer is a qt_image_renderer_rep, which opens a QPainter on the QImage of the picture after clearing it to transparent.
Create a new native picture covering the rectangle (x1, y1, x2, y2) of the current renderer (after outer_round), store it in pic, and return a picture renderer for it which has the same origin, clipping, zoom and pixel parameters as the current renderer, translated so that drawing at the same logical coordinates lands in the picture. Printers override this method to rasterize at a fixed resolution: they temporarily set their zoom factor to 5.0 * PICTURE_ZOOM before calling the default implementation.
The typical client is effect_box_rep::redraw:
array<picture> pics (subnr ());
SI shad_pixel= ren->pixel;
for (int i=0; i<subnr(); i++) {
renderer shad= ren->shadow (pics[i], sx3(i), sy3(i), sx4(i), sy4(i));
shad_pixel= shad->pixel;
rectangles rs;
subbox (i)->redraw (shad, path (), rs);
delete_renderer (shad);
}
…
picture result_pic= eff->apply (pics, shad_pixel);
ren->draw_picture (result_pic, 0, 0); |
The overload shadow (scalable& im, …) and the function scalable_renderer are not implemented.
The word shadow designates an auxiliary renderer of the same size as a screen renderer, which is used for double buffering: the editor draws a region into the shadow and then copies the result to the screen in one go, which avoids flickering. The design comes from the X11 port, where the shadow is an off-screen Pixmap.
virtual void new_shadow (renderer& ren) = 0
new_shadow makes sure that ren is a shadow compatible with the current renderer. If ren is not NULL and has the same extents (and, for Qt, the same pixel ratio), it is reused; otherwise it is deleted and a new one is allocated. The editor keeps its shadows in the fields shadow and stored of edit_interface_rep and calls new_shadow before every use. delete_shadow deletes ren and sets it to NULL.
Copy the rectangle (x1, y1, x2, y2) of the current renderer into the shadow ren, and give the shadow the same origin, a clipping rectangle equal to this rectangle (intersected with the current clipping), and set its master field to the current renderer.
Copy the rectangle (x1, y1, x2, y2) of the shadow ren onto the current renderer.
Called on a shadow: copy the given rectangle to the master renderer, via master->put_shadow. box_rep::redraw calls ren->apply_shadow for the first fifteen boxes painted (nr_painted < 15), so that the first parts of the document become visible immediately even though the rest is drawn into the shadow.
Copy a rectangle of ren to position (x, y) of the current renderer. The X11 renderer implements it (with XCopyArea), as do the MuPDF renderer (between pixmaps) and the Vue GPU renderer (between textures); the other renderers leave it empty.
Qt already double-buffers, and a Qt program cannot reliably read back pixels from the screen. The Qt port therefore keeps its own backing store: each qt_simple_widget_rep owns a backingPixmap, the TeXmacs side only ever paints on this pixmap, and the QWidget copies it to the screen in its paint event. On top of this, the comment in
qt_renderer.cpp
explains that two helper classes emulate the shadow protocol:
qt_renderer_rep::new_shadow returns a qt_proxy_renderer_rep, which draws with the same QPainter as the original renderer. The main double buffering therefore costs nothing: put_shadow and apply_shadow return immediately when both renderers share their painter.
qt_proxy_renderer_rep::new_shadow (a shadow of a shadow, such as the editor's stored backing store) creates a genuine qt_shadow_renderer_rep, which owns a QTMPixmapOrImage px and its own QPainter. Its get_shadow and the proxy's get_shadow copy pixels with drawPixmap (or drawImage in headless_mode).
The basic screen renderer class basic_renderer_rep implements all shadow operations as no-ops (new_shadow just returns this), which is a valid, if unbuffered, choice.
The following methods have trivial default implementations in renderer_rep and are overridden by the PostScript and PDF renderers.
Returns false by default. Boxes test it to suppress screen-only decorations (for instance in
highlight_boxes.cpp
and in the screen/printer filters of
decoration_boxes.cpp
), and font_rep::draw uses it to bypass zooming.
Returns true by default. The PDF renderer returns false if the output file could not be opened, in which case print_doc draws nothing.
virtual void next_page ()
next_page finishes the current page and starts the next one; printers reset their cached graphical state (current color, line width, font) and the clipping to the full page at that moment. set_page_nr sets cur_page; it is called by page_box_rep::pre_display and post_display, so that decorations can depend on the parity of the page.
The size of the device in pixels. It is 0, 0 by default; basic_renderer_rep returns its fields w and h, and the Qt renderer the size of the paint device. It is used to decide whether a shadow can be reused.
virtual void anchor (string label, SI x1, SI y1, SI x2, SI y2)
virtual void href (string label, SI x1, SI y1, SI x2, SI y2)
virtual void toc_entry (string kind, string title, SI x, SI y)
Record a link target, a clickable link area, an entry of the document outline and a metadata field (title, author, subject). Boxes call the first three unconditionally, the screen renderers simply ignoring them: locus_box_rep::post_display (in
change_boxes.cpp
) emits href and anchor, the table of contents boxes of
decoration_boxes.cpp
emit toc_entry, and box_rep::display_links, which box_rep::redraw only calls for non-screen renderers, emits href for hyperlinks attached to the source of the box. print_doc calls set_metadata. The PostScript renderer emits pdfmark style annotations; the PDF renderer writes native annotations, destinations and outlines.