summaryrefslogtreecommitdiffstats
path: root/kmail/folderstorage.cpp
blob: 53d7f66d8f7a5ebbb7583f354cc9c49b13789012 (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
/*
    Virtual base class for mail storage.

    This file is part of KMail.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    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.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the TQt library by Trolltech AS, Norway (or with modified versions
    of TQt that use the same license as TQt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    TQt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config.h>

#include "folderstorage.h"
#include "kmfolder.h"
#include "kmkernel.h"

#include "kmfolderimap.h" //for the nasty imap hacks, FIXME
#include "undostack.h"
#include "kmmsgdict.h"
#include "kmfoldermgr.h"
#include "kmcommands.h"
#include "listjob.h"
using KMail::ListJob;
#include "kmsearchpattern.h"
#include "globalsettings.h"

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

#include <tqfile.h>
#include <tqregexp.h>

#include <mimelib/mimepp.h>
#include <errno.h>

//-----------------------------------------------------------------------------

FolderStorage::FolderStorage( KMFolder* folder, const char* aName )
  : TQObject( folder, aName ), mFolder( folder ), mEmitChangedTimer( 0L )
{
  mOpenCount = 0;
  mQuiet = 0;
  mChanged = false;
  mAutoCreateIndex = true;
  mExportsSernums = false;
  mDirty = false;
  mUnreadMsgs = -1;
  mGuessedUnreadMsgs = -1;
  mTotalMsgs = -1;
  mSize = -1;
  needsCompact    = false;
  mConvertToUtf8  = false;
  mCompactable     = true;
  mNoContent      = false;
  mNoChildren     = false;
  mRDict = 0;
  mDirtyTimer = new TQTimer(this, "mDirtyTimer");
  connect(mDirtyTimer, TQT_SIGNAL(timeout()),
	  this, TQT_SLOT(updateIndex()));

  mHasChildren = HasNoChildren;
  mContentsType = KMail::ContentsTypeMail;

  connect(this, TQT_SIGNAL(closed(KMFolder*)), mFolder, TQT_SIGNAL(closed()));
}

//-----------------------------------------------------------------------------
FolderStorage::~FolderStorage()
{
  mJobList.setAutoDelete( true );
  TQObject::disconnect( TQT_SIGNAL(destroyed(TQObject*)), this, 0 );
  mJobList.clear();
  KMMsgDict::deleteRentry(mRDict);
}


void FolderStorage::close( const char* owner, bool aForced )
{
  if (mOpenCount <= 0) return;
  if (mOpenCount > 0) mOpenCount--;
  if (mOpenCount > 0 && !aForced) return;

  // kdWarning() << "Really closing: " << folder()->prettyURL()  << kdBacktrace() << endl;
  reallyDoClose(owner);
}

//-----------------------------------------------------------------------------
TQString FolderStorage::dotEscape(const TQString& aStr)
{
  if (aStr[0] != '.') return aStr;
  return aStr.left(aStr.find(TQRegExp("[^\\.]"))) + aStr;
}

void FolderStorage::addJob( FolderJob* job ) const
{
  TQObject::connect( job, TQT_SIGNAL(destroyed(TQObject*)),
                    TQT_SLOT(removeJob(TQObject*)) );
  mJobList.append( job );
}

void FolderStorage::removeJob( TQObject* job )
{
  mJobList.remove( static_cast<FolderJob*>( job ) );
}


//-----------------------------------------------------------------------------
TQString FolderStorage::location() const
{
  TQString sLocation(const_cast<FolderStorage*>(this)->folder()->path());

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

  return sLocation;
}

TQString FolderStorage::fileName() const
{
  return mFolder->name();
}



//-----------------------------------------------------------------------------
void FolderStorage::setAutoCreateIndex(bool autoIndex)
{
  mAutoCreateIndex = autoIndex;
}

//-----------------------------------------------------------------------------
void FolderStorage::setDirty(bool f)
{
  mDirty = f;
  if (mDirty  && mAutoCreateIndex)
    mDirtyTimer->changeInterval( mDirtyTimerInterval );
  else
    mDirtyTimer->stop();
}

//-----------------------------------------------------------------------------
void FolderStorage::markNewAsUnread()
{
  KMMsgBase* msgBase;
  int i;

  for (i=0; i< count(); ++i)
  {
    if (!(msgBase = getMsgBase(i))) continue;
    if (msgBase->isNew())
    {
      msgBase->seStatus(KMMsgStatusUnread);
      msgBase->setDirty(true);
    }
  }
}

void FolderStorage::markUnreadAsRead()
{
  KMMsgBase* msgBase;
  SerNumList serNums;

  for (int i=count()-1; i>=0; --i)
  {
    msgBase = getMsgBase(i);
    assert(msgBase);
    if (msgBase->isNew() || msgBase->isUnread())
    {
      serNums.append( msgBase->getMsgSerNum() );
    }
  }
  if (serNums.empty())
    return;

  KMCommand *command = new KMSeStatusCommand( KMMsgStatusRead, serNums );
  command->start();
}

//-----------------------------------------------------------------------------
void FolderStorage::quiet(bool beQuiet)
{

  if (beQuiet)
  {
    /* Allocate the timer here to don't have one timer for each folder. BTW,
     * a timer is created when a folder is checked
     */
    if ( !mEmitChangedTimer) {
      mEmitChangedTimer= new TQTimer( this, "mEmitChangedTimer" );
      connect( mEmitChangedTimer, TQT_SIGNAL( timeout() ),
      this, TQT_SLOT( slotEmitChangedTimer() ) );
    }
    mQuiet++;
  } else {
    mQuiet--;
    if (mQuiet <= 0)
    {
      delete mEmitChangedTimer;
      mEmitChangedTimer=0L;

      mQuiet = 0;
      if (mChanged) {
       emit changed();
       // Don't hurt emit this if the mUnreadMsg really don't change
       // We emit it here, because this signal is delayed if mQuiet >0
       emit numUnreadMsgsChanged( folder() );
      }
      mChanged = false;
    }
  }
}

