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