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