//-----------------------------------------------------------------------------

/** Compare message's date. This is useful for message sorting */
int operator<( KMMsgBase & m1, KMMsgBase & m2 )
{
  return (m1.date() < m2.date());
}

/** Compare message's date. This is useful for message sorting */
int operator==( KMMsgBase & m1, KMMsgBase & m2 )
{
  return (m1.date() == m2.date());
}


//-----------------------------------------------------------------------------
int FolderStorage::expungeOldMsg(int days)
{
  int i, msgnb=0;
  time_t msgTime, maxTime;
  const KMMsgBase* mb;
  TQValueList<int> rmvMsgList;

  maxTime = time(0) - days * 3600 * 24;

  for (i=count()-1; i>=0; i--) {
    mb = getMsgBase(i);
    assert(mb);
    msgTime = mb->date();

    if (msgTime < maxTime) {
      //kdDebug(5006) << "deleting msg " << i << " : " << mb->subject() << " - " << mb->dateStr(); // << endl;
      removeMsg( i );
      msgnb++;
    }
  }
  return msgnb;
}

//------------------------------------------
void FolderStorage::slotEmitChangedTimer()
{
  emit changed();
  mChanged=false;
}
//-----------------------------------------------------------------------------
void FolderStorage::emitMsgAddedSignals(int idx)
{
  TQ_UINT32 serNum = KMMsgDict::instance()->getMsgSerNum( folder() , idx );
  if (!mQuiet) {
    emit msgAdded(idx);
  } else {
    /** Restart always the timer or not. BTW we get a kmheaders refresh
     * each 3 seg.?*/
    if ( !mEmitChangedTimer->isActive() ) {
      mEmitChangedTimer->start( 3000 );
    }
    mChanged=true;
  }
  emit msgAdded( folder(), serNum );
}

//-----------------------------------------------------------------------------
bool FolderStorage::canAddMsgNow(KMMessage* aMsg, int* aIndex_ret)
{
  if (aIndex_ret) *aIndex_ret = -1;
  KMFolder *msgParent = aMsg->parent();
  // If the message has a parent and is in transfer, bail out. If it does not
  // have a parent we want to be able to add it even if it is in transfer.
  if (aMsg->transferInProgress() && msgParent)
      return false;
  if (!aMsg->isComplete() && msgParent && msgParent->folderType() == KMFolderTypeImap)
  {
    FolderJob *job = msgParent->createJob(aMsg);
    connect(job, TQT_SIGNAL(messageRetrieved(KMMessage*)),
            TQT_SLOT(reallyAddMsg(KMMessage*)));
    job->start();
    aMsg->setTransferInProgress( true );
    return false;
  }
  return true;
}


//-----------------------------------------------------------------------------
void FolderStorage::reallyAddMsg(KMMessage* aMsg)
{
  if (!aMsg) // the signal that is connected can call with aMsg=0
    return;
  aMsg->setTransferInProgress( false );
  aMsg->setComplete( true );
  KMFolder *aFolder = aMsg->parent();
  int index;
  ulong serNum = aMsg->getMsgSerNum();
  bool undo = aMsg->enableUndo();
  addMsg(aMsg, &index);
  if (index < 0) return;
  unGetMsg(index);
  if (undo)
  {
    kmkernel->undoStack()->pushSingleAction( serNum, aFolder, folder() );
  }
}


