]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix "Clean project" and "Delete unused files" removing folders and check for duplicat...
[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 "editclipcommand.h"
35 #include "editfoldercommand.h"
36 #include "ui_templateclip_ui.h"
37
38 #include <KDebug>
39 #include <KAction>
40 #include <KLocale>
41 #include <KFileDialog>
42 #include <KInputDialog>
43 #include <KMessageBox>
44 #include <KIO/NetAccess>
45 #include <KFileItem>
46
47 #include <nepomuk/global.h>
48 #include <nepomuk/resourcemanager.h>
49 //#include <nepomuk/tag.h>
50
51 #include <QMouseEvent>
52 #include <QStylePainter>
53 #include <QPixmap>
54 #include <QIcon>
55 #include <QMenu>
56 #include <QProcess>
57 #include <QHeaderView>
58
59 ProjectList::ProjectList(QWidget *parent) :
60         QWidget(parent),
61         m_render(NULL),
62         m_fps(-1),
63         m_commandStack(NULL),
64         m_editAction(NULL),
65         m_deleteAction(NULL),
66         m_openAction(NULL),
67         m_reloadAction(NULL),
68         m_transcodeAction(NULL),
69         m_selectedItem(NULL),
70         m_refreshed(false),
71         m_infoQueue(),
72         m_thumbnailQueue()
73 {
74
75     m_listView = new ProjectListView(this);;
76     QVBoxLayout *layout = new QVBoxLayout;
77     layout->setContentsMargins(0, 0, 0, 0);
78
79     // setup toolbar
80     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine(this);
81     m_toolbar = new QToolBar("projectToolBar", this);
82     m_toolbar->addWidget(searchView);
83     searchView->setTreeWidget(m_listView);
84
85     m_addButton = new QToolButton(m_toolbar);
86     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
87     m_toolbar->addWidget(m_addButton);
88
89     layout->addWidget(m_toolbar);
90     layout->addWidget(m_listView);
91     setLayout(layout);
92
93     m_queueTimer.setInterval(100);
94     connect(&m_queueTimer, SIGNAL(timeout()), this, SLOT(slotProcessNextClipInQueue()));
95     m_queueTimer.setSingleShot(true);
96
97
98
99     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
100     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
101     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
102     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
103     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
104     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
105     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
106     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
107
108     m_listViewDelegate = new ItemDelegate(m_listView);
109     m_listView->setItemDelegate(m_listViewDelegate);
110
111     if (KdenliveSettings::activate_nepomuk()) {
112         Nepomuk::ResourceManager::instance()->init();
113         if (!Nepomuk::ResourceManager::instance()->initialized()) {
114             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
115             KdenliveSettings::setActivate_nepomuk(false);
116         }
117     }
118 }
119
120 ProjectList::~ProjectList()
121 {
122     delete m_menu;
123     delete m_toolbar;
124     m_listView->blockSignals(true);
125     m_listView->clear();
126     delete m_listViewDelegate;
127 }
128
129 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
130 {
131     QList <QAction *> actions = addMenu->actions();
132     for (int i = 0; i < actions.count(); i++) {
133         if (actions.at(i)->data().toString() == "clip_properties") {
134             m_editAction = actions.at(i);
135             m_toolbar->addAction(m_editAction);
136             actions.removeAt(i);
137             i--;
138         } else if (actions.at(i)->data().toString() == "delete_clip") {
139             m_deleteAction = actions.at(i);
140             m_toolbar->addAction(m_deleteAction);
141             actions.removeAt(i);
142             i--;
143         } else if (actions.at(i)->data().toString() == "edit_clip") {
144             m_openAction = actions.at(i);
145             actions.removeAt(i);
146             i--;
147         } else if (actions.at(i)->data().toString() == "reload_clip") {
148             m_reloadAction = actions.at(i);
149             actions.removeAt(i);
150             i--;
151         }
152     }
153
154     QMenu *m = new QMenu();
155     m->addActions(actions);
156     m_addButton->setMenu(m);
157     m_addButton->setDefaultAction(defaultAction);
158     m_menu = new QMenu();
159     m_menu->addActions(addMenu->actions());
160 }
161
162 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu)
163 {
164     if (!addMenu) return;
165     QMenu *menu = m_addButton->menu();
166     menu->addMenu(addMenu);
167     m_addButton->setMenu(menu);
168
169     m_menu->addMenu(addMenu);
170     if (addMenu->isEmpty()) addMenu->setEnabled(false);
171     m_menu->addMenu(transcodeMenu);
172     if (transcodeMenu->isEmpty()) transcodeMenu->setEnabled(false);
173     m_transcodeAction = transcodeMenu;
174     m_menu->addAction(m_reloadAction);
175     m_menu->addAction(m_editAction);
176     m_menu->addAction(m_openAction);
177     m_menu->addAction(m_deleteAction);
178     m_menu->insertSeparator(m_deleteAction);
179 }
180
181
182 QByteArray ProjectList::headerInfo() const
183 {
184     return m_listView->header()->saveState();
185 }
186
187 void ProjectList::setHeaderInfo(const QByteArray &state)
188 {
189     m_listView->header()->restoreState(state);
190 }
191
192 void ProjectList::slotEditClip()
193 {
194     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
195     if (!(item->flags() & Qt::ItemIsDragEnabled)) return;
196     if (item && !item->isGroup()) {
197         emit clipSelected(item->referencedClip());
198         emit showClipProperties(item->referencedClip());
199     }
200 }
201
202 void ProjectList::slotOpenClip()
203 {
204     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
205     if (item && !item->isGroup()) {
206         if (item->clipType() == IMAGE) {
207             if (KdenliveSettings::defaultimageapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open images in the Settings dialog"));
208             else QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
209         }
210         if (item->clipType() == AUDIO) {
211             if (KdenliveSettings::defaultaudioapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open audio files in the Settings dialog"));
212             else QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
213         }
214     }
215 }
216
217 void ProjectList::cleanup()
218 {
219     m_listView->clearSelection();
220     QTreeWidgetItemIterator it(m_listView);
221     ProjectItem *item;
222     while (*it) {
223         item = static_cast <ProjectItem *>(*it);
224         if (!item->isGroup() && item->numReferences() == 0) item->setSelected(true);
225         it++;
226     }
227     slotRemoveClip();
228 }
229
230 void ProjectList::trashUnusedClips()
231 {
232     QTreeWidgetItemIterator it(m_listView);
233     ProjectItem *item;
234     QStringList ids;
235     KUrl::List urls;
236     while (*it) {
237         item = static_cast <ProjectItem *>(*it);
238         if (!item->isGroup() && item->numReferences() == 0) {
239             ids << item->clipId();
240             KUrl url = item->clipUrl();
241             if (!url.isEmpty()) urls << url;
242         }
243         it++;
244     }
245     // Check that we don't use the URL in another clip
246     QTreeWidgetItemIterator it2(m_listView);
247     while (*it2) {
248         item = static_cast <ProjectItem *>(*it2);
249         if (item->numReferences() > 0) {
250             KUrl url = item->clipUrl();
251             if (!url.isEmpty() && urls.contains(url)) urls.removeAll(url);
252         }
253         it2++;
254     }
255
256     m_doc->deleteProjectClip(ids);
257     for (int i = 0; i < urls.count(); i++) {
258         KIO::NetAccess::del(urls.at(i), this);
259     }
260 }
261
262 void ProjectList::slotReloadClip(const QString &id)
263 {
264     QList<QTreeWidgetItem *> selected;
265     if (id.isEmpty()) selected = m_listView->selectedItems();
266     else selected.append(getItemById(id));
267     ProjectItem *item;
268     for (int i = 0; i < selected.count(); i++) {
269         item = static_cast <ProjectItem *>(selected.at(i));
270         if (item && !item->isGroup()) {
271             if (item->clipType() == IMAGE) {
272                 item->referencedClip()->producer()->set("force_reload", 1);
273             } else if (item->clipType() == TEXT) {
274                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item);
275             }
276             //requestClipInfo(item->toXml(), item->clipId(), true);
277             // Clear the file_hash value, which will cause a complete reload of the clip
278             emit getFileProperties(item->toXml(), item->clipId(), true);
279         }
280     }
281 }
282
283 void ProjectList::setRenderer(Render *projectRender)
284 {
285     m_render = projectRender;
286     m_listView->setIconSize(QSize(40 * m_render->dar(), 40));
287 }
288
289 void ProjectList::slotClipSelected()
290 {
291     if (m_listView->currentItem()) {
292         ProjectItem *clip = static_cast <ProjectItem*>(m_listView->currentItem());
293         if (!clip->isGroup()) {
294             m_selectedItem = clip;
295             emit clipSelected(clip->referencedClip());
296         }
297         m_editAction->setEnabled(true);
298         m_deleteAction->setEnabled(true);
299         m_reloadAction->setEnabled(true);
300         m_transcodeAction->setEnabled(true);
301         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
302             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
303             m_openAction->setEnabled(true);
304         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
305             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
306             m_openAction->setEnabled(true);
307         } else m_openAction->setEnabled(false);
308     } else {
309         emit clipSelected(NULL);
310         m_editAction->setEnabled(false);
311         m_deleteAction->setEnabled(false);
312         m_openAction->setEnabled(false);
313         m_reloadAction->setEnabled(false);
314         m_transcodeAction->setEnabled(false);
315     }
316 }
317
318 void ProjectList::slotPauseMonitor()
319 {
320     if (m_render) m_render->pause();
321 }
322
323 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
324 {
325     ProjectItem *item = getItemById(id);
326     if (item) {
327         slotUpdateClipProperties(item, properties);
328         if (properties.contains("out")) {
329             slotReloadClip(id);
330         } else if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio") || properties.contains("templatetext")) {
331             slotRefreshClipThumbnail(item);
332             emit refreshClip();
333         }
334     }
335 }
336
337 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
338 {
339     if (!clip) return;
340     if (!clip->isGroup()) clip->setProperties(properties);
341     if (properties.contains("name")) {
342         m_listView->blockSignals(true);
343         clip->setText(1, properties.value("name"));
344         m_listView->blockSignals(false);
345         emit clipNameChanged(clip->clipId(), properties.value("name"));
346     }
347     if (properties.contains("description")) {
348         CLIPTYPE type = clip->clipType();
349         m_listView->blockSignals(true);
350         clip->setText(2, properties.value("description"));
351         m_listView->blockSignals(false);
352         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
353             // Use Nepomuk system to store clip description
354             Nepomuk::Resource f(clip->clipUrl().path());
355             f.setDescription(properties.value("description"));
356         }
357         emit projectModified();
358     }
359 }
360
361 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
362 {
363     ProjectItem *clip = static_cast <ProjectItem*>(item);
364     if (column == 2) {
365         if (clip->referencedClip()) {
366             QMap <QString, QString> oldprops;
367             QMap <QString, QString> newprops;
368             oldprops["description"] = clip->referencedClip()->getProperty("description");
369             newprops["description"] = item->text(2);
370
371             if (clip->clipType() == TEXT) {
372                 // This is a text template clip, update the image
373                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
374                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
375                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
376                 newprops.insert("templatetext", item->text(2));
377             }
378             slotUpdateClipProperties(clip->clipId(), newprops);
379             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
380             m_commandStack->push(command);
381         }
382     } else if (column == 1) {
383         if (clip->isGroup()) {
384             editFolder(item->text(1), clip->groupName(), clip->clipId());
385             clip->setGroupName(item->text(1));
386             m_doc->clipManager()->addFolder(clip->clipId(), item->text(1));
387             const int children = item->childCount();
388             for (int i = 0; i < children; i++) {
389                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
390                 child->setProperty("groupname", item->text(1));
391             }
392         } else {
393             if (clip->referencedClip()) {
394                 QMap <QString, QString> oldprops;
395                 QMap <QString, QString> newprops;
396                 oldprops["name"] = clip->referencedClip()->getProperty("name");
397                 newprops["name"] = item->text(1);
398                 slotUpdateClipProperties(clip, newprops);
399                 emit projectModified();
400                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
401                 m_commandStack->push(command);
402             }
403         }
404     }
405 }
406
407 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
408 {
409     bool enable = false;
410     if (item) {
411         enable = true;
412     }
413     m_editAction->setEnabled(enable);
414     m_deleteAction->setEnabled(enable);
415     m_reloadAction->setEnabled(enable);
416     m_transcodeAction->setEnabled(enable);
417     if (enable) {
418         ProjectItem *clip = static_cast <ProjectItem*>(item);
419         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
420             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
421             m_openAction->setEnabled(true);
422         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
423             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
424             m_openAction->setEnabled(true);
425         } else m_openAction->setEnabled(false);
426     } else m_openAction->setEnabled(false);
427     m_menu->popup(pos);
428 }
429
430 void ProjectList::slotRemoveClip()
431 {
432     if (!m_listView->currentItem()) return;
433     QStringList ids;
434     QMap <QString, QString> folderids;
435     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
436     ProjectItem *item;
437     for (int i = 0; i < selected.count(); i++) {
438         item = static_cast <ProjectItem *>(selected.at(i));
439         if (item->isGroup()) folderids[item->groupName()] = item->clipId();
440         else ids << item->clipId();
441         if (item->numReferences() > 0) {
442             if (KMessageBox::questionYesNo(this, 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")) != KMessageBox::Yes) return;
443         } else if (item->isGroup() && item->childCount() > 0) {
444             int children = item->childCount();
445             if (KMessageBox::questionYesNo(this, 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, item->names().at(1)), i18n("Delete Folder")) != KMessageBox::Yes) return;
446             for (int i = 0; i < children; ++i) {
447                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
448                 ids << child->clipId();
449             }
450         }
451     }
452     if (!ids.isEmpty()) m_doc->deleteProjectClip(ids);
453     if (!folderids.isEmpty()) deleteProjectFolder(folderids);
454     if (m_listView->topLevelItemCount() == 0) {
455         m_editAction->setEnabled(false);
456         m_deleteAction->setEnabled(false);
457         m_openAction->setEnabled(false);
458         m_reloadAction->setEnabled(false);
459         m_transcodeAction->setEnabled(false);
460     }
461 }
462
463 void ProjectList::selectItemById(const QString &clipId)
464 {
465     ProjectItem *item = getItemById(clipId);
466     if (item) m_listView->setCurrentItem(item);
467 }
468
469
470 void ProjectList::slotDeleteClip(const QString &clipId)
471 {
472     ProjectItem *item = getItemById(clipId);
473     if (!item) {
474         kDebug() << "/// Cannot find clip to delete";
475         return;
476     }
477     m_listView->blockSignals(true);
478     delete item;
479     m_doc->clipManager()->deleteClip(clipId);
480     m_listView->blockSignals(false);
481     slotClipSelected();
482 }
483
484
485 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
486 {
487     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
488     m_commandStack->push(command);
489     m_doc->setModified(true);
490 }
491
492 void ProjectList::slotAddFolder()
493 {
494     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
495     m_commandStack->push(command);
496 }
497
498 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
499 {
500     if (remove) {
501         ProjectItem *item = getFolderItemById(clipId);
502         if (item) {
503             m_doc->clipManager()->deleteFolder(clipId);
504             delete item;
505         }
506     } else {
507         if (edit) {
508             ProjectItem *item = getFolderItemById(clipId);
509             if (item) {
510                 m_listView->blockSignals(true);
511                 item->setGroupName(foldername);
512                 m_listView->blockSignals(false);
513                 m_doc->clipManager()->addFolder(clipId, foldername);
514                 const int children = item->childCount();
515                 for (int i = 0; i < children; i++) {
516                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
517                     child->setProperty("groupname", foldername);
518                 }
519             }
520         } else {
521             QStringList text;
522             text << QString() << foldername;
523             m_listView->blockSignals(true);
524             m_listView->setCurrentItem(new ProjectItem(m_listView, text, clipId));
525             m_doc->clipManager()->addFolder(clipId, foldername);
526             m_listView->blockSignals(false);
527         }
528     }
529 }
530
531
532
533 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
534 {
535     QMapIterator<QString, QString> i(map);
536     QUndoCommand *delCommand = new QUndoCommand();
537     delCommand->setText(i18n("Delete Folder"));
538     while (i.hasNext()) {
539         i.next();
540         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
541     }
542     m_commandStack->push(delCommand);
543     m_doc->setModified(true);
544 }
545
546 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
547 {
548     m_listView->setEnabled(false);
549     if (getProperties) {
550         m_listView->blockSignals(true);
551         m_refreshed = false;
552         // remove file_hash so that we load all properties for the clip
553         QDomElement e = clip->toXML().cloneNode().toElement();
554         e.removeAttribute("file_hash");
555         m_infoQueue.insert(clip->getId(), e);
556         //m_render->getFileProperties(clip->toXML(), clip->getId(), true);
557     }
558     const QString parent = clip->getProperty("groupid");
559     ProjectItem *item = NULL;
560     if (!parent.isEmpty()) {
561         ProjectItem *parentitem = getFolderItemById(parent);
562         if (!parentitem) {
563             QStringList text;
564             QString groupName = clip->getProperty("groupname");
565             //kDebug() << "Adding clip to new group: " << groupName;
566             if (groupName.isEmpty()) groupName = i18n("Folder");
567             text << QString() << groupName;
568             parentitem = new ProjectItem(m_listView, text, parent);
569         } else {
570             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
571         }
572         if (parentitem) item = new ProjectItem(parentitem, clip);
573     }
574     if (item == NULL) item = new ProjectItem(m_listView, clip);
575     KUrl url = clip->fileURL();
576
577     if (getProperties == false && !clip->getClipHash().isEmpty()) {
578         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
579         if (QFile::exists(cachedPixmap)) {
580             item->setIcon(0, QPixmap(cachedPixmap));
581         }
582     }
583
584     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
585         // if file has Nepomuk comment, use it
586         Nepomuk::Resource f(url.path());
587         QString annotation = f.description();
588         if (!annotation.isEmpty()) item->setText(2, annotation);
589         item->setText(3, QString::number(f.rating()));
590     }
591     if (getProperties && m_listView->isEnabled()) m_listView->blockSignals(false);
592     if (getProperties && !m_queueTimer.isActive()) m_queueTimer.start();
593 }
594
595 void ProjectList::slotResetProjectList()
596 {
597     m_listView->clear();
598     emit clipSelected(NULL);
599     m_thumbnailQueue.clear();
600     m_infoQueue.clear();
601     m_refreshed = false;
602 }
603
604 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
605 {
606     m_refreshed = false;
607     m_infoQueue.insert(id, xml);
608     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
609 }
610
611 void ProjectList::slotProcessNextClipInQueue()
612 {
613     if (m_infoQueue.isEmpty()) {
614         slotProcessNextThumbnail();
615         return;
616     }
617
618     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
619     if (j != m_infoQueue.constEnd()) {
620         const QDomElement dom = j.value();
621         const QString id = j.key();
622         m_infoQueue.remove(j.key());
623         emit getFileProperties(dom, id, false);
624     }
625     //if (!m_infoQueue.isEmpty() && !m_queueTimer.isActive()) m_queueTimer.start();
626 }
627
628 void ProjectList::slotUpdateClip(const QString &id)
629 {
630     ProjectItem *item = getItemById(id);
631     m_listView->blockSignals(true);
632     if (item) item->setData(1, UsageRole, QString::number(item->numReferences()));
633     m_listView->blockSignals(false);
634 }
635
636 void ProjectList::updateAllClips()
637 {
638     m_listView->setSortingEnabled(false);
639
640     QTreeWidgetItemIterator it(m_listView);
641     DocClipBase *clip;
642     ProjectItem *item;
643     m_listView->blockSignals(true);
644     while (*it) {
645         item = static_cast <ProjectItem *>(*it);
646         if (!item->isGroup()) {
647             clip = item->referencedClip();
648             if (item->referencedClip()->producer() == NULL) {
649                 if (clip->isPlaceHolder() == false) {
650                     requestClipInfo(clip->toXML(), clip->getId());
651                 } else item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
652             } else {
653                 if (item->icon(0).isNull()) {
654                     requestClipThumbnail(clip->getId());
655                 }
656                 if (item->data(1, DurationRole).toString().isEmpty()) {
657                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
658                 }
659             }
660             item->setData(1, UsageRole, QString::number(item->numReferences()));
661             //qApp->processEvents();
662         }
663         ++it;
664     }
665     qApp->processEvents();
666     if (!m_queueTimer.isActive()) m_queueTimer.start();
667
668     if (m_listView->isEnabled()) m_listView->blockSignals(false);
669     m_listView->setSortingEnabled(true);
670     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
671 }
672
673 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
674 {
675     if (!m_commandStack) {
676         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
677     }
678     KUrl::List list;
679     if (givenList.isEmpty()) {
680         // Build list of mime types
681         QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mlt-playlist" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "application/ogg" << "video/mp4" << "video/quicktime" << "image/gif" << "image/jpeg" << "image/png" << "image/x-tga" << "image/x-bmp" << "image/svg+xml" << "image/tiff" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
682
683         QString allExtensions;
684         foreach(const QString& mimeType, mimeTypes) {
685             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
686             if (mime) {
687                 allExtensions.append(mime->patterns().join(" "));
688                 allExtensions.append(' ');
689             }
690         }
691         const QString dialogFilter = allExtensions.simplified() + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
692         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
693
694     } else {
695         for (int i = 0; i < givenList.count(); i++)
696             list << givenList.at(i);
697     }
698     if (list.isEmpty()) return;
699
700     if (givenList.isEmpty()) {
701         QStringList groupInfo = getGroup();
702         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
703     } else m_doc->slotAddClipList(list, groupName, groupId);
704 }
705
706 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
707 {
708     ProjectItem *item = getItemById(id);
709     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
710     if (item) {
711         const QString path = item->referencedClip()->fileURL().path();
712         if (!path.isEmpty()) {
713             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br>is invalid, will be removed from project.", path));
714             else {
715                 if (KMessageBox::questionYesNo(this, i18n("Clip <b>%1</b><br>is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes) replace = true;
716             }
717         }
718         QStringList ids;
719         ids << id;
720         if (replace) m_doc->deleteProjectClip(ids);
721     }
722 }
723
724 void ProjectList::slotAddColorClip()
725 {
726     if (!m_commandStack) {
727         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
728     }
729     QDialog *dia = new QDialog(this);
730     Ui::ColorClip_UI dia_ui;
731     dia_ui.setupUi(dia);
732     dia_ui.clip_name->setText(i18n("Color Clip"));
733     dia_ui.clip_duration->setText(KdenliveSettings::color_duration());
734     if (dia->exec() == QDialog::Accepted) {
735         QString color = dia_ui.clip_color->color().name();
736         color = color.replace(0, 1, "0x") + "ff";
737         QStringList groupInfo = getGroup();
738         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
739     }
740     delete dia;
741 }
742
743
744 void ProjectList::slotAddSlideshowClip()
745 {
746     if (!m_commandStack) {
747         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
748     }
749     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
750
751     if (dia->exec() == QDialog::Accepted) {
752         QStringList groupInfo = getGroup();
753         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(), dia->loop(), dia->fade(), dia->lumaDuration(), dia->lumaFile(), dia->softness(), groupInfo.at(0), groupInfo.at(1));
754     }
755     delete dia;
756 }
757
758 void ProjectList::slotAddTitleClip()
759 {
760     QStringList groupInfo = getGroup();
761     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
762 }
763
764 void ProjectList::slotAddTitleTemplateClip()
765 {
766     QStringList groupInfo = getGroup();
767     if (!m_commandStack) {
768         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
769     }
770
771     // Get the list of existing templates
772     QStringList filter;
773     filter << "*.kdenlivetitle";
774     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
775     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
776
777     QDialog *dia = new QDialog(this);
778     Ui::TemplateClip_UI dia_ui;
779     dia_ui.setupUi(dia);
780     for (int i = 0; i < templateFiles.size(); ++i) {
781         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
782     }
783     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
784     //warning: setting base directory doesn't work??
785     KUrl startDir(path);
786     dia_ui.template_list->fileDialog()->setUrl(startDir);
787     dia_ui.text_box->setHidden(true);
788     if (dia->exec() == QDialog::Accepted) {
789         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
790         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
791         // Create a cloned template clip
792         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
793     }
794     delete dia;
795 }
796
797 QStringList ProjectList::getGroup() const
798 {
799     QStringList result;
800     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
801     if (item && !item->isGroup()) {
802         while (item->parent()) {
803             item = static_cast <ProjectItem*>(item->parent());
804             if (item->isGroup()) break;
805         }
806     }
807     if (item && item->isGroup()) {
808         result << item->groupName();
809         result << item->clipId();
810     } else result << QString() << QString();
811     return result;
812 }
813
814 void ProjectList::setDocument(KdenliveDoc *doc)
815 {
816     m_listView->blockSignals(true);
817     m_listView->clear();
818     m_listView->setSortingEnabled(false);
819     emit clipSelected(NULL);
820     m_thumbnailQueue.clear();
821     m_infoQueue.clear();
822     m_refreshed = false;
823     m_fps = doc->fps();
824     m_timecode = doc->timecode();
825     m_commandStack = doc->commandStack();
826     m_doc = doc;
827
828     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
829     QMapIterator<QString, QString> f(flist);
830     while (f.hasNext()) {
831         f.next();
832         (void) new ProjectItem(m_listView, QStringList() << QString() << f.value(), f.key());
833     }
834
835     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
836     for (int i = 0; i < list.count(); i++) {
837         slotAddClip(list.at(i), false);
838     }
839
840     m_listView->blockSignals(false);
841     m_toolbar->setEnabled(true);
842     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
843     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
844 }
845
846 QDomElement ProjectList::producersList()
847 {
848     QDomDocument doc;
849     QDomElement prods = doc.createElement("producerlist");
850     doc.appendChild(prods);
851     kDebug() << "////////////  PRO LISTĀ BUILD PRDSLIST ";
852     QTreeWidgetItemIterator it(m_listView);
853     while (*it) {
854         if (!((ProjectItem *)(*it))->isGroup())
855             prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
856         ++it;
857     }
858     return prods;
859 }
860
861 void ProjectList::slotCheckForEmptyQueue()
862 {
863     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
864         m_refreshed = true;
865         emit loadingIsOver();
866         emit displayMessage(QString(), -1);
867         m_listView->blockSignals(false);
868         m_listView->setEnabled(true);
869     } else if (!m_refreshed) QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
870 }
871
872 void ProjectList::reloadClipThumbnails()
873 {
874     kDebug() << "//////////////  RELOAD CLIPS THUMBNAILS!!!";
875     m_thumbnailQueue.clear();
876     QTreeWidgetItemIterator it(m_listView);
877     while (*it) {
878         if (!((ProjectItem *)(*it))->isGroup())
879             m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
880         ++it;
881     }
882     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
883 }
884
885 void ProjectList::requestClipThumbnail(const QString id)
886 {
887     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
888 }
889
890 void ProjectList::slotProcessNextThumbnail()
891 {
892     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
893         slotCheckForEmptyQueue();
894         return;
895     }
896     if (!m_infoQueue.isEmpty()) {
897         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
898         return;
899     }
900     if (m_thumbnailQueue.count() > 1) {
901         int max = m_doc->clipManager()->clipsCount();
902         emit displayMessage(i18n("Loading thumbnails"), (int)(100 * (max - m_thumbnailQueue.count()) / max));
903     }
904     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
905 }
906
907 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
908 {
909     ProjectItem *item = getItemById(clipId);
910     if (item) slotRefreshClipThumbnail(item, update);
911     else slotProcessNextThumbnail();
912 }
913
914 void ProjectList::slotRefreshClipThumbnail(ProjectItem *item, bool update)
915 {
916     if (item) {
917         DocClipBase *clip = item->referencedClip();
918         if (!clip) {
919             slotProcessNextThumbnail();
920             return;
921         }
922         QPixmap pix;
923         int height = 50;
924         int width = (int)(height  * m_render->dar());
925         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
926         else if (clip->clipType() == IMAGE) pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
927         else pix = item->referencedClip()->thumbProducer()->extractImage(item->referencedClip()->getClipThumbFrame(), width, height);
928         if (!pix.isNull()) {
929             m_listView->blockSignals(true);
930             item->setIcon(0, pix);
931             if (m_listView->isEnabled()) m_listView->blockSignals(false);
932             m_doc->cachePixmap(item->getClipHash(), pix);
933         }
934         if (update) emit projectModified();
935         QTimer::singleShot(30, this, SLOT(slotProcessNextThumbnail()));
936     }
937 }
938
939 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
940 {
941     ProjectItem *item = getItemById(clipId);
942     if (item && producer) {
943         m_listView->blockSignals(true);
944         item->setProperties(properties, metadata);
945         Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
946         item->referencedClip()->setProducer(producer, replace);
947         //emit receivedClipDuration(clipId);
948         if (m_listView->isEnabled() && replace) {
949             // update clip in clip monitor
950             emit clipSelected(NULL);
951             emit clipSelected(item->referencedClip());
952         }
953         /*else {
954             // Check if duration changed.
955             emit receivedClipDuration(clipId);
956             delete producer;
957         }*/
958         if (m_listView->isEnabled()) m_listView->blockSignals(false);
959         if (item->icon(0).isNull()) {
960             requestClipThumbnail(clipId);
961         }
962     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
963     int max = m_doc->clipManager()->clipsCount();
964     emit displayMessage(i18n("Loading clips"), (int)(100 * (max - m_infoQueue.count()) / max));
965     // small delay so that the app can display the progress info
966     QTimer::singleShot(30, this, SLOT(slotProcessNextClipInQueue()));
967 }
968
969 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
970 {
971     ProjectItem *item = getItemById(clipId);
972     if (item && !pix.isNull()) {
973         m_listView->blockSignals(true);
974         item->setIcon(0, pix);
975         m_doc->cachePixmap(item->getClipHash(), pix);
976         if (m_listView->isEnabled()) m_listView->blockSignals(false);
977     }
978 }
979
980 ProjectItem *ProjectList::getItemById(const QString &id)
981 {
982     ProjectItem *item;
983     QTreeWidgetItemIterator it(m_listView);
984     while (*it) {
985         item = static_cast<ProjectItem *>(*it);
986         if (item->clipId() == id && item->clipType() != FOLDER)
987             return item;
988         ++it;
989     }
990     return NULL;
991 }
992
993 ProjectItem *ProjectList::getFolderItemById(const QString &id)
994 {
995     ProjectItem *item;
996     QTreeWidgetItemIterator it(m_listView);
997     while (*it) {
998         item = static_cast<ProjectItem *>(*it);
999         if (item->clipId() == id && item->clipType() == FOLDER)
1000             return item;
1001         ++it;
1002     }
1003     return NULL;
1004 }
1005
1006 void ProjectList::slotSelectClip(const QString &ix)
1007 {
1008     ProjectItem *clip = getItemById(ix);
1009     if (clip) {
1010         m_listView->setCurrentItem(clip);
1011         m_listView->scrollToItem(clip);
1012         m_editAction->setEnabled(true);
1013         m_deleteAction->setEnabled(true);
1014         m_reloadAction->setEnabled(true);
1015         m_transcodeAction->setEnabled(true);
1016         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1017             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1018             m_openAction->setEnabled(true);
1019         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1020             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1021             m_openAction->setEnabled(true);
1022         } else m_openAction->setEnabled(false);
1023     }
1024 }
1025
1026 QString ProjectList::currentClipUrl() const
1027 {
1028     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
1029     if (item == NULL) return QString();
1030     return item->clipUrl().path();
1031 }
1032
1033 void ProjectList::regenerateTemplate(const QString &id)
1034 {
1035     ProjectItem *clip = getItemById(id);
1036     if (clip) regenerateTemplate(clip);
1037 }
1038
1039 void ProjectList::regenerateTemplate(ProjectItem *clip)
1040 {
1041     //TODO: remove this unused method, only force_reload is necessary
1042     clip->referencedClip()->producer()->set("force_reload", 1);
1043 }
1044
1045 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1046 {
1047     QDomDocument doc;
1048     QFile file(path);
1049     if (!file.open(QIODevice::ReadOnly)) {
1050         kWarning() << "ERROR, CANNOT READ: " << path;
1051         return doc;
1052     }
1053     if (!doc.setContent(&file)) {
1054         kWarning() << "ERROR, CANNOT READ: " << path;
1055         file.close();
1056         return doc;
1057     }
1058     file.close();
1059     QDomNodeList texts = doc.elementsByTagName("content");
1060     for (int i = 0; i < texts.count(); i++) {
1061         QString data = texts.item(i).firstChild().nodeValue();
1062         data.replace("%s", replaceString);
1063         texts.item(i).firstChild().setNodeValue(data);
1064     }
1065     return doc;
1066 }
1067
1068 #include "projectlist.moc"