summaryrefslogtreecommitdiffstats
path: root/kmail/kmfoldersearch.cpp
blob: 29c0c8abe6a9f51a1c90593bec9a5279b3b3d66c (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
/*
    This file is part of KMail, the KDE mail client.
    Copyright (c) 2000 Don Sanders <sanders@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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
*/

//Factor byteswap stuff into one header file

#include <config.h>

#include "kmfoldersearch.h"
#include "kmfolderimap.h"
#include "kmfoldermgr.h"
#include "kmsearchpattern.h"
#include "kmmsgdict.h"
#include "index.h"
#include "jobscheduler.h"

#include <kdebug.h>
#include <tdelocale.h>
#include <tdeconfig.h>

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <utime.h>

#include <tqfile.h>

#ifdef HAVE_BYTESWAP_H
#include <byteswap.h>
#endif

// We define functions as kmail_swap_NN so that we don't get compile errors
// on platforms where bswap_NN happens to be a function instead of a define.

/* Swap bytes in 32 bit value.  */
#ifndef kmail_swap_32
#ifdef bswap_32
#define kmail_swap_32(x) bswap_32(x)
#else
#define kmail_swap_32(x) \
     ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >>  8) |               \
      (((x) & 0x0000ff00) <<  8) | (((x) & 0x000000ff) << 24))
#endif
#endif // kmail_swap_32

// Current version of the .index.search files
#define IDS_SEARCH_VERSION 1000
// The asterisk at the end is important
#define IDS_SEARCH_HEADER "# KMail-Search-IDs V%d\n*"
#define IDS_SEARCH_HEADER_LEN 30


KMSearch::KMSearch(TQObject * parent, const char * name)
    :TQObject(parent, name)
{
    mRemainingFolders = -1;
    mRecursive = true;
    mRunByIndex = mRunning = false;
    mRoot = 0;
    mSearchPattern = 0;
    mFoundCount = 0;
    mSearchCount = 0;

    mProcessNextBatchTimer = new TQTimer(0, "mProcessNextBatchTimer");
    connect(mProcessNextBatchTimer, TQ_SIGNAL(timeout()), this, TQ_SLOT(slotProcessNextBatch()));
}

KMSearch::~KMSearch()
{
    delete mProcessNextBatchTimer;
    delete mSearchPattern;
}

bool KMSearch::write(TQString location) const
{
    TDEConfig config(location);
    config.setGroup("Search Folder");
    if (mSearchPattern)
        mSearchPattern->writeConfig(&config);
    if (mRoot.isNull())
        config.writeEntry("Base", "");
    else
        config.writeEntry("Base", mRoot->idString());
    config.writeEntry("Recursive", recursive());
    return true;
}

bool KMSearch::read(TQString location)
{
    TDEConfig config( location );
    config.setGroup( "Search Folder" );
    if ( !mSearchPattern )
        mSearchPattern = new KMSearchPattern();
    mSearchPattern->readConfig( &config );
    TQString rootString = config.readEntry( "Base" );
    mRoot = kmkernel->findFolderById( rootString );
    mRecursive = config.readBoolEntry( "Recursive" );
    return true;
}

void KMSearch::setSearchPattern(KMSearchPattern *searchPattern)
{
    if ( running() )
        stop();
    if ( mSearchPattern != searchPattern ) {
        delete mSearchPattern;
        mSearchPattern = searchPattern;
    }
}

bool KMSearch::inScope(KMFolder* folder) const
{
    if ( mRoot.isNull() || folder == mRoot )
        return true;
    if ( !recursive() )
        return false;

    KMFolderDir *rootDir = mRoot->child();
    KMFolderDir *ancestorDir = folder->parent();
    while ( ancestorDir ) {
        if ( ancestorDir == rootDir )
            return true;
        ancestorDir = ancestorDir->parent();
    }
    return false;
}

void KMSearch::start()
{
    //close all referenced folders
    TQValueListIterator<TQGuardedPtr<KMFolder> > fit;
    for (fit = mOpenedFolders.begin(); fit != mOpenedFolders.end(); ++fit) {
        if (!(*fit))
            continue;
        (*fit)->close( "kmsearch" );
    }
    mOpenedFolders.clear();
    mFolders.clear();

    if ( running() )
        return;

    if ( !mSearchPattern ) {
        emit finished(true);
        return;
    }

    mFoundCount = 0;
    mSearchCount = 0;
    mRunning = true;
    mRunByIndex = false;
    // check if this query can be done with the index
    if ( kmkernel->msgIndex() && kmkernel->msgIndex()->startQuery( this ) ) {
        mRunByIndex = true;
        return;
    }

    mFolders.append( mRoot );
    if ( recursive() )
    {
        //Append all descendants to folders
        KMFolderNode* node;
        KMFolder* folder;
        TQValueListConstIterator<TQGuardedPtr<KMFolder> > it;
        for ( it = mFolders.begin(); it != mFolders.end(); ++it )
        {
            folder = *it;
            KMFolderDir *dir = 0;
            if ( folder )
                dir = folder->child();
            else
                dir = &kmkernel->folderMgr()->dir();
            if ( !dir )
                continue;
            TQPtrListIterator<KMFolderNode> it(*dir);
            while ( (node = it.current()) ) {
                ++it;
                if ( !node->isDir() ) {
                    KMFolder* kmf = dynamic_cast<KMFolder*>( node );
                    if ( kmf )
                        mFolders.append( kmf );
                }
            }
        }
    }

    mRemainingFolders = mFolders.count();
    mLastFolder = TQString();
    mProcessNextBatchTimer->start( 0, true );
}

