DISTRHO Plugin Framework
NanoVG.hpp
1 /*
2  * DISTRHO Plugin Framework (DPF)
3  * Copyright (C) 2012-2016 Filipe Coelho <falktx@falktx.com>
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any purpose with
6  * or without fee is hereby granted, provided that the above copyright notice and this
7  * permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
10  * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
11  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
12  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
13  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #ifndef DGL_NANO_WIDGET_HPP_INCLUDED
18 #define DGL_NANO_WIDGET_HPP_INCLUDED
19 
20 #include "Color.hpp"
21 #include "Widget.hpp"
22 
23 #define NANOVG_DEJAVU_SANS_TTF "__dpf_dejavusans_ttf__"
24 
25 struct NVGcontext;
26 struct NVGpaint;
27 
28 START_NAMESPACE_DGL
29 
30 // -----------------------------------------------------------------------
31 // Forward class names
32 
33 class BlendishWidget;
34 class NanoVG;
35 
36 // -----------------------------------------------------------------------
37 // NanoImage
38 
39 /**
40  NanoVG Image class.
41 
42  This implements NanoVG images as a C++ class where deletion is handled automatically.
43  Images need to be created within a NanoVG or NanoWidget class.
44  */
45 class NanoImage
46 {
47 private:
48  struct Handle {
49  NVGcontext* context;
50  int imageId;
51 
52  Handle() noexcept
53  : context(nullptr),
54  imageId(0) {}
55 
56  Handle(NVGcontext* c, int id) noexcept
57  : context(c),
58  imageId(id) {}
59  };
60 
61 public:
62  /**
63  Constructor for an invalid/null image.
64  */
65  NanoImage();
66 
67  /**
68  Constructor.
69  */
70  NanoImage(const Handle& handle);
71 
72  /**
73  Destructor.
74  */
75  ~NanoImage();
76 
77  /**
78  Create a new image without recreating the C++ class.
79  */
80  NanoImage& operator=(const Handle& handle);
81 
82  /**
83  Wherever this image is valid.
84  */
85  bool isValid() const noexcept;
86 
87  /**
88  Get size.
89  */
90  Size<uint> getSize() const noexcept;
91 
92  /**
93  Get the OpenGL texture handle.
94  */
95  GLuint getTextureHandle() const;
96 
97 private:
98  Handle fHandle;
99  Size<uint> fSize;
100  friend class NanoVG;
101 
102  /** @internal */
103  void _updateSize();
104 
105  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoImage)
106 };
107 
108 // -----------------------------------------------------------------------
109 // NanoVG
110 
111 /**
112  NanoVG class.
113 
114  This class exposes the NanoVG drawing API.
115  All calls should be wrapped in beginFrame() and endFrame().
116 
117  @section State Handling
118  NanoVG contains state which represents how paths will be rendered.
119  The state contains transform, fill and stroke styles, text and font styles, and scissor clipping.
120 
121  @section Render styles
122  Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern.
123  Solid color is simply defined as a color value, different kinds of paints can be created
124  using linearGradient(), boxGradient(), radialGradient() and imagePattern().
125 
126  Current render style can be saved and restored using save() and restore().
127 
128  @section Transforms
129  The paths, gradients, patterns and scissor region are transformed by an transformation
130  matrix at the time when they are passed to the API.
131  The current transformation matrix is a affine matrix:
132  [sx kx tx]
133  [ky sy ty]
134  [ 0 0 1]
135  Where: sx,sy define scaling, kx,ky skewing, and tx,ty translation.
136  The last row is assumed to be 0,0,1 and is not stored.
137 
138  Apart from resetTransform(), each transformation function first creates
139  specific transformation matrix and pre-multiplies the current transformation by it.
140 
141  Current coordinate system (transformation) can be saved and restored using save() and restore().
142 
143  @section Images
144  NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering.
145  In addition you can upload your own image. The image loading is provided by stb_image.
146 
147  @section Paints
148  NanoVG supports four types of paints: linear gradient, box gradient, radial gradient and image pattern.
149  These can be used as paints for strokes and fills.
150 
151  @section Scissoring
152  Scissoring allows you to clip the rendering into a rectangle. This is useful for various
153  user interface cases like rendering a text edit or a timeline.
154 
155  @section Paths
156  Drawing a new shape starts with beginPath(), it clears all the currently defined paths.
157  Then you define one or more paths and sub-paths which describe the shape. The are functions
158  to draw common shapes like rectangles and circles, and lower level step-by-step functions,
159  which allow to define a path curve by curve.
160 
161  NanoVG uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise
162  winding and holes should have counter clockwise order. To specify winding of a path you can
163  call pathWinding(). This is useful especially for the common shapes, which are drawn CCW.
164 
165  Finally you can fill the path using current fill style by calling fill(), and stroke it
166  with current stroke style by calling stroke().
167 
168  The curve segments and sub-paths are transformed by the current transform.
169 
170  @section Text
171  NanoVG allows you to load .ttf files and use the font to render text.
172 
173  The appearance of the text can be defined by setting the current text style
174  and by specifying the fill color. Common text and font settings such as
175  font size, letter spacing and text align are supported. Font blur allows you
176  to create simple text effects such as drop shadows.
177 
178  At render time the font face can be set based on the font handles or name.
179 
180  Font measure functions return values in local space, the calculations are
181  carried in the same resolution as the final rendering. This is done because
182  the text glyph positions are snapped to the nearest pixels sharp rendering.
183 
184  The local space means that values are not rotated or scale as per the current
185  transformation. For example if you set font size to 12, which would mean that
186  line height is 16, then regardless of the current scaling and rotation, the
187  returned line height is always 16. Some measures may vary because of the scaling
188  since aforementioned pixel snapping.
189 
190  While this may sound a little odd, the setup allows you to always render the
191  same way regardless of scaling. i.e. following works regardless of scaling:
192 
193  @code
194  const char* txt = "Text me up.";
195  textBounds(vg, x,y, txt, NULL, bounds);
196  beginPath(vg);
197  roundedRect(vg, bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]);
198  fill(vg);
199  @endcode
200 
201  Note: currently only solid color fill is supported for text.
202  */
203 class NanoVG
204 {
205 public:
206  enum CreateFlags {
207  /**
208  Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA).
209  */
210  CREATE_ANTIALIAS = 1 << 0,
211 
212  /**
213  Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little
214  slower, but path overlaps (i.e. self-intersecting or sharp turns) will be drawn just once.
215  */
216  CREATE_STENCIL_STROKES = 1 << 1,
217 
218  /**
219  Flag indicating that additional debug checks are done.
220  */
221  CREATE_DEBUG = 1 << 2,
222  };
223 
224  enum ImageFlags {
225  IMAGE_GENERATE_MIPMAPS = 1 << 0, // Generate mipmaps during creation of the image.
226  IMAGE_REPEAT_X = 1 << 1, // Repeat image in X direction.
227  IMAGE_REPEAT_Y = 1 << 2, // Repeat image in Y direction.
228  IMAGE_FLIP_Y = 1 << 3, // Flips (inverses) image in Y direction when rendered.
229  IMAGE_PREMULTIPLIED = 1 << 4 // Image data has premultiplied alpha.
230  };
231 
232  enum Align {
233  // Horizontal align
234  ALIGN_LEFT = 1 << 0, // Align horizontally to left (default).
235  ALIGN_CENTER = 1 << 1, // Align horizontally to center.
236  ALIGN_RIGHT = 1 << 2, // Align horizontally to right.
237  // Vertical align
238  ALIGN_TOP = 1 << 3, // Align vertically to top.
239  ALIGN_MIDDLE = 1 << 4, // Align vertically to middle.
240  ALIGN_BOTTOM = 1 << 5, // Align vertically to bottom.
241  ALIGN_BASELINE = 1 << 6 // Align vertically to baseline (default).
242  };
243 
244  enum LineCap {
245  BUTT,
246  ROUND,
247  SQUARE,
248  BEVEL,
249  MITER
250  };
251 
252  enum Solidity {
253  SOLID = 1, // CCW
254  HOLE = 2 // CW
255  };
256 
257  enum Winding {
258  CCW = 1, // Winding for solid shapes
259  CW = 2 // Winding for holes
260  };
261 
262  struct Paint {
263  float xform[6];
264  float extent[2];
265  float radius;
266  float feather;
267  Color innerColor;
268  Color outerColor;
269  int imageId;
270 
271  Paint() noexcept;
272 
273  /**
274  @internal
275  */
276  Paint(const NVGpaint&) noexcept;
277  operator NVGpaint() const noexcept;
278  };
279 
280  struct GlyphPosition {
281  const char* str; // Position of the glyph in the input string.
282  float x; // The x-coordinate of the logical glyph position.
283  float minx, maxx; // The bounds of the glyph shape.
284  };
285 
286  struct TextRow {
287  const char* start; // Pointer to the input text where the row starts.
288  const char* end; // Pointer to the input text where the row ends (one past the last character).
289  const char* next; // Pointer to the beginning of the next row.
290  float width; // Logical width of the row.
291  float minx, maxx; // Actual bounds of the row. Logical with and bounds can differ because of kerning and some parts over extending.
292  };
293 
294  typedef int FontId;
295 
296  /**
297  Constructor.
298  @see CreateFlags
299  */
300  NanoVG(int flags = CREATE_ANTIALIAS);
301 
302  /**
303  Constructor reusing a NanoVG context, used for subwidgets.
304  */
305  NanoVG(NanoWidget* groupWidget);
306 
307  /**
308  Destructor.
309  */
310  virtual ~NanoVG();
311 
312  /**
313  Get the NanoVG context.
314  You should not need this under normal circumstances.
315  */
316  NVGcontext* getContext() const noexcept
317  {
318  return fContext;
319  }
320 
321  /**
322  Begin drawing a new frame.
323  */
324  void beginFrame(const uint width, const uint height, const float scaleFactor = 1.0f);
325 
326  /**
327  Begin drawing a new frame inside a widget.
328  */
329  void beginFrame(Widget* const widget);
330 
331  /**
332  Cancels drawing the current frame.
333  */
334  void cancelFrame();
335 
336  /**
337  Ends drawing flushing remaining render state.
338  */
339  void endFrame();
340 
341  /* --------------------------------------------------------------------
342  * State Handling */
343 
344  /**
345  Pushes and saves the current render state into a state stack.
346  A matching restore() must be used to restore the state.
347  */
348  void save();
349 
350  /**
351  Pops and restores current render state.
352  */
353  void restore();
354 
355  /**
356  Resets current render state to default values. Does not affect the render state stack.
357  */
358  void reset();
359 
360  /* --------------------------------------------------------------------
361  * Render styles */
362 
363  /**
364  Sets current stroke style to a solid color.
365  */
366  void strokeColor(const Color& color);
367 
368  /**
369  Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values.
370  Values must be in [0..255] range.
371  */
372  void strokeColor(const int red, const int green, const int blue, const int alpha = 255);
373 
374  /**
375  Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values.
376  Values must in [0..1] range.
377  */
378  void strokeColor(const float red, const float green, const float blue, const float alpha = 1.0f);
379 
380  /**
381  Sets current stroke style to a paint, which can be a one of the gradients or a pattern.
382  */
383  void strokePaint(const Paint& paint);
384 
385  /**
386  Sets current fill style to a solid color.
387  */
388  void fillColor(const Color& color);
389 
390  /**
391  Sets current fill style to a solid color, made from red, green, blue and alpha numeric values.
392  Values must be in [0..255] range.
393  */
394  void fillColor(const int red, const int green, const int blue, const int alpha = 255);
395 
396  /**
397  Sets current fill style to a solid color, made from red, green, blue and alpha numeric values.
398  Values must in [0..1] range.
399  */
400  void fillColor(const float red, const float green, const float blue, const float alpha = 1.0f);
401 
402  /**
403  Sets current fill style to a paint, which can be a one of the gradients or a pattern.
404  */
405  void fillPaint(const Paint& paint);
406 
407  /**
408  Sets the miter limit of the stroke style.
409  Miter limit controls when a sharp corner is beveled.
410  */
411  void miterLimit(float limit);
412 
413  /**
414  Sets the stroke width of the stroke style.
415  */
416  void strokeWidth(float size);
417 
418  /**
419  Sets how the end of the line (cap) is drawn,
420  Can be one of: BUTT, ROUND, SQUARE.
421  */
422  void lineCap(LineCap cap = BUTT);
423 
424  /**
425  Sets how sharp path corners are drawn.
426  Can be one of MITER, ROUND, BEVEL.
427  */
428  void lineJoin(LineCap join = MITER);
429 
430  /**
431  Sets the transparency applied to all rendered shapes.
432  Already transparent paths will get proportionally more transparent as well.
433  */
434  void globalAlpha(float alpha);
435 
436  /* --------------------------------------------------------------------
437  * Transforms */
438 
439  /**
440  Resets current transform to a identity matrix.
441  */
442  void resetTransform();
443 
444  /**
445  Pre-multiplies current coordinate system by specified matrix.
446  The parameters are interpreted as matrix as follows:
447  [a c e]
448  [b d f]
449  [0 0 1]
450  */
451  void transform(float a, float b, float c, float d, float e, float f);
452 
453  /**
454  Translates current coordinate system.
455  */
456  void translate(float x, float y);
457 
458  /**
459  Rotates current coordinate system. Angle is specified in radians.
460  */
461  void rotate(float angle);
462 
463  /**
464  Skews the current coordinate system along X axis. Angle is specified in radians.
465  */
466  void skewX(float angle);
467 
468  /**
469  Skews the current coordinate system along Y axis. Angle is specified in radians.
470  */
471  void skewY(float angle);
472 
473  /**
474  Scales the current coordinate system.
475  */
476  void scale(float x, float y);
477 
478  /**
479  Stores the top part (a-f) of the current transformation matrix in to the specified buffer.
480  [a c e]
481  [b d f]
482  [0 0 1]
483  */
484  void currentTransform(float xform[6]);
485 
486  /**
487  The following functions can be used to make calculations on 2x3 transformation matrices.
488  A 2x3 matrix is represented as float[6]. */
489 
490  /**
491  Sets the transform to identity matrix.
492  */
493  static void transformIdentity(float dst[6]);
494 
495  /**
496  Sets the transform to translation matrix
497  */
498  static void transformTranslate(float dst[6], float tx, float ty);
499 
500  /**
501  Sets the transform to scale matrix.
502  */
503  static void transformScale(float dst[6], float sx, float sy);
504 
505  /**
506  Sets the transform to rotate matrix. Angle is specified in radians.
507  */
508  static void transformRotate(float dst[6], float a);
509 
510  /**
511  Sets the transform to skew-x matrix. Angle is specified in radians.
512  */
513  static void transformSkewX(float dst[6], float a);
514 
515  /**
516  Sets the transform to skew-y matrix. Angle is specified in radians.
517  */
518  static void transformSkewY(float dst[6], float a);
519 
520  /**
521  Sets the transform to the result of multiplication of two transforms, of A = A*B.
522  */
523  static void transformMultiply(float dst[6], const float src[6]);
524 
525  /**
526  Sets the transform to the result of multiplication of two transforms, of A = B*A.
527  */
528  static void transformPremultiply(float dst[6], const float src[6]);
529 
530  /**
531  Sets the destination to inverse of specified transform.
532  Returns 1 if the inverse could be calculated, else 0.
533  */
534  static int transformInverse(float dst[6], const float src[6]);
535 
536  /**
537  Transform a point by given transform.
538  */
539  static void transformPoint(float& dstx, float& dsty, const float xform[6], float srcx, float srcy);
540 
541  /**
542  Convert degrees to radians.
543  */
544  static float degToRad(float deg);
545 
546  /**
547  Convert radians to degrees.
548  */
549  static float radToDeg(float rad);
550 
551  /* --------------------------------------------------------------------
552  * Images */
553 
554  /**
555  Creates image by loading it from the disk from specified file name.
556  */
557  NanoImage::Handle createImageFromFile(const char* filename, ImageFlags imageFlags);
558 
559  /**
560  Creates image by loading it from the disk from specified file name.
561  Overloaded function for convenience.
562  @see ImageFlags
563  */
564  NanoImage::Handle createImageFromFile(const char* filename, int imageFlags);
565 
566  /**
567  Creates image by loading it from the specified chunk of memory.
568  */
569  NanoImage::Handle createImageFromMemory(uchar* data, uint dataSize, ImageFlags imageFlags);
570 
571  /**
572  Creates image by loading it from the specified chunk of memory.
573  Overloaded function for convenience.
574  @see ImageFlags
575  */
576  NanoImage::Handle createImageFromMemory(uchar* data, uint dataSize, int imageFlags);
577 
578  /**
579  Creates image from specified image data.
580  */
581  NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar* data, ImageFlags imageFlags);
582 
583  /**
584  Creates image from specified image data.
585  Overloaded function for convenience.
586  @see ImageFlags
587  */
588  NanoImage::Handle createImageFromRGBA(uint w, uint h, const uchar* data, int imageFlags);
589 
590  /**
591  Creates image from an OpenGL texture handle.
592  */
593  NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, ImageFlags imageFlags, bool deleteTexture = false);
594 
595  /**
596  Creates image from an OpenGL texture handle.
597  Overloaded function for convenience.
598  @see ImageFlags
599  */
600  NanoImage::Handle createImageFromTextureHandle(GLuint textureId, uint w, uint h, int imageFlags, bool deleteTexture = false);
601 
602  /* --------------------------------------------------------------------
603  * Paints */
604 
605  /**
606  Creates and returns a linear gradient. Parameters (sx,sy)-(ex,ey) specify the start and end coordinates
607  of the linear gradient, icol specifies the start color and ocol the end color.
608  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
609  */
610  Paint linearGradient(float sx, float sy, float ex, float ey, const Color& icol, const Color& ocol);
611 
612  /**
613  Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering
614  drop shadows or highlights for boxes. Parameters (x,y) define the top-left corner of the rectangle,
615  (w,h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry
616  the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient.
617  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
618  */
619  Paint boxGradient(float x, float y, float w, float h, float r, float f, const Color& icol, const Color& ocol);
620 
621  /**
622  Creates and returns a radial gradient. Parameters (cx,cy) specify the center, inr and outr specify
623  the inner and outer radius of the gradient, icol specifies the start color and ocol the end color.
624  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
625  */
626  Paint radialGradient(float cx, float cy, float inr, float outr, const Color& icol, const Color& ocol);
627 
628  /**
629  Creates and returns an image pattern. Parameters (ox,oy) specify the left-top location of the image pattern,
630  (ex,ey) the size of one image, angle rotation around the top-left corner, image is handle to the image to render.
631  The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint().
632  */
633  Paint imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage& image, float alpha);
634 
635  /* --------------------------------------------------------------------
636  * Scissoring */
637 
638  /**
639  Sets the current scissor rectangle.
640  The scissor rectangle is transformed by the current transform.
641  */
642  void scissor(float x, float y, float w, float h);
643 
644  /**
645  Intersects current scissor rectangle with the specified rectangle.
646  The scissor rectangle is transformed by the current transform.
647  Note: in case the rotation of previous scissor rect differs from
648  the current one, the intersection will be done between the specified
649  rectangle and the previous scissor rectangle transformed in the current
650  transform space. The resulting shape is always rectangle.
651  */
652  void intersectScissor(float x, float y, float w, float h);
653 
654  /**
655  Reset and disables scissoring.
656  */
657  void resetScissor();
658 
659  /* --------------------------------------------------------------------
660  * Paths */
661 
662  /**
663  Clears the current path and sub-paths.
664  */
665  void beginPath();
666 
667  /**
668  Starts new sub-path with specified point as first point.
669  */
670  void moveTo(float x, float y);
671 
672  /**
673  Adds line segment from the last point in the path to the specified point.
674  */
675  void lineTo(float x, float y);
676 
677  /**
678  Adds cubic bezier segment from last point in the path via two control points to the specified point.
679  */
680  void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y);
681 
682  /**
683  Adds quadratic bezier segment from last point in the path via a control point to the specified point.
684  */
685  void quadTo(float cx, float cy, float x, float y);
686 
687  /**
688  Adds an arc segment at the corner defined by the last path point, and two specified points.
689  */
690  void arcTo(float x1, float y1, float x2, float y2, float radius);
691 
692  /**
693  Closes current sub-path with a line segment.
694  */
695  void closePath();
696 
697  /**
698  Sets the current sub-path winding.
699  */
700  void pathWinding(Winding dir);
701 
702  /**
703  Creates new circle arc shaped sub-path. The arc center is at cx,cy, the arc radius is r,
704  and the arc is drawn from angle a0 to a1, and swept in direction dir (NVG_CCW or NVG_CW).
705  Angles are specified in radians.
706  */
707  void arc(float cx, float cy, float r, float a0, float a1, Winding dir);
708 
709  /**
710  Creates new rectangle shaped sub-path.
711  */
712  void rect(float x, float y, float w, float h);
713 
714  /**
715  Creates new rounded rectangle shaped sub-path.
716  */
717  void roundedRect(float x, float y, float w, float h, float r);
718 
719  /**
720  Creates new ellipse shaped sub-path.
721  */
722  void ellipse(float cx, float cy, float rx, float ry);
723 
724  /**
725  Creates new circle shaped sub-path.
726  */
727  void circle(float cx, float cy, float r);
728 
729  /**
730  Fills the current path with current fill style.
731  */
732  void fill();
733 
734  /**
735  Fills the current path with current stroke style.
736  */
737  void stroke();
738 
739  /* --------------------------------------------------------------------
740  * Text */
741 
742  /**
743  Creates font by loading it from the disk from specified file name.
744  Returns handle to the font.
745  */
746  FontId createFontFromFile(const char* name, const char* filename);
747 
748  /**
749  Creates font by loading it from the specified memory chunk.
750  Returns handle to the font.
751  */
752  FontId createFontFromMemory(const char* name, const uchar* data, uint dataSize, bool freeData);
753 
754  /**
755  Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found.
756  */
757  FontId findFont(const char* name);
758 
759  /**
760  Sets the font size of current text style.
761  */
762  void fontSize(float size);
763 
764  /**
765  Sets the blur of current text style.
766  */
767  void fontBlur(float blur);
768 
769  /**
770  Sets the letter spacing of current text style.
771  */
772  void textLetterSpacing(float spacing);
773 
774  /**
775  Sets the proportional line height of current text style. The line height is specified as multiple of font size.
776  */
777  void textLineHeight(float lineHeight);
778 
779  /**
780  Sets the text align of current text style.
781  */
782  void textAlign(Align align);
783 
784  /**
785  Sets the text align of current text style.
786  Overloaded function for convenience.
787  @see Align
788  */
789  void textAlign(int align);
790 
791  /**
792  Sets the font face based on specified id of current text style.
793  */
794  void fontFaceId(FontId font);
795 
796  /**
797  Sets the font face based on specified name of current text style.
798  */
799  void fontFace(const char* font);
800 
801  /**
802  Draws text string at specified location. If end is specified only the sub-string up to the end is drawn.
803  */
804  float text(float x, float y, const char* string, const char* end);
805 
806  /**
807  Draws multi-line text string at specified location wrapped at the specified width.
808  If end is specified only the sub-string up to the end is drawn.
809  White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
810  Words longer than the max width are slit at nearest character (i.e. no hyphenation).
811  */
812  void textBox(float x, float y, float breakRowWidth, const char* string, const char* end = nullptr);
813 
814  /**
815  Measures the specified text string. The bounds value are [xmin,ymin, xmax,ymax].
816  Returns the horizontal advance of the measured text (i.e. where the next character should drawn).
817  Measured values are returned in local coordinate space.
818  */
819  float textBounds(float x, float y, const char* string, const char* end, Rectangle<float>& bounds);
820 
821  /**
822  Measures the specified multi-text string. Parameter bounds should be a pointer to float[4],
823  if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]
824  Measured values are returned in local coordinate space.
825  */
826  void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float bounds[4]);
827 
828  /**
829  Calculates the glyph x positions of the specified text. If end is specified only the sub-string will be used.
830  Measured values are returned in local coordinate space.
831  */
832  int textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition& positions, int maxPositions);
833 
834  /**
835  Returns the vertical metrics based on the current text style.
836  Measured values are returned in local coordinate space.
837  */
838  void textMetrics(float* ascender, float* descender, float* lineh);
839 
840  /**
841  Breaks the specified text into lines. If end is specified only the sub-string will be used.
842  White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
843  Words longer than the max width are slit at nearest character (i.e. no hyphenation).
844  */
845  int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow& rows, int maxRows);
846 
847  /**
848  Load DPF's internal shared resources for this NanoVG class.
849  */
850  virtual void loadSharedResources();
851 
852 private:
853  NVGcontext* const fContext;
854  bool fInFrame;
855  bool fIsSubWidget;
856  friend class BlendishWidget;
857 
858  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoVG)
859 };
860 
861 // -----------------------------------------------------------------------
862 // NanoWidget
863 
864 /**
865  NanoVG Widget class.
866 
867  This class implements the NanoVG drawing API inside a DGL Widget.
868  The drawing function onDisplay() is implemented internally but a
869  new onNanoDisplay() needs to be overridden instead.
870  */
871 class NanoWidget : public Widget,
872  public NanoVG
873 {
874 public:
875  /**
876  Constructor.
877  @see CreateFlags
878  */
879  explicit NanoWidget(Window& parent, int flags = CREATE_ANTIALIAS);
880 
881  /**
882  Constructor for a subwidget.
883  */
884  explicit NanoWidget(Widget* groupWidget, int flags = CREATE_ANTIALIAS);
885 
886  /**
887  Constructor for a subwidget, reusing a NanoVG context.
888  */
889  explicit NanoWidget(NanoWidget* groupWidget);
890 
891  /**
892  Destructor.
893  */
894  virtual ~NanoWidget();
895 
896 protected:
897  /**
898  New virtual onDisplay function.
899  @see onDisplay
900  */
901  virtual void onNanoDisplay() = 0;
902 
903 private:
904  struct PrivateData;
905  PrivateData* const nData;
906 
907  /**
908  Widget display function.
909  Implemented internally to wrap begin/endFrame() automatically.
910  */
911  void onDisplay() override;
912 
913  // these should not be used
914  void beginFrame(uint,uint) {}
915  void beginFrame(uint,uint,float) {}
916  void beginFrame(Widget*) {}
917  void cancelFrame() {}
918  void endFrame() {}
919 
920  DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoWidget)
921 };
922 
923 // -----------------------------------------------------------------------
924 
925 END_NAMESPACE_DGL
926 
927 #endif // DGL_NANO_WIDGET_HPP_INCLUDED
NVGcontext * getContext() const noexcept
Definition: NanoVG.hpp:316
Definition: NanoVG.hpp:286
Definition: NanoVG.hpp:45
Definition: NanoVG.hpp:871
Definition: Window.hpp:30
Definition: Color.hpp:31
Definition: Geometry.hpp:30
Definition: NanoVG.hpp:262
Definition: NanoVG.hpp:203
Size< uint > getSize() const noexcept
Definition: NanoVG.hpp:280
Definition: Widget.hpp:59
NanoImage & operator=(const Handle &handle)
GLuint getTextureHandle() const
bool isValid() const noexcept
CreateFlags
Definition: NanoVG.hpp:206