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