summaryrefslogtreecommitdiffstats
path: root/lib/kformula/textelement.cc
blob: 7f146b49bcb9e089c7d97b191404cf192ddec004 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/* This file is part of the KDE project
   Copyright (C) 2001 Andrea Rizzi <[email protected]>
	              Ulrich Kuettler <[email protected]>

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

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include <tqfontmetrics.h>
#include <tqpainter.h>

#include <kdebug.h>

#include "basicelement.h"
#include "contextstyle.h"
#include "elementtype.h"
#include "elementvisitor.h"
#include "fontstyle.h"
#include "formulaelement.h"
#include "kformulacommand.h"
#include "sequenceelement.h"
#include "symboltable.h"
#include "textelement.h"


KFORMULA_NAMESPACE_BEGIN

TextElement::TextElement(TQChar ch, bool beSymbol, BasicElement* parent)
        : BasicElement(parent), character(ch), symbol(beSymbol)
{
    charStyle( anyChar );
    charFamily( anyFamily );
}


TextElement::TextElement( const TextElement& other )
    : BasicElement( other ),
      character( other.character ),
      symbol( other.symbol ),
      m_format( other.m_format )
{
}


bool TextElement::accept( ElementVisitor* visitor )
{
    return visitor->visit( this );
}


TokenType TextElement::getTokenType() const
{
    if ( isSymbol() ) {
        return getSymbolTable().charClass( character );
    }

    switch ( character.unicode() ) {
    case '+':
    case '-':
    case '*':
        //case '/':  because it counts as text -- no extra spaces
        return BINOP;
    case '=':
    case '<':
    case '>':
        return RELATION;
    case ',':
    case ';':
    case ':':
        return PUNCTUATION;
    case '\\':
        return SEPARATOR;
    case '\0':
        return ELEMENT;
    default:
        if ( character.isNumber() ) {
            return NUMBER;
        }
        else {
            return ORDINARY;
        }
    }
}


bool TextElement::isInvisible() const
{
    if (getElementType() != 0) {
        return getElementType()->isInvisible(*this);
    }
    return false;
}


/**
 * Calculates our width and height and
 * our children's parentPosition.
 */
void TextElement::calcSizes( const ContextStyle& context, 
                             ContextStyle::TextStyle tstyle, 
                             ContextStyle::IndexStyle /*istyle*/,
                             StyleAttributes& style )
{
    double factor = style.sizeFactor();
    luPt mySize = context.getAdjustedSize( tstyle, factor );

    setCharStyle( style.charStyle() );
    setCharFamily( style.charFamily() );

    TQFont font = getFont( context, style );
    double fontsize = context.layoutUnitPtToPt( mySize );
    double scriptsize = pow( style.scriptSizeMultiplier(), style.scriptLevel() );
    double size = fontsize * scriptsize;
    font.setPointSizeFloat( size < style.scriptMinSize() ? style.scriptMinSize() : size );

    TQFontMetrics fm( font );
    if ( character == applyFunctionChar || character == invisibleTimes || character == invisibleComma ) {
        setWidth( 0 );
        setHeight( 0 );
        setBaseline( getHeight() );
    }
    else {
        TQChar ch = getRealCharacter(context);
        if ( ch == TQChar::null ) {
            setWidth( tqRound( context.getEmptyRectWidth( factor ) * 2./3. ) );
            setHeight( tqRound( context.getEmptyRectHeight( factor ) * 2./3. ) );
            setBaseline( getHeight() );
        }
        else {
            TQRect bound = fm.boundingRect( ch );
            setWidth( context.ptToLayoutUnitPt( fm.width( ch ) ) );
            setHeight( context.ptToLayoutUnitPt( bound.height() ) );
            setBaseline( context.ptToLayoutUnitPt( -bound.top() ) );

            // There are some glyphs in TeX that have
            // baseline==0. (\int, \sum, \prod)
            if ( getBaseline() == 0 ) {
                //setBaseline( getHeight()/2 + context.axisHeight( tstyle ) );
                setBaseline( -1 );
            }
        }
    }
}

/**
 * Draws the whole element including its children.
 * The `parentOrigin' is the point this element's parent starts.
 * We can use our parentPosition to get our own origin then.
 */