//-----------------------------------------------------------------------------
void FolderStorage::reallyAddCopyOfMsg(KMMessage* aMsg)
{
  if ( !aMsg ) return; // messageRetrieved(0) is always possible
  aMsg->setParent( 0 );
  aMsg->setTransferInProgress( false );
  addMsg( aMsg );
  unGetMsg( count() - 1 );
}

int FolderStorage::find( const KMMessage * msg ) const {
  return find( &msg->toMsgBase() );
}

//-----------------------------------------------------------------------------
void FolderStorage::removeMsg(const TQPtrList<KMMsgBase>& msgList, bool imapQuiet)
{
  for( TQPtrListIterator<KMMsgBase> it( msgList ); *it; ++it )
  {
    int idx = find(it.current());
    assert( idx != -1);
    removeMsg(idx, imapQuiet);
  }
}

//-----------------------------------------------------------------------------
void FolderStorage::removeMsg(const TQPtrList<KMMessage>& msgList, bool imapQuiet)
{
  for( TQPtrListIterator<KMMessage> it( msgList ); *it; ++it )
  {
    int idx = find(it.current());
    assert( idx != -1);
    removeMsg(idx, imapQuiet);
  }
}

//-----------------------------------------------------------------------------
void FolderStorage::removeMsg(int idx, bool)
{
  //assert(idx>=0);
  if(idx < 0)
  {
    kdDebug(5006) << "FolderStorage::removeMsg() : idx < 0\n" << endl;
    return;
  }

  KMMsgBase* mb = getMsgBase(idx);

  TQ_UINT32 serNum = KMMsgDict::instance()->getMsgSerNum( folder(), idx );
  if (serNum != 0)
    emit msgRemoved( folder(), serNum );
  mb = takeIndexEntry( idx );

  setDirty( true );
  needsCompact=true; // message is taken from here - needs to be compacted

  if (mb->isUnread() || mb->isNew() ||
      (folder() == kmkernel->outboxFolder())) {
    --mUnreadMsgs;
    if ( !mQuiet ) {
//      kdDebug( 5006 ) << "FolderStorage::msgStatusChanged" << endl;
      emit numUnreadMsgsChanged( folder() );
    }else{
      if ( !mEmitChangedTimer->isActive() ) {
//        kdDebug( 5006 )<< "EmitChangedTimer started" << endl;
        mEmitChangedTimer->start( 3000 );
      }
      mChanged = true;
    }
  }
  --mTotalMsgs;

  mSize = -1;
  TQString msgIdMD5 = mb->msgIdMD5();
  emit msgRemoved( idx, msgIdMD5 );
  emit msgRemoved( folder() );
}


//-----------------------------------------------------------------------------
KMMessage* FolderStorage::take(int idx)
{
  KMMsgBase* mb;
  KMMessage* msg;

  assert(idx>=0 && idx<=count());

  mb = getMsgBase(idx);
  if (!mb) return 0;
  if (!mb->isMessage()) readMsg(idx);
  TQ_UINT32 serNum = KMMsgDict::instance()->getMsgSerNum( folder(), idx );
  emit msgRemoved( folder(), serNum );

  msg = (KMMessage*)takeIndexEntry(idx);

  if (msg->isUnread() || msg->isNew() ||
      ( folder() == kmkernel->outboxFolder() )) {
    --mUnreadMsgs;
    if ( !mQuiet ) {
      emit numUnreadMsgsChanged( folder() );
    }else{
      if ( !mEmitChangedTimer->isActive() ) {
        mEmitChangedTimer->start( 3000 );
      }
      mChanged = true;
    }
  }
  --mTotalMsgs;
  msg->setParent(0);
  setDirty( true );
  mSize = -1;
  needsCompact=true; // message is taken from here - needs to be compacted
  TQString msgIdMD5 = msg->msgIdMD5();
  emit msgRemoved( idx, msgIdMD5 );
  emit msgRemoved( folder() );

  return msg;
}

void FolderStorage::take(TQPtrList<KMMessage> msgList)
{
  for ( KMMessage* msg = msgList.first(); msg; msg = msgList.next() )
  {
    if (msg->parent())
    {
      int idx = msg->parent()->find(msg);
      if ( idx >= 0 )
        take(idx);
    }
  }
}


