]> git.sesse.net Git - kdenlive/blob - src/archivewidget.cpp
use const'ref
[kdenlive] / src / archivewidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2011 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "archivewidget.h"
22 #include "titlewidget.h"
23
24 #include <KLocale>
25 #include <KDiskFreeSpaceInfo>
26 #include <KUrlRequester>
27 #include <KFileDialog>
28 #include <KMessageBox>
29 #include <KGuiItem>
30 #include <KIO/NetAccess>
31 #include <KTar>
32 #include <KDebug>
33 #include <KApplication>
34 #include <kio/directorysizejob.h>
35 #if KDE_IS_VERSION(4,7,0)
36 #include <KMessageWidget>
37 #endif
38
39 #include <QTreeWidget>
40 #include <QtConcurrentRun>
41 #include "projectsettings.h"
42
43
44 ArchiveWidget::ArchiveWidget(const QString &projectName, const QDomDocument &doc, const QList <DocClipBase*> &list, const QStringList &luma_list, QWidget * parent) :
45         QDialog(parent)
46         , m_requestedSize(0)
47         , m_copyJob(NULL)
48         , m_name(projectName.section('.', 0, -2))
49         , m_doc(doc)
50         , m_temp(NULL)
51         , m_abortArchive(false)
52         , m_extractMode(false)
53         , m_progressTimer(NULL)
54         , m_extractArchive(NULL)
55         , m_missingClips(0)
56 {
57     setAttribute(Qt::WA_DeleteOnClose);
58     setupUi(this);
59     setWindowTitle(i18n("Archive Project"));
60     archive_url->setUrl(KUrl(QDir::homePath()));
61     connect(archive_url, SIGNAL(textChanged(QString)), this, SLOT(slotCheckSpace()));
62     connect(this, SIGNAL(archivingFinished(bool)), this, SLOT(slotArchivingFinished(bool)));
63     connect(this, SIGNAL(archiveProgress(int)), this, SLOT(slotArchivingProgress(int)));
64     connect(proxy_only, SIGNAL(stateChanged(int)), this, SLOT(slotProxyOnly(int)));
65
66     // Setup categories
67     QTreeWidgetItem *videos = new QTreeWidgetItem(files_list, QStringList() << i18n("Video clips"));
68     videos->setIcon(0, KIcon("video-x-generic"));
69     videos->setData(0, Qt::UserRole, "videos");
70     videos->setExpanded(false);
71     QTreeWidgetItem *sounds = new QTreeWidgetItem(files_list, QStringList() << i18n("Audio clips"));
72     sounds->setIcon(0, KIcon("audio-x-generic"));
73     sounds->setData(0, Qt::UserRole, "sounds");
74     sounds->setExpanded(false);
75     QTreeWidgetItem *images = new QTreeWidgetItem(files_list, QStringList() << i18n("Image clips"));
76     images->setIcon(0, KIcon("image-x-generic"));
77     images->setData(0, Qt::UserRole, "images");
78     images->setExpanded(false);
79     QTreeWidgetItem *slideshows = new QTreeWidgetItem(files_list, QStringList() << i18n("Slideshow clips"));
80     slideshows->setIcon(0, KIcon("image-x-generic"));
81     slideshows->setData(0, Qt::UserRole, "slideshows");
82     slideshows->setExpanded(false);
83     QTreeWidgetItem *texts = new QTreeWidgetItem(files_list, QStringList() << i18n("Text clips"));
84     texts->setIcon(0, KIcon("text-plain"));
85     texts->setData(0, Qt::UserRole, "texts");
86     texts->setExpanded(false);
87     QTreeWidgetItem *playlists = new QTreeWidgetItem(files_list, QStringList() << i18n("Playlist clips"));
88     playlists->setIcon(0, KIcon("video-mlt-playlist"));
89     playlists->setData(0, Qt::UserRole, "playlist");
90     playlists->setExpanded(false);
91     QTreeWidgetItem *others = new QTreeWidgetItem(files_list, QStringList() << i18n("Other clips"));
92     others->setIcon(0, KIcon("unknown"));
93     others->setData(0, Qt::UserRole, "others");
94     others->setExpanded(false);
95     QTreeWidgetItem *lumas = new QTreeWidgetItem(files_list, QStringList() << i18n("Luma files"));
96     lumas->setIcon(0, KIcon("image-x-generic"));
97     lumas->setData(0, Qt::UserRole, "lumas");
98     lumas->setExpanded(false);
99     
100     QTreeWidgetItem *proxies = new QTreeWidgetItem(files_list, QStringList() << i18n("Proxy clips"));
101     proxies->setIcon(0, KIcon("video-x-generic"));
102     proxies->setData(0, Qt::UserRole, "proxy");
103     proxies->setExpanded(false);
104     
105     // process all files
106     QStringList allFonts;
107     KUrl::List fileUrls;
108     QStringList fileNames;
109     QStringList extraImageUrls;
110     QStringList otherUrls;
111     generateItems(lumas, luma_list);
112
113     QMap <QString, QString> slideUrls;
114     QMap <QString, QString> audioUrls;
115     QMap <QString, QString>videoUrls;
116     QMap <QString, QString>imageUrls;
117     QMap <QString, QString>playlistUrls;
118     QMap <QString, QString>proxyUrls;
119
120     for (int i = 0; i < list.count(); ++i) {
121         DocClipBase *clip = list.at(i);
122         CLIPTYPE t = clip->clipType();
123         QString id = clip->getId();
124         if (t == SLIDESHOW) {
125             KUrl slideUrl = clip->fileURL();
126             //TODO: Slideshow files
127             slideUrls.insert(id, slideUrl.path());
128         }
129         else if (t == IMAGE) imageUrls.insert(id, clip->fileURL().path());
130         else if (t == TEXT) {
131             QStringList imagefiles = TitleWidget::extractImageList(clip->getProperty("xmldata"));
132             QStringList fonts = TitleWidget::extractFontList(clip->getProperty("xmldata"));
133             extraImageUrls << imagefiles;
134             allFonts << fonts;
135         } else if (t == PLAYLIST) {
136             playlistUrls.insert(id, clip->fileURL().path());
137             QStringList files = ProjectSettings::extractPlaylistUrls(clip->fileURL().path());
138             otherUrls << files;
139         }
140         else if (!clip->fileURL().isEmpty()) {
141             if (t == AUDIO) audioUrls.insert(id, clip->fileURL().path());
142             else {
143                 videoUrls.insert(id, clip->fileURL().path());
144                 // Check if we have a proxy
145                 QString proxy = clip->getProperty("proxy");
146                 if (!proxy.isEmpty() && proxy != "-" && QFile::exists(proxy)) proxyUrls.insert(id, proxy);
147             }
148         }
149     }
150
151     generateItems(images, extraImageUrls);
152     generateItems(sounds, audioUrls);
153     generateItems(videos, videoUrls);
154     generateItems(images, imageUrls);
155     generateItems(slideshows, slideUrls);
156     generateItems(playlists, playlistUrls);
157     generateItems(others, otherUrls);
158     generateItems(proxies, proxyUrls);
159     
160     allFonts.removeDuplicates();
161
162 #if KDE_IS_VERSION(4,7,0)
163         m_infoMessage = new KMessageWidget(this);
164         QVBoxLayout *s =  static_cast <QVBoxLayout*> (layout());
165         s->insertWidget(5, m_infoMessage);
166         m_infoMessage->setCloseButtonVisible(false);
167         m_infoMessage->setWordWrap(true);
168         m_infoMessage->hide();
169 #endif
170         
171         // missing clips, warn user
172     if (m_missingClips > 0) {
173         QString infoText = i18np("You have %1 missing clip in your project.", "You have %1 missing clips in your project.", m_missingClips);
174 #if KDE_IS_VERSION(4,7,0)
175         m_infoMessage->setMessageType(KMessageWidget::Warning);
176         m_infoMessage->setText(infoText);
177         m_infoMessage->animatedShow();
178 #else
179         KMessageBox::sorry(this, infoText);
180 #endif
181     }
182
183     //TODO: fonts
184
185     // Hide unused categories, add item count
186     int total = 0;
187     for (int i = 0; i < files_list->topLevelItemCount(); ++i) {
188         QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
189         int items = parentItem->childCount();
190         if (items == 0) {
191             files_list->topLevelItem(i)->setHidden(true);
192         }
193         else {
194             if (parentItem->data(0, Qt::UserRole).toString() == "slideshows")
195             {
196                 // Special case: slideshows contain several files
197                 for (int j = 0; j < items; j++) {
198                     total += parentItem->child(j)->data(0, Qt::UserRole + 1).toStringList().count();
199                 }
200             }
201             else total += items;
202             parentItem->setText(0, files_list->topLevelItem(i)->text(0) + ' ' + i18np("(%1 item)", "(%1 items)", items));
203         }
204     }
205     if (m_name.isEmpty()) m_name = i18n("Untitled");
206     compressed_archive->setText(compressed_archive->text() + " (" + m_name + ".tar.gz)");
207     project_files->setText(i18np("%1 file to archive, requires %2", "%1 files to archive, requires %2", total, KIO::convertSize(m_requestedSize)));
208     buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Archive"));
209     connect(buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(slotStartArchiving()));
210     buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
211     
212     slotCheckSpace();
213 }
214
215 // Constructor for extract widget
216 ArchiveWidget::ArchiveWidget(const KUrl &url, QWidget * parent):
217     QDialog(parent),
218     m_extractMode(true),
219     m_extractUrl(url)
220 {
221     //setAttribute(Qt::WA_DeleteOnClose);
222
223     setupUi(this);
224     m_progressTimer = new QTimer;
225     m_progressTimer->setInterval(800);
226     m_progressTimer->setSingleShot(false);
227     connect(m_progressTimer, SIGNAL(timeout()), this, SLOT(slotExtractProgress()));
228     connect(this, SIGNAL(extractingFinished()), this, SLOT(slotExtractingFinished()));
229     connect(this, SIGNAL(showMessage(QString,QString)), this, SLOT(slotDisplayMessage(QString,QString)));
230     
231     compressed_archive->setHidden(true);
232     proxy_only->setHidden(true);
233     project_files->setHidden(true);
234     files_list->setHidden(true);
235     label->setText(i18n("Extract to"));
236     setWindowTitle(i18n("Open Archived Project"));
237     archive_url->setUrl(KUrl(QDir::homePath()));
238     buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Extract"));
239     connect(buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(slotStartExtracting()));
240     buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
241     adjustSize();
242     m_archiveThread = QtConcurrent::run(this, &ArchiveWidget::openArchiveForExtraction);
243 }
244
245
246 ArchiveWidget::~ArchiveWidget()
247 {
248     delete m_extractArchive;
249     delete m_progressTimer;
250 }
251
252 void ArchiveWidget::slotDisplayMessage(const QString &icon, const QString &text)
253 {    
254     icon_info->setPixmap(KIcon(icon).pixmap(16, 16));
255     text_info->setText(text);
256 }
257
258 void ArchiveWidget::slotJobResult(bool success, const QString &text)
259 {
260 #if KDE_IS_VERSION(4,7,0)
261     m_infoMessage->setMessageType(success ? KMessageWidget::Positive : KMessageWidget::Warning);
262     m_infoMessage->setText(text);
263     m_infoMessage->animatedShow();
264 #else
265     if (success) icon_info->setPixmap(KIcon("dialog-ok").pixmap(16, 16));
266     else icon_info->setPixmap(KIcon("dialog-close").pixmap(16, 16));
267     text_info->setText(text);
268 #endif
269 }
270
271 void ArchiveWidget::openArchiveForExtraction()
272 {
273     emit showMessage("system-run", i18n("Opening archive..."));
274     m_extractArchive = new KTar(m_extractUrl.path());
275     if (!m_extractArchive->isOpen() && !m_extractArchive->open( QIODevice::ReadOnly )) {
276         emit showMessage("dialog-close", i18n("Cannot open archive file:\n %1", m_extractUrl.path()));
277         groupBox->setEnabled(false);
278         return;
279     }
280
281     // Check that it is a kdenlive project archive
282     bool isProjectArchive = false;
283     QStringList files = m_extractArchive->directory()->entries();
284     for (int i = 0; i < files.count(); i++) {
285         if (files.at(i).endsWith(".kdenlive")) {
286             m_projectName = files.at(i);
287             isProjectArchive = true;
288             break;
289         }
290     }
291
292     if (!isProjectArchive) {
293         emit showMessage("dialog-close", i18n("File %1\n is not an archived Kdenlive project", m_extractUrl.path()));
294         groupBox->setEnabled(false);
295         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
296         return;
297     }
298     buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
299     emit showMessage("dialog-ok", i18n("Ready"));
300 }
301
302 void ArchiveWidget::done ( int r )
303 {
304     if (closeAccepted()) QDialog::done(r);
305 }
306
307 void ArchiveWidget::closeEvent ( QCloseEvent * e )
308 {
309
310     if (closeAccepted()) e->accept();
311     else e->ignore();
312 }
313
314
315 bool ArchiveWidget::closeAccepted()
316 {
317     if (!m_extractMode && !archive_url->isEnabled()) {
318         // Archiving in progress, should we stop?
319         if (KMessageBox::warningContinueCancel(this, i18n("Archiving in progress, do you want to stop it?"), i18n("Stop Archiving"), KGuiItem(i18n("Stop Archiving"))) != KMessageBox::Continue) {
320             return false;
321         }
322         if (m_copyJob) m_copyJob->kill();
323     }
324     return true;
325 }
326
327
328 void ArchiveWidget::generateItems(QTreeWidgetItem *parentItem, QStringList items)
329 {
330     QStringList filesList;
331     QString fileName;
332     int ix = 0;
333     bool isSlideshow = parentItem->data(0, Qt::UserRole).toString() == "slideshows";
334     foreach(const QString & file, items) {
335         QTreeWidgetItem *item = new QTreeWidgetItem(parentItem, QStringList() << file);
336         fileName = KUrl(file).fileName();
337         if (isSlideshow) {
338             // we store each slideshow in a separate subdirectory
339             item->setData(0, Qt::UserRole, ix);
340             ix++;
341             KUrl slideUrl(file);
342             QDir dir(slideUrl.directory(KUrl::AppendTrailingSlash));
343             if (slideUrl.fileName().startsWith(".all.")) {
344                 // mimetype slideshow (for example *.png)
345                     QStringList filters;
346                     QString extension;
347                     // TODO: improve jpeg image detection with extension like jpeg, requires change in MLT image producers
348                     filters << "*." + slideUrl.fileName().section('.', -1);
349                     dir.setNameFilters(filters);
350                     QFileInfoList resultList = dir.entryInfoList(QDir::Files);
351                     QStringList slideImages;
352                     qint64 totalSize = 0;
353                     for (int i = 0; i < resultList.count(); i++) {
354                         totalSize += resultList.at(i).size();
355                         slideImages << resultList.at(i).absoluteFilePath();
356                     }
357                     item->setData(0, Qt::UserRole + 1, slideImages);
358                     item->setData(0, Qt::UserRole + 3, totalSize);
359                     m_requestedSize += totalSize;
360             }
361             else {
362                 // pattern url (like clip%.3d.png)
363                 QStringList result = dir.entryList(QDir::Files);
364                 QString filter = slideUrl.fileName();
365                 QString ext = filter.section('.', -1);
366                 filter = filter.section('%', 0, -2);
367                 QString regexp = '^' + filter + "\\d+\\." + ext + '$';
368                 QRegExp rx(regexp);
369                 QStringList slideImages;
370                 QString directory = dir.absolutePath();
371                 if (!directory.endsWith('/')) directory.append('/');
372                 qint64 totalSize = 0;
373                 foreach(const QString & path, result) {
374                     if (rx.exactMatch(path)) {
375                         totalSize += QFileInfo(directory + path).size();
376                         slideImages <<  directory + path;
377                     }
378                 }
379                 item->setData(0, Qt::UserRole + 1, slideImages);
380                 item->setData(0, Qt::UserRole + 3, totalSize);
381                 m_requestedSize += totalSize;
382             }                    
383         }
384         else if (filesList.contains(fileName)) {
385             // we have 2 files with same name
386             int ix = 0;
387             QString newFileName = fileName.section('.', 0, -2) + '_' + QString::number(ix) + '.' + fileName.section('.', -1);
388             while (filesList.contains(newFileName)) {
389                 ix ++;
390                 newFileName = fileName.section('.', 0, -2) + '_' + QString::number(ix) + '.' + fileName.section('.', -1);
391             }
392             fileName = newFileName;
393             item->setData(0, Qt::UserRole, fileName);
394         }
395         if (!isSlideshow) {
396             qint64 fileSize = QFileInfo(file).size();
397             if (fileSize <= 0) {
398                 item->setIcon(0, KIcon("edit-delete"));
399                 m_missingClips++;
400             }
401             else {
402                 m_requestedSize += fileSize;
403                 item->setData(0, Qt::UserRole + 3, fileSize);
404             }
405             filesList << fileName;
406         }
407     }
408 }
409
410 void ArchiveWidget::generateItems(QTreeWidgetItem *parentItem, const QMap <QString, QString>& items)
411 {
412     QStringList filesList;
413     QString fileName;
414     int ix = 0;
415     bool isSlideshow = parentItem->data(0, Qt::UserRole).toString() == "slideshows";
416     QMap<QString, QString>::const_iterator it = items.constBegin();
417     while (it != items.constEnd()) {
418         QString file = it.value();
419         QTreeWidgetItem *item = new QTreeWidgetItem(parentItem, QStringList() << file);
420         // Store the clip's id
421         item->setData(0, Qt::UserRole + 2, it.key());
422         fileName = KUrl(file).fileName();
423         if (isSlideshow) {
424             // we store each slideshow in a separate subdirectory
425             item->setData(0, Qt::UserRole, ix);
426             ix++;
427             KUrl slideUrl(file);
428             QDir dir(slideUrl.directory(KUrl::AppendTrailingSlash));
429             if (slideUrl.fileName().startsWith(".all.")) {
430                 // mimetype slideshow (for example *.png)
431                     QStringList filters;
432                     // TODO: improve jpeg image detection with extension like jpeg, requires change in MLT image producers
433                     filters << "*." + slideUrl.fileName().section('.', -1);
434                     dir.setNameFilters(filters);
435                     QFileInfoList resultList = dir.entryInfoList(QDir::Files);
436                     QStringList slideImages;
437                     qint64 totalSize = 0;
438                     for (int i = 0; i < resultList.count(); i++) {
439                         totalSize += resultList.at(i).size();
440                         slideImages << resultList.at(i).absoluteFilePath();
441                     }
442                     item->setData(0, Qt::UserRole + 1, slideImages);
443                     item->setData(0, Qt::UserRole + 3, totalSize);
444                     m_requestedSize += totalSize;
445             }
446             else {
447                 // pattern url (like clip%.3d.png)
448                 QStringList result = dir.entryList(QDir::Files);
449                 QString filter = slideUrl.fileName();
450                 QString ext = filter.section('.', -1);
451                 filter = filter.section('%', 0, -2);
452                 QString regexp = '^' + filter + "\\d+\\." + ext + '$';
453                 QRegExp rx(regexp);
454                 QStringList slideImages;
455                 qint64 totalSize = 0;
456                 QString directory = dir.absolutePath();
457                 if (!directory.endsWith('/')) directory.append('/');
458                 foreach(const QString & path, result) {
459                     if (rx.exactMatch(path)) {
460                         totalSize += QFileInfo(directory + path).size();
461                         slideImages <<  directory + path;
462                     }
463                 }
464                 item->setData(0, Qt::UserRole + 1, slideImages);
465                 item->setData(0, Qt::UserRole + 3, totalSize);
466                 m_requestedSize += totalSize;
467             }                    
468         }
469         else if (filesList.contains(fileName)) {
470             // we have 2 files with same name
471             int ix = 0;
472             QString newFileName = fileName.section('.', 0, -2) + '_' + QString::number(ix) + '.' + fileName.section('.', -1);
473             while (filesList.contains(newFileName)) {
474                 ix ++;
475                 newFileName = fileName.section('.', 0, -2) + "_" + QString::number(ix) + "." + fileName.section('.', -1);
476             }
477             fileName = newFileName;
478             item->setData(0, Qt::UserRole, fileName);
479         }
480         if (!isSlideshow) {
481             qint64 fileSize = QFileInfo(file).size();
482             if (fileSize <= 0) {
483                 item->setIcon(0, KIcon("edit-delete"));
484                 m_missingClips++;
485             }
486             else {
487                 m_requestedSize += fileSize;
488                 item->setData(0, Qt::UserRole + 3, fileSize);
489             }
490             filesList << fileName;
491         }
492         ++it;
493     }
494 }
495
496 void ArchiveWidget::slotCheckSpace()
497 {
498     KDiskFreeSpaceInfo inf = KDiskFreeSpaceInfo::freeSpaceInfo( archive_url->url().path());
499     KIO::filesize_t freeSize = inf.available();
500     if (freeSize > m_requestedSize) {
501         // everything is ok
502         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
503         slotDisplayMessage("dialog-ok", i18n("Available space on drive: %1", KIO::convertSize(freeSize)));
504     }
505     else {
506         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
507         slotDisplayMessage("dialog-close", i18n("Not enough space on drive, free space: %1", KIO::convertSize(freeSize)));
508     }
509 }
510
511 bool ArchiveWidget::slotStartArchiving(bool firstPass)
512 {
513     if (firstPass && (m_copyJob || m_archiveThread.isRunning())) {
514         // archiving in progress, abort
515         if (m_copyJob) m_copyJob->kill(KJob::EmitResult);
516         m_abortArchive = true;
517         return true;
518     }
519     bool isArchive = compressed_archive->isChecked();
520     if (!firstPass) m_copyJob = NULL;
521     else {
522         //starting archiving
523         m_abortArchive = false;
524         m_duplicateFiles.clear();
525         m_replacementList.clear();
526         m_foldersList.clear();
527         m_filesList.clear();
528         slotDisplayMessage("system-run", i18n("Archiving..."));
529         repaint();
530         archive_url->setEnabled(false);
531         proxy_only->setEnabled(false);
532         compressed_archive->setEnabled(false);
533     }
534     KUrl::List files;
535     KUrl destUrl;
536     QString destPath;
537     QTreeWidgetItem *parentItem;
538     bool isSlideshow = false;
539     int items = 0;
540     
541     // We parse all files going into one folder, then start the copy job
542     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
543         parentItem = files_list->topLevelItem(i);
544         if (parentItem->isDisabled()) {
545             parentItem->setExpanded(false);
546             continue;
547         }
548         if (parentItem->childCount() > 0) {
549             if (parentItem->data(0, Qt::UserRole).toString() == "slideshows") {
550                 KUrl slideFolder(archive_url->url().path(KUrl::AddTrailingSlash) + "slideshows");
551                 if (isArchive) m_foldersList.append("slideshows");
552                 else KIO::NetAccess::mkdir(slideFolder, this);
553                 isSlideshow = true;
554             }
555             else isSlideshow = false;
556             files_list->setCurrentItem(parentItem);
557             parentItem->setExpanded(true);
558             destPath = parentItem->data(0, Qt::UserRole).toString() + '/';
559             destUrl = KUrl(archive_url->url().path(KUrl::AddTrailingSlash) + destPath);
560             QTreeWidgetItem *item;
561             for (int j = 0; j < parentItem->childCount(); j++) {
562                 item = parentItem->child(j);
563                 if (item->isDisabled()) continue;
564                 // Special case: slideshows
565                 items++;
566                 if (isSlideshow) {
567                     destPath += item->data(0, Qt::UserRole).toString() + '/';
568                     destUrl = KUrl(archive_url->url().path(KUrl::AddTrailingSlash) + destPath);
569                     QStringList srcFiles = item->data(0, Qt::UserRole + 1).toStringList();
570                     for (int k = 0; k < srcFiles.count(); k++) {
571                         files << KUrl(srcFiles.at(k));
572                     }
573                     item->setDisabled(true);
574                     if (parentItem->indexOfChild(item) == parentItem->childCount() - 1) {
575                         // We have processed all slideshows
576                         parentItem->setDisabled(true);
577                     }
578                     break;
579                 }
580                 else if (item->data(0, Qt::UserRole).isNull()) {
581                     files << KUrl(item->text(0));
582                 }
583                 else {
584                     // We must rename the destination file, since another file with same name exists
585                     //TODO: monitor progress
586                     if (isArchive) {
587                         m_filesList.insert(item->text(0), destPath + item->data(0, Qt::UserRole).toString());
588                     }
589                     else m_duplicateFiles.insert(KUrl(item->text(0)), KUrl(destUrl.path(KUrl::AddTrailingSlash) + item->data(0, Qt::UserRole).toString()));
590                 }
591             }
592             if (!isSlideshow) parentItem->setDisabled(true);
593             break;
594         }
595     }
596
597     if (items == 0) {
598         // No clips to archive
599         slotArchivingFinished(NULL, true);
600         return true;
601     }
602     
603     if (destPath.isEmpty()) {
604         if (m_duplicateFiles.isEmpty()) return false;        
605         QMapIterator<KUrl, KUrl> i(m_duplicateFiles);
606         if (i.hasNext()) {
607             i.next();
608             KUrl startJobSrc = i.key();
609             KUrl startJobDst = i.value();
610             m_duplicateFiles.remove(startJobSrc);
611             KIO::CopyJob *job = KIO::copyAs(startJobSrc, startJobDst, KIO::HideProgressInfo);
612             connect(job, SIGNAL(result(KJob*)), this, SLOT(slotArchivingFinished(KJob*)));
613             connect(job, SIGNAL(processedSize(KJob*,qulonglong)), this, SLOT(slotArchivingProgress(KJob*,qulonglong)));
614         }
615         return true;
616     }
617
618     if (isArchive) {
619         m_foldersList.append(destPath);
620         for (int i = 0; i < files.count(); i++) {
621             m_filesList.insert(files.at(i).path(), destPath + files.at(i).fileName());
622         }
623         slotArchivingFinished();
624     }
625     else if (files.isEmpty()) {
626         slotStartArchiving(false);
627     }
628     else {
629         KIO::NetAccess::mkdir(destUrl, this);
630         m_copyJob = KIO::copy (files, destUrl, KIO::HideProgressInfo);
631         connect(m_copyJob, SIGNAL(result(KJob*)), this, SLOT(slotArchivingFinished(KJob*)));
632         connect(m_copyJob, SIGNAL(processedSize(KJob*,qulonglong)), this, SLOT(slotArchivingProgress(KJob*,qulonglong)));
633     }
634     if (firstPass) {
635         progressBar->setValue(0);
636         buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Abort"));
637     }
638     return true;
639 }
640
641 void ArchiveWidget::slotArchivingFinished(KJob *job, bool finished)
642 {
643     if (job == NULL || job->error() == 0) {
644         if (!finished && slotStartArchiving(false)) {
645             // We still have files to archive
646             return;
647         }
648         else if (!compressed_archive->isChecked()) {
649             // Archiving finished
650             progressBar->setValue(100);
651             if (processProjectFile()) {
652                 slotJobResult(true, i18n("Project was successfully archived."));
653             }
654             else {
655                 slotJobResult(false, i18n("There was an error processing project file"));
656             }
657         } else processProjectFile();
658     }
659     else {
660         m_copyJob = NULL;
661         slotJobResult(false, i18n("There was an error while copying the files: %1", job->errorString()));
662     }
663     if (!compressed_archive->isChecked()) {
664         buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Archive"));
665         archive_url->setEnabled(true);
666         proxy_only->setEnabled(true);
667         compressed_archive->setEnabled(true);
668         for (int i = 0; i < files_list->topLevelItemCount(); i++) {
669             files_list->topLevelItem(i)->setDisabled(false);
670             for (int j = 0; j < files_list->topLevelItem(i)->childCount(); j++)
671                 files_list->topLevelItem(i)->child(j)->setDisabled(false);        
672         }
673     }
674 }
675
676 void ArchiveWidget::slotArchivingProgress(KJob *, qulonglong size)
677 {
678     progressBar->setValue((int) 100 * size / m_requestedSize);
679 }
680
681
682 bool ArchiveWidget::processProjectFile()
683 {
684     KUrl destUrl;
685     QTreeWidgetItem *item;
686     bool isArchive = compressed_archive->isChecked();
687
688     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
689         QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
690         if (parentItem->childCount() > 0) {
691             destUrl = KUrl(archive_url->url().path(KUrl::AddTrailingSlash) + parentItem->data(0, Qt::UserRole).toString());
692             bool isSlideshow = parentItem->data(0, Qt::UserRole).toString() == "slideshows";
693             for (int j = 0; j < parentItem->childCount(); j++) {
694                 item = parentItem->child(j);
695                 KUrl src(item->text(0));
696                 KUrl dest = destUrl;
697                 if (isSlideshow) {
698                     dest = KUrl(destUrl.path(KUrl::AddTrailingSlash) + item->data(0, Qt::UserRole).toString() + '/' + src.fileName());
699                 }
700                 else if (item->data(0, Qt::UserRole).isNull()) {
701                     dest.addPath(src.fileName());
702                 }
703                 else {
704                     dest.addPath(item->data(0, Qt::UserRole).toString());
705                 }
706                 m_replacementList.insert(src, dest);
707             }
708         }
709     }
710     
711     QDomElement mlt = m_doc.documentElement();
712     QString root = mlt.attribute("root") + '/';
713
714     // Adjust global settings
715     QString basePath;
716     if (isArchive) basePath = "$CURRENTPATH";
717     else basePath = archive_url->url().path(KUrl::RemoveTrailingSlash);
718     mlt.setAttribute("root", basePath);
719     QDomElement project = mlt.firstChildElement("kdenlivedoc");
720     project.setAttribute("projectfolder", basePath);
721
722     // process kdenlive producers
723     QDomNodeList prods = mlt.elementsByTagName("kdenlive_producer");
724     for (int i = 0; i < prods.count(); i++) {
725         QDomElement e = prods.item(i).toElement();
726         if (e.isNull()) continue;
727         if (e.hasAttribute("resource")) {
728             KUrl src(e.attribute("resource"));
729             KUrl dest = m_replacementList.value(src);
730             if (!dest.isEmpty()) e.setAttribute("resource", dest.path());
731         }
732         if (e.hasAttribute("proxy") && e.attribute("proxy") != "-") {
733             KUrl src(e.attribute("proxy"));
734             KUrl dest = m_replacementList.value(src);
735             if (!dest.isEmpty()) e.setAttribute("proxy", dest.path());
736         }
737     }
738
739     // process mlt producers
740     prods = mlt.elementsByTagName("producer");
741     for (int i = 0; i < prods.count(); i++) {
742         QDomElement e = prods.item(i).toElement();
743         if (e.isNull()) continue;
744         QString src = EffectsList::property(e, "resource");
745         if (!src.isEmpty()) {
746             if (!src.startsWith('/')) src.prepend(root);
747             KUrl srcUrl(src);
748             KUrl dest = m_replacementList.value(src);
749             if (!dest.isEmpty()) EffectsList::setProperty(e, "resource", dest.path());
750         }
751     }
752
753     // process mlt transitions (for luma files)
754     prods = mlt.elementsByTagName("transition");
755     QString attribute;
756     for (int i = 0; i < prods.count(); i++) {
757         QDomElement e = prods.item(i).toElement();
758         if (e.isNull()) continue;
759         attribute = "resource";
760         QString src = EffectsList::property(e, attribute);
761         if (src.isEmpty()) attribute = "luma";
762         src = EffectsList::property(e, attribute);
763         if (!src.isEmpty()) {
764             if (!src.startsWith('/')) src.prepend(root);
765             KUrl srcUrl(src);
766             KUrl dest = m_replacementList.value(src);
767             if (!dest.isEmpty()) EffectsList::setProperty(e, attribute, dest.path());
768         }
769     }
770
771     QString playList = m_doc.toString();
772     if (isArchive) {
773         QString startString("\"");
774         startString.append(archive_url->url().path(KUrl::RemoveTrailingSlash));
775         QString endString("\"");
776         endString.append(basePath);
777         playList.replace(startString, endString);
778         startString = '>' + archive_url->url().path(KUrl::RemoveTrailingSlash);
779         endString = '>' + basePath;
780         playList.replace(startString, endString);
781     }
782
783     if (isArchive) {
784         m_temp = new KTemporaryFile;
785         if (!m_temp->open()) KMessageBox::error(this, i18n("Cannot create temporary file"));
786         m_temp->write(playList.toUtf8());
787         m_temp->close();
788         m_archiveThread = QtConcurrent::run(this, &ArchiveWidget::createArchive);
789         return true;
790     }
791     
792     QString path = archive_url->url().path(KUrl::AddTrailingSlash) + m_name + ".kdenlive";
793     QFile file(path);
794     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
795         kWarning() << "//////  ERROR writing to file: " << path;
796         KMessageBox::error(this, i18n("Cannot write to file %1", path));
797         return false;
798     }
799
800     file.write(m_doc.toString().toUtf8());
801     if (file.error() != QFile::NoError) {
802         KMessageBox::error(this, i18n("Cannot write to file %1", path));
803         file.close();
804         return false;
805     }
806     file.close();
807     return true;
808 }
809
810 void ArchiveWidget::createArchive()
811 {
812     QFileInfo dirInfo(archive_url->url().path());
813     QString user = dirInfo.owner();
814     QString group = dirInfo.group();
815     KTar archive(archive_url->url().path(KUrl::AddTrailingSlash) + m_name + ".tar.gz", "application/x-gzip");
816     archive.open( QIODevice::WriteOnly );
817
818     // Create folders
819     foreach(const QString &path, m_foldersList) {
820         archive.writeDir(path, user, group);
821     }
822
823     // Add files
824     int ix = 0;
825     QMapIterator<QString, QString> i(m_filesList);
826     while (i.hasNext()) {
827         i.next();
828         archive.addLocalFile(i.key(), i.value());
829         emit archiveProgress((int) 100 * ix / m_filesList.count());
830         ix++;
831     }
832
833     // Add project file
834     bool result = false;
835     if (m_temp) {
836         archive.addLocalFile(m_temp->fileName(), m_name + ".kdenlive");
837         result = archive.close();
838         delete m_temp;
839     }
840     emit archivingFinished(result);
841 }
842
843 void ArchiveWidget::slotArchivingFinished(bool result)
844 {
845     if (result) {
846         slotJobResult(true, i18n("Project was successfully archived."));
847         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
848     }
849     else {
850         slotJobResult(false, i18n("There was an error processing project file"));
851     }
852     progressBar->setValue(100);
853     buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Archive"));
854     archive_url->setEnabled(true);
855     proxy_only->setEnabled(true);
856     compressed_archive->setEnabled(true);
857     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
858         files_list->topLevelItem(i)->setDisabled(false);
859         for (int j = 0; j < files_list->topLevelItem(i)->childCount(); j++)
860             files_list->topLevelItem(i)->child(j)->setDisabled(false);
861     }
862 }
863
864 void ArchiveWidget::slotArchivingProgress(int p)
865 {
866     progressBar->setValue(p);
867 }
868
869 void ArchiveWidget::slotStartExtracting()
870 {
871     if (m_archiveThread.isRunning()) {
872         //TODO: abort extracting
873         return;
874     }
875     QFileInfo f(m_extractUrl.path());
876     m_requestedSize = f.size();
877     KIO::NetAccess::mkdir(archive_url->url().path(KUrl::RemoveTrailingSlash), this);
878     slotDisplayMessage("system-run", i18n("Extracting..."));
879     buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Abort"));
880     m_archiveThread = QtConcurrent::run(this, &ArchiveWidget::doExtracting);
881     m_progressTimer->start();
882 }
883
884 void ArchiveWidget::slotExtractProgress()
885 {
886     KIO::DirectorySizeJob *job = KIO::directorySize(archive_url->url());
887     connect(job, SIGNAL(result(KJob*)), this, SLOT(slotGotProgress(KJob*)));
888 }
889
890 void ArchiveWidget::slotGotProgress(KJob* job)
891 {
892     if (!job->error()) {
893         KIO::DirectorySizeJob *j = static_cast <KIO::DirectorySizeJob *>(job);
894         progressBar->setValue((int) 100 * j->totalSize() / m_requestedSize);
895     }
896     job->deleteLater();
897 }
898
899 void ArchiveWidget::doExtracting()
900 {
901     m_extractArchive->directory()->copyTo(archive_url->url().path(KUrl::AddTrailingSlash));
902     m_extractArchive->close();
903     emit extractingFinished();    
904 }
905
906 QString ArchiveWidget::extractedProjectFile()
907 {
908     return archive_url->url().path(KUrl::AddTrailingSlash) + m_projectName;
909 }
910
911 void ArchiveWidget::slotExtractingFinished()
912 {
913     m_progressTimer->stop();
914     // Process project file
915     QFile file(extractedProjectFile());
916     bool error = false;
917     if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
918         error = true;
919     }
920     else {
921         QString playList = QString::fromUtf8(file.readAll());
922         file.close();
923         if (playList.isEmpty()) {
924             error = true;
925         }
926         else {
927             playList.replace("$CURRENTPATH", archive_url->url().path(KUrl::RemoveTrailingSlash));
928             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
929                 kWarning() << "//////  ERROR writing to file: ";
930                 error = true;
931             }
932             else {
933                 file.write(playList.toUtf8());
934                 if (file.error() != QFile::NoError) {
935                     error = true;
936                 }
937                 file.close();
938             }
939         }
940     }
941     if (error) {
942         KMessageBox::sorry(kapp->activeWindow(), i18n("Cannot open project file %1", extractedProjectFile()), i18n("Cannot open file"));
943         reject();
944     }
945     else accept();
946 }
947
948 void ArchiveWidget::slotProxyOnly(int onlyProxy)
949 {
950     m_requestedSize = 0;
951     if (onlyProxy == Qt::Checked) {
952         // Archive proxy clips
953         QStringList proxyIdList;
954         QTreeWidgetItem *parentItem = NULL;
955
956         // Build list of existing proxy ids
957         for (int i = 0; i < files_list->topLevelItemCount(); i++) {
958             parentItem = files_list->topLevelItem(i);
959             if (parentItem->data(0, Qt::UserRole).toString() == "proxy") break;
960         }
961         if (!parentItem) return;
962         int items = parentItem->childCount();
963         for (int j = 0; j < items; j++) {
964             proxyIdList << parentItem->child(j)->data(0, Qt::UserRole + 2).toString();
965         }
966         
967         // Parse all items to disable original clips for existing proxies
968         for (int i = 0; i < proxyIdList.count(); i++) {
969             QString id = proxyIdList.at(i);
970             if (id.isEmpty()) continue;
971             for (int j = 0; j < files_list->topLevelItemCount(); j++) {
972                 parentItem = files_list->topLevelItem(j);
973                 if (parentItem->data(0, Qt::UserRole).toString() == "proxy") continue;
974                 items = parentItem->childCount();
975                 for (int k = 0; k < items; k++) {
976                     if (parentItem->child(k)->data(0, Qt::UserRole + 2).toString() == id) {
977                         // This item has a proxy, do not archive it
978                         parentItem->child(k)->setFlags(Qt::ItemIsSelectable);
979                         break;
980                     }
981                 }
982             }
983         }
984     }
985     else {
986         // Archive all clips
987         for (int i = 0; i < files_list->topLevelItemCount(); i++) {
988             QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
989             int items = parentItem->childCount();
990             for (int j = 0; j < items; j++) {
991                 parentItem->child(j)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
992             }
993         }
994     }
995     
996     // Calculate requested size
997     int total = 0;
998     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
999         QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
1000         int items = parentItem->childCount();
1001         int itemsCount = 0;
1002         bool isSlideshow = parentItem->data(0, Qt::UserRole).toString() == "slideshows";
1003         
1004         for (int j = 0; j < items; j++) {
1005             if (!parentItem->child(j)->isDisabled()) {
1006                 m_requestedSize += parentItem->child(j)->data(0, Qt::UserRole + 3).toInt();
1007                 if (isSlideshow) total += parentItem->child(j)->data(0, Qt::UserRole + 1).toStringList().count();
1008                 else total ++;
1009                 itemsCount ++;
1010             }
1011         }
1012         parentItem->setText(0, parentItem->text(0).section('(', 0, 0) + i18np("(%1 item)", "(%1 items)", itemsCount));
1013     }
1014     project_files->setText(i18np("%1 file to archive, requires %2", "%1 files to archive, requires %2", total, KIO::convertSize(m_requestedSize)));
1015     slotCheckSpace();
1016 }
1017