summaryrefslogtreecommitdiffstats
path: root/kmail/subscriptiondialog.cpp
blob: ac59099366434402563e4349813111639fa444fa (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
/*  -*- c++ -*-
    subscriptiondialog.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (C) 2002 Carsten Burghardt <burghardt@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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), 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
    Qt.  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.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "subscriptiondialog.h"
#include "folderstorage.h"
#include "listjob.h"
#include "imapaccountbase.h"

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


namespace KMail {

SubscriptionDialogBase::SubscriptionDialogBase( QWidget *parent, const QString &caption,
    KAccount *acct, QString startPath )
  : KSubscription( parent, caption, acct, User1, QString::null, false ),
    mStartPath( startPath ), mSubscribed( false ), mForceSubscriptionEnable( false)
{
  // hide unneeded checkboxes
  hideTreeCheckbox();
  hideNewOnlyCheckbox();

  // ok-button
  connect(this, SIGNAL(okClicked()), SLOT(slotSave()));

  // reload-list button
  connect(this, SIGNAL(user1Clicked()), SLOT(slotLoadFolders()));

  // get the folders, delayed execution style, otherwise there's bother
  // with virtuals from ctors and whatnot
  QTimer::singleShot(0, this, SLOT(slotLoadFolders()));
}

//------------------------------------------------------------------------------
void SubscriptionDialogBase::slotListDirectory( const QStringList& subfolderNames,
                                            const QStringList& subfolderPaths,
                                            const QStringList& subfolderMimeTypes,
                                            const QStringList& subfolderAttributes,
                                            const ImapAccountBase::jobData& jobData )
{
  mFolderNames = subfolderNames;
  mFolderPaths = subfolderPaths;
  mFolderMimeTypes = subfolderMimeTypes;
  mFolderAttributes = subfolderAttributes;
  mJobData = jobData;

  mCount = 0;

  processFolderListing();
}

void SubscriptionDialogBase::moveChildrenToNewParent( GroupItem *oldItem, GroupItem *item  )
{
  if ( !oldItem || !item ) return;

  QPtrList<QListViewItem> itemsToMove;
  QListViewItem * myChild = oldItem->firstChild();
  while (myChild)
  {
    itemsToMove.append(myChild);
    myChild = myChild->nextSibling();
  }
  QPtrListIterator<QListViewItem> it( itemsToMove );
  QListViewItem *cur;
  while ((cur = it.current()))
  {
    oldItem->takeItem(cur);
    item->insertItem(cur);
    if ( cur->isSelected() ) // we have new parents so open them
      folderTree()->ensureItemVisible( cur );
    ++it;
  }
  delete oldItem;
  itemsToMove.clear();
}

void SubscriptionDialogBase::createListViewItem( int i )
{
  GroupItem *item = 0;
  GroupItem *parent = 0;

  // get the parent
  GroupItem *oldItem = 0;
  QString parentPath;
  findParentItem( mFolderNames[i], mFolderPaths[i], parentPath, &parent, &oldItem );

  if (!parent && parentPath != "/")
  {
    // the parent is not available and it's no root-item
    // this happens when the folders do not arrive in hierarchical order
    // so we create each parent in advance
    QStringList folders = QStringList::split(mDelimiter, parentPath);
    uint i = 0;
    for ( QStringList::Iterator it = folders.begin(); it != folders.end(); ++it )
    {
      QString name = *it;
      if (name.startsWith("/"))
        name = name.right(name.length()-1);
      if (name.endsWith("/"))
        name.truncate(name.length()-1);
      KGroupInfo info(name);
      info.subscribed = false;

      QStringList tmpPath;
      for ( uint j = 0; j <= i; ++j )
        tmpPath << folders[j];
      QString path = tmpPath.join(mDelimiter);
      if (!path.startsWith("/"))
        path = "/" + path;
      if (!path.endsWith("/"))
        path = path + "/";
      info.path = path;
      item = 0;
      if (folders.count() > 1)
      {
        // we have to create more then one level, so better check if this
        // folder already exists somewhere
        item = mItemDict[path];
      }
      // as these items are "dummies" we create them non-checkable
      if (!item)
      {
        if (parent)
          item = new GroupItem(parent, info, this, false);
        else
          item = new GroupItem(folderTree(), info, this, false);
        mItemDict.insert(info.path, item);
      }

      parent = item;
      ++i;
    } // folders
  } // parent

  KGroupInfo info(mFolderNames[i]);
  if (mFolderNames[i].upper() == "INBOX" &&
      mFolderPaths[i] == "/INBOX/")
    info.name = i18n("inbox");
  info.subscribed = false;
  info.path = mFolderPaths[i];
  // only checkable when the folder is selectable
  bool checkable = ( mFolderMimeTypes[i] == "inode/directory" ) ? false : true;
  // create a new item
  if (parent)
    item = new GroupItem(parent, info, this, checkable);
  else
    item = new GroupItem(folderTree(), info, this, checkable);

  if (oldItem) // remove old item
    mItemDict.remove(info.path);

  mItemDict.insert(info.path, item);
  if (oldItem)
    moveChildrenToNewParent( oldItem, item );

  // select the start item
  if ( mFolderPaths[i] == mStartPath )
  {
    item->setSelected( true );
    folderTree()->ensureItemVisible( item );
  }
}



//------------------------------------------------------------------------------
void SubscriptionDialogBase::findParentItem( QString &name, QString &path, QString &parentPath,
    GroupItem **parent, GroupItem **oldItem )
{
  // remove the name (and the separator) from the path to get the parent path
  int start = path.length() - (name.length()+2);
  int length = name.length()+1;
  if (start < 0) start = 0;
  parentPath = path;
  parentPath.remove(start, length);

  // find the parent by it's path
  *parent = mItemDict[parentPath];

  // check if the item already exists
  *oldItem = mItemDict[path];
}

//------------------------------------------------------------------------------
void SubscriptionDialogBase::slotSave()
{
  doSave();
}

//------------------------------------------------------------------------------
void SubscriptionDialogBase::slotLoadFolders()
{
  ImapAccountBase* ai = static_cast<ImapAccountBase*>(account());
  // we need a connection
  if ( ai->makeConnection() == ImapAccountBase::Error )
  {
    kdWarning(5006) << "SubscriptionDialog - got no connection" << endl;
    return;
  } else if ( ai->makeConnection() == ImapAccountBase::Connecting )
  {
    // We'll wait for the connectionResult signal from the account.
    kdDebug(5006) << "SubscriptionDialog - waiting for connection" << endl;
    connect( ai, SIGNAL( connectionResult(int, const QString&) ),
        this, SLOT( slotConnectionResult(int, const QString&) ) );
    return;
  }
  // clear the views
  KSubscription::slotLoadFolders();
  mItemDict.clear();
  mSubscribed = false;
  mLoading = true;

  // first step is to load a list of all available folders and create listview
  // items for them
  listAllAvailableAndCreateItems();
}

//------------------------------------------------------------------------------
void SubscriptionDialogBase::processNext()
{
  if ( mPrefixList.isEmpty() )
  {
    if ( !mSubscribed )
    {
      mSubscribed = true;
      initPrefixList();
      if ( mPrefixList.isEmpty() )
      {
          // still empty? then we have nothing to do here as this is an error
          loadingComplete();
          return;
      }
    } else {
      loadingComplete();
      return;
    }
  }
  ImapAccountBase* ai = static_cast<ImapAccountBase*>(account());
  ImapAccountBase::ListType type = ( mSubscribed ?
      ImapAccountBase::ListSubscribedNoCheck : ImapAccountBase::List );

  bool completeListing = true;
  mCurrentNamespace = mPrefixList.first();
  mDelimiter = ai->delimiterForNamespace( mCurrentNamespace );
  mPrefixList.pop_front();
  if ( mCurrentNamespace == "/INBOX/" )
  {
    type = mSubscribed ?
      ImapAccountBase::ListFolderOnlySubscribed : ImapAccountBase::ListFolderOnly;
    completeListing = false;
  }

//  kdDebug(5006) << "process " << mCurrentNamespace << ",subscribed=" << mSubscribed << endl;
  ListJob* job = new ListJob( ai, type, 0, ai->addPathToNamespace( mCurrentNamespace ), completeListing );
  connect( job, SIGNAL(receivedFolders(const QStringList&, const QStringList&,
          const QStringList&, const QStringList&, const ImapAccountBase::jobData&)),
      this, SLOT(slotListDirectory(const QStringList&, const QStringList&,
          const QStringList&, const QStringList&, const ImapAccountBase::jobData&)));
  job->start();
}

void SubscriptionDialogBase::loadingComplete()
{
  slotLoadingComplete();
}


//------------------------------------------------------------------------------
// implementation for server side subscription
//------------------------------------------------------------------------------

SubscriptionDialog::SubscriptionDialog( QWidget *parent, const QString &caption,
    KAccount *acct, QString startPath )
  : SubscriptionDialogBase( parent, caption, acct, startPath )
{
}

/* virtual */
SubscriptionDialog::~SubscriptionDialog()
{

}

/* virtual */
void SubscriptionDialog::listAllAvailableAndCreateItems()
{
  initPrefixList();
  processNext();
}

//------------------------------------------------------------------------------
void SubscriptionDialogBase::initPrefixList()
{
  ImapAccountBase* ai = static_cast<ImapAccountBase*>(account());
  ImapAccountBase::nsMap map = ai->namespaces();
  mPrefixList.clear();

  bool hasInbox = false;
  const QStringList ns = map[ImapAccountBase::PersonalNS];
  for ( QStringList::ConstIterator it = ns.begin(); it != ns.end(); ++it )
  {
    if ( (*it).isEmpty() )
      hasInbox = true;
  }
  if ( !hasInbox && !ns.isEmpty() )
  {
    // the namespaces includes no listing for the root so start a special
    // listing for the INBOX to make sure we get it
    mPrefixList += "/INBOX/";
  }

  mPrefixList += map[ImapAccountBase::PersonalNS];
  mPrefixList += map[ImapAccountBase::OtherUsersNS];
  mPrefixList += map[ImapAccountBase::SharedNS];
}

void SubscriptionDialogBase::slotConnectionResult( int errorCode, const QString& errorMsg )
{
  Q_UNUSED( errorMsg );
  if ( !errorCode )
    slotLoadFolders();
}

void SubscriptionDialogBase::show()
{
  KDialogBase::show();
}

// =======
/* virtual */
void SubscriptionDialog::processFolderListing()
{
    processItems();
}

/* virtual */
void SubscriptionDialog::doSave()
{
  KMail::ImapAccountBase *a = static_cast<KMail::ImapAccountBase*>(mAcct);
  if( !a->onlySubscribedFolders() ) {
      int result = KMessageBox::questionYesNoCancel( this,
              i18n("Currently subscriptions are not used for server %1\ndo you want to enable subscriptions?")
              .arg( a->name() ),
              i18n("Enable Subscriptions?"), i18n("Enable"), i18n("Do Not Enable"));
      switch(result) {
          case KMessageBox::Yes:
              mForceSubscriptionEnable = true;
              break;
          case KMessageBox::No:
              break;
          case KMessageBox::Cancel:
              cancel();
      }
  }

  // subscribe
  QListViewItemIterator it(subView);
  for ( ; it.current(); ++it)
  {
    static_cast<ImapAccountBase*>(account())->changeSubscription(true,
        static_cast<GroupItem*>(it.current())->info().path);
  }

  // unsubscribe
  QListViewItemIterator it2(unsubView);
  for ( ; it2.current(); ++it2)
  {
    static_cast<ImapAccountBase*>(account())->changeSubscription(false,
        static_cast<GroupItem*>(it2.current())->info().path);
  }

  if ( mForceSubscriptionEnable ) {
    a->setOnlySubscribedFolders(true);
  }
}

void SubscriptionDialog::processItems()
{
  bool onlySubscribed = mJobData.onlySubscribed;
  uint done = 0;
  for (uint i = mCount; i < mFolderNames.count(); ++i)
  {
    // give the dialog a chance to repaint
    if (done == 1000)
    {
      emit listChanged();
      QTimer::singleShot(0, this, SLOT(processItems()));
      return;
    }
    ++mCount;
    ++done;
    if (!onlySubscribed && mFolderPaths.size() > 0)
    {
      createListViewItem( i );
    } else if (onlySubscribed)
    {
      // find the item
      if ( mItemDict[mFolderPaths[i]] )
      {
        GroupItem* item = mItemDict[mFolderPaths[i]];
        item->setOn( true );
      }
    }
  }

  processNext();
}
} // namespace

#include "subscriptiondialog.moc"