X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=src%2Fprojectlist.cpp;h=38391bd26143cb9c693d71b50478c80978759faa;hb=a1f47db12529bede571e784fe5e49d48707dcfa9;hp=102896c341dc18f28f965b6ba7741ee0367eb9f5;hpb=a222871aa5a6599f36eae197c7cfa3406ae017ce;p=kdenlive diff --git a/src/projectlist.cpp b/src/projectlist.cpp index 102896c3..c294ab19 100644 --- a/src/projectlist.cpp +++ b/src/projectlist.cpp @@ -19,7 +19,10 @@ #include "projectlist.h" #include "projectitem.h" -#include "addfoldercommand.h" +#include "commands/addfoldercommand.h" +#include "projecttree/proxyclipjob.h" +#include "projecttree/cutclipjob.h" +#include "projecttree/meltjob.h" #include "kdenlivesettings.h" #include "slideshowclip.h" #include "ui_colorclip_ui.h" @@ -33,12 +36,15 @@ #include "projectlistview.h" #include "timecodedisplay.h" #include "profilesdialog.h" -#include "editclipcommand.h" -#include "editclipcutcommand.h" -#include "editfoldercommand.h" -#include "addclipcutcommand.h" +#include "clipstabilize.h" +#include "commands/editclipcommand.h" +#include "commands/editclipcutcommand.h" +#include "commands/editfoldercommand.h" +#include "commands/addclipcutcommand.h" #include "ui_templateclip_ui.h" +#include "ui_cutjobdialog_ui.h" +#include "ui_scenecutdialog_ui.h" #include #include @@ -50,10 +56,16 @@ #include #include #include +#include +#include +#include +#include +#include -#ifdef NEPOMUK +#ifdef USE_NEPOMUK #include #include +#include //#include #endif @@ -63,9 +75,148 @@ #include #include #include +#include #include #include #include +#include +#include + + +MyMessageWidget::MyMessageWidget(QWidget *parent) : KMessageWidget(parent) {} +MyMessageWidget::MyMessageWidget(const QString &text, QWidget *parent) : KMessageWidget(text, parent) {} + + +bool MyMessageWidget::event(QEvent* ev) { + if (ev->type() == QEvent::Hide || ev->type() == QEvent::Close) emit messageClosing(); + return KMessageWidget::event(ev); +} + +SmallInfoLabel::SmallInfoLabel(QWidget *parent) : QPushButton(parent) +{ + setFixedWidth(0); + setFlat(true); + + /*QString style = "QToolButton {background-color: %1;border-style: outset;border-width: 2px; + border-radius: 5px;border-color: beige;}";*/ + m_timeLine = new QTimeLine(500, this); + QObject::connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(slotTimeLineChanged(qreal))); + QObject::connect(m_timeLine, SIGNAL(finished()), this, SLOT(slotTimeLineFinished())); + hide(); +} + +const QString SmallInfoLabel::getStyleSheet(const QPalette &p) +{ + KColorScheme scheme(p.currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme())); + QColor bg = scheme.background(KColorScheme::LinkBackground).color(); + QColor fg = scheme.foreground(KColorScheme::LinkText).color(); + QString style = QString("QPushButton {padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(fg.red()).arg(fg.green()).arg(fg.blue()); + + bg = scheme.background(KColorScheme::ActiveBackground).color(); + fg = scheme.foreground(KColorScheme::ActiveText).color(); + style.append(QString("\nQPushButton:hover {padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(fg.red()).arg(fg.green()).arg(fg.blue())); + + return style; +} + +void SmallInfoLabel::slotTimeLineChanged(qreal value) +{ + setFixedWidth(qMin(value * 2, qreal(1.0)) * sizeHint().width()); + update(); +} + +void SmallInfoLabel::slotTimeLineFinished() +{ + if (m_timeLine->direction() == QTimeLine::Forward) { + // Show + show(); + } else { + // Hide + hide(); + setText(QString()); + } +} + +void SmallInfoLabel::slotSetJobCount(int jobCount) +{ + if (jobCount > 0) { + // prepare animation + setText(i18np("%1 job", "%1 jobs", jobCount)); + setToolTip(i18np("%1 pending job", "%1 pending jobs", jobCount)); + + if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) { + setFixedWidth(sizeHint().width()); + show(); + return; + } + + if (isVisible()) { + setFixedWidth(sizeHint().width()); + update(); + return; + } + + setFixedWidth(0); + show(); + int wantedWidth = sizeHint().width(); + setGeometry(-wantedWidth, 0, wantedWidth, height()); + m_timeLine->setDirection(QTimeLine::Forward); + if (m_timeLine->state() == QTimeLine::NotRunning) { + m_timeLine->start(); + } + } + else { + if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) { + setFixedWidth(0); + hide(); + return; + } + // hide + m_timeLine->setDirection(QTimeLine::Backward); + if (m_timeLine->state() == QTimeLine::NotRunning) { + m_timeLine->start(); + } + } + +} + + +InvalidDialog::InvalidDialog(const QString &caption, const QString &message, bool infoOnly, QWidget *parent) : KDialog(parent) +{ + setCaption(caption); + if (infoOnly) setButtons(KDialog::Ok); + else setButtons(KDialog::Yes | KDialog::No); + QWidget *w = new QWidget(this); + QVBoxLayout *l = new QVBoxLayout; + l->addWidget(new QLabel(message)); + m_clipList = new QListWidget; + l->addWidget(m_clipList); + w->setLayout(l); + setMainWidget(w); +} + +InvalidDialog::~InvalidDialog() +{ + delete m_clipList; +} + + +void InvalidDialog::addClip(const QString &id, const QString &path) +{ + QListWidgetItem *item = new QListWidgetItem(path); + item->setData(Qt::UserRole, id); + m_clipList->addItem(item); +} + +QStringList InvalidDialog::getIds() const +{ + QStringList ids; + for (int i = 0; i < m_clipList->count(); i++) { + ids << m_clipList->item(i)->data(Qt::UserRole).toString(); + } + return ids; +} + ProjectList::ProjectList(QWidget *parent) : QWidget(parent), @@ -74,12 +225,18 @@ ProjectList::ProjectList(QWidget *parent) : m_commandStack(NULL), m_openAction(NULL), m_reloadAction(NULL), + m_extractAudioAction(NULL), m_transcodeAction(NULL), + m_clipsActionsMenu(NULL), m_doc(NULL), m_refreshed(false), - m_infoQueue(), - m_thumbnailQueue() + m_allClipsProcessed(false), + m_thumbnailQueue(), + m_abortAllJobs(false), + m_closing(false), + m_invalidClipDialog(NULL) { + qRegisterMetaType ("stringMap"); QVBoxLayout *layout = new QVBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); @@ -88,51 +245,92 @@ ProjectList::ProjectList(QWidget *parent) : QFrame *frame = new QFrame; frame->setFrameStyle(QFrame::NoFrame); QHBoxLayout *box = new QHBoxLayout; + box->setContentsMargins(0, 0, 0, 0); + KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine; - box->addWidget(searchView); - //int s = style()->pixelMetric(QStyle::PM_SmallIconSize); - //m_toolbar->setIconSize(QSize(s, s)); + + // small info button for pending jobs + m_infoLabel = new SmallInfoLabel(this); + m_infoLabel->setStyleSheet(SmallInfoLabel::getStyleSheet(palette())); + connect(this, SIGNAL(jobCount(int)), m_infoLabel, SLOT(slotSetJobCount(int))); + m_jobsMenu = new QMenu(this); + connect(m_jobsMenu, SIGNAL(aboutToShow()), this, SLOT(slotPrepareJobsMenu())); + QAction *cancelJobs = new QAction(i18n("Cancel All Jobs"), this); + cancelJobs->setCheckable(false); + connect(cancelJobs, SIGNAL(triggered()), this, SLOT(slotCancelJobs())); + connect(this, SIGNAL(checkJobProcess()), this, SLOT(slotCheckJobProcess())); + m_discardCurrentClipJobs = new QAction(i18n("Cancel Current Clip Jobs"), this); + m_discardCurrentClipJobs->setCheckable(false); + connect(m_discardCurrentClipJobs, SIGNAL(triggered()), this, SLOT(slotDiscardClipJobs())); + m_jobsMenu->addAction(cancelJobs); + m_jobsMenu->addAction(m_discardCurrentClipJobs); + m_infoLabel->setMenu(m_jobsMenu); + box->addWidget(m_infoLabel); + + int size = style()->pixelMetric(QStyle::PM_SmallIconSize); + QSize iconSize(size, size); m_addButton = new QToolButton; m_addButton->setPopupMode(QToolButton::MenuButtonPopup); m_addButton->setAutoRaise(true); + m_addButton->setIconSize(iconSize); box->addWidget(m_addButton); m_editButton = new QToolButton; m_editButton->setAutoRaise(true); + m_editButton->setIconSize(iconSize); box->addWidget(m_editButton); m_deleteButton = new QToolButton; m_deleteButton->setAutoRaise(true); + m_deleteButton->setIconSize(iconSize); box->addWidget(m_deleteButton); frame->setLayout(box); layout->addWidget(frame); - m_listView = new ProjectListView; + m_listView = new ProjectListView(this); layout->addWidget(m_listView); + +#if KDE_IS_VERSION(4,7,0) + m_infoMessage = new MyMessageWidget; + layout->addWidget(m_infoMessage); + m_infoMessage->setCloseButtonVisible(true); + connect(m_infoMessage, SIGNAL(messageClosing()), this, SLOT(slotResetInfoMessage())); + //m_infoMessage->setWordWrap(true); + m_infoMessage->hide(); + m_logAction = new QAction(i18n("Show Log"), this); + m_logAction->setCheckable(false); + connect(m_logAction, SIGNAL(triggered()), this, SLOT(slotShowJobLog())); +#endif + setLayout(layout); searchView->setTreeWidget(m_listView); - m_proxyAction = new QAction(i18n("Proxy clip"), this); - m_proxyAction->setCheckable(true); - m_proxyAction->setChecked(false); - connect(m_proxyAction, SIGNAL(toggled(bool)), this, SLOT(slotProxyCurrentItem(bool))); connect(this, SIGNAL(processNextThumbnail()), this, SLOT(slotProcessNextThumbnail())); connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified())); connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected())); - connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected())); - connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor())); + connect(m_listView, SIGNAL(focusMonitor(bool)), this, SIGNAL(raiseClipMonitor(bool))); + connect(m_listView, SIGNAL(pauseMonitor()), this, SIGNAL(pauseMonitor())); connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *))); + connect(m_listView, SIGNAL(addClip()), this, SIGNAL(pauseMonitor())); connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip())); connect(m_listView, SIGNAL(addClip(const QList , const QString &, const QString &)), this, SLOT(slotAddClip(const QList , const QString &, const QString &))); + connect(this, SIGNAL(addClip(const QString, const QString &, const QString &)), this, SLOT(slotAddClip(const QString, const QString &, const QString &))); connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int))); connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int))); connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *))); - + + connect(this, SIGNAL(cancelRunningJob(const QString, stringMap )), this, SLOT(slotCancelRunningJob(const QString, stringMap))); + connect(this, SIGNAL(processLog(const QString, int , int, const QString)), this, SLOT(slotProcessLog(const QString, int , int, const QString))); + + connect(this, SIGNAL(updateJobStatus(const QString, int, int, const QString, const QString, const QString)), this, SLOT(slotUpdateJobStatus(const QString, int, int, const QString, const QString, const QString))); + + connect(this, SIGNAL(gotProxy(const QString)), this, SLOT(slotGotProxyForId(const QString))); + m_listViewDelegate = new ItemDelegate(m_listView); m_listView->setItemDelegate(m_listViewDelegate); -#ifdef NEPOMUK +#ifdef USE_NEPOMUK if (KdenliveSettings::activate_nepomuk()) { Nepomuk::ResourceManager::instance()->init(); if (!Nepomuk::ResourceManager::instance()->initialized()) { @@ -145,10 +343,23 @@ ProjectList::ProjectList(QWidget *parent) : ProjectList::~ProjectList() { + m_abortAllJobs = true; + for (int i = 0; i < m_jobList.count(); i++) { + m_jobList.at(i)->setStatus(JOBABORTED); + } + m_closing = true; + m_thumbnailQueue.clear(); + m_jobThreads.waitForFinished(); + m_jobThreads.clearFutures(); + if (!m_jobList.isEmpty()) qDeleteAll(m_jobList); + m_jobList.clear(); delete m_menu; m_listView->blockSignals(true); m_listView->clear(); delete m_listViewDelegate; +#if KDE_IS_VERSION(4,7,0) + delete m_infoMessage; +#endif } void ProjectList::focusTree() const @@ -176,6 +387,10 @@ void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction) m_reloadAction = actions.at(i); actions.removeAt(i); i--; + } else if (actions.at(i)->data().toString() == "proxy_clip") { + m_proxyAction = actions.at(i); + actions.removeAt(i); + i--; } } @@ -187,31 +402,55 @@ void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction) m_menu->addActions(addMenu->actions()); } -void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu, QMenu *inTimelineMenu) +void ProjectList::setupGeneratorMenu(const QHash& menus) { - if (!addMenu) + if (!menus.contains("addMenu") && ! menus.value("addMenu") ) return; QMenu *menu = m_addButton->menu(); - menu->addMenu(addMenu); - m_addButton->setMenu(menu); - - m_menu->addMenu(addMenu); - if (addMenu->isEmpty()) - addMenu->setEnabled(false); - m_menu->addMenu(transcodeMenu); - if (transcodeMenu->isEmpty()) - transcodeMenu->setEnabled(false); - m_transcodeAction = transcodeMenu; + if (menus.contains("addMenu") && menus.value("addMenu")){ + QMenu* addMenu=menus.value("addMenu"); + menu->addMenu(addMenu); + m_addButton->setMenu(menu); + if (addMenu->isEmpty()) + addMenu->setEnabled(false); + } + if (menus.contains("extractAudioMenu") && menus.value("extractAudioMenu") ){ + QMenu* extractAudioMenu = menus.value("extractAudioMenu"); + m_menu->addMenu(extractAudioMenu); + m_extractAudioAction = extractAudioMenu; + } + if (menus.contains("transcodeMenu") && menus.value("transcodeMenu") ){ + QMenu* transcodeMenu = menus.value("transcodeMenu"); + m_menu->addMenu(transcodeMenu); + if (transcodeMenu->isEmpty()) + transcodeMenu->setEnabled(false); + m_transcodeAction = transcodeMenu; + } + if (menus.contains("clipActionsMenu") && menus.value("clipActionsMenu") ){ + QMenu* stabilizeMenu=menus.value("clipActionsMenu"); + m_menu->addMenu(stabilizeMenu); + if (stabilizeMenu->isEmpty()) + stabilizeMenu->setEnabled(false); + m_clipsActionsMenu = stabilizeMenu; + + } m_menu->addAction(m_reloadAction); m_menu->addAction(m_proxyAction); - m_menu->addMenu(inTimelineMenu); - inTimelineMenu->setEnabled(false); + if (menus.contains("inTimelineMenu") && menus.value("inTimelineMenu")){ + QMenu* inTimelineMenu=menus.value("inTimelineMenu"); + m_menu->addMenu(inTimelineMenu); + inTimelineMenu->setEnabled(false); + } m_menu->addAction(m_editButton->defaultAction()); m_menu->addAction(m_openAction); m_menu->addAction(m_deleteButton->defaultAction()); m_menu->insertSeparator(m_deleteButton->defaultAction()); } +void ProjectList::clearSelection() +{ + m_listView->clearSelection(); +} QByteArray ProjectList::headerInfo() const { @@ -295,7 +534,7 @@ void ProjectList::editClipSelection(QList list) if (clip->getProperty("transparency").isEmpty() || clip->getProperty("transparency").toInt() == 0) { if (transparency == "-") { // first non transparent image - transparency = "0"; + transparency = '0'; } else if (transparency == "1") { // we have transparent and non transparent clips @@ -305,7 +544,7 @@ void ProjectList::editClipSelection(QList list) else { if (transparency == "-") { // first transparent image - transparency = "1"; + transparency = '1'; } else if (transparency == "0") { // we have transparent and non transparent clips @@ -347,7 +586,10 @@ void ProjectList::editClipSelection(QList list) p.next(); kDebug() << "Result: " << p.key() << " = " << p.value(); }*/ - emit showClipProperties(clipList, commonproperties); + if (clipList.isEmpty()) { + emit displayMessage(i18n("No available clip selected"), -2, ErrorMessage); + } + else emit showClipProperties(clipList, commonproperties); } void ProjectList::slotOpenClip() @@ -453,27 +695,34 @@ void ProjectList::slotReloadClip(const QString &id) continue; } item = static_cast (selected.at(i)); - if (item) { + if (item && !hasPendingJob(item, PROXYJOB)) { + DocClipBase *clip = item->referencedClip(); + if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) { + kDebug()<<"//// TRYING TO RELOAD: "<clipId()<<", but it is busy"; + continue; + } CLIPTYPE t = item->clipType(); if (t == TEXT) { - if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) + if (clip && !clip->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item); - } else if (t != COLOR && t != SLIDESHOW && item->referencedClip() && item->referencedClip()->checkHash() == false) { + } else if (t != COLOR && t != SLIDESHOW && clip && clip->checkHash() == false) { item->referencedClip()->setPlaceHolder(true); item->setProperty("file_hash", QString()); } else if (t == IMAGE) { - item->referencedClip()->producer()->set("force_reload", 1); + //clip->getProducer() clip->getProducer()->set("force_reload", 1); } QDomElement e = item->toXml(); // Make sure we get the correct producer length if it was adjusted in timeline if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) { - int length = QString(item->referencedClip()->producerProperty("length")).toInt(); - if (length > 0 && !e.hasAttribute("length")) { - e.setAttribute("length", length); - } - } - emit getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true, false); + int length = QString(clip->producerProperty("length")).toInt(); + if (length > 0 && !e.hasAttribute("length")) { + e.setAttribute("length", length); + } + e.setAttribute("duration", clip->getProperty("duration")); + } + resetThumbsProducer(clip); + m_render->getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true); } } } @@ -491,7 +740,7 @@ void ProjectList::slotModifiedClip(const QString &id) } else { pixmap = KIcon("view-refresh").pixmap(m_listView->iconSize()); } - item->setData(0, Qt::DecorationRole, pixmap); + item->setPixmap(pixmap); } } @@ -501,6 +750,10 @@ void ProjectList::slotMissingClip(const QString &id) if (item) { item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled); int height = m_listView->iconSize().height(); + if (m_render == NULL) { + kDebug() << "********* ERROR, NULL RENDR"; + return; + } int width = (int)(height * m_render->dar()); QPixmap pixmap = qVariantValue(item->data(0, Qt::DecorationRole)); if (pixmap.isNull()) { @@ -511,26 +764,22 @@ void ProjectList::slotMissingClip(const QString &id) QPainter p(&pixmap); p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6)); p.end(); - item->setData(0, Qt::DecorationRole, pixmap); + item->setPixmap(pixmap); if (item->referencedClip()) { item->referencedClip()->setPlaceHolder(true); - if (m_render == NULL) { - kDebug() << "********* ERROR, NULL RENDR"; - return; - } Mlt::Producer *newProd = m_render->invalidProducer(id); - if (item->referencedClip()->producer()) { + if (item->referencedClip()->getProducer()) { Mlt::Properties props(newProd->get_properties()); - Mlt::Properties src_props(item->referencedClip()->producer()->get_properties()); + Mlt::Properties src_props(item->referencedClip()->getProducer()->get_properties()); props.inherit(src_props); } item->referencedClip()->setProducer(newProd, true); item->slotSetToolTip(); - emit clipNeedsReload(id, true); + emit clipNeedsReload(id); } } update(); - emit displayMessage(i18n("Check missing clips"), -2); + emit displayMessage(i18n("Check missing clips"), -2, ErrorMessage); emit updateRenderStatus(); } @@ -570,39 +819,49 @@ void ProjectList::setRenderer(Render *projectRender) { m_render = projectRender; m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2)); + connect(m_render, SIGNAL(requestProxy(QString)), this, SLOT(slotCreateProxy(QString))); } void ProjectList::slotClipSelected() { - if (!m_listView->isEnabled()) return; - if (m_listView->currentItem()) { - if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) { + QTreeWidgetItem *item = m_listView->currentItem(); + ProjectItem *clip = NULL; + if (item) { + if (item->type() == PROJECTFOLDERTYPE) { emit clipSelected(NULL); - m_editButton->defaultAction()->setEnabled(m_listView->currentItem()->childCount() > 0); + m_editButton->defaultAction()->setEnabled(item->childCount() > 0); m_deleteButton->defaultAction()->setEnabled(true); m_openAction->setEnabled(false); m_reloadAction->setEnabled(false); + m_extractAudioAction->setEnabled(false); m_transcodeAction->setEnabled(false); - m_proxyAction->setEnabled(false); + m_clipsActionsMenu->setEnabled(false); } else { - ProjectItem *clip; - if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) { + if (item->type() == PROJECTSUBCLIPTYPE) { // this is a sub item, use base clip m_deleteButton->defaultAction()->setEnabled(true); - clip = static_cast (m_listView->currentItem()->parent()); + clip = static_cast (item->parent()); if (clip == NULL) kDebug() << "-----------ERROR"; - SubProjectItem *sub = static_cast (m_listView->currentItem()); + SubProjectItem *sub = static_cast (item); + if (clip->referencedClip()->getProducer() == NULL) m_render->getFileProperties(clip->referencedClip()->toXML(), clip->clipId(), m_listView->iconSize().height(), true); emit clipSelected(clip->referencedClip(), sub->zone()); + m_extractAudioAction->setEnabled(false); m_transcodeAction->setEnabled(false); + m_clipsActionsMenu->setEnabled(false); + m_reloadAction->setEnabled(false); + adjustProxyActions(clip); return; } - clip = static_cast (m_listView->currentItem()); + clip = static_cast (item); if (clip && clip->referencedClip()) emit clipSelected(clip->referencedClip()); + if (clip->referencedClip()->getProducer() == NULL) m_render->getFileProperties(clip->referencedClip()->toXML(), clip->clipId(), m_listView->iconSize().height(), true); m_editButton->defaultAction()->setEnabled(true); m_deleteButton->defaultAction()->setEnabled(true); m_reloadAction->setEnabled(true); + m_extractAudioAction->setEnabled(true); m_transcodeAction->setEnabled(true); + m_clipsActionsMenu->setEnabled(true); if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) { m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp())); m_openAction->setEnabled(true); @@ -614,6 +873,7 @@ void ProjectList::slotClipSelected() } // Display relevant transcoding actions only adjustTranscodeActions(clip); + adjustStabilizeActions(clip); // Display uses in timeline emit findInTimeline(clip->clipId()); } @@ -623,8 +883,11 @@ void ProjectList::slotClipSelected() m_deleteButton->defaultAction()->setEnabled(false); m_openAction->setEnabled(false); m_reloadAction->setEnabled(false); + m_extractAudioAction->setEnabled(true); m_transcodeAction->setEnabled(false); + m_clipsActionsMenu->setEnabled(false); } + adjustProxyActions(clip); } void ProjectList::adjustProxyActions(ProjectItem *clip) const @@ -633,19 +896,34 @@ void ProjectList::adjustProxyActions(ProjectItem *clip) const m_proxyAction->setEnabled(false); return; } - m_proxyAction->setEnabled(useProxy()); + bool enabled = useProxy(); + if (clip->referencedClip() && !clip->referencedClip()->getProperty("_missingsource").isEmpty()) enabled = false; + m_proxyAction->setEnabled(enabled); m_proxyAction->blockSignals(true); m_proxyAction->setChecked(clip->hasProxy()); m_proxyAction->blockSignals(false); } +void ProjectList::adjustStabilizeActions(ProjectItem *clip) const +{ + + if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == SLIDESHOW) { + m_clipsActionsMenu->setEnabled(false); + return; + } + m_clipsActionsMenu->setEnabled(true); + +} + void ProjectList::adjustTranscodeActions(ProjectItem *clip) const { if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW) { m_transcodeAction->setEnabled(false); + m_extractAudioAction->setEnabled(false); return; } m_transcodeAction->setEnabled(true); + m_extractAudioAction->setEnabled(true); QList transcodeActions = m_transcodeAction->actions(); QStringList data; QString condition; @@ -673,7 +951,7 @@ void ProjectList::slotUpdateClipProperties(const QString &id, QMap setProperties(properties); + if (properties.contains("proxy")) { + if (properties.value("proxy") == "-" || properties.value("proxy").isEmpty()) + // this should only apply to proxy jobs + clip->setConditionalJobStatus(NOJOB, PROXYJOB); + } if (properties.contains("name")) { monitorItemEditing(false); clip->setText(0, properties.value("name")); @@ -704,7 +987,7 @@ void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap setText(1, properties.value("description")); monitorItemEditing(true); -#ifdef NEPOMUK +#ifdef USE_NEPOMUK if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) { // Use Nepomuk system to store clip description Nepomuk::Resource f(clip->clipUrl().path()); @@ -732,6 +1015,7 @@ void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column) if (item->type() == PROJECTFOLDERTYPE) { if (column == 0) { FolderProjectItem *folder = static_cast (item); + if (item->text(0) == folder->groupName()) return; editFolder(item->text(0), folder->groupName(), folder->clipId()); folder->setGroupName(item->text(0)); m_doc->clipManager()->addFolder(folder->clipId(), item->text(0)); @@ -774,32 +1058,46 @@ void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column) emit projectModified(); EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false); m_commandStack->push(command); + QTimer::singleShot(100, this, SLOT(slotCheckScrolling())); } } } } +void ProjectList::slotCheckScrolling() +{ + m_listView->scrollToItem(m_listView->currentItem()); +} + void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item) { bool enable = item ? true : false; m_editButton->defaultAction()->setEnabled(enable); m_deleteButton->defaultAction()->setEnabled(enable); m_reloadAction->setEnabled(enable); + m_extractAudioAction->setEnabled(enable); m_transcodeAction->setEnabled(enable); + m_clipsActionsMenu->setEnabled(enable); if (enable) { ProjectItem *clip = NULL; if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) { clip = static_cast (item->parent()); + m_extractAudioAction->setEnabled(false); m_transcodeAction->setEnabled(false); + m_clipsActionsMenu->setEnabled(false); + adjustProxyActions(clip); } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) { clip = static_cast (item); // Display relevant transcoding actions only adjustTranscodeActions(clip); + adjustStabilizeActions(clip); adjustProxyActions(clip); // Display uses in timeline emit findInTimeline(clip->clipId()); } else { + m_extractAudioAction->setEnabled(false); m_transcodeAction->setEnabled(false); + m_clipsActionsMenu->setEnabled(false); } if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) { m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp())); @@ -848,7 +1146,7 @@ void ProjectList::slotRemoveClip() } else { ProjectItem *item = static_cast (selected.at(i)); ids << item->clipId(); - if (item->numReferences() > 0 && KMessageBox::questionYesNo(kapp->activeWindow(), i18np("Delete clip %2?
This will also remove the clip in timeline", "Delete clip %2?
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) { + if (item->numReferences() > 0 && KMessageBox::questionYesNo(kapp->activeWindow(), i18np("Delete clip %2?
This will also remove the clip in timeline", "Delete clip %2?
This will also remove its %1 clips in timeline", item->numReferences(), item->text(1)), i18n("Delete Clip"), KStandardGuiItem::yes(), KStandardGuiItem::no(), "DeleteAll") == KMessageBox::No) { KMessageBox::enableMessage("DeleteAll"); return; } @@ -877,7 +1175,7 @@ void ProjectList::updateButtons() const m_openAction->setEnabled(true); m_reloadAction->setEnabled(true); m_transcodeAction->setEnabled(true); - m_proxyAction->setEnabled(useProxy()); + m_clipsActionsMenu->setEnabled(true); return; } else if (item && item->type() == PROJECTFOLDERTYPE && item->childCount() > 0) { @@ -888,6 +1186,7 @@ void ProjectList::updateButtons() const m_openAction->setEnabled(false); m_reloadAction->setEnabled(false); m_transcodeAction->setEnabled(false); + m_clipsActionsMenu->setEnabled(false); m_proxyAction->setEnabled(false); } @@ -906,11 +1205,14 @@ void ProjectList::slotDeleteClip(const QString &clipId) kDebug() << "/// Cannot find clip to delete"; return; } + deleteJobsForClip(clipId); m_listView->blockSignals(true); QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item); if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item); delete item; + // Pause playing to prevent crash while deleting clip + slotPauseMonitor(); m_doc->clipManager()->deleteClip(clipId); m_listView->blockSignals(false); if (newSelectedItem) { @@ -929,9 +1231,9 @@ void ProjectList::editFolder(const QString folderName, const QString oldfolderNa m_doc->setModified(true); } -void ProjectList::slotAddFolder() +void ProjectList::slotAddFolder(const QString &name) { - AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true); + AddFolderCommand *command = new AddFolderCommand(this, name.isEmpty() ? i18n("Folder") : name, QString::number(m_doc->clipManager()->getFreeFolderId()), true); m_commandStack->push(command); } @@ -993,15 +1295,16 @@ void ProjectList::deleteProjectFolder(QMap map) void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties) { - m_listView->setEnabled(false); + //m_listView->setEnabled(false); const QString parent = clip->getProperty("groupid"); + QString groupName = clip->getProperty("groupname"); + QSize pixelSize((int)(m_listView->iconSize().height() * m_render->dar()), m_listView->iconSize().height()); ProjectItem *item = NULL; monitorItemEditing(false); if (!parent.isEmpty()) { FolderProjectItem *parentitem = getFolderItemById(parent); if (!parentitem) { QStringList text; - QString groupName = clip->getProperty("groupname"); //kDebug() << "Adding clip to new group: " << groupName; if (groupName.isEmpty()) groupName = i18n("Folder"); text << groupName; @@ -1009,49 +1312,57 @@ void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties) } if (parentitem) - item = new ProjectItem(parentitem, clip); + item = new ProjectItem(parentitem, clip, pixelSize); } if (item == NULL) { - item = new ProjectItem(m_listView, clip); + item = new ProjectItem(m_listView, clip, pixelSize); } if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading")); - connect(clip, SIGNAL(createProxy(const QString)), this, SLOT(slotCreateProxy(const QString))); - connect(clip, SIGNAL(abortProxy(const QString)), this, SLOT(slotAbortProxy(const QString))); + connect(clip, SIGNAL(createProxy(const QString &)), this, SLOT(slotCreateProxy(const QString &))); + connect(clip, SIGNAL(abortProxy(const QString &, const QString &)), this, SLOT(slotAbortProxy(const QString, const QString))); + if (getProperties) { + //item->setFlags(Qt::ItemIsSelectable); m_listView->processLayout(); QDomElement e = clip->toXML().cloneNode().toElement(); + if (!groupName.isEmpty()) { + e.setAttribute("groupId", parent); + e.setAttribute("group", groupName); + } e.removeAttribute("file_hash"); - m_infoQueue.insert(clip->getId(), e); + resetThumbsProducer(clip); + m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true); } - else if (item->hasProxy() && !item->isProxyRunning()) { + // WARNING: code below triggers unnecessary reload of all proxy clips on document loading... is it useful in some cases? + /*else if (item->hasProxy() && !item->isJobRunning()) { slotCreateProxy(clip->getId()); - } - clip->askForAudioThumbs(); + }*/ KUrl url = clip->fileURL(); - if (getProperties == false && !clip->getClipHash().isEmpty()) { - QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png"; - if (QFile::exists(cachedPixmap)) { - QPixmap pix(cachedPixmap); - if (pix.isNull()) - KIO::NetAccess::del(KUrl(cachedPixmap), this); - item->setData(0, Qt::DecorationRole, pix); - } - } -#ifdef NEPOMUK - if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) { +#ifdef USE_NEPOMUK + if (!url.isEmpty() && KdenliveSettings::activate_nepomuk() && clip->getProperty("description").isEmpty()) { // if file has Nepomuk comment, use it Nepomuk::Resource f(url.path()); QString annotation = f.description(); - if (!annotation.isEmpty()) item->setText(1, annotation); + if (!annotation.isEmpty()) { + item->setText(1, annotation); + clip->setProperty("description", annotation); + } item->setText(2, QString::number(f.rating())); } #endif + + // Add info to date column + QFileInfo fileInfo(url.path()); + if (fileInfo.exists()) { + item->setText(3, fileInfo.lastModified().toString(QString("yyyy/MM/dd hh:mm:ss"))); + } + // Add cut zones QList cuts = clip->cutZones(); if (!cuts.isEmpty()) { for (int i = 0; i < cuts.count(); i++) { - SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description); + SubProjectItem *sub = new SubProjectItem(m_render->dar(), item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description); if (!clip->getClipHash().isEmpty()) { QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png"; if (QFile::exists(cachedPixmap)) { @@ -1064,89 +1375,165 @@ void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties) } } monitorItemEditing(true); - if (m_listView->isEnabled()) { - updateButtons(); + updateButtons(); +} + +void ProjectList::slotGotProxy(const QString &proxyPath) +{ + if (proxyPath.isEmpty() || m_abortAllJobs) return; + QTreeWidgetItemIterator it(m_listView); + ProjectItem *item; + + while (*it && !m_closing) { + if ((*it)->type() == PROJECTCLIPTYPE) { + item = static_cast (*it); + if (item->referencedClip()->getProperty("proxy") == proxyPath) + slotGotProxy(item); + } + ++it; } - - if (getProperties && m_processingClips.isEmpty()) - m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); } -void ProjectList::slotGotProxy(const QString &id) +void ProjectList::slotGotProxyForId(const QString id) { + if (m_closing) return; ProjectItem *item = getItemById(id); - if (item) { - // Proxy clip successfully created - QDomElement e = item->referencedClip()->toXML().cloneNode().toElement(); - //e.removeAttribute("file_hash"); + slotGotProxy(item); +} - // Make sure we get the correct producer length if it was adjusted in timeline - CLIPTYPE t = item->clipType(); - if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) { - int length = QString(item->referencedClip()->producerProperty("length")).toInt(); - if (length > 0 && !e.hasAttribute("length")) { - e.setAttribute("length", length); - } +void ProjectList::slotGotProxy(ProjectItem *item) +{ + if (item == NULL) return; + DocClipBase *clip = item->referencedClip(); + if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) { + // Clip is being reprocessed, abort + kDebug()<<"//// TRYING TO PROXY: "<clipId()<<", but it is busy"; + return; + } + + // Proxy clip successfully created + QDomElement e = clip->toXML().cloneNode().toElement(); + + // Make sure we get the correct producer length if it was adjusted in timeline + CLIPTYPE t = item->clipType(); + if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) { + int length = QString(clip->producerProperty("length")).toInt(); + if (length > 0 && !e.hasAttribute("length")) { + e.setAttribute("length", length); } - e.setAttribute("replace", 1); - m_infoQueue.insert(id, e); - if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); } + resetThumbsProducer(clip); + m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true); } void ProjectList::slotResetProjectList() { + m_listView->blockSignals(true); + m_abortAllJobs = true; + for (int i = 0; i < m_jobList.count(); i++) { + m_jobList.at(i)->setStatus(JOBABORTED); + } + m_closing = true; + m_jobThreads.waitForFinished(); + m_jobThreads.clearFutures(); + m_thumbnailQueue.clear(); + if (!m_jobList.isEmpty()) qDeleteAll(m_jobList); + m_jobList.clear(); m_listView->clear(); + m_listView->setEnabled(true); emit clipSelected(NULL); - m_thumbnailQueue.clear(); - m_infoQueue.clear(); m_refreshed = false; + m_allClipsProcessed = false; + m_abortAllJobs = false; + m_closing = false; + m_listView->blockSignals(false); } -void ProjectList::requestClipInfo(const QDomElement xml, const QString id) +void ProjectList::slotUpdateClip(const QString &id) { - m_infoQueue.insert(id, xml); - //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue())); + ProjectItem *item = getItemById(id); + monitorItemEditing(false); + if (item) item->setData(0, UsageRole, QString::number(item->numReferences())); + monitorItemEditing(true); } -void ProjectList::slotProcessNextClipInQueue() +void ProjectList::getCachedThumbnail(ProjectItem *item) { - if (m_infoQueue.isEmpty()) { - emit processNextThumbnail(); - return; + if (!item) return; + DocClipBase *clip = item->referencedClip(); + if (!clip) { + return; } - - QMap::const_iterator j = m_infoQueue.constBegin(); - if (j != m_infoQueue.constEnd()) { - QDomElement dom = j.value(); - const QString id = j.key(); - m_infoQueue.remove(id); - m_processingClips.append(id); - bool replace; - if (dom.hasAttribute("replace")) { - // Proxy action was enabled / disabled and we want to replace current producer - dom.removeAttribute("replace"); - replace = true; + QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png"; + if (QFile::exists(cachedPixmap)) { + QPixmap pix(cachedPixmap); + if (pix.isNull()) { + KIO::NetAccess::del(KUrl(cachedPixmap), this); + requestClipThumbnail(item->clipId()); } - else replace = false; - bool selectClip = !replace; - if (m_infoQueue.count() > 1) selectClip = false; - emit getFileProperties(dom, id, m_listView->iconSize().height(), replace, selectClip); + else { + QPixmap result = roundedPixmap(pix); + processThumbOverlays(item, result); + item->setPixmap(result); + } + } + else { + requestClipThumbnail(item->clipId()); } } -void ProjectList::slotUpdateClip(const QString &id) +QPixmap ProjectList::roundedPixmap(QImage img) { - ProjectItem *item = getItemById(id); - monitorItemEditing(false); - if (item) item->setData(0, UsageRole, QString::number(item->numReferences())); - monitorItemEditing(true); + QPixmap pix(img.width(), img.height()); + pix.fill(Qt::transparent); + QPainter p(&pix); + p.setRenderHint(QPainter::Antialiasing, true); + QPainterPath path; + path.addRoundedRect(0.5, 0.5, pix.width() - 1, pix.height() - 1, 2, 2); + p.setClipPath(path); + p.drawImage(0, 0, img); + p.end(); + return pix; } -void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged) +QPixmap ProjectList::roundedPixmap(QPixmap source) { - m_listView->setSortingEnabled(false); + QPixmap pix(source.width(), source.height()); + pix.fill(Qt::transparent); + QPainter p(&pix); + p.setRenderHint(QPainter::Antialiasing, true); + QPainterPath path; + path.addRoundedRect(0.5, 0.5, pix.width() - 1, pix.height() - 1, 2, 2); + p.setClipPath(path); + p.drawPixmap(0, 0, source); + p.end(); + return pix; +} + +void ProjectList::getCachedThumbnail(SubProjectItem *item) +{ + if (!item) return; + ProjectItem *parentItem = static_cast (item->parent()); + if (!parentItem) return; + DocClipBase *clip = parentItem->referencedClip(); + if (!clip) return; + int pos = item->zone().x(); + QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(pos) + ".png"; + if (QFile::exists(cachedPixmap)) { + QPixmap pix(cachedPixmap); + if (pix.isNull()) { + KIO::NetAccess::del(KUrl(cachedPixmap), this); + requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos)); + } + else item->setData(0, Qt::DecorationRole, pix); + } + else requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos)); +} +void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged, QStringList brokenClips) +{ + if (!m_allClipsProcessed) m_listView->setEnabled(false); + m_listView->setSortingEnabled(false); QTreeWidgetItemIterator it(m_listView); DocClipBase *clip; ProjectItem *item; @@ -1159,15 +1546,23 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged) QPainter p(&missingPixmap); p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6)); p.end(); - + + int max = m_doc->clipManager()->clipsCount(); + max = qMax(1, max); + int ct = 0; + while (*it) { + emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - ct++) / max)); if ((*it)->type() == PROJECTSUBCLIPTYPE) { // subitem SubProjectItem *sub = static_cast (*it); - if (displayRatioChanged || sub->data(0, Qt::DecorationRole).isNull()) { + if (displayRatioChanged) { item = static_cast ((*it)->parent()); requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x())); } + else if (sub->data(0, Qt::DecorationRole).isNull()) { + getCachedThumbnail(sub); + } ++it; continue; } else if ((*it)->type() == PROJECTFOLDERTYPE) { @@ -1177,34 +1572,56 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged) } else { item = static_cast (*it); clip = item->referencedClip(); - if (item->referencedClip()->producer() == NULL) { - if (clip->isPlaceHolder() == false) { + if (clip->getProducer() == NULL) { + bool replace = false; + if (brokenClips.contains(item->clipId())) { + // if this is a proxy clip, disable proxy + item->setConditionalJobStatus(NOJOB, PROXYJOB); + discardJobs(item->clipId(), PROXYJOB); + clip->setProperty("proxy", "-"); + replace = true; + } + if (clip->isPlaceHolder() == false && !hasPendingJob(item, PROXYJOB)) { QDomElement xml = clip->toXML(); + getCachedThumbnail(item); if (fpsChanged) { xml.removeAttribute("out"); xml.removeAttribute("file_hash"); xml.removeAttribute("proxy_out"); } - requestClipInfo(xml, clip->getId()); + if (!replace) replace = xml.attribute("_replaceproxy") == "1"; + xml.removeAttribute("_replaceproxy"); + if (replace) { + resetThumbsProducer(clip); + m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace); + } + else if (item->numReferences() > 0) { + // In some cases, like slowmotion clips, the producer is not loaded automatically be MLT + m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace); + } } - else { + else if (clip->isPlaceHolder()) { item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled); - if (item->data(0, Qt::DecorationRole).isNull()) { - item->setData(0, Qt::DecorationRole, missingPixmap); + if (!item->hasPixmap()) { + item->setPixmap(missingPixmap); } else { QPixmap pixmap = qVariantValue(item->data(0, Qt::DecorationRole)); QPainter p(&pixmap); p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6)); p.end(); - item->setData(0, Qt::DecorationRole, pixmap); + item->setPixmap(pixmap); } } - } else { - if (displayRatioChanged || item->data(0, Qt::DecorationRole).isNull()) + } else { + if (displayRatioChanged) { requestClipThumbnail(clip->getId()); + } + else if (!item->hasPixmap()) { + getCachedThumbnail(item); + } if (item->data(0, DurationRole).toString().isEmpty()) { - item->changeDuration(item->referencedClip()->producer()->get_playtime()); + item->changeDuration(clip->getProducer()->get_playtime()); } if (clip->isPlaceHolder()) { QPixmap pixmap = qVariantValue(item->data(0, Qt::DecorationRole)); @@ -1215,20 +1632,22 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged) QPainter p(&pixmap); p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6)); p.end(); - item->setData(0, Qt::DecorationRole, pixmap); + item->setPixmap(pixmap); + } + else if (clip->getProperty("_replaceproxy") == "1") { + clip->setProperty("_replaceproxy", QString()); + slotCreateProxy(clip->getId()); } } item->setData(0, UsageRole, QString::number(item->numReferences())); } - //qApp->processEvents(); ++it; } - if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); - if (m_listView->isEnabled()) - monitorItemEditing(true); m_listView->setSortingEnabled(true); - if (m_infoQueue.isEmpty()) { + m_allClipsProcessed = true; + if (m_render->processingItems() == 0) { + monitorItemEditing(true); slotProcessNextThumbnail(); } } @@ -1237,10 +1656,16 @@ void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged) QString ProjectList::getExtensions() { // Build list of mime types - QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain" - << "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" - << "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" - << "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"; + QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"; + + // Video mimes + mimeTypes << "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" << "video/3gpp" << "video/mp2t"; + + // Audio mimes + mimeTypes << "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" << "audio/ac3"; + + // Image mimes + mimeTypes << "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"; QString allExtensions; foreach(const QString & mimeType, mimeTypes) { @@ -1253,6 +1678,14 @@ QString ProjectList::getExtensions() return allExtensions.simplified(); } +void ProjectList::slotAddClip(const QString url, const QString &groupName, const QString &groupId) +{ + kDebug()<<"// Adding clip: "< list; + list.append(url); + slotAddClip(list, groupName, groupId); +} + void ProjectList::slotAddClip(const QList givenList, const QString &groupName, const QString &groupId) { if (!m_commandStack) @@ -1273,7 +1706,7 @@ void ProjectList::slotAddClip(const QList givenList, const QString &group l->addWidget(c); l->addStretch(5); f->setLayout(l); - KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f); + QPointer d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f); d->setOperationMode(KFileDialog::Opening); d->setMode(KFile::Files); if (d->exec() == QDialog::Accepted) { @@ -1299,11 +1732,18 @@ void ProjectList::slotAddClip(const QList givenList, const QString &group while (fileName.at(fileName.size() - 1).isDigit()) { fileName.chop(1); } - - m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()), - false, false, false, - m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0, - QString(), groupInfo.at(0), groupInfo.at(1)); + QMap properties; + properties.insert("name", fileName); + properties.insert("resource", pattern); + properties.insert("in", "0"); + QString duration = m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()); + properties.insert("out", QString::number(m_doc->getFramePos(duration) * count)); + properties.insert("ttl", QString::number(m_doc->getFramePos(duration))); + properties.insert("loop", QString::number(false)); + properties.insert("crop", QString::number(false)); + properties.insert("fade", QString::number(false)); + properties.insert("luma_duration", QString::number(m_doc->getFramePos(m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps())))))); + m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1)); return; } } @@ -1314,43 +1754,96 @@ void ProjectList::slotAddClip(const QList givenList, const QString &group for (int i = 0; i < givenList.count(); i++) list << givenList.at(i); } + QList foldersList; foreach(const KUrl & file, list) { // Check there is no folder here KMimeType::Ptr type = KMimeType::findByUrl(file); if (type->is("inode/directory")) { - // user dropped a folder + // user dropped a folder, import its files list.removeAll(file); + QDir dir(file.path()); + QStringList result = dir.entryList(QDir::Files); + KUrl::List folderFiles; + folderFiles << file; + foreach(const QString & path, result) { + KUrl newFile = file; + newFile.addPath(path); + folderFiles.append(newFile); + } + if (folderFiles.count() > 1) foldersList.append(folderFiles); } } - if (list.isEmpty()) - return; - - if (givenList.isEmpty()) { + if (givenList.isEmpty() && !list.isEmpty()) { QStringList groupInfo = getGroup(); - m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1)); - } else { - m_doc->slotAddClipList(list, groupName, groupId); + QMap data; + data.insert("group", groupInfo.at(0)); + data.insert("groupId", groupInfo.at(1)); + m_doc->slotAddClipList(list, data); + } else if (!list.isEmpty()) { + QMap data; + data.insert("group", groupName); + data.insert("groupId", groupId); + m_doc->slotAddClipList(list, data); + } + + if (!foldersList.isEmpty()) { + // create folders + for (int i = 0; i < foldersList.count(); i++) { + KUrl::List urls = foldersList.at(i); + KUrl folderUrl = urls.takeFirst(); + QString folderName = folderUrl.fileName(); + FolderProjectItem *folder = NULL; + if (!folderName.isEmpty()) { + folder = getFolderItemByName(folderName); + if (folder == NULL) { + slotAddFolder(folderName); + folder = getFolderItemByName(folderName); + } + } + if (folder) { + QMap data; + data.insert("group", folder->groupName()); + data.insert("groupId", folder->clipId()); + m_doc->slotAddClipList(urls, data); + } + else m_doc->slotAddClipList(urls); + } } } void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace) { ProjectItem *item = getItemById(id); - m_processingClips.removeAll(id); - if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); + m_thumbnailQueue.removeAll(id); if (item) { + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled); const QString path = item->referencedClip()->fileURL().path(); if (item->referencedClip()->isPlaceHolder()) replace = false; if (!path.isEmpty()) { + if (m_invalidClipDialog) { + m_invalidClipDialog->addClip(id, path); + return; + } + else { + if (replace) + m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"), i18n("Clip %1
is invalid, will be removed from project.", QString()), replace, kapp->activeWindow()); + else { + m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"), i18n("Clip %1
is missing or invalid. Remove it from project?", QString()), replace, kapp->activeWindow()); + } + m_invalidClipDialog->addClip(id, path); + int result = m_invalidClipDialog->exec(); + if (result == KDialog::Yes) replace = true; + } + } + if (m_invalidClipDialog) { if (replace) - KMessageBox::sorry(kapp->activeWindow(), i18n("Clip %1
is invalid, will be removed from project.", path)); - else if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("Clip %1
is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes) - replace = true; + emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap ()); + delete m_invalidClipDialog; + m_invalidClipDialog = NULL; } - if (replace) - emit deleteProjectClips(QStringList() << id, QMap ()); + } } @@ -1358,11 +1851,13 @@ void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError) { ProjectItem *item = getItemById(id); if (item) { + kDebug()<<"// Proxy for clip "<setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled); if (durationError) { kDebug() << "Proxy duration is wrong, try changing transcoding parameters."; - emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2); + emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2, ErrorMessage); } - item->setProxyStatus(PROXYCRASHED); + slotUpdateJobStatus(item, PROXYJOB, JOBCRASHED, i18n("Failed to create proxy for %1. check parameters", item->text(0)), "project_settings"); QString path = item->referencedClip()->getProperty("proxy"); KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/"); @@ -1370,9 +1865,16 @@ void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError) if (proxyFolder.isParentOf(KUrl(path))) { QFile::remove(path); } + if (item->referencedClip()->getProducer() == NULL) { + // Clip has no valid producer, request it + slotProxyCurrentItem(false, item); + } + else { + // refresh thumbs producer + item->referencedClip()->reloadThumbProducer(); + } } - m_processingClips.removeAll(id); - if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); + m_thumbnailQueue.removeAll(id); } void ProjectList::slotAddColorClip() @@ -1380,7 +1882,7 @@ void ProjectList::slotAddColorClip() if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK"; - QDialog *dia = new QDialog(this); + QPointer dia = new QDialog(this); Ui::ColorClip_UI dia_ui; dia_ui.setupUi(dia); dia->setWindowTitle(i18n("Color Clip")); @@ -1388,7 +1890,6 @@ void ProjectList::slotAddColorClip() TimecodeDisplay *t = new TimecodeDisplay(m_timecode); t->setValue(KdenliveSettings::color_duration()); - t->setTimeCodeFormat(false); dia_ui.clip_durationBox->addWidget(t); dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor()); @@ -1413,10 +1914,22 @@ void ProjectList::slotAddSlideshowClip() if (dia->exec() == QDialog::Accepted) { QStringList groupInfo = getGroup(); - m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(), - dia->loop(), dia->crop(), dia->fade(), - dia->lumaDuration(), dia->lumaFile(), dia->softness(), - dia->animation(), groupInfo.at(0), groupInfo.at(1)); + + QMap properties; + properties.insert("name", dia->clipName()); + properties.insert("resource", dia->selectedPath()); + properties.insert("in", "0"); + properties.insert("out", QString::number(m_doc->getFramePos(dia->clipDuration()) * dia->imageCount())); + properties.insert("ttl", QString::number(m_doc->getFramePos(dia->clipDuration()))); + properties.insert("loop", QString::number(dia->loop())); + properties.insert("crop", QString::number(dia->crop())); + properties.insert("fade", QString::number(dia->fade())); + properties.insert("luma_duration", dia->lumaDuration()); + properties.insert("luma_file", dia->lumaFile()); + properties.insert("softness", QString::number(dia->softness())); + properties.insert("animation", dia->animation()); + + m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1)); } delete dia; } @@ -1440,7 +1953,7 @@ void ProjectList::slotAddTitleTemplateClip() const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/"; QStringList templateFiles = QDir(path).entryList(filter, QDir::Files); - QDialog *dia = new QDialog(this); + QPointer dia = new QDialog(this); Ui::TemplateClip_UI dia_ui; dia_ui.setupUi(dia); for (int i = 0; i < templateFiles.size(); ++i) @@ -1481,18 +1994,26 @@ QStringList ProjectList::getGroup() const void ProjectList::setDocument(KdenliveDoc *doc) { m_listView->blockSignals(true); + m_abortAllJobs = true; + for (int i = 0; i < m_jobList.count(); i++) { + m_jobList.at(i)->setStatus(JOBABORTED); + } + m_closing = true; + m_jobThreads.waitForFinished(); + m_jobThreads.clearFutures(); + m_thumbnailQueue.clear(); m_listView->clear(); - m_processingClips.clear(); + m_listView->setSortingEnabled(false); emit clipSelected(NULL); - m_thumbnailQueue.clear(); - m_infoQueue.clear(); m_refreshed = false; + m_allClipsProcessed = false; m_fps = doc->fps(); m_timecode = doc->timecode(); m_commandStack = doc->commandStack(); m_doc = doc; - m_proxyList.clear(); + m_abortAllJobs = false; + m_closing = false; QMap flist = doc->clipManager()->documentFolderList(); QStringList openedFolders = doc->getExpandedFolders(); @@ -1504,6 +2025,11 @@ void ProjectList::setDocument(KdenliveDoc *doc) } QList list = doc->clipManager()->documentClipList(); + if (list.isEmpty()) { + // blank document + m_refreshed = true; + m_allClipsProcessed = true; + } for (int i = 0; i < list.count(); i++) slotAddClip(list.at(i), false); @@ -1512,7 +2038,27 @@ void ProjectList::setDocument(KdenliveDoc *doc) connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &))); connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &))); connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &))); - connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool)), this, SLOT(updateAllClips(bool, bool))); + connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool, QStringList)), this, SLOT(updateAllClips(bool, bool, QStringList))); + connect(m_doc->clipManager(), SIGNAL(thumbReady(const QString &, int, QImage)), this, SLOT(slotSetThumbnail(const QString &, int, QImage))); +} + +void ProjectList::slotSetThumbnail(const QString &id, int framePos, QImage img) +{ + QString fullid = id + '#' + QString::number(framePos); + ProjectItem *pItem = NULL; + QTreeWidgetItem *item = getAnyItemById(fullid); + if (item && item->parent()) pItem = static_cast (item->parent()); + if (!item && framePos == 0) pItem = getItemById(id); + if (!item && !pItem) return; + if (item) { + if (item->type() == PROJECTCLIPTYPE) static_cast(item)->setPixmap(QPixmap::fromImage(img)); + else item->setData(0, Qt::DecorationRole, QPixmap::fromImage(img)); + } + else if (pItem) pItem->setPixmap(QPixmap::fromImage(img)); + if (pItem) { + QString hash = pItem->getClipHash(); + if (!hash.isEmpty()) m_doc->cacheImage(hash + '#' + QString::number(framePos), img); + } } QList ProjectList::documentClipList() const @@ -1528,7 +2074,6 @@ QDomElement ProjectList::producersList() QDomDocument doc; QDomElement prods = doc.createElement("producerlist"); doc.appendChild(prods); - kDebug() << "//////////// PRO LIST BUILD PRDSLIST "; QTreeWidgetItemIterator it(m_listView); while (*it) { if ((*it)->type() != PROJECTCLIPTYPE) { @@ -1544,12 +2089,14 @@ QDomElement ProjectList::producersList() void ProjectList::slotCheckForEmptyQueue() { - if (!m_refreshed && m_processingClips.isEmpty() && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) { - m_refreshed = true; - emit loadingIsOver(); - emit displayMessage(QString(), -1); - m_listView->blockSignals(false); - m_listView->setEnabled(true); + if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) { + if (!m_refreshed && m_allClipsProcessed) { + m_refreshed = true; + m_listView->setEnabled(true); + slotClipSelected(); + QTimer::singleShot(500, this, SIGNAL(loadingIsOver())); + emit displayMessage(QString(), -1); + } updateButtons(); } else if (!m_refreshed) { QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue())); @@ -1560,22 +2107,28 @@ void ProjectList::slotCheckForEmptyQueue() void ProjectList::requestClipThumbnail(const QString id) { if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id); + slotProcessNextThumbnail(); +} + +void ProjectList::resetThumbsProducer(DocClipBase *clip) +{ + if (!clip) return; + clip->clearThumbProducer(); + QString id = clip->getId(); + m_thumbnailQueue.removeAll(id); } void ProjectList::slotProcessNextThumbnail() { - if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) { - slotCheckForEmptyQueue(); + if (m_render->processingItems() > 0) { return; } - if (!m_infoQueue.isEmpty()) { - //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail())); + if (m_thumbnailQueue.isEmpty()) { + slotCheckForEmptyQueue(); return; } - if (m_thumbnailQueue.count() > 1) { - int max = m_doc->clipManager()->clipsCount(); - emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max)); - } + int max = m_doc->clipManager()->clipsCount(); + emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max)); slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false); } @@ -1611,25 +2164,31 @@ void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update) slotProcessNextThumbnail(); return; } - QPixmap pix; + QImage img; int height = m_listView->iconSize().height(); - int width = (int)(height * m_render->dar()); - if (clip->clipType() == AUDIO) - pix = KIcon("audio-x-generic").pixmap(QSize(width, height)); - else if (clip->clipType() == IMAGE) - pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height)); - else - pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height); - - if (!pix.isNull()) { + int swidth = (int)(height * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5); + int dwidth = (int)(height * m_render->dar() + 0.5); + if (clip->clipType() == IMAGE) { + img = KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height); + } + else if (clip->clipType() != AUDIO) { + img = item->referencedClip()->extractImage(frame, dwidth, height); + } + if (!img.isNull()) { monitorItemEditing(false); - it->setData(0, Qt::DecorationRole, pix); + QPixmap pix = roundedPixmap(img); + processThumbOverlays(item, pix); + if (isSubItem) it->setData(0, Qt::DecorationRole, pix); + else item->setPixmap(pix); monitorItemEditing(true); - - if (!isSubItem) - m_doc->cachePixmap(item->getClipHash(), pix); - else - m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix); + + QString hash = item->getClipHash(); + if (!hash.isEmpty() && !img.isNull()) { + if (!isSubItem) + m_doc->cacheImage(hash, img); + else + m_doc->cacheImage(hash + '#' + QString::number(frame), img); + } } if (update) emit projectModified(); @@ -1637,46 +2196,127 @@ void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update) } } -void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace, bool selectClip) -{ +void ProjectList::extractMetadata(DocClipBase *clip) +{ + CLIPTYPE t = clip->clipType(); + if (t != AV && t != VIDEO) { + // Currently, we only use exiftool on video files + return; + } + QMap props = clip->properties(); + if (KdenliveSettings::use_exiftool() && !props.contains("exiftool")) { + QMap meta; + QString url = clip->fileURL().path(); + //Check for Canon THM file + url = url.section('.', 0, -2) + ".THM"; + if (QFile::exists(url)) { + // Read the exif metadata embeded in the THM file + QProcess p; + QStringList args; + args << "-g" << "-args" << url; + p.start("exiftool", args); + p.waitForFinished(); + QString res = p.readAllStandardOutput(); + QStringList list = res.split("\n"); + foreach(QString tagline, list) { + if (tagline.startsWith("-File") || tagline.startsWith("-ExifTool")) continue; + QString tag = tagline.section(':', 1).simplified(); + if (tag.startsWith("ImageWidth") || tag.startsWith("ImageHeight")) continue; + if (!tag.section('=', 0, 0).isEmpty() && !tag.section('=', 1).simplified().isEmpty()) + meta.insert(tag.section('=', 0, 0), tag.section('=', 1).simplified()); + } + } else { + QString codecid = props.value("videocodecid").simplified(); + if (codecid == "h264") { + QProcess p; + QStringList args; + args << "-g" << "-args" << clip->fileURL().encodedPathAndQuery(); + p.start("exiftool", args); + p.waitForFinished(); + QString res = p.readAllStandardOutput(); + QStringList list = res.split("\n"); + foreach(QString tagline, list) { + if (!tagline.startsWith("-H264")) continue; + QString tag = tagline.section(':', 1); + if (tag.startsWith("ImageWidth") || tag.startsWith("ImageHeight")) continue; + meta.insert(tag.section('=', 0, 0), tag.section('=', 1)); + } + } + } + clip->setProperty("exiftool", "1"); + if (!meta.isEmpty()) { + clip->setMetadata(meta, "ExifTool"); + //checkCamcorderFilters(clip, meta); + } + } + if (KdenliveSettings::use_magicLantern() && !props.contains("magiclantern")) { + QMap meta; + QString url = clip->fileURL().path(); + url = url.section('.', 0, -2) + ".LOG"; + if (QFile::exists(url)) { + QFile file(url); + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { + while (!file.atEnd()) { + QString line = file.readLine().simplified(); + if (line.startsWith('#') || line.isEmpty() || !line.contains(':')) continue; + if (line.startsWith("CSV data")) break; + meta.insert(line.section(':', 0, 0).simplified(), line.section(':', 1).simplified()); + } + } + } + + if (!meta.isEmpty()) + clip->setMetadata(meta, "Magic Lantern"); + clip->setProperty("magiclantern", "1"); + } +} + + +void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace) +{ + QMutexLocker lock(&m_processMutex); QString toReload; ProjectItem *item = getItemById(clipId); - if (!m_refreshed) { - // we are still finishing to load the document - selectClip = false; - } - m_processingClips.removeAll(clipId); - if (m_infoQueue.isEmpty() && m_processingClips.isEmpty()) m_listView->setEnabled(true); if (item && producer) { - //m_listView->blockSignals(true); monitorItemEditing(false); DocClipBase *clip = item->referencedClip(); - item->setProperties(properties, metadata); - if (clip->isPlaceHolder() && producer->is_valid()) { - clip->setValid(); + if (producer->is_valid()) { + if (clip->isPlaceHolder()) { + clip->setValid(); + toReload = clipId; + } item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled); - toReload = clipId; } + item->setProperties(properties, metadata); + clip->setProducer(producer, replace); + extractMetadata(clip); + m_render->processingDone(clipId); // Proxy stuff QString size = properties.value("frame_size"); - if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY); - if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY); - else if (useProxy() && !item->isProxyRunning()) { + if (!useProxy() && clip->getProperty("proxy").isEmpty()) { + item->setConditionalJobStatus(NOJOB, PROXYJOB); + discardJobs(clipId, PROXYJOB); + } + if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") { + item->setConditionalJobStatus(NOJOB, PROXYJOB); + discardJobs(clipId, PROXYJOB); + } + else if (useProxy() && !item->hasProxy() && !hasPendingJob(item, PROXYJOB)) { // proxy video and image clips int maxSize; CLIPTYPE t = item->clipType(); if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt(); else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt(); - if ((size.section('x', 0, 0).toInt() > maxSize || size.section('x', 1, 1).toInt() > maxSize) && (((t == AV || t == VIDEO || t == PLAYLIST) && generateProxy()) || (t == IMAGE && generateImageProxy()))) { + 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)) { if (clip->getProperty("proxy").isEmpty()) { KUrl proxyPath = m_doc->projectFolder(); proxyPath.addPath("proxy/"); - proxyPath.addPath(clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"))); + proxyPath.addPath(clip->getClipHash() + '.' + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"))); QMap newProps; - newProps.insert("proxy", proxyPath.path()); // insert required duration for proxy if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out")); + newProps.insert("proxy", proxyPath.path()); QMap oldProps = clip->properties(); oldProps.insert("proxy", QString()); EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true); @@ -1684,53 +2324,50 @@ void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Produce } } } - - clip->setProducer(producer, replace); - clip->askForAudioThumbs(); - if (!replace && item->data(0, Qt::DecorationRole).isNull()) - requestClipThumbnail(clipId); + + if (!replace && m_allClipsProcessed && !item->hasPixmap()) { + getCachedThumbnail(item); + } if (!toReload.isEmpty()) item->slotSetToolTip(); - - if (m_listView->isEnabled() && replace) { - // update clip in clip monitor - emit clipSelected(NULL); - emit clipSelected(clip); - //TODO: Make sure the line below has no side effect - toReload = clipId; - } - /*else { - // Check if duration changed. - emit receivedClipDuration(clipId); - delete producer; - }*/ - if (m_listView->isEnabled()) - monitorItemEditing(true); - /*if (item->icon(0).isNull()) { - requestClipThumbnail(clipId); - }*/ - } else kDebug() << "//////// COULD NOT FIND CLIP TO UPDATE PRPS..."; - if (selectClip && m_infoQueue.isEmpty()) { - if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) { - m_listView->setCurrentItem(item); - bool updatedProfile = false; - if (item->parent()) { - if (item->parent()->type() == PROJECTFOLDERTYPE) - static_cast (item->parent())->switchIcon(); - } else if (KdenliveSettings::checkfirstprojectclip() && m_listView->topLevelItemCount() == 1) { - // this is the first clip loaded in project, check if we want to adjust project settings to the clip - updatedProfile = adjustProjectProfileToItem(item); - } - if (updatedProfile == false) emit clipSelected(item->referencedClip()); } else { - int max = m_doc->clipManager()->clipsCount(); - emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max)); + kDebug() << "//////// COULD NOT FIND CLIP TO UPDATE PRPS..."; + m_render->processingDone(clipId); } + int queue = m_render->processingItems(); + if (queue == 0) { + monitorItemEditing(true); + if (item && m_thumbnailQueue.isEmpty()) { + if (!item->hasProxy() || m_render->activeClipId() == item->clipId()) + m_listView->setCurrentItem(item); + bool updatedProfile = false; + if (item->parent()) { + if (item->parent()->type() == PROJECTFOLDERTYPE) + static_cast (item->parent())->switchIcon(); + } else if (KdenliveSettings::checkfirstprojectclip() && m_listView->topLevelItemCount() == 1 && m_refreshed && m_allClipsProcessed) { + // this is the first clip loaded in project, check if we want to adjust project settings to the clip + updatedProfile = adjustProjectProfileToItem(item); + if (updatedProfile == false) { + emit clipSelected(item->referencedClip()); + } + } + if (updatedProfile == false) { + //emit clipSelected(item->referencedClip()); + } + } else { + int max = m_doc->clipManager()->clipsCount(); + if (max > 0) emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max)); + } + if (m_allClipsProcessed) emit processNextThumbnail(); } - if (!toReload.isEmpty()) - emit clipNeedsReload(toReload, true); - - if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); + if (!item) { + // no item for producer, delete it + delete producer; + return; + } + if (replace) toReload = clipId; + if (!toReload.isEmpty()) + emit clipNeedsReload(toReload); } bool ProjectList::adjustProjectProfileToItem(ProjectItem *item) @@ -1747,6 +2384,8 @@ bool ProjectList::adjustProjectProfileToItem(ProjectItem *item) QString size = item->referencedClip()->getProperty("frame_size"); int width = size.section('x', 0, 0).toInt(); int height = size.section('x', -1).toInt(); + // Fix some avchd clips tht report a wrong size (1920x1088) + if (height == 1088) height = 1080; double fps = item->referencedClip()->getProperty("fps").toDouble(); double par = item->referencedClip()->getProperty("aspect_ratio").toDouble(); if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) { @@ -1812,16 +2451,29 @@ bool ProjectList::generateImageProxy() const return m_doc->getDocumentProperty("generateimageproxy").toInt(); } -void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix) +void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img) +{ + ProjectItem *item = getItemById(clipId); + if (item && !img.isNull()) { + QPixmap pix = roundedPixmap(img); + processThumbOverlays(item, pix); + monitorItemEditing(false); + item->setPixmap(pix); + monitorItemEditing(true); + QString hash = item->getClipHash(); + if (!hash.isEmpty()) m_doc->cacheImage(hash, img); + } +} + +void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height) { + // For clips that have a generic icon (like audio clips...) ProjectItem *item = getItemById(clipId); + QPixmap pix = KIcon(name).pixmap(QSize(width, height)); if (item && !pix.isNull()) { monitorItemEditing(false); item->setData(0, Qt::DecorationRole, pix); monitorItemEditing(true); - m_doc->cachePixmap(item->getClipHash(), pix); - if (m_listView->isEnabled()) - m_listView->blockSignals(false); } } @@ -1878,6 +2530,19 @@ ProjectItem *ProjectList::getItemById(const QString &id) return NULL; } +FolderProjectItem *ProjectList::getFolderItemByName(const QString &name) +{ + FolderProjectItem *item = NULL; + QList hits = m_listView->findItems(name, Qt::MatchExactly, 0); + for (int i = 0; i < hits.count(); i++) { + if (hits.at(i)->type() == PROJECTFOLDERTYPE) { + item = static_cast(hits.at(i)); + break; + } + } + return item; +} + FolderProjectItem *ProjectList::getFolderItemById(const QString &id) { FolderProjectItem *item; @@ -1902,8 +2567,9 @@ void ProjectList::slotSelectClip(const QString &ix) m_editButton->defaultAction()->setEnabled(true); m_deleteButton->defaultAction()->setEnabled(true); m_reloadAction->setEnabled(true); + m_extractAudioAction->setEnabled(true); m_transcodeAction->setEnabled(true); - m_proxyAction->setEnabled(useProxy()); + m_clipsActionsMenu->setEnabled(true); if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) { m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp())); m_openAction->setEnabled(true); @@ -1959,6 +2625,34 @@ KUrl::List ProjectList::getConditionalUrls(const QString &condition) const return result; } +QStringList ProjectList::getConditionalIds(const QString &condition) const +{ + QStringList result; + ProjectItem *item; + QList list = m_listView->selectedItems(); + for (int i = 0; i < list.count(); i++) { + if (list.at(i)->type() == PROJECTFOLDERTYPE) + continue; + if (list.at(i)->type() == PROJECTSUBCLIPTYPE) { + // subitem + item = static_cast (list.at(i)->parent()); + } else { + item = static_cast (list.at(i)); + } + if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT) + continue; + DocClipBase *clip = item->referencedClip(); + if (!condition.isEmpty()) { + if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1))) + continue; + else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1))) + continue; + } + result.append(item->clipId()); + } + return result; +} + void ProjectList::regenerateTemplate(const QString &id) { ProjectItem *clip = getItemById(id); @@ -1969,7 +2663,7 @@ void ProjectList::regenerateTemplate(const QString &id) void ProjectList::regenerateTemplate(ProjectItem *clip) { //TODO: remove this unused method, only force_reload is necessary - clip->referencedClip()->producer()->set("force_reload", 1); + clip->referencedClip()->getProducer()->set("force_reload", 1); } QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString) @@ -2012,16 +2706,14 @@ void ProjectList::addClipCut(const QString &id, int in, int out, const QString d DocClipBase *base = clip->referencedClip(); base->addCutZone(in, out); monitorItemEditing(false); - SubProjectItem *sub = new SubProjectItem(clip, in, out, desc); + SubProjectItem *sub = new SubProjectItem(m_render->dar(), clip, in, out, desc); if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) { if (!clip->isExpanded()) clip->setExpanded(true); m_listView->scrollToItem(sub); m_listView->editItem(sub, 1); } - QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height() * m_render->dar()), sub->sizeHint(0).height() - 2); - sub->setData(0, Qt::DecorationRole, p); - m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p); + m_doc->clipManager()->slotRequestThumbs(QString('#' + id), QList () << in); monitorItemEditing(true); } emit projectModified(); @@ -2088,9 +2780,7 @@ void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const void ProjectList::slotForceProcessing(const QString &id) { - while (m_infoQueue.contains(id)) { - slotProcessNextClipInQueue(); - } + m_render->forceProcessing(id); } void ProjectList::slotAddOrUpdateSequence(const QString frameName) @@ -2116,12 +2806,21 @@ void ProjectList::slotAddOrUpdateSequence(const QString frameName) } else { // Create sequence QStringList groupInfo = getGroup(); - m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()), - false, false, false, - m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0, - QString(), groupInfo.at(0), groupInfo.at(1)); + QMap properties; + properties.insert("name", fileName); + properties.insert("resource", pattern); + properties.insert("in", "0"); + QString duration = m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()); + properties.insert("out", QString::number(m_doc->getFramePos(duration) * count)); + properties.insert("ttl", QString::number(m_doc->getFramePos(duration))); + properties.insert("loop", QString::number(false)); + properties.insert("crop", QString::number(false)); + properties.insert("fade", QString::number(false)); + properties.insert("luma_duration", m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps())))); + + m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1)); } - } else emit displayMessage(i18n("Sequence not found"), -2); + } else emit displayMessage(i18n("Sequence not found"), -2, ErrorMessage); } QMap ProjectList::getProxies() @@ -2149,203 +2848,300 @@ QMap ProjectList::getProxies() void ProjectList::slotCreateProxy(const QString id) { ProjectItem *item = getItemById(id); - if (!item || item->isProxyRunning() || item->referencedClip()->isPlaceHolder()) return; - setProxyStatus(id, PROXYWAITING); - if (m_abortProxyId.contains(id)) m_abortProxyId.removeAll(id); - QtConcurrent::run(this, &ProjectList::slotGenerateProxy, id); -} - -void ProjectList::slotAbortProxy(const QString id) -{ - if (m_proxyList.contains(id)) m_proxyList.removeAll(id); - ProjectItem *item = getItemById(id); - if (item) { - emit projectModified(); - if (item->isProxyReady()) slotGotProxy(id); - else if (item->isProxyRunning()) m_abortProxyId << id; - setProxyStatus(id, NOPROXY); + if (!item || hasPendingJob(item, PROXYJOB) || item->referencedClip()->isPlaceHolder()) return; + QString path = item->referencedClip()->getProperty("proxy"); + if (path.isEmpty()) { + slotUpdateJobStatus(item, PROXYJOB, JOBCRASHED, i18n("Failed to create proxy, empty path.")); + return; } + + if (QFileInfo(path).size() > 0) { + // Proxy already created + setJobStatus(item, PROXYJOB, JOBDONE); + slotGotProxy(path); + return; + } + QString sourcePath = item->clipUrl().path(); + if (item->clipType() == PLAYLIST) { + // Special case: playlists use the special 'consumer' producer to support resizing + sourcePath.prepend("consumer:"); + } + ProxyJob *job = new ProxyJob(item->clipType(), id, QStringList() << path << sourcePath << item->referencedClip()->producerProperty("_exif_orientation") << m_doc->getDocumentProperty("proxyparams").simplified() << QString::number(m_render->frameRenderWidth()) << QString::number(m_render->renderHeight())); + if (job->isExclusive() && hasPendingJob(item, job->jobType)) { + delete job; + return; + } + + m_jobList.append(job); + setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage()); + slotCheckJobProcess(); } -void ProjectList::slotGenerateProxy(const QString id) +void ProjectList::slotCutClipJob(const QString &id, QPoint zone) { - setProxyStatus(id, CREATINGPROXY); ProjectItem *item = getItemById(id); - if (item == NULL) return; - QString path = item->referencedClip()->getProperty("proxy"); - if (path.isEmpty()) { - setProxyStatus(id, PROXYCRASHED); + if (!item|| item->referencedClip()->isPlaceHolder()) return; + QString source = item->clipUrl().path(); + QString ext = source.section('.', -1); + QString dest = source.section('.', 0, -2) + '_' + QString::number(zone.x()) + '.' + ext; + + double clipFps = item->referencedClip()->getProperty("fps").toDouble(); + if (clipFps == 0) clipFps = m_fps; + // if clip and project have different frame rate, adjust in and out + int in = zone.x(); + int out = zone.y(); + in = GenTime(in, m_timecode.fps()).frames(clipFps); + out = GenTime(out, m_timecode.fps()).frames(clipFps); + int max = GenTime(item->clipMaxDuration(), m_timecode.fps()).frames(clipFps); + int duration = out - in + 1; + QString timeIn = Timecode::getStringTimecode(in, clipFps, true); + QString timeOut = Timecode::getStringTimecode(duration, clipFps, true); + + QPointer d = new QDialog(this); + Ui::CutJobDialog_UI ui; + ui.setupUi(d); + ui.extra_params->setVisible(false); + ui.add_clip->setChecked(KdenliveSettings::add_new_clip()); + ui.file_url->fileDialog()->setOperationMode(KFileDialog::Saving); + ui.extra_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5); + ui.file_url->setUrl(KUrl(dest)); + ui.button_more->setIcon(KIcon("configure")); + ui.extra_params->setPlainText("-acodec copy -vcodec copy"); + QString mess = i18n("Extracting %1 out of %2", timeOut, Timecode::getStringTimecode(max, clipFps, true)); + ui.info_label->setText(mess); + if (d->exec() != QDialog::Accepted) { + delete d; return; } + dest = ui.file_url->url().path(); + bool acceptPath = dest != source; + if (acceptPath && QFileInfo(dest).size() > 0) { + // destination file olready exists, overwrite? + acceptPath = false; + } + while (!acceptPath) { + // Do not allow to save over original clip + if (dest == source) ui.info_label->setText("" + i18n("You cannot overwrite original clip.") + "
" + mess); + else if (KMessageBox::questionYesNo(this, i18n("Overwrite file %1", dest)) == KMessageBox::Yes) break; + if (d->exec() != QDialog::Accepted) { + delete d; + return; + } + dest = ui.file_url->url().path(); + acceptPath = dest != source; + if (acceptPath && QFileInfo(dest).size() > 0) { + acceptPath = false; + } + } + QString extraParams = ui.extra_params->toPlainText().simplified(); + KdenliveSettings::setAdd_new_clip(ui.add_clip->isChecked()); + delete d; - if (QFile::exists(path)) { - setProxyStatus(id, PROXYDONE); - slotGotProxy(id); + QStringList jobParams; + jobParams << dest << item->clipUrl().path() << timeIn << timeOut << QString::number(duration) << QString::number(KdenliveSettings::add_new_clip()); + if (!extraParams.isEmpty()) jobParams << extraParams; + CutClipJob *job = new CutClipJob(item->clipType(), id, jobParams); + if (job->isExclusive() && hasPendingJob(item, job->jobType)) { + delete job; return; } + m_jobList.append(job); + setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage()); + + slotCheckJobProcess(); +} + +void ProjectList::slotTranscodeClipJob(const QString &condition, QString params, QString desc) +{ + QStringList existingFiles; + QStringList ids = getConditionalIds(condition); + QStringList destinations; + foreach(const QString &id, ids) { + ProjectItem *item = getItemById(id); + if (!item) continue; + QString newFile = params.section(' ', -1).replace("%1", item->clipUrl().path()); + destinations << newFile; + if (QFile::exists(newFile)) existingFiles << newFile; + } + if (!existingFiles.isEmpty()) { + if (KMessageBox::warningContinueCancelList(this, i18n("The transcoding job will overwrite the following files:"), existingFiles) == KMessageBox::Cancel) return; + } + + QDialog *d = new QDialog(this); + Ui::CutJobDialog_UI ui; + ui.setupUi(d); + d->setWindowTitle(i18n("Transcoding")); + ui.extra_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5); + if (ids.count() == 1) { + ui.file_url->setUrl(KUrl(destinations.first())); + } else { - emit projectModified(); - // Make sure proxy path is writable - QFile file(path); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - setProxyStatus(id, PROXYCRASHED); - return; + ui.destination_label->setVisible(false); + ui.file_url->setVisible(false); + } + ui.extra_params->setVisible(false); + d->adjustSize(); + ui.button_more->setIcon(KIcon("configure")); + ui.add_clip->setChecked(KdenliveSettings::add_new_clip()); + ui.extra_params->setPlainText(params.simplified().section(' ', 0, -2)); + QString mess = desc; + mess.append(' ' + i18np("(%1 clip)", "(%1 clips)", ids.count())); + ui.info_label->setText(mess); + if (d->exec() != QDialog::Accepted) { + delete d; + return; + } + params = ui.extra_params->toPlainText().simplified(); + KdenliveSettings::setAdd_new_clip(ui.add_clip->isChecked()); + int index = 0; + foreach(const QString &id, ids) { + ProjectItem *item = getItemById(id); + if (!item || !item->referencedClip()) continue; + QString src = item->clipUrl().path(); + QString dest; + if (ids.count() > 1) { + dest = destinations.at(index); + index++; + } + else dest = ui.file_url->url().path(); + QStringList jobParams; + jobParams << dest << src << QString() << QString(); + double clipFps = item->referencedClip()->getProperty("fps").toDouble(); + if (clipFps == 0) clipFps = m_fps; + int max = item->clipMaxDuration(); + QString duration = QString::number(max); + jobParams << duration; + jobParams << QString::number(KdenliveSettings::add_new_clip()); + jobParams << params; + CutClipJob *job = new CutClipJob(item->clipType(), id, jobParams); + if (job->isExclusive() && hasPendingJob(item, job->jobType)) { + delete job; + continue; } - file.close(); - QFile::remove(path); + m_jobList.append(job); + setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage()); } + delete d; + slotCheckJobProcess(); + +} - QString url = item->clipUrl().path(); - - // Special case: playlist clips (.mlt or .kdenlive project files) - if (item->clipType() == PLAYLIST) { - // change FFmpeg params to MLT format - QStringList parameters; - parameters << url; - parameters << "-consumer" << "avformat:" + path; - QStringList params = m_doc->getDocumentProperty("proxyparams").simplified().split('-', QString::SkipEmptyParts); - - foreach(QString s, params) { - s = s.simplified(); - if (s.count(' ') == 0) { - s.append("=1"); +void ProjectList::slotCheckJobProcess() +{ + if (!m_jobThreads.futures().isEmpty()) { + // Remove inactive threads + QList > futures = m_jobThreads.futures(); + m_jobThreads.clearFutures(); + for (int i = 0; i < futures.count(); i++) + if (!futures.at(i).isFinished()) { + m_jobThreads.addFuture(futures.at(i)); } - else s.replace(' ', '='); - parameters << s; + } + if (m_jobList.isEmpty()) return; + + m_jobMutex.lock(); + int count = 0; + for (int i = 0; i < m_jobList.count(); i++) { + if (m_jobList.at(i)->status() == JOBWORKING || m_jobList.at(i)->status() == JOBWAITING) + count ++; + else { + // remove finished jobs + AbstractClipJob *job = m_jobList.takeAt(i); + job->deleteLater(); + i--; } - - parameters.append(QString("real_time=-%1").arg(KdenliveSettings::mltthreads())); - - // currently, when rendering an xml file through melt, the display ration is lost, so we enforce it manualy - double display_ratio = KdenliveDoc::getDisplayRatio(url); - parameters << "aspect=" + QString::number(display_ratio); - - //kDebug()<<"TRANSCOD: "<isProxyRunning()) slotGotProxy(item); + item->setConditionalJobStatus(NOJOB, PROXYJOB); + discardJobs(id, PROXYJOB); +} + +void ProjectList::slotProcessJobs() +{ + while (!m_jobList.isEmpty() && !m_abortAllJobs) { + emit projectModified(); + AbstractClipJob *job = NULL; + int count = 0; + m_jobMutex.lock(); + for (int i = 0; i < m_jobList.count(); i++) { + if (m_jobList.at(i)->status() == JOBWAITING) { + if (job == NULL) { + m_jobList.at(i)->setStatus(JOBWORKING); + job = m_jobList.at(i); + } + count++; } - myProcess.waitForFinished(500); + else if (m_jobList.at(i)->status() == JOBWORKING) + count ++; } - myProcess.waitForFinished(); - if (result == -1) result = myProcess.exitStatus(); - if (result == 0) { - // proxy successfully created - setProxyStatus(id, PROXYDONE); - slotGotProxy(id); - } - else if (result == 1) { - // Proxy process crashed - QFile::remove(path); - setProxyStatus(id, PROXYCRASHED); - } + // Set jobs count + emit jobCount(count); + m_jobMutex.unlock(); - } - - if (item->clipType() == IMAGE) { - // Image proxy - QImage i(url); - if (i.isNull()) { - // Cannot load image - setProxyStatus(id, PROXYCRASHED); - return; + if (job == NULL) { + break; } - QImage proxy; - // Images are scaled to profile size. - //TODO: Make it be configurable? - if (i.width() > i.height()) proxy = i.scaledToWidth(m_render->frameRenderWidth()); - else proxy = i.scaledToHeight(m_render->renderHeight()); - int exif_orientation = QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt(); - if (exif_orientation > 1) { - // Rotate image according to exif data - QImage processed; - QMatrix matrix; - - switch ( exif_orientation ) { - case 2: - matrix.scale( -1, 1 ); - break; - case 3: - matrix.rotate( 180 ); - break; - case 4: - matrix.scale( 1, -1 ); - break; - case 5: - matrix.rotate( 270 ); - matrix.scale( -1, 1 ); - break; - case 6: - matrix.rotate( 90 ); - break; - case 7: - matrix.rotate( 90 ); - matrix.scale( -1, 1 ); - break; - case 8: - matrix.rotate( 270 ); - break; - } - processed = proxy.transformed( matrix ); - processed.save(path); - } - else proxy.save(path); - setProxyStatus(id, PROXYDONE); - slotGotProxy(id); - return; - } + QString destination = job->destination(); + // Check if the clip is still here + DocClipBase *currentClip = m_doc->clipManager()->getClipById(job->clipId()); + //ProjectItem *processingItem = getItemById(job->clipId()); + if (currentClip == NULL) { + job->setStatus(JOBDONE); + continue; + } + // Set clip status to started + emit processLog(job->clipId(), 0, job->jobType, job->statusMessage()); - QStringList parameters; - parameters << "-i" << url; - QString params = m_doc->getDocumentProperty("proxyparams").simplified(); - foreach(QString s, params.split(' ')) - parameters << s; - - // Make sure we don't block when proxy file already exists - parameters << "-y"; - parameters << path; - QProcess myProcess; - myProcess.start("ffmpeg", parameters); - myProcess.waitForStarted(); - int result = -1; - while (myProcess.state() != QProcess::NotRunning) { - // building proxy file - if (m_abortProxyId.contains(id)) { - myProcess.close(); - myProcess.waitForFinished(); - m_abortProxyId.removeAll(id); - QFile::remove(path); - setProxyStatus(id, NOPROXY); - result = -2; - + // Make sure destination path is writable + if (!destination.isEmpty()) { + QFile file(destination); + if (!file.open(QIODevice::WriteOnly)) { + emit updateJobStatus(job->clipId(), job->jobType, JOBCRASHED, i18n("Cannot write to path: %1", destination)); + job->setStatus(JOBCRASHED); + continue; + } + file.close(); + QFile::remove(destination); + } + connect(job, SIGNAL(jobProgress(QString, int, int)), this, SIGNAL(processLog(QString, int, int))); + connect(job, SIGNAL(cancelRunningJob(const QString, stringMap)), this, SIGNAL(cancelRunningJob(const QString, stringMap))); + + if (job->jobType == MLTJOB) { + MeltJob *jb = static_cast (job); + jb->setProducer(currentClip->getProducer(), currentClip->fileURL()); + if (jb->isProjectFilter()) + connect(job, SIGNAL(gotFilterJobResults(QString,int, int, stringMap,stringMap)), this, SLOT(slotGotFilterJobResults(QString,int, int,stringMap,stringMap))); + else + connect(job, SIGNAL(gotFilterJobResults(QString,int, int, stringMap,stringMap)), this, SIGNAL(gotFilterJobResults(QString,int, int,stringMap,stringMap))); + } + job->startJob(); + if (job->status() == JOBDONE) { + emit updateJobStatus(job->clipId(), job->jobType, JOBDONE); + //TODO: replace with more generic clip replacement framework + if (job->jobType == PROXYJOB) emit gotProxy(job->clipId()); + if (job->addClipToProject()) { + emit addClip(destination, QString(), QString()); + } + } else if (job->status() == JOBCRASHED || job->status() == JOBABORTED) { + emit updateJobStatus(job->clipId(), job->jobType, job->status(), job->errorMessage(), QString(), job->logDetails()); } - myProcess.waitForFinished(500); - } - myProcess.waitForFinished(); - if (result == -1) result = myProcess.exitStatus(); - if (result == 0) { - // proxy successfully created - setProxyStatus(id, PROXYDONE); - slotGotProxy(id); - } - else if (result == 1) { - // Proxy process crashed - QFile::remove(path); - setProxyStatus(id, PROXYCRASHED); } + // Thread finished, cleanup & update count + QTimer::singleShot(200, this, SIGNAL(checkJobProcess())); } + void ProjectList::updateProxyConfig() { ProjectItem *item; @@ -2365,15 +3161,15 @@ void ProjectList::updateProxyConfig() } CLIPTYPE t = item->clipType(); if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) { - if (generateProxy() && useProxy() && !item->isProxyRunning()) { + if (generateProxy() && useProxy() && !hasPendingJob(item, PROXYJOB)) { DocClipBase *clip = item->referencedClip(); if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) { if (clip->getProperty("proxy").isEmpty()) { // We need to insert empty proxy in old properties so that undo will work - QMap oldProps = clip->properties(); + QMap oldProps;// = clip->properties(); oldProps.insert("proxy", QString()); QMap newProps; - newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + "." + m_doc->getDocumentProperty("proxyextension")); + newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + '.' + m_doc->getDocumentProperty("proxyextension")); new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command); } } @@ -2382,10 +3178,9 @@ void ProjectList::updateProxyConfig() // remove proxy QMap newProps; newProps.insert("proxy", QString()); - newProps.insert("replace", "1"); // insert required duration for proxy newProps.insert("proxy_out", item->referencedClip()->producerProperty("out")); - new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command); + new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(newProps), newProps, true, command); } } else if (t == IMAGE && item->referencedClip() != NULL) { @@ -2407,7 +3202,6 @@ void ProjectList::updateProxyConfig() // remove proxy QMap newProps; newProps.insert("proxy", QString()); - newProps.insert("replace", "1"); new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command); } } @@ -2415,16 +3209,48 @@ void ProjectList::updateProxyConfig() } if (command->childCount() > 0) m_doc->commandStack()->push(command); else delete command; - if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); } -void ProjectList::slotProxyCurrentItem(bool doProxy) +void ProjectList::slotProcessLog(const QString id, int progress, int type, const QString message) { - QList list = m_listView->selectedItems(); + ProjectItem *item = getItemById(id); + setJobStatus(item, (JOBTYPE) type, JOBWORKING, progress, message); +} + +void ProjectList::slotProxyCurrentItem(bool doProxy, ProjectItem *itemToProxy) +{ + QList list; + if (itemToProxy == NULL) list = m_listView->selectedItems(); + else list << itemToProxy; + + // expand list (folders, subclips) to get real clips QTreeWidgetItem *listItem; + QList clipList; + for (int i = 0; i < list.count(); i++) { + listItem = list.at(i); + if (listItem->type() == PROJECTFOLDERTYPE) { + for (int j = 0; j < listItem->childCount(); j++) { + QTreeWidgetItem *sub = listItem->child(j); + if (sub->type() == PROJECTCLIPTYPE) { + ProjectItem *item = static_cast (sub); + if (!clipList.contains(item)) clipList.append(item); + } + } + } + else if (listItem->type() == PROJECTSUBCLIPTYPE) { + QTreeWidgetItem *sub = listItem->parent(); + ProjectItem *item = static_cast (sub); + if (!clipList.contains(item)) clipList.append(item); + } + else if (listItem->type() == PROJECTCLIPTYPE) { + ProjectItem *item = static_cast (listItem); + if (!clipList.contains(item)) clipList.append(item); + } + } + QUndoCommand *command = new QUndoCommand(); - if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", list.count())); - else command->setText(i18np("Remove proxy clip", "Remove proxy clips", list.count())); + if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", clipList.count())); + else command->setText(i18np("Remove proxy clip", "Remove proxy clips", clipList.count())); // Make sure the proxy folder exists QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/"; @@ -2433,50 +3259,92 @@ void ProjectList::slotProxyCurrentItem(bool doProxy) QMap newProps; QMap oldProps; if (!doProxy) newProps.insert("proxy", "-"); - for (int i = 0; i < list.count(); i++) { - listItem = list.at(i); - if (listItem->type() == PROJECTFOLDERTYPE) { - for (int j = 0; j < listItem->childCount(); j++) { - QTreeWidgetItem *sub = listItem->child(j); - if (!list.contains(sub)) list.append(sub); + for (int i = 0; i < clipList.count(); i++) { + ProjectItem *item = clipList.at(i); + CLIPTYPE t = item->clipType(); + if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) { + if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy() && item->referencedClip()->getProducer() != NULL)) continue; + DocClipBase *clip = item->referencedClip(); + if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) { + kDebug()<<"//// TRYING TO PROXY: "<clipId()<<", but it is busy"; + continue; } - } - if (listItem->type() == PROJECTCLIPTYPE) { - ProjectItem *item = static_cast (listItem); - CLIPTYPE t = item->clipType(); - if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) { - oldProps = item->referencedClip()->properties(); - if (doProxy) { - newProps.clear(); - QString path = proxydir + item->referencedClip()->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")); - newProps.insert("proxy", path); - // insert required duration for proxy - newProps.insert("proxy_out", item->referencedClip()->producerProperty("out")); - // We need to insert empty proxy so that undo will work - oldProps.insert("proxy", QString()); - } - new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command); + + //oldProps = clip->properties(); + if (doProxy) { + newProps.clear(); + QString path = proxydir + clip->getClipHash() + '.' + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")); + // insert required duration for proxy + newProps.insert("proxy_out", clip->producerProperty("out")); + newProps.insert("proxy", path); + // We need to insert empty proxy so that undo will work + //oldProps.insert("proxy", QString()); } + else if (item->referencedClip()->getProducer() == NULL) { + // Force clip reload + kDebug()<<"// CLIP HAD NULL PROD------------"; + newProps.insert("resource", item->referencedClip()->getProperty("resource")); + } + // We need to insert empty proxy so that undo will work + oldProps = clip->currentProperties(newProps); + if (doProxy) oldProps.insert("proxy", "-"); + new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command); } } if (command->childCount() > 0) { m_doc->commandStack()->push(command); } else delete command; - //if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue); } -void ProjectList::setProxyStatus(const QString id, PROXYSTATUS status) + +void ProjectList::slotDeleteProxy(const QString proxyPath) { - ProjectItem *item = getItemById(id); - setProxyStatus(item, status); + if (proxyPath.isEmpty()) return; + QUndoCommand *proxyCommand = new QUndoCommand(); + proxyCommand->setText(i18n("Remove Proxy")); + QTreeWidgetItemIterator it(m_listView); + ProjectItem *item; + while (*it) { + if ((*it)->type() == PROJECTCLIPTYPE) { + item = static_cast (*it); + if (item->referencedClip()->getProperty("proxy") == proxyPath) { + QMap props; + props.insert("proxy", QString()); + new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(props), props, true, proxyCommand); + + } + } + ++it; + } + if (proxyCommand->childCount() == 0) + delete proxyCommand; + else + m_commandStack->push(proxyCommand); + QFile::remove(proxyPath); } -void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status) +void ProjectList::setJobStatus(ProjectItem *item, JOBTYPE jobType, CLIPJOBSTATUS status, int progress, const QString &statusMessage) { - if (item == NULL) return; + if (item == NULL || (m_abortAllJobs && m_closing)) return; monitorItemEditing(false); - item->setProxyStatus(status); + item->setJobStatus(jobType, status, progress, statusMessage); + if (status == JOBCRASHED) { + DocClipBase *clip = item->referencedClip(); + if (!clip) { + kDebug()<<"// PROXY CRASHED"; + } + else if (clip->getProducer() == NULL && !clip->isPlaceHolder()) { + // disable proxy and fetch real clip + clip->setProperty("proxy", "-"); + QDomElement xml = clip->toXML(); + m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), true); + } + else { + // Disable proxy for this clip + clip->setProperty("proxy", "-"); + } + } monitorItemEditing(true); } @@ -2505,4 +3373,461 @@ QStringList ProjectList::expandedFolders() const return result; } +void ProjectList::processThumbOverlays(ProjectItem *item, QPixmap &pix) +{ + if (item->hasProxy()) { + QPainter p(&pix); + QColor c(220, 220, 10, 200); + QRect r(0, 0, 12, 12); + p.fillRect(r, c); + QFont font = p.font(); + font.setBold(true); + p.setFont(font); + p.setPen(Qt::black); + p.drawText(r, Qt::AlignCenter, i18nc("The first letter of Proxy, used as abbreviation", "P")); + } +} + +void ProjectList::slotCancelJobs() +{ + m_abortAllJobs = true; + for (int i = 0; i < m_jobList.count(); i++) { + m_jobList.at(i)->setStatus(JOBABORTED); + } + m_jobThreads.waitForFinished(); + m_jobThreads.clearFutures(); + QUndoCommand *command = new QUndoCommand(); + command->setText(i18np("Cancel job", "Cancel jobs", m_jobList.count())); + m_jobMutex.lock(); + for (int i = 0; i < m_jobList.count(); i++) { + DocClipBase *currentClip = m_doc->clipManager()->getClipById(m_jobList.at(i)->clipId()); + if (!currentClip) continue; + QMap newProps = m_jobList.at(i)->cancelProperties(); + if (newProps.isEmpty()) continue; + QMap oldProps = currentClip->currentProperties(newProps); + new EditClipCommand(this, m_jobList.at(i)->clipId(), oldProps, newProps, true, command); + } + m_jobMutex.unlock(); + if (command->childCount() > 0) { + m_doc->commandStack()->push(command); + } + else delete command; + if (!m_jobList.isEmpty()) qDeleteAll(m_jobList); + m_jobList.clear(); + m_abortAllJobs = false; + m_infoLabel->slotSetJobCount(0); +} + +void ProjectList::slotCancelRunningJob(const QString id, stringMap newProps) +{ + if (newProps.isEmpty() || m_closing) return; + DocClipBase *currentClip = m_doc->clipManager()->getClipById(id); + if (!currentClip) return; + QMap oldProps = currentClip->currentProperties(newProps); + if (newProps == oldProps) return; + QMapIterator i(oldProps); + EditClipCommand *command = new EditClipCommand(this, id, oldProps, newProps, true); + m_commandStack->push(command); +} + +bool ProjectList::hasPendingJob(ProjectItem *item, JOBTYPE type) +{ + if (!item || !item->referencedClip() || m_abortAllJobs) return false; + AbstractClipJob *job; + QMutexLocker lock(&m_jobMutex); + for (int i = 0; i < m_jobList.count(); i++) { + if (m_abortAllJobs) break; + job = m_jobList.at(i); + if (job->clipId() == item->clipId() && job->jobType == type && (job->status() == JOBWAITING || job->status() == JOBWORKING)) return true; + } + + return false; +} + +void ProjectList::deleteJobsForClip(const QString &clipId) +{ + QMutexLocker lock(&m_jobMutex); + for (int i = 0; i < m_jobList.count(); i++) { + if (m_jobList.at(i)->clipId() == clipId) { + m_jobList.at(i)->setStatus(JOBABORTED); + } + } +} + +void ProjectList::slotUpdateJobStatus(const QString id, int type, int status, const QString label, const QString actionName, const QString details) +{ + ProjectItem *item = getItemById(id); + if (!item) return; + slotUpdateJobStatus(item, type, status, label, actionName, details); + +} + +void ProjectList::slotUpdateJobStatus(ProjectItem *item, int type, int status, const QString &label, const QString &actionName, const QString details) +{ + item->setJobStatus((JOBTYPE) type, (CLIPJOBSTATUS) status); + if (status != JOBCRASHED) return; +#if KDE_IS_VERSION(4,7,0) + QList actions = m_infoMessage->actions(); + if (m_infoMessage->isHidden()) { + m_infoMessage->setText(label); + m_infoMessage->setWordWrap(m_infoMessage->text().length() > 35); + m_infoMessage->setMessageType(KMessageWidget::Warning); + } + + if (!actionName.isEmpty()) { + QAction *action = NULL; + QList< KActionCollection * > collections = KActionCollection::allCollections(); + for (int i = 0; i < collections.count(); i++) { + KActionCollection *coll = collections.at(i); + action = coll->action(actionName); + if (action) break; + } + if (action && !actions.contains(action)) m_infoMessage->addAction(action); + } + if (!details.isEmpty()) { + m_errorLog.append(details); + if (!actions.contains(m_logAction)) m_infoMessage->addAction(m_logAction); + } + m_infoMessage->animatedShow(); +#else + // warning for KDE < 4.7 + KPassivePopup *passivePop = new KPassivePopup( this ); + passivePop->setAutoDelete(true); + connect(passivePop, SIGNAL(clicked()), this, SLOT(slotClosePopup())); + m_errorLog.append(details); + KVBox *vb = new KVBox( passivePop ); + KHBox *vh1 = new KHBox( vb ); + KIcon icon("dialog-warning"); + QLabel *iconLabel = new QLabel(vh1); + iconLabel->setPixmap(icon.pixmap(m_listView->iconSize())); + (void) new QLabel( label, vh1); + KHBox *box = new KHBox( vb ); + QPushButton *but = new QPushButton( "Show log", box ); + connect(but, SIGNAL(clicked(bool)), this, SLOT(slotShowJobLog())); + + passivePop->setView( vb ); + passivePop->show(); + +#endif +} + +void ProjectList::slotShowJobLog() +{ + KDialog d(this); + d.setButtons(KDialog::Close); + QTextEdit t(&d); + for (int i = 0; i < m_errorLog.count(); i++) { + if (i > 0) t.insertHtml("


