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