//-----------------------------------------------------------------------------
KMMessage* FolderStorage::getMsg(int idx)
{
  if ( mOpenCount <= 0 ) {
    kdWarning(5006) << "FolderStorage::getMsg was called on a closed folder: " << folder()->prettyURL() << endl;
    return 0;
  }
  if ( idx < 0 || idx >= count() ) {
    kdWarning(5006) << "FolderStorage::getMsg was asked for an invalid index. idx =" << idx << " count()=" << count() << endl;
    return 0;
  }

  KMMsgBase* mb = getMsgBase(idx);
  if (!mb) {
    kdWarning(5006) << "FolderStorage::getMsg, getMsgBase failed for index: " << idx << endl;
    return 0;
  }

  KMMessage *msg = 0;
  bool undo = mb->enableUndo();
  if (mb->isMessage()) {
      msg = ((KMMessage*)mb);
  } else {
      TQString mbSubject = mb->subject();
      msg = readMsg(idx);
      // sanity check
      if (mCompactable && (!msg || (msg->subject().isEmpty() != mbSubject.isEmpty()))) {
        kdDebug(5006) << "Error: " << location() <<
          " Index file is inconsistent with folder file. This should never happen." << endl;

        // We can't recreate the index at this point, since that would invalidate the current
        // message list and delete KMMsgBase or KMMessage objects that are in use.
        // Do it later in KMFolderIndex::readIndexHeader() instead.
        mCompactable = false; // Don't compact
        writeConfig();
      }

  }
  // Either isMessage and we had a sernum, or readMsg gives us one
  // (via insertion into mMsgList). sernum == 0 may still occur due to
  // an outdated or corrupt IMAP cache.
  if ( msg->getMsgSerNum() == 0 ) {
    kdWarning(5006) << "FolderStorage::getMsg, message has no sernum, index: " << idx << endl;
    return 0;
  }
  msg->setEnableUndo(undo);
  msg->setComplete( true );
  return msg;
}

//-----------------------------------------------------------------------------
KMMessage* FolderStorage::readTemporaryMsg(int idx)
{
  if(!(idx >= 0 && idx <= count())) {
    kdDebug(5006) << k_funcinfo << "Invalid index " << idx << "!" << endl;
    return 0;
  }

  KMMsgBase* mb = getMsgBase(idx);
  if (!mb) {
    kdDebug(5006) << k_funcinfo << "getMsgBase() for " << idx << " failed!" << endl;
    return 0;
  }

  unsigned long sernum = mb->getMsgSerNum();

  KMMessage *msg = 0;
  bool undo = mb->enableUndo();
  if (mb->isMessage()) {
    // the caller will delete it, so we must make a copy it
    msg = new KMMessage(*(KMMessage*)mb);
    msg->setMsgSerNum(sernum);
    msg->setComplete( true );
  } else {
    // ## Those two lines need to be moved to a virtual method for KMFolderSearch, like readMsg
    msg = new KMMessage(*(KMMsgInfo*)mb);
    msg->setMsgSerNum(sernum); // before fromDwString so that readyToShow uses the right sernum
    msg->setComplete( true );
    const DwString msgString = getDwString( idx );
    if ( msgString.size() <= 0 ) {
      kdDebug(5006) << k_funcinfo << " Calling getDwString() failed!" << endl;
    }
    msg->fromDwString( msgString );
  }
  msg->setEnableUndo(undo);
  return msg;
}


//-----------------------------------------------------------------------------
KMMsgInfo* FolderStorage::unGetMsg(int idx)
{
  KMMsgBase* mb;

  if(!(idx >= 0 && idx <= count()))
    return 0;

  mb = getMsgBase(idx);
  if (!mb) return 0;


  if (mb->isMessage()) {
    // Remove this message from all jobs' list it might still be on.
    // setIndexEntry deletes the message.
    KMMessage *msg = static_cast<KMMessage*>(mb);
    if ( msg->transferInProgress() ) return 0;
    ignoreJobsForMessage( msg );
    return setIndexEntry( idx, msg );
  }

  return 0;
}


//-----------------------------------------------------------------------------
bool FolderStorage::isMessage(int idx)
{
  KMMsgBase* mb;
  if (!(idx >= 0 && idx <= count())) return false;
  mb = getMsgBase(idx);
  return (mb && mb->isMessage());
}

//-----------------------------------------------------------------------------
FolderJob* FolderStorage::createJob( KMMessage *msg, FolderJob::JobType jt,
                                KMFolder *folder, TQString partSpecifier,
                                const AttachmentStrategy *as ) const
{
  FolderJob * job = doCreateJob( msg, jt, folder, partSpecifier, as );
  if ( job )
    addJob( job );
  return job;
}

//-----------------------------------------------------------------------------
FolderJob* FolderStorage::createJob( TQPtrList<KMMessage>& msgList, const TQString& sets,
                                FolderJob::JobType jt, KMFolder *folder ) const
{
  FolderJob * job = doCreateJob( msgList, sets, jt, folder );
  if ( job )
    addJob( job );
  return job;
}

