updateview.cpp 32.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 
 *  Copyright (C) 1999-2001 Bernd Gehrmann
 *                          bernd@physik.hu-berlin.de
 *
 * This program may be distributed under the terms of the Q Public
 * License as defined by Trolltech AS of Norway and appearing in the
 * file LICENSE.QPL included in the packaging of this file.
 *
 * 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.
 */


#include <qstrlist.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <qheader.h>
#include <qstack.h>
#include <kapp.h>
#include <kdebug.h>
22
#include <kfileview.h>
23 24 25 26 27 28 29 30
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <klocale.h>
#include "misc.h"
#include "cvsdir.h"

#include <sys/stat.h>
#include <unistd.h>
31
#include <locale.h>
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <time.h>

#include "updateview.h"
#include "updateview.moc"


class UpdateDirItem : public ListViewItem
{
public:
    UpdateDirItem( UpdateView *parent, QString dirname );
    UpdateDirItem( UpdateDirItem *parent, QString dirname );
 
    QString dirPath();
    void syncWithDirectory();
    void syncWithEntries();
    void updateChildItem(QString name, UpdateView::Status status, bool isdir);
    void updateEntriesItem(QString name, UpdateView::Status status, bool isdir,
49
                           QString rev, QString tagname, time_t timestamp);
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
    virtual QString key(int col, bool) const;
    virtual QString text(int col) const;
    virtual void setOpen(bool o);
    virtual void setup();
 
    void maybeScanDir(bool recursive);

private:
    UpdateView *updateView() const
        { return static_cast<UpdateView*>(listView()); }
    void scanDirectory();
    
    QString m_dirname;
    bool m_opened;
};


class UpdateViewItem : public ListViewItem
{
public:
    UpdateViewItem( ListViewItem *parent, QString filename );

    QString filePath();
    UpdateView::Status status() const
        { return m_status; }
    QString revision() const
        { return m_revision; }
    bool undefinedState() const
    { return m_undefined; }
    
    virtual QString key(int col, bool) const;
    virtual QString text(int col) const;
    virtual void paintCell(QPainter *p, const QColorGroup &cg,
			   int col, int width, int align);

    void setStatus(UpdateView::Status status, UpdateView::Filter filter);
    void applyFilter(UpdateView::Filter filter);
    void setRevTag(QString rev, QString tag);
88
    void setTimestamp(time_t timestamp);
89 90 91 92 93 94 95 96 97 98
    void setUndefinedState(bool b)
    { m_undefined = b; }
    void markUpdated(bool laststage, bool success, UpdateView::Filter filter);
    
private:
    QString m_filename;
    QString m_revision;
    QString m_tag;
    bool m_undefined;
    UpdateView::Status m_status;
99
    time_t m_timestamp;
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
};


UpdateDirItem::UpdateDirItem( UpdateDirItem *parent, QString dirname )
    : ListViewItem(parent)
{
    setPixmap(0, SmallIcon("folder"));
    m_dirname = dirname;
    m_opened = false;
}
 
 
UpdateDirItem::UpdateDirItem( UpdateView *parent, QString dirname )
    : ListViewItem(parent)
{
    setPixmap(0, SmallIcon("folder"));
    m_dirname = dirname;
    m_opened = false;
}


QString UpdateDirItem::dirPath()
{
    UpdateDirItem *diritem = static_cast<UpdateDirItem*>(parent());

    return parent()? diritem->dirPath() + m_dirname + "/" : QString("");
}                      


/**
 * Update the status of an item; if it doesn't exist yet, create new one
 */
void UpdateDirItem::updateChildItem(QString name, UpdateView::Status status, bool isdir)
{
    kdDebug() << "Updating " << name << " in " << dirPath() << endl;
    for (ListViewItem *item = myFirstChild(); item;
	 item = item->myNextSibling() )
	{
	    if (item->text(0) == name)
		{
		    if (UpdateView::isDirItem(item))
                        ; // ignore
		    else
                        {
                            UpdateViewItem *viewitem = static_cast<UpdateViewItem*>(item);
                            UpdateView::Filter filter = updateView()->filter();
                            viewitem->setStatus(status, filter);
                        }
		    return;
		}
	}

    // Not found, make new entry
    if (isdir)
        ( new UpdateDirItem(this, name) )->maybeScanDir(true);
    else
        {
            UpdateViewItem *viewitem = new UpdateViewItem(this, name);
            UpdateView::Filter filter = updateView()->filter();
            viewitem->setStatus(status, filter);
        }
}


