# Fonts

A font system has been implemented in the git branch home/cparker/font_fun. This system was initially designed by Chad Parker. The initial set of fonts were converted for PCB by Erich Heinzle. With this system, the font of a design can be easily changed, and multiple fonts can be used in the same design. This system also reduces the need to store font data in saved design files, because a font name should be forever. If a font ever changes, it should be given a new name. So, saved designs can reference only the font name without having to worry about the font changing and a design being different when it is next opened.

geda:pcbwithmultifonts.png

# Usage

## Getting the Feature Branch

To test the font system, check out the feature branch from git. Switch to the feature branch with

    git checkout home/cparker/font_fun

reconfigure if necessary and build. Then, run pcb by executing the pcbtest.sh script in the src directory. This is important because it sets the font path so that pcb can load some of the included fonts.

## Font Settings

All font settings can be viewed and edited from the Fonts tab in the preferences window.

geda:fontprefswindow.png

There are three font related options that can be configured:

- "Save font data in files"
  When enabled, this will save the font of text objects in saved design files. If disabled, it will not, and the design will be backwards compatible with older versions of pcb.
- "Save current system font as symbols in pcb files (old format)."
  This option is only available when "Save font data in files" is disabled. This option does exactly what it says. This is how you can save a font in a design file that is compatible with older versions of pcb.
- "Embed used fonts in pcb files"
  This option is only available when "Save font data in files" is enabled. This option will store the font information of every font used in the design into the saved pcb file. This makes the pcb file portable to other systems that may not have the same fonts installed, or a different version of a font installed.

There are two fonts that can be configured:

- System font:
  The system font is used for all new objects that are added to the design, and also for system generated text such as pin numbers and pin functions. System font information is not stored in saved designs.
- PCB font:
  The PCB font is stored in saved files as the default font for a design. It is used for any texts that cannot be assigned a font, presently reference designators. It's also the font that is assigned to any texts that don't have a specific font assigned when the design is loaded. The system font is set to this after loading.

If a design is loaded and requests a font that is not on the system, it will issue a warning to the message log and the text will be displayed using the system font. If the system font is changed, it will also change. (This behavior should be reviewed.)

The fonts can also be manipulated by executing Actions.

## Font Libraries

There are two font libraries:

- System Font Library:
  This library contains all of the fonts that pcb knows about that are stored on the local system. Fonts can be loaded and unloaded from this library using actions. This functionality is not yet available in the preferences menu, but it is planned to be eventually.
- Embedded Font Library:
  This library contains the fonts that are stored in the pcb file of the current design. The only control a user has over this library is in the fonts that he or she chooses to use in the design. This library is populated whenever a pcb file is loaded. If you load a file, add an object with a different font, and choose to save the file with fonts embedded, the additional fonts will be saved in the file, but the embedded library will only be updated if you reload the pcb file. A possible future extension might be to allow the user to explicitly move fonts into the embedded library.

## Changing Fonts

Fonts can be easily changed using the Fonts tab in the preferences window:

- Open the Preferences window and switch to the Fonts tab.
- Select the new font to be assigned to the text objects.
- In the main window, select the text objects to which the font should be assigned.
- Click the "Change Selected" button to assign the new font to the text objects.

Alternatively, all text in a design can have a font assigned by using the "Change All" button.

Note that these methods will only change the font of discrete text objects. Reference designators of components cannot presently have fonts assigned to them individually. However, the font of *all* reference designators can be changed together by setting the PCB Font to the desired font.

## Compatibility with Older Versions of PCB

Previous versions of pcb would store the data of a single font in saved files as symbols. Alternatively, if the file did not contain symbols, perhaps because they were deleted, then pcb would load the default font instead. This feature branch will still play nicely with these scenarios.

If you load an existing design that has symbols stored in the design, the symbols will be converted into an embedded font (Font 0), all the text objects in the design will use that font, and that font will be set as the system font. If the design does not have symbols stored in it, then the text objects will be assigned the system font. So, if you've changed the system font then the text objects will not look exactly as they did when you saved them. However, If you load a design and don't like the font the text ends up in, it's easy to change the font.

