summaryrefslogtreecommitdiffstats
path: root/vcs/cvsservice/cvspartimpl.cpp
blob: f038ac565abdc05468fab70c834254ef8f9284c0 (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
/***************************************************************************
 *   Copyright (C) 2003 by Mario Scalas                                    *
 *   [email protected]                                                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <tqfile.h>
#include <tqfileinfo.h>
#include <tqdir.h>
#include<tqcheckbox.h>

#include <kapplication.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <klocale.h>
#include <kprocess.h>
#include <kstandarddirs.h>
#include <kmainwindow.h>
#include <dcopref.h>
// CvsService stuff
#include <repository_stub.h>
#include <cvsservice_stub.h>
#include <cvsjob_stub.h>
// KDevelop SDK stuff
#include <urlutil.h>
#include <kdevproject.h>
#include <kdevmainwindow.h>
#include <kdevcore.h>
#include <kdevdifffrontend.h>
#include <kdevmakefrontend.h>
#include <kdevpartcontroller.h>
// Part's widgets
#include "cvsprocesswidget.h"
#include "checkoutdialog.h"
#include "commitdlg.h"
#include "tagdialog.h"
#include "diffdialog.h"
#include "releaseinputdialog.h"
#include "cvslogdialog.h"
#include "editorsdialog.h"
#include "annotatedialog.h"

#include "changelog.h"
#include "cvsoptions.h"
#include "cvsdir.h"
#include "cvsentry.h"
#include "jobscheduler.h"
#include "cvsfileinfoprovider.h"

#include "cvspart.h"
#include "cvspartimpl.h"

///////////////////////////////////////////////////////////////////////////////
// class Constants
///////////////////////////////////////////////////////////////////////////////

// Nice name (relative to projectDirectory()) ;-)
const TQString CvsServicePartImpl::changeLogFileName( "ChangeLog" );
// Four spaces for every log line (except the first, which includes the
// developers name)
const TQString CvsServicePartImpl::changeLogPrependString( "    " );

///////////////////////////////////////////////////////////////////////////////
// class CvsServicePartImpl
///////////////////////////////////////////////////////////////////////////////

CvsServicePartImpl::CvsServicePartImpl( CvsServicePart *part, const char *name )
    : TQObject( this, name? name : "cvspartimpl" ),
    m_scheduler( 0 ), m_part( part ), m_widget( 0 )
{
    if (requestCvsService())
    {
        m_widget = new CvsProcessWidget( m_cvsService, part, 0, "cvsprocesswidget" );
        m_scheduler = new DirectScheduler( m_widget );
        m_fileInfoProvider = new CVSFileInfoProvider( part, m_cvsService );
    
        connect( core(), TQT_SIGNAL(projectOpened()), this, TQT_SLOT(slotProjectOpened()) );
    }
    else
    {
        kdDebug(9006) << "CvsServicePartImpl::CvsServicePartImpl(): somebody kills me because"
            "I could not request a valid CvsService!!!! :-((( " << endl;
    }

}

///////////////////////////////////////////////////////////////////////////////

CvsServicePartImpl::~CvsServicePartImpl()
{
    if (processWidget())
    {
        // Inform toplevel, that the output view is gone
        mainWindow()->removeView( m_widget );
        delete m_widget;
    }
    delete m_scheduler;
    //delete m_fileInfoProvider;
    releaseCvsService();
}

///////////////////////////////////////////////////////////////////////////////

bool CvsServicePartImpl::prepareOperation( const KURL::List &someUrls, CvsOperation op )
{
    kdDebug(9006) << k_funcinfo << endl;

    bool correctlySetup = (m_cvsService != 0) && (m_repository != 0);
    if (!correctlySetup)
    {
        kdDebug(9006) << "DCOP CvsService is not available!!!" << endl;
        return false;
    }

    KURL::List urls = someUrls;
    URLUtil::dump( urls, "Requested CVS operation for: " );

    if (!m_part->project())
    {
        kdDebug(9006) << k_funcinfo << "No project???" << endl;
        KMessageBox::sorry( 0, i18n("Open a project first.\nOperation will be aborted.") );
        return false;
    }

    if (m_widget->isAlreadyWorking())
    {
        if (KMessageBox::warningYesNo( 0,
            i18n("Another CVS operation is executing: do you want to cancel it \n"
                "and start this new one?"),
            i18n("CVS: Operation Already Pending ")) == KMessageBox::Yes)
        {
            m_widget->cancelJob();
        }
        else // Operation canceled
        {
            kdDebug(9006) << k_funcinfo << "Operation canceled by user request" << endl;
            return false;
        }
    }

    validateURLs( projectDirectory(),  urls, op );
    if (urls.count() <= 0) // who knows? ;)
    {
        kdDebug(9006) << "CvsServicePartImpl::prepareOperation(): No valid document URL selected!!!" << endl;
        KMessageBox::sorry( 0, i18n("None of the file(s) you selected seem to be valid for repository.") );
        return false;
    }

    URLUtil::dump( urls );
    // Save for later use
    m_urlList = urls;
    m_lastOperation = op;

    return true;
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::doneOperation( const KURL::List &/*someUrls*/, CvsOperation /*op*/ )
{
    kdDebug(9006) << k_funcinfo << endl;

    // @ todo notify clients (filetree) about changed status?)
}