void KMSearch::stop()
{
    if ( !running() )
        return;
    if ( mRunByIndex ) {
        if ( kmkernel->msgIndex() )
            kmkernel->msgIndex()->stopQuery( this );
    } else {
        mIncompleteFolders.clear();
        TQValueListConstIterator<TQGuardedPtr<KMFolder> > jt;
        for ( jt = mOpenedFolders.begin(); jt != mOpenedFolders.end(); ++jt ) {
            KMFolder *folder = *jt;
            if ( !folder )
                continue;
            // explicitely stop jobs for this folder as it will not be closed below
            // when the folder is currently selected
            if ( folder->folderType() == KMFolderTypeImap ) {
                KMAcctImap *account =
                    static_cast<KMFolderImap*>( folder->storage() )->account();
                account->ignoreJobsForFolder( folder );
            }
            folder->storage()->search( 0 );
            mSearchCount += folder->count();
            folder->close("kmsearch");
        }
    }
    mRemainingFolders = -1;
    mOpenedFolders.clear();
    mFolders.clear();
    mLastFolder = TQString();
    mRunByIndex = mRunning = false;
    emit finished(false);
}

void KMSearch::indexFinished() {
    mRunning = false;
    mRunByIndex = false;
}

void KMSearch::slotProcessNextBatch()
{
    if ( !running() )
        return;

    if ( mFolders.count() != 0 )
    {
        KMFolder *folder = *( mFolders.begin() );
        mFolders.erase( mFolders.begin() );
        if ( folder )
        {
            mLastFolder = folder->label();
            folder->open("kmsearch");
            mOpenedFolders.append( folder );
            connect( folder->storage(),
                TQ_SIGNAL( searchResult( KMFolder*, TQValueList<TQ_UINT32>, const KMSearchPattern*, bool ) ),
                this,
                TQ_SLOT( slotSearchFolderResult( KMFolder*, TQValueList<TQ_UINT32>, const KMSearchPattern*, bool ) ) );
            folder->storage()->search( mSearchPattern );
        } else
            --mRemainingFolders;
        mProcessNextBatchTimer->start( 0, true );
        return;
    }
}

void KMSearch::slotSearchFolderResult( KMFolder* folder,
                                       TQValueList<TQ_UINT32> serNums,
                                       const KMSearchPattern* pattern,
                                       bool complete )
{
    if ( pattern != mSearchPattern )
      return;
    kdDebug(5006) << k_funcinfo << folder->label() << " found " << serNums.count() << endl;
    mLastFolder = folder->label();
    TQValueListIterator<TQ_UINT32> it;
    for ( it = serNums.begin(); it != serNums.end(); ++it )
    {
      emit found( *it );
      ++mFoundCount;
    }
    if ( complete )
    {
      disconnect( folder->storage(),
          TQ_SIGNAL( searchResult( KMFolder*, TQValueList<TQ_UINT32>,
                                const KMSearchPattern*, bool ) ),
          this,
          TQ_SLOT( slotSearchFolderResult( KMFolder*, TQValueList<TQ_UINT32>,
                                        const KMSearchPattern*, bool ) ) );
      --mRemainingFolders;
      mSearchCount += folder->count();
      folder->close("kmsearch");
      mOpenedFolders.remove( folder );
      if ( mRemainingFolders <= 0 )
      {
        mRemainingFolders = 0;
        mRunning = false;
        mLastFolder = TQString();
        mRemainingFolders = -1;
        mFolders.clear();
        emit finished( true );
      }
    }
}

