Foundation classes for a basic GUI implementing simple widgets and events

Dependents:   TouchScreenGUIDemo

Widgets/TextWidget.cpp

Committer:
duncanFrance
Date:
2016-03-25
Revision:
1:48796b602c86
Parent:
0:0a590815d51c
Child:
2:bb9183379488

File content as of revision 1:48796b602c86:

#include "TextWidget.h"

/**
* A basic widget implementation which just draws some text.
* If the text does not fit in the bounding-box it will be clipped
**/

TextWidget::TextWidget(GraphicsDisplay* display) : Widget(display) {}

void TextWidget::setText(char* text)
{
    _text = text;
}

void TextWidget::setFont(unsigned char* f, unsigned char firstascii, unsigned char lastascii, bool proportional)
{
    _font = f;
    // read font parameter from start of array in format understood by UniGraphics for now
    //fontoffset = font[0];                    // bytes / char
    _fontWidth = _font[1];
    _fontHeight = _font[2];
    //fontbpl = font[3];                       // bytes per line
    _fontBytesPerLine = (_fontHeight+7) >> 3; //bytes per line, rounded up to multiple of 8
    _fontOffset = (_fontWidth * _fontBytesPerLine) + 1;
    _fontFirstAscii = firstascii;   // first ascii code present in font array (usually 32)
    _fontLastAscii = lastascii;     // last ascii code present in font array (usually 127)
    _fontProportional = proportional;
}

void TextWidget::draw()
{

    int right = _x + _width; // right side of clipping window
    int bottom = _y + _height; // bottom edge of clipping window

    int _cx = _x;
    // Start drawing characters at top left
    int _cy = _y;

    char c;
    char *p = _text;
    unsigned char* glyph;
    uint8_t charWidth;

    _display->foreground(_fg);
    _display->background(_bg);
    _display->set_font(_font);


    while(*p != NULL) {
        c = *p;
        p++;
        if(c=='\n') {
            _cy = _cy + _fontHeight;
            _cx = _x;
        } else {
            // Only draw the character if it is not clipped
            if( (_cx+_fontWidth) < right && (_cy +_fontHeight) < bottom) {
                _display->character(_cx, _cy, c);
                glyph = &_font[((c - _fontFirstAscii) * _fontOffset) + 4]; // start of char bitmap
                charWidth = glyph[0];                          // width of actual char

                if(_fontProportional) {
                    if((charWidth+1) < _fontWidth) {
                        _cx += charWidth + 1; // put at least 1 blank after variable-width characters, except characters that occupy whole fonthor space like "_"
                    } else {
                        _cx += _fontWidth;
                    }
                } else {
                    _cx += _fontWidth; // fixed width
                }
            }
        }
    }
}

bool TextWidget::isEventTarget(Event e)
{
    return e.screenX < (_x+_width) && _x <= e.screenX && e.screenY < (_y+_height) && _y <= e.screenY;
}