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