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