directorymergewindow.cpp 120 KB
Newer Older
Joachim Eibl's avatar
Joachim Eibl committed
1
/***************************************************************************
2 3 4
 *   Copyright (C) 2003-2007 by Joachim Eibl <joachim.eibl at gmx.de>      *
 *   Copyright (C) 2018 Michael Reeves reeves.87@gmail.com                 *
 *                                                                         *
Joachim Eibl's avatar
Joachim Eibl committed
5 6 7 8 9 10 11
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
Michael Reeves's avatar
Michael Reeves committed
12
#include "directorymergewindow.h"
13

14
#include "DirectoryInfo.h"
15 16 17
#include "MergeFileInfos.h"
#include "PixMapUtils.h"
#include "Utils.h"
Michael Reeves's avatar
Michael Reeves committed
18
#include "guiutils.h"
19
#include "kdiff3.h"
20 21
#include "options.h"
#include "progress.h"
Michael Reeves's avatar
Michael Reeves committed
22 23

#include <algorithm>
Joachim Eibl's avatar
Joachim Eibl committed
24
#include <map>
Michael Reeves's avatar
Michael Reeves committed
25
#include <vector>
Joachim Eibl's avatar
Joachim Eibl committed
26

Michael Reeves's avatar
Michael Reeves committed
27
#include <QAction>
Joachim Eibl's avatar
Joachim Eibl committed
28
#include <QApplication>
Pino Toscano's avatar
Pino Toscano committed
29
#include <QDialogButtonBox>
30
#include <QDir>
Michael Reeves's avatar
Michael Reeves committed
31
#include <QFileDialog>
32
#include <QImage>
Joachim Eibl's avatar
Joachim Eibl committed
33
#include <QKeyEvent>
Michael Reeves's avatar
Michael Reeves committed
34 35
#include <QLabel>
#include <QLayout>
Joachim Eibl's avatar
Joachim Eibl committed
36
#include <QMenu>
Michael Reeves's avatar
Michael Reeves committed
37 38
#include <QPushButton>
#include <QRegExp>
Joachim Eibl's avatar
Joachim Eibl committed
39
#include <QSplitter>
40
#include <QStyledItemDelegate>
Michael Reeves's avatar
Michael Reeves committed
41
#include <QTextStream>
42
#include <QPainter>
Joachim Eibl's avatar
Joachim Eibl committed
43

Michael Reeves's avatar
Michael Reeves committed
44
#include <KLocalizedString>
45
#include <KMessageBox>
46
#include <KTextEdit>
47
#include <KToggleAction>
Joachim Eibl's avatar
Joachim Eibl committed
48

49 50
class StatusInfo : public QDialog
{
51
    KTextEdit* m_pTextEdit;
52 53

  public:
54 55
    explicit StatusInfo(QWidget* pParent)
        : QDialog(pParent)
56 57
    {
        QVBoxLayout* pVLayout = new QVBoxLayout(this);
58
        m_pTextEdit = new KTextEdit(this);
59 60 61 62 63
        pVLayout->addWidget(m_pTextEdit);
        setObjectName("StatusInfo");
        setWindowFlags(Qt::Dialog);
        m_pTextEdit->setWordWrapMode(QTextOption::NoWrap);
        m_pTextEdit->setReadOnly(true);
64
        QDialogButtonBox* box = new QDialogButtonBox(QDialogButtonBox::Close, this);
Pino Toscano's avatar
Pino Toscano committed
65 66
        connect(box, &QDialogButtonBox::rejected, this, &QDialog::accept);
        pVLayout->addWidget(box);
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    }

    bool isEmpty()
    {
        return m_pTextEdit->toPlainText().isEmpty();
    }

    void addText(const QString& s)
    {
        m_pTextEdit->append(s);
    }

    void clear()
    {
        m_pTextEdit->clear();
    }

84
    void setVisible(bool bVisible) override
85 86 87 88 89 90 91
    {
        if(bVisible)
        {
            m_pTextEdit->moveCursor(QTextCursor::End);
            m_pTextEdit->moveCursor(QTextCursor::StartOfLine);
            m_pTextEdit->ensureCursorVisible();
        }
Joachim Eibl's avatar
Joachim Eibl committed
92

93 94 95 96 97
        QDialog::setVisible(bVisible);
        if(bVisible)
            setWindowState(windowState() | Qt::WindowMaximized);
    }
};
Joachim Eibl's avatar
Joachim Eibl committed
98

99 100
enum Columns
{
101 102 103 104 105 106 107 108 109 110
    s_NameCol = 0,
    s_ACol = 1,
    s_BCol = 2,
    s_CCol = 3,
    s_OpCol = 4,
    s_OpStatusCol = 5,
    s_UnsolvedCol = 6, // Nr of unsolved conflicts (for 3 input files)
    s_SolvedCol = 7,   // Nr of auto-solvable conflicts (for 3 input files)
    s_NonWhiteCol = 8, // Nr of nonwhite deltas (for 2 input files)
    s_WhiteCol = 9     // Nr of white deltas (for 2 input files)
111
};
Joachim Eibl's avatar
Joachim Eibl committed
112

113
static Qt::CaseSensitivity s_eCaseSensitivity = Qt::CaseSensitive;
114

115 116
//TODO: clean up this mess.
class DirectoryMergeWindow::DirectoryMergeWindowPrivate : public QAbstractItemModel
117
{
118
    friend class DirMergeItem;
119

120 121
  public:
    DirectoryMergeWindow* q;
122
    explicit DirectoryMergeWindowPrivate(DirectoryMergeWindow* pDMW)
123 124
    {
        q = pDMW;
Michael Reeves's avatar
Michael Reeves committed
125 126
        m_pOptions = nullptr;
        m_pDirectoryMergeInfo = nullptr;
127 128 129 130 131 132 133 134 135 136
        m_bSimulatedMergeStarted = false;
        m_bRealMergeStarted = false;
        m_bError = false;
        m_bSyncMode = false;
        m_pStatusInfo = new StatusInfo(q);
        m_pStatusInfo->hide();
        m_bScanning = false;
        m_bCaseSensitive = true;
        m_bUnfoldSubdirs = false;
        m_bSkipDirStatus = false;
137
        m_pRoot = new MergeFileInfos;
138
    }
139
    ~DirectoryMergeWindowPrivate() override
140 141 142 143
    {
        delete m_pRoot;
    }
    // Implement QAbstractItemModel
144
    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
145
    //Qt::ItemFlags flags ( const QModelIndex & index ) const
146
    QModelIndex parent(const QModelIndex& index) const override
147 148
    {
        MergeFileInfos* pMFI = getMFI(index);
149
        if(pMFI == nullptr || pMFI == m_pRoot || pMFI->parent() == m_pRoot)
150 151 152
            return QModelIndex();
        else
        {
153 154
            MergeFileInfos* pParentsParent = pMFI->parent()->parent();
            return createIndex(pParentsParent->children().indexOf(pMFI->parent()), 0, pMFI->parent());
155 156
        }
    }
157
    int rowCount(const QModelIndex& parent = QModelIndex()) const override
158 159
    {
        MergeFileInfos* pParentMFI = getMFI(parent);
Michael Reeves's avatar
Michael Reeves committed
160
        if(pParentMFI != nullptr)
161
            return pParentMFI->children().count();
162
        else
163
            return m_pRoot->children().count();
164
    }
165
    int columnCount(const QModelIndex& /*parent*/) const override
166 167 168
    {
        return 10;
    }
169
    QModelIndex index(int row, int column, const QModelIndex& parent) const override
170 171
    {
        MergeFileInfos* pParentMFI = getMFI(parent);
172 173 174 175
        if(pParentMFI == nullptr && row < m_pRoot->children().count())
            return createIndex(row, column, m_pRoot->children()[row]);
        else if(pParentMFI != nullptr && row < pParentMFI->children().count())
            return createIndex(row, column, pParentMFI->children()[row]);
176 177 178
        else
            return QModelIndex();
    }
179 180
    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
    void sort(int column, Qt::SortOrder order) override;
181 182 183 184 185 186
    // private data and helper methods
    MergeFileInfos* getMFI(const QModelIndex& mi) const
    {
        if(mi.isValid())
            return (MergeFileInfos*)mi.internalPointer();
        else
Michael Reeves's avatar
Michael Reeves committed
187
            return nullptr;
188
    }
Michael Reeves's avatar
Michael Reeves committed
189

190 191 192 193 194
    bool isThreeWay() const
    {
        if(rootMFI() == nullptr || rootMFI()->getDirectoryInfo() == nullptr) return false;
        return rootMFI()->getDirectoryInfo()->dirC().isValid();
    }
195
    MergeFileInfos* rootMFI() const { return m_pRoot; }
Michael Reeves's avatar
Michael Reeves committed
196

197 198
    static void setPixmaps(MergeFileInfos& mfi, bool);

199 200 201 202 203 204 205 206
    Options* m_pOptions;

    void calcDirStatus(bool bThreeDirs, const QModelIndex& mi,
                       int& nofFiles, int& nofDirs, int& nofEqualFiles, int& nofManualMerges);

    void mergeContinue(bool bStart, bool bVerbose);

    void prepareListView(ProgressProxy& pp);
Michael Reeves's avatar
Michael Reeves committed
207
    void calcSuggestedOperation(const QModelIndex& mi, e_MergeOperation eDefaultMergeOp);
208 209 210 211 212 213 214 215 216 217 218
    void setAllMergeOperations(e_MergeOperation eDefaultOperation);

    bool canContinue();
    QModelIndex treeIterator(QModelIndex mi, bool bVisitChildren = true, bool bFindInvisible = false);
    void prepareMergeStart(const QModelIndex& miBegin, const QModelIndex& miEnd, bool bVerbose);
    bool executeMergeOperation(MergeFileInfos& mfi, bool& bSingleFileMerge);

    void scanDirectory(const QString& dirName, t_DirectoryList& dirList);
    void scanLocalDirectory(const QString& dirName, t_DirectoryList& dirList);
    bool fastFileComparison(FileAccess& fi1, FileAccess& fi2,
                            bool& bError, QString& status);
219
    bool compareFilesAndCalcAges(MergeFileInfos& mfi, QStringList& errors);
220 221 222 223 224 225 226 227 228 229 230 231 232

    void setMergeOperation(const QModelIndex& mi, e_MergeOperation eMergeOp, bool bRecursive = true);
    bool isDir(const QModelIndex& mi);
    QString getFileName(const QModelIndex& mi);

    bool copyFLD(const QString& srcName, const QString& destName);
    bool deleteFLD(const QString& name, bool bCreateBackup);
    bool makeDir(const QString& name, bool bQuiet = false);
    bool renameFLD(const QString& srcName, const QString& destName);
    bool mergeFLD(const QString& nameA, const QString& nameB, const QString& nameC,
                  const QString& nameDest, bool& bSingleFileMerge);


233
    void buildMergeMap(const QSharedPointer<DirectoryInfo>& dirInfo);
234

235
  private:
236 237
    class FileKey
    {
238
      private:
239
        const FileAccess* m_pFA;
240
      public:
241 242
        explicit FileKey(const FileAccess& fa)
            : m_pFA(&fa) {}
243

244
        quint32 getParents(const FileAccess* pFA, const FileAccess* v[], quint32 maxSize) const
245
        {
246
            quint32 s = 0;
Michael Reeves's avatar
Michael Reeves committed
247
            for(s = 0; pFA->parent() != nullptr; pFA = pFA->parent(), ++s)
248 249 250
            {
                if(s == maxSize)
                    break;
251
                v[s] = pFA;
252
            }
253 254 255 256 257 258 259 260 261 262 263 264
            return s;
        }

        // This is essentially the same as
        // int r = filePath().compare( fa.filePath() )
        // if ( r<0 ) return true;
        // if ( r==0 ) return m_col < fa.m_col;
        // return false;
        bool operator<(const FileKey& fk) const
        {
            const FileAccess* v1[100];
            const FileAccess* v2[100];
265 266
            quint32 v1Size = getParents(m_pFA, v1, 100);
            quint32 v2Size = getParents(fk.m_pFA, v2, 100);
267

268
            for(quint32 i = 0; i < v1Size && i < v2Size; ++i)
269 270 271 272 273 274 275 276
            {
                int r = v1[v1Size - i - 1]->fileName().compare(v2[v2Size - i - 1]->fileName(), s_eCaseSensitivity);
                if(r < 0)
                    return true;
                else if(r > 0)
                    return false;
            }

277
            return v1Size < v2Size;
278 279
        }
    };
280

281
    typedef QMap<FileKey, MergeFileInfos> t_fileMergeMap;
Michael Reeves's avatar
Michael Reeves committed
282 283

    MergeFileInfos* m_pRoot;
284

285
    t_fileMergeMap m_fileMergeMap;
Michael Reeves's avatar
Michael Reeves committed
286
  public:
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

    bool m_bFollowDirLinks;
    bool m_bFollowFileLinks;
    bool m_bSimulatedMergeStarted;
    bool m_bRealMergeStarted;
    bool m_bError;
    bool m_bSyncMode;
    bool m_bDirectoryMerge; // if true, then merge is the default operation, otherwise it's diff.
    bool m_bCaseSensitive;
    bool m_bUnfoldSubdirs;
    bool m_bSkipDirStatus;
    bool m_bScanning; // true while in init()

    DirectoryMergeInfo* m_pDirectoryMergeInfo;
    StatusInfo* m_pStatusInfo;

    typedef std::list<QModelIndex> MergeItemList; // linked list
    MergeItemList m_mergeItemList;
    MergeItemList::iterator m_currentIndexForOperation;

    QModelIndex m_selection1Index;
    QModelIndex m_selection2Index;
    QModelIndex m_selection3Index;
    void selectItemAndColumn(const QModelIndex& mi, bool bContextMenu);

    QAction* m_pDirStartOperation;
    QAction* m_pDirRunOperationForCurrentItem;
    QAction* m_pDirCompareCurrent;
    QAction* m_pDirMergeCurrent;
    QAction* m_pDirRescan;
    QAction* m_pDirChooseAEverywhere;
    QAction* m_pDirChooseBEverywhere;
    QAction* m_pDirChooseCEverywhere;
    QAction* m_pDirAutoChoiceEverywhere;
    QAction* m_pDirDoNothingEverywhere;
    QAction* m_pDirFoldAll;
    QAction* m_pDirUnfoldAll;

    KToggleAction* m_pDirShowIdenticalFiles;
    KToggleAction* m_pDirShowDifferentFiles;
    KToggleAction* m_pDirShowFilesOnlyInA;
    KToggleAction* m_pDirShowFilesOnlyInB;
    KToggleAction* m_pDirShowFilesOnlyInC;

    KToggleAction* m_pDirSynchronizeDirectories;
    KToggleAction* m_pDirChooseNewerFiles;

    QAction* m_pDirCompareExplicit;
    QAction* m_pDirMergeExplicit;

    QAction* m_pDirCurrentDoNothing;
    QAction* m_pDirCurrentChooseA;
    QAction* m_pDirCurrentChooseB;
    QAction* m_pDirCurrentChooseC;
    QAction* m_pDirCurrentMerge;
    QAction* m_pDirCurrentDelete;

    QAction* m_pDirCurrentSyncDoNothing;
    QAction* m_pDirCurrentSyncCopyAToB;
    QAction* m_pDirCurrentSyncCopyBToA;
    QAction* m_pDirCurrentSyncDeleteA;
    QAction* m_pDirCurrentSyncDeleteB;
    QAction* m_pDirCurrentSyncDeleteAAndB;
    QAction* m_pDirCurrentSyncMergeToA;
    QAction* m_pDirCurrentSyncMergeToB;
    QAction* m_pDirCurrentSyncMergeToAAndB;

    QAction* m_pDirSaveMergeState;
    QAction* m_pDirLoadMergeState;

