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