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