# Implementation

The font system is implemented using a few data structures and several actions.

## Data Structures

### Font Type

The font data structure is called FontType and is defined in global.h as follows:

    typedef struct
    {
        char * Name;
        char * SourceFile;
        Coord MaxHeight; /*!< Maximum cell width. */
        Coord MaxWidth; /*!< Maximum cell height. */
        BoxType DefaultSymbol; /*!< The default symbol is a filled box. */
        SymbolType Symbol[MAX_FONTPOSITION + 1];
        int nSymbols;
    } FontType;

The MaxHeight and MaxWidth parameters are set by the SetFontInfo function that's been relocated into font.c. This structure has updated to include two new fields for the name of the font and the source file of the font.

### Font Libraries

The two font libraries (system and embedded) are both implemented as GLib GSLists. Each list element points to a FontType structure. The choice of a GSList was made because its a simple structure, and at the moment I don't anticipate there being a vast database of fonts to choose from, so searching through a list ought not to take all that long. GLib includes many functions for working with GSLists, and these are used for managing and accessing the list items.

#### Finding Fonts

Searching through the library for a font is done by using the FindFontInLibrary function. This function iterates through the list once comparing the name of the font to the provided reference string. If a match is not found, the list is searched through again comparing the name of the source file. If it's still not found then a null is returned.

A second function, FindFont, is available for searching. This function searches first through the embedded library, and if the font is not found, it will then search through the system library. This way, the embedded library always has precedence. So, if a customized version of a font is stored in the pcb file and there is a system font with the same name, the embedded font will be used. The assumption is that if the font was explicitly stored in the file, it was done so to ensure that it was used.

### Font File Format

The format for font files is basically the same as the format for symbols in complete pcb files, with one new keyword: Font. The argument of the Font keyword is the name of the font. Following the Font keyword a set of symbols using the existing pcb format are wrapped inside of normal parenthesis.

    Font("Default") (
    Symbol(' ' 18)
    (
    )
    Symbol('!' 12)
    (
    	SymbolLine(0 35 0 40 8)
    	SymbolLine(0 0 0 25 8)
    )
    ...
    ) # end font

The "# end font" is just for reference and is not required.

A font file can have one or more fonts defined in succession.

### PCB File Format Changes

#### Embedded Font Syntax

A single addition to the file format has been implemented. That's the Font directive that was described above. That directive can have two meanings. Fonts can be embedded in regular pcb files using the same syntax as above. The only caveat is that the font must be defined early in the file, between the styles and the layout data.

The Font directive can also be included without symbols. If it appears this way, then the argument is considered to be the PCB Default Font. This font is made the current font and is used for all reference designators and for any text objects that are not explicitly assigned a font.

#### Text Syntax

There is also an addition to the text syntax. It's labeled in `parse_y.y` as `text_20161008_format`. This is the same as `text_hi_format` with the addition of a second string field. The second string field is interpreted as the font. Here's the syntax definition:

    text_20161008_format
    			/* x, y, direction, scale, text, font, flags */
    		: T_TEXT '[' measure measure number number STRING STRING flags ']'
    			{
                    FontType * font = FindFont($8);
                    if(!font) Message(_("Warning: Could not find font %s for text \"%s\"\n"), $8, $7);
    		CreateNewText(Layer, font, NU ($3), NU ($4), $5, $6, $7, $9);
    		free ($7);
                    free ($8);
    			}
    		;

## Actions

### Change Font

The ChangeFont action can has two forms that can be invoked from the pcb command entry, a single argument version and a two argument version.
Syntax:

- `ChangeFont(fontname)`
  With one argument, the `ChangeFont` action changes the current system font to the font specified by `fontname`.
- `ChangeFont([All|Selected|Object|System|PCB], fontname)`
  With two arguments, the `ChangeFont` action changes the font of the specified item to the font specified by `fontname`.