/**
 * Update the revision and tag of an item. Use status only to create
 * new items and for items which were NotInCVS.
 */
void UpdateDirItem::updateEntriesItem(QString name, UpdateView::Status status, bool isdir,
169
                                      QString rev, QString tagname, time_t timestamp)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
{
    for (ListViewItem *item = myFirstChild(); item;
	 item = item->myNextSibling() )
	{
	    if (item->text(0) == name)
		{
		    if (UpdateView::isDirItem(item))
                        ; // ignore
		    else
                        {
                            UpdateViewItem *viewitem = static_cast<UpdateViewItem*>(item);
                            if (viewitem->status() == UpdateView::NotInCVS ||
                                viewitem->status() == UpdateView::LocallyRemoved ||
                                status == UpdateView::LocallyAdded ||
                                status == UpdateView::LocallyRemoved ||
                                status == UpdateView::Conflict)
                                {
                                    UpdateView::Filter filter = updateView()->filter();
                                    viewitem->setStatus(status, filter);
                                }
                            viewitem->setRevTag(rev, tagname);
191
                            viewitem->setTimestamp(timestamp);
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
                        }
		    return;
		}
	}

    kdDebug() << "new entries item for " << name << endl;
    // Not found, make new entry
    if (isdir)
        ( new UpdateDirItem(this, name) )->maybeScanDir(true);
    else
        {
            UpdateViewItem *viewitem = new UpdateViewItem(this, name);
            UpdateView::Filter filter = updateView()->filter();
            viewitem->setStatus(status, filter);
        }
}


void UpdateDirItem::scanDirectory()
{
    if (!dirPath().isEmpty() && !QFile::exists(dirPath()))
        return;

    CvsDir dir( dirPath() );
    
    const QFileInfoList *files = dir.entryInfoList();
    if (files)
	{
	    QFileInfoListIterator it(*files);
	    for (; it.current(); ++it)
		{
		    if ( it.current()->isDir() )
			(void) new UpdateDirItem(this, it.current()->fileName());
		    else
			(void) new UpdateViewItem(this, it.current()->fileName());
		}
	}
}


static const char *lastModifiedStr(const char *fname)
{
    struct stat st;
    if (lstat(fname, &st) != 0)
	return "";
    struct tm *tm_p = gmtime(&st.st_mtime);
    char *p = asctime(tm_p);
    p[24] = '\0';
    return p;
}


// Format of the CVS/Entries file:
//   /NAME/REVISION/TIMESTAMP[+CONFLICT]/OPTIONS/TAGDATE

void UpdateDirItem::syncWithEntries()
{
    char buf[512];
    QString name, rev, timestamp, options, tagdate;
    UpdateView::Status status;

    FILE *f = fopen(QString(dirPath() + QString("CVS/Entries")).latin1(), "r");
    if (!f)
	return;

    while (fgets(buf, sizeof buf, f))
	{
            char *nextp, *p = buf;
            bool isdir = (*p == 'D');
            if (isdir)
                ++p;
	    if (*p != '/')
		continue;
            ++p;
	    if ( (nextp = strchr(p, '/')) == 0)
		continue;
	    *nextp = '\0';
	    name = QString(p); p = nextp+1;
	    if ( (nextp = strchr(p, '/')) == 0)
		continue;
	    *nextp = '\0';
	    rev = QString(p); p = nextp+1;
	    if ( (nextp = strchr(p, '/')) == 0)
		continue;
	    *nextp = '\0';
	    timestamp = QString(p); p = nextp+1;
	    if ( (nextp = strchr(p, '/')) == 0)
		continue;
	    *nextp = '\0';
	    options = QString(p); p = nextp+1;
	    if ( (nextp = strchr(p, '\n')) == 0)
		continue;
	    *nextp = '\0';
	    tagdate = QString(p); p = nextp+1;

	    if (rev == "0")
		status = UpdateView::LocallyAdded;
	    else if (rev.length() > 2 && rev[0] == '-')
                {
                    status = UpdateView::LocallyRemoved;
                    rev.remove(0, 1);
                }
	    else if (timestamp.find('+') != -1)
295 296 297 298
                {
		    status = UpdateView::Conflict;
		    timestamp.truncate(timestamp.find('+'));
                }
299 300 301 302 303
	    else if (timestamp != lastModifiedStr(QString(dirPath() + name).latin1()))
		status = UpdateView::LocallyModified;
	    else
		status = UpdateView::Unknown;

304 305 306 307 308 309 310 311 312 313
	    // Convert timestamp into a time.
	    char *oldLocale;
	    struct tm tmp;
	    time_t time;

	    oldLocale = setlocale(LC_TIME, "C");
	    strptime(timestamp, "%c" , &tmp);
	    setlocale(LC_TIME, oldLocale);
	    time = mktime(&tmp);
	    updateEntriesItem(name, status, isdir, rev, tagdate, time);
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
	}
    fclose(f);
}