"); + t.insertPlainText(m_errorLog.at(i)); + } + t.setReadOnly(true); + d.setMainWidget(&t); + d.exec(); +} + +QStringList ProjectList::getPendingJobs(const QString &id) +{ + QStringList result; + QMutexLocker lock(&m_jobMutex); + for (int i = 0; i < m_jobList.count(); i++) { + if (m_jobList.at(i)->clipId() == id && (m_jobList.at(i)->status() == JOBWAITING || m_jobList.at(i)->status() == JOBWORKING)) { + // discard this job + result << m_jobList.at(i)->description; + } + } + return result; +} + +void ProjectList::discardJobs(const QString &id, JOBTYPE type) { + QMutexLocker lock(&m_jobMutex); + for (int i = 0; i < m_jobList.count(); i++) { + if (m_jobList.at(i)->clipId() == id && (m_jobList.at(i)->jobType == type || type == NOJOBTYPE)) { + // discard this job + m_jobList.at(i)->setStatus(JOBABORTED); + } + } +} + +void ProjectList::slotStartFilterJob(ItemInfo info, const QString&id, const QString&filterName, const QString&filterParams, const QString&consumer, const QString&consumerParams, const QMap &extraParams) +{ + ProjectItem *item = getItemById(id); + if (!item) return; + QStringList jobParams; + jobParams << QString::number(info.cropStart.frames(m_fps)) << QString::number((info.cropStart + info.cropDuration).frames(m_fps)); + jobParams << QString() << filterName << filterParams << consumer << consumerParams << QString::number(info.startPos.frames(m_fps)) << QString::number(info.track); + MeltJob *job = new MeltJob(item->clipType(), id, jobParams, extraParams); + if (job->isExclusive() && hasPendingJob(item, job->jobType)) { + delete job; + return; + } + job->description = i18n("Filter %1", extraParams.value("finalfilter")); + m_jobList.append(job); + setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage()); + slotCheckJobProcess(); +} + +void ProjectList::startClipFilterJob(const QString &filterName, const QString &condition) +{ + QStringList ids = getConditionalIds(condition); + QString destination; + ProjectItem *item = getItemById(ids.at(0)); + if (!item) { + emit displayMessage(i18n("Cannot find clip to process filter %1", filterName), -2, ErrorMessage); + return; + } + if (ids.count() == 1) { + destination = item->clipUrl().path(); + } + else { + destination = item->clipUrl().directory(); + } + if (filterName == "motion_est") { + // Show config dialog + QPointer d = new QDialog(this); + Ui::SceneCutDialog_UI ui; + ui.setupUi(d); + // Set up categories + for (int i = 0; i < 5; ++i) { + ui.marker_type->insertItem(i, i18n("Category %1", i)); + ui.marker_type->setItemData(i, CommentedTime::markerColor(i), Qt::DecorationRole); + } + ui.marker_type->setCurrentIndex(KdenliveSettings::default_marker_type()); + if (d->exec() != QDialog::Accepted) { + delete d; + return; + } + // Autosplit filter + QStringList jobParams; + // Producer params + jobParams << QString(); + // Filter params, use a smaller region of the image to speed up operation + // In fact, it's faster to rescale whole image than using part of it (bounding=\"25%x25%:15%x15\") + jobParams << filterName << "shot_change_list=0 denoise=0"; + // Consumer + jobParams << "null" << "all=1 terminate_on_pause=1 real_time=-1 rescale=nearest deinterlace_method=onefield top_field_first=-1"; + QMap extraParams; + extraParams.insert("key", "shot_change_list"); + extraParams.insert("projecttreefilter", "1"); + QString keyword("%count"); + extraParams.insert("resultmessage", i18n("Found %1 scenes.", keyword)); + extraParams.insert("resize_profile", "160"); + if (ui.store_data->isChecked()) { + // We want to save result as clip metadata + extraParams.insert("storedata", "1"); + } + if (ui.zone_only->isChecked()) { + // We want to analyze only clip zone + extraParams.insert("zoneonly", "1"); + } + if (ui.add_markers->isChecked()) { + // We want to create markers + extraParams.insert("addmarkers", QString::number(ui.marker_type->currentIndex())); + } + if (ui.cut_scenes->isChecked()) { + // We want to cut scenes + extraParams.insert("cutscenes", "1"); + } + delete d; + processClipJob(ids, QString(), false, jobParams, i18n("Auto split"), extraParams); + } + else { + QPointer d = new ClipStabilize(destination, ids.count(), filterName); + if (d->exec() == QDialog::Accepted) { + QMap extraParams; + extraParams.insert("producer_profile", "1"); + processClipJob(ids, d->destination(), d->autoAddClip(), d->params(), d->desc(), extraParams); + } + delete d; + } +} + +void ProjectList::processClipJob(QStringList ids, const QString&destination, bool autoAdd, QStringList jobParams, const QString &description, QMap extraParams) +{ + QStringList preParams; + // in and out + preParams << QString::number(0) << QString::number(-1); + // producer params + preParams << jobParams.takeFirst(); + // filter name + preParams << jobParams.takeFirst(); + // filter params + preParams << jobParams.takeFirst(); + // consumer + QString consumer = jobParams.takeFirst(); + + foreach(const QString&id, ids) { + ProjectItem *item = getItemById(id); + if (!item) continue; + QStringList jobArgs; + if (extraParams.contains("zoneonly")) { + // Analyse clip zone only, remove in / out and replace with zone + preParams.takeFirst(); + preParams.takeFirst(); + QPoint zone = item->referencedClip()->zone(); + jobArgs << QString::number(zone.x()) << QString::number(zone.y()); + } + jobArgs << preParams; + if (ids.count() == 1) { + jobArgs << consumer + ':' + destination; + } + else { + jobArgs << consumer + ':' + destination + item->clipUrl().fileName() + ".mlt"; + } + jobArgs << jobParams; + + MeltJob *job = new MeltJob(item->clipType(), id, jobArgs, extraParams); + if (autoAdd) { + job->setAddClipToProject(true); + kDebug()<<"// ADDING TRUE"; + } + else kDebug()<<"// ADDING FALSE!!!"; + + if (job->isExclusive() && hasPendingJob(item, job->jobType)) { + delete job; + return; + } + job->description = description; + m_jobList.append(job); + setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage()); + slotCheckJobProcess(); + } +} + + +void ProjectList::slotPrepareJobsMenu() +{ + ProjectItem *item; + if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) + return; + if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) + item = static_cast (m_listView->currentItem()->parent()); + else + item = static_cast (m_listView->currentItem()); + if (item && (item->flags() & Qt::ItemIsDragEnabled)) { + QString id = item->clipId(); + m_discardCurrentClipJobs->setData(id); + QStringList jobs = getPendingJobs(id); + m_discardCurrentClipJobs->setEnabled(!jobs.isEmpty()); + } else { + m_discardCurrentClipJobs->setData(QString()); + m_discardCurrentClipJobs->setEnabled(false); + } +} + +void ProjectList::slotDiscardClipJobs() +{ + QString id = m_discardCurrentClipJobs->data().toString(); + if (id.isEmpty()) return; + discardJobs(id); +} + +void ProjectList::updatePalette() +{ + m_infoLabel->setStyleSheet(SmallInfoLabel::getStyleSheet(QApplication::palette())); + m_listView->updateStyleSheet(); +} + +void ProjectList::slotResetInfoMessage() +{ +#if KDE_IS_VERSION(4,7,0) + m_errorLog.clear(); + QList actions = m_infoMessage->actions(); + for (int i = 0; i < actions.count(); i++) { + m_infoMessage->removeAction(actions.at(i)); + } +#endif +} + +void ProjectList::slotClosePopup() +{ + m_errorLog.clear(); +} + +void ProjectList::slotGotFilterJobResults(QString id, int , int , stringMap results, stringMap filterInfo) +{ + // Currently, only the first value of results is used + //kDebug()<<"// FILTER RES:\n"<setText(i18n("Auto Split Clip")); + foreach (QString pos, value) { + if (!pos.contains("=")) continue; + int newPos = pos.section("=", 0, 0).toInt(); + // Don't use scenes shorter than 1 second + if (newPos - cutPos < 24) continue; + (void) new AddClipCutCommand(this, id, cutPos + offset, newPos + offset, QString(), true, false, command); + cutPos = newPos; + } + if (command->childCount() == 0) + delete command; + else m_commandStack->push(command); + } + if (markersType >= 0) { + // Add markers from returned data + dataProcessed = true; + int cutPos = 0; + QUndoCommand *command = new QUndoCommand(); + command->setText(i18n("Add Markers")); + QList markersList; + int index = 1; + foreach (QString pos, value) { + if (!pos.contains("=")) continue; + int newPos = pos.section("=", 0, 0).toInt(); + // Don't use scenes shorter than 1 second + if (newPos - cutPos < 24) continue; + CommentedTime m(GenTime(newPos + offset, m_fps), QString::number(index), markersType); + markersList << m; + index++; + cutPos = newPos; + } + emit addMarkers(id, markersList); + } + if (!dataProcessed || filterInfo.contains("storedata")) { + // Store returned data as clip extra data + clip->referencedClip()->setAnalysisData(filterInfo.contains("displaydataname") ? filterInfo.value("displaydataname") : key, results.value(key), filterInfo.value("offset").toInt()); + emit updateAnalysisData(clip->referencedClip()); + } +} + + +/* +// Work in progress: apply filter based on clip's camcorder +void ProjectList::checkCamcorderFilters(DocClipBase *clip, QMap meta) +{ + KConfig conf("camcorderfilters.rc", KConfig::CascadeConfig, "appdata"); + QStringList groups = conf.groupList(); + foreach(QString grp, groups) { + if (!meta.contains(grp)) continue; + KConfigGroup group(&conf, grp); + QString value = group.readEntry(meta.value(grp)); + if (value.isEmpty()) continue; + clip->setProperty(value.section(' ', 0, 0), value.section(' ', 1)); + break; + } +}*/ + #include "projectlist.moc"