Michael Reeves's avatar
Michael Reeves committed
357
    bool init(const QSharedPointer<DirectoryInfo> &dirInfo, bool bDirectoryMerge, bool bReload);
358 359 360 361
    void setOpStatus(const QModelIndex& mi, e_OperationStatus eOpStatus)
    {
        if(MergeFileInfos* pMFI = getMFI(mi))
        {
362
            pMFI->setOpStatus(eOpStatus);
363 364 365
            emit dataChanged(mi, mi);
        }
    }
366 367

    QModelIndex nextSibling(const QModelIndex& mi);
368
};
Joachim Eibl's avatar
Joachim Eibl committed
369

370
QVariant DirectoryMergeWindow::DirectoryMergeWindowPrivate::data(const QModelIndex& index, int role) const
371 372 373 374 375 376 377 378
{
    MergeFileInfos* pMFI = getMFI(index);
    if(pMFI)
    {
        if(role == Qt::DisplayRole)
        {
            switch(index.column())
            {
379 380 381 382 383 384 385 386 387 388 389
                case s_NameCol:
                    return QFileInfo(pMFI->subPath()).fileName();
                case s_ACol:
                    return i18n("A");
                case s_BCol:
                    return i18n("B");
                case s_CCol:
                    return i18n("C");
                //case s_OpCol:       return i18n("Operation");
                //case s_OpStatusCol: return i18n("Status");
                case s_UnsolvedCol:
390
                    return pMFI->diffStatus().getUnsolvedConflicts();
391
                case s_SolvedCol:
392
                    return pMFI->diffStatus().getSolvedConflicts();
393
                case s_NonWhiteCol:
394
                    return pMFI->diffStatus().getNonWhitespaceConflicts();
395
                case s_WhiteCol:
396
                    return pMFI->diffStatus().getWhitespaceConflicts();
397
                    //default :           return QVariant();
398 399 400
            }

            if(s_OpCol == index.column())
401
            {
402
                bool bDir = pMFI->isDirA() || pMFI->isDirB() || pMFI->isDirC();
403
                switch(pMFI->getOperation())
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
                    case eNoOperation:
                        return "";
                        break;
                    case eCopyAToB:
                        return i18n("Copy A to B");
                        break;
                    case eCopyBToA:
                        return i18n("Copy B to A");
                        break;
                    case eDeleteA:
                        return i18n("Delete A");
                        break;
                    case eDeleteB:
                        return i18n("Delete B");
                        break;
                    case eDeleteAB:
                        return i18n("Delete A & B");
                        break;
                    case eMergeToA:
                        return i18n("Merge to A");
                        break;
                    case eMergeToB:
                        return i18n("Merge to B");
                        break;
                    case eMergeToAB:
                        return i18n("Merge to A & B");
                        break;
                    case eCopyAToDest:
                        return i18n("A");
                        break;
                    case eCopyBToDest:
                        return i18n("B");
                        break;
                    case eCopyCToDest:
                        return i18n("C");
                        break;
                    case eDeleteFromDest:
                        return i18n("Delete (if exists)");
                        break;
                    case eMergeABCToDest:
                        return bDir ? i18n("Merge") : i18n("Merge (manual)");
                        break;
                    case eMergeABToDest:
                        return bDir ? i18n("Merge") : i18n("Merge (manual)");
                        break;
                    case eConflictingFileTypes:
                        return i18n("Error: Conflicting File Types");
                        break;
                    case eChangedAndDeleted:
                        return i18n("Error: Changed and Deleted");
                        break;
                    case eConflictingAges:
                        return i18n("Error: Dates are equal but files are not.");
                        break;
                    default:
                        Q_ASSERT(true);
                        break;
462 463 464 465
                }
            }
            if(s_OpStatusCol == index.column())
            {
466
                switch(pMFI->getOpStatus())
467
                {
468 469 470 471 472 473 474 475 476 477 478 479 480 481
                    case eOpStatusNone:
                        return "";
                    case eOpStatusDone:
                        return i18n("Done");
                    case eOpStatusError:
                        return i18n("Error");
                    case eOpStatusSkipped:
                        return i18n("Skipped.");
                    case eOpStatusNotSaved:
                        return i18n("Not saved.");
                    case eOpStatusInProgress:
                        return i18n("In progress...");
                    case eOpStatusToDo:
                        return i18n("To do.");
482 483 484 485 486 487 488
                }
            }
        }
        else if(role == Qt::DecorationRole)
        {
            if(s_NameCol == index.column())
            {
489
                return PixMapUtils::getOnePixmap(eAgeEnd, pMFI->isLinkA() || pMFI->isLinkB() || pMFI->isLinkC(),
490
                                                 pMFI->isDirA() || pMFI->isDirB() || pMFI->isDirC());
491 492 493
            }

            if(s_ACol == index.column())
494
            {
Michael Reeves's avatar
Michael Reeves committed
495
                return PixMapUtils::getOnePixmap(pMFI->getAgeA(), pMFI->isLinkA(), pMFI->isDirA());
496 497 498
            }
            if(s_BCol == index.column())
            {
Michael Reeves's avatar
Michael Reeves committed
499
                return PixMapUtils::getOnePixmap(pMFI->getAgeB(), pMFI->isLinkB(), pMFI->isDirB());
500 501 502
            }
            if(s_CCol == index.column())
            {
Michael Reeves's avatar
Michael Reeves committed
503
                return PixMapUtils::getOnePixmap(pMFI->getAgeC(), pMFI->isLinkC(), pMFI->isDirC());
504 505 506 507 508 509 510 511 512 513 514
            }
        }
        else if(role == Qt::TextAlignmentRole)
        {
            if(s_UnsolvedCol == index.column() || s_SolvedCol == index.column() || s_NonWhiteCol == index.column() || s_WhiteCol == index.column())
                return Qt::AlignRight;
        }
    }
    return QVariant();
}

515
QVariant DirectoryMergeWindow::DirectoryMergeWindowPrivate::headerData(int section, Qt::Orientation orientation, int role) const
516 517 518 519 520
{
    if(orientation == Qt::Horizontal && section >= 0 && section < columnCount(QModelIndex()) && role == Qt::DisplayRole)
    {
        switch(section)
        {
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
            case s_NameCol:
                return i18n("Name");
            case s_ACol:
                return i18n("A");
            case s_BCol:
                return i18n("B");
            case s_CCol:
                return i18n("C");
            case s_OpCol:
                return i18n("Operation");
            case s_OpStatusCol:
                return i18n("Status");
            case s_UnsolvedCol:
                return i18n("Unsolved");
            case s_SolvedCol:
                return i18n("Solved");
            case s_NonWhiteCol:
                return i18n("Nonwhite");
            case s_WhiteCol:
                return i18n("White");
            default:
                return QVariant();
543 544 545
        }
    }
    return QVariant();
Joachim Eibl's avatar
Joachim Eibl committed
546 547
}