The first argument to the second form has the following effects:

- `All`
  Change the font of *all* existing text objects to the specified font.
- `Selected`
  Change the font of all *selected* text objects to the specified font.
- `Object`
  Change the font of the object underneath the crosshair.
- `System`
  Change the system font. This has the same function as the single argument invocation.
- `PCB`
  Change the PCB font.

The `All`, `Selected`, and `Object` action will not change the font of dynamically generated text such as pin names/numbers or text that cannot be assigned a specific font, such as reference designators.
Changing the System or PCB font will update all of the dynamically generated text or reference designators, respectively.

### Load Font

The Load Font Action attempts to load a font from a font file.
Syntax:

- `LoadFont(<filename>)`
  Load a font from the specified file.
- `LoadFont(All)`
  Scan the font path(s) and attempt to load fonts from any file with the extension `.pcb_font`.

The Load Font Action is primarily an interface to the LoadFont function which takes as an argument being the name of the file containing the font(s) to load.

Fonts can only be deliberately loaded to the system font library, so prior to reading the specified file, the system library is checked for a font that came from a file with the same name. If it is present, then it does not reload the font. So, if you've changed a font and want to update it without closing pcb, you must first use the Unload Font Action to unload the font. Then you can reload it. (Note that the Unload Font Action will not allow you to unload a font that is currently being used in the design.)

A note on the LoadFont function: the ParseFont function is still used, however, the details of how fonts are parsed in parse_y.y have been modified to create fonts in the appropriate library. After ParseFont reads the file and loads the data, the new font is appended to the end of the GSList that is the library. LoadFont exploits this to get the font pointer and set the name of the source file in the data structure. LoadFont then explicitly sorts the library to put the entry in alphabetical order.

### Unload Font

The Unload Font Action is used for removing a font from the system library.
Syntax:

- `UnloadFont(<fontname>)`
  Unload the font with the specified name.
- `UnloadFont(<filename>)`
  Unload the font loaded from the specified file name.

The Unload Font Action acts primarily as an interface to the UnloadFont function. This action first checks to see if the specified font is in the system library, and then checks to see if that font is used anywhere in the design.

The Unload Font Action will not allow a font that is used in the current design to be unloaded from the font library.

The Unload Font Action will also not allow the Default font to be unloaded, and although it should be redundant, checks to ensure that there is always at least one font in the system library.

A note about the UnloadFont function. All of the sanity checking is performed in the Action, not in the function, because there are things that the system should be able to do that the user shouldn't. For example, the UnloadFont function is capable of unloading fonts from either the system library or the embedded library. This is to facilitate the closing of designs and the of the program. UnloadFont can be called with the font name "`all`" which will enter a loop that will unload every font in the library.

### List Fonts

The List Fonts Action was primarily for use as an introspection tool to evaluate the font system during development, however it may also find use facilitating testing. This action takes no arguments and writes to the message log the names of all of the fonts in the system library and the embedded library, the currently system font, the PCB font, and all of the fonts presently in use.
Syntax:

- `ListFonts()`
  List all fonts in use in the current design.

A noteworthy function that is used here is the FontsUsed() function. This function builds a GSList of all the fonts used in the design. The list must be freed by the calling function.

Possible future upgrades/expansions for this or a similar function:

- list information about which library a font is in
- take as an argument the name of a font and list the text objects that use that font

## Processes

### Startup/Shutdown

When PCB starts up the font system has several command line options that are processed like normal options. These options include:

- `font-path`
  The path(s) in which to search for font files
- `font-file`
  The file name of the "Default" font. This is loaded first to ensure that there is always at least one font in the system.
- `save-font-data`
  Save font information in pcb files. This is required in order for fonts to persist across saves. It will save the name of the font with the text object in the file. This option does not cause the fonts themselves to be included in the file (the `embed-font` option has that effect). Disabling this option will make the saved files backwards compatible with older versions of pcb.
