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