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