//-----------------------------------------------------------------------------
int FolderStorage::moveMsg(KMMessage* aMsg, int* aIndex_ret)
{
  assert(aMsg != 0);
  KMFolder* msgParent = aMsg->parent();

  if (msgParent)
    msgParent->open("moveMsgSrc");

  open("moveMsgDest");
  int rc = addMsg(aMsg, aIndex_ret);
  close("moveMsgDest");

  if (msgParent)
    msgParent->close("moveMsgSrc");

  return rc;
}

//-----------------------------------------------------------------------------
int FolderStorage::moveMsg(TQPtrList<KMMessage> msglist, int* aIndex_ret)
{
  KMMessage* aMsg = msglist.first();
  assert(aMsg != 0);
  KMFolder* msgParent = aMsg->parent();

  if (msgParent)
    msgParent->open("foldermovemsg");

  TQValueList<int> index;
  open("moveMsg");
  int rc = addMsg(msglist, index);
  close("moveMsg");
  // FIXME: we want to have a TQValueList to pass it back, so change this method
  if ( !index.isEmpty() )
    aIndex_ret = &index.first();

  if (msgParent)
    msgParent->close("foldermovemsg");

  return rc;
}


//-----------------------------------------------------------------------------
int FolderStorage::rename(const TQString& newName, KMFolderDir *newParent)
{
  TQString oldLoc, oldIndexLoc, oldIdsLoc, newLoc, newIndexLoc, newIdsLoc;
  TQString oldSubDirLoc, newSubDirLoc;
  TQString oldName;
  int rc=0;
  KMFolderDir *oldParent;

  assert(!newName.isEmpty());

  oldLoc = location();
  oldIndexLoc = indexLocation();
  oldSubDirLoc = folder()->subdirLocation();
  oldIdsLoc =  KMMsgDict::instance()->getFolderIdsLocation( *this );
  TQString oldConfigString = "Folder-" + folder()->idString();

  close("rename", true);

  oldName = folder()->fileName();
  oldParent = folder()->parent();
  if (newParent)
    folder()->setParent( newParent );

  folder()->setName(newName);
  newLoc = location();
  newIndexLoc = indexLocation();
  newSubDirLoc = folder()->subdirLocation();
  newIdsLoc = KMMsgDict::instance()->getFolderIdsLocation( *this );

  if (::rename(TQFile::encodeName(oldLoc), TQFile::encodeName(newLoc))) {
    folder()->setName(oldName);
    folder()->setParent(oldParent);
    rc = errno;
  }
  else {
    // rename/move index file and index.sorted file
    if (!oldIndexLoc.isEmpty()) {
      ::rename(TQFile::encodeName(oldIndexLoc), TQFile::encodeName(newIndexLoc));
      ::rename(TQFile::encodeName(oldIndexLoc) + ".sorted",
               TQFile::encodeName(newIndexLoc) + ".sorted");
    }

    // rename/move serial number file
    if (!oldIdsLoc.isEmpty())
      ::rename(TQFile::encodeName(oldIdsLoc), TQFile::encodeName(newIdsLoc));

    // rename/move the subfolder directory
    KMFolderDir* child = 0;
    if( folder() )
      child = folder()->child();

    if (!::rename(TQFile::encodeName(oldSubDirLoc), TQFile::encodeName(newSubDirLoc) )) {
      // now that the subfolder directory has been renamed and/or moved also
      // change the name that is stored in the corresponding KMFolderNode
      // (provide that the name actually changed)
      if( child && ( oldName != newName ) ) {
        child->setName( "." + TQFile::encodeName(newName) + ".directory" );
      }
    }

    // if the folder is being moved then move its node and, if necessary, also
    // the associated subfolder directory node to the new parent
    if (newParent) {
      if (oldParent->findRef( folder() ) != -1)
        oldParent->take();
      newParent->inSort( folder() );
      if ( child ) {
        if ( child->parent()->findRef( child ) != -1 )
          child->parent()->take();
        newParent->inSort( child );
        child->setParent( newParent );
      }
    }
  }

  writeConfig();

  // delete the old entry as we get two entries with the same ID otherwise
  if ( oldConfigString != "Folder-" + folder()->idString() )
    KMKernel::config()->deleteGroup( oldConfigString );

  emit locationChanged( oldLoc, newLoc );
  emit nameChanged();
  kmkernel->folderMgr()->contentsChanged();
  emit closed(folder()); // let the ticket owners regain
  return rc;
}


