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