//-----------------------------------------------------------------------------
KMFolderSearch::KMFolderSearch(KMFolder* folder, const char* name)
  : FolderStorage(folder, name)
{
    mIdsStream = 0;
    mSearch = 0;
    mInvalid = false;
    mUnlinked = true;
    mTempOpened = false;
    setNoChildren(true);

    //Hook up some slots for live updating of search folders
    //TODO: Optimize folderInvalidated, folderAdded, folderRemoved
    connect(kmkernel->folderMgr(), TQ_SIGNAL(msgAdded(KMFolder*, TQ_UINT32)),
            this, TQ_SLOT(examineAddedMessage(KMFolder*, TQ_UINT32)));
    connect(kmkernel->folderMgr(), TQ_SIGNAL(msgRemoved(KMFolder*, TQ_UINT32)),
            this, TQ_SLOT(examineRemovedMessage(KMFolder*, TQ_UINT32)));
    connect(kmkernel->folderMgr(), TQ_SIGNAL(msgChanged(KMFolder*, TQ_UINT32, int)),
            this, TQ_SLOT(examineChangedMessage(KMFolder*, TQ_UINT32, int)));
    connect(kmkernel->folderMgr(), TQ_SIGNAL(folderInvalidated(KMFolder*)),
            this, TQ_SLOT(examineInvalidatedFolder(KMFolder*)));
    connect(kmkernel->folderMgr(), TQ_SIGNAL(folderAdded(KMFolder*)),
            this, TQ_SLOT(examineInvalidatedFolder(KMFolder*)));
    connect(kmkernel->folderMgr(), TQ_SIGNAL(folderRemoved(KMFolder*)),
            this, TQ_SLOT(examineRemovedFolder(KMFolder*)));
    connect(kmkernel->folderMgr(), TQ_SIGNAL(msgHeaderChanged(KMFolder*,int)),
            this, TQ_SLOT(propagateHeaderChanged(KMFolder*,int)));

    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(msgAdded(KMFolder*, TQ_UINT32)),
            this, TQ_SLOT(examineAddedMessage(KMFolder*, TQ_UINT32)));
    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(msgRemoved(KMFolder*, TQ_UINT32)),
            this, TQ_SLOT(examineRemovedMessage(KMFolder*, TQ_UINT32)));
    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(msgChanged(KMFolder*, TQ_UINT32, int)),
            this, TQ_SLOT(examineChangedMessage(KMFolder*, TQ_UINT32, int)));
    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(folderInvalidated(KMFolder*)),
            this, TQ_SLOT(examineInvalidatedFolder(KMFolder*)));
    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(folderAdded(KMFolder*)),
            this, TQ_SLOT(examineInvalidatedFolder(KMFolder*)));
    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(folderRemoved(KMFolder*)),
            this, TQ_SLOT(examineRemovedFolder(KMFolder*)));
    connect(kmkernel->imapFolderMgr(), TQ_SIGNAL(msgHeaderChanged(KMFolder*,int)),
            this, TQ_SLOT(propagateHeaderChanged(KMFolder*,int)));

    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(msgAdded(KMFolder*, TQ_UINT32)),
            this, TQ_SLOT(examineAddedMessage(KMFolder*, TQ_UINT32)));
    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(msgRemoved(KMFolder*, TQ_UINT32)),
            this, TQ_SLOT(examineRemovedMessage(KMFolder*, TQ_UINT32)));
    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(msgChanged(KMFolder*, TQ_UINT32, int)),
            this, TQ_SLOT(examineChangedMessage(KMFolder*, TQ_UINT32, int)));
    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(folderInvalidated(KMFolder*)),
            this, TQ_SLOT(examineInvalidatedFolder(KMFolder*)));
    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(folderAdded(KMFolder*)),
            this, TQ_SLOT(examineInvalidatedFolder(KMFolder*)));
    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(folderRemoved(KMFolder*)),
            this, TQ_SLOT(examineRemovedFolder(KMFolder*)));
    connect(kmkernel->dimapFolderMgr(), TQ_SIGNAL(msgHeaderChanged(KMFolder*,int)),
            this, TQ_SLOT(propagateHeaderChanged(KMFolder*,int)));

  mExecuteSearchTimer = new TQTimer(0, "mExecuteSearchTimer");
  connect(mExecuteSearchTimer, TQ_SIGNAL(timeout()),
          this, TQ_SLOT(executeSearch()));
}

KMFolderSearch::~KMFolderSearch()
{
    delete mExecuteSearchTimer;
    delete mSearch;
    mSearch = 0;
    if (mOpenCount > 0)
        close("~foldersearch", TRUE);
}

void KMFolderSearch::setSearch(KMSearch *search)
{
    truncateIndex(); //new search old index is obsolete
    emit cleared();
    mInvalid = false;
    setDirty( true ); //have to write the index
    if (!mUnlinked) {
        unlink(TQFile::encodeName(indexLocation()));
        mUnlinked = true;
    }
    if (mSearch != search) {
        mSearch->stop();
        delete mSearch;
        mSearch = search; // take ownership
        if (mSearch) {
            TQObject::connect(search, TQ_SIGNAL(found(TQ_UINT32)),
                    TQ_SLOT(addSerNum(TQ_UINT32)));
            TQObject::connect(search, TQ_SIGNAL(finished(bool)),
                    TQ_SLOT(searchFinished(bool)));
        }
    }
    if (mSearch)
        mSearch->write(location());
    clearIndex();
    mTotalMsgs = 0;
    mUnreadMsgs = 0;
    emit numUnreadMsgsChanged( folder() );
    emit changed(); // really want a kmfolder cleared signal
    /* TODO There is KMFolder::cleared signal now. Adjust. */
    if (mSearch)
        mSearch->start();
    open("foldersearch"); // will be closed in searchFinished
}

