view libinterp/corefcn/txt-eng-ft.cc @ 19593:446c46af4b42 stable

strip trailing whitespace from most source files * Makefile.am, NEWS, build-aux/common.mk, configure.ac, doc/Makefile.am, doc/doxyhtml/Makefile.am, doc/interpreter/Makefile.am, doc/interpreter/arith.txi, doc/interpreter/audio.txi, doc/interpreter/basics.txi, doc/interpreter/bugs.txi, doc/interpreter/container.txi, doc/interpreter/cp-idx.txi, doc/interpreter/data.txi, doc/interpreter/debug.txi, doc/interpreter/diagperm.txi, doc/interpreter/diffeq.txi, doc/interpreter/doccheck/README, doc/interpreter/doccheck/spellcheck, doc/interpreter/emacs.txi, doc/interpreter/errors.txi, doc/interpreter/eval.txi, doc/interpreter/expr.txi, doc/interpreter/external.txi, doc/interpreter/fn-idx.txi, doc/interpreter/func.txi, doc/interpreter/geometry.txi, doc/interpreter/geometryimages.m, doc/interpreter/gpl.txi, doc/interpreter/grammar.txi, doc/interpreter/gui.txi, doc/interpreter/image.txi, doc/interpreter/install.txi, doc/interpreter/interp.txi, doc/interpreter/interpimages.m, doc/interpreter/intro.txi, doc/interpreter/io.txi, doc/interpreter/java.txi, doc/interpreter/linalg.txi, doc/interpreter/macros.texi, doc/interpreter/matrix.txi, doc/interpreter/munge-texi.pl, doc/interpreter/nonlin.txi, doc/interpreter/numbers.txi, doc/interpreter/obsolete.txi, doc/interpreter/octave-config.1, doc/interpreter/octave.texi, doc/interpreter/oop.txi, doc/interpreter/op-idx.txi, doc/interpreter/optim.txi, doc/interpreter/package.txi, doc/interpreter/plot.txi, doc/interpreter/poly.txi, doc/interpreter/preface.txi, doc/interpreter/quad.txi, doc/interpreter/set.txi, doc/interpreter/signal.txi, doc/interpreter/sparse.txi, doc/interpreter/sparseimages.m, doc/interpreter/splineimages.m, doc/interpreter/stats.txi, doc/interpreter/stmt.txi, doc/interpreter/strings.txi, doc/interpreter/system.txi, doc/interpreter/testfun.txi, doc/interpreter/tips.txi, doc/interpreter/var.txi, doc/interpreter/vectorize.txi, doc/liboctave/Makefile.am, doc/liboctave/array.texi, doc/liboctave/bugs.texi, doc/liboctave/cp-idx.texi, doc/liboctave/dae.texi, doc/liboctave/diffeq.texi, doc/liboctave/error.texi, doc/liboctave/factor.texi, doc/liboctave/fn-idx.texi, doc/liboctave/gpl.texi, doc/liboctave/install.texi, doc/liboctave/intro.texi, doc/liboctave/liboctave.texi, doc/liboctave/matvec.texi, doc/liboctave/nleqn.texi, doc/liboctave/nlfunc.texi, doc/liboctave/ode.texi, doc/liboctave/optim.texi, doc/liboctave/preface.texi, doc/liboctave/quad.texi, doc/liboctave/range.texi, doc/refcard/Makefile.am, doc/refcard/refcard.tex, etc/HACKING, etc/NEWS.1, etc/NEWS.2, etc/NEWS.3, etc/OLD-ChangeLogs/ChangeLog, etc/OLD-ChangeLogs/doc-ChangeLog, etc/OLD-ChangeLogs/scripts-ChangeLog, etc/OLD-ChangeLogs/src-ChangeLog, etc/OLD-ChangeLogs/test-ChangeLog, etc/PROJECTS, etc/README.Cygwin, etc/README.MacOS, etc/README.MinGW, etc/README.gnuplot, etc/gdbinit, etc/icons/Makefile.am, examples/@polynomial/end.m, examples/@polynomial/subsasgn.m, examples/Makefile.am, examples/standalonebuiltin.cc, libgui/Makefile.am, libgui/qterminal/libqterminal/README, libgui/qterminal/libqterminal/unix/BlockArray.cpp, libgui/qterminal/libqterminal/unix/BlockArray.h, libgui/qterminal/libqterminal/unix/Character.h, libgui/qterminal/libqterminal/unix/CharacterColor.h, libgui/qterminal/libqterminal/unix/Emulation.cpp, libgui/qterminal/libqterminal/unix/Emulation.h, libgui/qterminal/libqterminal/unix/Filter.cpp, libgui/qterminal/libqterminal/unix/Filter.h, libgui/qterminal/libqterminal/unix/History.cpp, libgui/qterminal/libqterminal/unix/History.h, libgui/qterminal/libqterminal/unix/KeyboardTranslator.cpp, libgui/qterminal/libqterminal/unix/KeyboardTranslator.h, libgui/qterminal/libqterminal/unix/LineFont.h, libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.cpp, libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.h, libgui/qterminal/libqterminal/unix/Screen.cpp, libgui/qterminal/libqterminal/unix/Screen.h, libgui/qterminal/libqterminal/unix/ScreenWindow.cpp, libgui/qterminal/libqterminal/unix/ScreenWindow.h, libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.cpp, libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.h, libgui/qterminal/libqterminal/unix/Vt102Emulation.h, libgui/qterminal/libqterminal/win32/QWinTerminalImpl.cpp, libgui/qterminal/qterminal/main.cpp, libgui/src/m-editor/file-editor-tab.cc, libgui/src/octave-gui.cc, libgui/src/octave-qt-link.cc, libinterp/corefcn/data.cc, libinterp/corefcn/defun-int.h, libinterp/corefcn/det.cc, libinterp/corefcn/gl2ps-renderer.cc, libinterp/corefcn/graphics.cc, libinterp/corefcn/graphics.in.h, libinterp/corefcn/ls-mat5.cc, libinterp/corefcn/lu.cc, libinterp/corefcn/oct-tex-parser.yy, libinterp/corefcn/oct-tex-symbols.in, libinterp/corefcn/quadcc.cc, libinterp/corefcn/zfstream.cc, libinterp/dldfcn/__eigs__.cc, libinterp/dldfcn/__voronoi__.cc, libinterp/gendoc.pl, libinterp/genprops.awk, libinterp/mk-errno-list, libinterp/mk-pkg-add, libinterp/mkbuiltins, libinterp/mkdefs, libinterp/mkdocs, libinterp/mkops, libinterp/octave-value/ov-java.cc, libinterp/parse-tree/lex.ll, libinterp/parse-tree/oct-parse.in.yy, libinterp/parse-tree/octave.gperf, liboctave/Makefile.am, liboctave/array/Array.cc, liboctave/array/module.mk, liboctave/cruft/daspk/datv.f, liboctave/cruft/daspk/dcnst0.f, liboctave/cruft/daspk/dcnstr.f, liboctave/cruft/daspk/ddasic.f, liboctave/cruft/daspk/ddasid.f, liboctave/cruft/daspk/ddasik.f, liboctave/cruft/daspk/ddaspk.f, liboctave/cruft/daspk/ddstp.f, liboctave/cruft/daspk/ddwnrm.f, liboctave/cruft/daspk/dfnrmd.f, liboctave/cruft/daspk/dfnrmk.f, liboctave/cruft/daspk/dhels.f, liboctave/cruft/daspk/dheqr.f, liboctave/cruft/daspk/dinvwt.f, liboctave/cruft/daspk/dlinsd.f, liboctave/cruft/daspk/dlinsk.f, liboctave/cruft/daspk/dmatd.f, liboctave/cruft/daspk/dnedd.f, liboctave/cruft/daspk/dnedk.f, liboctave/cruft/daspk/dnsd.f, liboctave/cruft/daspk/dnsid.f, liboctave/cruft/daspk/dnsik.f, liboctave/cruft/daspk/dnsk.f, liboctave/cruft/daspk/dorth.f, liboctave/cruft/daspk/dslvd.f, liboctave/cruft/daspk/dslvk.f, liboctave/cruft/daspk/dspigm.f, liboctave/cruft/daspk/dyypnw.f, liboctave/cruft/dasrt/ddasrt.f, liboctave/cruft/dasrt/drchek.f, liboctave/cruft/dassl/ddaslv.f, liboctave/cruft/dassl/ddassl.f, liboctave/cruft/misc/blaswrap.c, liboctave/cruft/misc/module.mk, liboctave/cruft/odepack/cfode.f, liboctave/cruft/odepack/dlsode.f, liboctave/cruft/odepack/ewset.f, liboctave/cruft/odepack/intdy.f, liboctave/cruft/odepack/prepj.f, liboctave/cruft/odepack/sintdy.f, liboctave/cruft/odepack/slsode.f, liboctave/cruft/odepack/solsy.f, liboctave/cruft/odepack/ssolsy.f, liboctave/cruft/odepack/stode.f, liboctave/cruft/odepack/vnorm.f, liboctave/cruft/ranlib/Basegen.doc, liboctave/cruft/ranlib/README, liboctave/cruft/ranlib/genbet.f, liboctave/cruft/ranlib/genexp.f, liboctave/cruft/ranlib/gennch.f, liboctave/cruft/ranlib/gennf.f, liboctave/cruft/ranlib/gennor.f, liboctave/cruft/ranlib/getsd.f, liboctave/cruft/ranlib/initgn.f, liboctave/cruft/ranlib/phrtsd.f, liboctave/cruft/ranlib/randlib.fdoc, liboctave/cruft/ranlib/setsd.f, liboctave/cruft/ranlib/tstgmn.for, liboctave/cruft/ranlib/tstmid.for, liboctave/cruft/slatec-fn/atanh.f, liboctave/cruft/slatec-fn/datanh.f, liboctave/cruft/slatec-fn/xgmainc.f, liboctave/cruft/slatec-fn/xsgmainc.f, liboctave/numeric/module.mk, liboctave/operators/mk-ops.awk, liboctave/operators/mx-ops, liboctave/operators/sparse-mk-ops.awk, liboctave/operators/sparse-mx-ops, liboctave/operators/vx-ops, liboctave/util/module.mk, run-octave.in, scripts/@ftp/ftp.m, scripts/audio/wavread.m, scripts/deprecated/java_convert_matrix.m, scripts/deprecated/java_debug.m, scripts/deprecated/java_invoke.m, scripts/deprecated/java_new.m, scripts/deprecated/java_unsigned_conversion.m, scripts/deprecated/javafields.m, scripts/deprecated/javamethods.m, scripts/deprecated/shell_cmd.m, scripts/general/accumarray.m, scripts/general/display.m, scripts/general/fieldnames.m, scripts/general/interp1.m, scripts/general/interp2.m, scripts/general/interp3.m, scripts/general/isa.m, scripts/general/methods.m, scripts/general/sortrows.m, scripts/geometry/convhull.m, scripts/geometry/delaunay.m, scripts/geometry/delaunay3.m, scripts/geometry/delaunayn.m, scripts/geometry/griddata.m, scripts/geometry/griddatan.m, scripts/geometry/voronoi.m, scripts/geometry/voronoin.m, scripts/gui/guihandles.m, scripts/gui/inputdlg.m, scripts/gui/listdlg.m, scripts/gui/msgbox.m, scripts/gui/questdlg.m, scripts/gui/uigetfile.m, scripts/gui/waitbar.m, scripts/gui/warndlg.m, scripts/help/doc.m, scripts/help/help.m, scripts/help/type.m, scripts/image/bone.m, scripts/image/cmpermute.m, scripts/image/cmunique.m, scripts/image/colorcube.m, scripts/image/colormap.m, scripts/image/contrast.m, scripts/image/gray2ind.m, scripts/image/image.m, scripts/image/imshow.m, scripts/image/ind2gray.m, scripts/image/jet.m, scripts/image/rgb2ntsc.m, scripts/image/spinmap.m, scripts/io/importdata.m, scripts/io/strread.m, scripts/io/textread.m, scripts/io/textscan.m, scripts/java/java_get.m, scripts/java/java_set.m, scripts/java/javaaddpath.m, scripts/java/javaclasspath.m, scripts/java/javamem.m, scripts/linear-algebra/linsolve.m, scripts/linear-algebra/qzhess.m, scripts/miscellaneous/debug.m, scripts/miscellaneous/desktop.m, scripts/miscellaneous/dir.m, scripts/miscellaneous/dos.m, scripts/miscellaneous/edit.m, scripts/miscellaneous/fact.m, scripts/miscellaneous/getappdata.m, scripts/miscellaneous/inputname.m, scripts/miscellaneous/license.m, scripts/miscellaneous/ls_command.m, scripts/miscellaneous/run.m, scripts/miscellaneous/setfield.m, scripts/miscellaneous/unix.m, scripts/miscellaneous/ver.m, scripts/mk-pkg-add, scripts/mkdoc.pl, scripts/optimization/fminsearch.m, scripts/optimization/optimset.m, scripts/optimization/sqp.m, scripts/pkg/pkg.m, scripts/pkg/private/create_pkgadddel.m, scripts/pkg/private/fix_depends.m, scripts/pkg/private/install.m, scripts/plot/appearance/axis.m, scripts/plot/appearance/box.m, scripts/plot/appearance/clabel.m, scripts/plot/appearance/daspect.m, scripts/plot/appearance/datetick.m, scripts/plot/appearance/grid.m, scripts/plot/appearance/legend.m, scripts/plot/appearance/orient.m, scripts/plot/appearance/shading.m, scripts/plot/appearance/text.m, scripts/plot/appearance/title.m, scripts/plot/appearance/xlabel.m, scripts/plot/appearance/ylabel.m, scripts/plot/appearance/zlabel.m, scripts/plot/draw/area.m, scripts/plot/draw/bar.m, scripts/plot/draw/barh.m, scripts/plot/draw/colorbar.m, scripts/plot/draw/contour.m, scripts/plot/draw/contour3.m, scripts/plot/draw/contourf.m, scripts/plot/draw/ellipsoid.m, scripts/plot/draw/errorbar.m, scripts/plot/draw/ezcontour.m, scripts/plot/draw/ezcontourf.m, scripts/plot/draw/ezmesh.m, scripts/plot/draw/ezpolar.m, scripts/plot/draw/fill.m, scripts/plot/draw/fplot.m, scripts/plot/draw/hist.m, scripts/plot/draw/meshc.m, scripts/plot/draw/meshz.m, scripts/plot/draw/pareto.m, scripts/plot/draw/patch.m, scripts/plot/draw/peaks.m, scripts/plot/draw/pie.m, scripts/plot/draw/pie3.m, scripts/plot/draw/plot.m, scripts/plot/draw/plotyy.m, scripts/plot/draw/private/__bar__.m, scripts/plot/draw/private/__contour__.m, scripts/plot/draw/private/__errplot__.m, scripts/plot/draw/private/__ezplot__.m, scripts/plot/draw/private/__patch__.m, scripts/plot/draw/private/__stem__.m, scripts/plot/draw/rectangle.m, scripts/plot/draw/ribbon.m, scripts/plot/draw/rose.m, scripts/plot/draw/scatter.m, scripts/plot/draw/scatter3.m, scripts/plot/draw/semilogx.m, scripts/plot/draw/shrinkfaces.m, scripts/plot/draw/sombrero.m, scripts/plot/draw/sphere.m, scripts/plot/draw/stairs.m, scripts/plot/draw/stem.m, scripts/plot/draw/stemleaf.m, scripts/plot/draw/surf.m, scripts/plot/draw/surface.m, scripts/plot/draw/surfc.m, scripts/plot/draw/surfl.m, scripts/plot/draw/surfnorm.m, scripts/plot/draw/tetramesh.m, scripts/plot/draw/trimesh.m, scripts/plot/draw/triplot.m, scripts/plot/draw/trisurf.m, scripts/plot/util/__gnuplot_drawnow__.m, scripts/plot/util/__plt_get_axis_arg__.m, scripts/plot/util/axes.m, scripts/plot/util/clf.m, scripts/plot/util/copyobj.m, scripts/plot/util/figure.m, scripts/plot/util/gcbo.m, scripts/plot/util/graphics_toolkit.m, scripts/plot/util/hggroup.m, scripts/plot/util/meshgrid.m, scripts/plot/util/newplot.m, scripts/plot/util/print.m, scripts/plot/util/private/__add_default_menu__.m, scripts/plot/util/private/__fltk_print__.m, scripts/plot/util/private/__gnuplot_print__.m, scripts/plot/util/private/__print_parse_opts__.m, scripts/plot/util/refreshdata.m, scripts/plot/util/subplot.m, scripts/polynomial/conv.m, scripts/polynomial/poly.m, scripts/polynomial/polyeig.m, scripts/polynomial/polyfit.m, scripts/polynomial/polyval.m, scripts/polynomial/private/__splinefit__.m, scripts/polynomial/spline.m, scripts/prefs/prefdir.m, scripts/prefs/preferences.m, scripts/prefs/private/prefsfile.m, scripts/prefs/rmpref.m, scripts/signal/freqz.m, scripts/signal/module.mk, scripts/sparse/eigs.m, scripts/sparse/pcg.m, scripts/sparse/private/__sprand_impl__.m, scripts/sparse/sprand.m, scripts/sparse/sprandn.m, scripts/sparse/spy.m, scripts/sparse/svds.m, scripts/specfun/expint.m, scripts/specfun/factor.m, scripts/special-matrix/gallery.m, scripts/special-matrix/hankel.m, scripts/special-matrix/toeplitz.m, scripts/startup/inputrc, scripts/statistics/base/kurtosis.m, scripts/statistics/base/moment.m, scripts/statistics/base/qqplot.m, scripts/statistics/base/var.m, scripts/statistics/distributions/betarnd.m, scripts/statistics/distributions/binoinv.m, scripts/statistics/distributions/binopdf.m, scripts/statistics/distributions/binornd.m, scripts/statistics/distributions/cauchy_rnd.m, scripts/statistics/distributions/chi2rnd.m, scripts/statistics/distributions/discrete_pdf.m, scripts/statistics/distributions/discrete_rnd.m, scripts/statistics/distributions/empirical_rnd.m, scripts/statistics/distributions/exprnd.m, scripts/statistics/distributions/frnd.m, scripts/statistics/distributions/gamrnd.m, scripts/statistics/distributions/geornd.m, scripts/statistics/distributions/hygernd.m, scripts/statistics/distributions/kolmogorov_smirnov_cdf.m, scripts/statistics/distributions/laplace_cdf.m, scripts/statistics/distributions/laplace_pdf.m, scripts/statistics/distributions/logistic_cdf.m, scripts/statistics/distributions/logistic_pdf.m, scripts/statistics/distributions/lognrnd.m, scripts/statistics/distributions/nbincdf.m, scripts/statistics/distributions/nbininv.m, scripts/statistics/distributions/nbinpdf.m, scripts/statistics/distributions/nbinrnd.m, scripts/statistics/distributions/normrnd.m, scripts/statistics/distributions/poissinv.m, scripts/statistics/distributions/poissrnd.m, scripts/statistics/distributions/tinv.m, scripts/statistics/distributions/trnd.m, scripts/statistics/distributions/unidcdf.m, scripts/statistics/distributions/unidpdf.m, scripts/statistics/distributions/unidrnd.m, scripts/statistics/distributions/unifrnd.m, scripts/statistics/distributions/wblrnd.m, scripts/statistics/models/module.mk, scripts/statistics/tests/kruskal_wallis_test.m, scripts/strings/base2dec.m, scripts/strings/deblank.m, scripts/strings/dec2base.m, scripts/strings/dec2bin.m, scripts/strings/dec2hex.m, scripts/strings/mat2str.m, scripts/strings/ostrsplit.m, scripts/strings/regexptranslate.m, scripts/strings/str2num.m, scripts/strings/strcat.m, scripts/strings/strjoin.m, scripts/strings/strsplit.m, scripts/strings/strtok.m, scripts/strings/strtrim.m, scripts/strings/strtrunc.m, scripts/strings/substr.m, scripts/testfun/__run_test_suite__.m, scripts/testfun/speed.m, scripts/testfun/test.m, scripts/time/asctime.m, scripts/time/datenum.m, scripts/time/datevec.m, scripts/time/weekday.m, src/Makefile.am, test/Makefile.am, test/build-bc-overload-tests.sh, test/build-sparse-tests.sh, test/jit.tst, test/line-continue.tst: Strip trailing whitespace.
author John W. Eaton <jwe@octave.org>
date Tue, 20 Jan 2015 08:26:57 -0500
parents 8c33abdd2f9a
children 6a71e5030df5
line wrap: on
line source

