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