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