void UpdateDirItem::syncWithDirectory()
{
    // Do not use CvsDir here, because CVS/Entries may
    // contain files which are in .cvsignore (stupid
    // idea, but that's possible...)
    QDir dir( dirPath(), QString::null, QDir::Name,
              QDir::Files|QDir::Hidden|QDir::NoSymLinks );

    const QFileInfoList *files = dir.exists()? dir.entryInfoList() : 0;

    for (ListViewItem *item = myFirstChild(); item;
         item = item->myNextSibling() )
        {
            // Look if file still exists. We never remove directories!
            bool exists = false;
            if (UpdateView::isDirItem(item))
                exists = true;
            else if (files)
                {
                    QFileInfoListIterator it(*files);
                    for ( ; it.current(); ++it)
                        if (it.current()->fileName() == item->text(0))
                            {
                                exists = true;
                                break;
                            }
                }
            if (!exists)
                {
                    UpdateViewItem *viewitem = static_cast<UpdateViewItem*>(item);
                    UpdateView::Filter filter = updateView()->filter();
                    viewitem->setStatus(UpdateView::Removed, filter);
                    viewitem->setRevTag("", "");
                }
        }
}


/**
 * Read in the content of the directory. If recursive is false, this
 * is shallow, otherwise all child directories are scanned recursively.
 */
void UpdateDirItem::maybeScanDir(bool recursive)
{
    if (!m_opened)
        {
            m_opened = true;
            scanDirectory();
            syncWithEntries();
        }

    if (recursive)
        {
            for ( ListViewItem *item = myFirstChild(); item;
                  item = item->myNextSibling() )
                if (UpdateView::isDirItem(item))
                    static_cast<UpdateDirItem*>(item)->maybeScanDir(true);
        }
}


void UpdateDirItem::setOpen(bool o)
{
    if ( o )
        maybeScanDir(false);
    
    QListViewItem::setOpen( o );
}
 

QString UpdateDirItem::key(int col, bool) const
{
    static QString tmp;
    switch (col)
	{
	case 0: //return m_dirname;
	case 1: return tmp = QString("0") + m_dirname;
        default:return "";
	}
}


QString UpdateDirItem::text(int col) const
{
    switch (col)
	{
	case 0:  return m_dirname;
	default: return "";
	}
}       


void UpdateDirItem::setup()
{
    setExpandable(true);
    QListViewItem::setup();
}
 

UpdateViewItem::UpdateViewItem( ListViewItem *parent, QString filename )
    : ListViewItem(parent) 
{
    m_status = UpdateView::NotInCVS;
    m_filename = filename;
    m_revision = "";
    m_tag = "";
    m_undefined = false;
}


QString UpdateViewItem::filePath()
{
    UpdateDirItem *diritem = static_cast<UpdateDirItem*>(parent());
    return diritem->dirPath() + m_filename;
}                      


void UpdateViewItem::setStatus(UpdateView::Status newstatus, UpdateView::Filter filter)
{
    if (newstatus != m_status)
        {
            m_status = newstatus;
            applyFilter(filter);
            if (visible())
                repaint();
        }
    m_undefined = false;
}


void UpdateViewItem::applyFilter(UpdateView::Filter filter)
{
    bool hide = false;
    if (filter & UpdateView::OnlyDirectories)
        hide = true;
    if ((filter & UpdateView::NoUpToDate) && (m_status == UpdateView::UpToDate))
        hide = true;
    if ((filter & UpdateView::NoRemoved) && (m_status == UpdateView::Removed))
	hide = true;
    setVisible(!hide);
}


