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