summaryrefslogtreecommitdiffstats
path: root/lib/kformula/kformulacontainer.cc
blob: 46f3415a6e114b199d29fd4de8e20bd99ceb0baf (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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/* This file is part of the KDE project
   Copyright (C) 2001 Andrea Rizzi <rizzi@kde.org>
	              Ulrich Kuettler <ulrich.kuettler@mailbox.tu-dresden.de>

   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 <tqapplication.h>
#include <tqdom.h>
#include <tqevent.h>
#include <tqfile.h>
#include <tqpainter.h>
#include <tqpixmap.h>
#include <tqstring.h>
#include <textstream.h>

#include <kdebug.h>
#include <klocale.h>
#include <kprinter.h>

#include "KoGlobal.h"
#include "bracketelement.h"
#include "contextstyle.h"
#include "formulacursor.h"
#include "formulaelement.h"
#include "fractionelement.h"
#include "indexelement.h"
#include "kformulacommand.h"
#include "kformulacompatibility.h"
#include "kformulacontainer.h"
#include "kformuladocument.h"
#include "kformulamathmlread.h"
#include "kformulamimesource.h"
#include "matrixelement.h"
#include "rootelement.h"
#include "sequenceelement.h"
#include "symbolelement.h"
#include "symboltable.h"
#include "spaceelement.h"
#include "textelement.h"

#include <assert.h>

KFORMULA_NAMESPACE_BEGIN
using namespace std;


struct Container::Container_Impl {

    Container_Impl( Document* doc )
            : dirty( true ), cursorMoved( false ), document( doc )
    {
    }

    ~Container_Impl()
    {
        delete internCursor;
        delete rootElement;
        document = 0;
    }

    /**
     * If true we need to recalc the formula.
     */
    bool dirty;

    /**
     * Tells whether a request caused the cursor to move.
     */
    bool cursorMoved;

    /**
     * The element tree's root.
     */
    FormulaElement* rootElement;

    /**
     * The active cursor is the one that triggered the last command.
     */
    FormulaCursor* activeCursor;

    /**
     * The cursor that is used if there is no view.
     */
    FormulaCursor* internCursor;

    /**
     * The document we belong to.
     */
    Document* document;
};


FormulaElement* Container::rootElement() const { return impl->rootElement; }
Document* Container::document() const { return impl->document; }

Container::Container( Document* doc, int pos, bool registerMe )
{
    impl = new Container_Impl( doc );
    impl->rootElement = 0;
    if ( registerMe ) {
        registerFormula( pos );
    }
}

Container::~Container()
{
    unregisterFormula();
    delete impl;
    impl = 0;
}


void Container::initialize()
{
    assert( impl->rootElement == 0 );
    impl->rootElement = createMainSequence();
    impl->activeCursor = impl->internCursor = createCursor();
    recalc();
}


FormulaElement* Container::createMainSequence()
{
    return new FormulaElement( this );
}


FormulaCursor* Container::createCursor()
{
    return new FormulaCursor(rootElement());
}


KoCommandHistory* Container::getHistory() const
{
    return document()->getHistory();
}


/**
 * Gets called just before the child is removed from
 * the element tree.
 */
void Container::elementRemoval(BasicElement* child)
{
    emit elementWillVanish(child);
}

/**
 * Gets called whenever something changes and we need to
 * recalc.
 */
void Container::changed()
{
    impl->dirty = true;
}

void Container::cursorHasMoved( FormulaCursor* )
{
    impl->cursorMoved = true;
}

void Container::moveOutLeft( FormulaCursor* cursor )
{
    emit leaveFormula( this, cursor, EXIT_LEFT );
}

void Container::moveOutRight( FormulaCursor* cursor )
{
    emit leaveFormula( this, cursor, EXIT_RIGHT );
}

void Container::moveOutAbove( FormulaCursor* cursor )
{
    emit leaveFormula( this, cursor, EXIT_ABOVE );
}

void Container::moveOutBelow( FormulaCursor* cursor )
{
    emit leaveFormula( this, cursor, EXIT_BELOW );
}

void Container::tell( const TQString& msg )
{
    emit statusMsg( msg );
}

void Container::removeFormula( FormulaCursor* cursor )
{
    emit leaveFormula( this, cursor, REMOVE_FORMULA );
}