void UpdateViewItem::setRevTag(QString rev, QString tag)
{
    m_revision = rev;

    if (tag.length() == 20 && tag[0] == 'D' && tag[5] == '.'
        && tag[8] == '.' && tag[11] == '.' && tag[14] == '.'
        && tag[17] == '.')
        {
            m_tag = tag.mid(1, 4);
            m_tag += "/";
            m_tag += tag.mid(6, 2);
            m_tag += "/";
            m_tag += tag.mid(9, 2);
            m_tag += " ";
            m_tag += tag.mid(12, 2);
            m_tag += ":";
            m_tag += tag.mid(15, 2);
            m_tag += ":";
            m_tag += tag.mid(18, 2);
        }
    else if (tag.length() > 1 && tag[0] == 'T')
        m_tag = tag.mid(1, tag.length()-1);
    else
        m_tag = tag;

    if (visible())
        {
            widthChanged();
            repaint();
        }
}

494 495 496 497
void UpdateViewItem::setTimestamp(time_t timestamp)
{
    m_timestamp = timestamp;
}
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

void UpdateViewItem::markUpdated(bool laststage, bool success, UpdateView::Filter filter)
{
    UpdateView::Status newstatus = m_status;
    
    if (laststage)
        {
            if (undefinedState() && m_status != UpdateView::NotInCVS)
                newstatus = success? UpdateView::UpToDate : UpdateView::Unknown;
            setStatus(newstatus, filter);
        }
    else
        setUndefinedState(true);
}


QString UpdateViewItem::key(int col, bool) const
{
    static QString tmp;
    QString prefix;

    switch (col)
	{
	case 0:
            // Put ordinary files behind all directories
            return tmp = QString("1") + m_filename;
	case 1:
	    // We want to have a kind of priority order when
	    // sorted by 'status'
	    switch (m_status)
		{
		case UpdateView::Conflict:
		    prefix = "1"; break;
		case UpdateView::LocallyAdded:
		    prefix = "2"; break;
		case UpdateView::LocallyRemoved:
		    prefix = "3"; break;
		case UpdateView::LocallyModified:
		    prefix = "4"; break;
		case UpdateView::Updated:
		case UpdateView::NeedsUpdate:
		case UpdateView::Patched:
                case UpdateView::Removed:
		case UpdateView::NeedsPatch:
		case UpdateView::NeedsMerge:
		    prefix = "5"; break;
		case UpdateView::NotInCVS:
		    prefix = "6"; break;
		default:  prefix = "7"; 
		}
	    return tmp = prefix + m_filename;
        case 2:
            return m_revision; // First approximation...
        case 3:
            return m_tag;
553 554 555 556 557
        case 4:
    //static QString sortingKey( const QString& value, bool isDir, int sortSpec);
    //static QString sortingKey( KIO::filesize_t value, bool isDir,int sortSpec);
            //return m_timestamp.toString();
	    return KFileView::sortingKey(m_timestamp, false, QDir::Time);
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
	default:
	    return "";
	}
}


QString UpdateViewItem::text(int col) const
{
    switch (col)
	{
	case 0:
	    return m_filename;
	case 1:
	    switch (m_status)
		{
		case UpdateView::LocallyModified:
		    return i18n("Locally Modified"); 
		case UpdateView::LocallyAdded:
		    return i18n("Locally Added"); 
		case UpdateView::LocallyRemoved:
		    return i18n("Locally Removed"); 
		case UpdateView::NeedsUpdate:
		    return i18n("Needs Update"); 
		case UpdateView::NeedsPatch:
		    return i18n("Needs Patch"); 
		case UpdateView::NeedsMerge:
		    return i18n("Needs Merge"); 
		case UpdateView::UpToDate:
		    return i18n("Up to date");
		case UpdateView::Conflict:
		    return i18n("Conflict");
		case UpdateView::Updated:
		    return i18n("Updated"); 
		case UpdateView::Patched:
		    return i18n("Patched"); 
		case UpdateView::Removed:
		    return i18n("Removed"); 
		case UpdateView::NotInCVS:
		    return i18n("Not in CVS");
		default:  return i18n("Unknown");
		}
	case 2:
	    return m_revision;
        case 3:
            return m_tag;
603 604 605 606 607 608 609
        case 4:
	    {
		QDateTime timestamp;

		timestamp.setTime_t(m_timestamp);
                return timestamp.toString(Qt::LocalDate);
	    }
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
	default:
	    return "";
	}
}       



