]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Some progress on clip jobs
[kdenlive] / src / projectlist.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 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 #include "projectlist.h"
21 #include "projectitem.h"
22 #include "commands/addfoldercommand.h"
23 #include "projecttree/proxyclipjob.h"
24 #include "kdenlivesettings.h"
25 #include "slideshowclip.h"
26 #include "ui_colorclip_ui.h"
27 #include "titlewidget.h"
28 #include "definitions.h"
29 #include "clipmanager.h"
30 #include "docclipbase.h"
31 #include "kdenlivedoc.h"
32 #include "renderer.h"
33 #include "kthumb.h"
34 #include "projectlistview.h"
35 #include "timecodedisplay.h"
36 #include "profilesdialog.h"
37 #include "commands/editclipcommand.h"
38 #include "commands/editclipcutcommand.h"
39 #include "commands/editfoldercommand.h"
40 #include "commands/addclipcutcommand.h"
41
42 #include "ui_templateclip_ui.h"
43
44 #include <KDebug>
45 #include <KAction>
46 #include <KLocale>
47 #include <KFileDialog>
48 #include <KInputDialog>
49 #include <KMessageBox>
50 #include <KIO/NetAccess>
51 #include <KFileItem>
52 #include <KApplication>
53 #include <KStandardDirs>
54 #include <KColorScheme>
55
56 #ifdef NEPOMUK
57 #include <nepomuk/global.h>
58 #include <nepomuk/resourcemanager.h>
59 //#include <nepomuk/tag.h>
60 #endif
61
62 #include <QMouseEvent>
63 #include <QStylePainter>
64 #include <QPixmap>
65 #include <QIcon>
66 #include <QMenu>
67 #include <QProcess>
68 #include <QHeaderView>
69 #include <QInputDialog>
70 #include <QtConcurrentRun>
71 #include <QVBoxLayout>
72
73 SmallInfoLabel::SmallInfoLabel(QWidget *parent) : QPushButton(parent)
74 {
75     setFixedWidth(0);
76     setFlat(true);
77     
78     /*QString style = "QToolButton {background-color: %1;border-style: outset;border-width: 2px;
79      border-radius: 5px;border-color: beige;}";*/
80     KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
81     QColor bg = scheme.background(KColorScheme::LinkBackground).color();
82     QColor fg = scheme.foreground(KColorScheme::LinkText).color();
83     QString style = QString("QPushButton {padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(fg.red()).arg(fg.green()).arg(fg.blue());
84     
85     bg = scheme.background(KColorScheme::ActiveBackground).color();
86     fg = scheme.foreground(KColorScheme::ActiveText).color();
87     style.append(QString("\nQPushButton:hover {padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(fg.red()).arg(fg.green()).arg(fg.blue()));
88     
89     setStyleSheet(style);
90     m_timeLine = new QTimeLine(500, this);
91     QObject::connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(slotTimeLineChanged(qreal)));
92     QObject::connect(m_timeLine, SIGNAL(finished()), this, SLOT(slotTimeLineFinished()));
93     hide();
94 }
95
96 void SmallInfoLabel::slotTimeLineChanged(qreal value)
97 {
98     setFixedWidth(qMin(value * 2, qreal(1.0)) * sizeHint().width());
99     update();
100 }
101
102 void SmallInfoLabel::slotTimeLineFinished()
103 {
104     if (m_timeLine->direction() == QTimeLine::Forward) {
105         // Show
106         show();
107     } else {
108         // Hide
109         hide();
110         setText(QString());
111     }
112 }
113
114 void SmallInfoLabel::slotSetJobCount(int jobCount)
115 {
116     if (jobCount > 0) {
117         // prepare animation
118         setText(i18np("%1 job", "%1 jobs", jobCount));
119         setToolTip(i18np("%1 pending job", "%1 pending jobs", jobCount));
120         
121         if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) {
122             show();
123             return;
124         }
125         
126         if (isVisible()) {
127             setFixedWidth(sizeHint().width());
128             update();
129             return;
130         }
131         
132         setFixedWidth(0);
133         show();
134         int wantedWidth = sizeHint().width();
135         setGeometry(-wantedWidth, 0, wantedWidth, height());
136         m_timeLine->setDirection(QTimeLine::Forward);
137         if (m_timeLine->state() == QTimeLine::NotRunning) {
138             m_timeLine->start();
139         }
140     }
141     else {
142         if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) {
143             hide();
144             return;
145         }
146         // hide
147         m_timeLine->setDirection(QTimeLine::Backward);
148         if (m_timeLine->state() == QTimeLine::NotRunning) {
149             m_timeLine->start();
150         }
151     }
152     
153 }
154
155
156 InvalidDialog::InvalidDialog(const QString &caption, const QString &message, bool infoOnly, QWidget *parent) : KDialog(parent)
157 {
158     setCaption(caption);
159     if (infoOnly) setButtons(KDialog::Ok);
160     else setButtons(KDialog::Yes | KDialog::No);
161     QWidget *w = new QWidget(this);
162     QVBoxLayout *l = new QVBoxLayout;
163     l->addWidget(new QLabel(message));
164     m_clipList = new QListWidget;
165     l->addWidget(m_clipList);
166     w->setLayout(l);
167     setMainWidget(w);
168 }
169
170 InvalidDialog::~InvalidDialog()
171 {
172     delete m_clipList;
173 }
174
175
176 void InvalidDialog::addClip(const QString &id, const QString &path)
177 {
178     QListWidgetItem *item = new QListWidgetItem(path);
179     item->setData(Qt::UserRole, id);
180     m_clipList->addItem(item);
181 }
182
183 QStringList InvalidDialog::getIds() const
184 {
185     QStringList ids;
186     for (int i = 0; i < m_clipList->count(); i++) {
187         ids << m_clipList->item(i)->data(Qt::UserRole).toString();
188     }
189     return ids;
190 }
191
192
193 ProjectList::ProjectList(QWidget *parent) :
194     QWidget(parent),
195     m_render(NULL),
196     m_fps(-1),
197     m_commandStack(NULL),
198     m_openAction(NULL),
199     m_reloadAction(NULL),
200     m_stabilizeAction(NULL),
201     m_transcodeAction(NULL),
202     m_doc(NULL),
203     m_refreshed(false),
204     m_allClipsProcessed(false),
205     m_thumbnailQueue(),
206     m_abortAllJobs(false),
207     m_closing(false),
208     m_invalidClipDialog(NULL)
209 {
210     qRegisterMetaType<stringMap> ("stringMap");
211     QVBoxLayout *layout = new QVBoxLayout;
212     layout->setContentsMargins(0, 0, 0, 0);
213     layout->setSpacing(0);
214     qRegisterMetaType<QDomElement>("QDomElement");
215     // setup toolbar
216     QFrame *frame = new QFrame;
217     frame->setFrameStyle(QFrame::NoFrame);
218     QHBoxLayout *box = new QHBoxLayout;
219     box->setContentsMargins(0, 0, 0, 0);
220     
221     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine;
222     box->addWidget(searchView);
223     
224     // small info button for pending jobs
225     m_infoLabel = new SmallInfoLabel(this);
226     connect(this, SIGNAL(jobCount(int)), m_infoLabel, SLOT(slotSetJobCount(int)));
227     m_jobsMenu = new QMenu(this);
228     QAction *cancelJobs = new QAction(i18n("Cancel All Jobs"), this);
229     cancelJobs->setCheckable(false);
230     connect(cancelJobs, SIGNAL(triggered()), this, SLOT(slotCancelJobs()));
231     m_jobsMenu->addAction(cancelJobs);
232     m_infoLabel->setMenu(m_jobsMenu);
233     box->addWidget(m_infoLabel);
234     
235     int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
236     QSize iconSize(size, size);
237
238     m_addButton = new QToolButton;
239     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
240     m_addButton->setAutoRaise(true);
241     m_addButton->setIconSize(iconSize);
242     box->addWidget(m_addButton);
243
244     m_editButton = new QToolButton;
245     m_editButton->setAutoRaise(true);
246     m_editButton->setIconSize(iconSize);
247     box->addWidget(m_editButton);
248
249     m_deleteButton = new QToolButton;
250     m_deleteButton->setAutoRaise(true);
251     m_deleteButton->setIconSize(iconSize);
252     box->addWidget(m_deleteButton);
253     frame->setLayout(box);
254     layout->addWidget(frame);
255
256     m_listView = new ProjectListView;
257     layout->addWidget(m_listView);
258     setLayout(layout);
259     searchView->setTreeWidget(m_listView);
260
261     connect(this, SIGNAL(processNextThumbnail()), this, SLOT(slotProcessNextThumbnail()));
262     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
263     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
264     connect(m_listView, SIGNAL(focusMonitor()), this, SIGNAL(raiseClipMonitor()));
265     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
266     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
267     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
268     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
269     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
270     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
271     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
272     
273     connect(this, SIGNAL(cancelRunningJob(const QString, stringMap )), this, SLOT(slotCancelRunningJob(const QString, stringMap)));
274
275     m_listViewDelegate = new ItemDelegate(m_listView);
276     m_listView->setItemDelegate(m_listViewDelegate);
277 #ifdef NEPOMUK
278     if (KdenliveSettings::activate_nepomuk()) {
279         Nepomuk::ResourceManager::instance()->init();
280         if (!Nepomuk::ResourceManager::instance()->initialized()) {
281             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
282             KdenliveSettings::setActivate_nepomuk(false);
283         }
284     }
285 #endif
286 }
287
288 ProjectList::~ProjectList()
289 {
290     m_abortAllJobs = true;
291     m_closing = true;
292     m_thumbnailQueue.clear();
293     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
294     m_jobList.clear();
295     delete m_menu;
296     m_listView->blockSignals(true);
297     m_listView->clear();
298     delete m_listViewDelegate;
299 }
300
301 void ProjectList::focusTree() const
302 {
303     m_listView->setFocus();
304 }
305
306 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
307 {
308     QList <QAction *> actions = addMenu->actions();
309     for (int i = 0; i < actions.count(); i++) {
310         if (actions.at(i)->data().toString() == "clip_properties") {
311             m_editButton->setDefaultAction(actions.at(i));
312             actions.removeAt(i);
313             i--;
314         } else if (actions.at(i)->data().toString() == "delete_clip") {
315             m_deleteButton->setDefaultAction(actions.at(i));
316             actions.removeAt(i);
317             i--;
318         } else if (actions.at(i)->data().toString() == "edit_clip") {
319             m_openAction = actions.at(i);
320             actions.removeAt(i);
321             i--;
322         } else if (actions.at(i)->data().toString() == "reload_clip") {
323             m_reloadAction = actions.at(i);
324             actions.removeAt(i);
325             i--;
326         } else if (actions.at(i)->data().toString() == "proxy_clip") {
327             m_proxyAction = actions.at(i);
328             actions.removeAt(i);
329             i--;
330         }
331     }
332
333     QMenu *m = new QMenu();
334     m->addActions(actions);
335     m_addButton->setMenu(m);
336     m_addButton->setDefaultAction(defaultAction);
337     m_menu = new QMenu();
338     m_menu->addActions(addMenu->actions());
339 }
340
341 void ProjectList::setupGeneratorMenu(const QHash<QString,QMenu*>& menus)
342 {
343     if (!menus.contains("addMenu") && ! menus.value("addMenu") )
344         return;
345     QMenu *menu = m_addButton->menu();
346         if (menus.contains("addMenu") && menus.value("addMenu")){ 
347                 QMenu* addMenu=menus.value("addMenu");
348                 menu->addMenu(addMenu);
349                 m_addButton->setMenu(menu);
350
351                 m_menu->addMenu(addMenu);
352                 if (addMenu->isEmpty())
353                         addMenu->setEnabled(false);
354         }
355         if (menus.contains("transcodeMenu") && menus.value("transcodeMenu") ){
356                 QMenu* transcodeMenu=menus.value("transcodeMenu");
357                 m_menu->addMenu(transcodeMenu);
358                 if (transcodeMenu->isEmpty())
359                         transcodeMenu->setEnabled(false);
360                 m_transcodeAction = transcodeMenu;
361         }
362         if (menus.contains("stabilizeMenu") && menus.value("stabilizeMenu") ){
363                 QMenu* stabilizeMenu=menus.value("stabilizeMenu");
364                 m_menu->addMenu(stabilizeMenu);
365                 if (stabilizeMenu->isEmpty())
366                         stabilizeMenu->setEnabled(false);
367                 m_stabilizeAction=stabilizeMenu;
368
369         }
370     m_menu->addAction(m_reloadAction);
371     m_menu->addAction(m_proxyAction);
372         if (menus.contains("inTimelineMenu") && menus.value("inTimelineMenu")){
373                 QMenu* inTimelineMenu=menus.value("inTimelineMenu");
374                 m_menu->addMenu(inTimelineMenu);
375                 inTimelineMenu->setEnabled(false);
376         }
377     m_menu->addAction(m_editButton->defaultAction());
378     m_menu->addAction(m_openAction);
379     m_menu->addAction(m_deleteButton->defaultAction());
380     m_menu->insertSeparator(m_deleteButton->defaultAction());
381 }
382
383 void ProjectList::clearSelection()
384 {
385     m_listView->clearSelection();
386 }
387
388 QByteArray ProjectList::headerInfo() const
389 {
390     return m_listView->header()->saveState();
391 }
392
393 void ProjectList::setHeaderInfo(const QByteArray &state)
394 {
395     m_listView->header()->restoreState(state);
396 }
397
398 void ProjectList::updateProjectFormat(Timecode t)
399 {
400     m_timecode = t;
401 }
402
403 void ProjectList::slotEditClip()
404 {
405     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
406     if (list.isEmpty()) return;
407     if (list.count() > 1 || list.at(0)->type() == PROJECTFOLDERTYPE) {
408         editClipSelection(list);
409         return;
410     }
411     ProjectItem *item;
412     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
413         return;
414     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE)
415         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
416     else
417         item = static_cast <ProjectItem*>(m_listView->currentItem());
418     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
419         emit clipSelected(item->referencedClip());
420         emit showClipProperties(item->referencedClip());
421     }
422 }
423
424 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
425 {
426     // Gather all common properties
427     QMap <QString, QString> commonproperties;
428     QList <DocClipBase *> clipList;
429     commonproperties.insert("force_aspect_num", "-");
430     commonproperties.insert("force_aspect_den", "-");
431     commonproperties.insert("force_fps", "-");
432     commonproperties.insert("force_progressive", "-");
433     commonproperties.insert("force_tff", "-");
434     commonproperties.insert("threads", "-");
435     commonproperties.insert("video_index", "-");
436     commonproperties.insert("audio_index", "-");
437     commonproperties.insert("force_colorspace", "-");
438     commonproperties.insert("full_luma", "-");
439     QString transparency = "-";
440
441     bool allowDurationChange = true;
442     int commonDuration = -1;
443     bool hasImages = false;;
444     ProjectItem *item;
445     for (int i = 0; i < list.count(); i++) {
446         item = NULL;
447         if (list.at(i)->type() == PROJECTFOLDERTYPE) {
448             // Add folder items to the list
449             int ct = list.at(i)->childCount();
450             for (int j = 0; j < ct; j++) {
451                 list.append(list.at(i)->child(j));
452             }
453             continue;
454         }
455         else if (list.at(i)->type() == PROJECTSUBCLIPTYPE)
456             item = static_cast <ProjectItem*>(list.at(i)->parent());
457         else
458             item = static_cast <ProjectItem*>(list.at(i));
459         if (!(item->flags() & Qt::ItemIsDragEnabled))
460             continue;
461         if (item) {
462             // check properties
463             DocClipBase *clip = item->referencedClip();
464             if (clipList.contains(clip)) continue;
465             if (clip->clipType() == IMAGE) {
466                 hasImages = true;
467                 if (clip->getProperty("transparency").isEmpty() || clip->getProperty("transparency").toInt() == 0) {
468                     if (transparency == "-") {
469                         // first non transparent image
470                         transparency = "0";
471                     }
472                     else if (transparency == "1") {
473                         // we have transparent and non transparent clips
474                         transparency = "-1";
475                     }
476                 }
477                 else {
478                     if (transparency == "-") {
479                         // first transparent image
480                         transparency = "1";
481                     }
482                     else if (transparency == "0") {
483                         // we have transparent and non transparent clips
484                         transparency = "-1";
485                     }
486                 }
487             }
488             if (clip->clipType() != COLOR && clip->clipType() != IMAGE && clip->clipType() != TEXT)
489                 allowDurationChange = false;
490             if (allowDurationChange && commonDuration != 0) {
491                 if (commonDuration == -1)
492                     commonDuration = clip->duration().frames(m_fps);
493                 else if (commonDuration != clip->duration().frames(m_fps))
494                     commonDuration = 0;
495             }
496             clipList.append(clip);
497             QMap <QString, QString> clipprops = clip->properties();
498             QMapIterator<QString, QString> p(commonproperties);
499             while (p.hasNext()) {
500                 p.next();
501                 if (p.value().isEmpty()) continue;
502                 if (clipprops.contains(p.key())) {
503                     if (p.value() == "-")
504                         commonproperties.insert(p.key(), clipprops.value(p.key()));
505                     else if (p.value() != clipprops.value(p.key()))
506                         commonproperties.insert(p.key(), QString());
507                 } else {
508                     commonproperties.insert(p.key(), QString());
509                 }
510             }
511         }
512     }
513     if (allowDurationChange)
514         commonproperties.insert("out", QString::number(commonDuration));
515     if (hasImages)
516         commonproperties.insert("transparency", transparency);
517     /*QMapIterator<QString, QString> p(commonproperties);
518     while (p.hasNext()) {
519         p.next();
520         kDebug() << "Result: " << p.key() << " = " << p.value();
521     }*/
522     emit showClipProperties(clipList, commonproperties);
523 }
524
525 void ProjectList::slotOpenClip()
526 {
527     ProjectItem *item;
528     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
529         return;
530     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1)
531         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
532     else
533         item = static_cast <ProjectItem*>(m_listView->currentItem());
534     if (item) {
535         if (item->clipType() == IMAGE) {
536             if (KdenliveSettings::defaultimageapp().isEmpty())
537                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open images in the Settings dialog"));
538             else
539                 QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
540         }
541         if (item->clipType() == AUDIO) {
542             if (KdenliveSettings::defaultaudioapp().isEmpty())
543                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open audio files in the Settings dialog"));
544             else
545                 QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
546         }
547     }
548 }
549
550 void ProjectList::cleanup()
551 {
552     m_listView->clearSelection();
553     QTreeWidgetItemIterator it(m_listView);
554     ProjectItem *item;
555     while (*it) {
556         if ((*it)->type() != PROJECTCLIPTYPE) {
557             it++;
558             continue;
559         }
560         item = static_cast <ProjectItem *>(*it);
561         if (item->numReferences() == 0)
562             item->setSelected(true);
563         it++;
564     }
565     slotRemoveClip();
566 }
567
568 void ProjectList::trashUnusedClips()
569 {
570     QTreeWidgetItemIterator it(m_listView);
571     ProjectItem *item;
572     QStringList ids;
573     QStringList urls;
574     while (*it) {
575         if ((*it)->type() != PROJECTCLIPTYPE) {
576             it++;
577             continue;
578         }
579         item = static_cast <ProjectItem *>(*it);
580         if (item->numReferences() == 0) {
581             ids << item->clipId();
582             KUrl url = item->clipUrl();
583             if (!url.isEmpty() && !urls.contains(url.path()))
584                 urls << url.path();
585         }
586         it++;
587     }
588
589     // Check that we don't use the URL in another clip
590     QTreeWidgetItemIterator it2(m_listView);
591     while (*it2) {
592         if ((*it2)->type() != PROJECTCLIPTYPE) {
593             it2++;
594             continue;
595         }
596         item = static_cast <ProjectItem *>(*it2);
597         if (item->numReferences() > 0) {
598             KUrl url = item->clipUrl();
599             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
600         }
601         it2++;
602     }
603
604     emit deleteProjectClips(ids, QMap <QString, QString>());
605     for (int i = 0; i < urls.count(); i++)
606         KIO::NetAccess::del(KUrl(urls.at(i)), this);
607 }
608
609 void ProjectList::slotReloadClip(const QString &id)
610 {
611     QList<QTreeWidgetItem *> selected;
612     if (id.isEmpty())
613         selected = m_listView->selectedItems();
614     else {
615         ProjectItem *itemToReLoad = getItemById(id);
616         if (itemToReLoad) selected.append(itemToReLoad);
617     }
618     ProjectItem *item;
619     for (int i = 0; i < selected.count(); i++) {
620         if (selected.at(i)->type() != PROJECTCLIPTYPE) {
621             if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
622                 for (int j = 0; j < selected.at(i)->childCount(); j++)
623                     selected.append(selected.at(i)->child(j));
624             }
625             continue;
626         }
627         item = static_cast <ProjectItem *>(selected.at(i));
628         if (item && !item->isProxyRunning()) {
629             DocClipBase *clip = item->referencedClip();
630             if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
631                 kDebug()<<"//// TRYING TO RELOAD: "<<item->clipId()<<", but it is busy";
632                 continue;
633             }
634             CLIPTYPE t = item->clipType();
635             if (t == TEXT) {
636                 if (clip && !clip->getProperty("xmltemplate").isEmpty())
637                     regenerateTemplate(item);
638             } else if (t != COLOR && t != SLIDESHOW && clip && clip->checkHash() == false) {
639                 item->referencedClip()->setPlaceHolder(true);
640                 item->setProperty("file_hash", QString());
641             } else if (t == IMAGE) {
642                 clip->getProducer()->set("force_reload", 1);
643             }
644
645             QDomElement e = item->toXml();
646             // Make sure we get the correct producer length if it was adjusted in timeline
647             if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
648                 int length = QString(clip->producerProperty("length")).toInt();
649                 if (length > 0 && !e.hasAttribute("length")) {
650                     e.setAttribute("length", length);
651                 }
652             }
653             resetThumbsProducer(clip);
654             m_render->getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true);
655         }
656     }
657 }
658
659 void ProjectList::slotModifiedClip(const QString &id)
660 {
661     ProjectItem *item = getItemById(id);
662     if (item) {
663         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
664         if (!pixmap.isNull()) {
665             QPainter p(&pixmap);
666             p.fillRect(0, 0, pixmap.width(), pixmap.height(), QColor(255, 255, 255, 200));
667             p.drawPixmap(0, 0, KIcon("view-refresh").pixmap(m_listView->iconSize()));
668             p.end();
669         } else {
670             pixmap = KIcon("view-refresh").pixmap(m_listView->iconSize());
671         }
672         item->setData(0, Qt::DecorationRole, pixmap);
673     }
674 }
675
676 void ProjectList::slotMissingClip(const QString &id)
677 {
678     ProjectItem *item = getItemById(id);
679     if (item) {
680         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
681         int height = m_listView->iconSize().height();
682         int width = (int)(height  * m_render->dar());
683         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
684         if (pixmap.isNull()) {
685             pixmap = QPixmap(width, height);
686             pixmap.fill(Qt::transparent);
687         }
688         KIcon icon("dialog-close");
689         QPainter p(&pixmap);
690         p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
691         p.end();
692         item->setData(0, Qt::DecorationRole, pixmap);
693         if (item->referencedClip()) {
694             item->referencedClip()->setPlaceHolder(true);
695             if (m_render == NULL) {
696                 kDebug() << "*********  ERROR, NULL RENDR";
697                 return;
698             }
699             Mlt::Producer *newProd = m_render->invalidProducer(id);
700             if (item->referencedClip()->getProducer()) {
701                 Mlt::Properties props(newProd->get_properties());
702                 Mlt::Properties src_props(item->referencedClip()->getProducer()->get_properties());
703                 props.inherit(src_props);
704             }
705             item->referencedClip()->setProducer(newProd, true);
706             item->slotSetToolTip();
707             emit clipNeedsReload(id);
708         }
709     }
710     update();
711     emit displayMessage(i18n("Check missing clips"), -2);
712     emit updateRenderStatus();
713 }
714
715 void ProjectList::slotAvailableClip(const QString &id)
716 {
717     ProjectItem *item = getItemById(id);
718     if (item == NULL)
719         return;
720     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
721     if (item->referencedClip()) { // && item->referencedClip()->checkHash() == false) {
722         item->setProperty("file_hash", QString());
723         slotReloadClip(id);
724     }
725     /*else {
726     item->referencedClip()->setValid();
727     item->slotSetToolTip();
728     }
729     update();*/
730     emit updateRenderStatus();
731 }
732
733 bool ProjectList::hasMissingClips()
734 {
735     bool missing = false;
736     QTreeWidgetItemIterator it(m_listView);
737     while (*it) {
738         if ((*it)->type() == PROJECTCLIPTYPE && !((*it)->flags() & Qt::ItemIsDragEnabled)) {
739             missing = true;
740             break;
741         }
742         it++;
743     }
744     return missing;
745 }
746
747 void ProjectList::setRenderer(Render *projectRender)
748 {
749     m_render = projectRender;
750     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
751 }
752
753 void ProjectList::slotClipSelected()
754 {
755     QTreeWidgetItem *item = m_listView->currentItem();
756     ProjectItem *clip = NULL;
757     if (item) {
758         if (item->type() == PROJECTFOLDERTYPE) {
759             emit clipSelected(NULL);
760             m_editButton->defaultAction()->setEnabled(item->childCount() > 0);
761             m_deleteButton->defaultAction()->setEnabled(true);
762             m_openAction->setEnabled(false);
763             m_reloadAction->setEnabled(false);
764             m_transcodeAction->setEnabled(false);
765             m_stabilizeAction->setEnabled(false);
766         } else {
767             if (item->type() == PROJECTSUBCLIPTYPE) {
768                 // this is a sub item, use base clip
769                 m_deleteButton->defaultAction()->setEnabled(true);
770                 clip = static_cast <ProjectItem*>(item->parent());
771                 if (clip == NULL) kDebug() << "-----------ERROR";
772                 SubProjectItem *sub = static_cast <SubProjectItem*>(item);
773                 emit clipSelected(clip->referencedClip(), sub->zone());
774                 m_transcodeAction->setEnabled(false);
775                 m_stabilizeAction->setEnabled(false);
776                 m_reloadAction->setEnabled(false);
777                 adjustProxyActions(clip);
778                 return;
779             }
780             clip = static_cast <ProjectItem*>(item);
781             if (clip && clip->referencedClip())
782                 emit clipSelected(clip->referencedClip());
783             m_editButton->defaultAction()->setEnabled(true);
784             m_deleteButton->defaultAction()->setEnabled(true);
785             m_reloadAction->setEnabled(true);
786             m_transcodeAction->setEnabled(true);
787             m_stabilizeAction->setEnabled(true);
788             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
789                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
790                 m_openAction->setEnabled(true);
791             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
792                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
793                 m_openAction->setEnabled(true);
794             } else {
795                 m_openAction->setEnabled(false);
796             }
797             // Display relevant transcoding actions only
798             adjustTranscodeActions(clip);
799             adjustStabilizeActions(clip);
800             // Display uses in timeline
801             emit findInTimeline(clip->clipId());
802         }
803     } else {
804         emit clipSelected(NULL);
805         m_editButton->defaultAction()->setEnabled(false);
806         m_deleteButton->defaultAction()->setEnabled(false);
807         m_openAction->setEnabled(false);
808         m_reloadAction->setEnabled(false);
809         m_transcodeAction->setEnabled(false);
810         m_stabilizeAction->setEnabled(false);
811     }
812     adjustProxyActions(clip);
813 }
814
815 void ProjectList::adjustProxyActions(ProjectItem *clip) const
816 {
817     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == SLIDESHOW || clip->clipType() == AUDIO) {
818         m_proxyAction->setEnabled(false);
819         return;
820     }
821     m_proxyAction->setEnabled(useProxy());
822     m_proxyAction->blockSignals(true);
823     m_proxyAction->setChecked(clip->hasProxy());
824     m_proxyAction->blockSignals(false);
825 }
826
827 void ProjectList::adjustStabilizeActions(ProjectItem *clip) const
828 {
829
830     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW) {
831         m_stabilizeAction->setEnabled(false);
832         return;
833     }
834         m_stabilizeAction->setEnabled(true);
835
836 }
837
838 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
839 {
840     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW) {
841         m_transcodeAction->setEnabled(false);
842         return;
843     }
844     m_transcodeAction->setEnabled(true);
845     QList<QAction *> transcodeActions = m_transcodeAction->actions();
846     QStringList data;
847     QString condition;
848     for (int i = 0; i < transcodeActions.count(); i++) {
849         data = transcodeActions.at(i)->data().toStringList();
850         if (data.count() > 2) {
851             condition = data.at(2);
852             if (condition.startsWith("vcodec"))
853                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
854             else if (condition.startsWith("acodec"))
855                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
856         }
857     }
858
859 }
860
861 void ProjectList::slotPauseMonitor()
862 {
863     if (m_render)
864         m_render->pause();
865 }
866
867 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
868 {
869     ProjectItem *item = getItemById(id);
870     if (item) {
871         slotUpdateClipProperties(item, properties);
872         if (properties.contains("out") || properties.contains("force_fps") || properties.contains("resource")) {
873             slotReloadClip(id);
874         } else if (properties.contains("colour") ||
875                    properties.contains("xmldata") ||
876                    properties.contains("force_aspect_num") ||
877                    properties.contains("force_aspect_den") ||
878                    properties.contains("templatetext")) {
879             slotRefreshClipThumbnail(item);
880             emit refreshClip(id, true);
881         } else if (properties.contains("full_luma") || properties.contains("force_colorspace") || properties.contains("loop")) {
882             emit refreshClip(id, false);
883         }
884     }
885 }
886
887 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
888 {
889     if (!clip)
890         return;
891     clip->setProperties(properties);
892     if (properties.contains("proxy")) {
893         if (properties.value("proxy") == "-" || properties.value("proxy").isEmpty())
894             clip->setProxyStatus(NOJOB);
895     }
896     if (properties.contains("name")) {
897         monitorItemEditing(false);
898         clip->setText(0, properties.value("name"));
899         monitorItemEditing(true);
900         emit clipNameChanged(clip->clipId(), properties.value("name"));
901     }
902     if (properties.contains("description")) {
903         CLIPTYPE type = clip->clipType();
904         monitorItemEditing(false);
905         clip->setText(1, properties.value("description"));
906         monitorItemEditing(true);
907 #ifdef NEPOMUK
908         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
909             // Use Nepomuk system to store clip description
910             Nepomuk::Resource f(clip->clipUrl().path());
911             f.setDescription(properties.value("description"));
912         }
913 #endif
914         emit projectModified();
915     }
916 }
917
918 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
919 {
920     if (item->type() == PROJECTSUBCLIPTYPE) {
921         // this is a sub-item
922         if (column == 1) {
923             // user edited description
924             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
925             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
926             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
927             m_commandStack->push(command);
928             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
929         }
930         return;
931     }
932     if (item->type() == PROJECTFOLDERTYPE) {
933         if (column == 0) {
934             FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
935             editFolder(item->text(0), folder->groupName(), folder->clipId());
936             folder->setGroupName(item->text(0));
937             m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
938             const int children = item->childCount();
939             for (int i = 0; i < children; i++) {
940                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
941                 child->setProperty("groupname", item->text(0));
942             }
943         }
944         return;
945     }
946
947     ProjectItem *clip = static_cast <ProjectItem*>(item);
948     if (column == 1) {
949         if (clip->referencedClip()) {
950             QMap <QString, QString> oldprops;
951             QMap <QString, QString> newprops;
952             oldprops["description"] = clip->referencedClip()->getProperty("description");
953             newprops["description"] = item->text(1);
954
955             if (clip->clipType() == TEXT) {
956                 // This is a text template clip, update the image
957                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
958                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
959                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
960                 newprops.insert("templatetext", item->text(1));
961             }
962             slotUpdateClipProperties(clip->clipId(), newprops);
963             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
964             m_commandStack->push(command);
965         }
966     } else if (column == 0) {
967         if (clip->referencedClip()) {
968             QMap <QString, QString> oldprops;
969             QMap <QString, QString> newprops;
970             oldprops["name"] = clip->referencedClip()->getProperty("name");
971             if (oldprops.value("name") != item->text(0)) {
972                 newprops["name"] = item->text(0);
973                 slotUpdateClipProperties(clip, newprops);
974                 emit projectModified();
975                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
976                 m_commandStack->push(command);
977             }
978         }
979     }
980 }
981
982 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
983 {
984     bool enable = item ? true : false;
985     m_editButton->defaultAction()->setEnabled(enable);
986     m_deleteButton->defaultAction()->setEnabled(enable);
987     m_reloadAction->setEnabled(enable);
988     m_transcodeAction->setEnabled(enable);
989     m_stabilizeAction->setEnabled(enable);
990     if (enable) {
991         ProjectItem *clip = NULL;
992         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
993             clip = static_cast <ProjectItem*>(item->parent());
994             m_transcodeAction->setEnabled(false);
995             m_stabilizeAction->setEnabled(false);
996             adjustProxyActions(clip);
997         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
998             clip = static_cast <ProjectItem*>(item);
999             // Display relevant transcoding actions only
1000             adjustTranscodeActions(clip);
1001             adjustStabilizeActions(clip);
1002             adjustProxyActions(clip);
1003             // Display uses in timeline
1004             emit findInTimeline(clip->clipId());
1005         } else {
1006             m_transcodeAction->setEnabled(false);
1007             m_stabilizeAction->setEnabled(false);
1008         }
1009         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1010             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1011             m_openAction->setEnabled(true);
1012         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1013             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1014             m_openAction->setEnabled(true);
1015         } else {
1016             m_openAction->setEnabled(false);
1017         }
1018
1019     } else {
1020         m_openAction->setEnabled(false);
1021     }
1022     m_menu->popup(pos);
1023 }
1024
1025 void ProjectList::slotRemoveClip()
1026 {
1027     if (!m_listView->currentItem())
1028         return;
1029     QStringList ids;
1030     QMap <QString, QString> folderids;
1031     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
1032
1033     QUndoCommand *delCommand = new QUndoCommand();
1034     delCommand->setText(i18n("Delete Clip Zone"));
1035     for (int i = 0; i < selected.count(); i++) {
1036         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
1037             // subitem
1038             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
1039             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1040             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
1041         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
1042             // folder
1043             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
1044             folderids[folder->groupName()] = folder->clipId();
1045             int children = folder->childCount();
1046
1047             if (children > 0 && KMessageBox::questionYesNo(kapp->activeWindow(), i18np("Delete folder <b>%2</b>?<br />This will also remove the clip in that folder", "Delete folder <b>%2</b>?<br />This will also remove the %1 clips in that folder",  children, folder->text(1)), i18n("Delete Folder")) != KMessageBox::Yes)
1048                 return;
1049             for (int i = 0; i < children; ++i) {
1050                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
1051                 ids << child->clipId();
1052             }
1053         } else {
1054             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
1055             ids << item->clipId();
1056             if (item->numReferences() > 0 && KMessageBox::questionYesNo(kapp->activeWindow(), i18np("Delete clip <b>%2</b>?<br />This will also remove the clip in timeline", "Delete clip <b>%2</b>?<br />This will also remove its %1 clips in timeline", item->numReferences(), item->names().at(1)), i18n("Delete Clip"), KStandardGuiItem::yes(), KStandardGuiItem::no(), "DeleteAll") == KMessageBox::No) {
1057                 KMessageBox::enableMessage("DeleteAll");
1058                 return;
1059             }
1060         }
1061     }
1062     KMessageBox::enableMessage("DeleteAll");
1063     if (delCommand->childCount() == 0)
1064         delete delCommand;
1065     else
1066         m_commandStack->push(delCommand);
1067     emit deleteProjectClips(ids, folderids);
1068 }
1069
1070 void ProjectList::updateButtons() const
1071 {
1072     if (m_listView->topLevelItemCount() == 0) {
1073         m_deleteButton->defaultAction()->setEnabled(false);
1074         m_editButton->defaultAction()->setEnabled(false);
1075     } else {
1076         m_deleteButton->defaultAction()->setEnabled(true);
1077         if (!m_listView->currentItem())
1078             m_listView->setCurrentItem(m_listView->topLevelItem(0));
1079         QTreeWidgetItem *item = m_listView->currentItem();
1080         if (item && item->type() == PROJECTCLIPTYPE) {
1081             m_editButton->defaultAction()->setEnabled(true);
1082             m_openAction->setEnabled(true);
1083             m_reloadAction->setEnabled(true);
1084             m_transcodeAction->setEnabled(true);
1085             m_stabilizeAction->setEnabled(true);
1086             return;
1087         }
1088         else if (item && item->type() == PROJECTFOLDERTYPE && item->childCount() > 0) {
1089             m_editButton->defaultAction()->setEnabled(true);
1090         }
1091         else m_editButton->defaultAction()->setEnabled(false);
1092     }
1093     m_openAction->setEnabled(false);
1094     m_reloadAction->setEnabled(false);
1095     m_transcodeAction->setEnabled(false);
1096     m_stabilizeAction->setEnabled(false);
1097     m_proxyAction->setEnabled(false);
1098 }
1099
1100 void ProjectList::selectItemById(const QString &clipId)
1101 {
1102     ProjectItem *item = getItemById(clipId);
1103     if (item)
1104         m_listView->setCurrentItem(item);
1105 }
1106
1107
1108 void ProjectList::slotDeleteClip(const QString &clipId)
1109 {
1110     ProjectItem *item = getItemById(clipId);
1111     if (!item) {
1112         kDebug() << "/// Cannot find clip to delete";
1113         return;
1114     }
1115     if (item->isProxyRunning()) m_abortProxy.append(item->referencedClip()->getProperty("proxy"));
1116     m_listView->blockSignals(true);
1117     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
1118     if (!newSelectedItem)
1119         newSelectedItem = m_listView->itemBelow(item);
1120     delete item;
1121     // Pause playing to prevent crash while deleting clip
1122     slotPauseMonitor();
1123     m_doc->clipManager()->deleteClip(clipId);
1124     m_listView->blockSignals(false);
1125     if (newSelectedItem) {
1126         m_listView->setCurrentItem(newSelectedItem);
1127     } else {
1128         updateButtons();
1129         emit clipSelected(NULL);
1130     }
1131 }
1132
1133
1134 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
1135 {
1136     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
1137     m_commandStack->push(command);
1138     m_doc->setModified(true);
1139 }
1140
1141 void ProjectList::slotAddFolder()
1142 {
1143     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
1144     m_commandStack->push(command);
1145 }
1146
1147 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
1148 {
1149     if (remove) {
1150         FolderProjectItem *item = getFolderItemById(clipId);
1151         if (item) {
1152             m_doc->clipManager()->deleteFolder(clipId);
1153             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
1154             if (!newSelectedItem)
1155                 newSelectedItem = m_listView->itemBelow(item);
1156             delete item;
1157             if (newSelectedItem)
1158                 m_listView->setCurrentItem(newSelectedItem);
1159             else
1160                 updateButtons();
1161         }
1162     } else {
1163         if (edit) {
1164             FolderProjectItem *item = getFolderItemById(clipId);
1165             if (item) {
1166                 m_listView->blockSignals(true);
1167                 item->setGroupName(foldername);
1168                 m_listView->blockSignals(false);
1169                 m_doc->clipManager()->addFolder(clipId, foldername);
1170                 const int children = item->childCount();
1171                 for (int i = 0; i < children; i++) {
1172                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
1173                     child->setProperty("groupname", foldername);
1174                 }
1175             }
1176         } else {
1177             m_listView->blockSignals(true);
1178             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
1179             m_doc->clipManager()->addFolder(clipId, foldername);
1180             m_listView->blockSignals(false);
1181             m_listView->editItem(m_listView->currentItem(), 0);
1182         }
1183         updateButtons();
1184     }
1185     m_doc->setModified(true);
1186 }
1187
1188
1189
1190 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
1191 {
1192     QMapIterator<QString, QString> i(map);
1193     QUndoCommand *delCommand = new QUndoCommand();
1194     delCommand->setText(i18n("Delete Folder"));
1195     while (i.hasNext()) {
1196         i.next();
1197         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
1198     }
1199     if (delCommand->childCount() > 0) m_commandStack->push(delCommand);
1200     else delete delCommand;
1201 }
1202
1203 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
1204 {
1205     //m_listView->setEnabled(false);
1206     const QString parent = clip->getProperty("groupid");
1207     ProjectItem *item = NULL;
1208     monitorItemEditing(false);
1209     if (!parent.isEmpty()) {
1210         FolderProjectItem *parentitem = getFolderItemById(parent);
1211         if (!parentitem) {
1212             QStringList text;
1213             QString groupName = clip->getProperty("groupname");
1214             //kDebug() << "Adding clip to new group: " << groupName;
1215             if (groupName.isEmpty()) groupName = i18n("Folder");
1216             text << groupName;
1217             parentitem = new FolderProjectItem(m_listView, text, parent);
1218         }
1219
1220         if (parentitem)
1221             item = new ProjectItem(parentitem, clip);
1222     }
1223     if (item == NULL) {
1224         item = new ProjectItem(m_listView, clip);
1225     }
1226     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
1227     connect(clip, SIGNAL(createProxy(const QString &)), this, SLOT(slotCreateProxy(const QString &)));
1228     connect(clip, SIGNAL(abortProxy(const QString &, const QString &)), this, SLOT(slotAbortProxy(const QString, const QString)));
1229     if (getProperties) {
1230         int height = m_listView->iconSize().height();
1231         int width = (int)(height  * m_render->dar());
1232         QPixmap pix =  KIcon("video-x-generic").pixmap(QSize(width, height));
1233         item->setData(0, Qt::DecorationRole, pix);
1234         //item->setFlags(Qt::ItemIsSelectable);
1235         m_listView->processLayout();
1236         QDomElement e = clip->toXML().cloneNode().toElement();
1237         e.removeAttribute("file_hash");
1238         resetThumbsProducer(clip);
1239         m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1240     }
1241     // WARNING: code below triggers unnecessary reload of all proxy clips on document loading... is it useful in some cases?
1242     /*else if (item->hasProxy() && !item->isProxyRunning()) {
1243         slotCreateProxy(clip->getId());
1244     }*/
1245     
1246     KUrl url = clip->fileURL();
1247 #ifdef NEPOMUK
1248     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
1249         // if file has Nepomuk comment, use it
1250         Nepomuk::Resource f(url.path());
1251         QString annotation = f.description();
1252         if (!annotation.isEmpty()) item->setText(1, annotation);
1253         item->setText(2, QString::number(f.rating()));
1254     }
1255 #endif
1256
1257     // Add info to date column
1258     QFileInfo fileInfo(url.path());
1259     if (fileInfo.exists()) {
1260         item->setText(3, fileInfo.lastModified().toString(QString("yyyy/MM/dd hh:mm:ss")));
1261     }
1262
1263     // Add cut zones
1264     QList <CutZoneInfo> cuts = clip->cutZones();
1265     if (!cuts.isEmpty()) {
1266         for (int i = 0; i < cuts.count(); i++) {
1267             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1268             if (!clip->getClipHash().isEmpty()) {
1269                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1270                 if (QFile::exists(cachedPixmap)) {
1271                     QPixmap pix(cachedPixmap);
1272                     if (pix.isNull())
1273                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1274                     sub->setData(0, Qt::DecorationRole, pix);
1275                 }
1276             }
1277         }
1278     }
1279     monitorItemEditing(true);
1280     updateButtons();
1281 }
1282
1283 void ProjectList::slotGotProxy(const QString &proxyPath)
1284 {
1285     if (proxyPath.isEmpty() || m_abortAllJobs) return;
1286     QTreeWidgetItemIterator it(m_listView);
1287     ProjectItem *item;
1288
1289     while (*it && !m_abortAllJobs) {
1290         if ((*it)->type() == PROJECTCLIPTYPE) {
1291             item = static_cast <ProjectItem *>(*it);
1292             if (item->referencedClip()->getProperty("proxy") == proxyPath)
1293                 slotGotProxy(item);
1294         }
1295         ++it;
1296     }
1297 }
1298
1299 void ProjectList::slotGotProxy(ProjectItem *item)
1300 {
1301     if (item == NULL) return;
1302     DocClipBase *clip = item->referencedClip();
1303     if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
1304         // Clip is being reprocessed, abort
1305         kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
1306         return;
1307     }
1308     
1309     // Proxy clip successfully created
1310     QDomElement e = clip->toXML().cloneNode().toElement();
1311
1312     // Make sure we get the correct producer length if it was adjusted in timeline
1313     CLIPTYPE t = item->clipType();
1314     if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
1315         int length = QString(clip->producerProperty("length")).toInt();
1316         if (length > 0 && !e.hasAttribute("length")) {
1317             e.setAttribute("length", length);
1318         }
1319     }
1320     resetThumbsProducer(clip);
1321     m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1322 }
1323
1324 void ProjectList::slotResetProjectList()
1325 {
1326     m_listView->blockSignals(true);
1327     m_abortAllJobs = true;
1328     m_closing = true;
1329     m_proxyThreads.waitForFinished();
1330     m_proxyThreads.clearFutures();
1331     m_thumbnailQueue.clear();
1332     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
1333     m_jobList.clear();
1334     m_listView->clear();
1335     m_listView->setEnabled(true);
1336     emit clipSelected(NULL);
1337     m_refreshed = false;
1338     m_allClipsProcessed = false;
1339     m_abortAllJobs = false;
1340     m_closing = false;
1341     m_listView->blockSignals(false);
1342 }
1343
1344 void ProjectList::slotUpdateClip(const QString &id)
1345 {
1346     ProjectItem *item = getItemById(id);
1347     monitorItemEditing(false);
1348     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1349     monitorItemEditing(true);
1350 }
1351
1352 void ProjectList::getCachedThumbnail(ProjectItem *item)
1353 {
1354     if (!item) return;
1355     DocClipBase *clip = item->referencedClip();
1356     if (!clip) return;
1357     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
1358     if (QFile::exists(cachedPixmap)) {
1359         QPixmap pix(cachedPixmap);
1360         if (pix.isNull()) {
1361             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1362             requestClipThumbnail(item->clipId());
1363         }
1364         else {
1365             processThumbOverlays(item, pix);
1366             item->setData(0, Qt::DecorationRole, pix);
1367         }
1368     }
1369     else {
1370         requestClipThumbnail(item->clipId());
1371     }
1372 }
1373
1374 void ProjectList::getCachedThumbnail(SubProjectItem *item)
1375 {
1376     if (!item) return;
1377     ProjectItem *parentItem = static_cast <ProjectItem *>(item->parent());
1378     if (!parentItem) return;
1379     DocClipBase *clip = parentItem->referencedClip();
1380     if (!clip) return;
1381     int pos = item->zone().x();
1382     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + "#" + QString::number(pos) + ".png";
1383     if (QFile::exists(cachedPixmap)) {
1384         QPixmap pix(cachedPixmap);
1385         if (pix.isNull()) {
1386             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1387             requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1388         }
1389         else item->setData(0, Qt::DecorationRole, pix);
1390     }
1391     else requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1392 }
1393
1394 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged, QStringList brokenClips)
1395 {
1396     if (!m_allClipsProcessed) m_listView->setEnabled(false);
1397     m_listView->setSortingEnabled(false);
1398     QTreeWidgetItemIterator it(m_listView);
1399     DocClipBase *clip;
1400     ProjectItem *item;
1401     monitorItemEditing(false);
1402     int height = m_listView->iconSize().height();
1403     int width = (int)(height  * m_render->dar());
1404     QPixmap missingPixmap = QPixmap(width, height);
1405     missingPixmap.fill(Qt::transparent);
1406     KIcon icon("dialog-close");
1407     QPainter p(&missingPixmap);
1408     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1409     p.end();
1410     
1411     int max = m_doc->clipManager()->clipsCount();
1412     max = qMax(1, max);
1413     int ct = 0;
1414
1415     while (*it) {
1416         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - ct++) / max));
1417         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1418             // subitem
1419             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1420             if (displayRatioChanged) {
1421                 item = static_cast <ProjectItem *>((*it)->parent());
1422                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1423             }
1424             else if (sub->data(0, Qt::DecorationRole).isNull()) {
1425                 getCachedThumbnail(sub);
1426             }
1427             ++it;
1428             continue;
1429         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1430             // folder
1431             ++it;
1432             continue;
1433         } else {
1434             item = static_cast <ProjectItem *>(*it);
1435             clip = item->referencedClip();
1436             if (item->referencedClip()->getProducer() == NULL) {
1437                 bool replace = false;
1438                 if (brokenClips.contains(item->clipId())) {
1439                     // if this is a proxy clip, disable proxy
1440                     item->setProxyStatus(NOJOB);
1441                     clip->setProperty("proxy", "-");
1442                     replace = true;
1443                 }
1444                 if (clip->isPlaceHolder() == false && !item->isProxyRunning()) {
1445                     QDomElement xml = clip->toXML();
1446                     if (fpsChanged) {
1447                         xml.removeAttribute("out");
1448                         xml.removeAttribute("file_hash");
1449                         xml.removeAttribute("proxy_out");
1450                     }
1451                     if (!replace) replace = xml.attribute("replace") == "1";
1452                     if (replace) {
1453                         resetThumbsProducer(clip);
1454                     }
1455                     m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1456                 }
1457                 else if (clip->isPlaceHolder()) {
1458                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1459                     if (item->data(0, Qt::DecorationRole).isNull()) {
1460                         item->setData(0, Qt::DecorationRole, missingPixmap);
1461                     }
1462                     else {
1463                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1464                         QPainter p(&pixmap);
1465                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1466                         p.end();
1467                         item->setData(0, Qt::DecorationRole, pixmap);
1468                     }
1469                 }
1470             } else {              
1471                 if (displayRatioChanged) {
1472                     requestClipThumbnail(clip->getId());
1473                 }
1474                 else if (item->data(0, Qt::DecorationRole).isNull()) {
1475                     getCachedThumbnail(item);
1476                 }
1477                 if (item->data(0, DurationRole).toString().isEmpty()) {
1478                     item->changeDuration(item->referencedClip()->getProducer()->get_playtime());
1479                 }
1480                 if (clip->isPlaceHolder()) {
1481                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1482                     if (pixmap.isNull()) {
1483                         pixmap = QPixmap(width, height);
1484                         pixmap.fill(Qt::transparent);
1485                     }
1486                     QPainter p(&pixmap);
1487                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1488                     p.end();
1489                     item->setData(0, Qt::DecorationRole, pixmap);
1490                 }
1491             }
1492             item->setData(0, UsageRole, QString::number(item->numReferences()));
1493         }
1494         ++it;
1495     }
1496
1497     m_listView->setSortingEnabled(true);
1498     m_allClipsProcessed = true;
1499     if (m_render->processingItems() == 0) {
1500        monitorItemEditing(true);
1501        slotProcessNextThumbnail();
1502     }
1503 }
1504
1505 // static
1506 QString ProjectList::getExtensions()
1507 {
1508     // Build list of mime types
1509     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1510                             << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "video/mp4" << "video/quicktime" << "video/webm"
1511                             << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "audio/x-aiff" << "audio/aiff" << "application/ogg" << "application/mxf" << "application/x-shockwave-flash"
1512                             << "image/gif" << "image/jpeg" << "image/png" << "image/x-tga" << "image/x-bmp" << "image/svg+xml" << "image/tiff" << "image/x-xcf" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
1513
1514     QString allExtensions;
1515     foreach(const QString & mimeType, mimeTypes) {
1516         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1517         if (mime) {
1518             allExtensions.append(mime->patterns().join(" "));
1519             allExtensions.append(' ');
1520         }
1521     }
1522     return allExtensions.simplified();
1523 }
1524
1525 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1526 {
1527     if (!m_commandStack)
1528         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1529
1530     KUrl::List list;
1531     if (givenList.isEmpty()) {
1532         QString allExtensions = getExtensions();
1533         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1534         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1535         b->setChecked(KdenliveSettings::autoimagesequence());
1536         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1537         c->setChecked(KdenliveSettings::autoimagetransparency());
1538         QFrame *f = new QFrame;
1539         f->setFrameShape(QFrame::NoFrame);
1540         QHBoxLayout *l = new QHBoxLayout;
1541         l->addWidget(b);
1542         l->addWidget(c);
1543         l->addStretch(5);
1544         f->setLayout(l);
1545         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1546         d->setOperationMode(KFileDialog::Opening);
1547         d->setMode(KFile::Files);
1548         if (d->exec() == QDialog::Accepted) {
1549             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1550         }
1551         list = d->selectedUrls();
1552         if (b->isChecked() && list.count() == 1) {
1553             // Check for image sequence
1554             KUrl url = list.at(0);
1555             QString fileName = url.fileName().section('.', 0, -2);
1556             if (fileName.at(fileName.size() - 1).isDigit()) {
1557                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1558                 if (item.mimetype().startsWith("image")) {
1559                     // import as sequence if we found more than one image in the sequence
1560                     QStringList list;
1561                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1562                     int count = list.count();
1563                     if (count > 1) {
1564                         delete d;
1565                         QStringList groupInfo = getGroup();
1566
1567                         // get image sequence base name
1568                         while (fileName.at(fileName.size() - 1).isDigit()) {
1569                             fileName.chop(1);
1570                         }
1571
1572                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1573                                                            false, false, false,
1574                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1575                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1576                         return;
1577                     }
1578                 }
1579             }
1580         }
1581         delete d;
1582     } else {
1583         for (int i = 0; i < givenList.count(); i++)
1584             list << givenList.at(i);
1585     }
1586
1587     foreach(const KUrl & file, list) {
1588         // Check there is no folder here
1589         KMimeType::Ptr type = KMimeType::findByUrl(file);
1590         if (type->is("inode/directory")) {
1591             // user dropped a folder
1592             list.removeAll(file);
1593         }
1594     }
1595
1596     if (list.isEmpty())
1597         return;
1598
1599     if (givenList.isEmpty()) {
1600         QStringList groupInfo = getGroup();
1601         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1602     } else {
1603         m_doc->slotAddClipList(list, groupName, groupId);
1604     }
1605 }
1606
1607 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1608 {
1609     ProjectItem *item = getItemById(id);
1610     m_processingClips.removeAll(id);
1611     m_thumbnailQueue.removeAll(id);
1612     if (item) {
1613         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1614         const QString path = item->referencedClip()->fileURL().path();
1615         if (item->referencedClip()->isPlaceHolder()) replace = false;
1616         if (!path.isEmpty()) {
1617             if (m_invalidClipDialog) {
1618                 m_invalidClipDialog->addClip(id, path);
1619                 return;
1620             }
1621             else {
1622                 if (replace)
1623                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", QString()), replace, kapp->activeWindow());
1624                 else {
1625                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is missing or invalid. Remove it from project?", QString()), replace, kapp->activeWindow());
1626                 }
1627                 m_invalidClipDialog->addClip(id, path);
1628                 int result = m_invalidClipDialog->exec();
1629                 if (result == KDialog::Yes) replace = true;
1630             }
1631         }
1632         if (m_invalidClipDialog) {
1633             if (replace)
1634                 emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap <QString, QString>());
1635             delete m_invalidClipDialog;
1636             m_invalidClipDialog = NULL;
1637         }
1638         
1639     }
1640 }
1641
1642 void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
1643 {
1644     ProjectItem *item = getItemById(id);
1645     if (item) {
1646         kDebug()<<"// Proxy for clip "<<id<<" is invalid, delete";
1647         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1648         if (durationError) {
1649             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
1650             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2);
1651         }
1652         item->setProxyStatus(JOBCRASHED);
1653         QString path = item->referencedClip()->getProperty("proxy");
1654         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1655
1656         //Security check: make sure the invalid proxy file is in the proxy folder
1657         if (proxyFolder.isParentOf(KUrl(path))) {
1658             QFile::remove(path);
1659         }
1660         if (item->referencedClip()->getProducer() == NULL) {
1661             // Clip has no valid producer, request it
1662             slotProxyCurrentItem(false, item);
1663         }
1664         else {
1665             // refresh thumbs producer
1666             item->referencedClip()->reloadThumbProducer();
1667         }
1668     }
1669     m_processingClips.removeAll(id);
1670     m_thumbnailQueue.removeAll(id);
1671 }
1672
1673 void ProjectList::slotAddColorClip()
1674 {
1675     if (!m_commandStack)
1676         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1677
1678     QDialog *dia = new QDialog(this);
1679     Ui::ColorClip_UI dia_ui;
1680     dia_ui.setupUi(dia);
1681     dia->setWindowTitle(i18n("Color Clip"));
1682     dia_ui.clip_name->setText(i18n("Color Clip"));
1683
1684     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1685     t->setValue(KdenliveSettings::color_duration());
1686     dia_ui.clip_durationBox->addWidget(t);
1687     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1688
1689     if (dia->exec() == QDialog::Accepted) {
1690         QString color = dia_ui.clip_color->color().name();
1691         KdenliveSettings::setColorclipcolor(color);
1692         color = color.replace(0, 1, "0x") + "ff";
1693         QStringList groupInfo = getGroup();
1694         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1695     }
1696     delete t;
1697     delete dia;
1698 }
1699
1700
1701 void ProjectList::slotAddSlideshowClip()
1702 {
1703     if (!m_commandStack)
1704         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1705
1706     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1707
1708     if (dia->exec() == QDialog::Accepted) {
1709         QStringList groupInfo = getGroup();
1710         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1711                                            dia->loop(), dia->crop(), dia->fade(),
1712                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1713                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1714     }
1715     delete dia;
1716 }
1717
1718 void ProjectList::slotAddTitleClip()
1719 {
1720     QStringList groupInfo = getGroup();
1721     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1722 }
1723
1724 void ProjectList::slotAddTitleTemplateClip()
1725 {
1726     if (!m_commandStack)
1727         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1728
1729     QStringList groupInfo = getGroup();
1730
1731     // Get the list of existing templates
1732     QStringList filter;
1733     filter << "*.kdenlivetitle";
1734     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1735     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1736
1737     QDialog *dia = new QDialog(this);
1738     Ui::TemplateClip_UI dia_ui;
1739     dia_ui.setupUi(dia);
1740     for (int i = 0; i < templateFiles.size(); ++i)
1741         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1742
1743     if (!templateFiles.isEmpty())
1744         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1745     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1746     //warning: setting base directory doesn't work??
1747     KUrl startDir(path);
1748     dia_ui.template_list->fileDialog()->setUrl(startDir);
1749     dia_ui.text_box->setHidden(true);
1750     if (dia->exec() == QDialog::Accepted) {
1751         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1752         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1753         // Create a cloned template clip
1754         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1755     }
1756     delete dia;
1757 }
1758
1759 QStringList ProjectList::getGroup() const
1760 {
1761     QStringList result;
1762     QTreeWidgetItem *item = m_listView->currentItem();
1763     while (item && item->type() != PROJECTFOLDERTYPE)
1764         item = item->parent();
1765
1766     if (item) {
1767         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1768         result << folder->groupName() << folder->clipId();
1769     } else {
1770         result << QString() << QString();
1771     }
1772     return result;
1773 }
1774
1775 void ProjectList::setDocument(KdenliveDoc *doc)
1776 {
1777     m_listView->blockSignals(true);
1778     m_abortAllJobs = true;
1779     m_closing = true;
1780     m_proxyThreads.waitForFinished();
1781     m_proxyThreads.clearFutures();
1782     m_thumbnailQueue.clear();
1783     m_listView->clear();
1784     m_processingClips.clear();
1785     
1786     m_listView->setSortingEnabled(false);
1787     emit clipSelected(NULL);
1788     m_refreshed = false;
1789     m_allClipsProcessed = false;
1790     m_fps = doc->fps();
1791     m_timecode = doc->timecode();
1792     m_commandStack = doc->commandStack();
1793     m_doc = doc;
1794     m_abortAllJobs = false;
1795     m_closing = false;
1796
1797     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1798     QStringList openedFolders = doc->getExpandedFolders();
1799     QMapIterator<QString, QString> f(flist);
1800     while (f.hasNext()) {
1801         f.next();
1802         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1803         folder->setExpanded(openedFolders.contains(f.key()));
1804     }
1805
1806     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1807     if (list.isEmpty()) {
1808         // blank document
1809         m_refreshed = true;
1810         m_allClipsProcessed = true;
1811     }
1812     for (int i = 0; i < list.count(); i++)
1813         slotAddClip(list.at(i), false);
1814
1815     m_listView->blockSignals(false);
1816     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1817     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1818     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1819     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1820     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool, QStringList)), this, SLOT(updateAllClips(bool, bool, QStringList)));
1821 }
1822
1823 QList <DocClipBase*> ProjectList::documentClipList() const
1824 {
1825     if (m_doc == NULL)
1826         return QList <DocClipBase*> ();
1827
1828     return m_doc->clipManager()->documentClipList();
1829 }
1830
1831 QDomElement ProjectList::producersList()
1832 {
1833     QDomDocument doc;
1834     QDomElement prods = doc.createElement("producerlist");
1835     doc.appendChild(prods);
1836     QTreeWidgetItemIterator it(m_listView);
1837     while (*it) {
1838         if ((*it)->type() != PROJECTCLIPTYPE) {
1839             // subitem
1840             ++it;
1841             continue;
1842         }
1843         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1844         ++it;
1845     }
1846     return prods;
1847 }
1848
1849 void ProjectList::slotCheckForEmptyQueue()
1850 {
1851     if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) {
1852         if (!m_refreshed && m_allClipsProcessed) {
1853             m_refreshed = true;
1854             m_listView->setEnabled(true);
1855             slotClipSelected();
1856             QTimer::singleShot(500, this, SIGNAL(loadingIsOver()));
1857             emit displayMessage(QString(), -1);
1858         }
1859         updateButtons();
1860     } else if (!m_refreshed) {
1861         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1862     }
1863 }
1864
1865
1866 void ProjectList::requestClipThumbnail(const QString id)
1867 {
1868     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1869     slotProcessNextThumbnail();
1870 }
1871
1872 void ProjectList::resetThumbsProducer(DocClipBase *clip)
1873 {
1874     if (!clip) return;
1875     clip->clearThumbProducer();
1876     QString id = clip->getId();
1877     m_thumbnailQueue.removeAll(id);
1878 }
1879
1880 void ProjectList::slotProcessNextThumbnail()
1881 {
1882     if (m_render->processingItems() > 0) {
1883         return;
1884     }
1885     if (m_thumbnailQueue.isEmpty()) {
1886         slotCheckForEmptyQueue();
1887         return;
1888     }
1889     int max = m_doc->clipManager()->clipsCount();
1890     emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1891     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1892 }
1893
1894 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1895 {
1896     QTreeWidgetItem *item = getAnyItemById(clipId);
1897     if (item)
1898         slotRefreshClipThumbnail(item, update);
1899     else {
1900         slotProcessNextThumbnail();
1901     }
1902 }
1903
1904 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1905 {
1906     if (it == NULL) return;
1907     ProjectItem *item = NULL;
1908     bool isSubItem = false;
1909     int frame;
1910     if (it->type() == PROJECTFOLDERTYPE) return;
1911     if (it->type() == PROJECTSUBCLIPTYPE) {
1912         item = static_cast <ProjectItem *>(it->parent());
1913         frame = static_cast <SubProjectItem *>(it)->zone().x();
1914         isSubItem = true;
1915     } else {
1916         item = static_cast <ProjectItem *>(it);
1917         frame = item->referencedClip()->getClipThumbFrame();
1918     }
1919
1920     if (item) {
1921         DocClipBase *clip = item->referencedClip();
1922         if (!clip) {
1923             slotProcessNextThumbnail();
1924             return;
1925         }
1926         QPixmap pix;
1927         QImage img;
1928         int height = m_listView->iconSize().height();
1929         int swidth = (int)(height  * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5);
1930         int dwidth = (int)(height  * m_render->dar() + 0.5);
1931         if (clip->clipType() == AUDIO)
1932             pix = KIcon("audio-x-generic").pixmap(QSize(dwidth, height));
1933         else if (clip->clipType() == IMAGE)
1934             img = KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height);
1935         else {
1936             img = item->referencedClip()->extractImage(frame, dwidth, height);
1937         }
1938
1939         if (!pix.isNull() || !img.isNull()) {
1940             monitorItemEditing(false);
1941             if (!img.isNull()) {
1942                 pix = QPixmap::fromImage(img);
1943                 processThumbOverlays(item, pix);
1944             }
1945             it->setData(0, Qt::DecorationRole, pix);
1946             monitorItemEditing(true);
1947             
1948             QString hash = item->getClipHash();
1949             if (!hash.isEmpty() && !img.isNull()) {
1950                 if (!isSubItem)
1951                     m_doc->cacheImage(hash, img);
1952                 else
1953                     m_doc->cacheImage(hash + '#' + QString::number(frame), img);
1954             }
1955         }
1956         if (update)
1957             emit projectModified();
1958         slotProcessNextThumbnail();
1959     }
1960 }
1961
1962
1963 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace)
1964 {
1965     QString toReload;
1966     ProjectItem *item = getItemById(clipId);
1967
1968     int queue = m_render->processingItems();
1969     if (item && producer) {
1970         monitorItemEditing(false);
1971         DocClipBase *clip = item->referencedClip();
1972         if (producer->is_valid()) {
1973             if (clip->isPlaceHolder()) {
1974                 clip->setValid();
1975                 toReload = clipId;
1976             }
1977             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1978         }
1979         item->setProperties(properties, metadata);
1980         clip->setProducer(producer, replace);
1981
1982         // Proxy stuff
1983         QString size = properties.value("frame_size");
1984         if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOJOB);
1985         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOJOB);
1986         else if (useProxy() && !item->hasProxy() && !item->isProxyRunning()) {
1987             // proxy video and image clips
1988             int maxSize;
1989             CLIPTYPE t = item->clipType();
1990             if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
1991             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
1992             if ((((t == AV || t == VIDEO || t == PLAYLIST) && generateProxy()) || (t == IMAGE && generateImageProxy())) && (size.section('x', 0, 0).toInt() > maxSize || size.section('x', 1, 1).toInt() > maxSize)) {
1993                 if (clip->getProperty("proxy").isEmpty()) {
1994                     KUrl proxyPath = m_doc->projectFolder();
1995                     proxyPath.addPath("proxy/");
1996                     proxyPath.addPath(clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")));
1997                     QMap <QString, QString> newProps;
1998                     // insert required duration for proxy
1999                     if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out"));
2000                     newProps.insert("proxy", proxyPath.path());
2001                     QMap <QString, QString> oldProps = clip->properties();
2002                     oldProps.insert("proxy", QString());
2003                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
2004                     m_doc->commandStack()->push(command);
2005                 }
2006             }
2007         }
2008
2009         if (!replace && m_allClipsProcessed && item->data(0, Qt::DecorationRole).isNull()) {
2010             getCachedThumbnail(item);
2011         }
2012         if (!toReload.isEmpty())
2013             item->slotSetToolTip();
2014     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
2015     if (queue == 0) {
2016         monitorItemEditing(true);
2017         if (item && m_thumbnailQueue.isEmpty()) {
2018             if (!item->hasProxy() || m_render->activeClipId() == item->clipId())
2019                 m_listView->setCurrentItem(item);
2020             bool updatedProfile = false;
2021             if (item->parent()) {
2022                 if (item->parent()->type() == PROJECTFOLDERTYPE)
2023                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
2024             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1 && m_refreshed && m_allClipsProcessed) {
2025                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
2026                 updatedProfile = adjustProjectProfileToItem(item);
2027             }
2028             if (updatedProfile == false) {
2029                 //emit clipSelected(item->referencedClip());
2030             }
2031         } else {
2032             int max = m_doc->clipManager()->clipsCount();
2033             if (max > 0) emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max));
2034         }
2035         if (m_allClipsProcessed) emit processNextThumbnail();
2036     }
2037     if (!item) {
2038         // no item for producer, delete it
2039         delete producer;
2040         return;
2041     }
2042     if (replace) toReload = clipId;
2043     if (!toReload.isEmpty())
2044         emit clipNeedsReload(toReload);
2045 }
2046
2047 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
2048 {
2049     if (item == NULL) {
2050         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
2051             item = static_cast <ProjectItem*>(m_listView->currentItem());
2052     }
2053     if (item == NULL || item->referencedClip() == NULL) {
2054         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
2055         return false;
2056     }
2057     bool profileUpdated = false;
2058     QString size = item->referencedClip()->getProperty("frame_size");
2059     int width = size.section('x', 0, 0).toInt();
2060     int height = size.section('x', -1).toInt();
2061     double fps = item->referencedClip()->getProperty("fps").toDouble();
2062     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
2063     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
2064         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
2065             // get a list of compatible profiles
2066             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
2067             if (!suggestedProfiles.isEmpty()) {
2068                 KDialog *dialog = new KDialog(this);
2069                 dialog->setCaption(i18n("Change project profile"));
2070                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
2071
2072                 QWidget container;
2073                 QVBoxLayout *l = new QVBoxLayout;
2074                 QLabel *label = new QLabel(i18n("Your clip does not match current project's profile.\nDo you want to change the project profile?\n\nThe following profiles match the clip (size: %1, fps: %2)", size, fps));
2075                 l->addWidget(label);
2076                 QListWidget *list = new QListWidget;
2077                 list->setAlternatingRowColors(true);
2078                 QMapIterator<QString, QString> i(suggestedProfiles);
2079                 while (i.hasNext()) {
2080                     i.next();
2081                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
2082                     item->setData(Qt::UserRole, i.key());
2083                     item->setToolTip(i.key());
2084                 }
2085                 list->setCurrentRow(0);
2086                 l->addWidget(list);
2087                 container.setLayout(l);
2088                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
2089                 dialog->setMainWidget(&container);
2090                 if (dialog->exec() == QDialog::Accepted) {
2091                     //Change project profile
2092                     profileUpdated = true;
2093                     if (list->currentItem())
2094                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
2095                 }
2096                 delete list;
2097                 delete label;
2098             } else if (fps > 0) {
2099                 KMessageBox::information(kapp->activeWindow(), i18n("Your clip does not match current project's profile.\nNo existing profile found to match the clip's properties.\nClip size: %1\nFps: %2\n", size, fps));
2100             }
2101         }
2102     }
2103     return profileUpdated;
2104 }
2105
2106 QString ProjectList::getDocumentProperty(const QString &key) const
2107 {
2108     return m_doc->getDocumentProperty(key);
2109 }
2110
2111 bool ProjectList::useProxy() const
2112 {
2113     return m_doc->getDocumentProperty("enableproxy").toInt();
2114 }
2115
2116 bool ProjectList::generateProxy() const
2117 {
2118     return m_doc->getDocumentProperty("generateproxy").toInt();
2119 }
2120
2121 bool ProjectList::generateImageProxy() const
2122 {
2123     return m_doc->getDocumentProperty("generateimageproxy").toInt();
2124 }
2125
2126 void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img)
2127 {
2128     ProjectItem *item = getItemById(clipId);
2129     if (item && !img.isNull()) {
2130         QPixmap pix = QPixmap::fromImage(img);
2131         processThumbOverlays(item, pix);
2132         monitorItemEditing(false);
2133         item->setData(0, Qt::DecorationRole, pix);
2134         monitorItemEditing(true);
2135         QString hash = item->getClipHash();
2136         if (!hash.isEmpty()) m_doc->cacheImage(hash, img);
2137     }
2138 }
2139
2140 void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height)
2141 {
2142     // For clips that have a generic icon (like audio clips...)
2143     ProjectItem *item = getItemById(clipId);
2144     QPixmap pix =  KIcon(name).pixmap(QSize(width, height));
2145     if (item && !pix.isNull()) {
2146         monitorItemEditing(false);
2147         item->setData(0, Qt::DecorationRole, pix);
2148         monitorItemEditing(true);
2149     }
2150 }
2151
2152 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
2153 {
2154     QTreeWidgetItemIterator it(m_listView);
2155     QString lookId = id;
2156     if (id.contains('#'))
2157         lookId = id.section('#', 0, 0);
2158
2159     ProjectItem *result = NULL;
2160     while (*it) {
2161         if ((*it)->type() != PROJECTCLIPTYPE) {
2162             // subitem
2163             ++it;
2164             continue;
2165         }
2166         ProjectItem *item = static_cast<ProjectItem *>(*it);
2167         if (item->clipId() == lookId) {
2168             result = item;
2169             break;
2170         }
2171         ++it;
2172     }
2173     if (result == NULL || !id.contains('#')) {
2174         return result;
2175     } else {
2176         for (int i = 0; i < result->childCount(); i++) {
2177             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
2178             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
2179                 return sub;
2180         }
2181     }
2182
2183     return NULL;
2184 }
2185
2186
2187 ProjectItem *ProjectList::getItemById(const QString &id)
2188 {
2189     ProjectItem *item;
2190     QTreeWidgetItemIterator it(m_listView);
2191     while (*it) {
2192         if ((*it)->type() != PROJECTCLIPTYPE) {
2193             // subitem or folder
2194             ++it;
2195             continue;
2196         }
2197         item = static_cast<ProjectItem *>(*it);
2198         if (item->clipId() == id)
2199             return item;
2200         ++it;
2201     }
2202     return NULL;
2203 }
2204
2205 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
2206 {
2207     FolderProjectItem *item;
2208     QTreeWidgetItemIterator it(m_listView);
2209     while (*it) {
2210         if ((*it)->type() == PROJECTFOLDERTYPE) {
2211             item = static_cast<FolderProjectItem *>(*it);
2212             if (item->clipId() == id)
2213                 return item;
2214         }
2215         ++it;
2216     }
2217     return NULL;
2218 }
2219
2220 void ProjectList::slotSelectClip(const QString &ix)
2221 {
2222     ProjectItem *clip = getItemById(ix);
2223     if (clip) {
2224         m_listView->setCurrentItem(clip);
2225         m_listView->scrollToItem(clip);
2226         m_editButton->defaultAction()->setEnabled(true);
2227         m_deleteButton->defaultAction()->setEnabled(true);
2228         m_reloadAction->setEnabled(true);
2229         m_transcodeAction->setEnabled(true);
2230         m_stabilizeAction->setEnabled(true);
2231         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
2232             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
2233             m_openAction->setEnabled(true);
2234         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
2235             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
2236             m_openAction->setEnabled(true);
2237         } else {
2238             m_openAction->setEnabled(false);
2239         }
2240     }
2241 }
2242
2243 QString ProjectList::currentClipUrl() const
2244 {
2245     ProjectItem *item;
2246     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
2247     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
2248         // subitem
2249         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
2250     } else {
2251         item = static_cast <ProjectItem*>(m_listView->currentItem());
2252     }
2253     if (item == NULL)
2254         return QString();
2255     return item->clipUrl().path();
2256 }
2257
2258 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
2259 {
2260     KUrl::List result;
2261     ProjectItem *item;
2262     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2263     for (int i = 0; i < list.count(); i++) {
2264         if (list.at(i)->type() == PROJECTFOLDERTYPE)
2265             continue;
2266         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
2267             // subitem
2268             item = static_cast <ProjectItem*>(list.at(i)->parent());
2269         } else {
2270             item = static_cast <ProjectItem*>(list.at(i));
2271         }
2272         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
2273             continue;
2274         DocClipBase *clip = item->referencedClip();
2275         if (!condition.isEmpty()) {
2276             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2277                 continue;
2278             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2279                 continue;
2280         }
2281         result.append(item->clipUrl());
2282     }
2283     return result;
2284 }
2285
2286 void ProjectList::regenerateTemplate(const QString &id)
2287 {
2288     ProjectItem *clip = getItemById(id);
2289     if (clip)
2290         regenerateTemplate(clip);
2291 }
2292
2293 void ProjectList::regenerateTemplate(ProjectItem *clip)
2294 {
2295     //TODO: remove this unused method, only force_reload is necessary
2296     clip->referencedClip()->getProducer()->set("force_reload", 1);
2297 }
2298
2299 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
2300 {
2301     QDomDocument doc;
2302     QFile file(path);
2303     if (!file.open(QIODevice::ReadOnly)) {
2304         kWarning() << "ERROR, CANNOT READ: " << path;
2305         return doc;
2306     }
2307     if (!doc.setContent(&file)) {
2308         kWarning() << "ERROR, CANNOT READ: " << path;
2309         file.close();
2310         return doc;
2311     }
2312     file.close();
2313     QDomNodeList texts = doc.elementsByTagName("content");
2314     for (int i = 0; i < texts.count(); i++) {
2315         QString data = texts.item(i).firstChild().nodeValue();
2316         data.replace("%s", replaceString);
2317         texts.item(i).firstChild().setNodeValue(data);
2318     }
2319     return doc;
2320 }
2321
2322
2323 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2324 {
2325     ProjectItem *clip = getItemById(id);
2326     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2327         return;
2328     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2329     m_commandStack->push(command);
2330 }
2331
2332 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2333 {
2334     ProjectItem *clip = getItemById(id);
2335     if (clip) {
2336         DocClipBase *base = clip->referencedClip();
2337         base->addCutZone(in, out);
2338         monitorItemEditing(false);
2339         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
2340         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2341             if (!clip->isExpanded())
2342                 clip->setExpanded(true);
2343             m_listView->scrollToItem(sub);
2344             m_listView->editItem(sub, 1);
2345         }
2346         QImage img = clip->referencedClip()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
2347         sub->setData(0, Qt::DecorationRole, QPixmap::fromImage(img));
2348         QString hash = clip->getClipHash();
2349         if (!hash.isEmpty()) m_doc->cacheImage(hash + '#' + QString::number(in), img);
2350         monitorItemEditing(true);
2351     }
2352     emit projectModified();
2353 }
2354
2355 void ProjectList::removeClipCut(const QString &id, int in, int out)
2356 {
2357     ProjectItem *clip = getItemById(id);
2358     if (clip) {
2359         DocClipBase *base = clip->referencedClip();
2360         base->removeCutZone(in, out);
2361         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2362         if (sub) {
2363             monitorItemEditing(false);
2364             delete sub;
2365             monitorItemEditing(true);
2366         }
2367     }
2368     emit projectModified();
2369 }
2370
2371 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
2372 {
2373     SubProjectItem *sub = NULL;
2374     if (clip) {
2375         for (int i = 0; i < clip->childCount(); i++) {
2376             QTreeWidgetItem *it = clip->child(i);
2377             if (it->type() == PROJECTSUBCLIPTYPE) {
2378                 sub = static_cast <SubProjectItem*>(it);
2379                 if (sub->zone() == zone)
2380                     break;
2381                 else
2382                     sub = NULL;
2383             }
2384         }
2385     }
2386     return sub;
2387 }
2388
2389 void ProjectList::slotUpdateClipCut(QPoint p)
2390 {
2391     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
2392         return;
2393     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2394     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2395     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2396     m_commandStack->push(command);
2397 }
2398
2399 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2400 {
2401     ProjectItem *clip = getItemById(id);
2402     SubProjectItem *sub = getSubItem(clip, oldzone);
2403     if (sub == NULL || clip == NULL)
2404         return;
2405     DocClipBase *base = clip->referencedClip();
2406     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2407     monitorItemEditing(false);
2408     sub->setZone(zone);
2409     sub->setDescription(comment);
2410     monitorItemEditing(true);
2411     emit projectModified();
2412 }
2413
2414 void ProjectList::slotForceProcessing(const QString &id)
2415 {
2416     m_render->forceProcessing(id);
2417 }
2418
2419 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2420 {
2421     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2422     QStringList list;
2423     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2424     int count = list.count();
2425     if (count > 1) {
2426         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2427         if (!existing.isEmpty()) {
2428             // Sequence already exists, update
2429             QString id = existing.at(0)->getId();
2430             //ProjectItem *item = getItemById(id);
2431             QMap <QString, QString> oldprops;
2432             QMap <QString, QString> newprops;
2433             int ttl = existing.at(0)->getProperty("ttl").toInt();
2434             oldprops["out"] = existing.at(0)->getProperty("out");
2435             newprops["out"] = QString::number(ttl * count - 1);
2436             slotUpdateClipProperties(id, newprops);
2437             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2438             m_commandStack->push(command);
2439         } else {
2440             // Create sequence
2441             QStringList groupInfo = getGroup();
2442             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2443                                                false, false, false,
2444                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2445                                                QString(), groupInfo.at(0), groupInfo.at(1));
2446         }
2447     } else emit displayMessage(i18n("Sequence not found"), -2);
2448 }
2449
2450 QMap <QString, QString> ProjectList::getProxies()
2451 {
2452     QMap <QString, QString> list;
2453     ProjectItem *item;
2454     QTreeWidgetItemIterator it(m_listView);
2455     while (*it) {
2456         if ((*it)->type() != PROJECTCLIPTYPE) {
2457             ++it;
2458             continue;
2459         }
2460         item = static_cast<ProjectItem *>(*it);
2461         if (item && item->referencedClip() != NULL) {
2462             if (item->hasProxy()) {
2463                 QString proxy = item->referencedClip()->getProperty("proxy");
2464                 list.insert(proxy, item->clipUrl().path());
2465             }
2466         }
2467         ++it;
2468     }
2469     return list;
2470 }
2471
2472 void ProjectList::slotCreateProxy(const QString id)
2473 {
2474     ProjectItem *item = getItemById(id);
2475     if (!item || item->isProxyRunning() || item->referencedClip()->isPlaceHolder()) return;
2476     QString path = item->referencedClip()->getProperty("proxy");
2477     if (path.isEmpty()) {
2478         setProxyStatus(item, JOBCRASHED);
2479         return;
2480     }
2481     setProxyStatus(item, JOBWAITING);
2482     if (m_abortProxy.contains(path)) m_abortProxy.removeAll(path);
2483     if (m_processingProxy.contains(path)) {
2484         // Proxy is already being generated
2485         return;
2486     }
2487     if (QFileInfo(path).size() > 0) {
2488         // Proxy already created
2489         setProxyStatus(item, JOBDONE);
2490         slotGotProxy(path);
2491         return;
2492     }
2493     m_processingProxy.append(path);
2494
2495     /*PROXYINFO info;
2496     info.dest = path;
2497     info.src = item->clipUrl().path();
2498     info.type = item->clipType();
2499     info.exif = QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt();*/
2500     ProxyJob *job = new ProxyJob(PROXYJOB, item->clipType(), item->clipId(), QStringList() << path << item->clipUrl().path() << item->referencedClip()->producerProperty("_exif_orientation") << m_doc->getDocumentProperty("proxyparams").simplified() << QString::number(m_render->frameRenderWidth()) << QString::number(m_render->renderHeight()));
2501     m_jobList.append(job);
2502     int ct = 0;
2503     if (!m_proxyThreads.futures().isEmpty()) {
2504         // Remove inactive threads
2505         QList <QFuture<void> > futures = m_proxyThreads.futures();
2506         m_proxyThreads.clearFutures();
2507         for (int i = 0; i < futures.count(); i++)
2508             if (!futures.at(i).isFinished()) {
2509                 m_proxyThreads.addFuture(futures.at(i));
2510                 ct++;
2511             }
2512     }
2513     emit jobCount(ct + m_jobList.count());
2514     
2515     if (m_proxyThreads.futures().isEmpty() || m_proxyThreads.futures().count() < KdenliveSettings::proxythreads()) m_proxyThreads.addFuture(QtConcurrent::run(this, &ProjectList::slotGenerateProxy));
2516 }
2517
2518 void ProjectList::slotAbortProxy(const QString id, const QString path)
2519 {
2520     QTreeWidgetItemIterator it(m_listView);
2521     ProjectItem *item = getItemById(id);
2522     if (!item) return;
2523     if (!path.isEmpty() && m_processingProxy.contains(path)) {
2524         m_abortProxy << path;
2525     }
2526     else {
2527         // Should only be done if we were already using a proxy producer
2528         if (!item->isProxyRunning()) slotGotProxy(item);
2529     }
2530 }
2531
2532 void ProjectList::slotGenerateProxy()
2533 {
2534     while (!m_jobList.isEmpty() && !m_abortAllJobs) {
2535         emit projectModified();
2536         AbstractClipJob *job = m_jobList.takeFirst();
2537         // Get jobs count
2538         int ct = 0;
2539         QList <QFuture<void> > futures = m_proxyThreads.futures();
2540         for (int i = 0; i < futures.count(); i++)
2541             if (futures.at(i).isRunning()) {
2542                 ct++;
2543             }
2544         emit jobCount(ct + m_jobList.count());
2545
2546         if (job->jobType == PROXYJOB) {
2547             //ProxyJob *pjob = static_cast<ProxyJob *> (job);
2548             kDebug()<<"// STARTING JOB: "<<job->destination();
2549             if (m_abortProxy.contains(job->destination())) {
2550                 m_abortProxy.removeAll(job->destination());
2551                 m_processingProxy.removeAll(job->destination());
2552                 emit cancelRunningJob(job->clipId(), job->cancelProperties());
2553                 delete job;
2554                 continue;
2555             }
2556         }
2557         
2558         // Get the list of clips that will need to get progress info
2559         QTreeWidgetItemIterator it(m_listView);
2560         QList <ProjectItem *> processingItems;
2561         ProjectItem *item = getItemById(job->clipId());
2562         processingItems.append(item);
2563         
2564         /*while (*it && !m_abortAllJobs) {
2565             if ((*it)->type() == PROJECTCLIPTYPE) {
2566                 ProjectItem *item = static_cast <ProjectItem *>(*it);
2567                 if (item->referencedClip()->getProperty("proxy") == job->destination()) {
2568                     processingItems.append(item);
2569                 }
2570             }
2571             ++it;
2572         }*/
2573
2574         // Make sure proxy path is writable
2575         QFile file(job->destination());
2576         if (!file.open(QIODevice::WriteOnly)) {
2577             for (int i = 0; i < processingItems.count(); i++)
2578                 setProxyStatus(processingItems.at(i), JOBCRASHED);
2579             m_processingProxy.removeAll(job->destination());
2580             delete job;
2581             continue;
2582         }
2583         file.close();
2584         QFile::remove(job->destination());
2585     
2586         for (int i = 0; i < processingItems.count(); i++)
2587             setProxyStatus(processingItems.at(i), CREATINGJOB, 0); //, job->description);
2588         bool success;
2589         QProcess *jobProcess = job->startJob(&success);
2590             
2591         int result = -1;
2592         if (jobProcess == NULL) {
2593             // job is finished
2594             for (int i = 0; i < processingItems.count(); i++)
2595                 setProxyStatus(processingItems.at(i), success ? JOBDONE : JOBCRASHED);
2596             if (success) {
2597                 slotGotProxy(job->destination());
2598             }
2599             else {
2600                 QFile::remove(job->destination());
2601             }
2602             m_abortProxy.removeAll(job->destination());
2603             m_processingProxy.removeAll(job->destination());
2604             delete job;
2605             continue;
2606         }
2607         else while (jobProcess->state() != QProcess::NotRunning) {
2608             // building proxy file
2609             if (m_abortProxy.contains(job->destination()) || m_abortAllJobs) {
2610                 jobProcess->close();
2611                 jobProcess->waitForFinished();
2612                 QFile::remove(job->destination());
2613                 m_abortProxy.removeAll(job->destination());
2614                 m_processingProxy.removeAll(job->destination());
2615                 if (!m_closing) {
2616                     emit cancelRunningJob(job->clipId(), job->cancelProperties());
2617                     /*for (int i = 0; i < processingItems.count(); i++)
2618                         setProxyStatus(processingItems.at(i), NOJOB);*/
2619                 }
2620                 else continue;
2621                 result = -2;
2622             }
2623             else {
2624                 int progress = job->processLogInfo();
2625                 if (progress > -1) processLogInfo(processingItems, progress);
2626             }
2627             jobProcess->waitForFinished(500);
2628         }
2629         jobProcess->waitForFinished();
2630         m_processingProxy.removeAll(job->destination());
2631         if (result == -1) result = jobProcess->exitStatus();
2632         
2633         if (result != -2 && QFileInfo(job->destination()).size() == 0) {
2634             result = QProcess::CrashExit;
2635         }
2636         
2637         if (result == QProcess::NormalExit) {
2638             // proxy successfully created
2639             for (int i = 0; i < processingItems.count(); i++)
2640                 setProxyStatus(processingItems.at(i), JOBDONE);
2641             slotGotProxy(job->destination());
2642         }
2643         else if (result == QProcess::CrashExit) {
2644             // Proxy process crashed
2645             QFile::remove(job->destination());
2646             for (int i = 0; i < processingItems.count(); i++)
2647                 setProxyStatus(processingItems.at(i), JOBCRASHED);
2648         }
2649         delete job;
2650         continue;
2651     }
2652     // Thread finished, update count
2653     int ct = -1; // -1 because we don't want to count this terminating thread
2654     QList <QFuture<void> > futures = m_proxyThreads.futures();
2655     for (int i = 0; i < futures.count(); i++)
2656         if (futures.at(i).isRunning()) {
2657             ct++;
2658         }
2659     emit jobCount(ct + m_jobList.count());
2660 }
2661
2662
2663 void ProjectList::processLogInfo(QList <ProjectItem *>items, int progress)
2664 {
2665     for (int i = 0; i < items.count(); i++)
2666         setProxyStatus(items.at(i), CREATINGJOB, progress);
2667 }
2668
2669 void ProjectList::updateProxyConfig()
2670 {
2671     ProjectItem *item;
2672     QTreeWidgetItemIterator it(m_listView);
2673     QUndoCommand *command = new QUndoCommand();
2674     command->setText(i18n("Update proxy settings"));
2675     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2676     while (*it) {
2677         if ((*it)->type() != PROJECTCLIPTYPE) {
2678             ++it;
2679             continue;
2680         }
2681         item = static_cast<ProjectItem *>(*it);
2682         if (item == NULL) {
2683             ++it;
2684             continue;
2685         }
2686         CLIPTYPE t = item->clipType();
2687         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2688             if  (generateProxy() && useProxy() && !item->isProxyRunning()) {
2689                 DocClipBase *clip = item->referencedClip();
2690                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
2691                     if (clip->getProperty("proxy").isEmpty()) {
2692                         // We need to insert empty proxy in old properties so that undo will work
2693                         QMap <QString, QString> oldProps;// = clip->properties();
2694                         oldProps.insert("proxy", QString());
2695                         QMap <QString, QString> newProps;
2696                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + "." + m_doc->getDocumentProperty("proxyextension"));
2697                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2698                     }
2699                 }
2700             }
2701             else if (item->hasProxy()) {
2702                 // remove proxy
2703                 QMap <QString, QString> newProps;
2704                 newProps.insert("proxy", QString());
2705                 newProps.insert("replace", "1");
2706                 // insert required duration for proxy
2707                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2708                 new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(newProps), newProps, true, command);
2709             }
2710         }
2711         else if (t == IMAGE && item->referencedClip() != NULL) {
2712             if  (generateImageProxy() && useProxy()) {
2713                 DocClipBase *clip = item->referencedClip();
2714                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2715                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
2716                     if (clip->getProperty("proxy").isEmpty()) {
2717                         // We need to insert empty proxy in old properties so that undo will work
2718                         QMap <QString, QString> oldProps = clip->properties();
2719                         oldProps.insert("proxy", QString());
2720                         QMap <QString, QString> newProps;
2721                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
2722                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2723                     }
2724                 }
2725             }
2726             else if (item->hasProxy()) {
2727                 // remove proxy
2728                 QMap <QString, QString> newProps;
2729                 newProps.insert("proxy", QString());
2730                 newProps.insert("replace", "1");
2731                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2732             }
2733         }
2734         ++it;
2735     }
2736     if (command->childCount() > 0) m_doc->commandStack()->push(command);
2737     else delete command;
2738 }
2739
2740 void ProjectList::slotProxyCurrentItem(bool doProxy, ProjectItem *itemToProxy)
2741 {
2742     QList<QTreeWidgetItem *> list;
2743     if (itemToProxy == NULL) list = m_listView->selectedItems();
2744     else list << itemToProxy;
2745
2746     // expand list (folders, subclips) to get real clips
2747     QTreeWidgetItem *listItem;
2748     QList<ProjectItem *> clipList;
2749     for (int i = 0; i < list.count(); i++) {
2750         listItem = list.at(i);
2751         if (listItem->type() == PROJECTFOLDERTYPE) {
2752             for (int j = 0; j < listItem->childCount(); j++) {
2753                 QTreeWidgetItem *sub = listItem->child(j);
2754                 if (sub->type() == PROJECTCLIPTYPE) {
2755                     ProjectItem *item = static_cast <ProjectItem*>(sub);
2756                     if (!clipList.contains(item)) clipList.append(item);
2757                 }
2758             }
2759         }
2760         else if (listItem->type() == PROJECTSUBCLIPTYPE) {
2761             QTreeWidgetItem *sub = listItem->parent();
2762             ProjectItem *item = static_cast <ProjectItem*>(sub);
2763             if (!clipList.contains(item)) clipList.append(item);
2764         }
2765         else if (listItem->type() == PROJECTCLIPTYPE) {
2766             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2767             if (!clipList.contains(item)) clipList.append(item);
2768         }
2769     }
2770     
2771     QUndoCommand *command = new QUndoCommand();
2772     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", clipList.count()));
2773     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", clipList.count()));
2774     
2775     // Make sure the proxy folder exists
2776     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2777     KStandardDirs::makeDir(proxydir);
2778                 
2779     QMap <QString, QString> newProps;
2780     QMap <QString, QString> oldProps;
2781     if (!doProxy) newProps.insert("proxy", "-");
2782     for (int i = 0; i < clipList.count(); i++) {
2783         ProjectItem *item = clipList.at(i);
2784         CLIPTYPE t = item->clipType();
2785         if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
2786             if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy() && item->referencedClip()->getProducer() != NULL)) continue;
2787             DocClipBase *clip = item->referencedClip();
2788             if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
2789                 kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
2790                 continue;
2791             }
2792                 
2793             //oldProps = clip->properties();
2794             if (doProxy) {
2795                 newProps.clear();
2796                 QString path = proxydir + clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"));
2797                 // insert required duration for proxy
2798                 newProps.insert("proxy_out", clip->producerProperty("out"));
2799                 newProps.insert("proxy", path);
2800                 // We need to insert empty proxy so that undo will work
2801                 //oldProps.insert("proxy", QString());
2802             }
2803             else if (item->referencedClip()->getProducer() == NULL) {
2804                 // Force clip reload
2805                 kDebug()<<"// CLIP HAD NULL PROD------------";
2806                 newProps.insert("resource", item->referencedClip()->getProperty("resource"));
2807             }
2808             // We need to insert empty proxy so that undo will work
2809             oldProps = clip->currentProperties(newProps);
2810             if (doProxy) oldProps.insert("proxy", "-");
2811             new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
2812         }
2813     }
2814     if (command->childCount() > 0) {
2815         m_doc->commandStack()->push(command);
2816     }
2817     else delete command;
2818 }
2819
2820
2821 void ProjectList::slotDeleteProxy(const QString proxyPath)
2822 {
2823     if (proxyPath.isEmpty()) return;
2824     QUndoCommand *proxyCommand = new QUndoCommand();
2825     proxyCommand->setText(i18n("Remove Proxy"));
2826     QTreeWidgetItemIterator it(m_listView);
2827     ProjectItem *item;
2828     while (*it) {
2829         if ((*it)->type() == PROJECTCLIPTYPE) {
2830             item = static_cast <ProjectItem *>(*it);
2831             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2832                 QMap <QString, QString> props;
2833                 props.insert("proxy", QString());
2834                 new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(props), props, true, proxyCommand);
2835             
2836             }
2837         }
2838         ++it;
2839     }
2840     if (proxyCommand->childCount() == 0)
2841         delete proxyCommand;
2842     else
2843         m_commandStack->push(proxyCommand);
2844     QFile::remove(proxyPath);
2845 }
2846
2847 void ProjectList::setProxyStatus(ProjectItem *item, CLIPJOBSTATUS status, int progress)
2848 {
2849     if (item == NULL || m_abortAllJobs) return;
2850     monitorItemEditing(false);
2851     item->setProxyStatus(status, progress);
2852     if (status == JOBCRASHED) {
2853         DocClipBase *clip = item->referencedClip();
2854         if (!clip) {
2855             kDebug()<<"// PROXY CRASHED";
2856         }
2857         else if (clip->getProducer() == NULL && !clip->isPlaceHolder()) {
2858             // disable proxy and fetch real clip
2859             clip->setProperty("proxy", "-");
2860             QDomElement xml = clip->toXML();
2861             m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), true);
2862         }
2863         else {
2864             // Disable proxy for this clip
2865             clip->setProperty("proxy", "-");
2866         }
2867     }
2868     monitorItemEditing(true);
2869 }
2870
2871 void ProjectList::monitorItemEditing(bool enable)
2872 {
2873     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2874     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2875 }
2876
2877 QStringList ProjectList::expandedFolders() const
2878 {
2879     QStringList result;
2880     FolderProjectItem *item;
2881     QTreeWidgetItemIterator it(m_listView);
2882     while (*it) {
2883         if ((*it)->type() != PROJECTFOLDERTYPE) {
2884             ++it;
2885             continue;
2886         }
2887         if ((*it)->isExpanded()) {
2888             item = static_cast<FolderProjectItem *>(*it);
2889             result.append(item->clipId());
2890         }
2891         ++it;
2892     }
2893     return result;
2894 }
2895
2896 void ProjectList::processThumbOverlays(ProjectItem *item, QPixmap &pix)
2897 {
2898     if (item->hasProxy()) {
2899         QPainter p(&pix);
2900         QColor c = QPalette().base().color();
2901         c.setAlpha(160);
2902         QBrush br(c);
2903         p.setBrush(br);
2904         p.setPen(Qt::NoPen);
2905         QRect r(1, 1, 10, 10);
2906         p.drawRect(r);
2907         p.setPen(QPalette().text().color());
2908         p.drawText(r, Qt::AlignCenter, i18nc("The first letter of Proxy, used as abbreviation", "P"));
2909     }
2910 }
2911
2912 void ProjectList::slotCancelJobs()
2913 {
2914     m_abortAllJobs = true;
2915     m_proxyThreads.waitForFinished();
2916     m_proxyThreads.clearFutures();
2917     QUndoCommand *command = new QUndoCommand();
2918     command->setText(i18np("Cancel job", "Cancel jobs", m_jobList.count()));
2919     for (int i = 0; i < m_jobList.count(); i++) {
2920         ProjectItem *item = getItemById(m_jobList.at(i)->clipId());
2921         if (!item || !item->referencedClip()) continue;
2922         QMap <QString, QString> newProps = m_jobList.at(i)->cancelProperties();
2923         if (newProps.isEmpty()) continue;
2924         QMap <QString, QString> oldProps = item->referencedClip()->currentProperties(newProps);
2925         new EditClipCommand(this, m_jobList.at(i)->clipId(), oldProps, newProps, true, command);
2926     }
2927     if (command->childCount() > 0) {
2928         m_doc->commandStack()->push(command);
2929     }
2930     else delete command;
2931     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
2932     m_processingProxy.clear();
2933     m_jobList.clear();
2934     m_abortAllJobs = false;
2935     m_infoLabel->slotSetJobCount(0);    
2936 }
2937
2938 void ProjectList::slotCancelRunningJob(const QString id, stringMap newProps)
2939 {
2940     if (newProps.isEmpty()) return;
2941     ProjectItem *item = getItemById(id);
2942     if (!item || !item->referencedClip()) return;
2943     QMap <QString, QString> oldProps = item->referencedClip()->currentProperties(newProps);
2944     if (newProps == oldProps) return;
2945     QMapIterator<QString, QString> i(oldProps);
2946     EditClipCommand *command = new EditClipCommand(this, id, oldProps, newProps, true);
2947     m_commandStack->push(command);    
2948 }
2949
2950 #include "projectlist.moc"