void KMFolderSearch::executeSearch()
{
    if (mSearch)
        mSearch->stop();
    setSearch(mSearch);
    invalidateFolder();
}

const KMSearch* KMFolderSearch::search() const
{
    return mSearch;
}

void KMFolderSearch::searchFinished(bool success)
{
    if (!success)
        mSerNums.clear();
    close("foldersearch");
}

void KMFolderSearch::addSerNum(TQ_UINT32 serNum)
{
    if (mInvalid) // A new search is scheduled don't bother doing anything
        return;
    int idx = -1;
    KMFolder *aFolder = 0;
    KMMsgDict::instance()->getLocation(serNum, &aFolder, &idx);
    // warn instead of assert() because of
    // https://intevation.de/roundup/kolab/issue2216
    if (!aFolder || (idx == -1)) {
        kdDebug(5006) << "Not adding message with serNum " << serNum
                      << ": folder is " << aFolder << ", index is " << idx << endl;
        return;
    }
    if(mFolders.findIndex(aFolder) == -1) {
        aFolder->open("foldersearch");
        mFolders.append(aFolder);
    }
    setDirty( true ); //TODO append a single entry to .ids file and sync.
    if (!mUnlinked) {
        unlink(TQFile::encodeName(indexLocation()));
        mUnlinked = true;
    }
    mSerNums.append(serNum);
    KMMsgBase *mb = aFolder->getMsgBase(idx);
    if (mb && (mb->isUnread() || mb->isNew())) {
       if (mUnreadMsgs == -1)
           mUnreadMsgs = 0;
       ++mUnreadMsgs;
       emit numUnreadMsgsChanged( folder() );
    }
    emitMsgAddedSignals(mSerNums.count()-1);
}

void KMFolderSearch::removeSerNum(TQ_UINT32 serNum)
{
    TQValueVector<TQ_UINT32>::const_iterator it;
    int i = 0;
    for(it = mSerNums.begin(); it != mSerNums.end(); ++it, ++i)
        if ((*it) == serNum) {
            int idx = -1;
            KMFolder *aFolder = 0;
            KMMsgDict::instance()->getLocation(serNum, &aFolder, &idx);
            assert(aFolder && (idx != -1));
            emit msgRemoved(folder(), serNum);
            removeMsg(i);
            return;
        }
    if (!mUnlinked) {
        unlink(TQFile::encodeName(indexLocation()));
        mUnlinked = true;
    }
}

int KMFolderSearch::addMsg(KMMessage*, int* index_return)
{
    //Not supported search folder can't own messages
    *index_return = -1;
    return 0;
}

bool KMFolderSearch::readSearch()
{
    mSearch = new KMSearch;
    TQObject::connect(mSearch, TQ_SIGNAL(found(TQ_UINT32)), TQ_SLOT(addSerNum(TQ_UINT32)));
    TQObject::connect(mSearch, TQ_SIGNAL(finished(bool)), TQ_SLOT(searchFinished(bool)));
    return mSearch->read(location());
}

int KMFolderSearch::open(const char *)
{
    mOpenCount++;
    kmkernel->jobScheduler()->notifyOpeningFolder( folder() );
    if (mOpenCount > 1)
        return 0;  // already open

    readConfig();
    if (!mSearch && !readSearch())
        return -1;

    emit cleared();
    if (!mSearch || !search()->running())
        if (!readIndex()) {
            executeSearch();
        }

    return 0;
}

int KMFolderSearch::canAccess()
{
    assert(!folder()->name().isEmpty());

    if (access(TQFile::encodeName(location()), R_OK | W_OK | X_OK) != 0)
        return 1;
    return 0;
}

void KMFolderSearch::sync()
{
    if (mDirty) {
        if (mSearch)
            mSearch->write(location());
        updateIndex();
    }
}

void KMFolderSearch::reallyDoClose(const char* owner)
{
    Q_UNUSED( owner );
    if (mAutoCreateIndex) {
        if (mSearch)
            mSearch->write(location());
        updateIndex();
        if (mSearch && search()->running())
            mSearch->stop();
        writeConfig();
    }

    //close all referenced folders
    TQValueListIterator<TQGuardedPtr<KMFolder> > fit;
    for (fit = mFolders.begin(); fit != mFolders.end(); ++fit) {
        if (!(*fit))
            continue;
        (*fit)->close("foldersearch");
    }
    mFolders.clear();

    clearIndex(TRUE);

    if (mIdsStream)
        fclose(mIdsStream);

    mOpenCount   = 0;
    mIdsStream = 0;
    mUnreadMsgs  = -1;
}

