]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
da8b443bbfe0346f8b42f1cdf3c42117921721ac
[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(useProxy());
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(useProxy());
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     }
966     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
967     if (getProperties) {
968         m_listView->processLayout();
969         m_refreshed = false;
970         // Proxy clips
971         CLIPTYPE t = clip->clipType();
972         if ((t == VIDEO || t == AV || t == UNKNOWN) && useProxy()) {
973             if (clip->getProperty("proxy").isEmpty()) {
974                 
975                 //connect(clip, SIGNAL(proxyReady(const QString&, bool)), this, SLOT(slotGotProxy(const QString&, bool)));
976                 //setProxyStatus(item, 1);
977                 //clip->generateProxy(m_doc->projectFolder(), proxyParams());
978             }
979             else {
980                 // Proxy clip already created
981                 setProxyStatus(item, 2);
982                 QDomElement e = clip->toXML().cloneNode().toElement();
983                 e.removeAttribute("file_hash");
984                 m_infoQueue.insert(clip->getId(), e);
985             }
986         }
987         //else {
988             // We don't use proxies
989             // remove file_hash so that we load all properties for the clip
990             QDomElement e = clip->toXML().cloneNode().toElement();
991             e.removeAttribute("file_hash");
992             m_infoQueue.insert(clip->getId(), e);
993         //}
994         //m_render->getFileProperties(clip->toXML(), clip->getId(), true);
995     }
996     else if (!clip->getProperty("proxy").isEmpty()) {
997         connect(clip, SIGNAL(proxyReady(const QString&, bool)), this, SLOT(slotGotProxy(const QString&, bool)));
998         setProxyStatus(item, 1);
999         clip->generateProxy(m_doc->projectFolder(), proxyParams());
1000     }
1001     clip->askForAudioThumbs();
1002     
1003     KUrl url = clip->fileURL();
1004     if (getProperties == false && !clip->getClipHash().isEmpty()) {
1005         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
1006         if (QFile::exists(cachedPixmap)) {
1007             QPixmap pix(cachedPixmap);
1008             if (pix.isNull())
1009                 KIO::NetAccess::del(KUrl(cachedPixmap), this);
1010             item->setData(0, Qt::DecorationRole, pix);
1011         }
1012     }
1013 #ifdef NEPOMUK
1014     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
1015         // if file has Nepomuk comment, use it
1016         Nepomuk::Resource f(url.path());
1017         QString annotation = f.description();
1018         if (!annotation.isEmpty()) item->setText(1, annotation);
1019         item->setText(2, QString::number(f.rating()));
1020     }
1021 #endif
1022     // Add cut zones
1023     QList <CutZoneInfo> cuts = clip->cutZones();
1024     if (!cuts.isEmpty()) {
1025         for (int i = 0; i < cuts.count(); i++) {
1026             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1027             if (!clip->getClipHash().isEmpty()) {
1028                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1029                 if (QFile::exists(cachedPixmap)) {
1030                     QPixmap pix(cachedPixmap);
1031                     if (pix.isNull())
1032                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1033                     sub->setData(0, Qt::DecorationRole, pix);
1034                 }
1035             }
1036         }
1037     }
1038     monitorItemEditing(true);
1039     if (m_listView->isEnabled()) {
1040         updateButtons();
1041     }
1042     
1043     if (getProperties && m_processingClips.isEmpty())
1044         m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1045 }
1046
1047 void ProjectList::slotGotProxy(const QString &id, bool success)
1048 {
1049     ProjectItem *item = getItemById(id);
1050     if (item) {
1051         if (success) {
1052             // Proxy clip successfully created
1053             setProxyStatus(item, 2);
1054             QDomElement e = item->referencedClip()->toXML().cloneNode().toElement();  
1055             e.removeAttribute("file_hash");
1056             e.setAttribute("replace", 1);
1057             m_infoQueue.insert(id, e);
1058             if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1059         }
1060         else setProxyStatus(item, 0);
1061         update();
1062     }
1063 }
1064
1065 void ProjectList::slotResetProjectList()
1066 {
1067     m_listView->clear();
1068     emit clipSelected(NULL);
1069     m_thumbnailQueue.clear();
1070     m_infoQueue.clear();
1071     m_refreshed = false;
1072 }
1073
1074 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
1075 {
1076     m_refreshed = false;
1077     m_infoQueue.insert(id, xml);
1078     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1079 }
1080
1081 void ProjectList::slotProcessNextClipInQueue()
1082 {
1083     if (m_infoQueue.isEmpty()) {
1084         emit processNextThumbnail();
1085         return;
1086     }
1087
1088     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
1089     if (j != m_infoQueue.constEnd()) {
1090         QDomElement dom = j.value();
1091         const QString id = j.key();
1092         m_infoQueue.remove(id);
1093         m_processingClips.append(id);
1094         bool replace;
1095         if (dom.hasAttribute("replace")) {
1096             // Proxy action was enabled / disabled and we want to replace current producer
1097             dom.removeAttribute("replace");
1098             replace = true;
1099         }
1100         else replace = false;
1101         bool selectClip = !replace;
1102         if (m_infoQueue.count() > 1) selectClip = false;
1103         emit getFileProperties(dom, id, m_listView->iconSize().height(), replace, selectClip);
1104     }
1105 }
1106
1107 void ProjectList::slotUpdateClip(const QString &id)
1108 {
1109     ProjectItem *item = getItemById(id);
1110     monitorItemEditing(false);
1111     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1112     monitorItemEditing(true);
1113 }
1114
1115 void ProjectList::updateAllClips()
1116 {
1117     m_listView->setSortingEnabled(false);
1118     kDebug() << "// UPDATE ALL CLPY";
1119
1120     QTreeWidgetItemIterator it(m_listView);
1121     DocClipBase *clip;
1122     ProjectItem *item;
1123     monitorItemEditing(false);
1124     while (*it) {
1125         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1126             // subitem
1127             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1128             if (sub->data(0, Qt::DecorationRole).isNull()) {
1129                 item = static_cast <ProjectItem *>((*it)->parent());
1130                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1131             }
1132             ++it;
1133             continue;
1134         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1135             // folder
1136             ++it;
1137             continue;
1138         } else {
1139             item = static_cast <ProjectItem *>(*it);
1140             clip = item->referencedClip();
1141             if (item->referencedClip()->producer() == NULL) {
1142                 if (clip->isPlaceHolder() == false)
1143                     requestClipInfo(clip->toXML(), clip->getId());
1144                 else if (!clip->isPlaceHolder())
1145                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1146             } else {
1147                 if (item->data(0, Qt::DecorationRole).isNull())
1148                     requestClipThumbnail(clip->getId());
1149                 if (item->data(0, DurationRole).toString().isEmpty())
1150                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
1151             }
1152             item->setData(0, UsageRole, QString::number(item->numReferences()));
1153         }
1154         //qApp->processEvents();
1155         ++it;
1156     }
1157     /*if (!m_queueTimer.isActive())
1158         m_queueTimer.start();*/
1159     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1160     if (m_listView->isEnabled())
1161         monitorItemEditing(true);
1162     m_listView->setSortingEnabled(true);
1163     if (m_infoQueue.isEmpty())
1164         slotProcessNextThumbnail();
1165 }
1166
1167 // static
1168 QString ProjectList::getExtensions()
1169 {
1170     // Build list of mime types
1171     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1172                             << "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"
1173                             << "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"
1174                             << "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";
1175
1176     QString allExtensions;
1177     foreach(const QString & mimeType, mimeTypes) {
1178         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1179         if (mime) {
1180             allExtensions.append(mime->patterns().join(" "));
1181             allExtensions.append(' ');
1182         }
1183     }
1184     return allExtensions.simplified();
1185 }
1186
1187 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1188 {
1189     if (!m_commandStack)
1190         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1191
1192     KUrl::List list;
1193     if (givenList.isEmpty()) {
1194         QString allExtensions = getExtensions();
1195         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1196         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1197         b->setChecked(KdenliveSettings::autoimagesequence());
1198         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), b);
1199         d->setOperationMode(KFileDialog::Opening);
1200         d->setMode(KFile::Files);
1201         d->exec();
1202         list = d->selectedUrls();
1203         if (b->isChecked() && list.count() == 1) {
1204             // Check for image sequence
1205             KUrl url = list.at(0);
1206             QString fileName = url.fileName().section('.', 0, -2);
1207             if (fileName.at(fileName.size() - 1).isDigit()) {
1208                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1209                 if (item.mimetype().startsWith("image")) {
1210                     // import as sequence if we found more than one image in the sequence
1211                     QStringList list;
1212                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1213                     int count = list.count();
1214                     if (count > 1) {
1215                         delete d;
1216                         QStringList groupInfo = getGroup();
1217
1218                         // get image sequence base name
1219                         while (fileName.at(fileName.size() - 1).isDigit()) {
1220                             fileName.chop(1);
1221                         }
1222
1223                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1224                                                            false, false, false,
1225                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1226                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1227                         return;
1228                     }
1229                 }
1230             }
1231         }
1232         delete d;
1233     } else {
1234         for (int i = 0; i < givenList.count(); i++)
1235             list << givenList.at(i);
1236     }
1237
1238     foreach(const KUrl & file, list) {
1239         // Check there is no folder here
1240         KMimeType::Ptr type = KMimeType::findByUrl(file);
1241         if (type->is("inode/directory")) {
1242             // user dropped a folder
1243             list.removeAll(file);
1244         }
1245     }
1246
1247     if (list.isEmpty())
1248         return;
1249
1250     if (givenList.isEmpty()) {
1251         QStringList groupInfo = getGroup();
1252         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1253     } else {
1254         m_doc->slotAddClipList(list, groupName, groupId);
1255     }
1256 }
1257
1258 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1259 {
1260     ProjectItem *item = getItemById(id);
1261     m_processingClips.removeAll(id);
1262     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1263     if (item) {
1264         const QString path = item->referencedClip()->fileURL().path();
1265         if (item->referencedClip()->isPlaceHolder()) replace = false;
1266         if (!path.isEmpty()) {
1267             if (replace)
1268                 KMessageBox::sorry(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
1269             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)
1270                 replace = true;
1271         }
1272         if (replace)
1273             emit deleteProjectClips(QStringList() << id, QMap <QString, QString>());
1274     }
1275 }
1276
1277 void ProjectList::slotAddColorClip()
1278 {
1279     if (!m_commandStack)
1280         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1281
1282     QDialog *dia = new QDialog(this);
1283     Ui::ColorClip_UI dia_ui;
1284     dia_ui.setupUi(dia);
1285     dia->setWindowTitle(i18n("Color Clip"));
1286     dia_ui.clip_name->setText(i18n("Color Clip"));
1287
1288     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1289     t->setValue(KdenliveSettings::color_duration());
1290     t->setTimeCodeFormat(false);
1291     dia_ui.clip_durationBox->addWidget(t);
1292     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1293
1294     if (dia->exec() == QDialog::Accepted) {
1295         QString color = dia_ui.clip_color->color().name();
1296         KdenliveSettings::setColorclipcolor(color);
1297         color = color.replace(0, 1, "0x") + "ff";
1298         QStringList groupInfo = getGroup();
1299         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1300     }
1301     delete t;
1302     delete dia;
1303 }
1304
1305
1306 void ProjectList::slotAddSlideshowClip()
1307 {
1308     if (!m_commandStack)
1309         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1310
1311     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1312
1313     if (dia->exec() == QDialog::Accepted) {
1314         QStringList groupInfo = getGroup();
1315         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1316                                            dia->loop(), dia->crop(), dia->fade(),
1317                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1318                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1319     }
1320     delete dia;
1321 }
1322
1323 void ProjectList::slotAddTitleClip()
1324 {
1325     QStringList groupInfo = getGroup();
1326     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1327 }
1328
1329 void ProjectList::slotAddTitleTemplateClip()
1330 {
1331     if (!m_commandStack)
1332         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1333
1334     QStringList groupInfo = getGroup();
1335
1336     // Get the list of existing templates
1337     QStringList filter;
1338     filter << "*.kdenlivetitle";
1339     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1340     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1341
1342     QDialog *dia = new QDialog(this);
1343     Ui::TemplateClip_UI dia_ui;
1344     dia_ui.setupUi(dia);
1345     for (int i = 0; i < templateFiles.size(); ++i)
1346         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1347
1348     if (!templateFiles.isEmpty())
1349         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1350     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1351     //warning: setting base directory doesn't work??
1352     KUrl startDir(path);
1353     dia_ui.template_list->fileDialog()->setUrl(startDir);
1354     dia_ui.text_box->setHidden(true);
1355     if (dia->exec() == QDialog::Accepted) {
1356         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1357         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1358         // Create a cloned template clip
1359         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1360     }
1361     delete dia;
1362 }
1363
1364 QStringList ProjectList::getGroup() const
1365 {
1366     QStringList result;
1367     QTreeWidgetItem *item = m_listView->currentItem();
1368     while (item && item->type() != PROJECTFOLDERTYPE)
1369         item = item->parent();
1370
1371     if (item) {
1372         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1373         result << folder->groupName() << folder->clipId();
1374     } else {
1375         result << QString() << QString();
1376     }
1377     return result;
1378 }
1379
1380 void ProjectList::setDocument(KdenliveDoc *doc)
1381 {
1382     m_listView->blockSignals(true);
1383     m_listView->clear();
1384     m_processingClips.clear();
1385     m_listView->setSortingEnabled(false);
1386     emit clipSelected(NULL);
1387     m_thumbnailQueue.clear();
1388     m_infoQueue.clear();
1389     m_refreshed = false;
1390     m_fps = doc->fps();
1391     m_timecode = doc->timecode();
1392     m_commandStack = doc->commandStack();
1393     m_doc = doc;
1394
1395     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1396     QMapIterator<QString, QString> f(flist);
1397     while (f.hasNext()) {
1398         f.next();
1399         (void) new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1400     }
1401
1402     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1403     for (int i = 0; i < list.count(); i++)
1404         slotAddClip(list.at(i), false);
1405
1406     m_listView->blockSignals(false);
1407     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1408     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1409     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1410     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1411     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
1412 }
1413
1414 QList <DocClipBase*> ProjectList::documentClipList() const
1415 {
1416     if (m_doc == NULL)
1417         return QList <DocClipBase*> ();
1418
1419     return m_doc->clipManager()->documentClipList();
1420 }
1421
1422 QDomElement ProjectList::producersList()
1423 {
1424     QDomDocument doc;
1425     QDomElement prods = doc.createElement("producerlist");
1426     doc.appendChild(prods);
1427     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1428     QTreeWidgetItemIterator it(m_listView);
1429     while (*it) {
1430         if ((*it)->type() != PROJECTCLIPTYPE) {
1431             // subitem
1432             ++it;
1433             continue;
1434         }
1435         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1436         ++it;
1437     }
1438     return prods;
1439 }
1440
1441 void ProjectList::slotCheckForEmptyQueue()
1442 {
1443     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1444         m_refreshed = true;
1445         emit loadingIsOver();
1446         emit displayMessage(QString(), -1);
1447         m_listView->blockSignals(false);
1448         m_listView->setEnabled(true);
1449         updateButtons();
1450     } else if (!m_refreshed) {
1451         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1452     }
1453 }
1454
1455 void ProjectList::reloadClipThumbnails()
1456 {
1457     m_thumbnailQueue.clear();
1458     QTreeWidgetItemIterator it(m_listView);
1459     while (*it) {
1460         if ((*it)->type() != PROJECTCLIPTYPE) {
1461             // subitem
1462             ++it;
1463             continue;
1464         }
1465         m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
1466         ++it;
1467     }
1468     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1469 }
1470
1471 void ProjectList::requestClipThumbnail(const QString id)
1472 {
1473     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1474 }
1475
1476 void ProjectList::slotProcessNextThumbnail()
1477 {
1478     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1479         slotCheckForEmptyQueue();
1480         return;
1481     }
1482     if (!m_infoQueue.isEmpty()) {
1483         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1484         return;
1485     }
1486     if (m_thumbnailQueue.count() > 1) {
1487         int max = m_doc->clipManager()->clipsCount();
1488         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1489     }
1490     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1491 }
1492
1493 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1494 {
1495     QTreeWidgetItem *item = getAnyItemById(clipId);
1496     if (item)
1497         slotRefreshClipThumbnail(item, update);
1498     else
1499         slotProcessNextThumbnail();
1500 }
1501
1502 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1503 {
1504     if (it == NULL) return;
1505     ProjectItem *item = NULL;
1506     bool isSubItem = false;
1507     int frame;
1508     if (it->type() == PROJECTFOLDERTYPE) return;
1509     if (it->type() == PROJECTSUBCLIPTYPE) {
1510         item = static_cast <ProjectItem *>(it->parent());
1511         frame = static_cast <SubProjectItem *>(it)->zone().x();
1512         isSubItem = true;
1513     } else {
1514         item = static_cast <ProjectItem *>(it);
1515         frame = item->referencedClip()->getClipThumbFrame();
1516     }
1517
1518     if (item) {
1519         DocClipBase *clip = item->referencedClip();
1520         if (!clip) {
1521             slotProcessNextThumbnail();
1522             return;
1523         }
1524         QPixmap pix;
1525         int height = m_listView->iconSize().height();
1526         int width = (int)(height  * m_render->dar());
1527         if (clip->clipType() == AUDIO)
1528             pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1529         else if (clip->clipType() == IMAGE)
1530             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1531         else
1532             pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height);
1533
1534         if (!pix.isNull()) {
1535             monitorItemEditing(false);
1536             it->setData(0, Qt::DecorationRole, pix);
1537             monitorItemEditing(true);
1538                 
1539             if (!isSubItem)
1540                 m_doc->cachePixmap(item->getClipHash(), pix);
1541             else
1542                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1543         }
1544         if (update)
1545             emit projectModified();
1546
1547         slotProcessNextThumbnail();
1548     }
1549 }
1550
1551 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace, bool selectClip)
1552 {
1553     QString toReload;
1554     ProjectItem *item = getItemById(clipId);
1555     m_processingClips.removeAll(clipId);
1556     if (m_infoQueue.isEmpty() && m_processingClips.isEmpty()) m_listView->setEnabled(true);
1557     if (item && producer) {
1558         //m_listView->blockSignals(true);
1559         monitorItemEditing(false);
1560         item->setProperties(properties, metadata);
1561         if (item->referencedClip()->isPlaceHolder() && producer->is_valid()) {
1562             item->referencedClip()->setValid();
1563             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1564             toReload = clipId;
1565         }
1566         if (!useProxy() && item->referencedClip()->getProperty("proxy").isEmpty()) setProxyStatus(item, 0);
1567         QString size = properties.value("frame_size");
1568         DocClipBase *clip = item->referencedClip();
1569         if (useProxy() && (item->clipType() == AV || item->clipType() == VIDEO) && generateProxy() && size.section('x', 0, 0).toInt() > proxyMinSize()) {
1570             if (clip->getProperty("proxy").isEmpty()) {
1571                 connect(clip, SIGNAL(proxyReady(const QString&, bool)), this, SLOT(slotGotProxy(const QString&, bool)));
1572                 setProxyStatus(item, 1);
1573                 clip->generateProxy(m_doc->projectFolder(), proxyParams());
1574             }
1575         }
1576         clip->setProducer(producer, replace);
1577         clip->askForAudioThumbs();
1578         if (!replace && item->data(0, Qt::DecorationRole).isNull())
1579             requestClipThumbnail(clipId);
1580         if (!toReload.isEmpty())
1581             item->slotSetToolTip();
1582
1583         if (m_listView->isEnabled() && replace) {
1584             // update clip in clip monitor
1585             emit clipSelected(NULL);
1586             emit clipSelected(clip);
1587             //TODO: Make sure the line below has no side effect
1588             toReload = clipId;
1589         }
1590         /*else {
1591             // Check if duration changed.
1592             emit receivedClipDuration(clipId);
1593             delete producer;
1594         }*/
1595         if (m_listView->isEnabled())
1596             monitorItemEditing(true);
1597         /*if (item->icon(0).isNull()) {
1598             requestClipThumbnail(clipId);
1599         }*/
1600     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1601     if (selectClip && m_infoQueue.isEmpty()) {
1602     if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1603         m_listView->setCurrentItem(item);
1604         bool updatedProfile = false;
1605         if (item->parent()) {
1606             if (item->parent()->type() == PROJECTFOLDERTYPE)
1607                 static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1608         } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1609             // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1610             updatedProfile = adjustProjectProfileToItem(item);
1611         }
1612         if (updatedProfile == false) emit clipSelected(item->referencedClip());
1613     } else {
1614         int max = m_doc->clipManager()->clipsCount();
1615         emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1616     }
1617     }
1618     if (!toReload.isEmpty())
1619         emit clipNeedsReload(toReload, true);
1620
1621     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1622 }
1623
1624 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1625 {
1626     if (item == NULL) {
1627         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1628             item = static_cast <ProjectItem*>(m_listView->currentItem());
1629     }
1630     if (item == NULL || item->referencedClip() == NULL) {
1631         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1632         return false;
1633     }
1634     bool profileUpdated = false;
1635     QString size = item->referencedClip()->getProperty("frame_size");
1636     int width = size.section('x', 0, 0).toInt();
1637     int height = size.section('x', -1).toInt();
1638     double fps = item->referencedClip()->getProperty("fps").toDouble();
1639     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1640     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1641         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1642             // get a list of compatible profiles
1643             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1644             if (!suggestedProfiles.isEmpty()) {
1645                 KDialog *dialog = new KDialog(this);
1646                 dialog->setCaption(i18n("Change project profile"));
1647                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1648
1649                 QWidget container;
1650                 QVBoxLayout *l = new QVBoxLayout;
1651                 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));
1652                 l->addWidget(label);
1653                 QListWidget *list = new QListWidget;
1654                 list->setAlternatingRowColors(true);
1655                 QMapIterator<QString, QString> i(suggestedProfiles);
1656                 while (i.hasNext()) {
1657                     i.next();
1658                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1659                     item->setData(Qt::UserRole, i.key());
1660                     item->setToolTip(i.key());
1661                 }
1662                 list->setCurrentRow(0);
1663                 l->addWidget(list);
1664                 container.setLayout(l);
1665                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1666                 dialog->setMainWidget(&container);
1667                 if (dialog->exec() == QDialog::Accepted) {
1668                     //Change project profile
1669                     profileUpdated = true;
1670                     if (list->currentItem())
1671                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1672                 }
1673                 delete list;
1674                 delete label;
1675             } else if (fps > 0) {
1676                 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));
1677             }
1678         }
1679     }
1680     return profileUpdated;
1681 }
1682
1683 bool ProjectList::useProxy() const
1684 {
1685     return m_doc->getDocumentProperty("enableproxy").toInt();
1686 }
1687
1688 bool ProjectList::generateProxy() const
1689 {
1690     return m_doc->getDocumentProperty("generateproxy").toInt();
1691 }
1692
1693 int ProjectList::proxyMinSize() const
1694 {
1695     return m_doc->getDocumentProperty("proxyminsize").toInt();
1696 }
1697
1698 QString ProjectList::proxyParams() const
1699 {
1700     return m_doc->getDocumentProperty("proxyparams").simplified();
1701 }
1702
1703 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1704 {
1705     ProjectItem *item = getItemById(clipId);
1706     if (item && !pix.isNull()) {
1707         monitorItemEditing(false);
1708         item->setData(0, Qt::DecorationRole, pix);
1709         monitorItemEditing(true);
1710         m_doc->cachePixmap(item->getClipHash(), pix);
1711         if (m_listView->isEnabled())
1712             m_listView->blockSignals(false);
1713     }
1714 }
1715
1716 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1717 {
1718     QTreeWidgetItemIterator it(m_listView);
1719     QString lookId = id;
1720     if (id.contains('#'))
1721         lookId = id.section('#', 0, 0);
1722
1723     ProjectItem *result = NULL;
1724     while (*it) {
1725         if ((*it)->type() != PROJECTCLIPTYPE) {
1726             // subitem
1727             ++it;
1728             continue;
1729         }
1730         ProjectItem *item = static_cast<ProjectItem *>(*it);
1731         if (item->clipId() == lookId) {
1732             result = item;
1733             break;
1734         }
1735         ++it;
1736     }
1737     if (result == NULL || !id.contains('#')) {
1738         return result;
1739     } else {
1740         for (int i = 0; i < result->childCount(); i++) {
1741             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1742             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1743                 return sub;
1744         }
1745     }
1746
1747     return NULL;
1748 }
1749
1750
1751 ProjectItem *ProjectList::getItemById(const QString &id)
1752 {
1753     ProjectItem *item;
1754     QTreeWidgetItemIterator it(m_listView);
1755     while (*it) {
1756         if ((*it)->type() != PROJECTCLIPTYPE) {
1757             // subitem or folder
1758             ++it;
1759             continue;
1760         }
1761         item = static_cast<ProjectItem *>(*it);
1762         if (item->clipId() == id)
1763             return item;
1764         ++it;
1765     }
1766     return NULL;
1767 }
1768
1769 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1770 {
1771     FolderProjectItem *item;
1772     QTreeWidgetItemIterator it(m_listView);
1773     while (*it) {
1774         if ((*it)->type() == PROJECTFOLDERTYPE) {
1775             item = static_cast<FolderProjectItem *>(*it);
1776             if (item->clipId() == id)
1777                 return item;
1778         }
1779         ++it;
1780     }
1781     return NULL;
1782 }
1783
1784 void ProjectList::slotSelectClip(const QString &ix)
1785 {
1786     ProjectItem *clip = getItemById(ix);
1787     if (clip) {
1788         m_listView->setCurrentItem(clip);
1789         m_listView->scrollToItem(clip);
1790         m_editButton->defaultAction()->setEnabled(true);
1791         m_deleteButton->defaultAction()->setEnabled(true);
1792         m_reloadAction->setEnabled(true);
1793         m_transcodeAction->setEnabled(true);
1794         m_proxyAction->setEnabled(useProxy());
1795         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1796             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1797             m_openAction->setEnabled(true);
1798         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1799             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1800             m_openAction->setEnabled(true);
1801         } else {
1802             m_openAction->setEnabled(false);
1803         }
1804     }
1805 }
1806
1807 QString ProjectList::currentClipUrl() const
1808 {
1809     ProjectItem *item;
1810     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1811     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1812         // subitem
1813         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1814     } else {
1815         item = static_cast <ProjectItem*>(m_listView->currentItem());
1816     }
1817     if (item == NULL)
1818         return QString();
1819     return item->clipUrl().path();
1820 }
1821
1822 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1823 {
1824     KUrl::List result;
1825     ProjectItem *item;
1826     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1827     for (int i = 0; i < list.count(); i++) {
1828         if (list.at(i)->type() == PROJECTFOLDERTYPE)
1829             continue;
1830         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1831             // subitem
1832             item = static_cast <ProjectItem*>(list.at(i)->parent());
1833         } else {
1834             item = static_cast <ProjectItem*>(list.at(i));
1835         }
1836         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
1837             continue;
1838         DocClipBase *clip = item->referencedClip();
1839         if (!condition.isEmpty()) {
1840             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
1841                 continue;
1842             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
1843                 continue;
1844         }
1845         result.append(item->clipUrl());
1846     }
1847     return result;
1848 }
1849
1850 void ProjectList::regenerateTemplate(const QString &id)
1851 {
1852     ProjectItem *clip = getItemById(id);
1853     if (clip)
1854         regenerateTemplate(clip);
1855 }
1856
1857 void ProjectList::regenerateTemplate(ProjectItem *clip)
1858 {
1859     //TODO: remove this unused method, only force_reload is necessary
1860     clip->referencedClip()->producer()->set("force_reload", 1);
1861 }
1862
1863 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1864 {
1865     QDomDocument doc;
1866     QFile file(path);
1867     if (!file.open(QIODevice::ReadOnly)) {
1868         kWarning() << "ERROR, CANNOT READ: " << path;
1869         return doc;
1870     }
1871     if (!doc.setContent(&file)) {
1872         kWarning() << "ERROR, CANNOT READ: " << path;
1873         file.close();
1874         return doc;
1875     }
1876     file.close();
1877     QDomNodeList texts = doc.elementsByTagName("content");
1878     for (int i = 0; i < texts.count(); i++) {
1879         QString data = texts.item(i).firstChild().nodeValue();
1880         data.replace("%s", replaceString);
1881         texts.item(i).firstChild().setNodeValue(data);
1882     }
1883     return doc;
1884 }
1885
1886
1887 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
1888 {
1889     ProjectItem *clip = getItemById(id);
1890     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
1891         return;
1892     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
1893     m_commandStack->push(command);
1894 }
1895
1896 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
1897 {
1898     ProjectItem *clip = getItemById(id);
1899     if (clip) {
1900         DocClipBase *base = clip->referencedClip();
1901         base->addCutZone(in, out);
1902         monitorItemEditing(false);
1903         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
1904         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
1905             if (!clip->isExpanded())
1906                 clip->setExpanded(true);
1907             m_listView->scrollToItem(sub);
1908             m_listView->editItem(sub, 1);
1909         }
1910         QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
1911         sub->setData(0, Qt::DecorationRole, p);
1912         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
1913         monitorItemEditing(true);
1914     }
1915     emit projectModified();
1916 }
1917
1918 void ProjectList::removeClipCut(const QString &id, int in, int out)
1919 {
1920     ProjectItem *clip = getItemById(id);
1921     if (clip) {
1922         DocClipBase *base = clip->referencedClip();
1923         base->removeCutZone(in, out);
1924         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
1925         if (sub) {
1926             monitorItemEditing(false);
1927             delete sub;
1928             monitorItemEditing(true);
1929         }
1930     }
1931     emit projectModified();
1932 }
1933
1934 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
1935 {
1936     SubProjectItem *sub = NULL;
1937     if (clip) {
1938         for (int i = 0; i < clip->childCount(); i++) {
1939             QTreeWidgetItem *it = clip->child(i);
1940             if (it->type() == PROJECTSUBCLIPTYPE) {
1941                 sub = static_cast <SubProjectItem*>(it);
1942                 if (sub->zone() == zone)
1943                     break;
1944                 else
1945                     sub = NULL;
1946             }
1947         }
1948     }
1949     return sub;
1950 }
1951
1952 void ProjectList::slotUpdateClipCut(QPoint p)
1953 {
1954     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
1955         return;
1956     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
1957     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1958     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
1959     m_commandStack->push(command);
1960 }
1961
1962 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
1963 {
1964     ProjectItem *clip = getItemById(id);
1965     SubProjectItem *sub = getSubItem(clip, oldzone);
1966     if (sub == NULL || clip == NULL)
1967         return;
1968     DocClipBase *base = clip->referencedClip();
1969     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
1970     monitorItemEditing(false);
1971     sub->setZone(zone);
1972     sub->setDescription(comment);
1973     monitorItemEditing(true);
1974     emit projectModified();
1975 }
1976
1977 void ProjectList::slotForceProcessing(const QString &id)
1978 {
1979     while (m_infoQueue.contains(id)) {
1980         slotProcessNextClipInQueue();
1981     }
1982 }
1983
1984 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
1985 {
1986     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
1987     QStringList list;
1988     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
1989     int count = list.count();
1990     if (count > 1) {
1991         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
1992         if (!existing.isEmpty()) {
1993             // Sequence already exists, update
1994             QString id = existing.at(0)->getId();
1995             //ProjectItem *item = getItemById(id);
1996             QMap <QString, QString> oldprops;
1997             QMap <QString, QString> newprops;
1998             int ttl = existing.at(0)->getProperty("ttl").toInt();
1999             oldprops["out"] = existing.at(0)->getProperty("out");
2000             newprops["out"] = QString::number(ttl * count - 1);
2001             slotUpdateClipProperties(id, newprops);
2002             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2003             m_commandStack->push(command);
2004         } else {
2005             // Create sequence
2006             QStringList groupInfo = getGroup();
2007             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2008                                                false, false, false,
2009                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2010                                                QString(), groupInfo.at(0), groupInfo.at(1));
2011         }
2012     } else emit displayMessage(i18n("Sequence not found"), -2);
2013 }
2014
2015 QMap <QString, QString> ProjectList::getProxies()
2016 {
2017     QMap <QString, QString> list;
2018     ProjectItem *item;
2019     QTreeWidgetItemIterator it(m_listView);
2020     while (*it) {
2021         if ((*it)->type() != PROJECTCLIPTYPE) {
2022             ++it;
2023             continue;
2024         }
2025         item = static_cast<ProjectItem *>(*it);
2026         if (item && item->referencedClip() != NULL) {
2027             QString proxy = item->referencedClip()->getProperty("proxy");
2028             if (!proxy.isEmpty()) list.insert(proxy, item->clipUrl().path());
2029         }
2030         ++it;
2031     }
2032     return list;
2033 }
2034
2035 void ProjectList::updateProxyConfig()
2036 {
2037     ProjectItem *item;
2038     QTreeWidgetItemIterator it(m_listView);
2039     while (*it) {
2040         if ((*it)->type() != PROJECTCLIPTYPE) {
2041             ++it;
2042             continue;
2043         }
2044         item = static_cast<ProjectItem *>(*it);
2045         if (item == NULL) {
2046             ++it;
2047             continue;
2048         }
2049         CLIPTYPE t = item->clipType();
2050         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2051             if  (generateProxy() && useProxy()) {
2052                 DocClipBase *clip = item->referencedClip();
2053                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > proxyMinSize()) {
2054                     connect(clip, SIGNAL(proxyReady(const QString &, bool)), this, SLOT(slotGotProxy(const QString &, bool)));
2055                     setProxyStatus(item, 1);
2056                     clip->generateProxy(m_doc->projectFolder(), proxyParams());
2057                 }
2058             }
2059             else if (!item->referencedClip()->getProperty("proxy").isEmpty()) {
2060                 // remove proxy
2061                 item->referencedClip()->clearProperty("proxy");
2062                 QDomElement e = item->toXml().cloneNode().toElement();
2063                 e.removeAttribute("file_hash");
2064                 e.setAttribute("replace", 1);
2065                 m_infoQueue.insert(item->clipId(), e);
2066             }
2067         }
2068         ++it;
2069     }
2070     if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2071 }
2072
2073 void ProjectList::slotProxyCurrentItem(bool doProxy)
2074 {
2075     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2076     QTreeWidgetItem *listItem;
2077     for (int i = 0; i < list.count(); i++) {
2078         listItem = list.at(i);
2079         if (listItem->type() == PROJECTFOLDERTYPE) {
2080             for (int j = 0; j < listItem->childCount(); j++) {
2081                 QTreeWidgetItem *sub = listItem->child(j);
2082                 if (!list.contains(sub)) list.append(sub);
2083             }
2084         }
2085         if (listItem->type() == PROJECTCLIPTYPE) {
2086             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2087             CLIPTYPE t = item->clipType();
2088             if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip()) {
2089                 if (doProxy) {
2090                     DocClipBase *clip = item->referencedClip();
2091                     connect(clip, SIGNAL(proxyReady(const QString&, bool)), this, SLOT(slotGotProxy(const QString&, bool)));
2092                     setProxyStatus(item, 1);
2093                     clip->generateProxy(m_doc->projectFolder(), proxyParams());
2094                 }
2095                 else if (!item->referencedClip()->getProperty("proxy").isEmpty()) {
2096                     // remove proxy
2097                     if (!item->isProxyRunning()) {
2098                         setProxyStatus(item, 0);
2099                         QDomElement e = item->toXml().cloneNode().toElement();
2100                         e.removeAttribute("file_hash");
2101                         e.setAttribute("replace", 1);
2102                         m_infoQueue.insert(item->clipId(), e);
2103                     }
2104                     else setProxyStatus(item, 0);
2105                 }
2106             }
2107         }
2108     }
2109     if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2110 }
2111
2112 void ProjectList::setProxyStatus(ProjectItem *item, int status)
2113 {
2114     monitorItemEditing(false);
2115     item->setProxyStatus(status);
2116     monitorItemEditing(true);
2117 }
2118
2119 void ProjectList::monitorItemEditing(bool enable)
2120 {
2121     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2122     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2123 }
2124
2125 #include "projectlist.moc"