summaryrefslogtreecommitdiffstats
path: root/kjots/kjotsentry.cpp
blob: 53613c30b644e8fb591c6bf45fd7b344c15de91f (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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//
//  kjots
//
//  Copyright (C) 1997 Christoph Neerfeld
//  Copyright (C) 2002, 2003 Aaron J. Seigo
//  Copyright (C) 2003 Stanislav Kljuhhin
//
//  This program 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 2 of the License, or
//  (at your option) any later version.
//
//  This program 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 this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//

#include <tqdir.h>
#include <tqpainter.h>
#include <tqpaintdevicemetrics.h>
#include <tqtextcodec.h>
#include <tqdom.h>

#include <kapplication.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kprogress.h>
#include <kstandarddirs.h>
#include <ktempfile.h>

#include <kio/job.h>
#include <assert.h>

#include "kjotsedit.h"
#include "KJotsMain.h"
#include "KJotsSettings.h"
#include "kjotsentry.h"

// helper functions for HTML output
TQString prepForHTML(TQString text)
{
    text.replace("<", "&lt;");
    text.replace(">", "&gt;");
    text.replace("\n", "<br>");
    return text;
}

TQString htmlHeader(const TQString& title, TQTextCodec* codec)
{
    TQString head = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=";
    head+=codec->mimeName();
    head+="\" ><title>" + prepForHTML(title) + "</title></head><body>";
    return head;
}

TQString htmlFooter()
{
    return "</body></html>";
}

//
// KJotsEntryBase
//

KJotsEntryBase::KJotsEntryBase(KListView* parent, TQListViewItem* after=0)
    :KListViewItem(parent,after)
{
    m_id = 0;
    m_saveInProgress = m_dirty = false;
    m_parent = 0;
}

KJotsEntryBase::KJotsEntryBase(KListViewItem* parent, TQListViewItem* after=0)
    :KListViewItem(parent,after)
{
    m_id = 0;
    m_saveInProgress = m_dirty = false;
    m_parent = dynamic_cast<KJotsBook*>(parent);
}

void KJotsEntryBase::setSubject(const TQString& subj)
{
    setText(0, subj);
}

void KJotsEntryBase::setText(int column, const TQString& text)
{
    if (column == 0 && text.isEmpty())
        KListViewItem::setText(0, defaultSubject());
    else
        KListViewItem::setText(column, text);
}

/*!
    \brief Sets a new parent.
    This is mostly just used during drag-and-drop reordering in the list view.
    We need to keep track of the previous parent in case the move is invalid.
*/
void KJotsEntryBase::resetParent() 
{ 
    m_parent = dynamic_cast<KJotsBook*>(TQListViewItem::parent()); 
}

/*! 
*    \brief Set the ID number.
*    \param id The ID to set, or 0 to pick a fresh one.
*
*    Set ourselves to a particular ID number, or pick a new one. The lastId used is
*    stored in the settings. Now in theory it will eventually wrap, and may collide
*    with preexisting IDs. Seeing as how we are using an unsigned long long, I am
*    comfortable with the amount of time we have to worry about this. 
*/
void KJotsEntryBase::setId(TQ_UINT64 id)
{
    //Find an unused id...
    if ( id == 0 )
    {
        TQ_UINT64 lastId = KJotsSettings::lastId();

        //TODO: In theory, we could wrap. The universe may end beforehand tho.
        id = ++lastId; 
        if ( id == 0 ) id = ++lastId; //*IF* by some chance we do wrap, this will prevent bad things.
        KJotsSettings::setLastId(id);
    }

    m_id = id;
    return;
}

/*!
    \brief Performs functions necessary to save the entry to a KJots file.
    This function should ONLY be called when saving the file, as it performs
    other functions than generating XML.
*/
void KJotsEntryBase::generateXml( TQDomDocument &doc, TQDomElement &parent )
{
    TQDomElement title = doc.createElement( "Title" );
    title.appendChild( doc.createTextNode( subject() ));
    parent.appendChild( title );

    TQDomElement id = doc.createElement( "ID" );
    TQString id_string;
    id_string.setNum(m_id);
    id.appendChild( doc.createTextNode(id_string) );
    parent.appendChild( id );

    setDirty( false );
    return;
}

/*!
    Parses through XML data for settings inherent to the base class. 
*/
void KJotsEntryBase::parseXml( TQDomElement &e )
{
    if ( !e.isNull() ) 
    {
        if ( e.tagName() == "Title" ) 
        {
            setSubject(e.text());
        } 
        else
        if ( e.tagName() == "ID" ) 
        {
            setId(e.text().toULongLong());
        } 
    }

    return;
}

/*!
    \brief Draws the Title box when printing.
    This is a helper function for the derived classes. Code consolidation==the good.
*/
int KJotsEntryBase::printTitleBox(TQString title, KPrinter& printer, TQPainter& painter, int y)
{
    TQPaintDeviceMetrics metrics( &printer );
    int maxWidth = metrics.width();
    int maxHeight = metrics.height();

    TQRect r = painter.boundingRect(0, y,
              maxWidth, maxHeight,
              TQPainter::ExpandTabs | TQPainter::WordBreak | TQPainter::AlignHCenter,
              title);
    y += 10;

    if ((y + r.height()) > maxHeight)
    {
        printer.newPage();
        y = 0;
    }
    else
    {
        r.moveBy(0, 10);
    }

    r.setLeft(0);
    r.setRight(maxWidth);
    painter.drawRect(r);
    painter.drawText(0, y, maxWidth, maxHeight - y,
            TQPainter::ExpandTabs | TQPainter::WordBreak | TQPainter::AlignHCenter,
            title);
    y += r.height() + 15;

    return y;
}

//
// KJotsBook
//

KJotsBook::KJotsBook(KListView* parent, TQListViewItem* after)
    : KJotsEntryBase(parent, after)
{
    init();
}

KJotsBook::KJotsBook(KListViewItem* parent, TQListViewItem* after)
    : KJotsEntryBase(parent, after)
{
    init();
}

KJotsBook::~KJotsBook()
{
}

/*!
    \brief Initialize a KJotsBook object.

    This function is used for code consolidation. Otherwise, you'de have to change these 
    things in both constructors.
*/
void KJotsBook::init()
{
    m_isBook = true;
    m_open = false;
    m_saveProgressDialog = 0;
    setExpandable(true);
    setPixmap(0, kapp->iconLoader()->loadIcon(TQString("contents"),KIcon::Small));
}

/*!
    \brief Is this a KJots file?
    \param filename Filename to check.

    This function does a cursory check to see if this looks like it is a KJots file.
    It's a little too quick and dirty for my taste, but seems to work OK.
*/
bool KJotsBook::isBookFile(const TQString& filename)
{
    TQFile folder(filename);
    bool test = false;

    if ( folder.exists() )
    {
        if ( folder.open(IO_ReadWrite) )
        {
            TQTextStream st(TQT_TQIODEVICE(&folder));
            st.setEncoding( KJotsSettings::unicode() ? TQTextStream::UnicodeUTF8 : TQTextStream::Locale );
            TQString buf = st.readLine().stripWhiteSpace();

            //Check for new-style book. Not very pretty, but it is faster than loading the DOM.
            if (buf == "<!DOCTYPE KJots>")
            {
                test=true;
            }
            else
            //Check for old-style book. See KJotsBook::loadOldBook()
            if (buf.left(9) == "\\NewEntry")
            {
                test=true;
            }

        }
    }

    return test;
}

/*!
    \brief Reads a book in from a disk file.
    This function is only called for root-level books.
*/
bool KJotsBook::openBook(const TQString& filename)
{
    if ( !m_open ) //sanity check
    {
        listView()->setUpdatesEnabled(false);
        m_fileName = filename;

        if ( m_fileName.isEmpty() ) //new books names are empty.
        {
            addPage();
            m_open = true;
        } else {
            TQFile file(m_fileName);
    
            if ( file.exists() && file.open(IO_ReadWrite) ) //TODO: Implement read-only mode?
            {
                TQTextStream st(TQT_TQIODEVICE(&file));
                st.setEncoding(  KJotsSettings::unicode() ? TQTextStream::UnicodeUTF8 : TQTextStream::Locale );
                TQString data = st.read();

                TQDomDocument doc( "KJots" );
                if ( doc.setContent( data ) ) 
                {
                    TQDomElement docElem = doc.documentElement();
            
                    if ( docElem.tagName() == "KJots" )
                    {
                        TQDomNode n = docElem.firstChild();
                        while( !n.isNull() ) 
                        {
                            TQDomElement e = n.toElement(); // try to convert the node to an element.
                            if( !e.isNull() && e.tagName() == "KJotsBook" ) 
                            {
                                    parseXml(e);
                            }
                            n = n.nextSibling();
                        }
                    }

                } else {
                    //Woah. Something didn't work right. Maybe this is an old file?
                    file.reset();
                    if ( loadOldBook(file) ) 
                    {
                        TQFileInfo fi( file );
                        setSubject(fi.fileName());
                    }
                }
            }
    
            if ( !childCount() ) //sanity check
            {
                //We should NOT be here. That must not have been a book file, or it is damaged. 
                //To make things happy-happy, we just create a blank page and continue. 
                //TODO: Add an information message? Make a translater work for something so unlikely?
                addPage();
            }
    
            m_open = true;

            // Support legacy files. Can be removed at some point. CREATION DATE: 2005/06/04
            if ( !m_fileName.isEmpty() && !m_fileName.endsWith(".book") )
            {
                //some old books have incorrect names. So we save a new copy, then kill the old file
                m_fileName = TQString(); //trick ourselves into thinking we're a new book
                saveBook();
                file.remove();
            }
        }
    
        listView()->setUpdatesEnabled(true);

        // Support legacy files. Can be removed at some point. CREATION DATE: 2005/06/07
        if ( m_open && !id() )
        {
            //This book (and its pages) need new IDs!
            setId(0);

            KJotsPage *page = dynamic_cast<KJotsPage*>(firstChild());
            while ( page )
            {
                page->setId(0); //TODO: Make setId() a protected function if this legacy code is removed.
                page = dynamic_cast<KJotsPage*>(page->nextSibling());
            }
        }
    }

    return m_open;
}

/*!
    \brief Load an old-style book file.

    This is a function for files made from older KJots versions. It could probably be removed
    at some point in the future. CREATION DATE: 2005/05/30 
*/
bool KJotsBook::loadOldBook(TQFile &file)
{
    TQTextStream st(TQT_TQIODEVICE(&file));
    st.setEncoding(  KJotsSettings::unicode() ? TQTextStream::UnicodeUTF8 : TQTextStream::Locale );
    TQString buf = st.readLine();

    if (buf.left(9) != "\\NewEntry")
    {
        addPage();
        return false;
    }

    KJotsPage *entry = 0;
    TQString body;

    bool quit=false;

    while (1)
    {
        if (buf.left(9) == "\\NewEntry")
        {
            if (entry)
            {
                entry->setBody(body);
            }

            body = TQString();
            TQString title = buf.mid(10, buf.length());

            // now catch the page id
            buf = st.readLine();
            if (buf.left(3) == "\\ID")
            {
                buf = st.readLine();
            }

            entry = new KJotsPage(this, entry);
            entry->setSubject(title);
        }

        int pos = 0;

        while ((pos = buf.find('\\',pos)) != -1)
            if (buf[++pos] == '\\')
                buf.remove(pos, 1 );

        body.append( buf + "\n");

        if (quit)
            break;

        buf = st.readLine();

        quit = st.eof();
    }

    entry->setBody(body);
    return true;
}

/*!
    \brief Saves this book and everything in it to the data directory.
*/
void KJotsBook::saveBook(void)
{
    if (!m_open) //sanity check
        return;

    // Are we a new book?
    if ( m_fileName.isEmpty() )
    {
        KTempFile temp(locateLocal("appdata",""), ".book", 0644);
        m_fileName = temp.name();
    }

    TQFile file(m_fileName);
    if (file.open(IO_WriteOnly | IO_Truncate)) 
    {
        TQDomDocument doc("KJots");
        TQDomElement root = doc.createElement( "KJots" );
        doc.appendChild( root );

        this->generateXml( doc, root ); //recursive

        TQTextStream st((TQIODevice *) &file);
        st.setEncoding(  KJotsSettings::unicode() ? TQTextStream::UnicodeUTF8 : TQTextStream::Locale );
        st << doc.toString();

        file.close();
    }

}

/*!
    \brief Deletes a book by removing the data file. 
    This does not affect the list display, and can be called for reasons other than 
    choosing to delete an entry from the list. If you want the object to dissappear
    from the list, then you have to delete it.
*/
void KJotsBook::deleteBook()
{
    TQFile::remove(m_fileName);
    m_fileName = TQString();
}

void KJotsBook::rename()
{
    bool ok;
    TQString name = KInputDialog::getText(i18n( "Rename Book" ),
                                         i18n( "Book name:" ),
                                         subject(), &ok, listView());
    if (ok)
    {
        setSubject(name);

        KJotsMain* m = dynamic_cast<KJotsMain*>(kapp->mainWidget());

        if (m)
            m->updateCaption();

        setDirty(true);
    }
}

/*!
    \brief Initiated when the user chooses to save this to a file.
    This function gets everything ready to go to save to the disk.
*/
void KJotsBook::saveToFile(KURL url, bool plainText, const TQString& encoding)
{
    if (url.isEmpty() || m_saveInProgress)
        return;

    m_saveToPlainText = plainText;
    m_saveEncoding = TQTextCodec::codecForName(encoding.ascii());
    KIO::TransferJob* job = KIO::put(url, -1, true, false, false);

    if (!job)
    {
        return;
    }

    //NOTE: The current implementation does not need the progress dialog, but further
    //revisions will likely use it. I don't want to make the translators add, remove,
    //and re-add translations, so I'm just keeping this here for now. 
    m_saveProgressDialog = new KProgressDialog(listView(), "bookSaveInProgress",
                                               i18n("Saving %1").tqarg(subject()),
                                               i18n("Saving the contents of %1 to %2")
                                                    .tqarg(subject(), url.prettyURL()),
                                               true);

    m_saveProgressDialog->progressBar()->setTotalSteps(1);
    m_saveProgressDialog->showCancelButton(false);
    m_saveProgressDialog->setAutoClose(true);

    connect(job, TQT_SIGNAL(dataReq(KIO::Job*, TQByteArray&)), TQT_SLOT(saveDataReq(KIO::Job*, TQByteArray&)));
    connect(job, TQT_SIGNAL(result( KIO::Job *)), TQT_SLOT(slotSaveResult( KIO::Job *)));

    m_saveInProgress = true;
}

/*!
    \brief Pumps out data when saving to a file.
    This function pumps out page data during a disk save. 
*/
void KJotsBook::saveDataReq(KIO::Job* /* job */, TQByteArray& data)
{
    if (!m_saveInProgress) return; //sanity check

    TQTextStream stream(data, IO_WriteOnly);
    stream.setCodec(m_saveEncoding);

    if (!m_saveToPlainText)
    {
        stream << htmlHeader(subject(), m_saveEncoding);
        stream << generateHtml(this, true);
        stream << htmlFooter();
    } else {
        stream << generateText();
    }

    m_saveInProgress = false;
}

/*!
    \brief Completes a disk save.
    This function is called after a disk save. The disk save may or may 
    not have completed normally.
*/
void KJotsBook::slotSaveResult(KIO::Job *)
{
    m_saveInProgress = false;
    delete m_saveProgressDialog;
    m_saveProgressDialog = 0;
    /* if (job->error() != 0) {} */
}

/*!
    \brief Add a new page to the end of this book.
*/
KJotsPage* KJotsBook::addPage()
{
    TQListViewItem *after = 0;

    // append new pages
    TQListViewItem* tmp = firstChild();
    while (tmp)
    {
        after = tmp;
        tmp = tmp->nextSibling();
    }

    KJotsPage *page = new KJotsPage(this, after);
    page->initNewPage();
    return page;
}

/*!
    \brief Called when the user wants to print the book.
*/
void KJotsBook::print(TQFont& defaultFont)
{
    KPrinter printer;
    printer.setDocName(subject());
    printer.setFullPage(false);
    printer.setCreator("KJots");

    if (!printer.setup(listView(), i18n("Print: %1").tqarg(subject())))
    {
        return;
    }

    TQPainter painter(&printer);
    painter.setFont(defaultFont);
    print(printer, painter, 0);

    painter.end();
}

/*!
    \brief Prints this book.
*/
int KJotsBook::print(KPrinter& printer, TQPainter& painter, int y)
{
    y = printTitleBox(subject(), printer, painter, y);

    KJotsEntryBase* entry = dynamic_cast<KJotsEntryBase*>(firstChild());
    while (entry)
    {
        y = entry->print(printer, painter, y);
        entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
    }

    return y;
}

TQString KJotsBook::defaultSubject()
{
    return i18n("Untitled Book");
}

/*!
    \brief Does this book need to be saved?
    This function recursively checks itself, and all books and pages it owns to
    see if any changes have been made.
*/
bool KJotsBook::isDirty()
{
    //Am I dirty?
    if ( KJotsEntryBase::isDirty() ) return true;

    //Check all tqchildren to see if any of them are dirty
    KJotsEntryBase *entry = dynamic_cast<KJotsEntryBase*>(firstChild());
    while ( entry )
    {
        if ( entry->isDirty() ) return true;
        entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
    }

    return false;
}

/*!
    \brief Creates XML code and performs necessary tasks to save file.
    This function should ONLY be called when saving the file.
*/
void KJotsBook::generateXml( TQDomDocument &doc, TQDomElement &parent )
{
    TQDomElement book = doc.createElement( "KJotsBook" );
    parent.appendChild( book );

    KJotsEntryBase::generateXml(doc, book); //let the base class save important stuff

    TQDomElement open = doc.createElement( "Open" );
    open.appendChild( this->isOpen() ? doc.createTextNode("1") : doc.createTextNode("0") );
    book.appendChild( open );

    KJotsEntryBase* entry = dynamic_cast<KJotsEntryBase*>(firstChild());
    while ( entry )
    {
        entry->generateXml( doc, book );
        entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
    }

    if ( !m_fileName.isEmpty() && TQListViewItem::parent() )
    {
        //Hmmmm... We were originally loaded from a file, but now we have a parent, so
        //we must have been moved into another tree. Remove the old file now that we
        //have saved ourselves into the new tree.
        deleteBook();
    }

    return;
}

/*!
    Parses through XML code from a file.
*/
void KJotsBook::parseXml( TQDomElement &me )
{
    KJotsEntryBase *lastEntry = 0; //keep track of the last entry inserted for speed

    if ( me.tagName() == "KJotsBook" )
    {
        TQDomNode n = me.firstChild();
        while( !n.isNull() ) 
        {
            TQDomElement e = n.toElement(); // try to convert the node to an element.
            if ( !e.isNull() ) 
            {
                if ( e.tagName() == "KJotsPage" ) 
                {
                    KJotsPage *page = new KJotsPage(this, lastEntry);
                    page->parseXml(e);
                    lastEntry=page;
                } 
                else
                if ( e.tagName() == "KJotsBook" ) 
                {
                    KJotsBook *book = new KJotsBook(this, lastEntry);
                    book->parseXml(e);
                    lastEntry=book;
                } 
                else
                if ( e.tagName() == "Open" ) 
                {
                    if ( e.text() == "1" )
                    {
                        this->setOpen(true);
                    }
                } 
                else
                {
                    //What was this? Send it to the base class and see if it can figure it out.
                    KJotsEntryBase::parseXml(e);
                }
            }
            n = n.nextSibling();
        }
    }

    return;
}

/*!
    \brief Returns an HTML Table of contents for this book.
    This is a helper function for generateHtml().
*/
TQString KJotsBook::getToc()
{
    TQString toc;

    toc += "<ul>";

    KJotsEntryBase *entry = dynamic_cast<KJotsEntryBase*>(firstChild());
    while ( entry ) {
        TQString htmlSubject = prepForHTML(entry->subject());
        toc += TQString("<li><a href=\"#%1\">").tqarg(entry->id()) + htmlSubject + "</a></li>";

        KJotsBook *book = dynamic_cast<KJotsBook*>(entry);
        if ( book ) toc += book->getToc();

        entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
    }

    toc += "</ul>";
    return toc;
}

/*!
    \brief Returns HTML for the read-only "book" view.
    \param top Pointer to the "starting point" of this tree.
    \param diskMode Files saved to disk have a slightly different format.
*/
TQString KJotsBook::generateHtml( KJotsEntryBase* top, bool diskMode )
{
    TQString toc, body;
    TQString htmlTitle = prepForHTML(subject());

    if ( top == this )
    {
        toc = TQString("<h1><a name=\"%1\">%2</a></h1>").tqarg(id()).tqarg(htmlTitle);
    } else {
        if ( diskMode )
        {
            toc = TQString("<h2><a name=\"%1\">%2</a></h2>").tqarg(id()).tqarg(htmlTitle);
        } else {
            toc = TQString("<h2><a name=\"%1\" href=\"%2\">%3</a></h2>").tqarg(id()).tqarg(id()).tqarg(htmlTitle);
        }
    }

    toc += "<h3>" + i18n("Table of Contents") + "</h3>";
    toc += getToc();
    toc += "<hr>";

    // Do the body text of the entries.
    KJotsEntryBase* entry = dynamic_cast<KJotsEntryBase*>(firstChild());
    while ( entry )
    {
        body += entry->generateHtml(top, diskMode);
        entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
    }

    return toc + body;
}

/*!
    \brief Returns Text when saving to a file.

    This functions output moderately formatted text when the user chooses to save as
    a text file. 
*/
TQString KJotsBook::generateText( void )
{
    TQString out;

    //Print Fancy Text header
    TQString line, buf;
    line.fill('#', subject().length() + 2);
    line += "\n";
    out = line + TQString("# ") + subject() + TQString("\n") + line;

    KJotsEntryBase* entry = dynamic_cast<KJotsEntryBase*>(firstChild());
    while ( entry )
    {
        out += entry->generateText();
        entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
    }

    out += "\n";
    return out;
}

//
// KJotsPage
//

KJotsPage::KJotsPage(KJotsBook* parent, TQListViewItem *after)
    : KJotsEntryBase(parent,after),
    m_editor(0)
{
    m_isBook = false;
    m_paraPos = m_indexPos = 0;
    setPixmap(0, kapp->iconLoader()->loadIcon(TQString("edit"), KIcon::Small));
}

KJotsPage::~KJotsPage()
{
    if ( m_editor )
    {
        //Well now, this isn't good. We're going bye-bye but the editor
        //still thinks we're here. Set ourselves to 0 (IMPORTANT!!) and
        //then clear the editor.
        KJotsEdit *temp = m_editor;
        m_editor=0;
        temp->setEntry(0);
    }
}

/*!
    \brief Sets up info for a new page.

    This should be called on brand new pages.
*/
void KJotsPage::initNewPage(void)
{
    setId(0);
    setSubject(defaultSubject());
}

/*!
    \brief Return the text of this page.
*/
TQString KJotsPage::body()
{
    //if we're being edited we want the current text, not whatever we saved before.
    if ( m_editor && m_editor->edited() )
    {
        m_text = m_editor->text();
        m_editor->setEdited(false);
        setDirty(true);
    }

    return m_text;
}

/*!
    \brief Sets the text of this page.
*/
void KJotsPage::setBody(const TQString& text)
{
    assert ( !m_editor ); //m_editor should *never* be set.
    m_text = text;
}

void KJotsPage::rename()
{
    bool ok;

    TQString name = KInputDialog::getText(i18n( "Rename Page" ),
                                         i18n( "Page title:" ),
                                         subject(), &ok, listView() );

    if (ok)
    {
        setSubject(name);

        KJotsMain* m = dynamic_cast<KJotsMain*>(kapp->mainWidget());

        if (m)
            m->updateCaption();

        setDirty(true);
    }
}

/*!
    \brief Initiated when the user chooses to save this to a file.
    This function gets everything ready to go to save to the disk.
*/
void KJotsPage::saveToFile(KURL url, bool plainText, const TQString& encoding)
{
    if (url.isEmpty() || m_saveInProgress)
        return;

    m_saveToPlainText = plainText;
    m_saveEncoding = TQTextCodec::codecForName(encoding.ascii());
    KIO::TransferJob* job = KIO::put(url, -1, true, false, false);
    if (!job)
    {
        return;
    }

    connect(job, TQT_SIGNAL(dataReq(KIO::Job*, TQByteArray&)), TQT_SLOT(saveDataReq(KIO::Job*, TQByteArray&)));
    connect(job, TQT_SIGNAL(result( KIO::Job *)), TQT_SLOT(slotSaveResult( KIO::Job *)));
    m_saveInProgress = true;
}

/*!
    \brief Pumps out data when saving to a file.
    This function pumps out page data during a disk save. 

    \todo This should be augmented to cycle in case of REALLY long pages.
*/
void KJotsPage::saveDataReq(KIO::Job* /* job */, TQByteArray& data)
{
    if (!m_saveInProgress) return; //sanity check

    TQTextStream stream(data, IO_WriteOnly);
    stream.setCodec(m_saveEncoding);

    if ( !m_saveToPlainText ) 
    {
        stream << htmlHeader(subject(), m_saveEncoding);
        stream << generateHtml(this, true);
        stream << htmlFooter();
    } else {
        stream << generateText();
    }

    m_saveInProgress = false;
}

/*!
    \brief Completes a disk save.
    This function is called after a disk save. The disk save may or may 
    not have completed normally.
*/
void KJotsPage::slotSaveResult(KIO::Job *)
{
    m_saveInProgress = false;
    /* if (job->error() != 0) {} */
}

void KJotsPage::print(TQFont& defaultFont)
{
    KJotsEntryBase* book = dynamic_cast<KJotsEntryBase*>(KListViewItem::parent());

    TQString docName = book->subject();
    if (!subject().isNull())
    {
        docName += ": " + subject();
    }

    KPrinter printer;
    printer.setDocName(docName);
    printer.setFullPage(false);
    printer.setCreator("KJots");

    if (printer.setup(listView(), i18n("Print: %1").tqarg(docName)))
    {
        TQPainter painter( &printer );
        painter.setFont(defaultFont);
        print(printer, painter, 0);
        painter.end();
    }
}

/*!
    \brief Prints this page.
*/
int KJotsPage::print(KPrinter& printer, TQPainter& painter, int y)
{
    TQPaintDeviceMetrics metrics( &printer );
    int maxWidth = metrics.width();
    int maxHeight = metrics.height();
    //TODO: Is it really necessary to copy the entire body when printing?
    TQStringList paragraphs = TQStringList::split(TQChar('\n'), body(), true);

    y = printTitleBox(subject(), printer, painter, y);

    for (TQStringList::iterator para = paragraphs.begin();
         para != paragraphs.end();
         ++para)
    {
        //Watch for blank lines inserted as spacers.
        if ( (*para).isNull() ) *para = " ";

        TQRect r = painter.boundingRect(0, y,
                                       maxWidth, maxHeight,
                                       TQPainter::ExpandTabs | TQPainter::WordBreak,
                                       *para);

        if ((y + r.height()) > maxHeight)
        {
            printer.newPage();
            y = 0;
        }

        painter.drawText(0, y, maxWidth, maxHeight - y,
                TQPainter::ExpandTabs | TQPainter::WordBreak,
                *para);
        y += r.height();
    }

    return y;
}

/*!
    \brief Get the default title of this page.
    \note This is only used by initNewPage(); it could probably be removed.
*/
TQString KJotsPage::defaultSubject()
{
    int page = 0;

    if ( parentBook() )
    {
        //We can't use childCount() here because it will count books, too.
        KJotsEntryBase *entry = dynamic_cast<KJotsEntryBase*>(parentBook()->firstChild());
        while ( entry )
        {
            if ( entry->isPage() ) ++page;
            entry = dynamic_cast<KJotsEntryBase*>(entry->nextSibling());
        }
    } else {
        //We should never be here.
        page = 1;
    }

    return i18n("Page %1").tqarg(page);
}

/*!
    \brief Tells this page that it has been loaded into the edit window.
*/
void KJotsPage::setEditor( KJotsEdit *editor )
{
    //out with the old...
    if ( m_editor )
    {
        m_editor->getCursorPosition(&m_paraPos, &m_indexPos);

        if ( m_editor->edited() )
        {
            m_text = m_editor->text();
            setDirty(true);
        }
    }

    m_editor = editor;

    //and in with the new
    if ( m_editor )
    {
        m_editor->setEdited(false);
        m_editor->setCursorPosition(m_paraPos, m_indexPos);
    }

    return;
}

/*!
    \brief Has the data in this page been changed?
    We first check the editor status, if we are being edited. Then we let 
    the base class handle things for us.
*/
bool KJotsPage::isDirty()
{
    if ( m_editor && m_editor->edited() )
    {
        setDirty(true);
    }

    return KJotsEntryBase::isDirty();
}

/*!
    \brief Creates XML code and performs necessary tasks to save file.
    This function should ONLY be called when saving the file.
*/void KJotsPage::generateXml( TQDomDocument &doc, TQDomElement &parent )
{
    TQDomElement page = doc.createElement( "KJotsPage" );
    parent.appendChild( page );

    KJotsEntryBase::generateXml(doc, page); //let the base class save important stuff

    TQDomElement text = doc.createElement( "Text" );
    TQString saveText = body();
    if ( saveText.contains("]]>") ) {
        saveText.replace("]]>","]]&gt;");
        text.setAttribute("fixed", "1");
    }
    text.appendChild( doc.createCDATASection( saveText ));
    page.appendChild( text );

    return;
}

/*!
    Parses through XML code from a file.
*/
void KJotsPage::parseXml( TQDomElement &me )
{
    if ( me.tagName() == "KJotsPage" )
    {
        TQDomNode n = me.firstChild();
        while( !n.isNull() ) 
        {
            TQDomElement e = n.toElement(); // try to convert the node to an element.
            if ( !e.isNull() ) 
            {
                if ( e.tagName() == "Text" ) 
                {
                    TQString bodyText = e.text();
                    if ( e.hasAttribute("fixed") ) 
                    {
                        bodyText.replace("]]&gt;", "]]>");
                    }
                    setBody(bodyText);
                } 
                else
                {
                    //What was this? Send it to the base class and see if it can figure it out.
                    KJotsEntryBase::parseXml(e);
                }
            }
            n = n.nextSibling();
        }
    }

    return;
}

/*!
    \brief Returns HTML for the read-only "book" overview.
    \param top This tells us that we are the toplevel.
    \param diskMode Files saved to disk have a slightly different format.
*/
TQString KJotsPage::generateHtml( KJotsEntryBase *top, bool diskMode )
{
    TQString html;
    TQString htmlSubject = prepForHTML(subject());

    if ( top == this || diskMode ) {
        html += TQString("<h3><a name=\"%1\">%2</a></h3>").tqarg(id()).tqarg(htmlSubject);
    } else {
        html += TQString("<h3><a name=\"%1\" href=\"%2\">%3</a></h3>").tqarg(id()).tqarg(id()).tqarg(htmlSubject);
    }
    html += prepForHTML(body());

    html += "<br><table border=1><tr>";
    html += TQString("<td><a href=\"#%1\">%2</a></td>").tqarg(id()).tqarg(subject());

    if ( top != this ) 
    {
        KJotsBook *parent = parentBook();
        while ( parent )
        {
            html += TQString("<td><a href=\"#%1\">%2</a></td>").tqarg(parent->id()).tqarg(parent->subject());
            if ( parent == top ) break;
            parent = parent->parentBook();
        }
    }
    html += TQString("</tr></table>");

    if ( top != this ) html += "<hr>";
    return html;
}

/*!
    \brief Returns Text when saving to a file.
    \param top This is a hint to specify if this book is the "starting point" or not.

    This functions output moderately formatted text when the user chooses to save as
    a text file. 
*/
TQString KJotsPage::generateText( void )
{
    TQString out;

    //Print Fancy Text header
    TQString line, buf;
    line.fill('#', subject().length() + 2);
    line += "\n";
    out = line + TQString("# ") + subject() + TQString("\n") + line;

    out += body();

    out += "\n";
    return out;
}

/* ex: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: */

#include "kjotsentry.moc"