void UpdateViewItem::paintCell(QPainter *p, const QColorGroup &cg,
			       int col, int width, int align)
{
    QColor color =
	(m_status == UpdateView::Conflict)? QColor(255, 100, 100)
	: (m_status == UpdateView::LocallyModified ||
	   m_status == UpdateView::LocallyAdded  ||
	   m_status == UpdateView::LocallyRemoved)? QColor(190, 190, 237)
	: (m_status == UpdateView::Patched ||
	   m_status == UpdateView::Updated ||
           m_status == UpdateView::Removed ||
	   m_status == UpdateView::NeedsPatch ||
	   m_status == UpdateView::NeedsUpdate)? QColor(255, 240, 190)
	: cg.base();
    QColorGroup mycg(cg);
    mycg.setBrush(QColorGroup::Base, color);

    QListViewItem::paintCell(p, mycg, col, width, align);
}


UpdateView::UpdateView(QWidget *parent, const char *name)
    : ListView(parent, name)
{
    setAllColumnsShowFocus(true);
    setShowSortIndicator(true);
    setSelectionMode(Extended);

    addColumn(i18n("File name"));
    addColumn(i18n("Status"));
    addColumn(i18n("Revision"));
    addColumn(i18n("Tag/Date"));
649
    addColumn(i18n("Timestamp"));
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

    QFontMetrics fm( fontMetrics() );

    int width = 0;
    width = QMAX(width, fm.width(i18n("Updated")));
    width = QMAX(width, fm.width(i18n("Patched")));
    width = QMAX(width, fm.width(i18n("Removed")));
    width = QMAX(width, fm.width(i18n("Needs Update")));
    width = QMAX(width, fm.width(i18n("Needs Patch")));
    width = QMAX(width, fm.width(i18n("Needs Merge")));
    width = QMAX(width, fm.width(i18n("Locally Added")));
    width = QMAX(width, fm.width(i18n("Locally Removed")));
    width = QMAX(width, fm.width(i18n("Locally Modified")));
    width = QMAX(width, fm.width(i18n("Up to date")));
    width = QMAX(width, fm.width(i18n("Conflict")));
    width = QMAX(width, fm.width(i18n("Not in CVS")));
    width = QMAX(width, fm.width(i18n("Unknown")));
    
    setColumnWidth(1, width+5);
    setPreferredColumn(0);
    setFilter(NoFilter);

    connect( this, SIGNAL(doubleClicked(QListViewItem*)),
             this, SLOT(itemExecuted(QListViewItem*)) );
    connect( this, SIGNAL(returnPressed(QListViewItem*)),
             this, SLOT(itemExecuted(QListViewItem*)) );
    connect( this, SIGNAL(rightButtonPressed(QListViewItem*, const QPoint&, int)),
             this, SIGNAL(contextMenu()) );
}


UpdateView::~UpdateView()
{}


bool UpdateView::isDirItem(QListViewItem *item)
{
    return qstrcmp(item->text(1).latin1(), "") == 0;
}


void UpdateView::setFilter(Filter filter)
{
    filt = filter;
    QStack<ListViewItem> s;
Laurent Montel's avatar
Laurent Montel committed
695
    QPtrList<ListViewItem> l;
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

    ListViewItem *item = static_cast<ListViewItem*>(firstChild());
    // Hack: Since applyFilter() changes the whole child structure, we have
    // to collect all children of one item in a list first, and then
    // iterator though the list
    while (item)
        {
            for (ListViewItem *childItem1 = item->myFirstChild();
                 childItem1; childItem1 = childItem1->myNextSibling())
                l.append(childItem1);

            for (ListViewItem *childItem2 = l.first();
                 childItem2; childItem2 = l.next())
                {
                    if (childItem2->myFirstChild())
                        s.push(childItem2);
                    
                    if (!isDirItem(childItem2))
                        {
                            static_cast<UpdateViewItem*>(childItem2)->applyFilter(filt);
                        }
                }

            l.clear();
            item = s.pop();
        }
    setSorting(sortColumn(), sortAscending());
}


UpdateView::Filter UpdateView::filter() const
{
    return filt;
}


bool UpdateView::hasSingleSelection()
{
    bool selfound = false;
    QStack<QListViewItem> s;

    for ( QListViewItem *item = firstChild(); item;
	  item = item->nextSibling()? item->nextSibling() : s.pop() )
	{
	    if (item->firstChild())
                s.push(item->firstChild());

	    if (item->isSelected())
		{
		    if (selfound || item->isExpandable())
			return false;
		    selfound = true;
		}
	}
    return selfound;
}


