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