void TextElement::draw( TQPainter& painter, const LuPixelRect& /*r*/,
                        const ContextStyle& context,
                        ContextStyle::TextStyle tstyle,
                        ContextStyle::IndexStyle /*istyle*/,
                        StyleAttributes& style,
                        const LuPixelPoint& parentOrigin )
{
    if ( character == applyFunctionChar || character == invisibleTimes || character == invisibleComma ) {
        return;
    }

    LuPixelPoint myPos( parentOrigin.x()+getX(), parentOrigin.y()+getY() );
    //if ( !LuPixelRect( myPos.x(), myPos.y(), getWidth(), getHeight() ).intersects( r ) )
    //    return;

    // Let container set the color, instead of elementType
    //setUpPainter( context, painter );
    painter.setPen( style.color() );

    setCharStyle( style.charStyle() );
    setCharFamily( style.charFamily() );

    double factor = style.sizeFactor();
    luPt mySize = context.getAdjustedSize( tstyle, factor );
    TQFont font = getFont( context, style );
    double fontsize = context.layoutUnitPtToPt( mySize );
    double scriptsize = pow( style.scriptSizeMultiplier(), style.scriptLevel() );
    double size = fontsize * scriptsize;
    font.setPointSizeFloat( size < style.scriptMinSize() ? style.scriptMinSize() : size );
    painter.setFont( font );

    //kdDebug( DEBUGID ) << "TextElement::draw font=" << font.rawName() << endl;
    //kdDebug( DEBUGID ) << "TextElement::draw size=" << mySize << endl;
    //kdDebug( DEBUGID ) << "TextElement::draw size=" << context.layoutUnitToFontSize( mySize, false ) << endl;
    //kdDebug( DEBUGID ) << "TextElement::draw height: " << getHeight() << endl;
    //kdDebug( DEBUGID ) << "TextElement::draw width: " << getWidth() << endl;
    //kdDebug( DEBUGID ) << endl;

    // Each starting element draws the whole token
    /*
    ElementType* token = getElementType();
    if ( ( token != 0 ) && !symbol ) {
        TQString text = token->text( static_cast<SequenceElement*>( getParent() ) );
//         kdDebug() << "draw text: " << text[0].unicode()
//                   << " " << painter.font().family().latin1()
//                   << endl;
        painter.fillRect( context.layoutUnitToPixelX( parentOrigin.x() ),
                          context.layoutUnitToPixelY( parentOrigin.y() ),
                          context.layoutUnitToPixelX( getParent()->getWidth() ),
                          context.layoutUnitToPixelY( getParent()->getHeight() ),
                          style.background() );
        painter.drawText( context.layoutUnitToPixelX( myPos.x() ),
                          context.layoutUnitToPixelY( myPos.y()+getBaseline() ),
                          text );
    }
    else {
    */
        TQChar ch = getRealCharacter(context);
        if ( ch != TQChar::null ) {
            luPixel bl = getBaseline();
            if ( bl == -1 ) {
                // That's quite hacky and actually not the way it's
                // meant to be. You shouldn't calculate a lot in
                // draw. But I don't see how else to deal with
                // baseline==0 glyphs without yet another flag.
                bl = -( getHeight()/2 + context.axisHeight( tstyle, factor ) );
            }
            painter.drawText( context.layoutUnitToPixelX( myPos.x() ),
                              context.layoutUnitToPixelY( myPos.y()+bl ),
                              TQString(ch) );
        }
        else {
            painter.setPen( TQPen( context.getErrorColor(),
                                  context.layoutUnitToPixelX( context.getLineWidth( factor ) ) ) );
            painter.drawRect( context.layoutUnitToPixelX( myPos.x() ),
                              context.layoutUnitToPixelY( myPos.y() ),
                              context.layoutUnitToPixelX( getWidth() ),
                              context.layoutUnitToPixelY( getHeight() ) );
        }
//    }

    // Debug
    //painter.setBrush(TQt::NoBrush);
//     if ( isSymbol() ) {
//         painter.setPen( TQt::red );
//         painter.drawRect( context.layoutUnitToPixelX( myPos.x() ),
//                           context.layoutUnitToPixelX( myPos.y() ),
//                           context.layoutUnitToPixelX( getWidth() ),
//                           context.layoutUnitToPixelX( getHeight() ) );
//         painter.setPen(TQt::green);
//         painter.drawLine(myPos.x(), myPos.y()+axis( context, tstyle ),
//                          myPos.x()+getWidth(), myPos.y()+axis( context, tstyle ));
//     }
}


void TextElement::dispatchFontCommand( FontCommand* cmd )
{
    cmd->addTextElement( this );
}