void UpdateView::getSingleSelection(QString *filename, QString *revision)
{
    QStack<QListViewItem> s;

    for ( QListViewItem *item = firstChild(); item;
	  item = item->nextSibling()? item->nextSibling() : s.pop() )
	{
	    if (item->firstChild())
		s.push(item->firstChild());
	    else if (item->isSelected())
                {
                    UpdateViewItem *viewitem = static_cast<UpdateViewItem*>(item);
                    *filename = viewitem->filePath();
                    if (revision)
                        *revision = viewitem->revision();
                }
	}
}


QStringList UpdateView::multipleSelection()
{
    QStringList res;
    QStack<QListViewItem> s;

    for ( QListViewItem *item = firstChild(); item;
          item = item->nextSibling()? item->nextSibling() : s.pop() )
        {
            if (item->firstChild())
                s.push(item->firstChild());

            if (item->isSelected())
                {
                    if (isDirItem(item))
                        {
                            QString dirpath = static_cast<UpdateDirItem*>(item)->dirPath();
                            if (!dirpath.isEmpty())
                                dirpath.truncate(dirpath.length()-1);
                            else
                                dirpath = ".";
                            res.append(dirpath);
                        }
                    else
                        res.append( static_cast<UpdateViewItem*>(item)->filePath() );
                }
        }
    return res;
}


QStringList UpdateView::fileSelection()
{
    QStringList res;
    QStack<QListViewItem> s;

    for ( QListViewItem *item = firstChild(); item;
          item = item->nextSibling()? item->nextSibling() : s.pop() )
        {
            if (item->firstChild())
                s.push(item->firstChild());

            if (item->isSelected() && !isDirItem(item))
                res.append( static_cast<UpdateViewItem*>(item)->filePath() );
        }
    return res;
}


void UpdateView::unfoldTree()
{
    QApplication::setOverrideCursor(waitCursor);
    
    QStack<QListViewItem> s;
    for ( QListViewItem *item = firstChild(); item;
	  item = item->nextSibling()? item->nextSibling() : s.pop() )
	{
	    if (isDirItem(item))
                item->setOpen(true);
            if (item->firstChild())
		s.push(item->firstChild());
            qApp->processEvents();
	}

    triggerUpdate();    
    QApplication::restoreOverrideCursor();
}


void UpdateView::foldTree()
{
    QStack<QListViewItem> s;
    for ( QListViewItem *item = firstChild(); item;
	  item = item->nextSibling()? item->nextSibling() : s.pop() )
	{
	    if (isDirItem(item) && item != firstChild())
                item->setOpen(false);
            if (item->firstChild())
		s.push(item->firstChild());
	}

    triggerUpdate();    
}


/**
 * Clear the tree view and insert the directory dirname
 * into it as the new root item
 */
void UpdateView::openDirectory(QString dirname)
{
    clear();
    UpdateDirItem *item = new UpdateDirItem(this, dirname);
    item->setOpen(true);
    setCurrentItem(item);
    setSelected(item, true);
}


/**
 * Start a job. We want to be able to change the status field
 * correctly afterwards, so we have to remember the current
 * selection (which the user may change during the update).
 * In the recursive case, we collect all relevant directories.
 * Furthermore, we have to change the items to undefined state.
 */
void UpdateView::prepareJob(bool recursive, Action action)
{
    act = action;

    // Scan recursively all entries - there's no way around this here
    if (recursive)
        static_cast<UpdateDirItem*>(firstChild())->maybeScanDir(true);
    
    rememberSelection(recursive);
    if (act != Add)
        markUpdated(false, false);
}


/**
 * Finishes a job. What we do depends a bit on
 * whether the command was successful or not.
 */
void UpdateView::finishJob(bool success)
{
    if (act != Add)
        markUpdated(true, success);
    syncSelection();
}


/**
 * Marking non-selected items in a directory updated (as a consequence
 * of not appearing in 'cvs update' output) is done in two steps: In the
 * first, they are marked as 'indefinite', so that their status on the screen
 * isn't misrepresented. In the second step, they are either set
 * to 'UpToDate' (success=true) or 'Unknown'.
 */
