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