//-----------------------------------------------------------------------------
void FolderStorage::remove()
{
  assert(!folder()->name().isEmpty());

  clearIndex( true, mExportsSernums ); // delete and remove from dict if necessary
  close("remove", true);

  if ( mExportsSernums ) {
    KMMsgDict::mutableInstance()->removeFolderIds( *this );
    mExportsSernums = false;	// do not writeFolderIds after removal
  }
  unlink(TQFile::encodeName(indexLocation()) + ".sorted");
  unlink(TQFile::encodeName(indexLocation()));

  int rc = removeContents();

  needsCompact = false; //we are dead - no need to compact us

  // Erase settings, otherwise they might interfer when recreating the folder
  KConfig* config = KMKernel::config();
  config->deleteGroup( "Folder-" + folder()->idString() );

  emit closed(folder());
  emit removed(folder(), (rc ? false : true));
}


//-----------------------------------------------------------------------------
int FolderStorage::expunge()
{
  assert(!folder()->name().isEmpty());

  clearIndex( true, mExportsSernums );   // delete and remove from dict, if needed
  close( "expunge", true );

  if ( mExportsSernums )
    KMMsgDict::mutableInstance()->removeFolderIds( *this );
  if ( mAutoCreateIndex )
    truncateIndex();
  else unlink(TQFile::encodeName(indexLocation()));

  int rc = expungeContents();
  if (rc) return rc;

  mDirty = false;
  needsCompact = false; //we're cleared and truncated no need to compact

  mUnreadMsgs = 0;
  mTotalMsgs = 0;
  mSize = 0;
  emit numUnreadMsgsChanged( folder() );
  if ( mAutoCreateIndex ) // FIXME Heh? - Till
    writeConfig();
  emit changed();
  emit expunged( folder() );

  return 0;
}

//-----------------------------------------------------------------------------
TQString FolderStorage::label() const
{
  return folder()->label();
}

int FolderStorage::count(bool cache) const
{
  if (cache && mTotalMsgs != -1)
    return mTotalMsgs;
  else
    return -1;
}

//-----------------------------------------------------------------------------
int FolderStorage::countUnread()
{
  if (mGuessedUnreadMsgs > -1)
    return mGuessedUnreadMsgs;
  if (mUnreadMsgs > -1)
    return mUnreadMsgs;

  readConfig();

  if (mUnreadMsgs > -1)
    return mUnreadMsgs;

  open("countunread"); // will update unreadMsgs
  int unread = mUnreadMsgs;
  close("countunread");
  return (unread > 0) ? unread : 0;
}

TQ_INT64 FolderStorage::folderSize() const
{
    if ( mSize != -1 ) {
        return mSize;
    } else {
        return doFolderSize();
    }
}


/*virtual*/
bool FolderStorage::isCloseToQuota() const
{
  return false;
}

//-----------------------------------------------------------------------------
void FolderStorage::msgStatusChanged(const KMMsgStatus oldStatus,
  const KMMsgStatus newStatus, int idx)
{
  int oldUnread = 0;
  int newUnread = 0;

  if (((oldStatus & KMMsgStatusUnread || oldStatus & KMMsgStatusNew) &&
      !(oldStatus & KMMsgStatusIgnored)) ||
      (folder() == kmkernel->outboxFolder()))
    oldUnread = 1;
  if (((newStatus & KMMsgStatusUnread || newStatus & KMMsgStatusNew) &&
      !(newStatus & KMMsgStatusIgnored)) ||
      (folder() == kmkernel->outboxFolder()))
    newUnread = 1;
  int deltaUnread = newUnread - oldUnread;

  mDirtyTimer->changeInterval(mDirtyTimerInterval);
  if (deltaUnread != 0) {
    if (mUnreadMsgs < 0) mUnreadMsgs = 0;
    mUnreadMsgs += deltaUnread;
    if ( !mQuiet ) {
      emit numUnreadMsgsChanged( folder() );
    }else{
      if ( !mEmitChangedTimer->isActive() ) {
        mEmitChangedTimer->start( 3000 );
      }
      mChanged = true;
    }
    TQ_UINT32 serNum = KMMsgDict::instance()->getMsgSerNum(folder(), idx);
    emit msgChanged( folder(), serNum, deltaUnread );
  }
}

//-----------------------------------------------------------------------------
void FolderStorage::headerOfMsgChanged(const KMMsgBase* aMsg, int idx)
{
  if (idx < 0)
    idx = aMsg->parent()->find( aMsg );

  if (idx >= 0 )
  {
    if ( !mQuiet )
      emit msgHeaderChanged(folder(), idx);
    else{
      if ( !mEmitChangedTimer->isActive() ) {
        mEmitChangedTimer->start( 3000 );
      }
      mChanged = true;
    }
  } else
    mChanged = true;
}