Joachim Eibl's avatar
Joachim Eibl committed
548
// Previously  Q3ListViewItem::paintCell(p,cg,column,width,align);
549
class DirectoryMergeWindow::DirMergeItemDelegate : public QStyledItemDelegate
550
{
551
    DirectoryMergeWindow* m_pDMW;
552
    DirectoryMergeWindow::DirectoryMergeWindowPrivate* d;
553 554

  public:
555
    explicit DirMergeItemDelegate(DirectoryMergeWindow* pParent)
556 557 558
        : QStyledItemDelegate(pParent), m_pDMW(pParent), d(pParent->d)
    {
    }
559
    void paint(QPainter* p, const QStyleOptionViewItem& option, const QModelIndex& index) const override
560 561 562 563 564 565 566
    {
        int column = index.column();
        if(column == s_ACol || column == s_BCol || column == s_CCol)
        {
            QVariant value = index.data(Qt::DecorationRole);
            QPixmap icon;
            if(value.isValid())
567
            {
568 569 570 571 572 573 574 575 576 577 578
                if(value.type() == QVariant::Icon)
                {
                    icon = qvariant_cast<QIcon>(value).pixmap(16, 16);
                    //icon = qvariant_cast<QIcon>(value);
                    //decorationRect = QRect(QPoint(0, 0), icon.actualSize(option.decorationSize, iconMode, iconState));
                }
                else
                {
                    icon = qvariant_cast<QPixmap>(value);
                    //decorationRect = QRect(QPoint(0, 0), option.decorationSize).intersected(pixmap.rect());
                }
Joachim Eibl's avatar
Joachim Eibl committed
579
            }
580 581 582 583 584

            int x = option.rect.left();
            int y = option.rect.top();
            //QPixmap icon = value.value<QPixmap>(); //pixmap(column);
            if(!icon.isNull())
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
                int yOffset = (sizeHint(option, index).height() - icon.height()) / 2;
                p->drawPixmap(x + 2, y + yOffset, icon);

                int i = index == d->m_selection1Index ? 1 : index == d->m_selection2Index ? 2 : index == d->m_selection3Index ? 3 : 0;
                if(i != 0)
                {
                    Options* pOpts = d->m_pOptions;
                    QColor c(i == 1 ? pOpts->m_colorA : i == 2 ? pOpts->m_colorB : pOpts->m_colorC);
                    p->setPen(c); // highlight() );
                    p->drawRect(x + 2, y + yOffset, icon.width(), icon.height());
                    p->setPen(QPen(c, 0, Qt::DotLine));
                    p->drawRect(x + 1, y + yOffset - 1, icon.width() + 2, icon.height() + 2);
                    p->setPen(Qt::white);
                    QString s(QChar('A' + i - 1));
                    p->drawText(x + 2 + (icon.width() - p->fontMetrics().width(s)) / 2,
                                y + yOffset + (icon.height() + p->fontMetrics().ascent()) / 2 - 1,
                                s);
                }
                else
                {
                    p->setPen(m_pDMW->palette().background().color());
                    p->drawRect(x + 1, y + yOffset - 1, icon.width() + 2, icon.height() + 2);
                }
                return;
610
            }
611 612 613 614 615 616 617 618
        }
        QStyleOptionViewItem option2 = option;
        if(column >= s_UnsolvedCol)
        {
            option2.displayAlignment = Qt::AlignRight;
        }
        QStyledItemDelegate::paint(p, option2, index);
    }
619
    QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override
620 621 622 623
    {
        QSize sz = QStyledItemDelegate::sizeHint(option, index);
        return sz.expandedTo(QSize(0, 18));
    }
Joachim Eibl's avatar
Joachim Eibl committed
624 625
};

626
DirectoryMergeWindow::DirectoryMergeWindow(QWidget* pParent, Options* pOptions)
627
    : QTreeView(pParent)
628
{
629
    d = new DirectoryMergeWindowPrivate(this);
630 631 632 633
    setModel(d);
    setItemDelegate(new DirMergeItemDelegate(this));
    connect(this, &DirectoryMergeWindow::doubleClicked, this, &DirectoryMergeWindow::onDoubleClick);
    connect(this, &DirectoryMergeWindow::expanded, this, &DirectoryMergeWindow::onExpanded);
Joachim Eibl's avatar
Joachim Eibl committed
634

635
    d->m_pOptions = pOptions;
Joachim Eibl's avatar
Joachim Eibl committed
636

637
    setSortingEnabled(true);
Joachim Eibl's avatar
Joachim Eibl committed
638 639
}