void Container::registerFormula( int pos )
{
    document()->registerFormula( this, pos );
}

void Container::unregisterFormula()
{
    document()->unregisterFormula( this );
}


void Container::baseSizeChanged( int size, bool owned )
{
    if ( owned ) {
        emit baseSizeChanged( size );
    }
    else {
        const ContextStyle& context = document()->getContextStyle();
        emit baseSizeChanged( context.baseSize() );
    }
}

FormulaCursor* Container::activeCursor()
{
    return impl->activeCursor;
}

const FormulaCursor* Container::activeCursor() const
{
    return impl->activeCursor;
}


/**
 * Tells the formula that a view got the focus and might want to
 * edit the formula.
 */
void Container::setActiveCursor(FormulaCursor* cursor)
{
    document()->activate(this);
    if (cursor != 0) {
        impl->activeCursor = cursor;
    }
    else {
        *(impl->internCursor) = *(impl->activeCursor);
        impl->activeCursor = impl->internCursor;
    }
}


bool Container::hasValidCursor() const
{
    return (impl->activeCursor != 0) && !impl->activeCursor->isReadOnly();
}

void Container::testDirty()
{
    if (impl->dirty) {
        recalc();
    }
}

void Container::recalc()
{
    impl->dirty = false;
    ContextStyle& context = impl->document->getContextStyle();
    rootElement()->calcSizes( context );

    emit formulaChanged( context.layoutUnitToPixelX( rootElement()->getWidth() ),
                         context.layoutUnitToPixelY( rootElement()->getHeight() ) );
    emit formulaChanged( context.layoutUnitPtToPt( context.pixelXToPt( rootElement()->getWidth() ) ),
                         context.layoutUnitPtToPt( context.pixelYToPt( rootElement()->getHeight() ) ) );
    emit cursorMoved( activeCursor() );
}

bool Container::isEmpty()
{
    return rootElement()->countChildren() == 0;
}


const SymbolTable& Container::getSymbolTable() const
{
    return document()->getSymbolTable();
}


void Container::draw( TQPainter& painter, const TQRect& r, const TQColorGroup& cg, bool edit )
{
    painter.fillRect( r, cg.base() );
    draw( painter, r, edit );
}


void Container::draw( TQPainter& painter, const TQRect& r, bool edit )
{
    //ContextStyle& context = document()->getContextStyle( painter.device()->devType() == TQInternal::Printer );
    ContextStyle& context = document()->getContextStyle( edit );
    rootElement()->draw( painter, context.pixelToLayoutUnit( r ), context );
}


void Container::checkCursor()
{
    if ( impl->cursorMoved ) {
        impl->cursorMoved = false;
        emit cursorMoved( activeCursor() );
    }
}

void Container::input( TQKeyEvent* event )
{
    //if ( !hasValidCursor() )
    if ( impl->activeCursor == 0 ) {
        return;
    }
    execute( activeCursor()->getElement()->input( this, event ) );
    checkCursor();
}


void Container::performRequest( Request* request )
{
    if ( !hasValidCursor() )
        return;
    execute( activeCursor()->getElement()->buildCommand( this, request ) );
    checkCursor();
}


void Container::paste()
{
    if (!hasValidCursor())
        return;
    TQClipboard* clipboard = TQApplication::clipboard();
    const TQMimeSource* source = clipboard->data();
    if (source->provides( MimeSource::selectionMimeType() )) {
        TQByteArray data = source->encodedData( MimeSource::selectionMimeType() );
        TQDomDocument formula;
        formula.setContent(data);
        paste( formula, i18n("Paste") );
    }
}

void Container::paste( const TQDomDocument& document, TQString desc )
{
    FormulaCursor* cursor = activeCursor();
    TQPtrList<BasicElement> list;
    list.setAutoDelete( true );
    if ( cursor->buildElementsFromMathMLDom( document.documentElement(), list ) ) {
        uint count = list.count();
        // You must not execute an add command that adds nothing.
        if (count > 0) {
            KFCReplace* command = new KFCReplace( desc, this );
            for (uint i = 0; i < count; i++) {
                command->addElement(list.take(0));
            }
            execute(command);
        }
    }
}