int KMFolderSearch::create()
{
    int old_umask;
    int rc = unlink(TQFile::encodeName(location()));
    if (!rc)
        return rc;
    rc = 0;

    assert(!folder()->name().isEmpty());
    assert(mOpenCount == 0);

    kdDebug(5006) << "Creating folder " << location() << endl;
    if (access(TQFile::encodeName(location()), F_OK) == 0) {
        kdDebug(5006) << "KMFolderSearch::create call to access function failed."
            << endl;
        return EEXIST;
    }

    old_umask = umask(077);
    FILE *mStream = fopen(TQFile::encodeName(location()), "w+");
    umask(old_umask);
    if (!mStream) return errno;
    fclose(mStream);

    clearIndex();
    if (!mSearch) {
        mSearch = new KMSearch();
        TQObject::connect(mSearch, TQ_SIGNAL(found(TQ_UINT32)), TQ_SLOT(addSerNum(TQ_UINT32)));
        TQObject::connect(mSearch, TQ_SIGNAL(finished(bool)), TQ_SLOT(searchFinished(bool)));
    }
    mSearch->write(location());
    mOpenCount++;
    mChanged = false;
    mUnreadMsgs = 0;
    mTotalMsgs = 0;
    return rc;
}

int KMFolderSearch::compact( bool )
{
    needsCompact = false;
    return 0;
}

bool KMFolderSearch::isReadOnly() const
{
    return false; //TODO: Make it true and get that working ok
}

FolderJob* KMFolderSearch::doCreateJob(KMMessage*, FolderJob::JobType,
                                     KMFolder*, TQString, const AttachmentStrategy* ) const
{
    // Should never be called
    assert(0);
    return 0;
}

FolderJob* KMFolderSearch::doCreateJob(TQPtrList<KMMessage>&, const TQString&,
                                       FolderJob::JobType, KMFolder*) const
{
    // Should never be called
    assert(0);
    return 0;
}

const KMMsgBase* KMFolderSearch::getMsgBase(int idx) const
{
    int folderIdx = -1;
    KMFolder *folder = 0;
    if (idx < 0 || (TQ_UINT32)idx >= mSerNums.count())
        return 0;
    KMMsgDict::instance()->getLocation(mSerNums[idx], &folder, &folderIdx);
    assert(folder && (folderIdx != -1));
    return folder->getMsgBase(folderIdx);
}

KMMsgBase* KMFolderSearch::getMsgBase(int idx)
{
    int folderIdx = -1;
    KMFolder *folder = 0;
    if (idx < 0 || (TQ_UINT32)idx >= mSerNums.count())
        return 0;
    KMMsgDict::instance()->getLocation(mSerNums[idx], &folder, &folderIdx);
    if (!folder || folderIdx == -1)
        return 0; //exceptional case
    return folder->getMsgBase(folderIdx);
}

//-----------------------------------------------------------------------------
KMMessage* KMFolderSearch::getMsg(int idx)
{
    int folderIdx = -1;
    KMFolder *folder = 0;
    if (idx < 0 || (TQ_UINT32)idx >= mSerNums.count())
        return 0;
    KMMsgDict::instance()->getLocation(mSerNums[idx], &folder, &folderIdx);
    assert(folder && (folderIdx != -1));
    KMMessage* msg = folder->getMsg( folderIdx );
    return msg;
}

//-------------------------------------------------------------
void
KMFolderSearch::ignoreJobsForMessage( KMMessage* msg )
{
    if ( !msg || msg->transferInProgress() )
        return;
    /* While non-imap folders manage their jobs themselves, imap ones let
       their account manage them. Therefor first clear the jobs managed by
       this folder via the inherited method, then clear the imap ones. */
    FolderStorage::ignoreJobsForMessage( msg );

    if (msg->parent()->folderType() == KMFolderTypeImap) {
        KMAcctImap *account =
            static_cast<KMFolderImap*>( msg->storage() )->account();
        if( !account )
            return;
        account->ignoreJobsForMessage( msg );
    }
}


int KMFolderSearch::find(const KMMsgBase* msg) const
{
    int pos = 0;
    TQ_UINT32 serNum = msg->getMsgSerNum();
    TQValueVector<TQ_UINT32>::const_iterator it;
    for(it = mSerNums.begin(); it != mSerNums.end(); ++it) {
        if ((*it) == serNum)
            return pos;
        ++pos;
    }
    return -1;
}