//-----------------------------------------------------------------------------
void FolderStorage::readConfig()
{
  //kdDebug(5006)<<"#### READING CONFIG  = "<< name() <<endl;
  KConfig* config = KMKernel::config();
  KConfigGroupSaver saver(config, "Folder-" + folder()->idString());
  if (mUnreadMsgs == -1)
    mUnreadMsgs = config->readNumEntry("UnreadMsgs", -1);
  if (mTotalMsgs == -1)
    mTotalMsgs = config->readNumEntry("TotalMsgs", -1);
  mCompactable = config->readBoolEntry("Compactable", true);
  if ( mSize == -1 )
      mSize = config->readNum64Entry("FolderSize", -1);

  int type = config->readNumEntry( "ContentsType", 0 );
  if ( type < 0 || type > KMail::ContentsTypeLast ) type = 0;
  setContentsType( static_cast<KMail::FolderContentsType>( type ) );

  if( folder() ) folder()->readConfig( config );
}

//-----------------------------------------------------------------------------
void FolderStorage::writeConfig()
{
  KConfig* config = KMKernel::config();
  KConfigGroupSaver saver(config, "Folder-" + folder()->idString());
  config->writeEntry("UnreadMsgs",
      mGuessedUnreadMsgs == -1 ? mUnreadMsgs : mGuessedUnreadMsgs);
  config->writeEntry("TotalMsgs", mTotalMsgs);
  config->writeEntry("Compactable", mCompactable);
  config->writeEntry("ContentsType", mContentsType);
  config->writeEntry("FolderSize", mSize);

  // Write the KMFolder parts
  if( folder() ) folder()->writeConfig( config );

  GlobalSettings::self()->requestSync();
}

//-----------------------------------------------------------------------------
void FolderStorage::correctUnreadMsgsCount()
{
  open("countunreadmsg");
  close("countunreadmsg");
  emit numUnreadMsgsChanged( folder() );
}

void FolderStorage::registerWithMessageDict()
{
  mExportsSernums = true;
  readFolderIdsFile();
}

void FolderStorage::deregisterFromMessageDict()
{
  writeFolderIdsFile();
  mExportsSernums = false;
}

void FolderStorage::readFolderIdsFile()
{
  if ( !mExportsSernums ) return;
  if ( KMMsgDict::mutableInstance()->readFolderIds( *this ) == -1 ) {
    invalidateFolder();
  }
  if ( !KMMsgDict::mutableInstance()->hasFolderIds( *this ) ) {
    invalidateFolder();
  }
}

void FolderStorage::invalidateFolder()
{
  if ( !mExportsSernums ) return;
  unlink(TQFile::encodeName( indexLocation()) + ".sorted");
  unlink(TQFile::encodeName( indexLocation()) + ".ids");
  fillMessageDict();
  KMMsgDict::mutableInstance()->writeFolderIds( *this );
  emit invalidated( folder() );
}


//-----------------------------------------------------------------------------
int FolderStorage::writeFolderIdsFile() const
{
  if ( !mExportsSernums ) return -1;
  return KMMsgDict::mutableInstance()->writeFolderIds( *this );
}

//-----------------------------------------------------------------------------
int FolderStorage::touchFolderIdsFile()
{
  if ( !mExportsSernums ) return -1;
  return KMMsgDict::mutableInstance()->touchFolderIds( *this );
}

//-----------------------------------------------------------------------------
int FolderStorage::appendToFolderIdsFile( int idx )
{
  if ( !mExportsSernums ) return -1;
  int ret = 0;
  if ( count() == 1 ) {
    ret = KMMsgDict::mutableInstance()->writeFolderIds( *this );
  } else {
    ret = KMMsgDict::mutableInstance()->appendToFolderIds( *this, idx );
  }
  return ret;
}

void FolderStorage::replaceMsgSerNum( unsigned long sernum, KMMsgBase* msg, int idx )
{
  if ( !mExportsSernums ) return;
  KMMsgDict::mutableInstance()->replace( sernum, msg, idx );
}

void FolderStorage::setRDict( KMMsgDictREntry *rentry ) const
{
  if ( ! mExportsSernums )
    kdDebug(5006) << "WTF, this FolderStorage should be invisible to the msgdict, who is calling us?" << kdBacktrace() << endl;
  assert( mExportsSernums ); // otherwise things are very wrong
  if ( rentry == mRDict )
    return;
  KMMsgDict::deleteRentry( mRDict );
  mRDict = rentry;
}

