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