summaryrefslogtreecommitdiffabout
path: root/libkdepim/ksyncmanager.cpp
blob: 9177f6350adfc2509df9cc4aff195d77642ace9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
/*
  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 <kmessagebox.h>

#include <qdir.h>
#include <qprogressbar.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 <qtextcodec.h>
#include <qlabel.h>
#include <qcheckbox.h>

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

QDateTime KSyncManager::mRequestedSyncEvent;


KSyncManager::KSyncManager(QWidget* parent, KSyncInterface* implementation, TargetApp ta, KPimPrefs* prefs, QPopupMenu* syncmenu)
    : QObject(),  mPrefs(prefs ), mParent(parent),mImplementation(implementation), mTargetApp(ta), mSyncMenu(syncmenu)
{
    mServerSocket = 0;
    bar = new QProgressBar ( 1, 0 );
    bar->setCaption ("");
    mWriteBackInPast = 2;
    int w = 300;
    if ( QApplication::desktop()->width() < 320 )
        w = 220;
    int h = bar->sizeHint().height() ;
    int dw = QApplication::desktop()->width();
    int dh = QApplication::desktop()->height();
    bar->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
    if ( mPrefs->mPassiveSyncAutoStart )
      enableQuick( false );

}

KSyncManager::~KSyncManager()
{
    delete bar;
}


void KSyncManager::fillSyncMenu()
{
    if ( mSyncMenu->count() )
        mSyncMenu->clear();
    
    mSyncMenu->insertItem( i18n("Configure..."), 0 );
    mSyncMenu->insertSeparator();
    QPopupMenu *clearMenu = new QPopupMenu ( mSyncMenu );
    mSyncMenu->insertItem( i18n("Remove sync info"),clearMenu, 5000 );
    clearMenu->insertItem( i18n("For all profiles"), 1 );
    clearMenu->insertSeparator();
    connect ( clearMenu, SIGNAL( activated ( int )  ), this, SLOT (slotClearMenu( int ) ) );
    mSyncMenu->insertSeparator();
    if ( mServerSocket == 0 ) {
        mSyncMenu->insertItem( i18n("Enable Pi-Sync"), 2 );
    } else {
        mSyncMenu->insertItem( i18n("Disable Pi-Sync"), 3 );
    }
    mSyncMenu->insertSeparator();
    mSyncMenu->insertItem( i18n("Multiple sync"), 1 );
    mSyncMenu->insertSeparator();
    KConfig config ( locateLocal( "config","ksyncprofilesrc"  ) );
    config.setGroup("General");
    QStringList prof = config.readListEntry("SyncProfileNames");
    mLocalMachineName = config.readEntry("LocalMachineName","undefined");
    if ( prof.count() < 2 ) {
        prof.clear();
        QString externalName;
#ifdef DESKTOP_VERSION
#ifdef _WIN32_
        externalName = "OutLook(not_implemented)";
#else
        externalName = "KDE_Desktop";
#endif
#else
        externalName = "Sharp_DTM";
#endif
        prof << externalName;
        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",externalName);
        config.sync();
        delete temp;
    }
    mExternSyncProfiles = config.readListEntry("ExternSyncProfiles");
    mSyncProfileNames = prof;
    unsigned int i;
    for ( i = 0; i < prof.count(); ++i ) {
        mSyncMenu->insertItem(  prof[i], 1000+i ); 
        clearMenu->insertItem(  prof[i], 1000+i ); 
        if ( i == 2 )
            mSyncMenu->insertSeparator();
    }
    QDir app_dir;
    //US do not display SharpDTM if app is pwmpi, or no sharpfiles available
    if ( mTargetApp == PWMPI) {
        mSyncMenu->removeItem( 1000 );
        clearMenu->removeItem( 1000 );
    }
#ifndef DESKTOP_VERSION
    else if (!app_dir.exists(QDir::homeDirPath()+"/Applications/dtm" ) ) {
        mSyncMenu->removeItem( 1000 );
        clearMenu->removeItem( 1000 );
    }
#endif
    mSyncMenu->removeItem( 1002 );
    clearMenu->removeItem( 1002 );
}
void KSyncManager::slotClearMenu( int action )
{
    QString syncDevice;
    if ( action > 999 ) {
        syncDevice = mSyncProfileNames[action - 1000] ;
    }



    int result = 0;
    QString sd;
    if ( syncDevice.isEmpty() )
        sd = i18n("Do you want to\nclear all sync info\nof all profiles?");
    else
        sd = i18n("Do you want to\nclear the sync\ninfo of profile\n%1?\n"). arg( syncDevice );

    result = QMessageBox::warning( mParent, i18n("Warning!"),sd,i18n("OK"), i18n("Cancel"), 0,
                                   0, 1 );
    if ( result )
        return;
    mImplementation->removeSyncInfo( syncDevice );
}
void KSyncManager::slotSyncMenu( int action )
{
    qDebug("KSM::syncaction %d ", action);
    if ( action == 5000 )
        return;
    mSyncWithDesktop = false;
    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 ( action == 2 ) {
        enableQuick();
        QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); 
        return;
    }
    if ( action == 3 ) {
        delete mServerSocket;
        mServerSocket = 0;
        QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); 
        return;
    }

    if (blockSave())
        return;

    setBlockSave(true);
    bool silent = false;
    if ( action == 999 ) {
        //special mode for silent syncing
        action = 1000;
        silent = true;
    }

    mCurrentSyncProfile = action - 1000 ;
    mCurrentSyncDevice = mSyncProfileNames[mCurrentSyncProfile] ;
    mCurrentSyncName =  mLocalMachineName ;
    KConfig config ( locateLocal( "config","ksyncprofilesrc"  ) );
    KSyncProfile* temp = new KSyncProfile ();
    temp->setName(mSyncProfileNames[mCurrentSyncProfile]);
    temp->readConfig(&config);
    if (silent) {
        mAskForPreferences = false;
        mShowSyncSummary = false;
        mWriteBackFile = true;
        mSyncAlgoPrefs = 2;// take newest
    }
    else {
        mAskForPreferences = temp->getAskForPreferences();
        mShowSyncSummary = temp->getShowSummaryAfterSync();
        mWriteBackFile = temp->getWriteBackFile();
        mSyncAlgoPrefs = temp->getSyncPrefs();
    }
    mWriteBackExistingOnly = temp->getWriteBackExisting();
    mIsKapiFile = temp->getIsKapiFile();
    mWriteBackInFuture = 0;
    if ( temp->getWriteBackFuture() ) {
        mWriteBackInFuture =  temp->getWriteBackFutureWeeks( );
        mWriteBackInPast =  temp->getWriteBackPastWeeks( );
    }
    mFilterInCal = temp->getFilterInCal();
    mFilterOutCal = temp->getFilterOutCal();
    mFilterInAB = temp->getFilterInAB();
    mFilterOutAB = temp->getFilterOutAB();

    if ( action == 1000  ) {
        mIsKapiFile = false; 
#ifdef DESKTOP_VERSION
        syncKDE();
#else
        syncSharp();
#endif
    
    } else if ( action == 1001 ) {
        syncLocalFile();

    } else if ( action == 1002 ) {
        mWriteBackFile = false;
        mAskForPreferences = false;
        mShowSyncSummary = false; 
        mSyncAlgoPrefs = 3; 
        quickSyncLocalFile();

    } else if ( action >= 1003  ) {
        if ( temp->getIsLocalFileSync() ) {
            switch(mTargetApp)
                {
                case (KAPI):
                    if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
                        mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
                    break;
                case (KOPI):
                    if ( syncWithFile( temp->getRemoteFileName( ), false ) )
                        mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName();
                    break;
                case (PWMPI):
                    if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) )
                        mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM();
                    break;
                default:
                    qDebug("KSM::slotSyncMenu: invalid apptype selected");
                    break;
	      
                }
        } else {
            if (  temp->getIsPhoneSync() ) {
                mPhoneDevice = temp->getPhoneDevice( ) ;
                mPhoneConnection = temp->getPhoneConnection( );
                mPhoneModel = temp->getPhoneModel( );
                syncPhone();
            } else if (  temp->getIsPiSync() ) {
                if ( mTargetApp == KAPI ) {
                    mPassWordPiSync = temp->getRemotePwAB();
                    mActiveSyncPort = temp->getRemotePortAB();
                    mActiveSyncIP = temp->getRemoteIPAB();
                } else if ( mTargetApp == KOPI ) {
                    mPassWordPiSync = temp->getRemotePw();
                    mActiveSyncPort = temp->getRemotePort();
                    mActiveSyncIP = temp->getRemoteIP();
                } else  {
                    mPassWordPiSync = temp->getRemotePwPWM();
                    mActiveSyncPort = temp->getRemotePortPWM();
                    mActiveSyncIP = temp->getRemoteIPPWM();
                } 
                syncPi();
                while ( !mPisyncFinished ) {
                    //qDebug("waiting ");
                    qApp->processEvents();
                }
            } else
                syncRemote( temp );

        }
    }
    delete temp;
    setBlockSave(false);
}

void KSyncManager::enableQuick( bool ask )
{
    bool autoStart;
    bool changed = false;
    if ( ask ) {
        QDialog dia ( 0, "input-dialog", true );
        QLineEdit lab ( &dia );
        QVBoxLayout lay( &dia );
        lab.setText( mPrefs->mPassiveSyncPort );
        lay.setMargin(7);
        lay.setSpacing(7);
        int po = 9197+mTargetApp;
        QLabel label ( i18n("Port number (Default: %1)").arg(po), &dia );
        lay.addWidget( &label);
        lay.addWidget( &lab);

        QLineEdit lepw ( &dia );
        lepw.setText( mPrefs->mPassiveSyncPw );
        QLabel label2 ( i18n("Password to enable\naccess from remote:"), &dia );
        lay.addWidget( &label2);
        lay.addWidget( &lepw);
        QCheckBox autostart(i18n("Automatically start\nat application startup"), &dia );
        lay.addWidget( &autostart);
        autostart.setChecked( mPrefs->mPassiveSyncAutoStart );
#ifdef DESKTOP_VERSION
#ifdef _WIN32_
        QCheckBox syncdesktop( i18n("Automatically sync with Outlook\nwhen receiving sync request"),&dia );
        syncdesktop.hide();// not implemented!
#else
        QCheckBox syncdesktop( i18n("Automatically sync with KDE-Desktop\nwhen receiving sync request"),&dia );
#endif
        lay.addWidget( &syncdesktop);
#else
        mPrefs->mPassiveSyncWithDesktop = false;
        QCheckBox syncdesktop( i18n("Automatically sync\nwith KDE-Desktop"),&dia );
        syncdesktop.hide();
#endif
        syncdesktop.setChecked( mPrefs->mPassiveSyncWithDesktop );

        QPushButton pb ( "OK",  &dia);
        lay.addWidget( &pb );
        connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
        dia.resize( 230,120 );
        dia.setCaption( i18n("Enter port for Pi-Sync") );
        dia.show();
#ifndef DESKTOP_VERSION
        int dw = QApplication::desktop()->width();
        int dh = QApplication::desktop()->height();
        dia.move( (dw-dia.width())/2, (dh - dia.height() )/2 );
#endif
        if ( ! dia.exec() )
            return;
        dia.hide();
        qApp->processEvents();
        if ( mPrefs->mPassiveSyncPw != lepw.text() ) {
            changed = true;
            mPrefs->mPassiveSyncPw = lepw.text();
        }
        if ( mPrefs->mPassiveSyncPort != lab.text() ) {
            mPrefs->mPassiveSyncPort = lab.text();
            changed = true;
        }
        autoStart = autostart.isChecked();
        if (mPrefs->mPassiveSyncWithDesktop != syncdesktop.isChecked() ) {
            changed = true;
            mPrefs->mPassiveSyncWithDesktop = syncdesktop.isChecked();
        }
    }
    else
        autoStart = mPrefs->mPassiveSyncAutoStart;
    if ( autoStart != mPrefs->mPassiveSyncAutoStart )
        changed =  true;
    bool ok;
    mPrefs->mPassiveSyncAutoStart = false;
    Q_UINT16 port = mPrefs->mPassiveSyncPort.toUInt(&ok);
    if ( ! ok ) {
        KMessageBox::information( 0, i18n("No valid port"));
        return;
    }
    //qDebug("port %d ", port);
    mServerSocket = new KServerSocket ( mPrefs->mPassiveSyncPw, port ,1 );
    mServerSocket->setFileName( defaultFileName() );//bbb
    //qDebug("connected ");
    if ( !mServerSocket->ok() ) {
        KMessageBox::information( 0, i18n("Failed to bind or\nlisten to the port!"));
        delete mServerSocket;
        mServerSocket = 0;
        return;
    }
    mPrefs->mPassiveSyncAutoStart = autoStart;
    if ( changed ) {
        mPrefs->writeConfig();
    }
    connect( mServerSocket, SIGNAL ( request_file() ),this, SIGNAL  ( request_file() ) );
    connect( mServerSocket, SIGNAL ( file_received( bool ) ), this,  SIGNAL  ( getFile( bool ) ) );
}

void KSyncManager::syncLocalFile()
{

    QString fn =mPrefs->mLastSyncedLocalFile;
    QString ext;

    switch(mTargetApp)
        {
	    case (KAPI):
            ext = "(*.vcf)";
            break;
	    case (KOPI):
            ext = "(*.ics/*.vcs)";
            break;
	    case (PWMPI):
            ext = "(*.pwm)";
            break;
	    default:
            qDebug("KSM::syncLocalFile: invalid apptype selected");
            break;
	      
        }

    fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename"+ext), mParent );
    if ( fn == "" )
        return;
    if (  syncWithFile(  fn, false ) ) {
        qDebug("KSM::syncLocalFile() successful ");
    }

}

bool  KSyncManager::syncWithFile( QString fn , bool quick )
{
    bool ret = false;
    QFileInfo info;
    info.setFile( fn );
    QString mess;
    if ( !info. exists() ) {
        mess =  i18n( "Sync file \n...%1\ndoes not exist!\nNothing synced!\n").arg(fn.right( 30) );
        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 ( mAskForPreferences )
        if ( !edit_sync_options()) {
            mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") );
            return false;
        }
    if ( result == 0 ) {
        //qDebug("Now sycing ... ");
        if ( ret = mImplementation->sync( this, fn, mSyncAlgoPrefs ) )
            mParent->topLevelWidget()->setCaption( i18n("Synchronization successful") );
        else
            mParent->topLevelWidget()->setCaption( i18n("Sync cancelled or failed.") );
        if ( ! quick )
            mPrefs->mLastSyncedLocalFile = fn;
    }
    return ret;
}

void KSyncManager::quickSyncLocalFile()
{
    
    if ( syncWithFile( mPrefs->mLastSyncedLocalFile, true ) ) {
        qDebug("KSM::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("KDE-Pim Sync"),
                                   question,
                                   i18n("Yes"), i18n("No"),
                                   0, 0 ) != 0 ) {
        setBlockSave(false);
        mParent->topLevelWidget()->setCaption(i18n("Aborted! Nothing synced!"));
        return;
    }
    mCurrentSyncDevice = i18n("Multiple profiles") ;
    mSyncAlgoPrefs = mPrefs->mRingSyncAlgoPrefs;
    if ( askforPrefs ) {
        if ( !edit_sync_options()) {
            mParent->topLevelWidget()->setCaption( i18n("Syncing aborted.") );
            return;
        }
        mPrefs->mRingSyncAlgoPrefs = mSyncAlgoPrefs;
    }
    mParent->topLevelWidget()->setCaption(i18n("Multiple sync started.") );
    qApp->processEvents();
    int num = ringSync() ;
    if (  num > 1 )
        ringSync();
    setBlockSave(false);
    if ( num )
        emit save();
    if ( num )
        mParent->topLevelWidget()->setCaption(i18n("%1 profiles synced. Multiple sync complete!").arg(num) );
    else
        mParent->topLevelWidget()->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 = mSyncProfileNames;
    KSyncProfile* temp = new KSyncProfile ();
    mAskForPreferences = false;
    for ( i = 0; i < syncProfileNames.count(); ++i ) {
        mCurrentSyncProfile = i;
        temp->setName(syncProfileNames[mCurrentSyncProfile]);
        temp->readConfig(&config);

        bool includeInRingSync = false;
        switch(mTargetApp)
            {
            case (KAPI):
                includeInRingSync = temp->getIncludeInRingSyncAB();
                break;
            case (KOPI):
                includeInRingSync = temp->getIncludeInRingSync();
                break;
            case (PWMPI):
                includeInRingSync = temp->getIncludeInRingSyncPWM();
                break;
            default:
                qDebug("KSM::ringSync: invalid apptype selected");
                break;
	      
            }
        
	
        if ( includeInRingSync && ( i < 1 || i > 2  )) {
            mParent->topLevelWidget()->setCaption(i18n("Profile ")+syncProfileNames[mCurrentSyncProfile]+ i18n(" is synced ... "));
            ++syncedProfiles; 
            mSyncWithDesktop = false; 
            // mAskForPreferences = temp->getAskForPreferences();
            mWriteBackFile = temp->getWriteBackFile();
            mWriteBackExistingOnly = temp->getWriteBackExisting();
            mIsKapiFile = temp->getIsKapiFile();
            mWriteBackInFuture = 0;
            if ( temp->getWriteBackFuture() ) {
                mWriteBackInFuture =  temp->getWriteBackFutureWeeks( );
                mWriteBackInPast =  temp->getWriteBackPastWeeks( );
            }
            mFilterInCal = temp->getFilterInCal();
            mFilterOutCal = temp->getFilterOutCal();
            mFilterInAB = temp->getFilterInAB();
            mFilterOutAB = temp->getFilterOutAB();
            mShowSyncSummary = false;
            mCurrentSyncDevice = syncProfileNames[i] ;
            mCurrentSyncName = mLocalMachineName;
            if ( i == 0 ) {
                mIsKapiFile = false; 
#ifdef DESKTOP_VERSION
                syncKDE();
#else
                syncSharp();
#endif
            } else {
                if ( temp->getIsLocalFileSync() ) {
                    switch(mTargetApp)
                        {
                        case (KAPI):
                            if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
                                mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
                            break;
                        case (KOPI):
                            if ( syncWithFile( temp->getRemoteFileName( ), false ) )
                                mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName();
                            break;
                        case (PWMPI):
                            if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) )
                                mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM();
                            break;
                        default:
                            qDebug("KSM: invalid apptype selected");
                            break;
                        }
                } else {
                    if (  temp->getIsPhoneSync() ) {
                        mPhoneDevice = temp->getPhoneDevice( ) ;
                        mPhoneConnection = temp->getPhoneConnection( );
                        mPhoneModel = temp->getPhoneModel( );
                        syncPhone();
                    } else if (  temp->getIsPiSync() ) {
                        if ( mTargetApp == KAPI ) {
                            mPassWordPiSync = temp->getRemotePwAB();
                            mActiveSyncPort = temp->getRemotePortAB();
                            mActiveSyncIP = temp->getRemoteIPAB();
                        } else if ( mTargetApp == KOPI ) {
                            mPassWordPiSync = temp->getRemotePw();
                            mActiveSyncPort = temp->getRemotePort();
                            mActiveSyncIP = temp->getRemoteIP();
                        } else  {
                            mPassWordPiSync = temp->getRemotePwPWM();
                            mActiveSyncPort = temp->getRemotePortPWM();
                            mActiveSyncIP = temp->getRemoteIPPWM();
                        } 
                        syncPi();
                        while ( !mPisyncFinished ) {
                            //qDebug("waiting ");
                            qApp->processEvents();
                        }
                        timer.start(); 
                        while ( timer.elapsed () < 2000 ) {
                            qApp->processEvents();
                        }
                    } else
                        syncRemote( temp, false );

                }
            }
            timer.start();
            mParent->topLevelWidget()->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 preCommand;
    QString localTempFile;
    QString postCommand;

    switch(mTargetApp)
        {
        case (KAPI):
            preCommand = prof->getPreSyncCommandAB();
            postCommand = prof->getPostSyncCommandAB();
            localTempFile = prof->getLocalTempFileAB();
            break;
        case (KOPI):
            preCommand = prof->getPreSyncCommand();
            postCommand = prof->getPostSyncCommand();
            localTempFile = prof->getLocalTempFile();
            break;
        case (PWMPI):
            preCommand = prof->getPreSyncCommandPWM();
            postCommand = prof->getPostSyncCommandPWM();
            localTempFile = prof->getLocalTempFilePWM();
            break;
        default:
            qDebug("KSM::syncRemote: invalid apptype selected");
            break;
        }


    int fi;
    if ( (fi = preCommand.find("$PWD$")) > 0 ) {
        QString pwd = getPassword();
        preCommand = preCommand.left( fi )+ pwd + preCommand.mid( fi+5 );

    }
    int maxlen = 30;
    if ( QApplication::desktop()->width() > 320 )
        maxlen += 25;
    mParent->topLevelWidget()->setCaption ( i18n( "Copy remote file to local machine..." ) );
    int fileSize = 0;
    int result = system ( preCommand );
    // 0 : okay
    // 256: no such file or dir
    //
    qDebug("KSM::Sync: Remote copy result(0 = okay): %d ",result );
    if ( result != 0 ) {
        unsigned int len = maxlen;
        while ( len <  preCommand.length() ) {
            preCommand.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 (preCommand) ;
        QMessageBox::information( mParent, i18n("Sync - ERROR"),
                                  question,
                                  i18n("Okay!")) ;
        mParent->topLevelWidget()->setCaption ("KDE-Pim");
        return;
    }
    mParent->topLevelWidget()->setCaption ( i18n( "Copying succeed." ) );
    //qDebug(" file **%s** ",prof->getLocalTempFile().latin1() );

    if ( syncWithFile( localTempFile, true ) ) {

        if ( mWriteBackFile ) {
            int fi;
            if ( (fi = postCommand.find("$PWD$")) > 0 ) {
                QString pwd = getPassword();
                postCommand = postCommand.left( fi )+ pwd + postCommand.mid( fi+5 );
                
            }
            mParent->topLevelWidget()->setCaption ( i18n( "Writing back file ..." ) );
            result = system ( postCommand );
            qDebug("KSM::Sync:Writing back file result: %d ", result);
            if ( result != 0 ) {
                mParent->topLevelWidget()->setCaption ( i18n( "Writing back file result: " )+QString::number( result ) );
                return;
            } else {
                mParent->topLevelWidget()->setCaption ( i18n( "Syncronization sucessfully completed" ) );
            }
        }
    }
    return;
}
bool KSyncManager::edit_pisync_options()
{
    QDialog dia( mParent, "dia", true );
    dia.setCaption( i18n("Pi-Sync options for device: " ) +mCurrentSyncDevice );
    QVBoxLayout lay ( &dia );
    lay.setSpacing( 5 );
    lay.setMargin( 3 );
    QLabel lab1 ( i18n("Password for remote access:"), &dia); 
    lay.addWidget( &lab1 );
    QLineEdit le1 (&dia );
    lay.addWidget( &le1 );
    QLabel lab2 ( i18n("Remote IP address:"), &dia);
    lay.addWidget( &lab2 );
    QLineEdit le2 (&dia );
    lay.addWidget( &le2 );
    QLabel lab3 ( i18n("Remote port number:"), &dia);
    lay.addWidget( &lab3 );
    QLineEdit le3 (&dia );
    lay.addWidget( &le3 );
    QPushButton pb ( "OK",  &dia); 
    lay.addWidget( &pb );
    connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); 
    le1.setText( mPassWordPiSync );
    le2.setText( mActiveSyncIP  );
    le3.setText( mActiveSyncPort );
    if ( dia.exec() ) {
        mPassWordPiSync = le1.text();
        mActiveSyncPort = le3.text();
        mActiveSyncIP = le2.text();
        return true;
    }
    return false;
}
bool KSyncManager::edit_sync_options()
{

    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 ( 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() ) {
        mSyncAlgoPrefs = rem.isChecked()*1+newest.isChecked()*2+  ask.isChecked()*3+  f_loc.isChecked()*4+  f_rem.isChecked()*5;//+  both.isChecked()*6 ;
        return true;
    }
    return false;
}

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();
    QStringList oldSyncProfileNames = mSyncProfileNames;
    mSyncProfileNames = sp->getSyncProfileNames();
    mLocalMachineName = sp->getLocalMachineName ();
    int ii;
    for ( ii = 0; ii < oldSyncProfileNames.count(); ++ii ) {
        if ( ! mSyncProfileNames.contains( oldSyncProfileNames[ii] ) )
            mImplementation->removeSyncInfo( oldSyncProfileNames[ii]  );
    }
    QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); 
}
void KSyncManager::syncKDE()
{
    mSyncWithDesktop = true;
    emit save();
    switch(mTargetApp)
        {
        case (KAPI):
            {
#ifdef DESKTOP_VERSION
                QString command = qApp->applicationDirPath () + "/kdeabdump"; 
#else
                QString command = "kdeabdump"; 
#endif
                if ( ! QFile::exists ( command ) )
                    command = "kdeabdump";  
                QString fileName = QDir::homeDirPath ()+"/.kdeaddressbookdump.vcf";
                system (  command.latin1());
                    if ( syncWithFile( fileName,true ) ) {
                        if ( mWriteBackFile ) {
                            command += " --read";
                            system (  command.latin1());
                        }
                    }
                
            }
            break;
        case (KOPI):
            {
#ifdef DESKTOP_VERSION
                QString command = qApp->applicationDirPath () + "/kdecaldump"; 
#else
                QString command = "kdecaldump"; 
#endif
                if ( ! QFile::exists ( command ) )
                    command = "kdecaldump";  
                QString fileName = QDir::homeDirPath ()+"/.kdecalendardump.ics";
                system (  command.latin1());
                    if ( syncWithFile( fileName,true ) ) {
                        if ( mWriteBackFile ) {
                            command += " --read";
                            system (  command.latin1());
                        }
                    }
                
            }
            break;
        case (PWMPI):

            break;
        default:
            qDebug("KSM::slotSyncMenu: invalid apptype selected");
            break;
	      
        }
}

void KSyncManager::syncSharp()
{

    if ( ! syncExternalApplication("sharp") )
        qDebug("KSM::ERROR sync sharp  ");
}

bool KSyncManager::syncExternalApplication(QString  resource)
{
   
    emit save();

    if ( mAskForPreferences )  
        if ( !edit_sync_options()) {
            mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") );
            return false;
        }

    qDebug("KSM::Sync extern %s", resource.latin1());

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

    return syncOK;

}

void KSyncManager::syncPhone()
{

    syncExternalApplication("phone");

}

void KSyncManager::showProgressBar(int percentage, QString caption, int total)
{
    if (!bar->isVisible())
        {
            bar->setCaption (caption); 
            bar->setTotalSteps (  total  ) ;
            bar->show();
        }
    bar->raise();
    bar->setProgress( percentage );
    qApp->processEvents();
}

void KSyncManager::hideProgressBar()
{
    bar->hide();
    qApp->processEvents();
}

bool KSyncManager::isProgressBarCanceled()
{
    return !bar->isVisible();
}

QString KSyncManager::syncFileName()
{

    QString fn = "tempfile";
    switch(mTargetApp)
        {
        case (KAPI):
            fn = "tempsyncab.vcf";
            break;
        case (KOPI):
            fn = "tempsynccal.ics";
            break;
        case (PWMPI):
            fn = "tempsyncpw.pwm";
            break;
        default:
            break;
        }
#ifdef _WIN32_
    return  locateLocal( "tmp", fn );
#else
    return (QString( "/tmp/" )+ fn );
#endif
}

void KSyncManager::syncPi()
{
    mIsKapiFile = true; 
    mPisyncFinished = false;
    qApp->processEvents();
    if ( mAskForPreferences )
        if ( !edit_pisync_options()) {
            mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") );
            return;
        }
    bool ok;
    Q_UINT16 port = mActiveSyncPort.toUInt(&ok);
    if ( ! ok ) {
        mParent->topLevelWidget()->setCaption( i18n("Sorry, no valid port.Syncing cancelled.") );
        return;
    }
    KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, port, mActiveSyncIP, this, mParent->topLevelWidget() );
    connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int )), this, SLOT(deleteCommandSocket(KCommandSocket*, int)) );
    commandSocket->readFile(  syncFileName() );
}

void KSyncManager::deleteCommandSocket(KCommandSocket*s, int state)
{
    //enum { success, errorW, errorR, quiet };
    if ( state == KCommandSocket::errorR ||state == KCommandSocket::errorTO ) {
        mParent->topLevelWidget()->setCaption( i18n("ERROR: Receiving remote file failed.") );
        delete s;
        if ( state == KCommandSocket::errorR ) {
            KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this, mParent->topLevelWidget());
            connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) );
            commandSocket->sendStop();
        }
        mPisyncFinished = true;
        return;
        
    } else  if ( state == KCommandSocket::errorW ) {
        mParent->topLevelWidget()->setCaption( i18n("ERROR:Writing back file failed.") );
        mPisyncFinished = true;

    } else  if ( state == KCommandSocket::successR ) {
        QTimer::singleShot( 1, this , SLOT ( readFileFromSocket()));

    } else  if ( state == KCommandSocket::successW ) {
        mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") );
        mPisyncFinished = true;
    }

    delete s;
}

void KSyncManager::readFileFromSocket()
{
    QString fileName = syncFileName();
    mParent->topLevelWidget()->setCaption( i18n("Remote file saved to temp file.") );
    if ( ! syncWithFile( fileName , true ) ) {
        mParent->topLevelWidget()->setCaption( i18n("Syncing failed.") );
        mPisyncFinished = true;
        return;
    }
    KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this, mParent->topLevelWidget() );
    connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) );
    if ( mWriteBackFile ) 
        commandSocket->writeFile(  fileName );
    else {
        commandSocket->sendStop();
        mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") );
        mPisyncFinished = true;
    }
}

KServerSocket:: KServerSocket ( QString pw, Q_UINT16 port, int backlog, QObject * parent, const char * name ) : QServerSocket( port, backlog, parent, name )
{
    mPassWord = pw;
    mSocket = 0;
    mSyncActionDialog = 0;
    blockRC = false;
};

void KServerSocket::newConnection ( int socket ) 
{
    // qDebug("KServerSocket:New connection %d ", socket); 
    if ( mSocket ) {
        qDebug("KSS::newConnection Socket deleted! ");
        delete mSocket;
        mSocket = 0;
    }
    mSocket = new QSocket( this );
    connect( mSocket , SIGNAL(readyRead()), this, SLOT(readClient()) );
    connect( mSocket , SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) );
    mSocket->setSocket( socket );
}

void KServerSocket::discardClient()
{
    //qDebug(" KServerSocket::discardClient()");
    if ( mSocket ) {
        delete mSocket;
        mSocket = 0;
    }
    //emit endConnect();
}
void KServerSocket::readClient()
{
    if ( blockRC )
        return;
    if ( mSocket == 0 ) {
        qDebug("ERROR::KSS::readClient(): mSocket == 0  ");
        return;
    }
    //qDebug("KServerSocket::readClient()");
    if ( mSocket->canReadLine() ) {
        QString line = mSocket->readLine();
        //qDebug("KServerSocket readline: %s ", line.latin1());
        QStringList tokens = QStringList::split( QRegExp("[ \r\n][ \r\n]*"), line );
        if ( tokens[0] == "GET" ) {
            if (  tokens[1] == mPassWord ) {
                //emit sendFile( mSocket );
                bool ok = false;
                QDateTime dt = KGlobal::locale()->readDateTime( tokens[2], KLocale::ISODate, &ok);
                if ( ok ) {
                    KSyncManager::mRequestedSyncEvent = dt; 
                }
                else
                    KSyncManager::mRequestedSyncEvent = QDateTime();
                send_file();
            }
            else {
                KMessageBox::error( 0, i18n("Got send file request\nwith invalid password"));
                //qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() );
            }
        } 
        if ( tokens[0] == "PUT" ) {
            if (  tokens[1] == mPassWord ) {
                //emit getFile( mSocket );
                blockRC = true;
                get_file();
            }
            else {
                KMessageBox::error( 0, i18n("Got receive file request\nwith invalid password"));
                //qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() );
            }
        } 
        if ( tokens[0] == "STOP" ) {
            //emit endConnect();
            end_connect();
        }
    }
}
void KServerSocket::end_connect()
{
    delete mSyncActionDialog;
    mSyncActionDialog = 0;
}
void KServerSocket::send_file()
{
    //qDebug("MainWindow::sendFile(QSocket* s) ");
    if ( mSyncActionDialog )
        delete mSyncActionDialog;
    mSyncActionDialog = new QDialog ( 0, "input-dialog", true );
    mSyncActionDialog->setCaption(i18n("Received sync request"));
    QLabel* label = new QLabel( i18n("Synchronizing from remote ...\n\nDo not use this application!\n\nIf syncing fails\nyou can close this dialog."), mSyncActionDialog ); 
    label->setAlignment ( Qt::AlignHCenter );
    QVBoxLayout* lay = new QVBoxLayout( mSyncActionDialog );
    lay->addWidget( label);
    lay->setMargin(7);
    lay->setSpacing(7);
    if ( KSyncManager::mRequestedSyncEvent.isValid() ) {
        int secs = QDateTime::currentDateTime().secsTo( KSyncManager::mRequestedSyncEvent );
        if ( secs < 0 )
             secs = secs * (-1);
        if ( secs > 30 ) 
            //if ( true ) 
            {
                QString warning = i18n("Clock skew of\nsyncing devices\nis %1 seconds!").arg( secs );
                QLabel* label = new QLabel( warning, mSyncActionDialog ); 
                label->setAlignment ( Qt::AlignHCenter );
                lay->addWidget( label);
                if ( secs > 180 )
                    {
                        if ( secs > 300 ) {
                            if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(0, i18n("The clocks of the syncing\ndevices have a difference\n of more than 5 minutes.\nPlease adjust your clocks.\n<b>You may get wrong syncing results!<\b>\nPlease confirm synchronization!"), i18n("High clock skew!"),i18n("Synchronize!"))) {
                                qDebug("KSS::Sync cancelled ,cs");
                                return ;
                            }
                        }
                        QFont f = label->font();
                        f.setPointSize ( f.pointSize() *2 );
                        f. setBold (true ); 
                        QLabel* label = new QLabel( warning, mSyncActionDialog );
                        label->setFont( f ); 
                        warning = i18n("ADJUST\nYOUR\nCLOCKS!");
                        label->setText( warning ); 
                        label->setAlignment ( Qt::AlignHCenter );
                        lay->addWidget( label);
                        mSyncActionDialog->setFixedSize( 230, 300);
                    } else {
                    mSyncActionDialog->setFixedSize( 230, 200);
                }
            } else {
            mSyncActionDialog->setFixedSize( 230, 120);
        }
    } else
        mSyncActionDialog->setFixedSize( 230, 120);
    mSyncActionDialog->show();
    mSyncActionDialog->raise();
    emit request_file();
    qApp->processEvents();
    QString fileName = mFileName;
    QFile file( fileName );
    if (!file.open( IO_ReadOnly ) ) {
        delete mSyncActionDialog;
        mSyncActionDialog = 0;
        qDebug("KSS::error open sync file: %s ", fileName.latin1());
        mSocket->close();
        if ( mSocket->state() == QSocket::Idle )
            QTimer::singleShot( 10, this , SLOT ( discardClient()));
        return ;
        
    } 
    mSyncActionDialog->setCaption( i18n("Sending file...") );
    QTextStream ts( &file );
    ts.setEncoding( QTextStream::Latin1 );

    QTextStream os( mSocket );
    os.setEncoding( QTextStream::Latin1 );
    while ( ! ts.atEnd() ) {
        os << ts.readLine() << "\r\n\r\n";
    }
    //os << ts.read();
    file.close();
    mSyncActionDialog->setCaption( i18n("Waiting for synced file...") );
    mSocket->close();
    if ( mSocket->state() == QSocket::Idle )
        QTimer::singleShot( 10, this , SLOT ( discardClient()));
}
void KServerSocket::get_file()
{
    mSyncActionDialog->setCaption( i18n("Receiving synced file...") );
   
    piTime.start();
    piFileString = "";
    QTimer::singleShot( 1, this , SLOT (readBackFileFromSocket( ) ));
}


void KServerSocket::readBackFileFromSocket()
{
    //qDebug("readBackFileFromSocket() %d ", piTime.elapsed ());
    while ( mSocket->canReadLine ()  ) {
        piTime.restart();
        QString line = mSocket->readLine ();
        piFileString += line;
        //qDebug("readline: %s ", line.latin1());
        mSyncActionDialog->setCaption( i18n("Received %1 bytes").arg( piFileString.length()  ) );

    }
    if ( piTime.elapsed () < 3000 ) {
        // wait for more 
        //qDebug("waitformore ");
        QTimer::singleShot( 100, this , SLOT (readBackFileFromSocket( ) ));
        return;
    }
    QString fileName = mFileName;
    QFile file ( fileName );
    if (!file.open( IO_WriteOnly ) ) {
        delete mSyncActionDialog;
        mSyncActionDialog = 0;
        qDebug("KSS:Error open read back file ");
        piFileString = "";
        emit file_received( false );
        blockRC = false;
        return ;
                    
    } 

    // mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1));
    QTextStream ts ( &file );
    ts.setEncoding( QTextStream::Latin1 );
    mSyncActionDialog->setCaption( i18n("Writing file to disk...") );
    ts << piFileString;
    mSocket->close();
    if ( mSocket->state() == QSocket::Idle )
        QTimer::singleShot( 10, this , SLOT ( discardClient()));
    file.close(); 
    piFileString = "";
    emit file_received( true );
    delete mSyncActionDialog;
    mSyncActionDialog = 0;
    blockRC = false;

}

KCommandSocket::KCommandSocket (  QString password, Q_UINT16 port, QString host, QObject * parent, QWidget * cap,  const char * name ): QObject( parent, name )
{
    mPassWord = password;
    mSocket = 0;
    mFirst = false;
    mPort = port;
    mHost = host;
    tlw = cap;
    mRetVal = quiet;
    mTimerSocket = new QTimer ( this );
    connect( mTimerSocket, SIGNAL ( timeout () ), this, SLOT ( deleteSocket()  ) );
}
void KCommandSocket::sendFileRequest()
{
    if ( tlw )
        tlw->setCaption( i18n("Connected! Sending request for remote file ...") );
    mTimerSocket->start( 300000 );
    QTextStream os( mSocket );
    os.setEncoding( QTextStream::Latin1 );

    QString curDt = " " +KGlobal::locale()->formatDateTime(QDateTime::currentDateTime().addSecs(-1),true, true,KLocale::ISODate );
    os << "GET " << mPassWord << curDt <<"\r\n\r\n";
}

void KCommandSocket::readFile( QString fn )
{
    if ( !mSocket ) {
        mSocket = new QSocket( this );
        connect( mSocket, SIGNAL(readyRead()), this, SLOT(startReadFileFromSocket()) );
        connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
        connect( mSocket, SIGNAL(connected ()), this, SLOT(sendFileRequest() ));
    }
    mFileString = "";
    mFileName = fn;
    mFirst = true;
    if ( tlw )
        tlw->setCaption( i18n("Trying to connect to remote...") );
    mSocket->connectToHost( mHost, mPort ); 
    qDebug("KSS: Waiting for connection");
    mTimerSocket->start( 20000 );
}

void KCommandSocket::writeFile( QString fileName  )
{
    if ( !mSocket ) {
        mSocket = new QSocket( this );
        connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
        connect( mSocket, SIGNAL(connected ()), this, SLOT(writeFileToSocket()) );
    }
    mFileName = fileName ;
    mSocket->connectToHost( mHost, mPort ); 
}
void KCommandSocket::writeFileToSocket()
{
    QFile file2( mFileName );
    if (!file2.open( IO_ReadOnly ) ) {
        mRetVal= errorW;
        mSocket->close();
        if ( mSocket->state() == QSocket::Idle )
            QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
        return ;
    }  
    QTextStream ts2( &file2 );
    ts2.setEncoding( QTextStream::Latin1 );
    QTextStream os2( mSocket );
    os2.setEncoding( QTextStream::Latin1 );
    os2 << "PUT " << mPassWord << "\r\n\r\n";;
    while ( ! ts2.atEnd() ) {
        os2 << ts2.readLine() << "\r\n\r\n";
    }
    mRetVal= successW;
    file2.close();
    mSocket->close();
    if ( mSocket->state() == QSocket::Idle )
        QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
}
void KCommandSocket::sendStop()
{
    if ( !mSocket ) {
        mSocket = new QSocket( this );
        connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
    }
    mSocket->connectToHost( mHost, mPort ); 
    QTextStream os2( mSocket );
    os2.setEncoding( QTextStream::Latin1 );
    os2 << "STOP\r\n\r\n";
    mSocket->close();
    if ( mSocket->state() == QSocket::Idle )
        QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
}

void KCommandSocket::startReadFileFromSocket()
{
    if ( ! mFirst )
        return;
    mFirst = false;
    mTimerSocket->stop();
    mFileString = "";
    mTime.start();
    QTimer::singleShot( 1, this , SLOT (readFileFromSocket( ) ));

}
void KCommandSocket::readFileFromSocket()
{
    //qDebug("readBackFileFromSocket() %d ", mTime.elapsed ());
    while ( mSocket->canReadLine ()  ) {
        mTime.restart();
        QString line = mSocket->readLine ();
        mFileString += line;
        //qDebug("readline: %s ", line.latin1());
    }
    if ( mTime.elapsed () < 3000 ) {
        // wait for more 
        //qDebug("waitformore ");
        QTimer::singleShot( 100, this , SLOT (readFileFromSocket( ) ));
        return;
    }
    QString fileName = mFileName;
    QFile file ( fileName );
    if (!file.open( IO_WriteOnly ) ) {
        mFileString = "";
        mRetVal = errorR;
        qDebug("KSS:Error open temp sync file for writing: %s",fileName.latin1() );
        deleteSocket();
        return ;
                    
    } 
    // mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1));
    QTextStream ts ( &file );
    ts.setEncoding( QTextStream::Latin1 );
    ts << mFileString;
    file.close();  
    mFileString = "";
    mRetVal = successR;
    mSocket->close();
    // if state is not idle, deleteSocket(); is called via 
    //  connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
    if ( mSocket->state() == QSocket::Idle )
        deleteSocket();
}

void KCommandSocket::deleteSocket()
{
    //qDebug("KCommandSocket::deleteSocket() ");
    if ( mTimerSocket->isActive () ) {
        mTimerSocket->stop();
        mRetVal = errorTO;
        qDebug("KCS::Connection to remote host timed out");
        if ( mSocket ) {
            mSocket->close();
            //if ( mSocket->state() == QSocket::Idle )
            //   deleteSocket();
            delete mSocket;
            mSocket = 0;
        }
        KMessageBox::error( 0, i18n("Connection to remote\nhost timed out!\nDid you forgot to enable\nsyncing on remote host?"));
        emit commandFinished( this, mRetVal );
        return;      
    }
    //qDebug("KCommandSocket::deleteSocket() %d", mRetVal ); 
    if ( mSocket)
        delete mSocket;
    mSocket = 0; 
    emit commandFinished( this, mRetVal );
}