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