void UpdateView::markUpdated(bool laststage, bool success)
{
Laurent Montel's avatar
Laurent Montel committed
914
    QPtrListIterator<ListViewItem> it(relevantSelection);
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
    for ( ; it.current(); ++it)
        if (isDirItem(it.current()))
            {
                for (ListViewItem *item = it.current()->myFirstChild(); item;
                     item = item->myNextSibling() )
                    if (!isDirItem(item))
                        {
                            UpdateViewItem *viewitem = static_cast<UpdateViewItem*>(item);
                            viewitem->markUpdated(laststage, success, filter());
                        }
            }
        else
            {
                UpdateViewItem *viewitem = static_cast<UpdateViewItem*>(it.current());
                viewitem->markUpdated(laststage, success, filter());
            }
}


/**
 * Remember the selection, see prepareJob()
 */
void UpdateView::rememberSelection(bool recursive)
{
    // Collect all selected dir and file items into relevantSelection

Laurent Montel's avatar
Laurent Montel committed
941
    QPtrList<ListViewItem> shallowItems, deepItems;
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

    QStack<QListViewItem> s;
    for ( QListViewItem *item = firstChild(); item;
	  item = item->nextSibling()? item->nextSibling() : s.pop() )
	{
            if (item->firstChild())
                s.push(item->firstChild());
            if (isSelected(item))
                shallowItems.append(static_cast<ListViewItem*>(item));
	}

    // In the recursive case, we add all directories from the hierarchies
    // under the selected directories.
    
    if (recursive)
        {
Laurent Montel's avatar
Laurent Montel committed
958
            QPtrListIterator<ListViewItem> it(shallowItems);
959 960 961 962 963 964 965 966 967 968 969 970 971 972
            for ( ; it.current(); ++it)
                if (isDirItem(it.current()))
                    for ( QListViewItem *item = it.current()->firstChild(); item;
                          item = item->nextSibling()? item->nextSibling() : s.pop() )
                        {
                            if (item->firstChild())
                                s.push(item->firstChild());
                            if (isDirItem(item))
                                deepItems.append(static_cast<ListViewItem*>(item));
                        }
        }

#if 0
    DEBUGOUT("Deep:");
Laurent Montel's avatar
Laurent Montel committed
973
    QPtrListIterator<ListViewItem> it42(deepItems);
974 975 976
    for (; it42.current(); ++it42)
        DEBUGOUT("  " << (*it42)->text(0));
    DEBUGOUT("Shallow:");
Laurent Montel's avatar
Laurent Montel committed
977
    QPtrListIterator<ListViewItem> it43(shallowItems);
978 979 980 981 982 983 984
    for (; it43.current(); ++it43)
        DEBUGOUT("  " << (*it43)->text(0));
#endif
    
    // Collect everything together, and avoid duplicates:
    
    relevantSelection.clear();
Laurent Montel's avatar
Laurent Montel committed
985
    QPtrListIterator<ListViewItem> it1(shallowItems);
986 987 988
    for ( ; it1.current(); ++it1)
        if (!relevantSelection.contains(it1.current()))
            relevantSelection.append(it1.current());
Laurent Montel's avatar
Laurent Montel committed
989
    QPtrListIterator<ListViewItem> it2(deepItems);
990 991 992 993 994 995
    for ( ; it2.current(); ++it2)
        if (!relevantSelection.contains(it2.current()))
            relevantSelection.append(it2.current());

#if 0
    DEBUGOUT("Relevant:");
Laurent Montel's avatar
Laurent Montel committed
996
    QPtrListIterator<ListViewItem> it44(relevantSelection);
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    for (; it44.current(); ++it44)
        DEBUGOUT("  " << (*it44)->text(0));
    DEBUGOUT("End");
#endif
}


/**
 * Use the remembered selection to resynchronize
 * with the actual directory and Entries content.
 */
void UpdateView::syncSelection()
{
Laurent Montel's avatar
Laurent Montel committed
1010
    QPtrList<UpdateDirItem> dirs;
1011
    
Laurent Montel's avatar
Laurent Montel committed
1012
    QPtrListIterator<ListViewItem> it1(relevantSelection);
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    for ( ; it1.current(); ++it1)
	{
            UpdateDirItem *diritem = 0;
            if (isDirItem(it1.current()))
                diritem = static_cast<UpdateDirItem*>(it1.current());
            else if (it1.current()->parent())
                diritem = static_cast<UpdateDirItem*>(it1.current()->parent());
            if (diritem && !dirs.contains(diritem))
                dirs.append(diritem);
        }

    QApplication::setOverrideCursor(waitCursor);
    
Laurent Montel's avatar
Laurent Montel committed
1026
    QPtrListIterator<UpdateDirItem> it2(dirs);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    for ( ; it2.current(); ++it2)
	{
            it2.current()->syncWithDirectory();
            it2.current()->syncWithEntries();
            qApp->processEvents();
        }
    
    QApplication::restoreOverrideCursor();
}


