summaryrefslogtreecommitdiffstats
path: root/cervisia/resolvedlg.cpp
blob: 5bf34db3050708612584f525df85b8b230f798c7 (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
/*
 *  Copyright (C) 1999-2002 Bernd Gehrmann
 *                          bernd@mail.berlios.de
 *  Copyright (c) 2003-2004 Christian Loose <christian.loose@hamburg.de>
 *
 * 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */


#include "resolvedlg.h"

#include <tqfile.h>
#include <tqkeycode.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqtextcodec.h>
#include <tqtextstream.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <tqregexp.h>
#include "misc.h"
#include "resolvedlg_p.h"
using Cervisia::ResolveEditorDialog;


// *UGLY HACK*
// The following conditions are a rough hack
static TQTextCodec *DetectCodec(const TQString &fileName)
{
    if (fileName.endsWith(".ui") || fileName.endsWith(".docbook")
        || fileName.endsWith(".xml"))
        return TQTextCodec::codecForName("utf8");

    return TQTextCodec::codecForLocale();
}


namespace
{

class LineSeparator
{
public:
    LineSeparator(const TQString& text)
        : m_text(text)
        , m_startPos(0)
        , m_endPos(0)
    {
    }
    
    TQString nextLine() const
    {
        // already reach end of text on previous call
        if( m_endPos < 0 )
        {
            m_currentLine = TQString();
            return m_currentLine;
        }
        
        m_endPos = m_text.tqfind('\n', m_startPos);
        
        int length    = m_endPos - m_startPos + 1;
        m_currentLine = m_text.mid(m_startPos, length);
        m_startPos    = m_endPos + 1;
        
        return m_currentLine;
    }
    
    bool atEnd() const
    {
        return (m_endPos < 0 && m_currentLine.isEmpty());
    }
    
private:
    const TQString    m_text;
    mutable TQString  m_currentLine;
    mutable int      m_startPos, m_endPos;
};

}


ResolveDialog::ResolveDialog(KConfig& cfg, TQWidget *tqparent, const char *name)
    : KDialogBase(tqparent, name, false, TQString(),
                  Close | Help | User1 | User2, Close, true,
                  KStdGuiItem::saveAs(), KStdGuiItem::save())
    , markeditem(-1)
    , partConfig(cfg)
{
    items.setAutoDelete(true);

    TQFrame* mainWidget = makeMainWidget();

    TQBoxLayout *tqlayout = new TQVBoxLayout(mainWidget, 0, spacingHint());

    TQSplitter *vertSplitter = new TQSplitter(Qt::Vertical, mainWidget);

    TQSplitter *splitter = new TQSplitter(Qt::Horizontal, vertSplitter);

    TQWidget *versionALayoutWidget = new TQWidget(splitter);
    TQBoxLayout *versionAtqlayout = new TQVBoxLayout(versionALayoutWidget, 5);

    TQLabel *revlabel1 = new TQLabel(i18n("Your version (A):"), versionALayoutWidget);
    versionAtqlayout->addWidget(revlabel1);
    diff1 = new DiffView(cfg, true, false, versionALayoutWidget);
    versionAtqlayout->addWidget(diff1, 10);

    TQWidget* versionBLayoutWidget = new TQWidget(splitter);
    TQBoxLayout *versionBtqlayout = new TQVBoxLayout(versionBLayoutWidget, 5);

    TQLabel *revlabel2 = new TQLabel(i18n("Other version (B):"), versionBLayoutWidget);
    versionBtqlayout->addWidget(revlabel2);
    diff2 = new DiffView(cfg, true, false, versionBLayoutWidget);
    versionBtqlayout->addWidget(diff2, 10);

    diff1->setPartner(diff2);
    diff2->setPartner(diff1);

    TQWidget* mergeLayoutWidget = new TQWidget(vertSplitter);
    TQBoxLayout *mergeLayout = new TQVBoxLayout(mergeLayoutWidget, 5);

    TQLabel *mergelabel = new TQLabel(i18n("Merged version:"), mergeLayoutWidget);
    mergeLayout->addWidget(mergelabel);

    merge = new DiffView(cfg, false, false, mergeLayoutWidget);
    mergeLayout->addWidget(merge, 10);

    tqlayout->addWidget(vertSplitter);

    abutton = new TQPushButton("&A", mainWidget);
    connect( abutton, TQT_SIGNAL(clicked()), TQT_SLOT(aClicked()) );

    bbutton = new TQPushButton("&B", mainWidget);
    connect( bbutton, TQT_SIGNAL(clicked()), TQT_SLOT(bClicked()) );

    abbutton = new TQPushButton("A+B", mainWidget);
    connect( abbutton, TQT_SIGNAL(clicked()), TQT_SLOT(abClicked()) );

    babutton = new TQPushButton("B+A", mainWidget);
    connect( babutton, TQT_SIGNAL(clicked()), TQT_SLOT(baClicked()) );

    editbutton = new TQPushButton(i18n("&Edit"), mainWidget);
    connect( editbutton, TQT_SIGNAL(clicked()), TQT_SLOT(editClicked()) );

    nofnlabel = new TQLabel(mainWidget);
    nofnlabel->tqsetAlignment(AlignCenter);

    backbutton = new TQPushButton("&<<", mainWidget);
    connect( backbutton, TQT_SIGNAL(clicked()), TQT_SLOT(backClicked()) );

    forwbutton = new TQPushButton("&>>", mainWidget);
    connect( forwbutton, TQT_SIGNAL(clicked()), TQT_SLOT(forwClicked()) );

    TQBoxLayout *buttontqlayout = new TQHBoxLayout(tqlayout);
    buttontqlayout->addWidget(abutton, 1);
    buttontqlayout->addWidget(bbutton, 1);
    buttontqlayout->addWidget(abbutton, 1);
    buttontqlayout->addWidget(babutton, 1);
    buttontqlayout->addWidget(editbutton, 1);
    buttontqlayout->addStretch(1);
    buttontqlayout->addWidget(nofnlabel, 2);
    buttontqlayout->addStretch(1);
    buttontqlayout->addWidget(backbutton, 1);
    buttontqlayout->addWidget(forwbutton, 1);

    connect( this, TQT_SIGNAL(user2Clicked()), TQT_SLOT(saveClicked()) );
    connect( this, TQT_SIGNAL(user1Clicked()), TQT_SLOT(saveAsClicked()) );

    TQFontMetrics const fm(fontMetrics());
    setMinimumSize(fm.width('0') * 120,
                   fm.lineSpacing() * 40);

    setHelp("resolvingconflicts");

    setWFlags(TQt::WDestructiveClose | getWFlags());

    TQSize size = configDialogSize(partConfig, "ResolveDialog");
    resize(size);
}


ResolveDialog::~ResolveDialog()
{
    saveDialogSize(partConfig, "ResolveDialog");
}


// One resolve item has a line number range of linenoA:linenoA+linecountA-1
// in A and linenoB:linenoB+linecountB-1 in B. If the user has chosen version A
// for the merged file (indicated by chosenA==true), then the line number
// range in the merged file is offsetM:offsetM+linecountA-1 (accordingly for
// the other case).
class ResolveItem
{
public:
    int linenoA, linecountA;
    int linenoB, linecountB;
    int linecountTotal;
    int offsetM;
    ResolveDialog::ChooseType chosen;
};


bool ResolveDialog::parseFile(const TQString &name)
{
    int lineno1, lineno2;
    int advanced1, advanced2;
    enum { Normal, VersionA, VersionB } state;

    setCaption(i18n("CVS Resolve: %1").tqarg(name));

    fname = name;
  
    TQString fileContent = readFile();
    if( fileContent.isNull() )
        return false;
        
    LineSeparator separator(fileContent);

    state = Normal;
    lineno1 = lineno2 = 0;
    advanced1 = advanced2 = 0;
    do
    {
        TQString line = separator.nextLine();
        
        // reached end of file?
        if( separator.atEnd() )
            break;
            
        switch( state )
        {
            case Normal:
                {
                    // check for start of conflict block
                    // Set to look for <<<<<<< at begining of line with exaclty one
                    // space after then anything after that.
                    TQRegExp rx( "^<{7}\\s.*$" ); 
                    int separatorPos = rx.search(line);
                    if( separatorPos >= 0 )
                    {
                        state     = VersionA;
                        advanced1 = 0;
                    }
                    else
                    {
                        addToMergeAndVersionA(line, DiffView::Unchanged, lineno1);
                        addToVersionB(line, DiffView::Unchanged, lineno2);
                    }
                }
                break;
            case VersionA:
                {
                    // Set to look for ======= at begining of line which may have one
                    // or more spaces after then nothing else.
                    TQRegExp rx( "^={7}\\s*$" );
                    int separatorPos = rx.search(line);
                    if( separatorPos < 0 )    // still in version A
                    {
                        advanced1++;
                        addToMergeAndVersionA(line, DiffView::Change, lineno1);
                    }
                    else
                    {
                        state     = VersionB;
                        advanced2 = 0;
                    }
                }
                break;
            case VersionB:
                {
                    // Set to look for >>>>>>> at begining of line with exaclty one
                    // space after then anything after that.
                    TQRegExp rx( "^>{7}\\s.*$" );
                    int separatorPos = rx.search(line);
                    if( separatorPos < 0 )    // still in version B
                    {
                        advanced2++;
                        addToVersionB(line, DiffView::Change, lineno2);
                    }
                    else
                    {
                        // create an resolve item
                        ResolveItem *item = new ResolveItem;
                        item->linenoA        = lineno1-advanced1+1;
                        item->linecountA     = advanced1;
                        item->linenoB        = lineno2-advanced2+1;
                        item->linecountB     = advanced2;
                        item->offsetM        = item->linenoA-1;
                        item->chosen         = ChA;
                        item->linecountTotal = item->linecountA;
                        items.append(item);
                        
                        for (; advanced1 < advanced2; advanced1++)
                            diff1->addLine("", DiffView::Neutral);
                        for (; advanced2 < advanced1; advanced2++)
                            diff2->addLine("", DiffView::Neutral);
                            
                        state = Normal;
                    }
                }
                break;
        }
    } 
    while( !separator.atEnd() );
    
    updateNofN();

    return true; // succesful
}


void ResolveDialog::addToMergeAndVersionA(const TQString& line, 
                                          DiffView::DiffType type, int& lineNo)
{
    lineNo++;
    diff1->addLine(line, type, lineNo);
    merge->addLine(line, type, lineNo);
}


void ResolveDialog::addToVersionB(const TQString& line, DiffView::DiffType type, 
                                  int& lineNo)
{
    lineNo++;
    diff2->addLine(line, type, lineNo);
}


void ResolveDialog::saveFile(const TQString &name)
{
    TQFile f(name);
    if (!f.open(IO_WriteOnly))
    {
        KMessageBox::sorry(this,
                           i18n("Could not open file for writing."),
                           "Cervisia");
        return;
    }
    TQTextStream stream(&f);
    TQTextCodec *fcodec = DetectCodec(name);
    stream.setCodec(fcodec);
    
    TQString output;
    for( int i = 0; i < merge->count(); i++ )
       output +=merge->stringAtOffset(i);
    stream << output;
    
    f.close();
}
    

TQString ResolveDialog::readFile()
{
    TQFile f(fname);
    if( !f.open(IO_ReadOnly) )
        return TQString();

    TQTextStream stream(&f);
    TQTextCodec* codec = DetectCodec(fname);
    stream.setCodec(codec);
    
    return stream.read();
}


void ResolveDialog::updateNofN()
{
    TQString str;
    if (markeditem >= 0)
        str = i18n("%1 of %2").tqarg(markeditem+1).tqarg(items.count());
    else
        str = i18n("%1 conflicts").tqarg(items.count());
    nofnlabel->setText(str);

    backbutton->setEnabled(markeditem != -1);
    forwbutton->setEnabled(markeditem != -2 && items.count());

    bool marked = markeditem >= 0;
    abutton->setEnabled(marked);
    bbutton->setEnabled(marked);
    abbutton->setEnabled(marked);
    babutton->setEnabled(marked);
    editbutton->setEnabled(marked);
}


void ResolveDialog::updateHighlight(int newitem)
{
    if (markeditem >= 0)
    {
        ResolveItem *item = items.at(markeditem);
        for (int i = item->linenoA; i < item->linenoA+item->linecountA; ++i)
            diff1->setInverted(i, false);
        for (int i = item->linenoB; i < item->linenoB+item->linecountB; ++i)
            diff2->setInverted(i, false);
    }

    markeditem = newitem;

    if (markeditem >= 0)
    {
        ResolveItem *item = items.at(markeditem);
        for (int i = item->linenoA; i < item->linenoA+item->linecountA; ++i)
            diff1->setInverted(i, true);
        for (int i = item->linenoB; i < item->linenoB+item->linecountB; ++i)
            diff2->setInverted(i, true);
        diff1->setCenterLine(item->linenoA);
        diff2->setCenterLine(item->linenoB);
        merge->setCenterOffset(item->offsetM);
    }
    diff1->tqrepaint();
    diff2->tqrepaint();
    merge->tqrepaint();
    updateNofN();
}


void ResolveDialog::updateMergedVersion(ResolveItem* item, 
                                        ResolveDialog::ChooseType chosen)
{
    // Remove old variant
    for (int i = 0; i < item->linecountTotal; ++i)
        merge->removeAtOffset(item->offsetM);

    // Insert new
    int total = 0;
    LineSeparator separator(m_contentMergedVersion);
    TQString line = separator.nextLine();
    while( !separator.atEnd() )
    {
        merge->insertAtOffset(line, DiffView::Change, item->offsetM+total);
        line = separator.nextLine();
        ++total;
    }

    // Adjust other items
    int difference = total - item->linecountTotal;
    item->chosen = chosen;
    item->linecountTotal = total;
    while ( (item = items.next()) != 0 )
        item->offsetM += difference;

    merge->tqrepaint();
}


void ResolveDialog::backClicked()
{
    int newitem;
    if (markeditem == -1)
        return; // internal error (button not disabled)
    else if (markeditem == -2) // past end
        newitem = items.count()-1;
    else
        newitem = markeditem-1;
    updateHighlight(newitem);
}


void ResolveDialog::forwClicked()
{
    int newitem;
    if (markeditem == -2 || (markeditem == -1 && !items.count()))
        return; // internal error (button not disabled)
    else if (markeditem+1 == (int)items.count()) // past end
        newitem = -2;
    else
        newitem = markeditem+1;
    updateHighlight(newitem);
}


void ResolveDialog::choose(ChooseType ch)
{
    if (markeditem < 0)
        return;

    ResolveItem *item = items.at(markeditem);

    switch (ch)
        {
        case ChA:
            m_contentMergedVersion = contentVersionA(item);
            break;
        case ChB:
            m_contentMergedVersion = contentVersionB(item);
            break;
        case ChAB:
            m_contentMergedVersion = contentVersionA(item) + contentVersionB(item);
            break;
        case ChBA:
            m_contentMergedVersion = contentVersionB(item) + contentVersionA(item);
            break;
        default:
            kdDebug(8050) << "Internal error at switch" << endl;
        }

    updateMergedVersion(item, ch);
}


void ResolveDialog::aClicked()
{
    choose(ChA);
}


void ResolveDialog::bClicked()
{
    choose(ChB);
}


void ResolveDialog::abClicked()
{
    choose(ChAB);
}


void ResolveDialog::baClicked()
{
    choose(ChBA);
}


void ResolveDialog::editClicked()
{
    if (markeditem < 0)
        return;
    
    ResolveItem *item = items.at(markeditem);
    
    TQString mergedPart;
    int total  = item->linecountTotal;
    int offset = item->offsetM;
    for( int i = 0; i < total; ++i )
        mergedPart += merge->stringAtOffset(offset+i);

    ResolveEditorDialog *dlg = new ResolveEditorDialog(partConfig, this, "edit");
    dlg->setContent(mergedPart);

    if (dlg->exec())
    {
        m_contentMergedVersion = dlg->content();
        updateMergedVersion(item, ChEdit);
    }

    delete dlg;
    diff1->tqrepaint();
    diff2->tqrepaint();
    merge->tqrepaint();
}


void ResolveDialog::saveClicked()
{
    saveFile(fname);
}


void ResolveDialog::saveAsClicked()
{
    TQString filename =
        KFileDialog::getSaveFileName(0, 0, this, 0);

    if( !filename.isEmpty() && Cervisia::CheckOverwrite(filename) )
        saveFile(filename);
}


void ResolveDialog::keyPressEvent(TQKeyEvent *e)
{
    switch (e->key())
    {
        case Key_A:    aClicked();    break;
        case Key_B:    bClicked();    break;
        case Key_Left: backClicked(); break;
        case Key_Right:forwClicked(); break;
        case Key_Up:   diff1->up();   break;
        case Key_Down: diff1->down(); break;
        default:
            KDialogBase::keyPressEvent(e);
    }
}



/* This will return the A side of the diff in a TQString. */
TQString ResolveDialog::contentVersionA(const ResolveItem *item)
{
    TQString result;
    for( int i = item->linenoA; i < item->linenoA+item->linecountA; ++i )
    {
        result += diff1->stringAtLine(i);
    }
    
    return result;  
}


/* This will return the B side of the diff item in a TQString. */
TQString ResolveDialog::contentVersionB(const ResolveItem *item)
{
    TQString result;
    for( int i = item->linenoB; i < item->linenoB+item->linecountB; ++i )
    {
        result += diff2->stringAtLine(i);
    }

    return result;
}

#include "resolvedlg.moc"


// Local Variables:
// c-basic-offset: 4
// End: