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