summaryrefslogtreecommitdiffabout
path: root/libkdepim/ksyncmanager.cpp
blob: 87f200aaeadb3042ea1e14f2a99478b9ecb96668 (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
/*
    This file is part of KDE-Pim/Pi.
    Copyright (c) 2004 Ulf Schenk

    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., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

// $Id$

#include "ksyncmanager.h"

#include <stdlib.h>

#ifndef _WIN32_
#include <unistd.h>
#endif


#include "ksyncprofile.h"
#include "ksyncprefsdialog.h"
#include "kpimprefs.h"

#include <qdir.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qtimer.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qlineedit.h>
#include <qdialog.h>
#include <qlayout.h>

#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kfiledialog.h>

KSyncManager::KSyncManager(QWidget* parent, KSyncInterface* implementation, TargetApp ta, KPimPrefs* prefs, QPopupMenu* syncmenu)
  : QObject(), mParent(parent), mImplementation(implementation), mTargetApp(ta), mPrefs(prefs), mSyncMenu(syncmenu)
{

}

KSyncManager::~KSyncManager()
{

}


void KSyncManager::fillSyncMenu()
{
    if ( mSyncMenu->count() )
        mSyncMenu->clear();
    
    mSyncMenu->insertItem( i18n("Configure..."), 0 );
    mSyncMenu->insertSeparator();
    mSyncMenu->insertItem( i18n("Multiple sync"), 1 );
    mSyncMenu->insertSeparator();
    
    KConfig config ( locateLocal( "config","ksyncprofilesrc"  ) );
    config.setGroup("General");
    QStringList prof = config.readListEntry("SyncProfileNames");
    mPrefs->mLocalMachineName = config.readEntry("LocalMachineName","undefined");
    if ( prof.count() < 3 ) {
        prof.clear();
        prof << i18n("Sharp_DTM");
        prof << i18n("Local_file");
        prof << i18n("Last_file");
        KSyncProfile* temp = new KSyncProfile ();
        temp->setName( prof[0] );
        temp->writeConfig(&config);
        temp->setName( prof[1] );
        temp->writeConfig(&config);
        temp->setName( prof[2] );
        temp->writeConfig(&config);
        config.setGroup("General");
        config.writeEntry("SyncProfileNames",prof);
        config.writeEntry("ExternSyncProfiles","Sharp_DTM");
        config.sync();
        delete temp;
    }
    mPrefs->mExternSyncProfiles = config.readListEntry("ExternSyncProfiles");
    mPrefs->mSyncProfileNames = prof;
    unsigned int i;
    for ( i = 0; i < prof.count(); ++i ) {

        mSyncMenu->insertItem(  prof[i], 1000+i );
        if ( i == 2 )
            mSyncMenu->insertSeparator();
    }
    QDir app_dir;
    if ( !app_dir.exists(QDir::homeDirPath()+"/Applications/dtm" ) ) {
        mSyncMenu->setItemEnabled( false , 1000 );
    }
    //probaly useless
    //mView->setupExternSyncProfiles();
}

void KSyncManager::slotSyncMenu( int action )
{
    //qDebug("syncaction %d ", action);
    if ( action == 0 ) {

        // seems to be a Qt2 event handling bug
        // syncmenu.clear causes a segfault at first time
        // when we call it after the main event loop, it is ok
        // same behaviour when calling OM/Pi via QCOP for the first time
        QTimer::singleShot ( 1, this, SLOT ( confSync() ) ); 
        //confSync();

        return;
    }
    if ( action == 1 ) {
        multiSync( true );
        return;
    }

    if (blockSave())
      return;

    setBlockSave(true);

    mCurrentSyncProfile = action - 1000 ;
    mCurrentSyncDevice = mPrefs->mSyncProfileNames[mCurrentSyncProfile] ;
    mCurrentSyncName =  mPrefs->mLocalMachineName ;
    KConfig config ( locateLocal( "config","ksyncprofilesrc"  ) );
    KSyncProfile* temp = new KSyncProfile ();
    temp->setName(mPrefs->mSyncProfileNames[mCurrentSyncProfile]);
    temp->readConfig(&config);
    mPrefs->mAskForPreferences = temp->getAskForPreferences();
    mPrefs->mSyncAlgoPrefs = temp->getSyncPrefs();
    mPrefs->mWriteBackFile = temp->getWriteBackFile();
    mPrefs->mWriteBackExistingOnly = temp->getWriteBackExisting();
    mPrefs->mWriteBackInFuture = 0;
    if ( temp->getWriteBackFuture() )
        mPrefs->mWriteBackInFuture =  temp->getWriteBackFutureWeeks( );
    mPrefs->mShowSyncSummary = temp->getShowSummaryAfterSync();
    if ( action == 1000  ) {
        syncSharp();
    
    } else if ( action == 1001 ) {
        syncLocalFile();

    } else if ( action == 1002 ) {
        quickSyncLocalFile();

    } else if ( action >= 1003  ) {
        if ( temp->getIsLocalFileSync() ) {
	  if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
                mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();

        } else {
            if (  temp->getIsPhoneSync() ) {
                mPrefs->mPhoneDevice = temp->getPhoneDevice( ) ;
                mPrefs->mPhoneConnection = temp->getPhoneConnection( );
                mPrefs->mPhoneModel = temp->getPhoneModel( );
                syncPhone();
            } else
                syncRemote( temp );

        }
    }
    delete temp;
    setBlockSave(false);
}

void KSyncManager::syncLocalFile()
{

    QString fn =mPrefs->mLastSyncedLocalFile;

    fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.ics/*.vcs)"), mParent );
    if ( fn == "" )
        return;
    if (  syncWithFile(  fn, false ) ) {
        qDebug("syncLocalFile() successful ");
    }

}
bool  KSyncManager::syncWithFile( QString fn , bool quick )
{
    bool ret = false;
    QFileInfo info;
    info.setFile( fn );
    QString mess;
    bool loadbup = true;
    if ( !info. exists() ) {
        mess =  i18n( "Sync file \n...%1\ndoes not exist!\nNothing synced!\n").arg(fn.right( 30) );
        int result = QMessageBox::warning( mParent, i18n("Warning!"),
                                           mess );
        return ret;
    }
    int result = 0;
    if ( !quick ) {
        mess =  i18n("Sync with file \n...%1\nfrom:\n%2\n").arg(fn.right( 25)).arg(KGlobal::locale()->formatDateTime(info.lastModified (), true, false ));
        result = QMessageBox::warning( mParent, i18n("Warning!"),
                                       mess,
                                       i18n("Sync"), i18n("Cancel"), 0,
                                       0, 1 );
        if ( result )
            return false;
    }
    if ( mPrefs->mAskForPreferences )
        edit_sync_options();
    if ( result == 0 ) {
        //qDebug("Now sycing ... ");
        if ( ret = mImplementation->sync( this, fn, mPrefs->mSyncAlgoPrefs ) )
            mParent->setCaption( i18n("Synchronization successful") );
        else
            mParent->setCaption( i18n("Sync cancelled or failed. Nothing synced.") );
        if ( ! quick )
            mPrefs->mLastSyncedLocalFile = fn;
	mImplementation->sync_setModified();
    }
    return ret;
}
void KSyncManager::quickSyncLocalFile()
{
    
    if ( syncWithFile( mPrefs->mLastSyncedLocalFile, false ) ) {
        qDebug("quick syncLocalFile() successful ");
      
    }
}
void KSyncManager::multiSync( bool askforPrefs  )
{
    if (blockSave())
        return;
    setBlockSave(true);
    QString question = i18n("Do you really want\nto multiple sync\nwith all checked profiles?\nSyncing takes some\ntime - all profiles\nare synced twice!");
    if ( QMessageBox::information( mParent, i18n("Sync"),
                                   question,
                                   i18n("Yes"), i18n("No"),
                                   0, 0 ) != 0 ) {
        setBlockSave(false);
        mParent->setCaption(i18n("Aborted! Nothing synced!"));
        return;
    }
    mCurrentSyncDevice = i18n("Multiple profiles") ;
    mPrefs->mSyncAlgoPrefs = mPrefs->mRingSyncAlgoPrefs;
    if ( askforPrefs ) {
        edit_sync_options();
        mPrefs->mRingSyncAlgoPrefs = mPrefs->mSyncAlgoPrefs;
    }
    mParent->setCaption(i18n("Multiple sync started.") );
    qApp->processEvents();
    int num = ringSync() ;
    if (  num > 1 )
        ringSync();
    setBlockSave(false);
    if ( num )
        mImplementation->sync_save();
    if ( num )
        mParent->setCaption(i18n("%1 profiles synced. Multiple sync completed!").arg(num) );
    else
        mParent->setCaption(i18n("Nothing synced! No profiles defined for multisync!"));
    return;
}
int KSyncManager::ringSync()
{
    int syncedProfiles = 0;
    unsigned int i;
    QTime timer;
    KConfig config ( locateLocal( "config","ksyncprofilesrc"  ) );
    QStringList syncProfileNames = mPrefs->mSyncProfileNames;
    KSyncProfile* temp = new KSyncProfile ();
    mPrefs->mAskForPreferences = false;
    for ( i = 0; i < syncProfileNames.count(); ++i ) {
        mCurrentSyncProfile = i;
        temp->setName(syncProfileNames[mCurrentSyncProfile]);
        temp->readConfig(&config);
        if ( temp->getIncludeInRingSyncAB() && ( i < 1 || i > 2  )) {
            mParent->setCaption(i18n("Profile ")+syncProfileNames[mCurrentSyncProfile]+ i18n(" is synced ... "));
            ++syncedProfiles;
            // mPrefs->mAskForPreferences = temp->getAskForPreferences();
            mPrefs->mWriteBackFile = temp->getWriteBackFile();
            mPrefs->mWriteBackExistingOnly = temp->getWriteBackExisting();
            mPrefs->mWriteBackInFuture = 0;
            if ( temp->getWriteBackFuture() )
                mPrefs->mWriteBackInFuture =  temp->getWriteBackFutureWeeks( );
            mPrefs->mShowSyncSummary = false;
            mCurrentSyncDevice = syncProfileNames[i] ;
            mCurrentSyncName = mPrefs->mLocalMachineName;
            if ( i == 0 ) {
                syncSharp();
            } else {
                if ( temp->getIsLocalFileSync() ) {
                    if ( syncWithFile( temp->getRemoteFileNameAB( ), true ) )
                        mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
                } else {
                    if (  temp->getIsPhoneSync() ) {
                        mPrefs->mPhoneDevice = temp->getPhoneDevice( ) ;
                        mPrefs->mPhoneConnection = temp->getPhoneConnection( );
                        mPrefs->mPhoneModel = temp->getPhoneModel( );
                        syncPhone();
                    } else
                        syncRemote( temp, false );

                }
            }
            timer.start();
            mParent->setCaption(i18n("Multiple sync in progress ... please wait!") );
            while ( timer.elapsed () < 2000 ) {
                qApp->processEvents();
#ifndef _WIN32_
                sleep (1);
#endif
            }

        }

    }
    delete temp;
    return syncedProfiles;
}

void KSyncManager::syncRemote( KSyncProfile* prof,  bool ask)
{
    QString question;
    if ( ask ) {
    question = i18n("Do you really want\nto remote sync\nwith profile \n")+ prof->getName()+" ?\n";
    if ( QMessageBox::information( mParent, i18n("Sync"),
                                   question,
                                   i18n("Yes"), i18n("No"),
                                   0, 0 ) != 0 )
        return;
    }
    QString command = prof->getPreSyncCommandAB();
    int fi;
    if ( (fi = command.find("$PWD$")) > 0 ) {
        QString pwd = getPassword();
        command = command.left( fi )+ pwd + command.mid( fi+5 );

    }
    int maxlen = 30;
    if ( QApplication::desktop()->width() > 320 )
        maxlen += 25;
    mParent->setCaption ( i18n( "Copy remote file to local machine..." ) );
    int fileSize = 0;
    int result = system ( command );
    // 0 : okay
    // 256: no such file or dir
    //
    qDebug("KO: Remote copy result(0 = okay): %d ",result );
    if ( result != 0 ) {
        unsigned int len = maxlen;
        while ( len <  command.length() ) {
            command.insert( len , "\n" );
            len += maxlen +2;
        }
        question = i18n("Sorry, the copy command failed!\nCommand was:\n%1\n \nTry command on console to get more\ndetailed info about the reason.\n").arg (command) ;
        QMessageBox::information( mParent, i18n("Sync - ERROR"),
                                  question,
                                  i18n("Okay!")) ;
        mParent->setCaption ("");
        return;
    }
    mParent->setCaption ( i18n( "Copying succeed." ) );
    //qDebug(" file **%s** ",prof->getLocalTempFile().latin1() );
    if ( syncWithFile( prof->getLocalTempFileAB(), true ) ) {
//         Event* e = mView->getLastSyncEvent();
//         e->setReadOnly( false );
//         e->setLocation( KOPrefs::instance()->mSyncProfileNames[mCurrentSyncProfile]);
//         e->setReadOnly( true );
        if ( mPrefs->mWriteBackFile ) {
            command =  prof->getPostSyncCommandAB(); 
            int fi;
            if ( (fi = command.find("$PWD$")) > 0 ) {
                QString pwd = getPassword();
                command = command.left( fi )+ pwd + command.mid( fi+5 );
                
            }
            mParent->setCaption ( i18n( "Writing back file ..." ) );
            result = system ( command );
            qDebug("Writing back file result: %d ", result);
            if ( result != 0 ) {
                mParent->setCaption ( i18n( "Writing back file result: " )+QString::number( result ) );
                return;
            } else {
                mParent->setCaption ( i18n( "Syncronization sucessfully completed" ) );
            }
        }
    }
    return;
}

void KSyncManager::edit_sync_options()
{
    //mDialogManager->showSyncOptions();
    //mPrefs->mSyncAlgoPrefs 
    QDialog dia( mParent, "dia", true );
    dia.setCaption( i18n("Device: " ) +mCurrentSyncDevice );
    QButtonGroup gr ( 1,  Qt::Horizontal, i18n("Sync preferences"), &dia);
    QVBoxLayout lay ( &dia );
    lay.setSpacing( 2 );
    lay.setMargin( 3 );
    lay.addWidget(&gr);
    QRadioButton loc ( i18n("Take local entry on conflict"), &gr );
    QRadioButton rem ( i18n("Take remote entry on conflict"), &gr );
    QRadioButton newest( i18n("Take newest entry on conflict"), &gr );
    QRadioButton ask( i18n("Ask for every entry on conflict"), &gr );
    QRadioButton f_loc( i18n("Force: Take local entry always"), &gr );
    QRadioButton f_rem( i18n("Force: Take remote entry always"), &gr );
    //QRadioButton both( i18n("Take both on conflict"), &gr );
    QPushButton pb ( "OK",  &dia); 
    lay.addWidget( &pb );
    connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); 
    switch ( mPrefs->mSyncAlgoPrefs ) {
    case 0:
        loc.setChecked( true);
        break;
    case 1:
        rem.setChecked( true );
        break;
    case 2:
        newest.setChecked( true);
        break;
    case 3:
        ask.setChecked( true);
        break;
    case 4:
        f_loc.setChecked( true);
        break;
    case 5:
        f_rem.setChecked( true);
        break;
    case 6:
        // both.setChecked( true);
        break; 
    default:
        break;
    }
    if ( dia.exec() ) {
        mPrefs->mSyncAlgoPrefs = rem.isChecked()*1+newest.isChecked()*2+  ask.isChecked()*3+  f_loc.isChecked()*4+  f_rem.isChecked()*5;//+  both.isChecked()*6 ;
    }
   

}
QString  KSyncManager::getPassword( )
{
    QString retfile = "";
    QDialog dia ( mParent, "input-dialog", true );
    QLineEdit lab ( &dia );
    lab.setEchoMode( QLineEdit::Password );
    QVBoxLayout lay( &dia );
    lay.setMargin(7);
    lay.setSpacing(7);
    lay.addWidget( &lab);
    dia.setFixedSize( 230,50 );
    dia.setCaption( i18n("Enter password") );
    QPushButton pb ( "OK",  &dia);
    lay.addWidget( &pb );
    connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
    dia.show();
    int res = dia.exec();
    if ( res )
        retfile = lab.text();
    dia.hide();
    qApp->processEvents();
    return retfile;

}


void KSyncManager::confSync()
{ 
    static KSyncPrefsDialog* sp = 0;
    if ( ! sp ) {
        sp = new KSyncPrefsDialog( mParent, "syncprefs", true );
    }
    sp->usrReadConfig();
#ifndef DESKTOP_VERSION
    sp->showMaximized();
#else
    sp->show();
#endif
    sp->exec();
    mPrefs->mSyncProfileNames = sp->getSyncProfileNames();
    mPrefs->mLocalMachineName = sp->getLocalMachineName ();
    fillSyncMenu();
}

void KSyncManager::syncSharp()
{
    if ( ! syncExternalApplication("sharp") )
        qDebug("ERROR sync sharp  ");;
}

bool KSyncManager::syncExternalApplication(QString  resource)
{
    if (  mImplementation->sync_isModified()  )
        mImplementation->sync_save();

    if ( mPrefs->mAskForPreferences )
        edit_sync_options();

    qDebug("sync %s", resource.latin1());

    bool syncOK = mImplementation->syncExternal(this, resource);

    return syncOK;

}

void KSyncManager::syncPhone()
{
    if (  mImplementation->sync_isModified()  )
        mImplementation->sync_save();

    qDebug("pending syncPhone(); ");
    //mView->syncPhone();
    mImplementation->sync_setModified();

}