TQString KMFolderSearch::indexLocation() const
{
    TQString sLocation(folder()->path());

    if (!sLocation.isEmpty()) sLocation += '/';
    sLocation += '.';
    sLocation += dotEscape(fileName());
    sLocation += ".index";
    sLocation += ".search";

    return sLocation;
}

int KMFolderSearch::updateIndex()
{
    if (mSearch && search()->running())
        unlink(TQFile::encodeName(indexLocation()));
    else
        if (dirty())
            return writeIndex();
    return 0;
}

int KMFolderSearch::writeIndex( bool )
{
    // TODO:If we fail to write the index we should panic the kernel
    // TODO:and the same for other folder types too, and the msgDict.
    TQString filename = indexLocation();
    int old_umask = umask(077);
    TQString tempName = filename + ".temp";
    unlink(TQFile::encodeName(tempName));

    // We touch the folder, otherwise the index is regenerated, if KMail is
    // running, while the clock switches from daylight savings time to normal time
    utime(TQFile::encodeName(location()), 0);

    FILE *tmpIndexStream = fopen(TQFile::encodeName(tempName), "w");
    umask(old_umask);

    if (!tmpIndexStream) {
        kdDebug(5006) << "Cannot write '" << filename
            << strerror(errno) << " (" << errno << ")" << endl;
        truncate(TQFile::encodeName(filename), 0);
        return -1;
    }
    fprintf(tmpIndexStream, IDS_SEARCH_HEADER, IDS_SEARCH_VERSION);
    TQ_UINT32 byteOrder = 0x12345678;
    fwrite(&byteOrder, sizeof(byteOrder), 1, tmpIndexStream);

    TQ_UINT32 count = mSerNums.count();
    if (!fwrite(&count, sizeof(count), 1, tmpIndexStream)) {
        fclose(tmpIndexStream);
        truncate(TQFile::encodeName(filename), 0);
        return -1;
    }

    TQValueVector<TQ_UINT32>::iterator it;
    for(it = mSerNums.begin(); it != mSerNums.end(); ++it) {
        TQ_UINT32 serNum = *it;
        if (!fwrite(&serNum, sizeof(serNum), 1, tmpIndexStream))
            return -1;
    }
    if (ferror(tmpIndexStream)) return ferror(tmpIndexStream);
    if (fflush(tmpIndexStream) != 0) return errno;
    if (fsync(fileno(tmpIndexStream)) != 0) return errno;
    if (fclose(tmpIndexStream) != 0) return errno;

    ::rename(TQFile::encodeName(tempName), TQFile::encodeName(indexLocation()));
    mDirty = FALSE;
    mUnlinked = FALSE;

    return 0;
}

DwString KMFolderSearch::getDwString(int idx)
{
    return getMsgBase(idx)->parent()->getDwString( idx );
}

KMMessage* KMFolderSearch::readMsg(int idx)
{
    int folderIdx = -1;
    KMFolder *folder = 0;
    KMMsgDict::instance()->getLocation(mSerNums[idx], &folder, &folderIdx);
    assert(folder && (folderIdx != -1));
    return folder->getMsg( folderIdx );
}

bool KMFolderSearch::readIndex()
{
    clearIndex();
    TQString filename = indexLocation();
    mIdsStream = fopen(TQFile::encodeName(filename), "r+");
    if (!mIdsStream)
        return false;

    int version = 0;
    fscanf(mIdsStream, IDS_SEARCH_HEADER, &version);
    if (version != IDS_SEARCH_VERSION) {
        fclose(mIdsStream);
        mIdsStream = 0;
        return false;
    }
    bool swapByteOrder;
    TQ_UINT32 byte_order;
    if (!fread(&byte_order, sizeof(byte_order), 1, mIdsStream)) {
        fclose(mIdsStream);
        mIdsStream = 0;
        return false;
    }
    swapByteOrder = (byte_order == 0x78563412);

    TQ_UINT32 count;
    if (!fread(&count, sizeof(count), 1, mIdsStream)) {
        fclose(mIdsStream);
        mIdsStream = 0;
        return false;
    }
    if (swapByteOrder)
        count = kmail_swap_32(count);

    mUnreadMsgs = 0;
    mSerNums.reserve(count);
    for (unsigned int index = 0; index < count; index++) {
        TQ_UINT32 serNum;
        int folderIdx = -1;
        KMFolder *folder = 0;
        bool readOk = fread(&serNum, sizeof(serNum), 1, mIdsStream);
        if (!readOk) {
            clearIndex();
            fclose(mIdsStream);
            mIdsStream = 0;
            return false;
        }
        if (swapByteOrder)
            serNum = kmail_swap_32(serNum);

        KMMsgDict::instance()->getLocation( serNum, &folder, &folderIdx );
        if (!folder || (folderIdx == -1)) {
            clearIndex();
            fclose(mIdsStream);
            mIdsStream = 0;
            return false;
        }
        mSerNums.push_back(serNum);
        if(mFolders.findIndex(folder) == -1) {
            if (mInvalid) //exceptional case for when folder has invalid ids
                return false;
            folder->open("foldersearch");
            mFolders.append(folder);
        }
        KMMsgBase *mb = folder->getMsgBase(folderIdx);
        if (!mb) //Exceptional case our .ids file is messed up
            return false;
        if (mb->isNew() || mb->isUnread()) {
            if (mUnreadMsgs == -1) ++mUnreadMsgs;
            ++mUnreadMsgs;
        }
    }
    mTotalMsgs = mSerNums.count();
    fclose(mIdsStream);
    mIdsStream = 0;
    mUnlinked = true;
    return true;
}