640 641
DirectoryMergeWindow::~DirectoryMergeWindow()
{
642
    delete d;
Joachim Eibl's avatar
Joachim Eibl committed
643 644
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
void DirectoryMergeWindow::setDirectoryMergeInfo(DirectoryMergeInfo* p)
{
    d->m_pDirectoryMergeInfo = p;
}
bool DirectoryMergeWindow::isDirectoryMergeInProgress()
{
    return d->m_bRealMergeStarted;
}
bool DirectoryMergeWindow::isSyncMode()
{
    return d->m_bSyncMode;
}
bool DirectoryMergeWindow::isScanning()
{
    return d->m_bScanning;
}
661

662
bool DirectoryMergeWindow::DirectoryMergeWindowPrivate::fastFileComparison(
663 664 665 666 667
    FileAccess& fi1, FileAccess& fi2,
    bool& bError, QString& status)
{
    ProgressProxy pp;
    bool bEqual = false;
668 669

    status = "";
670 671
    bError = true;

672 673 674 675 676 677 678 679 680 681 682 683
    if(fi1.isNormal() != fi2.isNormal())
    {
        status = i18n("Unable to compare non-normal file with normal file.");
        return false;
    }

    if(!fi1.isNormal())
    {
        bError = false;
        return false;
    }

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    if(!m_bFollowFileLinks)
    {
        if(fi1.isSymLink() != fi2.isSymLink())
        {
            status = i18n("Mix of links and normal files.");
            return bEqual;
        }
        else if(fi1.isSymLink() && fi2.isSymLink())
        {
            bError = false;
            bEqual = fi1.readLink() == fi2.readLink();
            status = i18n("Link: ");
            return bEqual;
        }
    }

    if(fi1.size() != fi2.size())
    {
702
        bError = false;
703 704 705 706 707 708 709
        bEqual = false;
        status = i18n("Size. ");
        return bEqual;
    }
    else if(m_pOptions->m_bDmTrustSize)
    {
        bEqual = true;
710
        bError = false;
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
        return bEqual;
    }

    if(m_pOptions->m_bDmTrustDate)
    {
        bEqual = (fi1.lastModified() == fi2.lastModified() && fi1.size() == fi2.size());
        bError = false;
        status = i18n("Date & Size: ");
        return bEqual;
    }

    if(m_pOptions->m_bDmTrustDateFallbackToBinary)
    {
        bEqual = (fi1.lastModified() == fi2.lastModified() && fi1.size() == fi2.size());
        if(bEqual)
        {
            bError = false;
            status = i18n("Date & Size: ");
            return bEqual;
        }
    }

    std::vector<char> buf1(100000);
    std::vector<char> buf2(buf1.size());

736
    if(!fi1.open(QIODevice::ReadOnly))
737
    {
738
        status = fi1.errorString();
739 740 741
        return bEqual;
    }

742
    if(!fi2.open(QIODevice::ReadOnly))
743
    {
744
        fi1.close();
745
        status = fi2.errorString();
746 747 748 749 750
        return bEqual;
    }

    pp.setInformation(i18n("Comparing file..."), 0, false);
    typedef qint64 t_FileSize;
751
    t_FileSize fullSize = fi1.size();
752 753 754 755 756 757
    t_FileSize sizeLeft = fullSize;

    pp.setMaxNofSteps(fullSize / buf1.size());

    while(sizeLeft > 0 && !pp.wasCancelled())
    {
758
        qint64 len = std::min(sizeLeft, (t_FileSize)buf1.size());
759
        if(len != fi1.read(&buf1[0], len))
760
        {
761
            status = fi1.errorString();
762 763
            fi1.close();
            fi2.close();
764 765 766
            return bEqual;
        }

767
        if(len != fi2.read(&buf2[0], len))
768
        {
769 770 771
            status = fi2.errorString();
            fi1.close();
            fi2.close();
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
            return bEqual;
        }

        if(memcmp(&buf1[0], &buf2[0], len) != 0)
        {
            bError = false;
            return bEqual;
        }
        sizeLeft -= len;
        //pp.setCurrent(double(fullSize-sizeLeft)/fullSize, false );
        pp.step();
    }

    // If the program really arrives here, then the files are really equal.
    bError = false;
    bEqual = true;
    return bEqual;
789 790 791 792
}

int DirectoryMergeWindow::totalColumnWidth()
{
793 794 795 796 797 798
    int w = 0;
    for(int i = 0; i < s_OpStatusCol; ++i)
    {
        w += columnWidth(i);
    }
    return w;
799 800 801 802
}

void DirectoryMergeWindow::reload()
{
803 804 805 806 807 808 809 810 811 812
    if(isDirectoryMergeInProgress())
    {
        int result = KMessageBox::warningYesNo(this,
                                               i18n("You are currently doing a directory merge. Are you sure, you want to abort the merge and rescan the directory?"),
                                               i18n("Warning"),
                                               KGuiItem(i18n("Rescan")),
                                               KGuiItem(i18n("Continue Merging")));
        if(result != KMessageBox::Yes)
            return;
    }
813

814
    init(d->rootMFI()->getDirectoryInfo(), true);
815 816
    //fix file visibilities after reload or menu will be out of sync with display if changed from defaults.
    updateFileVisibilities();
Joachim Eibl's avatar
Joachim Eibl committed
817 818
}

819
void DirectoryMergeWindow::DirectoryMergeWindowPrivate::calcDirStatus(bool bThreeDirs, const QModelIndex& mi,
820
                                                                      int& nofFiles, int& nofDirs, int& nofEqualFiles, int& nofManualMerges)
821 822
{
    MergeFileInfos* pMFI = getMFI(mi);
823
    if(pMFI->isDirA() || pMFI->isDirB() || pMFI->isDirC())
824 825 826 827 828 829 830 831 832 833 834 835
    {
        ++nofDirs;
    }
    else
    {
        ++nofFiles;
        if(pMFI->m_bEqualAB && (!bThreeDirs || pMFI->m_bEqualAC))
        {
            ++nofEqualFiles;
        }
        else
        {
836
            if(pMFI->getOperation() == eMergeABCToDest || pMFI->getOperation() == eMergeABToDest)
837 838 839 840 841 842 843 844 845 846 847 848
                ++nofManualMerges;
        }
    }
    for(int childIdx = 0; childIdx < rowCount(mi); ++childIdx)
        calcDirStatus(bThreeDirs, index(childIdx, 0, mi), nofFiles, nofDirs, nofEqualFiles, nofManualMerges);
}

struct t_ItemInfo {
    bool bExpanded;
    bool bOperationComplete;
    QString status;
    e_MergeOperation eMergeOperation;
Joachim Eibl's avatar
Joachim Eibl committed
849 850
};

851
bool DirectoryMergeWindow::init(
Michael Reeves's avatar
Michael Reeves committed
852
    const QSharedPointer<DirectoryInfo> &dirInfo,
853 854 855
    bool bDirectoryMerge,
    bool bReload)
{
856
    return d->init(dirInfo, bDirectoryMerge, bReload);
857 858
}

859
void DirectoryMergeWindow::DirectoryMergeWindowPrivate::buildMergeMap(const QSharedPointer<DirectoryInfo>& dirInfo)
860 861 862
{
    t_DirectoryList::iterator dirIterator;

863
    if(dirInfo->dirA().isValid())
864
    {
865
        for(dirIterator = dirInfo->getDirListA().begin(); dirIterator != dirInfo->getDirListA().end(); ++dirIterator)
866 867 868
        {
            MergeFileInfos& mfi = m_fileMergeMap[FileKey(*dirIterator)];

869
            mfi.setFileInfoA(&(*dirIterator));
870
            mfi.setDirectoryInfo(dirInfo);
871 872
        }
    }
873

874
    if(dirInfo->dirB().isValid())
875
    {
876
        for(dirIterator = dirInfo->getDirListB().begin(); dirIterator != dirInfo->getDirListB().end(); ++dirIterator)
877 878 879
        {
            MergeFileInfos& mfi = m_fileMergeMap[FileKey(*dirIterator)];

880
            mfi.setFileInfoB(&(*dirIterator));
881
            mfi.setDirectoryInfo(dirInfo);
882 883 884
        }
    }

885
    if(dirInfo->dirC().isValid())
886
    {
887
        for(dirIterator = dirInfo->getDirListC().begin(); dirIterator != dirInfo->getDirListC().end(); ++dirIterator)
888 889 890
        {
            MergeFileInfos& mfi = m_fileMergeMap[FileKey(*dirIterator)];

891
            mfi.setFileInfoC(&(*dirIterator));
892
            mfi.setDirectoryInfo(dirInfo);
893 894 895 896
        }
    }
}

897
bool DirectoryMergeWindow::DirectoryMergeWindowPrivate::init(
Michael Reeves's avatar
Michael Reeves committed
898
    const QSharedPointer<DirectoryInfo> &dirInfo,
899 900 901
    bool bDirectoryMerge,
    bool bReload)
{
Michael Reeves's avatar
Michael Reeves committed
902 903 904
    //set root data now that we have the directory info.
    rootMFI()->setDirectoryInfo(dirInfo);

905 906
    if(m_pOptions->m_bDmFullAnalysis)
    {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
907
        // A full analysis uses the same resources that a normal text-diff/merge uses.
908 909 910 911 912
        // So make sure that the user saves his data first.
        bool bCanContinue = false;
        emit q->checkIfCanContinue(&bCanContinue);
        if(!bCanContinue)
            return false;
Michael Reeves's avatar
Michael Reeves committed
913
        emit q->startDiffMerge("", "", "", "", "", "", "", nullptr); // hide main window
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    }

    q->show();
    q->setUpdatesEnabled(true);

    std::map<QString, t_ItemInfo> expandedDirsMap;

    if(bReload)
    {
        // Remember expanded items TODO
        //QTreeWidgetItemIterator it( this );
        //while ( *it )
        //{
        //   DirMergeItem* pDMI = static_cast<DirMergeItem*>( *it );
        //   t_ItemInfo& ii = expandedDirsMap[ pDMI->m_pMFI->subPath() ];
        //   ii.bExpanded = pDMI->isExpanded();
        //   ii.bOperationComplete = pDMI->m_pMFI->m_bOperationComplete;
        //   ii.status = pDMI->text( s_OpStatusCol );
932
        //   ii.eMergeOperation = pDMI->m_pMFI->getOperation();
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
        //   ++it;
        //}
    }

    ProgressProxy pp;
    m_bFollowDirLinks = m_pOptions->m_bDmFollowDirLinks;
    m_bFollowFileLinks = m_pOptions->m_bDmFollowFileLinks;
    m_bSimulatedMergeStarted = false;
    m_bRealMergeStarted = false;
    m_bError = false;
    m_bDirectoryMerge = bDirectoryMerge;
    m_selection1Index = QModelIndex();
    m_selection2Index = QModelIndex();
    m_selection3Index = QModelIndex();
    m_bCaseSensitive = m_pOptions->m_bDmCaseSensitiveFilenameComparison;
    m_bUnfoldSubdirs = m_pOptions->m_bDmUnfoldSubdirs;
    m_bSkipDirStatus = m_pOptions->m_bDmSkipDirStatus;

    beginResetModel();
952
    m_pRoot->clear();
953 954 955 956 957 958 959 960 961 962 963 964 965
    m_mergeItemList.clear();
    endResetModel();

    m_currentIndexForOperation = m_mergeItemList.end();

    if(!bReload)
    {
        m_pDirShowIdenticalFiles->setChecked(true);
        m_pDirShowDifferentFiles->setChecked(true);
        m_pDirShowFilesOnlyInA->setChecked(true);
        m_pDirShowFilesOnlyInB->setChecked(true);
        m_pDirShowFilesOnlyInC->setChecked(true);
    }
966
    Q_ASSERT(dirInfo != nullptr);
967 968 969 970
    FileAccess dirA = dirInfo->dirA();
    FileAccess dirB = dirInfo->dirB();
    FileAccess dirC = dirInfo->dirC();
    const FileAccess dirDest = dirInfo->destDir();
971 972
    // Check if all input directories exist and are valid. The dest dir is not tested now.
    // The test will happen only when we are going to write to it.
973 974
    if(!dirA.isDir() || !dirB.isDir() ||
       (dirC.isValid() && !dirC.isDir()))
975 976 977 978 979
    {
        QString text(i18n("Opening of directories failed:"));
        text += "\n\n";
        if(!dirA.isDir())
        {
980
            text += i18n("Dir A \"%1\" does not exist or is not a directory.\n", dirA.prettyAbsPath());
981 982 983 984
        }

        if(!dirB.isDir())
        {
985
            text += i18n("Dir B \"%1\" does not exist or is not a directory.\n", dirB.prettyAbsPath());
986 987
        }

988
        if(dirC.isValid() && !dirC.isDir())
989
        {
990
            text += i18n("Dir C \"%1\" does not exist or is not a directory.\n", dirC.prettyAbsPath());
991 992 993 994 995 996
        }

        KMessageBox::sorry(q, text, i18n("Directory Open Error"));
        return false;
    }

997 998
    if(dirC.isValid() &&
       (dirDest.prettyAbsPath() == dirA.prettyAbsPath() || dirDest.prettyAbsPath() == dirB.prettyAbsPath()))
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    {
        KMessageBox::error(q,
                           i18n("The destination directory must not be the same as A or B when "
                                "three directories are merged.\nCheck again before continuing."),
                           i18n("Parameter Warning"));
        return false;
    }

    m_bScanning = true;
    emit q->statusBarMessage(i18n("Scanning directories..."));

1010
    m_bSyncMode = m_pOptions->m_bDmSyncMode && !dirC.isValid() && !dirDest.isValid();
1011 1012 1013 1014

    m_fileMergeMap.clear();
    s_eCaseSensitivity = m_bCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;
    // calc how many directories will be read:
1015
    double nofScans = (dirA.isValid() ? 1 : 0) + (dirB.isValid() ? 1 : 0) + (dirC.isValid() ? 1 : 0);
1016 1017 1018 1019 1020 1021
    int currentScan = 0;

    //TODO   setColumnWidthMode(s_UnsolvedCol, Q3ListView::Manual);
    //   setColumnWidthMode(s_SolvedCol,   Q3ListView::Manual);
    //   setColumnWidthMode(s_WhiteCol,    Q3ListView::Manual);
    //   setColumnWidthMode(s_NonWhiteCol, Q3ListView::Manual);
Michael Reeves's avatar
Michael Reeves committed
1022
    q->setColumnHidden(s_CCol, !dirC.isValid());
1023 1024 1025
    q->setColumnHidden(s_WhiteCol, !m_pOptions->m_bDmFullAnalysis);
    q->setColumnHidden(s_NonWhiteCol, !m_pOptions->m_bDmFullAnalysis);
    q->setColumnHidden(s_UnsolvedCol, !m_pOptions->m_bDmFullAnalysis);
Michael Reeves's avatar
Michael Reeves committed
1026
    q->setColumnHidden(s_SolvedCol, !(m_pOptions->m_bDmFullAnalysis && dirC.isValid()));
1027 1028 1029 1030

    bool bListDirSuccessA = true;
    bool bListDirSuccessB = true;
    bool bListDirSuccessC = true;
1031

1032
    if(dirA.isValid())
1033 1034 1035 1036 1037
    {
        pp.setInformation(i18n("Reading Directory A"));
        pp.setSubRangeTransformation(currentScan / nofScans, (currentScan + 1) / nofScans);
        ++currentScan;

1038
        bListDirSuccessA = dirInfo->listDirA(*m_pOptions);
1039 1040
    }

1041
    if(dirB.isValid())
1042 1043 1044 1045 1046
    {
        pp.setInformation(i18n("Reading Directory B"));
        pp.setSubRangeTransformation(currentScan / nofScans, (currentScan + 1) / nofScans);
        ++currentScan;

1047
        bListDirSuccessB = dirInfo->listDirB(*m_pOptions);
1048 1049 1050
    }

    e_MergeOperation eDefaultMergeOp;
1051
    if(dirC.isValid())
1052 1053 1054 1055 1056
    {
        pp.setInformation(i18n("Reading Directory C"));
        pp.setSubRangeTransformation(currentScan / nofScans, (currentScan + 1) / nofScans);
        ++currentScan;

1057
        bListDirSuccessC = dirInfo->listDirC(*m_pOptions);
1058 1059 1060 1061 1062 1063

        eDefaultMergeOp = eMergeABCToDest;
    }
    else
        eDefaultMergeOp = m_bSyncMode ? eMergeToAB : eMergeABToDest;

1064
    buildMergeMap(dirInfo);
1065

1066 1067 1068 1069
    bool bContinue = true;
    if(!bListDirSuccessA || !bListDirSuccessB || !bListDirSuccessC)
    {
        QString s = i18n("Some subdirectories were not readable in");
1070 1071 1072
        if(!bListDirSuccessA) s += "\nA: " + dirA.prettyAbsPath();
        if(!bListDirSuccessB) s += "\nB: " + dirB.prettyAbsPath();
        if(!bListDirSuccessC) s += "\nC: " + dirC.prettyAbsPath();
1073
        s += '\n';
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        s += i18n("Check the permissions of the subdirectories.");
        bContinue = KMessageBox::Continue == KMessageBox::warningContinueCancel(q, s);
    }

    if(bContinue)
    {
        prepareListView(pp);

        q->updateFileVisibilities();

        for(int childIdx = 0; childIdx < rowCount(); ++childIdx)
        {
            QModelIndex mi = index(childIdx, 0, QModelIndex());
            calcSuggestedOperation(mi, eDefaultMergeOp);
        }
    }

    q->sortByColumn(0, Qt::AscendingOrder);

Michael Reeves's avatar
Michael Reeves committed
1093 1094
    for(int column = 0; column < columnCount(QModelIndex()); ++column)
        q->resizeColumnToContents(column);
1095 1096 1097 1098

    // Try to improve the view a little bit.
    QWidget* pParent = q->parentWidget();
    QSplitter* pSplitter = static_cast<QSplitter*>(pParent);
Michael Reeves's avatar
Michael Reeves committed
1099
    if(pSplitter != nullptr)
1100 1101 1102 1103 1104 1105 1106 1107 1108
    {
        QList<int> sizes = pSplitter->sizes();
        int total = sizes[0] + sizes[1];
        if(total < 10)
            total = 100;
        sizes[0] = total * 6 / 10;
        sizes[1] = total - sizes[0];
        pSplitter->setSizes(sizes);
    }
1109

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    m_bScanning = false;
    emit q->statusBarMessage(i18n("Ready."));

    if(bContinue && !m_bSkipDirStatus)
    {
        // Generate a status report
        int nofFiles = 0;
        int nofDirs = 0;
        int nofEqualFiles = 0;
        int nofManualMerges = 0;
        //TODO
        for(int childIdx = 0; childIdx < rowCount(); ++childIdx)
Michael Reeves's avatar
Michael Reeves committed
1122
            calcDirStatus(dirC.isValid(), index(childIdx, 0, QModelIndex()),
1123 1124 1125
                          nofFiles, nofDirs, nofEqualFiles, nofManualMerges);

        QString s;
Pino Toscano's avatar
Pino Toscano committed
1126 1127 1128 1129 1130
        s = i18n("Directory Comparison Status\n\n"
                 "Number of subdirectories: %1\n"
                 "Number of equal files: %2\n"
                 "Number of different files: %3",
                 nofDirs, nofEqualFiles, nofFiles - nofEqualFiles);
1131

Michael Reeves's avatar
Michael Reeves committed
1132
        if(dirC.isValid())
1133
            s += '\n' + i18n("Number of manual merges: %1", nofManualMerges);
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
        KMessageBox::information(q, s);
        //
        //TODO
        //if ( topLevelItemCount()>0 )
        //{
        //   topLevelItem(0)->setSelected(true);
        //   setCurrentItem( topLevelItem(0) );
        //}
    }

    if(bReload)
    {
        // Remember expanded items
        //TODO
        //QTreeWidgetItemIterator it( this );
        //while ( *it )
        //{
        //   DirMergeItem* pDMI = static_cast<DirMergeItem*>( *it );
        //   std::map<QString,t_ItemInfo>::iterator i = expandedDirsMap.find( pDMI->m_pMFI->subPath() );
        //   if ( i!=expandedDirsMap.end() )
        //   {
        //      t_ItemInfo& ii = i->second;
        //      pDMI->setExpanded( ii.bExpanded );
        //      //pDMI->m_pMFI->setMergeOperation( ii.eMergeOperation, false ); unsafe, might have changed
        //      pDMI->m_pMFI->m_bOperationComplete = ii.bOperationComplete;
        //      pDMI->setText( s_OpStatusCol, ii.status );
        //   }
        //   ++it;
        //}
    }
    else if(m_bUnfoldSubdirs)
    {
        m_pDirUnfoldAll->trigger();
    }

    return true;
1170 1171
}

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
inline QString DirectoryMergeWindow::getDirNameA() const
{
    return d->rootMFI()->getDirectoryInfo()->dirA().prettyAbsPath();
}
inline QString DirectoryMergeWindow::getDirNameB() const
{
    return d->rootMFI()->getDirectoryInfo()->dirB().prettyAbsPath();
}
inline QString DirectoryMergeWindow::getDirNameC() const
{
    return d->rootMFI()->getDirectoryInfo()->dirC().prettyAbsPath();
}
inline QString DirectoryMergeWindow::getDirNameDest() const
{
    return d->rootMFI()->getDirectoryInfo()->destDir().prettyAbsPath();
}
1188

1189 1190
void DirectoryMergeWindow::onExpanded()
{
1191
    resizeColumnToContents(s_NameCol);
1192 1193
}

1194 1195 1196 1197
void DirectoryMergeWindow::slotChooseAEverywhere()
{
    d->setAllMergeOperations(eCopyAToDest);
}
1198

1199 1200 1201 1202
void DirectoryMergeWindow::slotChooseBEverywhere()
{
    d->setAllMergeOperations(eCopyBToDest);
}
1203

1204 1205 1206 1207
void DirectoryMergeWindow::slotChooseCEverywhere()
{
    d->setAllMergeOperations(eCopyCToDest);
}
1208 1209 1210

void DirectoryMergeWindow::slotAutoChooseEverywhere()
{
Michael Reeves's avatar
Michael Reeves committed
1211
    e_MergeOperation eDefaultMergeOp = d->isThreeWay() ? eMergeABCToDest : d->m_bSyncMode ? eMergeToAB : eMergeABToDest;
1212
    d->setAllMergeOperations(eDefaultMergeOp);
1213 1214
}

1215 1216 1217 1218
void DirectoryMergeWindow::slotNoOpEverywhere()
{
    d->setAllMergeOperations(eNoOperation);
}
1219 1220 1221

void DirectoryMergeWindow::slotFoldAllSubdirs()
{
1222
    collapseAll();
1223 1224 1225 1226
}

void DirectoryMergeWindow::slotUnfoldAllSubdirs()
{
1227
    expandAll();
Joachim Eibl's avatar
Joachim Eibl committed
1228 1229 1230
}

// Merge current item (merge mode)
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
void DirectoryMergeWindow::slotCurrentDoNothing()
{
    d->setMergeOperation(currentIndex(), eNoOperation);
}
void DirectoryMergeWindow::slotCurrentChooseA()
{
    d->setMergeOperation(currentIndex(), d->m_bSyncMode ? eCopyAToB : eCopyAToDest);
}
void DirectoryMergeWindow::slotCurrentChooseB()
{
    d->setMergeOperation(currentIndex(), d->m_bSyncMode ? eCopyBToA : eCopyBToDest);
}
void DirectoryMergeWindow::slotCurrentChooseC()
{
    d->setMergeOperation(currentIndex(), eCopyCToDest);
}
1247 1248
void DirectoryMergeWindow::slotCurrentMerge()
{
Michael Reeves's avatar
Michael Reeves committed
1249
    bool bThreeDirs = d->isThreeWay();
1250
    d->setMergeOperation(currentIndex(), bThreeDirs ? eMergeABCToDest : eMergeABToDest);
1251
}
1252 1253 1254 1255
void DirectoryMergeWindow::slotCurrentDelete()
{
    d->setMergeOperation(currentIndex(), eDeleteFromDest);
}
Joachim Eibl's avatar
Joachim Eibl committed
1256
// Sync current item
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
void DirectoryMergeWindow::slotCurrentCopyAToB()
{
    d->setMergeOperation(currentIndex(), eCopyAToB);
}
void DirectoryMergeWindow::slotCurrentCopyBToA()
{
    d->setMergeOperation(currentIndex(), eCopyBToA);
}
void DirectoryMergeWindow::slotCurrentDeleteA()
{
    d->setMergeOperation(currentIndex(), eDeleteA);
}
void DirectoryMergeWindow::slotCurrentDeleteB()
{
    d->setMergeOperation(currentIndex(), eDeleteB);
}
void DirectoryMergeWindow::slotCurrentDeleteAAndB()
{
    d->setMergeOperation(currentIndex(), eDeleteAB);
}
void DirectoryMergeWindow::slotCurrentMergeToA()
{
    d->setMergeOperation(currentIndex(), eMergeToA);
}
void DirectoryMergeWindow::slotCurrentMergeToB()
{
    d->setMergeOperation(currentIndex(), eMergeToB);
}
void DirectoryMergeWindow::slotCurrentMergeToAAndB()
{
    d->setMergeOperation(currentIndex(), eMergeToAB);
}
1289 1290 1291 1292 1293 1294

void DirectoryMergeWindow::keyPressEvent(QKeyEvent* e)
{
    if((e->QInputEvent::modifiers() & Qt::ControlModifier) != 0)
    {
        MergeFileInfos* pMFI = d->getMFI(currentIndex());
Michael Reeves's avatar
Michael Reeves committed
1295
        if(pMFI == nullptr)
1296
            return;
1297

1298
        bool bThreeDirs = pMFI->getDirectoryInfo()->dirC().isValid();
1299
        bool bMergeMode = bThreeDirs || !d->m_bSyncMode;
1300
        bool bFTConflict = pMFI == nullptr ? false : pMFI->conflictingFileTypes();
1301 1302 1303 1304 1305

        if(bMergeMode)
        {
            switch(e->key())
            {
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
                case Qt::Key_1:
                    if(pMFI->existsInA())
                    {
                        slotCurrentChooseA();
                    }
                    return;
                case Qt::Key_2:
                    if(pMFI->existsInB())
                    {
                        slotCurrentChooseB();
                    }
                    return;
                case Qt::Key_3:
                    if(pMFI->existsInC())
                    {
                        slotCurrentChooseC();
                    }
                    return;
                case Qt::Key_Space:
                    slotCurrentDoNothing();
                    return;
                case Qt::Key_4:
                    if(!bFTConflict)
                    {
                        slotCurrentMerge();
                    }
                    return;
                case Qt::Key_Delete:
                    slotCurrentDelete();
                    return;
                default:
                    break;
1338 1339 1340 1341 1342 1343
            }
        }
        else
        {
            switch(e->key())
            {
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
                case Qt::Key_1:
                    if(pMFI->existsInA())
                    {
                        slotCurrentCopyAToB();
                    }
                    return;
                case Qt::Key_2:
                    if(pMFI->existsInB())
                    {
                        slotCurrentCopyBToA();
                    }
                    return;
                case Qt::Key_Space:
                    slotCurrentDoNothing();
                    return;
                case Qt::Key_4:
                    if(!bFTConflict)
                    {
                        slotCurrentMergeToAAndB();
                    }
                    return;
                case Qt::Key_Delete:
                    if(pMFI->existsInA() && pMFI->existsInB())
                        slotCurrentDeleteAAndB();
                    else if(pMFI->existsInA())
                        slotCurrentDeleteA();
                    else if(pMFI->existsInB())
                        slotCurrentDeleteB();
                    return;
                default:
                    break;
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
            }
        }
    }
    else if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter)
    {
        onDoubleClick(currentIndex());
        return;
    }

    QTreeView::keyPressEvent(e);
1385 1386 1387 1388
}