void Container::copy()
{
    // read-only cursors are fine for copying.
    FormulaCursor* cursor = activeCursor();
    if (cursor != 0) {
        TQDomDocument formula = document()->createMathMLDomDocument();
        cursor->copy( formula );
        TQClipboard* clipboard = TQApplication::clipboard();
        clipboard->setData(new MimeSource(document(), formula));
    }
}

void Container::cut()
{
    if (!hasValidCursor())
        return;
    FormulaCursor* cursor = activeCursor();
    if (cursor->isSelection()) {
        copy();
        DirectedRemove r( req_remove, beforeCursor );
        performRequest( &r );
    }
}


void Container::emitErrorMsg( const TQString& msg )
{
    emit errorMsg( msg );
}

void Container::execute(KCommand* command)
{
    if ( command != 0 ) {
        getHistory()->addCommand(command);
    }
}


TQRect Container::boundingRect() const
{
    const ContextStyle& context = document()->getContextStyle();
    return TQRect( context.layoutUnitToPixelX( rootElement()->getX() ),
                  context.layoutUnitToPixelY( rootElement()->getY() ),
                  context.layoutUnitToPixelX( rootElement()->getWidth() ),
                  context.layoutUnitToPixelY( rootElement()->getHeight() ) );
}

TQRect Container::coveredRect()
{
    if ( impl->activeCursor != 0 ) {
        const ContextStyle& context = document()->getContextStyle();
        const LuPixelRect& cursorRect = impl->activeCursor->getCursorSize();
        return TQRect( context.layoutUnitToPixelX( rootElement()->getX() ),
                      context.layoutUnitToPixelY( rootElement()->getY() ),
                      context.layoutUnitToPixelX( rootElement()->getWidth() ),
                      context.layoutUnitToPixelY( rootElement()->getHeight() ) ) |
            TQRect( context.layoutUnitToPixelX( cursorRect.x() ),
                   context.layoutUnitToPixelY( cursorRect.y() ),
                   context.layoutUnitToPixelX( cursorRect.width() ),
                   context.layoutUnitToPixelY( cursorRect.height() ) );
    }
    return boundingRect();
}

double Container::width() const
{
    const ContextStyle& context = document()->getContextStyle();
    return context.layoutUnitPtToPt( context.pixelXToPt( rootElement()->getWidth() ) );
}

double Container::height() const
{
    const ContextStyle& context = document()->getContextStyle();
    return context.layoutUnitPtToPt( context.pixelYToPt( rootElement()->getHeight() ) );
}

double Container::baseline() const
{
    const ContextStyle& context = document()->getContextStyle();
    //return context.layoutUnitToPixelY( rootElement()->getBaseline() );
    return context.layoutUnitPtToPt( context.pixelYToPt( rootElement()->getBaseline() ) );
}

void Container::moveTo( int x, int y )
{
    const ContextStyle& context = document()->getContextStyle();
    rootElement()->setX( context.pixelToLayoutUnitX( x ) );
    rootElement()->setY( context.pixelToLayoutUnitY( y ) );
}

int Container::fontSize() const
{
    if ( rootElement()->hasOwnBaseSize() ) {
        return rootElement()->getBaseSize();
    }
    else {
        const ContextStyle& context = document()->getContextStyle();
        return tqRound( context.baseSize() );
    }
}

void Container::setFontSize( int pointSize, bool /*forPrint*/ )
{
    if ( rootElement()->getBaseSize() != pointSize ) {
        execute( new KFCChangeBaseSize( i18n( "Base Size Change" ), this, rootElement(), pointSize ) );
    }
}

void Container::setFontSizeDirect( int pointSize )
{
    rootElement()->setBaseSize( pointSize );
    recalc();
}

void Container::updateMatrixActions()
{
    BasicElement *currentElement = activeCursor()->getElement();
    if ( ( currentElement = currentElement->getParent() ) != 0 )
        document()->wrapper()->enableMatrixActions( dynamic_cast<MatrixElement*>(currentElement) );
    else
        document()->wrapper()->enableMatrixActions( false );
}

void Container::save( TQDomElement &root )
{
    TQDomDocument ownerDoc = root.ownerDocument();
    root.appendChild(rootElement()->getElementDom(ownerDoc));
}


/**
 * Loads a formula from the document.
 */