void TextElement::setCharStyle( CharStyle cs )
{
    charStyle( cs );
    formula()->changed();
}

void TextElement::setCharFamily( CharFamily cf )
{
    charFamily( cf );
    formula()->changed();
}

TQChar TextElement::getRealCharacter(const ContextStyle& context)
{
    return character;
/*
    if ( !isSymbol() ) {
        const FontStyle& fontStyle = context.fontStyle();
        const AlphaTable* alphaTable = fontStyle.alphaTable();
        if ( alphaTable != 0 ) {
            AlphaTableEntry ate = alphaTable->entry( character,
                                                     charFamily(),
                                                     charStyle() );
            if ( ate.valid() ) {
                return ate.pos;
            }
        }
        return character;
    }
    else {
        return getSymbolTable().character(character, charStyle());
    }
*/
}


TQFont TextElement::getFont(const ContextStyle& context, const StyleAttributes& style)
{
    const FontStyle& fontStyle = context.fontStyle();
    TQFont font;
    if ( style.customFont() ) {
        font = style.font();
    }
    else if (getElementType() != 0) {
        font = getElementType()->getFont(context);
    }
    else {
        font = context.getDefaultFont();
    }
    switch ( charStyle() ) {
    case anyChar:
        font.setItalic( false );
        font.setBold( false );
        break;
    case normalChar:
        font.setItalic( false );
        font.setBold( false );
        break;
    case boldChar:
        font.setItalic( false );
        font.setBold( true );
        break;
    case italicChar:
        font.setItalic( true );
        font.setBold( false );
        break;
    case boldItalicChar:
        font.setItalic( true );
        font.setBold( true );
        break;
    }
    return fontStyle.symbolTable()->font( character, font );
}


void TextElement::setUpPainter(const ContextStyle& context, TQPainter& painter)
{
    if (getElementType() != 0) {
        getElementType()->setUpPainter(context, painter);
    }
    else {
        painter.setPen(TQt::red);
    }
}

const SymbolTable& TextElement::getSymbolTable() const
{
    return formula()->getSymbolTable();
}


void TextElement::writeMathML( TQDomDocument& doc, TQDomNode& parent, bool ) const
{
    parent.appendChild( doc.createTextNode( getCharacter() ) );
}

/**
 * Appends our attributes to the dom element.
 */
void TextElement::writeDom(TQDomElement element)
{
    BasicElement::writeDom(element);
    element.setAttribute("CHAR", TQString(character));
    //TQString s;
    //element.setAttribute("CHAR", s.sprintf( "#x%05X", character ) );
    if (symbol) element.setAttribute("SYMBOL", "3");

    switch ( charStyle() ) {
    case anyChar: break;
    case normalChar: element.setAttribute("STYLE", "normal"); break;
    case boldChar: element.setAttribute("STYLE", "bold"); break;
    case italicChar: element.setAttribute("STYLE", "italic"); break;
    case boldItalicChar: element.setAttribute("STYLE", "bolditalic"); break;
    }

    switch ( charFamily() ) {
    case normalFamily: element.setAttribute("FAMILY", "normal"); break;
    case scriptFamily: element.setAttribute("FAMILY", "script"); break;
    case frakturFamily: element.setAttribute("FAMILY", "fraktur"); break;
    case doubleStruckFamily: element.setAttribute("FAMILY", "doublestruck"); break;
    case anyFamily: break;
    }
}

/**
 * Reads our attributes from the element.
 * Returns false if it failed.
 */
