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