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