//-----------------------------------------------------------------------------
void FolderStorage::seStatus(int idx, KMMsgStatus status, bool toggle)
{
  KMMsgBase *msg = getMsgBase(idx);
  if ( msg ) {
    if (toggle)
      msg->toggleStatus(status, idx);
    else
      msg->seStatus(status, idx);
  }
}


//-----------------------------------------------------------------------------
void FolderStorage::seStatus(TQValueList<int>& ids, KMMsgStatus status, bool toggle)
{
  for ( TQValueList<int>::Iterator it = ids.begin(); it != ids.end(); ++it )
  {
    FolderStorage::seStatus(*it, status, toggle);
  }
}

void FolderStorage::ignoreJobsForMessage( KMMessage *msg )
{
  if ( !msg || msg->transferInProgress() )
    return;

  TQPtrListIterator<FolderJob> it( mJobList );
  while ( it.current() )
  {
    //FIXME: the questions is : should we iterate through all
    //messages in jobs? I don't think so, because it would
    //mean canceling the jobs that work with other messages
    if ( it.current()->msgList().first() == msg )
    {
      FolderJob* job = it.current();
      mJobList.remove( job );
      delete job;
    } else
      ++it;
  }
}

//-----------------------------------------------------------------------------
void FolderStorage::removeJobs()
{
  mJobList.setAutoDelete( true );
  mJobList.clear();
  mJobList.setAutoDelete( false );
}



//-----------------------------------------------------------------------------
void FolderStorage::updateChildrenState()
{
  if ( folder() && folder()->child() )
  {
    if ( kmkernel->folderMgr()->folderCount( folder()->child() ) > 0 )
      setHasChildren( HasChildren );
    else
      setHasChildren( HasNoChildren );
  }
}

//-----------------------------------------------------------------------------
void FolderStorage::setNoChildren( bool aNoChildren )
{
  mNoChildren = aNoChildren;
  if ( aNoChildren )
    setHasChildren( HasNoChildren );
}

//-----------------------------------------------------------------------------
void FolderStorage::setContentsType( KMail::FolderContentsType type, bool quiet )
{
  if ( type != mContentsType ) {
    mContentsType = type;
    if ( !quiet )
       emit contentsTypeChanged( type );
  }
}

//-----------------------------------------------------------------------------
void FolderStorage::search( const KMSearchPattern* pattern )
{
  mSearchPattern = pattern;
  mCurrentSearchedMsg = 0;
  if ( pattern )
    slotProcessNextSearchBatch();
}

void FolderStorage::slotProcessNextSearchBatch()
{
  if ( !mSearchPattern )
    return;
  TQValueList<TQ_UINT32> matchingSerNums;
  const int end = TQMIN( mCurrentSearchedMsg + 15, count() );
  for ( int i = mCurrentSearchedMsg; i < end; ++i )
  {
    TQ_UINT32 serNum = KMMsgDict::instance()->getMsgSerNum( folder(), i );
    if ( mSearchPattern->matches( serNum ) )
      matchingSerNums.append( serNum );
  }
  mCurrentSearchedMsg = end;
  bool complete = ( end >= count() );
  emit searchResult( folder(), matchingSerNums, mSearchPattern, complete );
  if ( !complete )
    TQTimer::singleShot( 0, this, TQT_SLOT(slotProcessNextSearchBatch()) );
}

//-----------------------------------------------------------------------------
void FolderStorage::search( const KMSearchPattern* pattern, TQ_UINT32 serNum )
{
  bool matches = pattern && pattern->matches( serNum );

  emit searchDone( folder(), serNum, pattern, matches );
}

//-----------------------------------------------------------------------------
int FolderStorage::addMsg( TQPtrList<KMMessage>& msgList, TQValueList<int>& index_ret )
{
  int ret = 0;
  int index;
  for ( TQPtrListIterator<KMMessage> it( msgList ); *it; ++it )
  {
    int aret = addMsg( *it, &index );
    index_ret << index;
    if ( aret != 0 ) // error condition
      ret = aret;
  }
  return ret;
}

//-----------------------------------------------------------------------------
bool FolderStorage::isMoveable() const
{
  return ( folder()->isSystemFolder() ) ? false : true;
}


/*virtual*/
KMAccount* FolderStorage::account() const
{
    return 0;
}

bool FolderStorage::mailCheckInProgress() const
{
  return false;
}

bool FolderStorage::canDeleteMessages() const
{
  return !isReadOnly();
}

void FolderStorage::setNoContent(bool aNoContent)
{
  const bool changed = aNoContent != mNoContent;
  mNoContent = aNoContent;
  if ( changed )
    emit noContentChanged();
}

#include "folderstorage.moc"