void DirectoryMergeWindow::focusInEvent(QFocusEvent*)
{
Michael Reeves's avatar
Michael Reeves committed
1389
    emit updateAvailabilities();
1390 1391 1392
}
void DirectoryMergeWindow::focusOutEvent(QFocusEvent*)
{
Michael Reeves's avatar
Michael Reeves committed
1393
    emit updateAvailabilities();
1394 1395
}

1396
void DirectoryMergeWindow::DirectoryMergeWindowPrivate::setAllMergeOperations(e_MergeOperation eDefaultOperation)
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
{
    if(KMessageBox::Yes == KMessageBox::warningYesNo(q,
                                                     i18n("This affects all merge operations."),
                                                     i18n("Changing All Merge Operations"),
                                                     KStandardGuiItem::cont(),
                                                     KStandardGuiItem::cancel()))
    {
        for(int i = 0; i < rowCount(); ++i)
        {
            calcSuggestedOperation(index(i, 0, QModelIndex()), eDefaultOperation);
        }
    }
}

1411
bool DirectoryMergeWindow::DirectoryMergeWindowPrivate::compareFilesAndCalcAges(MergeFileInfos& mfi, QStringList& errors)
1412 1413 1414 1415 1416
{
    std::map<QDateTime, int> dateMap;

    if(mfi.existsInA())
    {
1417
        dateMap[mfi.getFileInfoA()->lastModified()] = 0;
1418 1419 1420
    }
    if(mfi.existsInB())
    {
1421
        dateMap[mfi.getFileInfoB()->lastModified()] = 1;
1422 1423 1424
    }
    if(mfi.existsInC())
    {
1425
        dateMap[mfi.getFileInfoC()->lastModified()] = 2;
1426 1427 1428 1429
    }

    if(m_pOptions->m_bDmFullAnalysis)
    {
1430
        if((mfi.existsInA() && mfi.isDirA()) || (mfi.existsInB() && mfi.isDirB()) || (mfi.existsInC() && mfi.isDirC()))
1431 1432
        {
            // If any input is a directory, don't start any comparison.
1433 1434 1435
            mfi.m_bEqualAB = mfi.existsInA() && mfi.existsInB();
            mfi.m_bEqualAC = mfi.existsInA() && mfi.existsInC();
            mfi.m_bEqualBC = mfi.existsInB() && mfi.existsInC();
1436 1437 1438 1439
        }
        else
        {
            emit q->startDiffMerge(
1440 1441 1442
                mfi.existsInA() ? mfi.getFileInfoA()->absoluteFilePath() : QString(""),
                mfi.existsInB() ? mfi.getFileInfoB()->absoluteFilePath() : QString(""),
                mfi.existsInC() ? mfi.getFileInfoC()->absoluteFilePath() : QString(""),
1443
                "",
1444
                "", "", "", &mfi.diffStatus());
1445
            int nofNonwhiteConflicts = mfi.diffStatus().getNonWhitespaceConflicts();
1446 1447 1448 1449 1450 1451 1452 1453 1454

            if(m_pOptions->m_bDmWhiteSpaceEqual && nofNonwhiteConflicts == 0)
            {
                mfi.m_bEqualAB = mfi.existsInA() && mfi.existsInB();
                mfi.m_bEqualAC = mfi.existsInA() && mfi.existsInC();
                mfi.m_bEqualBC = mfi.existsInB() && mfi.existsInC();
            }
            else
            {
1455 1456 1457
                mfi.m_bEqualAB = mfi.diffStatus().isBinaryEqualAB();
                mfi.m_bEqualBC = mfi.diffStatus().isBinaryEqualBC();
                mfi.m_bEqualAC = mfi.diffStatus().isBinaryEqualAC();
1458 1459 1460 1461 1462
            }
        }
    }
    else
    {
1463
        bool bError = false;
1464 1465 1466
        QString eqStatus;
        if(mfi.existsInA() && mfi.existsInB())
        {
1467
            if(mfi.isDirA())
1468 1469
                mfi.m_bEqualAB = true;
            else
1470
                mfi.m_bEqualAB = fastFileComparison(*mfi.getFileInfoA(), *mfi.getFileInfoB(), bError, eqStatus);
1471 1472 1473
        }
        if(mfi.existsInA() && mfi.existsInC())
        {
1474
            if(mfi.isDirA())
1475 1476
                mfi.m_bEqualAC = true;
            else
1477
                mfi.m_bEqualAC = fastFileComparison(*mfi.getFileInfoA(), *mfi.getFileInfoC(), bError, eqStatus);
1478 1479 1480 1481 1482 1483 1484
        }
        if(mfi.existsInB() && mfi.existsInC())
        {
            if(mfi.m_bEqualAB && mfi.m_bEqualAC)
                mfi.m_bEqualBC = true;
            else
            {
1485
                if(mfi.isDirB())
1486 1487
                    mfi.m_bEqualBC = true;
                else
1488
                    mfi.m_bEqualBC = fastFileComparison(*mfi.getFileInfoB(), *mfi.getFileInfoC(), bError, eqStatus);
1489 1490
            }
        }
1491
        if(bError)
1492
        {
1493 1494 1495
            //Limit size of error list in memmory.
            if(errors.size() < 30)
                errors.append(eqStatus);
1496 1497
            return false;
        }
1498 1499 1500 1501 1502 1503
    }

    if(mfi.isLinkA() != mfi.isLinkB()) mfi.m_bEqualAB = false;
    if(mfi.isLinkA() != mfi.isLinkC()) mfi.m_bEqualAC = false;
    if(mfi.isLinkB() != mfi.isLinkC()) mfi.m_bEqualBC = false;

1504 1505 1506
    if(mfi.isDirA() != mfi.isDirB()) mfi.m_bEqualAB = false;
    if(mfi.isDirA() != mfi.isDirC()) mfi.m_bEqualAC = false;
    if(mfi.isDirB() != mfi.isDirC()) mfi.m_bEqualBC = false;
1507

1508
    Q_ASSERT(eNew == 0 && eMiddle == 1 && eOld == 2);
1509 1510 1511 1512 1513 1514 1515

    // The map automatically sorts the keys.
    int age = eNew;
    std::map<QDateTime, int>::reverse_iterator i;
    for(i = dateMap.rbegin(); i != dateMap.rend(); ++i)
    {
        int n = i->second;
Michael Reeves's avatar
Michael Reeves committed
1516
        if(n == 0 && mfi.getAgeA() == eNotThere)
1517
        {