///////////////////////////////////////////////////////////////////////////////

const KURL::List &CvsServicePartImpl::urlList() const
{
    return m_urlList;
}

///////////////////////////////////////////////////////////////////////////////

TQStringList CvsServicePartImpl::fileList( bool relativeToProjectDir ) const
{
    if (relativeToProjectDir)
        return URLUtil::toRelativePaths( projectDirectory(), urlList() );
    else
        return urlList().toStringList();
}

///////////////////////////////////////////////////////////////////////////////

bool CvsServicePartImpl::isRegisteredInRepository( const TQString &projectDirectory, const KURL &url )
{
    kdDebug(9006) << k_funcinfo << endl;

    // KURL::directory() is a bit tricky when used on file or _dir_ paths ;-)
    KURL projectURL = KURL::fromPathOrURL( projectDirectory );
    kdDebug(9006) << k_funcinfo << "projectURL = " << projectURL.url() << endl;
    kdDebug(9006) << k_funcinfo << "url        = " << url.url() << endl;

    if ( projectURL == url)
    {
        CVSDir cvsdir = CVSDir( projectDirectory );
        return cvsdir.isValid();
    }
    else
    {
        CVSDir cvsdir = CVSDir( url.directory() );

        if (!cvsdir.isValid())
        {
            kdDebug(9006) << k_funcinfo << " Error: " << cvsdir.path() << " is not a valid CVS directory " << endl;
            return false;
        }
        CVSEntry entry = cvsdir.filetqStatus( url.fileName() );
        return entry.isValid();
    }
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::validateURLs( const TQString &projectDirectory, KURL::List &urls, CvsOperation op )
{
    kdDebug(9006) << k_funcinfo << endl;

    // If files are to be added, we can avoid to check them to see if they are registered in the
    // repository ;)
    if (op == opAdd)
    {
        kdDebug(9006) << "This is a Cvs Add operation and will not be checked against repository ;-)" << endl;
        return;
    }
    TQValueList<KURL>::iterator it = urls.begin();
    while (it != urls.end())
    {
        if (!CvsServicePartImpl::isRegisteredInRepository( projectDirectory, (*it) ))
        {
            kdDebug(9006) << "Warning: file " << (*it).path() << " does NOT belong to repository and will not be used" << endl;

            it = urls.erase( it );
        }
        else
        {
            kdDebug(9006) << "Warning: file " << (*it).path() << " is in repository and will be accepted" << endl;

            ++it;
        }
    }
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::addToIgnoreList( const TQString &projectDirectory, const KURL &url )
{
    kdDebug(9006) << k_funcinfo << endl;

    if ( url.path() == projectDirectory )
    {
        kdDebug(9006) << "Can't add to ignore list current project directory " << endl;
        return;
    }

    CVSDir cvsdir( url.directory() );
    cvsdir.ignoreFile( url.fileName() );
}

void CvsServicePartImpl::addToIgnoreList( const TQString &projectDirectory, const KURL::List &urls )
{
    for (size_t i=0; i<urls.count(); ++i)
    {
        addToIgnoreList( projectDirectory, urls[i] );
    }
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::removeFromIgnoreList( const TQString &/*projectDirectory*/, const KURL &url )
{
    kdDebug(9006) << k_funcinfo << endl;

    TQStringList ignoreLines;

    CVSDir cvsdir( url.directory() );
    cvsdir.doNotIgnoreFile( url.fileName() );
}

void CvsServicePartImpl::removeFromIgnoreList( const TQString &projectDirectory, const KURL::List &urls )
{
    for (size_t i=0; i<urls.count(); ++i)
    {
        removeFromIgnoreList( projectDirectory, urls[i] );
    }
}

///////////////////////////////////////////////////////////////////////////////

bool CvsServicePartImpl::isValidDirectory( const TQDir &dir ) const
{
    CVSDir cvsdir( dir );

    return cvsdir.isValid();
}

///////////////////////////////////////////////////////////////////////////////

CvsProcessWidget *CvsServicePartImpl::processWidget() const
{
    return m_widget;
}

///////////////////////////////////////////////////////////////////////////////

KDevMainWindow *CvsServicePartImpl::mainWindow() const
{
    return m_part->mainWindow();
}

///////////////////////////////////////////////////////////////////////////////

TQString CvsServicePartImpl::projectDirectory() const
{
    return m_part->project() ? m_part->project()->projectDirectory() : TQString();
}

///////////////////////////////////////////////////////////////////////////////

KDevCore *CvsServicePartImpl::core() const
{
    return m_part->core();
}

///////////////////////////////////////////////////////////////////////////////

KDevDiffFrontend *CvsServicePartImpl::diffFrontend() const
{
    return m_part->extension<KDevDiffFrontend>("KDevelop/DiffFrontend");
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::login()
{
    DCOPRef job = m_cvsService->login( this->projectDirectory() );

    m_scheduler->schedule( job );
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::logout()
{
    DCOPRef job = m_cvsService->logout( this->projectDirectory() );

    m_scheduler->schedule( job );
}

///////////////////////////////////////////////////////////////////////////////

bool CvsServicePartImpl::checkout()
{
    kdDebug(9006) << k_funcinfo << endl;

    CheckoutDialog dlg( m_cvsService, mainWindow()->main()->centralWidget() );

    if ( dlg.exec() == TQDialog::Accepted )
    {
        DCOPRef job = m_cvsService->checkout( dlg.workDir(), dlg.serverPath(),
            dlg.module(), dlg.tag(), dlg.pruneDirs(), "", false
        );
        if (!m_cvsService->ok()) {
            KMessageBox::sorry( mainWindow()->main(), i18n( "Unable to checkout" ) );
        } else {
        	// Save the path for later retrieval since slotCheckoutFinished(bool,int)
        	// will use it for return the info to the caller.
			modulePath = dlg.workDir() + dlg.module();

        	m_scheduler->schedule( job );
        	connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotCheckoutFinished(bool,int)) );
			return true;
		}
    }
	return false;
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::commit( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;
    kdDebug(9006) << "Commit requested for " << urlList.count() << " file(s)." << endl;

    if (!prepareOperation( urlList, opCommit ))
        return;

    CommitDialog dlg( projectDirectory() + "/ChangeLog" );
    if (dlg.exec() == TQDialog::Rejected)
        return;

    CvsOptions *options = CvsOptions::instance();
    TQString logString = dlg.logMessage().join( "\n" );

    DCOPRef cvsJob = m_cvsService->commit( fileList(), logString, options->recursiveWhenCommitRemove() );
    if (!m_cvsService->ok())
    {
        kdDebug( 9006 ) << "Commit of " << fileList().join( ", " ) << " failed!!!" << endl;
        return;
    }

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotJobFinished(bool,int)) );

    // 2. if requested to do so, add an entry to the Changelog too
    if (dlg.mustAddToChangeLog())
    {
        // 2.1 Modify the Changelog
        ChangeLogEntry entry;
        entry.addLines( dlg.logMessage() );
        entry.addToLog( dlg.changeLogFileName() );

        kdDebug( 9006 ) << " *** ChangeLog entry : " <<
            entry.toString( changeLogPrependString ) << endl;
    }

    doneOperation( KURL::List( fileList() ), opCommit );
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::update( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opCommit ))
        return;

    CvsOptions *options = CvsOptions::instance();
    ReleaseInputDialog dlg( mainWindow()->main()->centralWidget() );
    if (dlg.exec() == TQDialog::Rejected)
        return;

    TQString additionalOptions = dlg.release();
    if (dlg.isRevert())
        additionalOptions = additionalOptions + " " + options->revertOptions();

    DCOPRef cvsJob = m_cvsService->update( fileList(),
        options->recursiveWhenUpdate(),
        options->createDirsWhenUpdate(),
        options->pruneEmptyDirsWhenUpdate(),
        additionalOptions );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::add( const KURL::List& urlList, bool binary )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opAdd ))
        return;

    DCOPRef cvsJob = m_cvsService->add( fileList(), binary );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::annotate( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opAnnotate ))
        return;

    //get the directory of the file we want to annotate
    TQString tagFilename = URLUtil::directory(projectDirectory()+"/"+fileList()[0]);
    //CVS stores tag information in the ./CVS/Tag file
    tagFilename += "/CVS/Tag";


    //Check if such a Tag file exists, and try to read the tag/branch from it
    TQFile fileTag(tagFilename);
    TQString strRev = "";  //default revision is empty ...
    if (fileTag.exists()) { //... but if there is a Tag file, we get the revision from there
        if ( fileTag.open( IO_ReadOnly ) ) {
            TQTextStream stream( &fileTag );
            TQString line;
            line = stream.readLine();
            if (line.startsWith("T")) { //the line always starts with a "T"...
                strRev = line.right(line.length()-1); //...and after this there is the tag name
                kdDebug(9006) << "The found revision is:  >>" << strRev << "<<" <<endl;
            }
            fileTag.close();
        }
    }
    
    AnnotateDialog * f = new AnnotateDialog( m_cvsService );
    f->show();
    //the dialog will do all the work, just give him the file and the revision to start with
    f->startFirstAnnotate( fileList()[0], strRev );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::unedit( const KURL::List& urlList)
{
    kdDebug(9006) << k_funcinfo << endl;

    int s = KMessageBox::questionYesNo( 0,
        i18n("Do you really want to unedit the selected files?"),
        i18n("CVS - Unedit Files"),
        i18n("Unedit"),
        i18n("Do Not Unedit"),
        "askUneditingFiles" );
    if (s == KMessageBox::No) {
        return;
    }

    if (!prepareOperation( urlList, opUnEdit ))
        return;

    DCOPRef cvsJob = m_cvsService->unedit( fileList() );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::edit( const KURL::List& urlList)
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opEdit ))
        return;

    DCOPRef cvsJob = m_cvsService->edit( fileList() );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::editors( const KURL::List& urlList)
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opEditors ))
        return;

    EditorsDialog * f = new EditorsDialog( m_cvsService );
    f->show();
    //the dialog will do all the work
    f->startjob( fileList()[0] );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::remove( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opRemove ))
        return;

    DCOPRef cvsJob = m_cvsService->remove( fileList(), true );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)),
        this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::removeStickyFlag( const KURL::List& urlList )
{
	kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opUpdate ))
        return;

    CvsOptions *options = CvsOptions::instance();

    DCOPRef cvsJob = m_cvsService->update( fileList(),
        options->recursiveWhenUpdate(),
        options->createDirsWhenUpdate(),
        options->pruneEmptyDirsWhenUpdate(),
        "-A" );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)),
        this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::log( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opLog ))
        return;

    CVSLogDialog* f = new CVSLogDialog( m_cvsService );
    f->show();
    // Form will do all the work
    f->startLog( projectDirectory(), fileList()[0] );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::diff( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opDiff ))
        return;
    
    CVSDir cvsdir = CVSDir( urlList[0].directory() );
    CVSEntry entry = cvsdir.filetqStatus( urlList[0].fileName() );

    DiffDialog dlg(entry);
    if (dlg.exec() != TQDialog::Accepted)
        return;

    CvsOptions *options = CvsOptions::instance();
    DCOPRef cvsJob = m_cvsService->diff( fileList()[0], dlg.revA(),
                dlg.revB(), options->diffOptions(), options->contextLines() );
    if (!m_cvsService->ok())
    {
        KMessageBox::sorry( 0, i18n("Sorry, cannot diff."),
            i18n("Error During Diff") );
        return;
    }

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)),
        this, TQT_SLOT(slotDiffFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::tag( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opTag ))
        return;

    TagDialog dlg( i18n("Creating Tag/Branch for files ..."),
        mainWindow()->main()->centralWidget() );
    if (dlg.exec() != TQDialog::Accepted)
        return;

    DCOPRef cvsJob = m_cvsService->createTag( fileList(), dlg.tagName(),
        dlg.isBranch(), dlg.force() );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)),
        this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::unTag( const KURL::List& urlList )
{
    kdDebug(9006) << k_funcinfo << endl;

    if (!prepareOperation( urlList, opUnTag ))
        return;

    TagDialog dlg( i18n("Removing Tag from files ..."),
        mainWindow()->main()->centralWidget() );
    dlg.tagAsBranchCheck->hide();
    if (dlg.exec() != TQDialog::Accepted)
        return;

    DCOPRef cvsJob = m_cvsService->deleteTag( fileList(), dlg.tagName(),
        dlg.isBranch(), dlg.force() );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)),
        this, TQT_SLOT(slotJobFinished(bool,int)) );

    doneOperation();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::addToIgnoreList( const KURL::List& urlList )
{
    addToIgnoreList( projectDirectory(), urlList );
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::removeFromIgnoreList( const KURL::List& urlList )
{
    removeFromIgnoreList( projectDirectory(), urlList );
}

///////////////////////////////////////////////////////////////////////////////

/**
* \FIXME Current implementation doesn't use CvsService :-( I just ported the
* old code which relies on buildcvs.sh script. [marios]
*/
void CvsServicePartImpl::createNewProject( const TQString &dirName,
    const TQString &cvsRsh, const TQString &location,
    const TQString &message, const TQString &module, const TQString &vendor,
    const TQString &release, bool mustInitRoot )
{
    kdDebug( 9006 ) << "====> CvsServicePartImpl::createNewProject( const TQString& )" << endl;

    CvsOptions *options = CvsOptions::instance();
    options->setCvsRshEnvVar( cvsRsh );
    options->setLocation( location );
/*
	//virtual DCOPRef import( const TQString& workingDir, const TQString& repository, const TQString& module, const TQString& ignoreList, const TQString& comment, const
    TQString filesToIgnore;
	DCOPRef cvsJob = m_cvsService->import( dirName, location, module, filesToIgnore, message, vendor, release, false );

    m_scheduler->schedule( cvsJob );
    connect( processWidget(), TQT_SIGNAL(jobFinished(bool,int)), this, TQT_SLOT(slotCheckoutFinished(bool,int)) );
*/
	TQString rsh_preamble;
    if ( !options->cvsRshEnvVar().isEmpty() )
        rsh_preamble = "CVS_RSH=" + KShellProcess::quote( options->cvsRshEnvVar() );

    TQString init;
    if (mustInitRoot)
    {
        init = rsh_preamble + " cvs -d " + KShellProcess::quote( options->location() ) + " init && ";
    }
    TQString cmdLine = init + "cd " + KShellProcess::quote(dirName) +
        " && " + rsh_preamble +
        " cvs -d " + KShellProcess::quote(options->location()) +
        " import -m " + KShellProcess::quote(message) + " " +
        KShellProcess::quote(module) + " " +
        KShellProcess::quote(vendor) + " " +
        KShellProcess::quote(release) +
        // CVS build-up magic here ...
        " && sh " +
        locate("data","kdevcvsservice/buildcvs.sh") + " . " +
        KShellProcess::quote(module) + " " +
        KShellProcess::quote(location);

    kdDebug( 9006 ) << "  ** Will run the following command: " << endl << cmdLine << endl;
    kdDebug( 9006 ) << "  ** on directory: " << dirName << endl;

    if (KDevMakeFrontend *makeFrontend = m_part->extension<KDevMakeFrontend>("KDevelop/MakeFrontend"))
        makeFrontend->queueCommand( dirName, cmdLine );
}

///////////////////////////////////////////////////////////////////////////////

bool CvsServicePartImpl::requestCvsService()
{
    TQCString appId;
    TQString error;

    if (KApplication::startServiceByDesktopName( "cvsservice",
        TQStringList(), &error, &appId ))
    {
        TQString msg = i18n( "Unable to find the Cervisia KPart. \n"
            "Cervisia Integration will not be available. Please check your\n"
            "Cervisia installation and re-try. Reason was:\n" ) + error;
        KMessageBox::error( processWidget(), msg, "DCOP Error" );

        return false;
    }
    else
    {
        m_cvsService = new CvsService_stub( appId, "CvsService" );
        m_repository = new Repository_stub( appId, "CvsRepository" );
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::releaseCvsService()
{
    if (m_cvsService)
        m_cvsService->quit();
    delete m_cvsService;
    m_cvsService = 0;
    delete m_repository;
    m_repository = 0;
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::flushJobs()
{
    processWidget()->cancelJob();
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::addFilesToProject( const TQStringList &filesToAdd )
{
    kdDebug( 9006 ) << k_funcinfo << " " << filesToAdd << endl;

    TQStringList filesInCVS = checkFileListAgainstCVS( filesToAdd );
    if (filesInCVS.isEmpty())
        return;

    kdDebug( 9006 ) << k_funcinfo << " " << filesInCVS << endl;

    int s = KMessageBox::questionYesNo( 0,
        i18n("Do you want the files to be added to CVS repository too?"),
        i18n("CVS - New Files Added to Project"),
        KStdGuiItem::add(),
        i18n("Do Not Add"),
        i18n("askWhenAddingNewFiles") );
    if (s == KMessageBox::Yes)
    {
        kdDebug( 9006 ) << "Adding these files: " << filesInCVS.join( ", " ) << endl;

        const KURL::List urls = KURL::List( filesInCVS );
        URLUtil::dump( urls );
        add( urls );
    }
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::removedFilesFromProject(const TQStringList &filesToRemove)
{
    kdDebug( 9006 ) << k_funcinfo << endl;

    TQStringList filesInCVS = checkFileListAgainstCVS( filesToRemove );
    if (filesInCVS.isEmpty())
        return;

    int s = KMessageBox::warningContinueCancel( 0,
        i18n("Do you want them to be removed from CVS repository too?\nWarning: They will be removed from disk too."),
        i18n("CVS - Files Removed From Project"),
        KStdGuiItem::del(),
        i18n("askWhenRemovingFiles") );

    if (s == KMessageBox::Continue)
    {
        kdDebug( 9006 ) << "Removing these files: " << filesInCVS.join( ", " ) << endl;
        const KURL::List urls = KURL::List( filesInCVS );
        URLUtil::dump( urls );
        remove( urls );
    }
}

///////////////////////////////////////////////////////////////////////////////

TQStringList CvsServicePartImpl::checkFileListAgainstCVS( const TQStringList &filesToCheck ) const
{
    TQStringList filesInCVS;
    for (TQStringList::const_iterator it = filesToCheck.begin(); it != filesToCheck.end(); ++it )
    {
        const TQString &fn = (*it);
        TQFileInfo fi( fn );
        if (fi.isRelative())
            fi = projectDirectory() + TQDir::separator() + fn;
        if (isValidDirectory( fi.dirPath( true ) ))
            filesInCVS += ( fi.filePath() );
    }

    return filesInCVS;
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::emitFileStateModified( const KURL::List &/*urls*/, VCSFileInfo::FileState &/*commonState*/ )
{
}

///////////////////////////////////////////////////////////////////////////////

KDevVCSFileInfoProvider *CvsServicePartImpl::fileInfoProvider() const
{
    return m_fileInfoProvider;
}

///////////////////////////////////////////////////////////////////////////////
// SLOTS here!
///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::slotDiffFinished( bool normalExit, int exitStatus )
{
    core()->running( m_part, false );

    TQString diff = processWidget()->output().join("\n"),
        err = processWidget()->errors().join("\n");

    kdDebug( 9006 ) << "diff = " << diff << endl;
    kdDebug( 9006 ) << "err = " << err << endl;

    if (normalExit)
        kdDebug( 9006 ) << " *** Process died nicely with exit status = " <<
            exitStatus << endl;
    else
        kdDebug( 9999 ) << " *** Process was killed with exit status = " <<
            exitStatus << endl;

    // Now show a message about operation ending status
    if (diff.isEmpty() && (exitStatus != 0))
    {
        KMessageBox::information( 0, i18n("Operation aborted (process killed)."),
            i18n("CVS Diff") );
        return;
    }
    if ( diff.isEmpty() && !err.isEmpty() )
    {
        KMessageBox::detailedError( 0, i18n("CVS outputted errors during diff."),
            err, i18n("Errors During Diff") );
        return;
    }

    if ( !err.isEmpty() )
    {
        int s = KMessageBox::warningContinueCancelList( 0,
            i18n("CVS output errors during diff. Do you still want to continue?"),
            TQStringList::split( "\n", err, false ), i18n("Errors During Diff")
        );
        if ( s != KMessageBox::Continue )
            return;
    }

    if ( diff.isEmpty() )
    {
        KMessageBox::information( 0, i18n("There is no difference to the repository."),
            i18n("No Difference Found") );
        return;
    }

    Q_ASSERT( diffFrontend() );
    diffFrontend()->showDiff( diff );
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::slotCheckoutFinished( bool exitStatus, int )
{
    kdDebug(9006) << "CvsServicePartImpl::slotCheckoutFinished(): job ended with status == "
        << exitStatus << endl;
    // Return a null string if the operation was not succesfull
    if (!exitStatus)
        modulePath = TQString();

    kdDebug(9006) << "   I'll emit modulePath == " << modulePath << endl;

    emit checkoutFinished( modulePath );
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::slotJobFinished( bool /*exitStatus*/, int exitCode )
{
    // Return a null string if the operation was not succesfull
    kdDebug(9006) << "CvsServicePartImpl::slotJobFinished(): job ended with code == "
        << exitCode << endl;
/*
    // Operation has been successfull
    if (!exitStatus)
        return;

    // 1. Assemble the CVSFileInfoList
    // 2. notify all clients
*/
}

///////////////////////////////////////////////////////////////////////////////

void CvsServicePartImpl::slotProjectOpened()
{
    kdDebug(9006) << "CvsServicePartImpl::slotProjectOpened(): setting work directory to "
        << projectDirectory() << endl;

    if ( m_repository )
    {
        m_repository->setWorkingCopy( projectDirectory() );
    }
}


#include "cvspartimpl.moc"