bool Container::load( const TQDomElement &fe )
{
    if (!fe.isNull()) {
        FormulaElement* root = createMainSequence();
        if (root->buildFromDom(fe)) {
            delete impl->rootElement;
            impl->rootElement = root;
            emit formulaLoaded(rootElement());

            recalc();
            return true;
        }
        else {
            delete root;
            kdWarning( DEBUGID ) << "Error constructing element tree." << endl;
        }
    }
    else {
        kdWarning( DEBUGID ) << "Empty element." << endl;
    }
    return false;
}


void Container::saveMathML( TQTextStream& stream, bool oasisFormat )
{
    TQDomDocument doc;
    if ( !oasisFormat ) {
        doc = document()->createMathMLDomDocument(); 
   }
    rootElement()->writeMathML( doc, doc, oasisFormat );
    stream << doc;
}

bool Container::loadMathML( const TQDomDocument &doc, bool oasisFormat )
{
    return loadMathML( doc.documentElement(), oasisFormat );
}

/*
bool Container::loadMathML( const TQDomElement &element, bool oasisFormat )
{
    const ContextStyle& context = document()->getContextStyle();
    MathML2KFormula filter( element, context, oasisFormat );
    filter.startConversion();
    if (filter.m_error) {
        return false;
    }

    if ( load( filter.getKFormulaDom().documentElement() ) ) {
        getHistory()->clear();
        return true;
    }
    return false;
}
*/

bool Container::loadMathML( const TQDomElement &fe, bool /*oasisFormat*/ )
{
    kdDebug( DEBUGID ) << "loadMathML" << endl;
    if (!fe.isNull()) {
        FormulaElement* root = createMainSequence();
        if ( root->buildFromMathMLDom( fe ) != - 1) {
            delete impl->rootElement;
            impl->rootElement = root;
            emit formulaLoaded(rootElement());

            recalc();
            return true;
        }
        else {
            delete root;
            kdWarning( DEBUGID ) << "Error constructing element tree." << endl;
        }
    }
    else {
        kdWarning( DEBUGID ) << "Empty element." << endl;
    }
    return false;
}


void Container::print(KPrinter& printer)
{
    //printer.setFullPage(true);
    TQPainter painter;
    if (painter.begin(&printer)) {
        rootElement()->draw( painter, LuPixelRect( rootElement()->getX(),
                                                   rootElement()->getY(),
                                                   rootElement()->getWidth(),
                                                   rootElement()->getHeight() ),
                             document()->getContextStyle( false ) );
    }
}

TQImage Container::drawImage( int width, int height )
{
    ContextStyle& context = document()->getContextStyle( false );
    TQRect rect(impl->rootElement->getX(), impl->rootElement->getY(),
               impl->rootElement->getWidth(), impl->rootElement->getHeight());

    int realWidth = context.layoutUnitToPixelX( impl->rootElement->getWidth() );
    int realHeight = context.layoutUnitToPixelY( impl->rootElement->getHeight() );

    double f = TQMAX( static_cast<double>( width )/static_cast<double>( realWidth ),
                     static_cast<double>( height )/static_cast<double>( realHeight ) );

    int oldZoom = context.zoom();
    context.setZoomAndResolution( tqRound( oldZoom*f ), KoGlobal::dpiX(), KoGlobal::dpiY() );

    kdDebug( DEBUGID ) << "Container::drawImage "
                       << "(" << width << " " << height << ")"
                       << "(" << context.layoutUnitToPixelX( impl->rootElement->getWidth() )
                       << " " << context.layoutUnitToPixelY( impl->rootElement->getHeight() ) << ")"
                       << endl;

    TQPixmap pm( context.layoutUnitToPixelX( impl->rootElement->getWidth() ),
                context.layoutUnitToPixelY( impl->rootElement->getHeight() ) );
    pm.fill();
    TQPainter paint(&pm);
    impl->rootElement->draw(paint, rect, context);
    paint.end();
    context.setZoomAndResolution( oldZoom, KoGlobal::dpiX(), KoGlobal::dpiY() );
    //return pm.convertToImage().smoothScale( width, height );
    return pm.convertToImage();
}

TQString Container::texString()
{
    return rootElement()->toLatex();
}

TQString Container::formulaString()
{
    return rootElement()->formulaString();
}

KFORMULA_NAMESPACE_END

using namespace KFormula;
#include "kformulacontainer.moc"