int KMFolderSearch::removeContents()
{
    unlink(TQFile::encodeName(location()));
    unlink(TQFile::encodeName(indexLocation()));
    mUnlinked = true;
    return 0;
}

int KMFolderSearch::expungeContents()
{
    setSearch(new KMSearch());
    return 0;
}

int KMFolderSearch::count(bool cache) const
{
    Q_UNUSED(cache);
    return mSerNums.count();
}

KMMsgBase* KMFolderSearch::takeIndexEntry(int idx)
{
    assert(idx >= 0 && idx < (int)mSerNums.count());
    KMMsgBase *msgBase = getMsgBase(idx);
    TQValueVector<TQ_UINT32>::iterator it = mSerNums.begin();
    mSerNums.erase(&it[idx]);
    return msgBase;
}

KMMsgInfo* KMFolderSearch::setIndexEntry(int idx, KMMessage *msg)
{
    assert(idx >= 0 && idx < (int)mSerNums.count());
    Q_UNUSED( idx );
    return msg->storage()->setIndexEntry(msg->parent()->find(msg), msg);
}

void KMFolderSearch::clearIndex(bool, bool)
{
  //close all referenced folders
  TQValueListIterator<TQGuardedPtr<KMFolder> > fit;
  for (fit = mFolders.begin(); fit != mFolders.end(); ++fit) {
    if (!(*fit))
      continue;
    (*fit)->close("foldersearch");
  }
  mFolders.clear();

  mSerNums.clear();
}

void KMFolderSearch::truncateIndex()
{
    truncate(TQFile::encodeName(indexLocation()), IDS_SEARCH_HEADER_LEN);
}

void KMFolderSearch::examineAddedMessage(KMFolder *aFolder, TQ_UINT32 serNum)
{
    if (!search() && !readSearch())
        return;
    if (!search()->inScope(aFolder))
        return;
    if (!mTempOpened) {
        open("foldersearch");
        mTempOpened = true;
    }

    if (!search()->searchPattern())
        return;

    int idx = -1;
    KMFolder *folder = 0;
    KMMsgDict::instance()->getLocation(serNum, &folder, &idx);
    assert(folder && (idx != -1));
    assert(folder == aFolder);
    KMFolderOpener openFolder(folder, "foldersearch");

    // if we are already checking this folder, refcount
    if ( mFoldersCurrentlyBeingSearched.contains( folder ) ) {
      unsigned int count = mFoldersCurrentlyBeingSearched[folder];
      mFoldersCurrentlyBeingSearched.replace( folder, count+1 );
    } else {
      connect( folder->storage(),
              TQ_SIGNAL( searchDone( KMFolder*, TQ_UINT32, const KMSearchPattern*, bool ) ),
              this,
              TQ_SLOT( slotSearchExamineMsgDone( KMFolder*, TQ_UINT32,
                      const KMSearchPattern*, bool ) ) );
      mFoldersCurrentlyBeingSearched.insert( folder, 1 );
    }
    folder->storage()->search( search()->searchPattern(), serNum );
}

void KMFolderSearch::slotSearchExamineMsgDone( KMFolder* folder,
                                               TQ_UINT32 serNum,
                                               const KMSearchPattern* pattern,
                                               bool matches )
{
    if ( search()->searchPattern() != pattern ) return;
    kdDebug(5006) << folder->label() << ": serNum " << serNum
     << " matches?" << matches << endl;
    KMFolderOpener openFolder(folder, "foldersearch");

    Q_ASSERT( mFoldersCurrentlyBeingSearched.contains( folder ) );

    unsigned int count = mFoldersCurrentlyBeingSearched[folder];
    if ( count == 1 ) {
      disconnect( folder->storage(),
                  TQ_SIGNAL( searchDone( KMFolder*, TQ_UINT32,
                                      const KMSearchPattern*, bool ) ),
                  this,
                  TQ_SLOT( slotSearchExamineMsgDone( KMFolder*, TQ_UINT32,
                                                  const KMSearchPattern*, bool ) ) );
      mFoldersCurrentlyBeingSearched.remove( folder );
    } else {
      mFoldersCurrentlyBeingSearched.replace( folder, count-1 );
    }

    if ( !matches ) {
        TQValueVector<TQ_UINT32>::const_iterator it;
        it = tqFind( mSerNums.begin(), mSerNums.end(), serNum );
        if (it != mSerNums.end()) {
            removeSerNum( serNum );
        }
        return;
    }

//    if (mSearch->running()) {
//        mSearch->stop();
//        mExecuteSearchTimer->start( 0, true );
//    } else {
        TQValueVector<TQ_UINT32>::const_iterator it;
        it = tqFind( mSerNums.begin(), mSerNums.end(), serNum );
        if (it == mSerNums.end()) {
            addSerNum( serNum );
        }
//    }
}