/*

Copyright (C) 2009-2013 Michael Goffioul

This file is part of Octave.

Octave is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

Octave is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with Octave; see the file COPYING.  If not, see
<http://www.gnu.org/licenses/>.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#if defined (HAVE_FREETYPE)

#if defined (HAVE_FONTCONFIG)
#include <fontconfig/fontconfig.h>
#endif

#include <clocale>
#include <cwchar>
#include <iostream>
#include <map>
#include <utility>

#include "singleton-cleanup.h"

#include "error.h"
#include "pr-output.h"
#include "txt-eng-ft.h"

// FIXME: maybe issue at most one warning per glyph/font/size/weight
//        combination.

static void
gripe_missing_glyph (FT_ULong c)
{
  warning_with_id ("Octave:missing-glyph",
                   "ft_render: skipping missing glyph for character '%x'",
                   c);
}

static void
gripe_glyph_render (FT_ULong c)
{
  warning_with_id ("Octave:glyph-render",
                   "ft_render: unable to render glyph for character '%x'",
                   c);
}

#ifdef _MSC_VER
// This is just a trick to avoid multiple symbol definitions.
// PermMatrix.h contains a dllexport'ed Array<octave_idx_type>
// that will cause MSVC not to generate a new instantiation and
// use the imported one instead.
#include "PermMatrix.h"
#endif

// Forward declaration
static void ft_face_destroyed (void* object);

class
ft_manager
{
public:
  static bool instance_ok (void)
  {
    bool retval = true;

    if (! instance)
      {
        instance = new ft_manager ();

        if (instance)
          singleton_cleanup_list::add (cleanup_instance);
      }

    if (! instance)
      {
        ::error ("unable to create ft_manager!");

        retval = false;
      }

    return retval;
  }

  static void cleanup_instance (void) { delete instance; instance = 0; }

  static FT_Face get_font (const std::string& name, const std::string& weight,
                           const std::string& angle, double size)
  {
    return (instance_ok ()
            ? instance->do_get_font (name, weight, angle, size)
            : 0);
  }

  static void font_destroyed (FT_Face face)
  {
    if (instance_ok ())
      instance->do_font_destroyed (face);
  }

private:

  static ft_manager *instance;

  typedef std::pair<std::string, double> ft_key;
  typedef std::map<ft_key, FT_Face> ft_cache;

  // Cache the fonts loaded by freetype. This cache only contains
  // weak references to the fonts, strong references are only present
  // in class ft_render.
  ft_cache cache;

private:

  // No copying!

  ft_manager (const ft_manager&);

  ft_manager& operator = (const ft_manager&);

  ft_manager (void)
    : library (), freetype_initialized (false), fontconfig_initialized (false)
  {
    if (FT_Init_FreeType (&library))
      ::error ("unable to initialize freetype library");
    else
      freetype_initialized = true;

#if defined (HAVE_FONTCONFIG)
    if (! FcInit ())
      ::error ("unable to initialize fontconfig library");
    else
      fontconfig_initialized = true;
#endif
  }

  ~ft_manager (void)
  {
    if (freetype_initialized)
      FT_Done_FreeType (library);

#if defined (HAVE_FONTCONFIG)
    // FIXME: Skip the call to FcFini because it can trigger the assertion
    //
    //   octave: fccache.c:507: FcCacheFini: Assertion 'fcCacheChains[i] == ((void *)0)' failed.
    //
    // if (fontconfig_initialized)
    //   FcFini ();
#endif
  }


  FT_Face do_get_font (const std::string& name, const std::string& weight,
                       const std::string& angle, double size)
  {
    FT_Face retval = 0;

#if HAVE_FT_REFERENCE_FACE
    // Look first into the font cache, then use fontconfig. If the font
    // is present in the cache, simply add a reference and return it.

    ft_key key (name + ":" + weight + ":" + angle, size);
    ft_cache::const_iterator it = cache.find (key);

    if (it != cache.end ())
      {
        FT_Reference_Face (it->second);
        return it->second;
      }
#endif

    std::string file;

#if defined (HAVE_FONTCONFIG)
    if (fontconfig_initialized)
      {
        int fc_weight, fc_angle;

        if (weight == "bold")
          fc_weight = FC_WEIGHT_BOLD;
        else if (weight == "light")
          fc_weight = FC_WEIGHT_LIGHT;
        else if (weight == "demi")
          fc_weight = FC_WEIGHT_DEMIBOLD;
        else
          fc_weight = FC_WEIGHT_NORMAL;

        if (angle == "italic")
          fc_angle = FC_SLANT_ITALIC;
        else if (angle == "oblique")
          fc_angle = FC_SLANT_OBLIQUE;
        else
          fc_angle = FC_SLANT_ROMAN;

        FcPattern *pat = FcPatternCreate ();

        FcPatternAddString (pat, FC_FAMILY,
                            (reinterpret_cast<const FcChar8*>
                             (name == "*" ? "sans" : name.c_str ())));

        FcPatternAddInteger (pat, FC_WEIGHT, fc_weight);
        FcPatternAddInteger (pat, FC_SLANT, fc_angle);
        FcPatternAddDouble (pat, FC_PIXEL_SIZE, size);

        if (FcConfigSubstitute (0, pat, FcMatchPattern))
          {
            FcResult res;
            FcPattern *match;

            FcDefaultSubstitute (pat);
            match = FcFontMatch (0, pat, &res);

            // FIXME: originally, this test also required that
            // res != FcResultNoMatch.  Is that really needed?
            if (match)
              {
                unsigned char *tmp;

                FcPatternGetString (match, FC_FILE, 0, &tmp);
                file = reinterpret_cast<char*> (tmp);
              }
            else
              ::warning ("could not match any font: %s-%s-%s-%g",
                         name.c_str (), weight.c_str (), angle.c_str (),
                         size);

            if (match)
              FcPatternDestroy (match);
          }

        FcPatternDestroy (pat);
      }
#endif

    if (file.empty ())
      {
#ifdef __WIN32__
        file = "C:/WINDOWS/Fonts/verdana.ttf";
#else
        // FIXME: find a "standard" font for UNIX platforms
#endif
      }

    if (! file.empty ())
      {
        if (FT_New_Face (library, file.c_str (), 0, &retval))
          ::warning ("ft_manager: unable to load font: %s", file.c_str ());
#if HAVE_FT_REFERENCE_FACE
        else
          {
            // Install a finalizer to notify ft_manager that the font is
            // being destroyed. The class ft_manager only keeps weak
            // references to font objects.

            retval->generic.data = new ft_key (key);
            retval->generic.finalizer = ft_face_destroyed;

            // Insert loaded font into the cache.

            cache[key] = retval;
          }
#endif
      }

    return retval;
  }

  void do_font_destroyed (FT_Face face)
  {
    if (face->generic.data)
      {
        ft_key* pkey = reinterpret_cast<ft_key*> (face->generic.data);

        cache.erase (*pkey);
        delete pkey;
        face->generic.data = 0;
      }
  }

private:
  FT_Library library;
  bool freetype_initialized;
  bool fontconfig_initialized;
};

ft_manager* ft_manager::instance = 0;

static void
ft_face_destroyed (void* object)
{ ft_manager::font_destroyed (reinterpret_cast<FT_Face> (object)); }

// ---------------------------------------------------------------------------

ft_render::ft_render (void)
  : text_processor (), font (), bbox (1, 4, 0.0), halign (0), xoffset (0),
    line_yoffset (0), yoffset (0), mode (MODE_BBOX),
    color (dim_vector (1, 3), 0)
{
}

ft_render::~ft_render (void)
{
}

void
ft_render::set_font (const std::string& name, const std::string& weight,
                     const std::string& angle, double size)
{
  // FIXME: take "fontunits" into account

  font = ft_font (name, weight, angle, size, 0);
}

void
ft_render::push_new_line (void)
{
  switch (mode)
    {
    case MODE_BBOX:
      {
        // Create a new bbox entry based on the current font.

        FT_Face face = font.get_face ();

        if (face)
          {
            int asc = face->size->metrics.ascender >> 6;
            int desc = face->size->metrics.descender >> 6;
            int h = face->size->metrics.height >> 6;

            Matrix bb (1, 5, 0.0);

            bb(1) = desc;
            bb(3) = asc - desc;
            bb(4) = h;

            line_bbox.push_back (bb);

            xoffset = yoffset = 0;
          }
      }
      break;

    case MODE_RENDER:
      {
        // Move to the next line bbox, adjust xoffset based on alignment
        // and yoffset based on the old and new line bbox.

        Matrix old_bbox = line_bbox.front ();
        line_bbox.pop_front ();
        Matrix new_bbox = line_bbox.front ();

        xoffset = compute_line_xoffset (new_bbox);
        line_yoffset += (old_bbox(1) - (new_bbox(1) + new_bbox(3)));
        yoffset = 0;
      }
      break;
    }
}

int
ft_render::compute_line_xoffset (const Matrix& lb) const
{
  if (! bbox.is_empty ())
    {
      switch (halign)
        {
        case 0:
          return 0;
        case 1:
          return (bbox(2) - lb(2)) / 2;
        case 2:
          return (bbox(2) - lb(2));
        }
    }

  return 0;
}

void
ft_render::compute_bbox (void)
{
  // Stack the various line bbox together and compute the final
  // bounding box for the entire text string.

  bbox = Matrix ();

  switch (line_bbox.size ())
    {
    case 0:
      break;
    case 1:
      bbox = line_bbox.front ().extract (0, 0, 0, 3);
      break;
    default:
      for (std::list<Matrix>::const_iterator it = line_bbox.begin ();
           it != line_bbox.end (); ++it)
        {
          if (bbox.is_empty ())
            bbox = it->extract (0, 0, 0, 3);
          else
            {
              bbox(1) -= (*it)(3);
              bbox(3) += (*it)(3);
              bbox(2) = xmax (bbox(2), (*it)(2));
            }
        }
      break;
    }
}

void
ft_render::update_line_bbox (void)
{
  // Called after a font change, when in MODE_BBOX mode, to update the
  // current line bbox with the new font metrics. This also includes the
  // current yoffset, that is the offset of the current glyph's baseline
  // the line's baseline.

  if (mode == MODE_BBOX)
    {
      int asc = font.get_face ()->size->metrics.ascender >> 6;
      int desc = font.get_face ()->size->metrics.descender >> 6;

      Matrix& bb = line_bbox.front ();

      if ((yoffset + desc) < bb(1))
        {
          // The new font goes below the bottom of the current bbox.

          int delta = bb(1) - (yoffset + desc);

          bb(1) -= delta;
          bb(3) += delta;
        }

      if ((yoffset + asc) > (bb(1) + bb(3)))
        {
          // The new font goes above the top of the current bbox.

          int delta = (yoffset + asc) - (bb(1) + bb(3));

          bb(3) += delta;
        }
    }
}

void
ft_render::set_mode (int m)
{
  mode = m;

  switch (mode)
    {
    case MODE_BBOX:
      xoffset = line_yoffset = yoffset = 0;
      bbox = Matrix (1, 4, 0.0);
      line_bbox.clear ();
      push_new_line ();
      break;
    case MODE_RENDER:
      if (bbox.numel () != 4)
        {
          ::warning ("ft_render: invalid bounding box, cannot render");

          xoffset = line_yoffset = yoffset = 0;
          pixels = uint8NDArray ();
        }
      else
        {
          pixels = uint8NDArray (dim_vector (4, bbox(2), bbox(3)),
                                 static_cast<uint8_t> (0));
          xoffset = compute_line_xoffset (line_bbox.front ());
          line_yoffset = -bbox(1)-1;
          yoffset = 0;
        }
      break;
    default:
      ::error ("ft_render: invalid mode '%d'", mode);
      break;
    }
}

FT_UInt
ft_render::process_character (FT_ULong code, FT_UInt previous)
{
  FT_Face face = font.get_face ();
  FT_UInt glyph_index = 0;

  if (face)
    {
      glyph_index = FT_Get_Char_Index (face, code);

      if (code != '\n'
          && (! glyph_index
              || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT)))
        {
          glyph_index = 0;
          gripe_missing_glyph (code);
        }
      else
        {
          switch (mode)
            {
            case MODE_RENDER:
              if (code == '\n')
                {
                  glyph_index = FT_Get_Char_Index (face, ' ');
                  if (! glyph_index
                      || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT))
                    {
                      glyph_index = 0;
                      gripe_missing_glyph (' ');
                    }
                  else
                    push_new_line ();
                }
              else if (FT_Render_Glyph (face->glyph, FT_RENDER_MODE_NORMAL))
                {
                  glyph_index = 0;
                  gripe_glyph_render (code);
                }
              else
                {
                  FT_Bitmap& bitmap = face->glyph->bitmap;
                  int x0, y0;

                  if (previous)
                    {
                      FT_Vector delta;

                      FT_Get_Kerning (face, previous, glyph_index,
                                      FT_KERNING_DEFAULT, &delta);
                      xoffset += (delta.x >> 6);
                    }

                  x0 = xoffset + face->glyph->bitmap_left;
                  y0 = line_yoffset + yoffset + face->glyph->bitmap_top;

                  // 'w' seems to have a negative -1
                  // face->glyph->bitmap_left, this is so we don't
                  // index out of bound, and assumes we we allocated
                  // the right amount of horizontal space in the bbox.
                  if (x0 < 0)
                    x0 = 0;

                  for (int r = 0; r < bitmap.rows; r++)
                    for (int c = 0; c < bitmap.width; c++)
                      {
                        unsigned char pix = bitmap.buffer[r*bitmap.width+c];
                        if (x0+c < 0 || x0+c >= pixels.dim2 ()
                            || y0-r < 0 || y0-r >= pixels.dim3 ())
                          {
                            //::warning ("ft_render: pixel out of bound (char=%d, (x,y)=(%d,%d), (w,h)=(%d,%d)",
                            //           str[i], x0+c, y0-r, pixels.dim2 (), pixels.dim3 ());
                          }
                        else if (pixels(3, x0+c, y0-r).value () == 0)
                          {
                            pixels(0, x0+c, y0-r) = color(0);
                            pixels(1, x0+c, y0-r) = color(1);
                            pixels(2, x0+c, y0-r) = color(2);
                            pixels(3, x0+c, y0-r) = pix;
                          }
                      }

                  xoffset += (face->glyph->advance.x >> 6);
                }
              break;

            case MODE_BBOX:
              if (code == '\n')
                {
                  glyph_index = FT_Get_Char_Index (face, ' ');
                  if (! glyph_index
                      || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT))
                    {
                      glyph_index = 0;
                      gripe_missing_glyph (' ');
                    }
                  else
                    push_new_line ();
                }
              else
                {
                  Matrix& bb = line_bbox.back ();

                  // If we have a previous glyph, use kerning information.
                  // This usually means moving a bit backward before adding
                  // the next glyph. That is, "delta.x" is usually < 0.
                  if (previous)
                    {
                      FT_Vector delta;

                      FT_Get_Kerning (face, previous, glyph_index,
                                      FT_KERNING_DEFAULT, &delta);

                      xoffset += (delta.x >> 6);
                    }

                  // Extend current X offset box by the width of the current
                  // glyph. Then extend the line bounding box if necessary.

                  xoffset += (face->glyph->advance.x >> 6);
                  bb(2) = xmax (bb(2), xoffset);
                }
              break;
            }
        }
    }

  return glyph_index;
}

void
ft_render::visit (text_element_string& e)
{
  if (font.is_valid ())
    {
      FT_UInt glyph_index, previous = 0;

      std::string str = e.string_value ();
      size_t n = str.length (), curr = 0;
      mbstate_t ps;
      memset (&ps, 0, sizeof (ps));  // Initialize state to 0.
      wchar_t wc;

      while (n > 0)
        {
          size_t r = gnulib::mbrtowc (&wc, str.data () + curr, n, &ps);

          if (r > 0
              && r != static_cast<size_t> (-1)
              && r != static_cast<size_t> (-2))
            {
              n -= r;
              curr += r;

              glyph_index = process_character (wc, previous);

              if (wc == L'\n')
                previous = 0;
              else
                previous = glyph_index;
            }
          else
            {
              if (r != 0)
                ::warning ("ft_render: failed to decode string `%s' with "
                           "locale `%s'", str.c_str (),
                           std::setlocale (LC_CTYPE, 0));
              break;
            }
        }
    }
}

void
ft_render::visit (text_element_list& e)
{
  // Save and restore (after processing the list) the current font and color.

  ft_font saved_font (font);
  uint8NDArray saved_color (color);

  text_processor::visit (e);

  font = saved_font;
  color = saved_color;
}

void
ft_render::visit (text_element_subscript& e)
{
  ft_font saved_font (font);
  int saved_line_yoffset = line_yoffset;
  int saved_yoffset = yoffset;

  set_font (font.get_name (), font.get_weight (), font.get_angle (),
            font.get_size () - 2);

  if (font.is_valid ())
    {
      int h = font.get_face ()->size->metrics.height >> 6;

      // Shifting the baseline by 2/3 the font height seems to produce
      // decent result.
      yoffset -= (h * 2) / 3;

      if (mode == MODE_BBOX)
        update_line_bbox ();
    }

  text_processor::visit (e);

  font = saved_font;
  // If line_yoffset changed, this means we moved to a new line; hence yoffset
  // cannot be restored, because the saved value is not relevant anymore.
  if (line_yoffset == saved_line_yoffset)
    yoffset = saved_yoffset;
}

void
ft_render::visit (text_element_superscript& e)
{
  ft_font saved_font (font);
  int saved_line_yoffset = line_yoffset;
  int saved_yoffset = yoffset;

  set_font (font.get_name (), font.get_weight (), font.get_angle (),
            font.get_size () - 2);

  if (saved_font.is_valid ())
    {
      int s_asc = saved_font.get_face ()->size->metrics.ascender >> 6;

      // Shifting the baseline by 2/3 base font ascender seems to produce
      // decent result.
      yoffset += (s_asc * 2) / 3;

      if (mode == MODE_BBOX)
        update_line_bbox ();
    }

  text_processor::visit (e);

  font = saved_font;
  // If line_yoffset changed, this means we moved to a new line; hence yoffset
  // cannot be restored, because the saved value is not relevant anymore.
  if (line_yoffset == saved_line_yoffset)
    yoffset = saved_yoffset;
}

void
ft_render::visit (text_element_color& e)
{
  if (mode == MODE_RENDER)
    set_color (e.get_color ());
}

void
ft_render::visit (text_element_fontsize& e)
{
  double sz = e.get_fontsize ();

  // FIXME: Matlab documentation says that the font size is expressed
  //        in the text object FontUnit.

  set_font (font.get_name (), font.get_weight (), font.get_angle (), sz);

  if (mode == MODE_BBOX)
    update_line_bbox ();
}

void
ft_render::visit (text_element_fontname& e)
{
  set_font (e.get_fontname (), font.get_weight (), font.get_angle (),
            font.get_size ());

  if (mode == MODE_BBOX)
    update_line_bbox ();
}

void
ft_render::visit (text_element_fontstyle& e)
{
  switch (e.get_fontstyle ())
    {
    case text_element_fontstyle::normal:
      set_font (font.get_name (), "normal", "normal", font.get_size ());
      break;
    case text_element_fontstyle::bold:
      set_font (font.get_name (), "bold", "normal", font.get_size ());
      break;
    case text_element_fontstyle::italic:
      set_font (font.get_name (), "normal", "italic", font.get_size ());
      break;
    case text_element_fontstyle::oblique:
      set_font (font.get_name (), "normal", "oblique", font.get_size ());
      break;
    }

  if (mode == MODE_BBOX)
    update_line_bbox ();
}

void
ft_render::visit (text_element_symbol& e)
{
  uint32_t code = e.get_symbol_code ();

  if (code != text_element_symbol::invalid_code && font.is_valid ())
    process_character (code);
  else if (font.is_valid ())
    ::warning ("ignoring unknown symbol: %d", e.get_symbol ());
}

void
ft_render::visit (text_element_combined& e)
{
  int saved_xoffset = xoffset;
  int max_xoffset = xoffset;

  for (text_element_combined::iterator it = e.begin (); it != e.end (); ++it)
    {
      xoffset = saved_xoffset;
      (*it)->accept (*this);
      max_xoffset = xmax (xoffset, max_xoffset);
    }

  xoffset = max_xoffset;
}

void
ft_render::reset (void)
{
  set_mode (MODE_BBOX);
  set_color (Matrix (1, 3, 0.0));
}

void
ft_render::set_color (Matrix c)
{
  if (c.numel () == 3)
    {
      color(0) = static_cast<uint8_t> (c(0)*255);
      color(1) = static_cast<uint8_t> (c(1)*255);
      color(2) = static_cast<uint8_t> (c(2)*255);
    }
  else
    ::warning ("ft_render::set_color: invalid color");
}

uint8NDArray
ft_render::render (text_element* elt, Matrix& box, int rotation)
{
  set_mode (MODE_BBOX);
  elt->accept (*this);
  compute_bbox ();
  box = bbox;

  set_mode (MODE_RENDER);
  if (pixels.numel () > 0)
    {
      elt->accept (*this);

      switch (rotation)
        {
        case ROTATION_0:
          break;
        case ROTATION_90:
          {
            Array<octave_idx_type> perm (dim_vector (3, 1));
            perm(0) = 0;
            perm(1) = 2;
            perm(2) = 1;
            pixels = pixels.permute (perm);

            Array<idx_vector> idx (dim_vector (3, 1));
            idx(0) = idx_vector (':');
            idx(1) = idx_vector (pixels.dim2 ()-1, -1, -1);
            idx(2) = idx_vector (':');
            pixels = uint8NDArray (pixels.index (idx));
          }
          break;
        case ROTATION_180:
          {
            Array<idx_vector> idx (dim_vector (3, 1));
            idx(0) = idx_vector (':');
            idx(1) = idx_vector (pixels.dim2 ()-1, -1, -1);
            idx(2)=  idx_vector (pixels.dim3 ()-1, -1, -1);
            pixels = uint8NDArray (pixels.index (idx));
          }
          break;
        case ROTATION_270:
          {
            Array<octave_idx_type> perm (dim_vector (3, 1));
            perm(0) = 0;
            perm(1) = 2;
            perm(2) = 1;
            pixels = pixels.permute (perm);

            Array<idx_vector> idx (dim_vector (3, 1));
            idx(0) = idx_vector (':');
            idx(1) = idx_vector (':');
            idx(2) = idx_vector (pixels.dim3 ()-1, -1, -1);
            pixels = uint8NDArray (pixels.index (idx));
          }
          break;
        }
    }

  return pixels;
}

// Note:
// x-extent accurately measures width of glyphs.
// y-extent is overly large because it is measured from baseline-to-baseline.
// Calling routines, such as ylabel, may need to account for this mismatch.

Matrix
ft_render::get_extent (text_element *elt, double rotation)
{
  set_mode (MODE_BBOX);
  elt->accept (*this);
  compute_bbox ();

  Matrix extent (1, 2, 0.0);

  switch (rotation_to_mode (rotation))
    {
    case ROTATION_0:
    case ROTATION_180:
      extent(0) = bbox(2);
      extent(1) = bbox(3);
      break;
    case ROTATION_90:
    case ROTATION_270:
      extent(0) = bbox(3);
      extent(1) = bbox(2);
    }

  return extent;
}

Matrix
ft_render::get_extent (const std::string& txt, double rotation,
                       const caseless_str& interpreter)
{
  text_element *elt = text_parser::parse (txt, interpreter);
  Matrix extent = get_extent (elt, rotation);
  delete elt;

  return extent;
}

int
ft_render::rotation_to_mode (double rotation) const
{
  // Clip rotation to range [0, 360]
  while (rotation < 0)
    rotation += 360.0;
  while (rotation > 360.0)
    rotation -= 360.0;

  if (rotation == 0.0)
    return ROTATION_0;
  else if (rotation == 90.0)
    return ROTATION_90;
  else if (rotation == 180.0)
    return ROTATION_180;
  else if (rotation == 270.0)
    return ROTATION_270;
  else
    return ROTATION_0;
}

void
ft_render::text_to_pixels (const std::string& txt,
                           uint8NDArray& pixels_, Matrix& box,
                           int _halign, int valign, double rotation,
                           const caseless_str& interpreter)
{
  int rot_mode = rotation_to_mode (rotation);

  halign = _halign;

  text_element *elt = text_parser::parse (txt, interpreter);
  pixels_ = render (elt, box, rot_mode);
  delete elt;

  if (pixels_.numel () == 0)
    {
      // nothing to render
      return;
    }

  switch (halign)
    {
    default: box(0) = 0; break;
    case 1: box(0) = -box(2)/2; break;
    case 2: box(0) = -box(2); break;
    }
  switch (valign)
    {
    default: box(1) = 0; break;
    case 1: box(1) = -box(3)/2; break;
    case 2: box(1) = -box(3); break;
    case 3: break;
    case 4: box(1) = -box(3)-box(1); break;
    }

  switch (rot_mode)
    {
    case ROTATION_90:
      std::swap (box(0), box(1));
      std::swap (box(2), box(3));
      box(0) = -box(0)-box(2);
      break;
    case ROTATION_180:
      box(0) = -box(0)-box(2);
      box(1) = -box(1)-box(3);
      break;
    case ROTATION_270:
      std::swap (box(0), box(1));
      std::swap (box(2), box(3));
      box(1) = -box(1)-box(3);
      break;
    }
}

ft_render::ft_font::ft_font (const ft_font& ft)
  : name (ft.name), weight (ft.weight), angle (ft.angle), size (ft.size),
    face (0)
{
#if HAVE_FT_REFERENCE_FACE
  FT_Face ft_face = ft.get_face ();

  if (ft_face && FT_Reference_Face (ft_face) == 0)
    face = ft_face;
#endif
}

ft_render::ft_font&
ft_render::ft_font::operator = (const ft_font& ft)
{
  if (&ft != this)
    {
      name = ft.name;
      weight = ft.weight;
      angle = ft.angle;
      size = ft.size;
      if (face)
        {
          FT_Done_Face (face);
          face = 0;
        }

#if HAVE_FT_REFERENCE_FACE
      FT_Face ft_face = ft.get_face ();

      if (ft_face && FT_Reference_Face (ft_face) == 0)
        face = ft_face;
#endif
    }

  return *this;
}

FT_Face
ft_render::ft_font::get_face (void) const
{
  if (! face && ! name.empty ())
    {
      face = ft_manager::get_font (name, weight, angle, size);

      if (face)
        {
          if (FT_Set_Char_Size (face, 0, size*64, 0, 0))
            ::warning ("ft_render: unable to set font size to %g", size);
        }
      else
        ::warning ("ft_render: unable to load appropriate font");
    }

  return face;
}

#endif // HAVE_FREETYPE