/**
 * Process one line from the output of 'cvs update'. If parseAsStatus
 * is true, it is assumed that the output is from a command
 * 'cvs update -n', i.e. cvs actually changes no files.
 */
void UpdateView::processUpdateLine(QString str)
{
    if (str.length() > 2 && str[1] == ' ')
        {
            QChar statuschar = str[0];
            Status status = UpdateView::Unknown;
            if (statuschar == 'C')
                status = UpdateView::Conflict;
            else if (statuschar == 'A')
                status = UpdateView::LocallyAdded;
            else if (statuschar == 'R')
                status = UpdateView::LocallyRemoved;
            else if (statuschar == 'M')
                status = UpdateView::LocallyModified;
            else if (statuschar == 'U')
                status = (act==UpdateNoAct)?
                    UpdateView::NeedsUpdate : UpdateView::Updated;
            else if (statuschar == 'P')
                status = (act==UpdateNoAct)?
                    UpdateView::NeedsPatch : UpdateView::Patched;
            else if (statuschar == '?')
                status = UpdateView::NotInCVS;
            else
                return;
            updateItem(str.right(str.length()-2), status, false);
        }
#if 0
    else if (str.left(21) == "cvs server: Updating " ||
             str.left(21) == "cvs update: Updating ")
        updateItem(str.right(str.length()-21), Unknown, true);
#endif
}


void UpdateView::updateItem(const QString &name, Status status, bool isdir)
{
    // bla -> dirpath = "", filename = "bla"
    // bla/foo -> dirpath = "bla/", filename = "foo"

    if (isdir && name == ".")
        return;
    
    QFileInfo fi(name);
    QString dirpath(fi.dirPath());
    QString fileName(fi.fileName());

    if (dirpath == ".") 
    	dirpath = "";
    else
	dirpath += '/';

    UpdateDirItem *longestmatch = 0;
    QStack<QListViewItem> s;
    for ( ListViewItem *item = static_cast<ListViewItem*>(firstChild()); item;
	  item = item->myNextSibling()? item->myNextSibling() : static_cast<ListViewItem*>(s.pop()) )
	{
	    if (UpdateView::isDirItem(item))
		{
		    UpdateDirItem *diritem = static_cast<UpdateDirItem*>(item);
		    if (diritem->dirPath() == dirpath)
			{
			    diritem->updateChildItem(fileName, status, isdir);
			    return;
			}
                    else if (!diritem->dirPath().isEmpty() && dirpath.startsWith(diritem->dirPath())
                             && (!longestmatch || diritem->dirPath().length() > longestmatch->dirPath().length()))
                        longestmatch = diritem;
                    
                    if (item->myFirstChild())
                        s.push(item->myFirstChild());
		}
	}

    if (!longestmatch)
        {
            kdDebug() << "no match: " << dirname << endl;
            return;
        }
    // Item doesn't belong any existing directory in the tree, so we have to create
    // the missing leaves. longestmatch is the directory item where we have to attach
    kdDebug() << "longest match: " << longestmatch->dirPath() << endl;
    kdDebug() << "leaves: " <<  dirpath.mid(longestmatch->dirPath().length()) << endl;
    QStringList leaves = QStringList::split('/', dirpath.mid(longestmatch->dirPath().length()));
    for (int i=0; i < leaves.count(); ++i)
        {
            QString newFileName = longestmatch->dirPath();
            for (int j=0; j < i; ++j)
                {
                    newFileName += leaves[j];
                    newFileName += '/';
                }
            newFileName += leaves[i];
            kdDebug() << "add missing " << newFileName << endl;
            updateItem(newFileName, Unknown, true);
        }
    // Recursive, but now it should work
    updateItem(name, status, isdir);
}


void UpdateView::keyPressEvent(QKeyEvent *e)
{
    if (e->key() == KGlobalSettings::contextMenuKey())
        emit contextMenu();
    else
        ListView::keyPressEvent(e);
}


void UpdateView::itemExecuted(QListViewItem *item)
{
    if (!isDirItem(item))
        emit fileOpened(static_cast<UpdateViewItem*>(item)->filePath());
}

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