bool TextElement::readAttributesFromDom(TQDomElement element)
{
    if (!BasicElement::readAttributesFromDom(element)) {
        return false;
    }
    TQString charStr = element.attribute("CHAR");
    if(!charStr.isNull()) {
        character = charStr.at(0);
    }
    TQString symbolStr = element.attribute("SYMBOL");
    if(!symbolStr.isNull()) {
        int symbolInt = symbolStr.toInt();
        if ( symbolInt == 1 ) {
            character = getSymbolTable().unicodeFromSymbolFont(character);
        }
        if ( symbolInt == 2 ) {
            switch ( character.unicode() ) {
            case 0x03D5: character = 0x03C6; break;
            case 0x03C6: character = 0x03D5; break;
            case 0x03Ba: character = 0x03BA; break;
            case 0x00B4: character = 0x2032; break;
            case 0x2215: character = 0x2244; break;
            case 0x00B7: character = 0x2022; break;
            case 0x1D574: character = 0x2111; break;
            case 0x1D579: character = 0x211C; break;
            case 0x2219: character = 0x22C5; break;
            case 0x2662: character = 0x26C4; break;
            case 0x220B: character = 0x220D; break;
            case 0x224C: character = 0x2245; break;
            case 0x03DB: character = 0x03C2; break;
            }
        }
        symbol = symbolInt != 0;
    }

    TQString styleStr = element.attribute("STYLE");
    if ( styleStr == "normal" ) {
        charStyle( normalChar );
    }
    else if ( styleStr == "bold" ) {
        charStyle( boldChar );
    }
    else if ( styleStr == "italic" ) {
        charStyle( italicChar );
    }
    else if ( styleStr == "bolditalic" ) {
        charStyle( boldItalicChar );
    }
    else {
        charStyle( anyChar );
    }

    TQString familyStr = element.attribute( "FAMILY" );
    if ( familyStr == "normal" ) {
        charFamily( normalFamily );
    }
    else if ( familyStr == "script" ) {
        charFamily( scriptFamily );
    }
    else if ( familyStr == "fraktur" ) {
        charFamily( frakturFamily );
    }
    else if ( familyStr == "doublestruck" ) {
        charFamily( doubleStruckFamily );
    }
    else {
        charFamily( anyFamily );
    }

//     kdDebug() << "charStyle=" << charStyle()
//               << "  charFamily=" << charFamily()
//               << "  format=" << int( format() ) << endl;

    return true;
}

/**
 * Reads our content from the node. Sets the node to the next node
 * that needs to be read.
 * Returns false if it failed.
 */
bool TextElement::readContentFromDom(TQDomNode& node)
{
    return BasicElement::readContentFromDom(node);
}

TQString TextElement::toLatex()
{
    if ( isSymbol() ) {
        TQString texName = getSymbolTable().name( character );
        if ( !texName.isNull() )
            return " \\" + texName + " ";
        return  " ? ";
    }
    else {
        return TQString(character);
    }
}

TQString TextElement::formulaString()
{
    if ( isSymbol() ) {
        TQString texName = getSymbolTable().name( character );
        if ( !texName.isNull() )
            return " " + texName + " ";
        return " ? ";
    }
    else {
        return character;
    }
}


EmptyElement::EmptyElement( BasicElement* parent )
    : BasicElement( parent )
{
}

EmptyElement::EmptyElement( const EmptyElement& other )
    : BasicElement( other )
{
}


bool EmptyElement::accept( ElementVisitor* visitor )
{
    return visitor->visit( this );
}


void EmptyElement::calcSizes( const ContextStyle& context,
                              ContextStyle::TextStyle tstyle,
                              ContextStyle::IndexStyle /*istyle*/,
                              StyleAttributes& style )
{
    luPt mySize = context.getAdjustedSize( tstyle, style.sizeFactor() );
    //kdDebug( DEBUGID ) << "TextElement::calcSizes size=" << mySize << endl;

    TQFont font = context.getDefaultFont();
    font.setPointSizeFloat( context.layoutUnitPtToPt( mySize ) );

    TQFontMetrics fm( font );
    TQChar ch = 'A';
    TQRect bound = fm.boundingRect( ch );
    setWidth( 0 );
    setHeight( context.ptToLayoutUnitPt( bound.height() ) );
    setBaseline( context.ptToLayoutUnitPt( -bound.top() ) );
}

void EmptyElement::draw( TQPainter& painter, const LuPixelRect& /*r*/,
                         const ContextStyle& context,
                         ContextStyle::TextStyle /*tstyle*/,
                         ContextStyle::IndexStyle /*istyle*/,
                         StyleAttributes& /*style*/ ,
                         const LuPixelPoint& parentOrigin )
{
    LuPixelPoint myPos( parentOrigin.x()+getX(), parentOrigin.y()+getY() );
    /*
    if ( !LuPixelRect( myPos.x(), myPos.y(), getWidth(), getHeight() ).intersects( r ) )
        return;
    */

    if ( context.edit() ) {
        painter.setPen( context.getHelpColor() );
        painter.drawLine( context.layoutUnitToPixelX( myPos.x() ),
                          context.layoutUnitToPixelY( myPos.y() ),
                          context.layoutUnitToPixelX( myPos.x() ),
                          context.layoutUnitToPixelY( myPos.y()+getHeight() ) );
    }
}

TQString EmptyElement::toLatex()
{
    return "{}";
}

KFORMULA_NAMESPACE_END