]> git.sesse.net Git - kdenlive/blob - src/archivewidget.cpp
normalize signal/slots
[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(QString projectName, QDomDocument doc, QList <DocClipBase*> list, 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     if (m_extractArchive) delete m_extractArchive;
249     if (m_progressTimer) 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, 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                     QString extension;
433                     // TODO: improve jpeg image detection with extension like jpeg, requires change in MLT image producers
434                     filters << "*." + slideUrl.fileName().section('.', -1);
435                     dir.setNameFilters(filters);
436                     QFileInfoList resultList = dir.entryInfoList(QDir::Files);
437                     QStringList slideImages;
438                     qint64 totalSize = 0;
439                     for (int i = 0; i < resultList.count(); i++) {
440                         totalSize += resultList.at(i).size();
441                         slideImages << resultList.at(i).absoluteFilePath();
442                     }
443                     item->setData(0, Qt::UserRole + 1, slideImages);
444                     item->setData(0, Qt::UserRole + 3, totalSize);
445                     m_requestedSize += totalSize;
446             }
447             else {
448                 // pattern url (like clip%.3d.png)
449                 QStringList result = dir.entryList(QDir::Files);
450                 QString filter = slideUrl.fileName();
451                 QString ext = filter.section('.', -1);
452                 filter = filter.section('%', 0, -2);
453                 QString regexp = '^' + filter + "\\d+\\." + ext + '$';
454                 QRegExp rx(regexp);
455                 QStringList slideImages;
456                 qint64 totalSize = 0;
457                 QString directory = dir.absolutePath();
458                 if (!directory.endsWith('/')) directory.append('/');
459                 foreach(const QString & path, result) {
460                     if (rx.exactMatch(path)) {
461                         totalSize += QFileInfo(directory + path).size();
462                         slideImages <<  directory + path;
463                     }
464                 }
465                 item->setData(0, Qt::UserRole + 1, slideImages);
466                 item->setData(0, Qt::UserRole + 3, totalSize);
467                 m_requestedSize += totalSize;
468             }                    
469         }
470         else if (filesList.contains(fileName)) {
471             // we have 2 files with same name
472             int ix = 0;
473             QString newFileName = fileName.section('.', 0, -2) + '_' + QString::number(ix) + '.' + fileName.section('.', -1);
474             while (filesList.contains(newFileName)) {
475                 ix ++;
476                 newFileName = fileName.section('.', 0, -2) + "_" + QString::number(ix) + "." + fileName.section('.', -1);
477             }
478             fileName = newFileName;
479             item->setData(0, Qt::UserRole, fileName);
480         }
481         if (!isSlideshow) {
482             qint64 fileSize = QFileInfo(file).size();
483             if (fileSize <= 0) {
484                 item->setIcon(0, KIcon("edit-delete"));
485                 m_missingClips++;
486             }
487             else {
488                 m_requestedSize += fileSize;
489                 item->setData(0, Qt::UserRole + 3, fileSize);
490             }
491             filesList << fileName;
492         }
493         ++it;
494     }
495 }
496
497 void ArchiveWidget::slotCheckSpace()
498 {
499     KDiskFreeSpaceInfo inf = KDiskFreeSpaceInfo::freeSpaceInfo( archive_url->url().path());
500     KIO::filesize_t freeSize = inf.available();
501     if (freeSize > m_requestedSize) {
502         // everything is ok
503         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
504         slotDisplayMessage("dialog-ok", i18n("Available space on drive: %1", KIO::convertSize(freeSize)));
505     }
506     else {
507         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
508         slotDisplayMessage("dialog-close", i18n("Not enough space on drive, free space: %1", KIO::convertSize(freeSize)));
509     }
510 }
511
512 bool ArchiveWidget::slotStartArchiving(bool firstPass)
513 {
514     if (firstPass && (m_copyJob || m_archiveThread.isRunning())) {
515         // archiving in progress, abort
516         if (m_copyJob) m_copyJob->kill(KJob::EmitResult);
517         m_abortArchive = true;
518         return true;
519     }
520     bool isArchive = compressed_archive->isChecked();
521     if (!firstPass) m_copyJob = NULL;
522     else {
523         //starting archiving
524         m_abortArchive = false;
525         m_duplicateFiles.clear();
526         m_replacementList.clear();
527         m_foldersList.clear();
528         m_filesList.clear();
529         slotDisplayMessage("system-run", i18n("Archiving..."));
530         repaint();
531         archive_url->setEnabled(false);
532         proxy_only->setEnabled(false);
533         compressed_archive->setEnabled(false);
534     }
535     KUrl::List files;
536     KUrl destUrl;
537     QString destPath;
538     QTreeWidgetItem *parentItem;
539     bool isSlideshow = false;
540     int items = 0;
541     
542     // We parse all files going into one folder, then start the copy job
543     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
544         parentItem = files_list->topLevelItem(i);
545         if (parentItem->isDisabled()) {
546             parentItem->setExpanded(false);
547             continue;
548         }
549         if (parentItem->childCount() > 0) {
550             if (parentItem->data(0, Qt::UserRole).toString() == "slideshows") {
551                 KUrl slideFolder(archive_url->url().path(KUrl::AddTrailingSlash) + "slideshows");
552                 if (isArchive) m_foldersList.append("slideshows");
553                 else KIO::NetAccess::mkdir(slideFolder, this);
554                 isSlideshow = true;
555             }
556             else isSlideshow = false;
557             files_list->setCurrentItem(parentItem);
558             parentItem->setExpanded(true);
559             destPath = parentItem->data(0, Qt::UserRole).toString() + '/';
560             destUrl = KUrl(archive_url->url().path(KUrl::AddTrailingSlash) + destPath);
561             QTreeWidgetItem *item;
562             for (int j = 0; j < parentItem->childCount(); j++) {
563                 item = parentItem->child(j);
564                 if (item->isDisabled()) continue;
565                 // Special case: slideshows
566                 items++;
567                 if (isSlideshow) {
568                     destPath += item->data(0, Qt::UserRole).toString() + '/';
569                     destUrl = KUrl(archive_url->url().path(KUrl::AddTrailingSlash) + destPath);
570                     QStringList srcFiles = item->data(0, Qt::UserRole + 1).toStringList();
571                     for (int k = 0; k < srcFiles.count(); k++) {
572                         files << KUrl(srcFiles.at(k));
573                     }
574                     item->setDisabled(true);
575                     if (parentItem->indexOfChild(item) == parentItem->childCount() - 1) {
576                         // We have processed all slideshows
577                         parentItem->setDisabled(true);
578                     }
579                     break;
580                 }
581                 else if (item->data(0, Qt::UserRole).isNull()) {
582                     files << KUrl(item->text(0));
583                 }
584                 else {
585                     // We must rename the destination file, since another file with same name exists
586                     //TODO: monitor progress
587                     if (isArchive) {
588                         m_filesList.insert(item->text(0), destPath + item->data(0, Qt::UserRole).toString());
589                     }
590                     else m_duplicateFiles.insert(KUrl(item->text(0)), KUrl(destUrl.path(KUrl::AddTrailingSlash) + item->data(0, Qt::UserRole).toString()));
591                 }
592             }
593             if (!isSlideshow) parentItem->setDisabled(true);
594             break;
595         }
596     }
597
598     if (items == 0) {
599         // No clips to archive
600         slotArchivingFinished(NULL, true);
601         return true;
602     }
603     
604     if (destPath.isEmpty()) {
605         if (m_duplicateFiles.isEmpty()) return false;        
606         QMapIterator<KUrl, KUrl> i(m_duplicateFiles);
607         if (i.hasNext()) {
608             i.next();
609             KUrl startJobSrc = i.key();
610             KUrl startJobDst = i.value();
611             m_duplicateFiles.remove(startJobSrc);
612             KIO::CopyJob *job = KIO::copyAs(startJobSrc, startJobDst, KIO::HideProgressInfo);
613             connect(job, SIGNAL(result(KJob*)), this, SLOT(slotArchivingFinished(KJob*)));
614             connect(job, SIGNAL(processedSize(KJob*,qulonglong)), this, SLOT(slotArchivingProgress(KJob*,qulonglong)));
615         }
616         return true;
617     }
618
619     if (isArchive) {
620         m_foldersList.append(destPath);
621         for (int i = 0; i < files.count(); i++) {
622             m_filesList.insert(files.at(i).path(), destPath + files.at(i).fileName());
623         }
624         slotArchivingFinished();
625     }
626     else if (files.isEmpty()) {
627         slotStartArchiving(false);
628     }
629     else {
630         KIO::NetAccess::mkdir(destUrl, this);
631         m_copyJob = KIO::copy (files, destUrl, KIO::HideProgressInfo);
632         connect(m_copyJob, SIGNAL(result(KJob*)), this, SLOT(slotArchivingFinished(KJob*)));
633         connect(m_copyJob, SIGNAL(processedSize(KJob*,qulonglong)), this, SLOT(slotArchivingProgress(KJob*,qulonglong)));
634     }
635     if (firstPass) {
636         progressBar->setValue(0);
637         buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Abort"));
638     }
639     return true;
640 }
641
642 void ArchiveWidget::slotArchivingFinished(KJob *job, bool finished)
643 {
644     if (job == NULL || job->error() == 0) {
645         if (!finished && slotStartArchiving(false)) {
646             // We still have files to archive
647             return;
648         }
649         else if (!compressed_archive->isChecked()) {
650             // Archiving finished
651             progressBar->setValue(100);
652             if (processProjectFile()) {
653                 slotJobResult(true, i18n("Project was successfully archived."));
654             }
655             else {
656                 slotJobResult(false, i18n("There was an error processing project file"));
657             }
658         } else processProjectFile();
659     }
660     else {
661         m_copyJob = NULL;
662         slotJobResult(false, i18n("There was an error while copying the files: %1", job->errorString()));
663     }
664     if (!compressed_archive->isChecked()) {
665         buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Archive"));
666         archive_url->setEnabled(true);
667         proxy_only->setEnabled(true);
668         compressed_archive->setEnabled(true);
669         for (int i = 0; i < files_list->topLevelItemCount(); i++) {
670             files_list->topLevelItem(i)->setDisabled(false);
671             for (int j = 0; j < files_list->topLevelItem(i)->childCount(); j++)
672                 files_list->topLevelItem(i)->child(j)->setDisabled(false);        
673         }
674     }
675 }
676
677 void ArchiveWidget::slotArchivingProgress(KJob *, qulonglong size)
678 {
679     progressBar->setValue((int) 100 * size / m_requestedSize);
680 }
681
682
683 bool ArchiveWidget::processProjectFile()
684 {
685     KUrl destUrl;
686     QTreeWidgetItem *item;
687     bool isArchive = compressed_archive->isChecked();
688
689     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
690         QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
691         if (parentItem->childCount() > 0) {
692             destUrl = KUrl(archive_url->url().path(KUrl::AddTrailingSlash) + parentItem->data(0, Qt::UserRole).toString());
693             bool isSlideshow = parentItem->data(0, Qt::UserRole).toString() == "slideshows";
694             for (int j = 0; j < parentItem->childCount(); j++) {
695                 item = parentItem->child(j);
696                 KUrl src(item->text(0));
697                 KUrl dest = destUrl;
698                 if (isSlideshow) {
699                     dest = KUrl(destUrl.path(KUrl::AddTrailingSlash) + item->data(0, Qt::UserRole).toString() + '/' + src.fileName());
700                 }
701                 else if (item->data(0, Qt::UserRole).isNull()) {
702                     dest.addPath(src.fileName());
703                 }
704                 else {
705                     dest.addPath(item->data(0, Qt::UserRole).toString());
706                 }
707                 m_replacementList.insert(src, dest);
708             }
709         }
710     }
711     
712     QDomElement mlt = m_doc.documentElement();
713     QString root = mlt.attribute("root") + '/';
714
715     // Adjust global settings
716     QString basePath;
717     if (isArchive) basePath = "$CURRENTPATH";
718     else basePath = archive_url->url().path(KUrl::RemoveTrailingSlash);
719     mlt.setAttribute("root", basePath);
720     QDomElement project = mlt.firstChildElement("kdenlivedoc");
721     project.setAttribute("projectfolder", basePath);
722
723     // process kdenlive producers
724     QDomNodeList prods = mlt.elementsByTagName("kdenlive_producer");
725     for (int i = 0; i < prods.count(); i++) {
726         QDomElement e = prods.item(i).toElement();
727         if (e.isNull()) continue;
728         if (e.hasAttribute("resource")) {
729             KUrl src(e.attribute("resource"));
730             KUrl dest = m_replacementList.value(src);
731             if (!dest.isEmpty()) e.setAttribute("resource", dest.path());
732         }
733         if (e.hasAttribute("proxy") && e.attribute("proxy") != "-") {
734             KUrl src(e.attribute("proxy"));
735             KUrl dest = m_replacementList.value(src);
736             if (!dest.isEmpty()) e.setAttribute("proxy", dest.path());
737         }
738     }
739
740     // process mlt producers
741     prods = mlt.elementsByTagName("producer");
742     for (int i = 0; i < prods.count(); i++) {
743         QDomElement e = prods.item(i).toElement();
744         if (e.isNull()) continue;
745         QString src = EffectsList::property(e, "resource");
746         if (!src.isEmpty()) {
747             if (!src.startsWith('/')) src.prepend(root);
748             KUrl srcUrl(src);
749             KUrl dest = m_replacementList.value(src);
750             if (!dest.isEmpty()) EffectsList::setProperty(e, "resource", dest.path());
751         }
752     }
753
754     // process mlt transitions (for luma files)
755     prods = mlt.elementsByTagName("transition");
756     QString attribute;
757     for (int i = 0; i < prods.count(); i++) {
758         QDomElement e = prods.item(i).toElement();
759         if (e.isNull()) continue;
760         attribute = "resource";
761         QString src = EffectsList::property(e, attribute);
762         if (src.isEmpty()) attribute = "luma";
763         src = EffectsList::property(e, attribute);
764         if (!src.isEmpty()) {
765             if (!src.startsWith('/')) src.prepend(root);
766             KUrl srcUrl(src);
767             KUrl dest = m_replacementList.value(src);
768             if (!dest.isEmpty()) EffectsList::setProperty(e, attribute, dest.path());
769         }
770     }
771
772     QString playList = m_doc.toString();
773     if (isArchive) {
774         QString startString("\"");
775         startString.append(archive_url->url().path(KUrl::RemoveTrailingSlash));
776         QString endString("\"");
777         endString.append(basePath);
778         playList.replace(startString, endString);
779         startString = '>' + archive_url->url().path(KUrl::RemoveTrailingSlash);
780         endString = '>' + basePath;
781         playList.replace(startString, endString);
782     }
783
784     if (isArchive) {
785         m_temp = new KTemporaryFile;
786         if (!m_temp->open()) KMessageBox::error(this, i18n("Cannot create temporary file"));
787         m_temp->write(playList.toUtf8());
788         m_temp->close();
789         m_archiveThread = QtConcurrent::run(this, &ArchiveWidget::createArchive);
790         return true;
791     }
792     
793     QString path = archive_url->url().path(KUrl::AddTrailingSlash) + m_name + ".kdenlive";
794     QFile file(path);
795     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
796         kWarning() << "//////  ERROR writing to file: " << path;
797         KMessageBox::error(this, i18n("Cannot write to file %1", path));
798         return false;
799     }
800
801     file.write(m_doc.toString().toUtf8());
802     if (file.error() != QFile::NoError) {
803         KMessageBox::error(this, i18n("Cannot write to file %1", path));
804         file.close();
805         return false;
806     }
807     file.close();
808     return true;
809 }
810
811 void ArchiveWidget::createArchive()
812 {
813     QFileInfo dirInfo(archive_url->url().path());
814     QString user = dirInfo.owner();
815     QString group = dirInfo.group();
816     KTar archive(archive_url->url().path(KUrl::AddTrailingSlash) + m_name + ".tar.gz", "application/x-gzip");
817     archive.open( QIODevice::WriteOnly );
818
819     // Create folders
820     foreach(const QString &path, m_foldersList) {
821         archive.writeDir(path, user, group);
822     }
823
824     // Add files
825     int ix = 0;
826     QMapIterator<QString, QString> i(m_filesList);
827     while (i.hasNext()) {
828         i.next();
829         archive.addLocalFile(i.key(), i.value());
830         emit archiveProgress((int) 100 * ix / m_filesList.count());
831         ix++;
832     }
833
834     // Add project file
835     bool result = false;
836     if (m_temp) {
837         archive.addLocalFile(m_temp->fileName(), m_name + ".kdenlive");
838         result = archive.close();
839         delete m_temp;
840     }
841     emit archivingFinished(result);
842 }
843
844 void ArchiveWidget::slotArchivingFinished(bool result)
845 {
846     if (result) {
847         slotJobResult(true, i18n("Project was successfully archived."));
848         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
849     }
850     else {
851         slotJobResult(false, i18n("There was an error processing project file"));
852     }
853     progressBar->setValue(100);
854     buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Archive"));
855     archive_url->setEnabled(true);
856     proxy_only->setEnabled(true);
857     compressed_archive->setEnabled(true);
858     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
859         files_list->topLevelItem(i)->setDisabled(false);
860         for (int j = 0; j < files_list->topLevelItem(i)->childCount(); j++)
861             files_list->topLevelItem(i)->child(j)->setDisabled(false);
862     }
863 }
864
865 void ArchiveWidget::slotArchivingProgress(int p)
866 {
867     progressBar->setValue(p);
868 }
869
870 void ArchiveWidget::slotStartExtracting()
871 {
872     if (m_archiveThread.isRunning()) {
873         //TODO: abort extracting
874         return;
875     }
876     QFileInfo f(m_extractUrl.path());
877     m_requestedSize = f.size();
878     KIO::NetAccess::mkdir(archive_url->url().path(KUrl::RemoveTrailingSlash), this);
879     slotDisplayMessage("system-run", i18n("Extracting..."));
880     buttonBox->button(QDialogButtonBox::Apply)->setText(i18n("Abort"));
881     m_archiveThread = QtConcurrent::run(this, &ArchiveWidget::doExtracting);
882     m_progressTimer->start();
883 }
884
885 void ArchiveWidget::slotExtractProgress()
886 {
887     KIO::DirectorySizeJob *job = KIO::directorySize(archive_url->url());
888     connect(job, SIGNAL(result(KJob*)), this, SLOT(slotGotProgress(KJob*)));
889 }
890
891 void ArchiveWidget::slotGotProgress(KJob* job)
892 {
893     if (!job->error()) {
894         KIO::DirectorySizeJob *j = static_cast <KIO::DirectorySizeJob *>(job);
895         progressBar->setValue((int) 100 * j->totalSize() / m_requestedSize);
896     }
897     job->deleteLater();
898 }
899
900 void ArchiveWidget::doExtracting()
901 {
902     m_extractArchive->directory()->copyTo(archive_url->url().path(KUrl::AddTrailingSlash));
903     m_extractArchive->close();
904     emit extractingFinished();    
905 }
906
907 QString ArchiveWidget::extractedProjectFile()
908 {
909     return archive_url->url().path(KUrl::AddTrailingSlash) + m_projectName;
910 }
911
912 void ArchiveWidget::slotExtractingFinished()
913 {
914     m_progressTimer->stop();
915     // Process project file
916     QFile file(extractedProjectFile());
917     bool error = false;
918     if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
919         error = true;
920     }
921     else {
922         QString playList = QString::fromUtf8(file.readAll());
923         file.close();
924         if (playList.isEmpty()) {
925             error = true;
926         }
927         else {
928             playList.replace("$CURRENTPATH", archive_url->url().path(KUrl::RemoveTrailingSlash));
929             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
930                 kWarning() << "//////  ERROR writing to file: ";
931                 error = true;
932             }
933             else {
934                 file.write(playList.toUtf8());
935                 if (file.error() != QFile::NoError) {
936                     error = true;
937                 }
938                 file.close();
939             }
940         }
941     }
942     if (error) {
943         KMessageBox::sorry(kapp->activeWindow(), i18n("Cannot open project file %1", extractedProjectFile()), i18n("Cannot open file"));
944         reject();
945     }
946     else accept();
947 }
948
949 void ArchiveWidget::slotProxyOnly(int onlyProxy)
950 {
951     m_requestedSize = 0;
952     if (onlyProxy == Qt::Checked) {
953         // Archive proxy clips
954         QStringList proxyIdList;
955         QTreeWidgetItem *parentItem = NULL;
956
957         // Build list of existing proxy ids
958         for (int i = 0; i < files_list->topLevelItemCount(); i++) {
959             parentItem = files_list->topLevelItem(i);
960             if (parentItem->data(0, Qt::UserRole).toString() == "proxy") break;
961         }
962         if (!parentItem) return;
963         int items = parentItem->childCount();
964         for (int j = 0; j < items; j++) {
965             proxyIdList << parentItem->child(j)->data(0, Qt::UserRole + 2).toString();
966         }
967         
968         // Parse all items to disable original clips for existing proxies
969         for (int i = 0; i < proxyIdList.count(); i++) {
970             QString id = proxyIdList.at(i);
971             if (id.isEmpty()) continue;
972             for (int j = 0; j < files_list->topLevelItemCount(); j++) {
973                 parentItem = files_list->topLevelItem(j);
974                 if (parentItem->data(0, Qt::UserRole).toString() == "proxy") continue;
975                 items = parentItem->childCount();
976                 for (int k = 0; k < items; k++) {
977                     if (parentItem->child(k)->data(0, Qt::UserRole + 2).toString() == id) {
978                         // This item has a proxy, do not archive it
979                         parentItem->child(k)->setFlags(Qt::ItemIsSelectable);
980                         break;
981                     }
982                 }
983             }
984         }
985     }
986     else {
987         // Archive all clips
988         for (int i = 0; i < files_list->topLevelItemCount(); i++) {
989             QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
990             int items = parentItem->childCount();
991             for (int j = 0; j < items; j++) {
992                 parentItem->child(j)->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
993             }
994         }
995     }
996     
997     // Calculate requested size
998     int total = 0;
999     for (int i = 0; i < files_list->topLevelItemCount(); i++) {
1000         QTreeWidgetItem *parentItem = files_list->topLevelItem(i);
1001         int items = parentItem->childCount();
1002         int itemsCount = 0;
1003         bool isSlideshow = parentItem->data(0, Qt::UserRole).toString() == "slideshows";
1004         
1005         for (int j = 0; j < items; j++) {
1006             if (!parentItem->child(j)->isDisabled()) {
1007                 m_requestedSize += parentItem->child(j)->data(0, Qt::UserRole + 3).toInt();
1008                 if (isSlideshow) total += parentItem->child(j)->data(0, Qt::UserRole + 1).toStringList().count();
1009                 else total ++;
1010                 itemsCount ++;
1011             }
1012         }
1013         parentItem->setText(0, parentItem->text(0).section('(', 0, 0) + i18np("(%1 item)", "(%1 items)", itemsCount));
1014     }
1015     project_files->setText(i18np("%1 file to archive, requires %2", "%1 files to archive, requires %2", total, KIO::convertSize(m_requestedSize)));
1016     slotCheckSpace();
1017 }
1018