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