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