void KMFolderSearch::examineRemovedMessage(KMFolder *folder, TQ_UINT32 serNum)
{
    if (!search() && !readSearch())
        return;
    if (!search()->inScope(folder))
        return;
    if (!mTempOpened) {
        open("foldersearch");
        mTempOpened = true;
    }

    if (mSearch->running()) {
        mExecuteSearchTimer->start(0, true);
    } else {
        removeSerNum(serNum);
    }
}

void KMFolderSearch::examineChangedMessage(KMFolder *aFolder, TQ_UINT32 serNum, int delta)
{
    if (!search() && !readSearch())
        return;
    if (!search()->inScope(aFolder))
        return;
    if (!mTempOpened) {
        open("foldersearch");
        mTempOpened = true;
    }
    TQValueVector<TQ_UINT32>::const_iterator it;
    it = tqFind( mSerNums.begin(), mSerNums.end(), serNum );
    if (it != mSerNums.end()) {
        mUnreadMsgs += delta;
        emit numUnreadMsgsChanged( folder() );
        emit msgChanged( folder(), serNum, delta );
    }
}

void KMFolderSearch::examineInvalidatedFolder(KMFolder *folder)
{
    if (!search() && !readSearch())
        return;
    if (!search()->inScope(folder))
        return;
    if (mTempOpened) {
        close("foldersearch");
        mTempOpened = false;
    }

    mInvalid = true;
    if (mSearch)
        mSearch->stop();

    if (!mUnlinked) {
        unlink(TQFile::encodeName(indexLocation()));
        mUnlinked = true;
    }

    if (!isOpened()) //give up, until the user manually opens the folder
        return;

    if (!mTempOpened) {
        open("foldersearch");
        mTempOpened = true;
    }
    mExecuteSearchTimer->start(0, true);
}

void KMFolderSearch::examineRemovedFolder(KMFolder *folder)
{
    examineInvalidatedFolder(folder);
    if (mSearch->root() == folder) {
        delete mSearch;
        mSearch = 0;
    }
}

void KMFolderSearch::propagateHeaderChanged(KMFolder *aFolder, int idx)
{
    int pos = 0;
    if (!search() && !readSearch())
        return;
    if (!search()->inScope(aFolder))
        return;
    if (!mTempOpened) {
        open("foldersearch");
        mTempOpened = true;
    }

    TQ_UINT32 serNum = KMMsgDict::instance()->getMsgSerNum(aFolder, idx);
    TQValueVector<TQ_UINT32>::const_iterator it;
    for(it = mSerNums.begin(); it != mSerNums.end(); ++it) {
        if ((*it) == serNum) {
            emit msgHeaderChanged(folder(), pos);
            break;
        }
        ++pos;
    }
    // let's try if the message matches our search
    KMFolderOpener openAFolder(aFolder, "foldersearch");

    // if we are already checking this folder, refcount
    if ( mFoldersCurrentlyBeingSearched.contains( aFolder ) ) {
      unsigned int count = mFoldersCurrentlyBeingSearched[aFolder];
      mFoldersCurrentlyBeingSearched.replace( aFolder, count+1 );
    } else {
      connect( aFolder->storage(),
              TQ_SIGNAL( searchDone( KMFolder*, TQ_UINT32, const KMSearchPattern*, bool ) ),
              this,
              TQ_SLOT( slotSearchExamineMsgDone( KMFolder*, TQ_UINT32,
                      const KMSearchPattern*, bool ) ) );
      mFoldersCurrentlyBeingSearched.insert( aFolder, 1 );
    }
    aFolder->storage()->search( search()->searchPattern(), serNum );
}

void KMFolderSearch::tryReleasingFolder(KMFolder* folder)
{
  // We'll succeed releasing the folder only if mTempOpened and mOpenCount==1.
  // Otherwise if mOpenCount>1 (e.g while the search dialog is up), we would just keep closing/reopening for nothing
  if ( mTempOpened && mOpenCount == 1 )
  {
    examineInvalidatedFolder( folder );
  }
}

#include "kmfoldersearch.moc"