]> git.sesse.net Git - kdenlive/blob - src/renderwidget.cpp
Add mlt and encoder threads to render dialog.
[kdenlive] / src / renderwidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2008 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
21 #include "renderwidget.h"
22 #include "kdenlivesettings.h"
23 #include "ui_saveprofile_ui.h"
24 #include "timecode.h"
25
26 #include <KStandardDirs>
27 #include <KDebug>
28 #include <KMessageBox>
29 #include <KComboBox>
30 #include <KRun>
31 #include <KIO/NetAccess>
32 #include <KColorScheme>
33 #include <KNotification>
34 #include <KStartupInfo>
35
36 #include <QDomDocument>
37 #include <QItemDelegate>
38 #include <QTreeWidgetItem>
39 #include <QListWidgetItem>
40 #include <QHeaderView>
41 #include <QMenu>
42 #include <QInputDialog>
43 #include <QProcess>
44 #include <QDBusConnectionInterface>
45 #include <QDBusInterface>
46 #include <QThread>
47
48 const int GroupRole = Qt::UserRole;
49 const int ExtensionRole = GroupRole + 1;
50 const int StandardRole = GroupRole + 2;
51 const int RenderRole = GroupRole + 3;
52 const int ParamsRole = GroupRole + 4;
53 const int EditableRole = GroupRole + 5;
54 const int MetaGroupRole = GroupRole + 6;
55 const int ExtraRole = GroupRole + 7;
56
57 // Running job status
58 const int WAITINGJOB = 0;
59 const int RUNNINGJOB = 1;
60 const int FINISHEDJOB = 2;
61
62
63 RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, QWidget * parent) :
64         QDialog(parent),
65         m_projectFolder(projectfolder),
66         m_blockProcessing(false)
67 {
68     m_view.setupUi(this);
69     setWindowTitle(i18n("Rendering"));
70     m_view.buttonDelete->setIcon(KIcon("trash-empty"));
71     m_view.buttonDelete->setToolTip(i18n("Delete profile"));
72     m_view.buttonDelete->setEnabled(false);
73
74     m_view.buttonEdit->setIcon(KIcon("document-properties"));
75     m_view.buttonEdit->setToolTip(i18n("Edit profile"));
76     m_view.buttonEdit->setEnabled(false);
77
78     m_view.buttonSave->setIcon(KIcon("document-new"));
79     m_view.buttonSave->setToolTip(i18n("Create new profile"));
80
81     m_view.buttonInfo->setIcon(KIcon("help-about"));
82     m_view.hide_log->setIcon(KIcon("go-down"));
83
84     m_view.buttonFavorite->setIcon(KIcon("favorites"));
85     m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
86
87     if (KdenliveSettings::showrenderparams()) {
88         m_view.buttonInfo->setDown(true);
89     } else m_view.advanced_params->hide();
90     
91     m_view.proxy_render->setHidden(!enableProxy);
92
93         m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
94         m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
95         connect(m_view.encoder_threads, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateEncodeThreads(int)));
96         
97     m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
98     connect(m_view.rescale_width, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleWidth(int)));
99     connect(m_view.rescale_height, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleHeight(int)));
100     m_view.rescale_keep->setIcon(KIcon("insert-link"));
101     m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
102     connect(m_view.rescale_keep, SIGNAL(clicked()), this, SLOT(slotSwitchAspectRatio()));
103
104     connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
105     connect(m_view.buttonGenerateScript, SIGNAL(clicked()), this, SLOT(slotGenerateScript()));
106
107     m_view.abort_job->setEnabled(false);
108     m_view.start_script->setEnabled(false);
109     m_view.delete_script->setEnabled(false);
110
111     m_view.format_list->setAlternatingRowColors(true);
112     m_view.size_list->setAlternatingRowColors(true);
113
114     KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
115     QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
116     m_view.errorBox->setStyleSheet(QString("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
117     int height = QFontInfo(font()).pixelSize();
118     m_view.errorIcon->setPixmap(KIcon("dialog-warning").pixmap(height, height));
119     m_view.errorBox->setHidden(true);
120
121     connect(m_view.export_audio, SIGNAL(stateChanged(int)), this, SLOT(slotUpdateAudioLabel(int)));
122     m_view.export_audio->setCheckState(Qt::PartiallyChecked);
123
124     parseProfiles();
125     parseScriptFiles();
126     m_view.running_jobs->setUniformRowHeights(false);
127     m_view.scripts_list->setUniformRowHeights(false);
128     connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
129     connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
130     connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
131     connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
132     connect(m_view.running_jobs, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(slotPlayRendering(QTreeWidgetItem *, int)));
133
134     connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));
135
136     connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
137     connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
138     connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
139     connect(m_view.buttonFavorite, SIGNAL(clicked()), this, SLOT(slotCopyToFavorites()));
140
141     connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
142     connect(m_view.start_job, SIGNAL(clicked()), this, SLOT(slotStartCurrentJob()));
143     connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
144     connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));
145
146     connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
147     connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
148     connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
149     connect(m_view.rescale, SIGNAL(toggled(bool)), m_view.rescale_box, SLOT(setEnabled(bool)));
150     connect(m_view.destination_list, SIGNAL(activated(int)), this, SLOT(refreshCategory()));
151     connect(m_view.out_file, SIGNAL(textChanged(const QString &)), this, SLOT(slotUpdateButtons()));
152     connect(m_view.out_file, SIGNAL(urlSelected(const KUrl &)), this, SLOT(slotUpdateButtons(const KUrl &)));
153     connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
154     connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
155
156     connect(m_view.size_list, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotEditItem(QListWidgetItem *)));
157
158     connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
159     connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
160     connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
161
162     connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
163     connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));
164
165     connect(m_view.format_selection, SIGNAL(activated(int)), this, SLOT(refreshView()));
166
167     m_view.buttonRender->setEnabled(false);
168     m_view.buttonGenerateScript->setEnabled(false);
169     m_view.rescale_box->setEnabled(false);
170     m_view.guides_box->setVisible(false);
171     m_view.open_dvd->setVisible(false);
172     m_view.create_chapter->setVisible(false);
173     m_view.open_browser->setVisible(false);
174     m_view.error_box->setVisible(false);
175
176     m_view.splitter->setStretchFactor(1, 5);
177     m_view.splitter->setStretchFactor(0, 2);
178
179     m_view.out_file->setMode(KFile::File);
180
181     m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File") << i18n("Progress"));
182     m_jobsDelegate = new RenderViewDelegate(this);
183     m_view.running_jobs->setItemDelegate(m_jobsDelegate);
184
185     QHeaderView *header = m_view.running_jobs->header();
186     header->setResizeMode(0, QHeaderView::Fixed);
187     header->resizeSection(0, 30);
188     header->setResizeMode(1, QHeaderView::Interactive);
189     header->setResizeMode(2, QHeaderView::Fixed);
190     header->resizeSection(1, width() * 2 / 3 - 15);
191     header->setResizeMode(2, QHeaderView::Interactive);
192     //header->setResizeMode(1, QHeaderView::Fixed);
193
194
195     m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
196     m_scriptsDelegate = new RenderViewDelegate(this);
197     m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
198     header = m_view.scripts_list->header();
199     header->setResizeMode(0, QHeaderView::Fixed);
200     header->resizeSection(0, 30);
201
202     // Find path for Kdenlive renderer
203     m_renderer = QCoreApplication::applicationDirPath() + QString("/kdenlive_render");
204     if (!QFile::exists(m_renderer)) {
205         m_renderer = KStandardDirs::findExe("kdenlive_render");
206         if (m_renderer.isEmpty()) m_renderer = KStandardDirs::locate("exe", "kdenlive_render");
207         if (m_renderer.isEmpty()) m_renderer = "kdenlive_render";
208     }
209
210     QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
211     if (!interface || (!interface->isServiceRegistered("org.kde.ksmserver") && !interface->isServiceRegistered("org.gnome.SessionManager")))
212         m_view.shutdown->setEnabled(false);
213
214     focusFirstVisibleItem();
215 }
216
217 RenderWidget::~RenderWidget()
218 {
219     m_view.running_jobs->blockSignals(true);
220     m_view.scripts_list->blockSignals(true);
221     m_view.running_jobs->clear();
222     m_view.scripts_list->clear();
223     delete m_jobsDelegate;
224     delete m_scriptsDelegate;
225 }
226
227 void RenderWidget::slotEditItem(QListWidgetItem *item)
228 {
229     QString edit = item->data(EditableRole).toString();
230     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) slotSaveProfile();
231     else slotEditProfile();
232 }
233
234 void RenderWidget::showInfoPanel()
235 {
236     if (m_view.advanced_params->isVisible()) {
237         m_view.advanced_params->setVisible(false);
238         m_view.buttonInfo->setDown(false);
239         KdenliveSettings::setShowrenderparams(false);
240     } else {
241         m_view.advanced_params->setVisible(true);
242         m_view.buttonInfo->setDown(true);
243         KdenliveSettings::setShowrenderparams(true);
244     }
245 }
246
247 void RenderWidget::setDocumentPath(const QString path)
248 {
249     if (m_view.out_file->url().directory() == KUrl(m_projectFolder).directory()) {
250         const QString fileName = m_view.out_file->url().fileName();
251         m_view.out_file->setUrl(KUrl(path + fileName));
252     }
253     m_projectFolder = path;
254     parseScriptFiles();
255
256 }
257
258 void RenderWidget::slotUpdateGuideBox()
259 {
260     m_view.guides_box->setVisible(m_view.render_guide->isChecked());
261 }
262
263 void RenderWidget::slotCheckStartGuidePosition()
264 {
265     if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
266         m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
267 }
268
269 void RenderWidget::slotCheckEndGuidePosition()
270 {
271     if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
272         m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
273 }
274
275 void RenderWidget::setGuides(QDomElement guidesxml, double duration)
276 {
277     m_view.guide_start->clear();
278     m_view.guide_end->clear();
279     QDomNodeList nodes = guidesxml.elementsByTagName("guide");
280     if (nodes.count() > 0) {
281         m_view.guide_start->addItem(i18n("Beginning"), "0");
282         m_view.render_guide->setEnabled(true);
283         m_view.create_chapter->setEnabled(true);
284     } else {
285         m_view.render_guide->setEnabled(false);
286         m_view.create_chapter->setEnabled(false);
287     }
288     double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
289     for (int i = 0; i < nodes.count(); i++) {
290         QDomElement e = nodes.item(i).toElement();
291         if (!e.isNull()) {
292             GenTime pos = GenTime(e.attribute("time").toDouble());
293             const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
294             m_view.guide_start->addItem(e.attribute("comment") + '/' + guidePos, e.attribute("time").toDouble());
295             m_view.guide_end->addItem(e.attribute("comment") + '/' + guidePos, e.attribute("time").toDouble());
296         }
297     }
298     if (nodes.count() > 0)
299         m_view.guide_end->addItem(i18n("End"), QString::number(duration));
300 }
301
302 /**
303  * Will be called when the user selects an output file via the file dialog.
304  * File extension will be added automatically.
305  */
306 void RenderWidget::slotUpdateButtons(KUrl url)
307 {
308     if (m_view.out_file->url().isEmpty()) {
309         m_view.buttonGenerateScript->setEnabled(false);
310         m_view.buttonRender->setEnabled(false);
311     } else {
312         updateButtons(); // This also checks whether the selected format is available
313     }
314     if (url != 0) {
315         QListWidgetItem *item = m_view.size_list->currentItem();
316         if (!item) {
317             m_view.buttonRender->setEnabled(false);
318             m_view.buttonGenerateScript->setEnabled(false);
319             return;
320         }
321         QString extension = item->data(ExtensionRole).toString();
322         url = filenameWithExtension(url, extension);
323         m_view.out_file->setUrl(url);
324     }
325 }
326
327 /**
328  * Will be called when the user changes the output file path in the text line.
329  * File extension must NOT be added, would make editing impossible!
330  */
331 void RenderWidget::slotUpdateButtons()
332 {
333     if (m_view.out_file->url().isEmpty()) {
334         m_view.buttonRender->setEnabled(false);
335         m_view.buttonGenerateScript->setEnabled(false);
336     } else {
337         updateButtons(); // This also checks whether the selected format is available
338     }
339 }
340
341 void RenderWidget::slotSaveProfile()
342 {
343     //TODO: update to correctly use metagroups
344     Ui::SaveProfile_UI ui;
345     QDialog *d = new QDialog(this);
346     ui.setupUi(d);
347
348     for (int i = 0; i < m_view.destination_list->count(); i++)
349         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
350
351     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
352     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
353
354     QString customGroup = m_view.format_list->currentItem()->text();
355     if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
356     ui.group_name->setText(customGroup);
357
358     ui.parameters->setText(m_view.advanced_params->toPlainText());
359     ui.extension->setText(m_view.size_list->currentItem()->data(ExtensionRole).toString());
360     ui.profile_name->setFocus();
361
362     if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
363         QString newProfileName = ui.profile_name->text().simplified();
364         QString newGroupName = ui.group_name->text().simplified();
365         if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
366         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
367
368         QDomDocument doc;
369         QDomElement profileElement = doc.createElement("profile");
370         profileElement.setAttribute("name", newProfileName);
371         profileElement.setAttribute("category", newGroupName);
372         profileElement.setAttribute("destinationid", newMetaGroupId);
373         profileElement.setAttribute("extension", ui.extension->text().simplified());
374         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
375         doc.appendChild(profileElement);
376         saveProfile(doc.documentElement());
377
378         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
379     }
380     delete d;
381 }
382
383
384 void RenderWidget::saveProfile(QDomElement newprofile)
385 {
386     QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
387     QDomDocument doc;
388     QFile file(exportFile);
389     doc.setContent(&file, false);
390     file.close();
391     QDomElement documentElement;
392     QDomElement profiles = doc.documentElement();
393     if (profiles.isNull() || profiles.tagName() != "profiles") {
394         doc.clear();
395         profiles = doc.createElement("profiles");
396         profiles.setAttribute("version", 1);
397         doc.appendChild(profiles);
398     }
399     int version = profiles.attribute("version", 0).toInt();
400     if (version < 1) {
401         kDebug() << "// OLD profile version";
402         doc.clear();
403         profiles = doc.createElement("profiles");
404         profiles.setAttribute("version", 1);
405         doc.appendChild(profiles);
406     }
407
408
409     QDomNodeList profilelist = doc.elementsByTagName("profile");
410     int i = 0;
411     while (!profilelist.item(i).isNull()) {
412         // make sure a profile with same name doesn't exist
413         documentElement = profilelist.item(i).toElement();
414         QString profileName = documentElement.attribute("name");
415         if (profileName == newprofile.attribute("name")) {
416             // a profile with that same name already exists
417             bool ok;
418             QString newProfileName = QInputDialog::getText(this, i18n("Profile already exists"), i18n("This profile name already exists. Change the name if you don't want to overwrite it."), QLineEdit::Normal, profileName, &ok);
419             if (!ok) return;
420             if (profileName == newProfileName) {
421                 profiles.removeChild(profilelist.item(i));
422                 break;
423             }
424         }
425         i++;
426     }
427
428     profiles.appendChild(newprofile);
429
430     //QCString save = doc.toString().utf8();
431
432     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
433         KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
434         return;
435     }
436     QTextStream out(&file);
437     out << doc.toString();
438     if (file.error() != QFile::NoError) {
439         KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
440         file.close();
441         return;
442     }
443     file.close();
444 }
445
446 void RenderWidget::slotCopyToFavorites()
447 {
448     QListWidgetItem *item = m_view.size_list->currentItem();
449     if (!item) return;
450     QString currentGroup = m_view.format_list->currentItem()->text();
451
452     QString params = item->data(ParamsRole).toString();
453     QString extension = item->data(ExtensionRole).toString();
454     QString currentProfile = item->text();
455     QDomDocument doc;
456     QDomElement profileElement = doc.createElement("profile");
457     profileElement.setAttribute("name", currentProfile);
458     profileElement.setAttribute("category", i18nc("Category Name", "Custom"));
459     profileElement.setAttribute("destinationid", "favorites");
460     profileElement.setAttribute("extension", extension);
461     profileElement.setAttribute("args", params);
462     doc.appendChild(profileElement);
463     saveProfile(doc.documentElement());
464     parseProfiles(m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString(), currentGroup, currentProfile);
465 }
466
467 void RenderWidget::slotEditProfile()
468 {
469     QListWidgetItem *item = m_view.size_list->currentItem();
470     if (!item) return;
471     QString currentGroup = m_view.format_list->currentItem()->text();
472
473     QString params = item->data(ParamsRole).toString();
474     QString extension = item->data(ExtensionRole).toString();
475     QString currentProfile = item->text();
476
477     Ui::SaveProfile_UI ui;
478     QDialog *d = new QDialog(this);
479     ui.setupUi(d);
480
481     for (int i = 0; i < m_view.destination_list->count(); i++)
482         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
483
484     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
485     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
486
487     QString customGroup = m_view.format_list->currentItem()->text();
488     if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
489     ui.group_name->setText(customGroup);
490
491     ui.profile_name->setText(currentProfile);
492     ui.extension->setText(extension);
493     ui.parameters->setText(params);
494     ui.profile_name->setFocus();
495     d->setWindowTitle(i18n("Edit Profile"));
496     if (d->exec() == QDialog::Accepted) {
497         slotDeleteProfile(false);
498         QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
499         QDomDocument doc;
500         QFile file(exportFile);
501         doc.setContent(&file, false);
502         file.close();
503         QDomElement documentElement;
504         QDomElement profiles = doc.documentElement();
505
506         if (profiles.isNull() || profiles.tagName() != "profiles") {
507             doc.clear();
508             profiles = doc.createElement("profiles");
509             profiles.setAttribute("version", 1);
510             doc.appendChild(profiles);
511         }
512
513         int version = profiles.attribute("version", 0).toInt();
514         if (version < 1) {
515             kDebug() << "// OLD profile version";
516             doc.clear();
517             profiles = doc.createElement("profiles");
518             profiles.setAttribute("version", 1);
519             doc.appendChild(profiles);
520         }
521
522         QString newProfileName = ui.profile_name->text().simplified();
523         QString newGroupName = ui.group_name->text().simplified();
524         if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
525         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
526         QDomNodeList profilelist = doc.elementsByTagName("profile");
527         int i = 0;
528         while (!profilelist.item(i).isNull()) {
529             // make sure a profile with same name doesn't exist
530             documentElement = profilelist.item(i).toElement();
531             QString profileName = documentElement.attribute("name");
532             if (profileName == newProfileName) {
533                 // a profile with that same name already exists
534                 bool ok;
535                 newProfileName = QInputDialog::getText(this, i18n("Profile already exists"), i18n("This profile name already exists. Change the name if you don't want to overwrite it."), QLineEdit::Normal, newProfileName, &ok);
536                 if (!ok) return;
537                 if (profileName == newProfileName) {
538                     profiles.removeChild(profilelist.item(i));
539                     break;
540                 }
541             }
542             i++;
543         }
544
545         QDomElement profileElement = doc.createElement("profile");
546         profileElement.setAttribute("name", newProfileName);
547         profileElement.setAttribute("category", newGroupName);
548         profileElement.setAttribute("destinationid", newMetaGroupId);
549         profileElement.setAttribute("extension", ui.extension->text().simplified());
550         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
551         profiles.appendChild(profileElement);
552
553         //QCString save = doc.toString().utf8();
554         delete d;
555         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
556             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
557             return;
558         }
559         QTextStream out(&file);
560         out << doc.toString();
561         if (file.error() != QFile::NoError) {
562             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
563             file.close();
564             return;
565         }
566         file.close();
567         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
568     } else delete d;
569 }
570
571 void RenderWidget::slotDeleteProfile(bool refresh)
572 {
573     //TODO: delete a profile installed by KNewStuff the easy way
574     /*
575     QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
576     if (!edit.endsWith("customprofiles.xml")) {
577         // This is a KNewStuff installed file, process through KNS
578         KNS::Engine engine(0);
579         if (engine.init("kdenlive_render.knsrc")) {
580             KNS::Entry::List entries;
581         }
582         return;
583     }*/
584     QString currentGroup = m_view.format_list->currentItem()->text();
585     QString currentProfile = m_view.size_list->currentItem()->text();
586     QString metaGroupId = m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString();
587
588     QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
589     QDomDocument doc;
590     QFile file(exportFile);
591     doc.setContent(&file, false);
592     file.close();
593
594     QDomElement documentElement;
595     QDomNodeList profiles = doc.elementsByTagName("profile");
596     int i = 0;
597     QString groupName;
598     QString profileName;
599     QString destination;
600
601     while (!profiles.item(i).isNull()) {
602         documentElement = profiles.item(i).toElement();
603         profileName = documentElement.attribute("name");
604         groupName = documentElement.attribute("category");
605         destination = documentElement.attribute("destinationid");
606
607         if (profileName == currentProfile && groupName == currentGroup && destination == metaGroupId) {
608             kDebug() << "// GOT it: " << profileName;
609             doc.documentElement().removeChild(profiles.item(i));
610             break;
611         }
612         i++;
613     }
614
615     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
616         KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
617         return;
618     }
619     QTextStream out(&file);
620     out << doc.toString();
621     if (file.error() != QFile::NoError) {
622         KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
623         file.close();
624         return;
625     }
626     file.close();
627     if (refresh) {
628         parseProfiles(metaGroupId, currentGroup);
629         focusFirstVisibleItem();
630     }
631 }
632
633 void RenderWidget::updateButtons()
634 {
635     if (!m_view.size_list->currentItem() || m_view.size_list->currentItem()->isHidden()) {
636         m_view.buttonSave->setEnabled(false);
637         m_view.buttonDelete->setEnabled(false);
638         m_view.buttonEdit->setEnabled(false);
639         m_view.buttonRender->setEnabled(false);
640         m_view.buttonGenerateScript->setEnabled(false);
641     } else {
642         m_view.buttonSave->setEnabled(true);
643         m_view.buttonRender->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
644         m_view.buttonGenerateScript->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
645         QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
646         if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
647             m_view.buttonDelete->setEnabled(false);
648             m_view.buttonEdit->setEnabled(false);
649         } else {
650             m_view.buttonDelete->setEnabled(true);
651             m_view.buttonEdit->setEnabled(true);
652         }
653     }
654 }
655
656
657 void RenderWidget::focusFirstVisibleItem()
658 {
659     if (m_view.size_list->currentItem()) {
660         updateButtons();
661         return;
662     }
663     m_view.size_list->setCurrentRow(0);
664     updateButtons();
665 }
666
667 void RenderWidget::slotPrepareExport(bool scriptExport)
668 {
669     if (!QFile::exists(KdenliveSettings::rendererpath())) {
670         KMessageBox::sorry(this, i18n("Cannot find the melt program required for rendering (part of Mlt)"));
671         return;
672     }
673     if (m_view.play_after->isChecked() && KdenliveSettings::defaultplayerapp().isEmpty()) {
674         KMessageBox::sorry(this, i18n("Cannot play video after rendering because the default video player application is not set.\nPlease define it in Kdenlive settings dialog."));
675     }
676     QString chapterFile;
677     if (m_view.create_chapter->isChecked()) chapterFile = m_view.out_file->url().path() + ".dvdchapter";
678
679     // mantisbt 1051
680     if (!KStandardDirs::makeDir(m_view.out_file->url().directory())) {
681         KMessageBox::sorry(this, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_view.out_file->url().directory()));
682         return;
683     }
684
685     emit prepareRenderingData(scriptExport, m_view.render_zone->isChecked(), chapterFile);
686 }
687
688
689 void RenderWidget::slotExport(bool scriptExport, int zoneIn, int zoneOut, const QString &playlistPath, const QString &scriptPath, bool exportAudio)
690 {
691     QListWidgetItem *item = m_view.size_list->currentItem();
692     if (!item) return;
693
694     QString dest = m_view.out_file->url().path();
695     if (dest.isEmpty()) return;
696
697     // Check whether target file has an extension.
698     // If not, ask whether extension should be added or not.
699     QString extension = item->data(ExtensionRole).toString();
700     if (!dest.endsWith(extension, Qt::CaseInsensitive)) {
701         if (KMessageBox::questionYesNo(this, i18n("File has no extension. Add extension (%1)?", extension)) == KMessageBox::Yes) {
702             dest.append("." + extension);
703         }
704     }
705
706     QFile f(dest);
707     if (f.exists()) {
708         if (KMessageBox::warningYesNo(this, i18n("Output file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
709             return;
710     }
711
712     QStringList overlayargs;
713     if (m_view.tc_overlay->isChecked()) {
714         QString filterFile = KStandardDirs::locate("appdata", "metadata.properties");
715         overlayargs << "meta.attr.timecode=1" << "meta.attr.timecode.markup=#timecode";
716         overlayargs << "-attach" << "data_feed:attr_check" << "-attach";
717         overlayargs << "data_show:" + filterFile << "_loader=1" << "dynamic=1";
718     }
719
720     QStringList render_process_args;
721
722     if (!scriptExport) render_process_args << "-erase";
723     if (KdenliveSettings::usekuiserver()) render_process_args << "-kuiserver";
724
725     double guideStart = 0;
726     double guideEnd = 0;
727
728     if (m_view.render_zone->isChecked()) render_process_args << "in=" + QString::number(zoneIn) << "out=" + QString::number(zoneOut);
729     else if (m_view.render_guide->isChecked()) {
730         double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
731         guideStart = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
732         guideEnd = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
733         render_process_args << "in=" + QString::number(GenTime(guideStart).frames(fps)) << "out=" + QString::number(GenTime(guideEnd).frames(fps));
734     }
735
736     if (!overlayargs.isEmpty()) render_process_args << "preargs=" + overlayargs.join(" ");
737
738     render_process_args << KdenliveSettings::rendererpath() << m_profile.path << item->data(RenderRole).toString();
739     if (m_view.play_after->isChecked()) render_process_args << KdenliveSettings::KdenliveSettings::defaultplayerapp();
740     else render_process_args << "-";
741
742     QString renderArgs = m_view.advanced_params->toPlainText().simplified();
743
744     // Adjust frame scale
745     int width;
746     int height;
747     if (m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
748         width = m_view.rescale_width->value();
749         height = m_view.rescale_height->value();
750     } else {
751         width = m_profile.width;
752         height = m_profile.height;
753     }
754     renderArgs.replace("%dar", '@' + QString::number(m_profile.display_aspect_num) + '/' + QString::number(m_profile.display_aspect_den));
755
756     // Adjust scanning
757     if (m_view.scanning_list->currentIndex() == 1) renderArgs.append(" progressive=1");
758     else if (m_view.scanning_list->currentIndex() == 2) renderArgs.append(" progressive=0");
759
760     // disable audio if requested
761     if (!exportAudio) renderArgs.append(" an=1 ");
762
763         // Set the thread counts
764         renderArgs.append(QString(" threads=%1").arg(KdenliveSettings::encodethreads()));
765         renderArgs.append(QString(" real_time=-%1").arg(KdenliveSettings::mltthreads()));
766
767     // Check if the rendering profile is different from project profile,
768     // in which case we need to use the producer_comsumer from MLT
769     QString std = renderArgs;
770     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
771     const QString currentSize = QString::number(width) + 'x' + QString::number(height);
772     QString subsize = currentSize;
773     if (std.startsWith("s=")) {
774         subsize = std.section(' ', 0, 0).toLower();
775         subsize = subsize.section('=', 1, 1);
776     } else if (std.contains(" s=")) {
777         subsize = std.section(" s=", 1, 1);
778         subsize = subsize.section(' ', 0, 0).toLower();
779     } else if (destination != "audioonly" && m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
780         subsize = QString(" s=%1x%2").arg(width).arg(height);
781         // Add current size parameter
782         renderArgs.append(subsize);
783     }
784     bool resizeProfile = (subsize != currentSize);
785     QStringList paramsList = renderArgs.split(" ", QString::SkipEmptyParts);
786     for (int i = 0; i < paramsList.count(); i++) {
787         if (paramsList.at(i).startsWith("profile=")) {
788             if (paramsList.at(i).section('=', 1) != m_profile.path) resizeProfile = true;
789             break;
790         }
791     }
792         
793     if (resizeProfile)
794         render_process_args << "consumer:" + (scriptExport ? "$SOURCE" : playlistPath);
795     else
796         render_process_args <<  (scriptExport ? "$SOURCE" : playlistPath);
797     render_process_args << (scriptExport ? "$TARGET" : dest);
798     render_process_args << paramsList;
799
800     QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
801
802     QStringList renderParameters;
803     renderParameters << dest << item->data(RenderRole).toString() << renderArgs.simplified();
804     renderParameters << QString::number(zoneIn) << QString::number(zoneOut) << QString::number(m_view.play_after->isChecked());
805     renderParameters << QString::number(guideStart) << QString::number(guideEnd) << QString::number(resizeProfile);
806
807     QString scriptName;
808     if (scriptExport) {
809         // Generate script file
810         QFile file(scriptPath);
811         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
812             KMessageBox::error(this, i18n("Cannot write to file %1", scriptPath));
813             return;
814         }
815         QTextStream outStream(&file);
816         outStream << "#! /bin/sh" << "\n" << "\n";
817         outStream << "SOURCE=" << "\"" + playlistPath + "\"" << "\n";
818         outStream << "TARGET=" << "\"" + dest + "\"" << "\n";
819         outStream << "RENDERER=" << "\"" + m_renderer + "\"" << "\n";
820         outStream << "MELT=" << "\"" + render_process_args.takeFirst() + "\"" << "\n";
821         outStream << "PARAMETERS=" << "\"" + render_process_args.join(" ") + "\"" << "\n";
822         outStream << "$RENDERER $MELT $PARAMETERS" << "\n" << "\n";
823         if (file.error() != QFile::NoError) {
824             KMessageBox::error(this, i18n("Cannot write to file %1", scriptPath));
825             file.close();
826             return;
827         }
828         file.close();
829         QFile::setPermissions(scriptPath, file.permissions() | QFile::ExeUser);
830
831         QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
832         m_view.tabWidget->setCurrentIndex(2);
833         return;
834     }
835     renderParameters << scriptName;
836
837     // Save rendering profile to document
838     QMap <QString, QString> renderProps;
839     renderProps.insert("renderdestination", m_view.size_list->currentItem()->data(MetaGroupRole).toString());
840     renderProps.insert("rendercategory", m_view.size_list->currentItem()->data(GroupRole).toString());
841     renderProps.insert("renderprofile", m_view.size_list->currentItem()->text());
842     renderProps.insert("renderurl", dest);
843     renderProps.insert("renderzone", QString::number(m_view.render_zone->isChecked()));
844     renderProps.insert("renderguide", QString::number(m_view.render_guide->isChecked()));
845     renderProps.insert("renderstartguide", QString::number(m_view.guide_start->currentIndex()));
846     renderProps.insert("renderendguide", QString::number(m_view.guide_end->currentIndex()));
847     renderProps.insert("renderendguide", QString::number(m_view.guide_end->currentIndex()));
848     renderProps.insert("renderscanning", QString::number(m_view.scanning_list->currentIndex()));
849     int export_audio = 0;
850     if (m_view.export_audio->checkState() == Qt::Checked) export_audio = 2;
851     else if (m_view.export_audio->checkState() == Qt::Unchecked) export_audio = 1;
852     renderProps.insert("renderexportaudio", QString::number(export_audio));
853     renderProps.insert("renderrescale", QString::number(m_view.rescale->isChecked()));
854     renderProps.insert("renderrescalewidth", QString::number(m_view.rescale_width->value()));
855     renderProps.insert("renderrescaleheight", QString::number(m_view.rescale_height->value()));
856     renderProps.insert("rendertcoverlay", QString::number(m_view.tc_overlay->isChecked()));
857     renderProps.insert("renderratio", QString::number(m_view.rescale_keep->isChecked()));
858     renderProps.insert("renderplay", QString::number(m_view.play_after->isChecked()));
859
860     emit selectedRenderProfile(renderProps);
861
862     // insert item in running jobs list
863     QTreeWidgetItem *renderItem;
864     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
865     if (!existing.isEmpty()) {
866         renderItem = existing.at(0);
867         if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
868             KMessageBox::information(this, i18n("There is already a job writing file:<br /><b>%1</b><br />Abort the job if you want to overwrite it...", dest), i18n("Already running"));
869             return;
870         }
871         renderItem->setData(1, Qt::UserRole + 4, QString());
872     } else {
873         renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
874     }
875     renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
876     renderItem->setIcon(0, KIcon("media-playback-pause"));
877     renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
878     renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
879     renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
880
881     // Set rendering type
882     if (group == "dvd") {
883         if (m_view.open_dvd->isChecked()) {
884             renderItem->setData(0, Qt::UserRole, group);
885             if (renderArgs.contains("profile=")) {
886                 // rendering profile contains an MLT profile, so pass it to the running jog item, useful for dvd
887                 QString prof = renderArgs.section("profile=", 1, 1);
888                 prof = prof.section(' ', 0, 0);
889                 kDebug() << "// render profile: " << prof;
890                 renderItem->setData(0, Qt::UserRole + 1, prof);
891             }
892         }
893     } else {
894         if (group == "websites" && m_view.open_browser->isChecked()) {
895             renderItem->setData(0, Qt::UserRole, group);
896             // pass the url
897             QString url = m_view.size_list->currentItem()->data(ExtraRole).toString();
898             renderItem->setData(0, Qt::UserRole + 1, url);
899         }
900     }
901     renderItem->setData(1, Qt::UserRole + 3, render_process_args);
902     if (exportAudio == false) renderItem->setData(1, Qt::UserRole + 5, i18n("Video without audio track"));
903     else  renderItem->setData(1, Qt::UserRole + 5, QString());
904     m_view.running_jobs->setCurrentItem(renderItem);
905     m_view.tabWidget->setCurrentIndex(1);
906     checkRenderStatus();
907 }
908
909 void RenderWidget::checkRenderStatus()
910 {
911     // check if we have a job waiting to render
912     if (m_blockProcessing) return;
913     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
914     while (item) {
915         if (item->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) return;
916         item = m_view.running_jobs->itemBelow(item);
917     }
918     item = m_view.running_jobs->topLevelItem(0);
919     bool waitingJob = false;
920     while (item) {
921         if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
922             item->setData(1, Qt::UserRole + 1, QTime::currentTime());
923             waitingJob = true;
924             startRendering(item);
925             break;
926         }
927         item = m_view.running_jobs->itemBelow(item);
928     }
929     if (waitingJob == false && m_view.shutdown->isChecked()) emit shutdown();
930 }
931
932 void RenderWidget::startRendering(QTreeWidgetItem *item)
933 {
934     if (item->data(1, Qt::UserRole + 4).isNull()) {
935         // Normal render process
936         if (QProcess::startDetached(m_renderer, item->data(1, Qt::UserRole + 3).toStringList()) == false) {
937             item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
938             item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
939             item->setIcon(0, KIcon("dialog-close"));
940             item->setData(2, Qt::UserRole, 100);
941         } else KNotification::event("RenderStarted", i18n("Rendering <i>%1</i> started", item->text(1)), QPixmap(), this);
942     } else {
943         // Script item
944         if (QProcess::startDetached(item->data(1, Qt::UserRole + 3).toString()) == false) {
945             item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
946             item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
947             item->setIcon(0, KIcon("dialog-close"));
948             item->setData(2, Qt::UserRole, 100);
949         }
950     }
951 }
952
953 int RenderWidget::waitingJobsCount() const
954 {
955     int count = 0;
956     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
957     while (item) {
958         if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) count++;
959         item = m_view.running_jobs->itemBelow(item);
960     }
961     return count;
962 }
963
964 void RenderWidget::setProfile(MltVideoProfile profile)
965 {
966     m_profile = profile;
967     //WARNING: this way to tell the video standard is a bit hackish...
968     if (m_profile.description.contains("pal", Qt::CaseInsensitive) || m_profile.description.contains("25", Qt::CaseInsensitive) || m_profile.description.contains("50", Qt::CaseInsensitive)) m_view.format_selection->setCurrentIndex(0);
969     else m_view.format_selection->setCurrentIndex(1);
970     m_view.scanning_list->setCurrentIndex(0);
971     m_view.rescale_width->setValue(KdenliveSettings::defaultrescalewidth());
972     if (!m_view.rescale_keep->isChecked()) {
973         m_view.rescale_height->blockSignals(true);
974         m_view.rescale_height->setValue(KdenliveSettings::defaultrescaleheight());
975         m_view.rescale_height->blockSignals(false);
976     }
977     refreshView();
978 }
979
980 void RenderWidget::refreshCategory()
981 {
982     m_view.format_list->blockSignals(true);
983     m_view.format_list->clear();
984     QListWidgetItem *sizeItem;
985
986     QString destination;
987     if (m_view.destination_list->currentIndex() > 0)
988         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
989
990
991     if (destination == "dvd") {
992         m_view.open_dvd->setVisible(true);
993         m_view.create_chapter->setVisible(true);
994     } else {
995         m_view.open_dvd->setVisible(false);
996         m_view.create_chapter->setVisible(false);
997     }
998
999     if (destination == "websites")
1000         m_view.open_browser->setVisible(true);
1001     else
1002         m_view.open_browser->setVisible(false);
1003
1004     // hide groups that are not in the correct destination
1005     for (int i = 0; i < m_renderCategory.count(); i++) {
1006         sizeItem = m_renderCategory.at(i);
1007         if (sizeItem->data(MetaGroupRole).toString() == destination) {
1008             m_view.format_list->addItem(sizeItem->clone());
1009             //kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
1010         }
1011     }
1012
1013     // activate first visible item
1014     QListWidgetItem * item = m_view.format_list->currentItem();
1015     if (!item) {
1016         m_view.format_list->setCurrentRow(0);
1017         item = m_view.format_list->currentItem();
1018     }
1019     if (!item) {
1020         m_view.format_list->setEnabled(false);
1021         m_view.size_list->setEnabled(false);
1022         m_view.size_list->blockSignals(false);
1023         m_view.format_list->blockSignals(false);
1024         return;
1025     } else {
1026         m_view.format_list->setEnabled(true);
1027         m_view.size_list->setEnabled(true);
1028     }
1029
1030     if (m_view.format_list->count() > 1)
1031         m_view.format_list->setVisible(true);
1032     else
1033         m_view.format_list->setVisible(false);
1034     refreshView();
1035 }
1036
1037 void RenderWidget::refreshView()
1038 {
1039     if (!m_view.format_list->currentItem()) return;
1040     m_view.size_list->blockSignals(true);
1041     m_view.size_list->clear();
1042     QListWidgetItem *sizeItem;
1043     QString std;
1044     QString group = m_view.format_list->currentItem()->text();
1045     QString destination;
1046     if (m_view.destination_list->currentIndex() > 0)
1047         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
1048     KIcon brokenIcon("dialog-close");
1049
1050     const QStringList formatsList = KdenliveSettings::supportedformats();
1051     const QStringList vcodecsList = KdenliveSettings::videocodecs();
1052     const QStringList acodecsList = KdenliveSettings::audiocodecs();
1053
1054     KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window);
1055     const QColor disabled = scheme.foreground(KColorScheme::InactiveText).color();
1056     const QColor disabledbg = scheme.background(KColorScheme::NegativeBackground).color();
1057
1058
1059     for (int i = 0; i < m_renderItems.count(); i++) {
1060         sizeItem = m_renderItems.at(i);
1061         QListWidgetItem *dupItem = NULL;
1062         if ((sizeItem->data(GroupRole).toString() == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole).toString() == destination) {
1063             std = sizeItem->data(StandardRole).toString();
1064             if (!std.isEmpty()) {
1065                 if (std.contains("PAL", Qt::CaseInsensitive) && m_view.format_selection->currentIndex() == 0) dupItem = sizeItem->clone();
1066                 else if (std.contains("NTSC", Qt::CaseInsensitive) && m_view.format_selection->currentIndex() == 1)  dupItem = sizeItem->clone();
1067             } else {
1068                 dupItem = sizeItem->clone();
1069             }
1070
1071             if (dupItem) {
1072                 m_view.size_list->addItem(dupItem);
1073                 // Make sure the selected profile uses an installed avformat codec / format
1074                 std = dupItem->data(ParamsRole).toString();
1075                 if (!formatsList.isEmpty()) {
1076                     QString format;
1077                     if (std.startsWith("f=")) format = std.section("f=", 1, 1);
1078                     else if (std.contains(" f=")) format = std.section(" f=", 1, 1);
1079                     if (!format.isEmpty()) {
1080                         format = format.section(' ', 0, 0).toLower();
1081                         if (!formatsList.contains(format)) {
1082                             kDebug() << "***** UNSUPPORTED F: " << format;
1083                             //sizeItem->setHidden(true);
1084                             //sizeItem->setFlags(Qt::ItemIsSelectable);
1085                             dupItem->setToolTip(i18n("Unsupported video format: %1", format));
1086                             dupItem->setIcon(brokenIcon);
1087                             dupItem->setForeground(disabled);
1088                         }
1089                     }
1090                 }
1091                 if (!acodecsList.isEmpty()) {
1092                     QString format;
1093                     if (std.startsWith("acodec=")) format = std.section("acodec=", 1, 1);
1094                     else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
1095                     if (!format.isEmpty()) {
1096                         format = format.section(' ', 0, 0).toLower();
1097                         if (!acodecsList.contains(format)) {
1098                             kDebug() << "*****  UNSUPPORTED ACODEC: " << format;
1099                             //sizeItem->setHidden(true);
1100                             //sizeItem->setFlags(Qt::ItemIsSelectable);
1101                             dupItem->setToolTip(i18n("Unsupported audio codec: %1", format));
1102                             dupItem->setIcon(brokenIcon);
1103                             dupItem->setForeground(disabled);
1104                             dupItem->setBackground(disabledbg);
1105                         }
1106                     }
1107                 }
1108                 if (!vcodecsList.isEmpty()) {
1109                     QString format;
1110                     if (std.startsWith("vcodec=")) format = std.section("vcodec=", 1, 1);
1111                     else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
1112                     if (!format.isEmpty()) {
1113                         format = format.section(' ', 0, 0).toLower();
1114                         if (!vcodecsList.contains(format)) {
1115                             kDebug() << "*****  UNSUPPORTED VCODEC: " << format;
1116                             //sizeItem->setHidden(true);
1117                             //sizeItem->setFlags(Qt::ItemIsSelectable);
1118                             dupItem->setToolTip(i18n("Unsupported video codec: %1", format));
1119                             dupItem->setIcon(brokenIcon);
1120                             dupItem->setForeground(disabled);
1121                         }
1122                     }
1123                 }
1124             }
1125         }
1126     }
1127     // m_view.size_list->sortItems();
1128     focusFirstVisibleItem();
1129     m_view.size_list->blockSignals(false);
1130     m_view.format_list->blockSignals(false);
1131     refreshParams();
1132 }
1133
1134 KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension)
1135 {
1136     if (url.isEmpty()) url = KUrl(m_projectFolder);
1137     QString directory = url.directory(KUrl::AppendTrailingSlash | KUrl::ObeyTrailingSlash);
1138     QString filename = url.fileName(KUrl::ObeyTrailingSlash);
1139     QString ext;
1140
1141     if (extension.at(0) == '.') ext = extension;
1142     else ext = '.' + extension;
1143
1144     if (filename.isEmpty()) filename = i18n("untitled");
1145
1146     int pos = filename.lastIndexOf('.');
1147     if (pos == 0) filename.append(ext);
1148     else {
1149         if (!filename.endsWith(ext, Qt::CaseInsensitive)) {
1150             filename = filename.left(pos) + ext;
1151         }
1152     }
1153
1154     return KUrl(directory + filename);
1155 }
1156
1157 void RenderWidget::refreshParams()
1158 {
1159     // Format not available (e.g. codec not installed); Disable start button
1160     QListWidgetItem *item = m_view.size_list->currentItem();
1161     if (!item || item->isHidden()) {
1162         m_view.advanced_params->clear();
1163         m_view.buttonRender->setEnabled(false);
1164         m_view.buttonGenerateScript->setEnabled(false);
1165         return;
1166     }
1167     QString params = item->data(ParamsRole).toString();
1168     QString extension = item->data(ExtensionRole).toString();
1169     m_view.advanced_params->setPlainText(params);
1170     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
1171     if (params.contains(" s=") || params.startsWith("s=") || destination == "audioonly") {
1172         // profile has a fixed size, do not allow resize
1173         m_view.rescale->setEnabled(false);
1174         m_view.rescale_box->setEnabled(false);
1175     } else {
1176         m_view.rescale->setEnabled(true);
1177         m_view.rescale_box->setEnabled(m_view.rescale->isChecked());
1178     }
1179     KUrl url = filenameWithExtension(m_view.out_file->url(), extension);
1180     m_view.out_file->setUrl(url);
1181 //     if (!url.isEmpty()) {
1182 //         QString path = url.path();
1183 //         int pos = path.lastIndexOf('.') + 1;
1184 //  if (pos == 0) path.append('.' + extension);
1185 //         else path = path.left(pos) + extension;
1186 //         m_view.out_file->setUrl(KUrl(path));
1187 //     } else {
1188 //         m_view.out_file->setUrl(KUrl(QDir::homePath() + "/untitled." + extension));
1189 //     }
1190     m_view.out_file->setFilter("*." + extension);
1191     QString edit = item->data(EditableRole).toString();
1192     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
1193         m_view.buttonDelete->setEnabled(false);
1194         m_view.buttonEdit->setEnabled(false);
1195     } else {
1196         m_view.buttonDelete->setEnabled(true);
1197         m_view.buttonEdit->setEnabled(true);
1198     }
1199
1200     m_view.buttonRender->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
1201     m_view.buttonGenerateScript->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
1202 }
1203
1204 void RenderWidget::reloadProfiles()
1205 {
1206     parseProfiles();
1207 }
1208
1209 void RenderWidget::parseProfiles(QString meta, QString group, QString profile)
1210 {
1211     m_view.size_list->blockSignals(true);
1212     m_view.format_list->blockSignals(true);
1213     m_view.size_list->clear();
1214     m_view.format_list->clear();
1215     m_view.destination_list->clear();
1216     qDeleteAll(m_renderItems);
1217     qDeleteAll(m_renderCategory);
1218     m_renderItems.clear();
1219     m_renderCategory.clear();
1220     m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
1221     m_view.destination_list->addItem(KIcon("favorites"), i18n("Favorites"), "favorites");
1222     m_view.destination_list->addItem(KIcon("media-optical"), i18n("DVD"), "dvd");
1223     m_view.destination_list->addItem(KIcon("audio-x-generic"), i18n("Audio only"), "audioonly");
1224     m_view.destination_list->addItem(KIcon("applications-internet"), i18n("Web sites"), "websites");
1225     m_view.destination_list->addItem(KIcon("applications-multimedia"), i18n("Media players"), "mediaplayers");
1226     m_view.destination_list->addItem(KIcon("drive-harddisk"), i18n("Lossless / HQ"), "lossless");
1227     m_view.destination_list->addItem(KIcon("pda"), i18n("Mobile devices"), "mobile");
1228
1229     QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
1230     parseFile(exportFile, false);
1231
1232
1233     QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
1234     QDir directory = QDir(exportFolder);
1235     QStringList filter;
1236     filter << "*.xml";
1237     QStringList fileList = directory.entryList(filter, QDir::Files);
1238     // We should parse customprofiles.xml in last position, so that user profiles
1239     // can also override profiles installed by KNewStuff
1240     fileList.removeAll("customprofiles.xml");
1241     foreach(const QString &filename, fileList)
1242     parseFile(exportFolder + filename, true);
1243     if (QFile::exists(exportFolder + "customprofiles.xml")) parseFile(exportFolder + "customprofiles.xml", true);
1244
1245     if (!meta.isEmpty()) {
1246         m_view.destination_list->blockSignals(true);
1247         m_view.destination_list->setCurrentIndex(m_view.destination_list->findData(meta));
1248         m_view.destination_list->blockSignals(false);
1249     }
1250     refreshCategory();
1251     QList<QListWidgetItem *> child;
1252     if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
1253     if (!child.isEmpty()) {
1254         for (int i = 0; i < child.count(); i++) {
1255             if (child.at(i)->data(MetaGroupRole).toString() == meta) {
1256                 m_view.format_list->setCurrentItem(child.at(i));
1257                 break;
1258             }
1259         }
1260     }
1261     child.clear();
1262     m_view.size_list->blockSignals(false);
1263     m_view.format_list->blockSignals(false);
1264     if (!profile.isEmpty()) child = m_view.size_list->findItems(profile, Qt::MatchExactly);
1265     if (!child.isEmpty()) m_view.size_list->setCurrentItem(child.at(0));
1266 }
1267
1268 void RenderWidget::parseFile(QString exportFile, bool editable)
1269 {
1270     kDebug() << "// Parsing file: " << exportFile;
1271     kDebug() << "------------------------------";
1272     QDomDocument doc;
1273     QFile file(exportFile);
1274     doc.setContent(&file, false);
1275     file.close();
1276     QDomElement documentElement;
1277     QDomElement profileElement;
1278     QString extension;
1279     QDomNodeList groups = doc.elementsByTagName("group");
1280     QListWidgetItem *item = NULL;
1281     const QStringList acodecsList = KdenliveSettings::audiocodecs();
1282     bool replaceVorbisCodec = false;
1283     if (acodecsList.contains("libvorbis")) replaceVorbisCodec = true;
1284     bool replaceLibfaacCodec = false;
1285     if (!acodecsList.contains("aac") && acodecsList.contains("libfaac")) replaceLibfaacCodec = true;
1286
1287
1288     if (editable || groups.count() == 0) {
1289         QDomElement profiles = doc.documentElement();
1290         if (editable && profiles.attribute("version", 0).toInt() < 1) {
1291             kDebug() << "// OLD profile version";
1292             // this is an old profile version, update it
1293             QDomDocument newdoc;
1294             QDomElement newprofiles = newdoc.createElement("profiles");
1295             newprofiles.setAttribute("version", 1);
1296             newdoc.appendChild(newprofiles);
1297             QDomNodeList profilelist = doc.elementsByTagName("profile");
1298             for (int i = 0; i < profilelist.count(); i++) {
1299                 QString category = i18nc("Category Name", "Custom");
1300                 QString extension;
1301                 QDomNode parent = profilelist.at(i).parentNode();
1302                 if (!parent.isNull()) {
1303                     QDomElement parentNode = parent.toElement();
1304                     if (parentNode.hasAttribute("name")) category = parentNode.attribute("name");
1305                     extension = parentNode.attribute("extension");
1306                 }
1307                 profilelist.at(i).toElement().setAttribute("category", category);
1308                 if (!extension.isEmpty()) profilelist.at(i).toElement().setAttribute("extension", extension);
1309                 QDomNode n = profilelist.at(i).cloneNode();
1310                 newprofiles.appendChild(newdoc.importNode(n, true));
1311             }
1312             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1313                 KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
1314                 return;
1315             }
1316             QTextStream out(&file);
1317             out << newdoc.toString();
1318             file.close();
1319             parseFile(exportFile, editable);
1320             return;
1321         }
1322
1323         QDomNode node = doc.elementsByTagName("profile").at(0);
1324         if (node.isNull()) {
1325             kDebug() << "// Export file: " << exportFile << " IS BROKEN";
1326             return;
1327         }
1328         int count = 1;
1329         while (!node.isNull()) {
1330             QDomElement profile = node.toElement();
1331             QString profileName = profile.attribute("name");
1332             QString standard = profile.attribute("standard");
1333             QString params = profile.attribute("args");
1334
1335             if (replaceVorbisCodec && params.contains("acodec=vorbis")) {
1336                 // replace vorbis with libvorbis
1337                 params = params.replace("vorbis", "libvorbis");
1338             }
1339             if (replaceLibfaacCodec && params.contains("acodec=aac")) {
1340                 // replace libfaac with aac
1341                 params = params.replace("aac", "libfaac");
1342             }
1343
1344             QString category = profile.attribute("category", i18nc("Category Name", "Custom"));
1345             QString dest = profile.attribute("destinationid");
1346             QString prof_extension = profile.attribute("extension");
1347             if (!prof_extension.isEmpty()) extension = prof_extension;
1348             bool exists = false;
1349             for (int j = 0; j < m_renderCategory.count(); j++) {
1350                 if (m_renderCategory.at(j)->text() == category && m_renderCategory.at(j)->data(MetaGroupRole) == dest) {
1351                     exists = true;
1352                     break;
1353                 }
1354             }
1355
1356             if (!exists) {
1357                 QListWidgetItem *itemcat = new QListWidgetItem(category);
1358                 itemcat->setData(MetaGroupRole, dest);
1359                 m_renderCategory.append(itemcat);
1360             }
1361
1362             // Check if item with same name already exists and replace it,
1363             // allowing to override default profiles
1364
1365
1366             for (int j = 0; j < m_renderItems.count(); j++) {
1367                 if (m_renderItems.at(j)->text() == profileName && m_renderItems.at(j)->data(MetaGroupRole) == dest) {
1368                     QListWidgetItem *duplicate = m_renderItems.takeAt(j);
1369                     delete duplicate;
1370                     j--;
1371                 }
1372             }
1373
1374             item = new QListWidgetItem(profileName); // , m_view.size_list
1375             //kDebug() << "// ADDINg item with name: " << profileName << ", GRP" << category << ", DEST:" << dest ;
1376             item->setData(GroupRole, category);
1377             item->setData(MetaGroupRole, dest);
1378             item->setData(ExtensionRole, extension);
1379             item->setData(RenderRole, "avformat");
1380             item->setData(StandardRole, standard);
1381             item->setData(ParamsRole, params);
1382             if (profile.hasAttribute("url")) item->setData(ExtraRole, profile.attribute("url"));
1383             if (editable) {
1384                 item->setData(EditableRole, exportFile);
1385                 if (exportFile.endsWith("customprofiles.xml")) item->setIcon(KIcon("emblem-favorite"));
1386                 else item->setIcon(KIcon("applications-internet"));
1387             }
1388             m_renderItems.append(item);
1389             node = doc.elementsByTagName("profile").at(count);
1390             count++;
1391         }
1392         return;
1393     }
1394
1395     int i = 0;
1396     QString groupName;
1397     QString profileName;
1398
1399     QString prof_extension;
1400     QString renderer;
1401     QString params;
1402     QString standard;
1403     KIcon icon;
1404
1405     while (!groups.item(i).isNull()) {
1406         documentElement = groups.item(i).toElement();
1407         QDomNode gname = documentElement.elementsByTagName("groupname").at(0);
1408         QString metagroupName;
1409         QString metagroupId;
1410         if (!gname.isNull()) {
1411             metagroupName = gname.firstChild().nodeValue();
1412             metagroupId = gname.toElement().attribute("id");
1413
1414             if (!metagroupName.isEmpty() && m_view.destination_list->findData(metagroupId) == -1) {
1415                 if (metagroupId == "dvd") icon = KIcon("media-optical");
1416                 else if (metagroupId == "audioonly") icon = KIcon("audio-x-generic");
1417                 else if (metagroupId == "websites") icon = KIcon("applications-internet");
1418                 else if (metagroupId == "mediaplayers") icon = KIcon("applications-multimedia");
1419                 else if (metagroupId == "lossless") icon = KIcon("drive-harddisk");
1420                 else if (metagroupId == "mobile") icon = KIcon("pda");
1421                 m_view.destination_list->addItem(icon, i18n(metagroupName.toUtf8().data()), metagroupId);
1422             }
1423         }
1424         groupName = documentElement.attribute("name", i18nc("Attribute Name", "Custom"));
1425         extension = documentElement.attribute("extension", QString());
1426         renderer = documentElement.attribute("renderer", QString());
1427         bool exists = false;
1428         for (int j = 0; j < m_renderCategory.count(); j++) {
1429             if (m_renderCategory.at(j)->text() == groupName && m_renderCategory.at(j)->data(MetaGroupRole) == metagroupId) {
1430                 exists = true;
1431                 break;
1432             }
1433         }
1434         if (!exists) {
1435             QListWidgetItem *itemcat = new QListWidgetItem(groupName); //, m_view.format_list);
1436             itemcat->setData(MetaGroupRole, metagroupId);
1437             m_renderCategory.append(itemcat);
1438         }
1439
1440         QDomNode n = groups.item(i).firstChild();
1441         while (!n.isNull()) {
1442             if (n.toElement().tagName() != "profile") {
1443                 n = n.nextSibling();
1444                 continue;
1445             }
1446             profileElement = n.toElement();
1447             profileName = profileElement.attribute("name");
1448             standard = profileElement.attribute("standard");
1449             params = profileElement.attribute("args");
1450
1451             if (replaceVorbisCodec && params.contains("acodec=vorbis")) {
1452                 // replace vorbis with libvorbis
1453                 params = params.replace("vorbis", "libvorbis");
1454             }
1455             if (replaceLibfaacCodec && params.contains("acodec=aac")) {
1456                 // replace libfaac with aac
1457                 params = params.replace("aac", "libfaac");
1458             }
1459
1460             prof_extension = profileElement.attribute("extension");
1461             if (!prof_extension.isEmpty()) extension = prof_extension;
1462             item = new QListWidgetItem(profileName); //, m_view.size_list);
1463             item->setData(GroupRole, groupName);
1464             item->setData(MetaGroupRole, metagroupId);
1465             item->setData(ExtensionRole, extension);
1466             item->setData(RenderRole, renderer);
1467             item->setData(StandardRole, standard);
1468             item->setData(ParamsRole, params);
1469             if (profileElement.hasAttribute("url")) item->setData(ExtraRole, profileElement.attribute("url"));
1470             if (editable) item->setData(EditableRole, exportFile);
1471             m_renderItems.append(item);
1472             n = n.nextSibling();
1473         }
1474
1475         i++;
1476     }
1477 }
1478
1479 void RenderWidget::setRenderJob(const QString &dest, int progress)
1480 {
1481     QTreeWidgetItem *item;
1482     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1483     if (!existing.isEmpty()) item = existing.at(0);
1484     else {
1485         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1486         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1487         if (progress == 0) {
1488             item->setData(1, Qt::UserRole + 2, WAITINGJOB);
1489             item->setIcon(0, KIcon("media-playback-pause"));
1490             item->setData(1, Qt::UserRole, i18n("Waiting..."));
1491         }
1492     }
1493     item->setData(2, Qt::UserRole, progress);
1494     item->setData(1, Qt::UserRole + 2, RUNNINGJOB);
1495     if (progress == 0) {
1496         item->setIcon(0, KIcon("system-run"));
1497         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1498         item->setData(1, Qt::UserRole + 1, QTime::currentTime());
1499         slotCheckJob();
1500     } else {
1501         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1502         int seconds = startTime.secsTo(QTime::currentTime());;
1503         const QString t = i18n("Estimated time %1", QTime().addSecs(seconds * (100 - progress) / progress).toString("hh:mm:ss"));
1504         item->setData(1, Qt::UserRole, t);
1505     }
1506 }
1507
1508 void RenderWidget::setRenderStatus(const QString &dest, int status, const QString &error)
1509 {
1510     QTreeWidgetItem *item;
1511     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1512     if (!existing.isEmpty()) item = existing.at(0);
1513     else {
1514         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1515         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1516     }
1517     item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
1518     if (status == -1) {
1519         // Job finished successfully
1520         item->setIcon(0, KIcon("dialog-ok"));
1521         item->setData(2, Qt::UserRole, 100);
1522         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1523         int seconds = startTime.secsTo(QTime::currentTime());
1524         const QTime tm = QTime().addSecs(seconds);
1525         const QString t = i18n("Rendering finished in %1", tm.toString("hh:mm:ss"));
1526         item->setData(1, Qt::UserRole, t);
1527         QString itemGroup = item->data(0, Qt::UserRole).toString();
1528         if (itemGroup == "dvd") {
1529             emit openDvdWizard(item->text(1), item->data(0, Qt::UserRole + 1).toString());
1530         } else if (itemGroup == "websites") {
1531             QString url = item->data(0, Qt::UserRole + 1).toString();
1532             if (!url.isEmpty()) new KRun(url, this);
1533         }
1534     } else if (status == -2) {
1535         // Rendering crashed
1536         item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
1537         item->setIcon(0, KIcon("dialog-close"));
1538         item->setData(2, Qt::UserRole, 100);
1539         m_view.error_log->append(i18n("<strong>Rendering of %1 crashed</strong><br />", dest));
1540         m_view.error_log->append(error);
1541         m_view.error_log->append("<hr />");
1542         m_view.error_box->setVisible(true);
1543     } else if (status == -3) {
1544         // User aborted job
1545         item->setData(1, Qt::UserRole, i18n("Rendering aborted"));
1546         item->setIcon(0, KIcon("dialog-cancel"));
1547         item->setData(2, Qt::UserRole, 100);
1548     }
1549     slotCheckJob();
1550     checkRenderStatus();
1551 }
1552
1553 void RenderWidget::slotAbortCurrentJob()
1554 {
1555     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1556     if (current) {
1557         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1558             emit abortProcess(current->text(1));
1559         else {
1560             delete current;
1561             slotCheckJob();
1562             checkRenderStatus();
1563         }
1564     }
1565 }
1566
1567 void RenderWidget::slotStartCurrentJob()
1568 {
1569     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1570     if (current && current->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB)
1571         startRendering(current);
1572     m_view.start_job->setEnabled(false);
1573 }
1574
1575 void RenderWidget::slotCheckJob()
1576 {
1577     bool activate = false;
1578     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1579     if (current) {
1580         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1581             m_view.abort_job->setText(i18n("Abort Job"));
1582             m_view.start_job->setEnabled(false);
1583         } else {
1584             m_view.abort_job->setText(i18n("Remove Job"));
1585             m_view.start_job->setEnabled(current->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB);
1586         }
1587         activate = true;
1588     }
1589     m_view.abort_job->setEnabled(activate);
1590     for (int i = 0; i < m_view.running_jobs->topLevelItemCount(); i++) {
1591         current = m_view.running_jobs->topLevelItem(i);
1592         if (current == m_view.running_jobs->currentItem()) {
1593             current->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 3));
1594         } else current->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1595     }
1596 }
1597
1598 void RenderWidget::slotCLeanUpJobs()
1599 {
1600     int ix = 0;
1601     QTreeWidgetItem *current = m_view.running_jobs->topLevelItem(ix);
1602     while (current) {
1603         if (current->data(1, Qt::UserRole + 2).toInt() == FINISHEDJOB)
1604             delete current;
1605         else ix++;
1606         current = m_view.running_jobs->topLevelItem(ix);
1607     }
1608     slotCheckJob();
1609 }
1610
1611 void RenderWidget::parseScriptFiles()
1612 {
1613     QStringList scriptsFilter;
1614     scriptsFilter << "*.sh";
1615     m_view.scripts_list->clear();
1616
1617     QTreeWidgetItem *item;
1618     // List the project scripts
1619     QStringList scriptFiles = QDir(m_projectFolder + "scripts").entryList(scriptsFilter, QDir::Files);
1620     for (int i = 0; i < scriptFiles.size(); ++i) {
1621         KUrl scriptpath(m_projectFolder + "scripts/" + scriptFiles.at(i));
1622         QString target;
1623         QString renderer;
1624         QString melt;
1625         QFile file(scriptpath.path());
1626         if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1627             QTextStream stream(&file);
1628             while (!stream.atEnd()) {
1629                 QString line = stream.readLine();
1630                 if (line.startsWith("TARGET=")) {
1631                     target = line.section("TARGET=", 1).simplified();
1632                     target.remove(QChar('"'));
1633                 } else if (line.startsWith("RENDERER=")) {
1634                     renderer = line.section("RENDERER=", 1).simplified();
1635                     renderer.remove(QChar('"'));
1636                 } else if (line.startsWith("MELT=")) {
1637                     melt = line.section("MELT=", 1).simplified();
1638                     melt.remove(QChar('"'));
1639                 }
1640             }
1641             file.close();
1642         }
1643         if (target.isEmpty()) continue;
1644         item = new QTreeWidgetItem(m_view.scripts_list, QStringList() << QString() << scriptpath.fileName());
1645         if (!renderer.isEmpty() && renderer.contains('/') && !QFile::exists(renderer)) {
1646             item->setIcon(0, KIcon("dialog-cancel"));
1647             item->setToolTip(1, i18n("Script contains wrong command: %1", renderer));
1648             item->setData(0, Qt::UserRole, '1');
1649         } else if (!melt.isEmpty() && melt.contains('/') && !QFile::exists(melt)) {
1650             item->setIcon(0, KIcon("dialog-cancel"));
1651             item->setToolTip(1, i18n("Script contains wrong command: %1", melt));
1652             item->setData(0, Qt::UserRole, '1');
1653         } else item->setIcon(0, KIcon("application-x-executable-script"));
1654         item->setSizeHint(0, QSize(m_view.scripts_list->columnWidth(0), fontMetrics().height() * 2));
1655         item->setData(1, Qt::UserRole, target.simplified());
1656         item->setData(1, Qt::UserRole + 1, scriptpath.path());
1657     }
1658     bool activate = false;
1659     QTreeWidgetItem *script = m_view.scripts_list->topLevelItem(0);
1660     if (script) {
1661         m_view.scripts_list->setCurrentItem(script);
1662         script->setSelected(true);
1663         activate = true;
1664     }
1665 //    m_view.start_script->setEnabled(activate);
1666 //    m_view.delete_script->setEnabled(activate);
1667 }
1668
1669 void RenderWidget::slotCheckScript()
1670 {
1671     QTreeWidgetItem *current = m_view.scripts_list->currentItem();
1672     if (current == NULL) return;
1673     m_view.start_script->setEnabled(current->data(0, Qt::UserRole).toString().isEmpty());
1674     m_view.delete_script->setEnabled(true);
1675     for (int i = 0; i < m_view.scripts_list->topLevelItemCount(); i++) {
1676         current = m_view.scripts_list->topLevelItem(i);
1677         if (current == m_view.scripts_list->currentItem()) {
1678             current->setSizeHint(1, QSize(m_view.scripts_list->columnWidth(1), fontMetrics().height() * 3));
1679         } else current->setSizeHint(1, QSize(m_view.scripts_list->columnWidth(1), fontMetrics().height() * 2));
1680     }
1681 }
1682
1683 void RenderWidget::slotStartScript()
1684 {
1685     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1686     if (item) {
1687         QString destination = item->data(1, Qt::UserRole).toString();
1688         QString path = item->data(1, Qt::UserRole + 1).toString();
1689         // Insert new job in queue
1690         QTreeWidgetItem *renderItem;
1691         QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(destination, Qt::MatchExactly, 1);
1692         kDebug() << "------  START SCRIPT";
1693         if (!existing.isEmpty()) {
1694             renderItem = existing.at(0);
1695             if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1696                 KMessageBox::information(this, i18n("There is already a job writing file:<br /><b>%1</b><br />Abort the job if you want to overwrite it...", destination), i18n("Already running"));
1697                 return;
1698             }
1699         } else renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << destination << QString());
1700         kDebug() << "------  START SCRIPT 2";
1701         renderItem->setData(2, Qt::UserRole, 0);
1702         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
1703         renderItem->setIcon(0, KIcon("media-playback-pause"));
1704         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
1705         renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1706         renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
1707         renderItem->setData(1, Qt::UserRole + 3, path);
1708         renderItem->setData(1, Qt::UserRole + 4, '1');
1709         checkRenderStatus();
1710         m_view.tabWidget->setCurrentIndex(1);
1711     }
1712 }
1713
1714 void RenderWidget::slotDeleteScript()
1715 {
1716     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1717     if (item) {
1718         QString path = item->data(1, Qt::UserRole + 1).toString();
1719         KIO::NetAccess::del(path + ".mlt", this);
1720         KIO::NetAccess::del(path, this);
1721         parseScriptFiles();
1722     }
1723 }
1724
1725 void RenderWidget::slotGenerateScript()
1726 {
1727     slotPrepareExport(true);
1728 }
1729
1730 void RenderWidget::slotHideLog()
1731 {
1732     m_view.error_box->setVisible(false);
1733 }
1734
1735 void RenderWidget::setRenderProfile(QMap <QString, QString> props)
1736 {
1737     m_view.destination_list->blockSignals(true);
1738     m_view.format_list->blockSignals(true);
1739     m_view.scanning_list->setCurrentIndex(props.value("renderscanning").toInt());
1740     int exportAudio = props.value("renderexportaudio").toInt();
1741     switch (exportAudio) {
1742     case 1:
1743         m_view.export_audio->setCheckState(Qt::Unchecked);
1744         break;
1745     case 2:
1746         m_view.export_audio->setCheckState(Qt::Checked);
1747         break;
1748     default:
1749         m_view.export_audio->setCheckState(Qt::PartiallyChecked);
1750     }
1751     if (props.contains("renderrescale")) m_view.rescale->setChecked(props.value("renderrescale").toInt());
1752     if (props.contains("renderrescalewidth")) m_view.rescale_width->setValue(props.value("renderrescalewidth").toInt());
1753     if (props.contains("renderrescaleheight")) m_view.rescale_height->setValue(props.value("renderrescaleheight").toInt());
1754     if (props.contains("rendertcoverlay")) m_view.tc_overlay->setChecked(props.value("rendertcoverlay").toInt());
1755     if (props.contains("renderratio")) m_view.rescale_keep->setChecked(props.value("renderratio").toInt());
1756     if (props.contains("renderplay")) m_view.play_after->setChecked(props.value("renderplay").toInt());
1757
1758     if (props.value("renderzone") == "1") m_view.render_zone->setChecked(true);
1759     else if (props.value("renderguide") == "1") {
1760         m_view.render_guide->setChecked(true);
1761         m_view.guide_start->setCurrentIndex(props.value("renderstartguide").toInt());
1762         m_view.guide_end->setCurrentIndex(props.value("renderendguide").toInt());
1763     } else m_view.render_full->setChecked(true);
1764     slotUpdateGuideBox();
1765
1766     QString url = props.value("renderurl");
1767     if (!url.isEmpty()) m_view.out_file->setUrl(KUrl(url));
1768
1769     // set destination
1770     for (int i = 0; i < m_view.destination_list->count(); i++) {
1771         if (m_view.destination_list->itemData(i, Qt::UserRole) == props.value("renderdestination")) {
1772             m_view.destination_list->setCurrentIndex(i);
1773             break;
1774         }
1775     }
1776     refreshCategory();
1777
1778     // set category
1779     QString group = props.value("rendercategory");
1780     if (!group.isEmpty()) {
1781         QList<QListWidgetItem *> childs = m_view.format_list->findItems(group, Qt::MatchExactly);
1782         if (!childs.isEmpty()) {
1783             m_view.format_list->setCurrentItem(childs.at(0));
1784             m_view.format_list->scrollToItem(childs.at(0));
1785         }
1786         refreshView();
1787     }
1788
1789     // set profile
1790     QList<QListWidgetItem *> childs = m_view.size_list->findItems(props.value("renderprofile"), Qt::MatchExactly);
1791     if (!childs.isEmpty()) {
1792         m_view.size_list->setCurrentItem(childs.at(0));
1793         m_view.size_list->scrollToItem(childs.at(0));
1794     }
1795     //refreshView();
1796     m_view.destination_list->blockSignals(false);
1797     m_view.format_list->blockSignals(false);
1798
1799 }
1800
1801 bool RenderWidget::startWaitingRenderJobs()
1802 {
1803     m_blockProcessing = true;
1804     QString autoscriptFile = getFreeScriptName("auto");
1805     QFile file(autoscriptFile);
1806     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1807         kWarning() << "//////  ERROR writing to file: " << autoscriptFile;
1808         KMessageBox::error(0, i18n("Cannot write to file %1", autoscriptFile));
1809         return false;
1810     }
1811
1812     QTextStream outStream(&file);
1813     outStream << "#! /bin/sh" << "\n" << "\n";
1814     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
1815     while (item) {
1816         if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
1817             if (item->data(1, Qt::UserRole + 4).isNull()) {
1818                 // Add render process for item
1819                 const QString params = item->data(1, Qt::UserRole + 3).toStringList().join(" ");
1820                 outStream << m_renderer << " " << params << "\n";
1821             } else {
1822                 // Script item
1823                 outStream << item->data(1, Qt::UserRole + 3).toString() << "\n";
1824             }
1825         }
1826         item = m_view.running_jobs->itemBelow(item);
1827     }
1828     // erase itself when rendering is finished
1829     outStream << "rm " << autoscriptFile << "\n" << "\n";
1830     if (file.error() != QFile::NoError) {
1831         KMessageBox::error(0, i18n("Cannot write to file %1", autoscriptFile));
1832         file.close();
1833         m_blockProcessing = false;
1834         return false;
1835     }
1836     file.close();
1837     QFile::setPermissions(autoscriptFile, file.permissions() | QFile::ExeUser);
1838     QProcess::startDetached(autoscriptFile, QStringList());
1839     return true;
1840 }
1841
1842 QString RenderWidget::getFreeScriptName(const QString &prefix)
1843 {
1844     int ix = 0;
1845     QString scriptsFolder = m_projectFolder + "scripts/";
1846     KStandardDirs::makeDir(scriptsFolder);
1847     QString path;
1848     while (path.isEmpty() || QFile::exists(path)) {
1849         ix++;
1850         path = scriptsFolder + prefix + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
1851     }
1852     return path;
1853 }
1854
1855 void RenderWidget::slotPlayRendering(QTreeWidgetItem *item, int)
1856 {
1857     if (KdenliveSettings::defaultplayerapp().isEmpty() || item->data(1, Qt::UserRole + 2).toInt() != FINISHEDJOB) return;
1858     const QByteArray startId = KStartupInfo::createNewStartupId();
1859     const QString command = KdenliveSettings::defaultplayerapp() + ' ' + item->text(1);
1860     KRun::runCommand(command, KdenliveSettings::defaultplayerapp(), KdenliveSettings::defaultplayerapp(), this, startId);
1861 }
1862
1863 void RenderWidget::missingClips(bool hasMissing)
1864 {
1865     if (hasMissing) {
1866         m_view.errorLabel->setText(i18n("Check missing clips"));
1867         m_view.errorBox->setHidden(false);
1868     } else m_view.errorBox->setHidden(true);
1869 }
1870
1871 void RenderWidget::slotUpdateEncodeThreads(int val)
1872 {
1873         KdenliveSettings::setEncodethreads(val);
1874 }
1875
1876 void RenderWidget::slotUpdateRescaleWidth(int val)
1877 {
1878     KdenliveSettings::setDefaultrescalewidth(val);
1879     if (!m_view.rescale_keep->isChecked()) return;
1880     m_view.rescale_height->blockSignals(true);
1881     m_view.rescale_height->setValue(val * m_profile.height / m_profile.width  + 0.5);
1882     KdenliveSettings::setDefaultrescaleheight(m_view.rescale_height->value());
1883     m_view.rescale_height->blockSignals(false);
1884 }
1885
1886 void RenderWidget::slotUpdateRescaleHeight(int val)
1887 {
1888     KdenliveSettings::setDefaultrescaleheight(val);
1889     if (!m_view.rescale_keep->isChecked()) return;
1890     m_view.rescale_width->blockSignals(true);
1891     m_view.rescale_width->setValue(val * m_profile.width / m_profile.height + 0.5);
1892     KdenliveSettings::setDefaultrescaleheight(m_view.rescale_width->value());
1893     m_view.rescale_width->blockSignals(false);
1894 }
1895
1896 void RenderWidget::slotSwitchAspectRatio()
1897 {
1898     KdenliveSettings::setRescalekeepratio(m_view.rescale_keep->isChecked());
1899     if (m_view.rescale_keep->isChecked()) slotUpdateRescaleWidth(m_view.rescale_width->value());
1900 }
1901
1902 void RenderWidget::slotUpdateAudioLabel(int ix)
1903 {
1904     if (ix == Qt::PartiallyChecked)
1905         m_view.export_audio->setText(i18n("Export audio (automatic)"));
1906     else
1907         m_view.export_audio->setText(i18n("Export audio"));
1908 }
1909
1910 bool RenderWidget::automaticAudioExport() const
1911 {
1912     return (m_view.export_audio->checkState() == Qt::PartiallyChecked);
1913 }
1914
1915 bool RenderWidget::selectedAudioExport() const
1916 {
1917     return (m_view.export_audio->checkState() != Qt::Unchecked);
1918 }
1919
1920 void RenderWidget::updateProxyConfig(bool enable)
1921 {
1922     m_view.proxy_render->setHidden(!enable);
1923 }
1924
1925 bool RenderWidget::proxyRendering()
1926 {
1927     return m_view.proxy_render->isChecked();
1928 }