- `save-symbols`
  This option causes the symbols of the current system font to be stored in saved files. This is the way that pcb has previously preserved a potentially modified font across saves.
- `embed-fonts`
  This option will embed the data for every font used in the design in the saved files. This ensures portability across systems that may have different fonts or different versions of the same font installed.

The font system is initialized in the `settings_post_process` function (`main.c`). Here, the `font-file` is searched for in the `font-path`(s) and loaded. Then the `font-path`(s) are searched by the `ScanFontPaths` function (`font.c`) for any files that have a `.pcb_font` extension, and these files are read looking for font information.

### File Load

The loading of a pcb file has two parts: 1. the actual reading of data from the file and converting it into pcb data structures, and 2. applying policy to the loaded data. (1) is implemented using bison/flex in `parse_y.y` and `parse_l.l`. (2) is implemented in `file.c` in the `real_load_pcb` function.

#### Reading Data From Files Into Data Structures

##### Font Data

Font data is required to be located after style data and before object data in the pcb file (this is a requirement from before the font system that results from the definition of the file grammar). The variable `yyFont` acts as the global pointer to the current font. When font data (an embedded font or floating symbols) is found a new font instance is created in the appropriate library (depending on whether `yyPCB` is NULL, if not we're loading a pcb file, otherwise we're loading a font file), and subsequent symbols are added to that. If a new font is found, a new font instance is created and yyFont is updated to point at the new font. If only the font directive is found (no symbols), then the `DefaultFontName` field of the PCBType structure is updated with the name. (I've been inconsistent in the docs about referring to this font name as both the `PCBDefaultFont` and the `DefaultPCBFont`)

##### Text Data

When text data is read from the file, it will either use the standard format, in which case the font pointer is initially set to NULL, or it will have a font specified, in which case the specified font is searched for in the font library (embedded library first). If the font is not found, then the font pointer is set to NULL. In post processing, any text object that has a NULL font pointer is set to the `DefaultPCBFont`. If the `DefaultPCBFont` is NULL, then the font pointers remain set to NULL. This could happen if this is a pcb file from an older version that has no font information. When the font pointer of a text object is NULL, it is displayed using the system font instead. So, it's possible to completely ignore the font system, change the system font, and in doing so change the font of every bit of text on the board (including refdes).

##### Element Data

The format of element data in pcb files doesn't presently include font information, so individual font cannot be stored for individual ref des. New elements are created via the `CreateNewElement` function (`create.c`) which adds text to the element via the `AddTextToElement` function (`create.c`). This function searches for the `PCBDefaultFont`, and assigns that if it's found, or NULL otherwise.

#### Post Loading Policy

The policy defines how to handle objects that need fonts but were not assigned one during load. This is the magic that will hopefully make pcb "do the right thing" when loading older versions of pcb files.

##### System Font and Default Font Name

The first (font related) thing pcb tries to do after loading all the data from a pcb file is figure out if it needs to change the current system font. If a `DefaultFontName` was specified, the system font is changed to this font. If we're dealing with an older file, there will be no `DefaultFontName` specified, but there still might be font data in the file (as loose symbols), and if there is, then it should be used. Symbol data gets loaded as a font in the embedded library, so if there are any fonts in the embedded library, the first one is set to be the system font. (Is this behavior okay if there are embedded fonts but no default font?)

##### Text Data

After loading all data,

### File Save

## To Do List

These are tasks and ideas related to the font subsystem that still need to be done, could be done, or are in progress:

- Move work done in ChangeFontAction to separate function to isolate the work from the undo serial number increment
- Check what happens when loading a font file if a `DefaultFontName` is specified
- Add licensing info to font files
- Add fonts to install (and figure out where they should go)
- Write test scripts
- Add documentation to doc/ tree
- Add flow diagrams to code comments
- Font preview in settings window
- Character map for selecting non standard characters
- User control of fonts in embedded library
- Save font(s) to a file
- "Font mode" saving of fonts to font files.