]> git.sesse.net Git - kdenlive/blob - src/renderwidget.cpp
Update to the new MLT structure (based on patch by Dan Dennedy)
[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
25 #include <KStandardDirs>
26 #include <KDebug>
27 #include <KMessageBox>
28 #include <KComboBox>
29 #include <KRun>
30 #include <KIO/NetAccess>
31 // #include <knewstuff2/engine.h>
32
33 #include <QDomDocument>
34 #include <QItemDelegate>
35 #include <QTreeWidgetItem>
36 #include <QListWidgetItem>
37 #include <QHeaderView>
38 #include <QMenu>
39 #include <QProcess>
40 #include <QInputDialog>
41
42 const int GroupRole = Qt::UserRole;
43 const int ExtensionRole = GroupRole + 1;
44 const int StandardRole = GroupRole + 2;
45 const int RenderRole = GroupRole + 3;
46 const int ParamsRole = GroupRole + 4;
47 const int EditableRole = GroupRole + 5;
48 const int MetaGroupRole = GroupRole + 6;
49 const int ExtraRole = GroupRole + 7;
50
51 // Running job status
52 const int WAITINGJOB = 0;
53 const int RUNNINGJOB = 1;
54 const int FINISHEDJOB = 2;
55
56
57 RenderWidget::RenderWidget(const QString &projectfolder, QWidget * parent) :
58         QDialog(parent),
59         m_projectFolder(projectfolder)
60 {
61     m_view.setupUi(this);
62     setWindowTitle(i18n("Rendering"));
63     m_view.buttonDelete->setIcon(KIcon("trash-empty"));
64     m_view.buttonDelete->setToolTip(i18n("Delete profile"));
65     m_view.buttonDelete->setEnabled(false);
66
67     m_view.buttonEdit->setIcon(KIcon("document-properties"));
68     m_view.buttonEdit->setToolTip(i18n("Edit profile"));
69     m_view.buttonEdit->setEnabled(false);
70
71     m_view.buttonSave->setIcon(KIcon("document-new"));
72     m_view.buttonSave->setToolTip(i18n("Create new profile"));
73
74     m_view.buttonInfo->setIcon(KIcon("help-about"));
75     m_view.hide_log->setIcon(KIcon("go-down"));
76
77     if (KdenliveSettings::showrenderparams()) {
78         m_view.buttonInfo->setDown(true);
79     } else m_view.advanced_params->hide();
80
81     m_view.rescale_size->setInputMask("0099\\x0099");
82     m_view.rescale_size->setText("320x240");
83
84
85     QMenu *renderMenu = new QMenu(i18n("Start Rendering"), this);
86     QAction *renderAction = renderMenu->addAction(KIcon("video-x-generic"), i18n("Render to File"));
87     connect(renderAction, SIGNAL(triggered()), this, SLOT(slotExport()));
88     QAction *scriptAction = renderMenu->addAction(KIcon("application-x-shellscript"), i18n("Generate Script"));
89     connect(scriptAction, SIGNAL(triggered()), this, SLOT(slotGenerateScript()));
90
91     m_view.buttonStart->setMenu(renderMenu);
92     m_view.buttonStart->setPopupMode(QToolButton::MenuButtonPopup);
93     m_view.buttonStart->setDefaultAction(renderAction);
94     m_view.buttonStart->setToolButtonStyle(Qt::ToolButtonTextOnly);
95     m_view.abort_job->setEnabled(false);
96     m_view.start_script->setEnabled(false);
97     m_view.delete_script->setEnabled(false);
98
99     m_view.format_list->setAlternatingRowColors(true);
100     m_view.size_list->setAlternatingRowColors(true);
101
102     parseProfiles();
103     parseScriptFiles();
104
105     connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
106     connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
107     connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
108     connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
109
110     connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));
111
112     connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
113     connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
114     connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
115     connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
116     connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
117     connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));
118
119     connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
120     connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
121     connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
122     connect(m_view.rescale, SIGNAL(toggled(bool)), m_view.rescale_size, SLOT(setEnabled(bool)));
123     connect(m_view.destination_list, SIGNAL(activated(int)), this, SLOT(refreshView()));
124     connect(m_view.out_file, SIGNAL(textChanged(const QString &)), this, SLOT(slotUpdateButtons()));
125     connect(m_view.out_file, SIGNAL(urlSelected(const KUrl &)), this, SLOT(slotUpdateButtons(const KUrl &)));
126     connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
127     connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
128
129     connect(m_view.size_list, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotEditItem(QListWidgetItem *)));
130
131     connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
132     connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
133     connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
134
135     connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
136     connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));
137
138     connect(m_view.format_selection, SIGNAL(activated(int)), this, SLOT(refreshView()));
139
140     m_view.buttonStart->setEnabled(false);
141     m_view.rescale_size->setEnabled(false);
142     m_view.guides_box->setVisible(false);
143     m_view.open_dvd->setVisible(false);
144     m_view.create_chapter->setVisible(false);
145     m_view.open_browser->setVisible(false);
146     m_view.error_box->setVisible(false);
147
148     m_view.splitter->setStretchFactor(1, 5);
149     m_view.splitter->setStretchFactor(0, 2);
150
151     m_view.out_file->setMode(KFile::File);
152
153     m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File") << i18n("Progress"));
154     m_view.running_jobs->setItemDelegate(new RenderViewDelegate(this));
155
156     QHeaderView *header = m_view.running_jobs->header();
157     QFontMetrics fm = fontMetrics();
158     //header->resizeSection(0, fm.width("typical-name-for-a-torrent.torrent"));
159     header->setResizeMode(0, QHeaderView::Fixed);
160     header->resizeSection(0, 30);
161     header->setResizeMode(1, QHeaderView::Interactive);
162     header->resizeSection(1, fm.width("typical-name-for-a-file.torrent"));
163     header->setResizeMode(2, QHeaderView::Fixed);
164     header->resizeSection(1, width() * 2 / 3);
165     header->setResizeMode(2, QHeaderView::Interactive);
166     //header->setResizeMode(1, QHeaderView::Fixed);
167
168     m_view.scripts_list->setHeaderLabels(QStringList() << i18n("Script Files"));
169     m_view.scripts_list->setItemDelegate(new RenderScriptDelegate(this));
170
171
172     focusFirstVisibleItem();
173 }
174
175 void RenderWidget::slotEditItem(QListWidgetItem *item)
176 {
177     QString edit = item->data(EditableRole).toString();
178     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) slotSaveProfile();
179     else slotEditProfile();
180 }
181
182 void RenderWidget::showInfoPanel()
183 {
184     if (m_view.advanced_params->isVisible()) {
185         m_view.advanced_params->setVisible(false);
186         m_view.buttonInfo->setDown(false);
187         KdenliveSettings::setShowrenderparams(false);
188     } else {
189         m_view.advanced_params->setVisible(true);
190         m_view.buttonInfo->setDown(true);
191         KdenliveSettings::setShowrenderparams(true);
192     }
193 }
194
195 void RenderWidget::setDocumentPath(const QString path)
196 {
197     m_projectFolder = path;
198     const QString fileName = m_view.out_file->url().fileName();
199     m_view.out_file->setUrl(KUrl(m_projectFolder + '/' + fileName));
200     parseScriptFiles();
201 }
202
203 void RenderWidget::slotUpdateGuideBox()
204 {
205     m_view.guides_box->setVisible(m_view.render_guide->isChecked());
206 }
207
208 void RenderWidget::slotCheckStartGuidePosition()
209 {
210     if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
211         m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
212 }
213
214 void RenderWidget::slotCheckEndGuidePosition()
215 {
216     if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
217         m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
218 }
219
220 void RenderWidget::setGuides(QDomElement guidesxml, double duration)
221 {
222     m_view.guide_start->clear();
223     m_view.guide_end->clear();
224     QDomNodeList nodes = guidesxml.elementsByTagName("guide");
225     if (nodes.count() > 0) {
226         m_view.guide_start->addItem(i18n("Render"), "0");
227         m_view.render_guide->setEnabled(true);
228         m_view.create_chapter->setEnabled(true);
229     } else {
230         m_view.render_guide->setEnabled(false);
231         m_view.create_chapter->setEnabled(false);
232     }
233     for (int i = 0; i < nodes.count(); i++) {
234         QDomElement e = nodes.item(i).toElement();
235         if (!e.isNull()) {
236             m_view.guide_start->addItem(e.attribute("comment"), e.attribute("time").toDouble());
237             m_view.guide_end->addItem(e.attribute("comment"), e.attribute("time").toDouble());
238         }
239     }
240     if (nodes.count() > 0)
241         m_view.guide_end->addItem(i18n("End"), QString::number(duration));
242 }
243
244 // Will be called when the user selects an output file via the file dialog.
245 // File extension will be added automatically.
246 void RenderWidget::slotUpdateButtons(KUrl url)
247 {
248     if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
249     else m_view.buttonStart->setEnabled(true);
250     if (url != 0) {
251         QListWidgetItem *item = m_view.size_list->currentItem();
252         QString extension = item->data(ExtensionRole).toString();
253         url = filenameWithExtension(url, extension);
254         m_view.out_file->setUrl(url);
255     }
256 }
257
258 // Will be called when the user changes the output file path in the text line.
259 // File extension must NOT be added, would make editing impossible!
260 void RenderWidget::slotUpdateButtons()
261 {
262     if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
263     else m_view.buttonStart->setEnabled(true);
264 }
265
266 void RenderWidget::slotSaveProfile()
267 {
268     //TODO: update to correctly use metagroups
269     Ui::SaveProfile_UI ui;
270     QDialog *d = new QDialog(this);
271     ui.setupUi(d);
272
273     for (int i = 0; i < m_view.destination_list->count(); i++)
274         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
275
276     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
277     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
278
279     QString customGroup = m_view.format_list->currentItem()->text();
280     if (customGroup.isEmpty()) customGroup = i18n("Custom");
281     ui.group_name->setText(customGroup);
282
283     ui.parameters->setText(m_view.advanced_params->toPlainText());
284     ui.extension->setText(m_view.size_list->currentItem()->data(ExtensionRole).toString());
285     ui.profile_name->setFocus();
286     if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
287         QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
288         QDomDocument doc;
289         QFile file(exportFile);
290         doc.setContent(&file, false);
291         file.close();
292         QDomElement documentElement;
293         QDomElement profiles = doc.documentElement();
294         if (profiles.isNull() || profiles.tagName() != "profiles") {
295             doc.clear();
296             profiles = doc.createElement("profiles");
297             profiles.setAttribute("version", 1);
298             doc.appendChild(profiles);
299         }
300         int version = profiles.attribute("version", 0).toInt();
301         if (version < 1) {
302             kDebug() << "// OLD profile version";
303             doc.clear();
304             profiles = doc.createElement("profiles");
305             profiles.setAttribute("version", 1);
306             doc.appendChild(profiles);
307         }
308
309         QString newProfileName = ui.profile_name->text().simplified();
310         QString newGroupName = ui.group_name->text().simplified();
311         if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
312         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
313         QDomNodeList profilelist = doc.elementsByTagName("profile");
314         int i = 0;
315         while (!profilelist.item(i).isNull()) {
316             // make sure a profile with same name doesn't exist
317             documentElement = profilelist.item(i).toElement();
318             QString profileName = documentElement.attribute("name");
319             if (profileName == newProfileName) {
320                 // a profile with that same name already exists
321                 bool ok;
322                 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);
323                 if (!ok) return;
324                 if (profileName == newProfileName) {
325                     profiles.removeChild(profilelist.item(i));
326                     break;
327                 }
328             }
329             i++;
330         }
331
332         QDomElement profileElement = doc.createElement("profile");
333         profileElement.setAttribute("name", newProfileName);
334         profileElement.setAttribute("category", newGroupName);
335         profileElement.setAttribute("destinationid", newMetaGroupId);
336         profileElement.setAttribute("extension", ui.extension->text().simplified());
337         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
338         profiles.appendChild(profileElement);
339
340         //QCString save = doc.toString().utf8();
341
342         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
343             KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
344             delete d;
345             return;
346         }
347         QTextStream out(&file);
348         out << doc.toString();
349         if (file.error() != QFile::NoError) {
350             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
351             file.close();
352             delete d;
353             return;
354         }
355         file.close();
356         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
357     }
358     delete d;
359 }
360
361 void RenderWidget::slotEditProfile()
362 {
363     QListWidgetItem *item = m_view.size_list->currentItem();
364     if (!item) return;
365     QString currentGroup = m_view.format_list->currentItem()->text();
366
367     QString params = item->data(ParamsRole).toString();
368     QString extension = item->data(ExtensionRole).toString();
369     QString currentProfile = item->text();
370
371     Ui::SaveProfile_UI ui;
372     QDialog *d = new QDialog(this);
373     ui.setupUi(d);
374
375     for (int i = 0; i < m_view.destination_list->count(); i++)
376         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
377
378     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
379     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
380
381     QString customGroup = m_view.format_list->currentItem()->text();
382     if (customGroup.isEmpty()) customGroup = i18n("Custom");
383     ui.group_name->setText(customGroup);
384
385     ui.profile_name->setText(currentProfile);
386     ui.extension->setText(extension);
387     ui.parameters->setText(params);
388     ui.profile_name->setFocus();
389     d->setWindowTitle(i18n("Edit Profile"));
390     if (d->exec() == QDialog::Accepted) {
391         slotDeleteProfile(false);
392         QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
393         QDomDocument doc;
394         QFile file(exportFile);
395         doc.setContent(&file, false);
396         file.close();
397         QDomElement documentElement;
398         QDomElement profiles = doc.documentElement();
399
400         if (profiles.isNull() || profiles.tagName() != "profiles") {
401             doc.clear();
402             profiles = doc.createElement("profiles");
403             profiles.setAttribute("version", 1);
404             doc.appendChild(profiles);
405         }
406
407         int version = profiles.attribute("version", 0).toInt();
408         if (version < 1) {
409             kDebug() << "// OLD profile version";
410             doc.clear();
411             profiles = doc.createElement("profiles");
412             profiles.setAttribute("version", 1);
413             doc.appendChild(profiles);
414         }
415
416         QString newProfileName = ui.profile_name->text().simplified();
417         QString newGroupName = ui.group_name->text().simplified();
418         if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
419         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
420         QDomNodeList profilelist = doc.elementsByTagName("profile");
421         int i = 0;
422         while (!profilelist.item(i).isNull()) {
423             // make sure a profile with same name doesn't exist
424             documentElement = profilelist.item(i).toElement();
425             QString profileName = documentElement.attribute("name");
426             if (profileName == newProfileName) {
427                 // a profile with that same name already exists
428                 bool ok;
429                 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);
430                 if (!ok) return;
431                 if (profileName == newProfileName) {
432                     profiles.removeChild(profilelist.item(i));
433                     break;
434                 }
435             }
436             i++;
437         }
438
439         QDomElement profileElement = doc.createElement("profile");
440         profileElement.setAttribute("name", newProfileName);
441         profileElement.setAttribute("category", newGroupName);
442         profileElement.setAttribute("destinationid", newMetaGroupId);
443         profileElement.setAttribute("extension", ui.extension->text().simplified());
444         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
445         profiles.appendChild(profileElement);
446
447         //QCString save = doc.toString().utf8();
448         delete d;
449         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
450             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
451             return;
452         }
453         QTextStream out(&file);
454         out << doc.toString();
455         if (file.error() != QFile::NoError) {
456             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
457             file.close();
458             return;
459         }
460         file.close();
461         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
462     } else delete d;
463 }
464
465 void RenderWidget::slotDeleteProfile(bool refresh)
466 {
467     //TODO: delete a profile installed by KNewStuff the easy way
468     /*
469     QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
470     if (!edit.endsWith("customprofiles.xml")) {
471         // This is a KNewStuff installed file, process through KNS
472         KNS::Engine engine(0);
473         if (engine.init("kdenlive_render.knsrc")) {
474             KNS::Entry::List entries;
475         }
476         return;
477     }*/
478     QString currentGroup = m_view.format_list->currentItem()->text();
479     QString currentProfile = m_view.size_list->currentItem()->text();
480     QString metaGroupId = m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString();
481
482     QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
483     QDomDocument doc;
484     QFile file(exportFile);
485     doc.setContent(&file, false);
486     file.close();
487
488     QDomElement documentElement;
489     QDomNodeList profiles = doc.elementsByTagName("profile");
490     int i = 0;
491     QString groupName;
492     QString profileName;
493     QString destination;
494
495     while (!profiles.item(i).isNull()) {
496         documentElement = profiles.item(i).toElement();
497         profileName = documentElement.attribute("name");
498         groupName = documentElement.attribute("category");
499         destination = documentElement.attribute("destinationid");
500
501         if (profileName == currentProfile && groupName == currentGroup && destination == metaGroupId) {
502             kDebug() << "// GOT it: " << profileName;
503             doc.documentElement().removeChild(profiles.item(i));
504             break;
505         }
506         i++;
507     }
508
509     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
510         KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
511         return;
512     }
513     QTextStream out(&file);
514     out << doc.toString();
515     if (file.error() != QFile::NoError) {
516         KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
517         file.close();
518         return;
519     }
520     file.close();
521     if (refresh) {
522         parseProfiles(metaGroupId, currentGroup);
523         focusFirstVisibleItem();
524     }
525 }
526
527 void RenderWidget::updateButtons()
528 {
529     if (!m_view.size_list->currentItem() || m_view.size_list->currentItem()->isHidden()) {
530         m_view.buttonSave->setEnabled(false);
531         m_view.buttonDelete->setEnabled(false);
532         m_view.buttonEdit->setEnabled(false);
533         m_view.buttonStart->setEnabled(false);
534     } else {
535         m_view.buttonSave->setEnabled(true);
536         m_view.buttonStart->setEnabled(m_view.size_list->currentItem()->flags() & Qt::ItemIsEnabled);
537         QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
538         if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
539             m_view.buttonDelete->setEnabled(false);
540             m_view.buttonEdit->setEnabled(false);
541         } else {
542             m_view.buttonDelete->setEnabled(true);
543             m_view.buttonEdit->setEnabled(true);
544         }
545     }
546 }
547
548
549 void RenderWidget::focusFirstVisibleItem()
550 {
551     if (m_view.size_list->currentItem() && !m_view.size_list->currentItem()->isHidden()) {
552         updateButtons();
553         return;
554     }
555     for (int ix = 0; ix < m_view.size_list->count(); ix++) {
556         QListWidgetItem *item = m_view.size_list->item(ix);
557         if (item && !item->isHidden()) {
558             m_view.size_list->setCurrentRow(ix);
559             break;
560         }
561     }
562     if (!m_view.size_list->currentItem()) m_view.size_list->setCurrentRow(0);
563     updateButtons();
564 }
565
566 void RenderWidget::slotExport(bool scriptExport)
567 {
568     QListWidgetItem *item = m_view.size_list->currentItem();
569     if (!item) return;
570
571     const QString dest = m_view.out_file->url().path();
572     if (dest.isEmpty()) return;
573     QFile f(dest);
574     if (f.exists()) {
575         if (KMessageBox::warningYesNo(this, i18n("Output file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
576             return;
577     }
578
579     QString scriptName;
580     if (scriptExport) {
581         bool ok;
582         int ix = 0;
583         QString scriptsFolder = m_projectFolder + "/scripts/";
584         KStandardDirs::makeDir(scriptsFolder);
585         QString path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
586         while (QFile::exists(path)) {
587             ix++;
588             path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
589         }
590         scriptName = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
591         if (!ok || scriptName.isEmpty()) return;
592         scriptName.prepend(scriptsFolder);
593         QFile f(scriptName);
594         if (f.exists()) {
595             if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
596                 return;
597         }
598     }
599
600     QStringList overlayargs;
601     if (m_view.tc_overlay->isChecked()) {
602         QString filterFile = KStandardDirs::locate("appdata", "metadata.properties");
603         overlayargs << "meta.attr.timecode=1" << "meta.attr.timecode.markup=#timecode";
604         overlayargs << "-attach" << "data_feed:attr_check" << "-attach";
605         overlayargs << "data_show:" + filterFile << "_loader=1" << "dynamic=1";
606     }
607     double startPos = -1;
608     double endPos = -1;
609     if (m_view.render_guide->isChecked()) {
610         startPos = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
611         endPos = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
612     }
613     QString renderArgs = m_view.advanced_params->toPlainText().simplified();
614
615     // Adjust frame scale
616     int width;
617     int height;
618     if (m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
619         width = m_view.rescale_size->text().section('x', 0, 0).toInt();
620         height = m_view.rescale_size->text().section('x', 1, 1).toInt();
621     } else {
622         width = m_profile.width;
623         height = m_profile.height;
624     }
625     renderArgs.replace("%dar", '@' + QString::number(m_profile.display_aspect_num) + '/' + QString::number(m_profile.display_aspect_den));
626
627     // Adjust scanning
628     if (m_view.scanning_list->currentIndex() == 1) renderArgs.append(" progressive=1");
629     else if (m_view.scanning_list->currentIndex() == 2) renderArgs.append(" progressive=0");
630
631     // disable audio if requested
632     if (!m_view.export_audio->isChecked())
633         renderArgs.append(" an=1 ");
634
635     // Check if the rendering profile is different from project profile,
636     // in which case we need to use the producer_comsumer from MLT
637     bool resizeProfile = false;
638
639     QString std = renderArgs;
640     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
641     if (std.startsWith("s=")) {
642         QString subsize = std.section(' ', 0, 0).toLower();
643         subsize = subsize.section("=", 1, 1);
644         const QString currentSize = QString::number(width) + 'x' + QString::number(height);
645         if (subsize != currentSize) resizeProfile = true;
646     } else if (std.contains(" s=")) {
647         QString subsize = std.section(" s=", 1, 1);
648         subsize = subsize.section(' ', 0, 0).toLower();
649         const QString currentSize = QString::number(width) + 'x' + QString::number(height);
650         if (subsize != currentSize) resizeProfile = true;
651     } else if (destination != "audioonly") {
652         // Add current size parametrer
653         renderArgs.append(QString(" s=%1x%2").arg(width).arg(height));
654     }
655
656     // insert item in running jobs list
657     QTreeWidgetItem *renderItem;
658     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
659     if (!existing.isEmpty()) {
660         renderItem = existing.at(0);
661         if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
662             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"));
663             return;
664         }
665     } else {
666         renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
667         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
668         renderItem->setIcon(0, KIcon("media-playback-pause"));
669         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
670     }
671     renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
672     renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
673     renderItem->setData(1, Qt::UserRole + 2, overlayargs);
674     QStringList renderParameters;
675     renderParameters << dest << item->data(RenderRole).toString() << renderArgs.simplified();
676     renderParameters << QString::number(m_view.render_zone->isChecked()) << QString::number(m_view.play_after->isChecked());
677     renderParameters << QString::number(startPos) << QString::number(endPos) << QString::number(resizeProfile);
678     renderParameters << scriptName;
679
680     // Set rendering type
681     QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
682     if (group == "dvd") {
683         renderParameters << QString::number(m_view.create_chapter->isChecked());
684         if (m_view.open_dvd->isChecked()) {
685             renderItem->setData(0, Qt::UserRole, group);
686             if (renderArgs.contains("profile=")) {
687                 // rendering profile contains an MLT profile, so pass it to the running jog item, useful for dvd
688                 QString prof = renderArgs.section("profile=", 1, 1);
689                 prof = prof.section(' ', 0, 0);
690                 kDebug() << "// render profile: " << prof;
691                 renderItem->setData(0, Qt::UserRole + 1, prof);
692             }
693         }
694     } else {
695         renderParameters << QString::number(false);
696         if (group == "websites" && m_view.open_browser->isChecked()) {
697             renderItem->setData(0, Qt::UserRole, group);
698             // pass the url
699             QString url = m_view.size_list->currentItem()->data(ExtraRole).toString();
700             renderItem->setData(0, Qt::UserRole + 1, url);
701         }
702     }
703
704
705     renderItem->setData(1, Qt::UserRole + 3, renderParameters);
706
707     checkRenderStatus();
708     if (scriptName.isEmpty()) m_view.tabWidget->setCurrentIndex(1);
709     else {
710         QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
711         m_view.tabWidget->setCurrentIndex(2);
712     }
713 }
714
715 void RenderWidget::checkRenderStatus()
716 {
717     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
718     while (item) {
719         if (item->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) break;
720         else if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
721             item->setData(1, Qt::UserRole + 1, QTime::currentTime());
722             if (item->data(1, Qt::UserRole + 4).isNull())
723                 emit doRender(item->data(1, Qt::UserRole + 3).toStringList(), item->data(1, Qt::UserRole + 2).toStringList());
724             else QProcess::startDetached(item->data(1, Qt::UserRole + 3).toString());
725             break;
726         }
727         item = m_view.running_jobs->itemBelow(item);
728     }
729 }
730
731 void RenderWidget::setProfile(MltVideoProfile profile)
732 {
733     m_profile = profile;
734     //WARNING: this way to tell the video standard is a bit hackish...
735     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);
736     else m_view.format_selection->setCurrentIndex(1);
737     m_view.scanning_list->setCurrentIndex(0);
738     refreshView();
739 }
740
741 void RenderWidget::refreshView()
742 {
743     m_view.size_list->blockSignals(true);
744     QListWidgetItem *sizeItem;
745
746     QString destination;
747     KIcon brokenIcon("dialog-close");
748     if (m_view.destination_list->currentIndex() > 0)
749         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
750
751
752     if (destination == "dvd") {
753         m_view.open_dvd->setVisible(true);
754         m_view.create_chapter->setVisible(true);
755     } else {
756         m_view.open_dvd->setVisible(false);
757         m_view.create_chapter->setVisible(false);
758     }
759     if (destination == "websites") m_view.open_browser->setVisible(true);
760     else m_view.open_browser->setVisible(false);
761     if (!destination.isEmpty() && QString("dvd websites audioonly").contains(destination))
762         m_view.rescale->setEnabled(false);
763     else m_view.rescale->setEnabled(true);
764     // hide groups that are not in the correct destination
765     for (int i = 0; i < m_view.format_list->count(); i++) {
766         sizeItem = m_view.format_list->item(i);
767         if (sizeItem->data(MetaGroupRole).toString() == destination) {
768             sizeItem->setHidden(false);
769             //kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
770         } else sizeItem->setHidden(true);
771     }
772
773     // activate first visible item
774     QListWidgetItem * item = m_view.format_list->currentItem();
775     if (!item || item->isHidden()) {
776         for (int i = 0; i < m_view.format_list->count(); i++) {
777             if (!m_view.format_list->item(i)->isHidden()) {
778                 m_view.format_list->setCurrentRow(i);
779                 break;
780             }
781         }
782         item = m_view.format_list->currentItem();
783     }
784     if (!item || item->isHidden()) {
785         m_view.format_list->setEnabled(false);
786         m_view.size_list->setEnabled(false);
787         return;
788     } else {
789         m_view.format_list->setEnabled(true);
790         m_view.size_list->setEnabled(true);
791     }
792     int count = 0;
793     for (int i = 0; i < m_view.format_list->count() && count < 2; i++) {
794         if (!m_view.format_list->isRowHidden(i)) count++;
795     }
796     if (count > 1) m_view.format_list->setVisible(true);
797     else m_view.format_list->setVisible(false);
798     QString std;
799     QString group = item->text();
800     bool firstSelected = false;
801     const QStringList formatsList = KdenliveSettings::supportedformats();
802     const QStringList vcodecsList = KdenliveSettings::videocodecs();
803     const QStringList acodecsList = KdenliveSettings::audiocodecs();
804
805     for (int i = 0; i < m_view.size_list->count(); i++) {
806         sizeItem = m_view.size_list->item(i);
807         if ((sizeItem->data(GroupRole) == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole) == destination) {
808             std = sizeItem->data(StandardRole).toString();
809             if (!std.isEmpty()) {
810                 if (std.contains("PAL", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 0);
811                 else if (std.contains("NTSC", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 1);
812             } else {
813                 sizeItem->setHidden(false);
814                 if (!firstSelected) m_view.size_list->setCurrentItem(sizeItem);
815                 firstSelected = true;
816             }
817
818             if (!sizeItem->isHidden()) {
819                 // Make sure the selected profile uses an installed avformat codec / format
820                 std = sizeItem->data(ParamsRole).toString();
821
822                 if (!formatsList.isEmpty()) {
823                     QString format;
824                     if (std.startsWith("f=")) format = std.section("f=", 1, 1);
825                     else if (std.contains(" f=")) format = std.section(" f=", 1, 1);
826                     if (!format.isEmpty()) {
827                         format = format.section(' ', 0, 0).toLower();
828                         if (!formatsList.contains(format)) {
829                             kDebug() << "***** UNSUPPORTED F: " << format;
830                             //sizeItem->setHidden(true);
831                             sizeItem->setFlags(Qt::ItemIsSelectable);
832                             sizeItem->setToolTip(i18n("Unsupported video format: %1", format));
833                             sizeItem->setIcon(brokenIcon);
834                         }
835                     }
836                 }
837                 if (!acodecsList.isEmpty() && !sizeItem->isHidden()) {
838                     QString format;
839                     if (std.startsWith("acodec=")) format = std.section("acodec=", 1, 1);
840                     else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
841                     if (!format.isEmpty()) {
842                         format = format.section(' ', 0, 0).toLower();
843                         if (!acodecsList.contains(format)) {
844                             kDebug() << "*****  UNSUPPORTED ACODEC: " << format;
845                             //sizeItem->setHidden(true);
846                             sizeItem->setFlags(Qt::ItemIsSelectable);
847                             sizeItem->setToolTip(i18n("Unsupported audio codec: %1", format));
848                             sizeItem->setIcon(brokenIcon);
849                         }
850                     }
851                 }
852                 if (!vcodecsList.isEmpty() && !sizeItem->isHidden()) {
853                     QString format;
854                     if (std.startsWith("vcodec=")) format = std.section("vcodec=", 1, 1);
855                     else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
856                     if (!format.isEmpty()) {
857                         format = format.section(' ', 0, 0).toLower();
858                         if (!vcodecsList.contains(format)) {
859                             kDebug() << "*****  UNSUPPORTED VCODEC: " << format;
860                             //sizeItem->setHidden(true);
861                             sizeItem->setFlags(Qt::ItemIsSelectable);
862                             sizeItem->setToolTip(i18n("Unsupported video codec: %1", format));
863                             sizeItem->setIcon(brokenIcon);
864                         }
865                     }
866                 }
867             }
868         } else sizeItem->setHidden(true);
869     }
870     focusFirstVisibleItem();
871     m_view.size_list->blockSignals(false);
872     refreshParams();
873 }
874
875 KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension)
876 {
877     QString path;
878     if (!url.isEmpty()) {
879         path = url.path();
880         int pos = path.lastIndexOf('.') + 1;
881         if (pos == 0) path.append('.' + extension);
882         else path = path.left(pos) + extension;
883
884     } else {
885         path = m_projectFolder + "/untitled." + extension;
886     }
887     return KUrl(path);
888 }
889
890
891 void RenderWidget::refreshParams()
892 {
893     QListWidgetItem *item = m_view.size_list->currentItem();
894     if (!item || item->isHidden()) {
895         m_view.advanced_params->clear();
896         m_view.buttonStart->setEnabled(false);
897         return;
898     }
899     QString params = item->data(ParamsRole).toString();
900     QString extension = item->data(ExtensionRole).toString();
901     m_view.advanced_params->setPlainText(params);
902     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
903     if (params.contains(" s=") || destination == "audioonly") {
904         // profile has a fixed size, do not allow resize
905         m_view.rescale->setEnabled(false);
906         m_view.rescale_size->setEnabled(false);
907     } else {
908         m_view.rescale->setEnabled(true);
909         m_view.rescale_size->setEnabled(true);
910     }
911     KUrl url = filenameWithExtension(m_view.out_file->url(), extension);
912     m_view.out_file->setUrl(url);
913 //     if (!url.isEmpty()) {
914 //         QString path = url.path();
915 //         int pos = path.lastIndexOf('.') + 1;
916 //  if (pos == 0) path.append('.' + extension);
917 //         else path = path.left(pos) + extension;
918 //         m_view.out_file->setUrl(KUrl(path));
919 //     } else {
920 //         m_view.out_file->setUrl(KUrl(QDir::homePath() + "/untitled." + extension));
921 //     }
922     m_view.out_file->setFilter("*." + extension);
923     QString edit = item->data(EditableRole).toString();
924     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
925         m_view.buttonDelete->setEnabled(false);
926         m_view.buttonEdit->setEnabled(false);
927     } else {
928         m_view.buttonDelete->setEnabled(true);
929         m_view.buttonEdit->setEnabled(true);
930     }
931
932     m_view.buttonStart->setEnabled(m_view.size_list->currentItem()->flags() & Qt::ItemIsEnabled);
933 }
934
935 void RenderWidget::reloadProfiles()
936 {
937     parseProfiles();
938 }
939
940 void RenderWidget::parseProfiles(QString meta, QString group, QString profile)
941 {
942     m_view.size_list->clear();
943     m_view.format_list->clear();
944     m_view.destination_list->clear();
945     m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
946     m_view.destination_list->addItem(KIcon("media-optical"), i18n("DVD"), "dvd");
947     m_view.destination_list->addItem(KIcon("audio-x-generic"), i18n("Audio only"), "audioonly");
948     m_view.destination_list->addItem(KIcon("applications-internet"), i18n("Web sites"), "websites");
949     m_view.destination_list->addItem(KIcon("applications-multimedia"), i18n("Media players"), "mediaplayers");
950     m_view.destination_list->addItem(KIcon("drive-harddisk"), i18n("Lossless / HQ"), "lossless");
951     m_view.destination_list->addItem(KIcon("pda"), i18n("Mobile devices"), "mobile");
952
953     QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
954     parseFile(exportFile, false);
955
956
957     QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
958     QDir directory = QDir(exportFolder);
959     QStringList filter;
960     filter << "*.xml";
961     QStringList fileList = directory.entryList(filter, QDir::Files);
962     // We should parse customprofiles.xml in last position, so that user profiles
963     // can also override profiles installed by KNewStuff
964     fileList.removeAll("customprofiles.xml");
965     foreach(const QString &filename, fileList)
966     parseFile(exportFolder + '/' + filename, true);
967     if (QFile::exists(exportFolder + "/customprofiles.xml")) parseFile(exportFolder + "/customprofiles.xml", true);
968
969     if (!meta.isEmpty()) {
970         m_view.destination_list->blockSignals(true);
971         m_view.destination_list->setCurrentIndex(m_view.destination_list->findData(meta));
972         m_view.destination_list->blockSignals(false);
973     }
974     refreshView();
975     QList<QListWidgetItem *> child;
976     if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
977     if (!child.isEmpty()) {
978         for (int i = 0; i < child.count(); i++) {
979             if (child.at(i)->data(MetaGroupRole).toString() == meta) {
980                 m_view.format_list->setCurrentItem(child.at(i));
981                 break;
982             }
983         }
984     }
985     child.clear();
986     if (!profile.isEmpty()) child = m_view.size_list->findItems(profile, Qt::MatchExactly);
987     if (!child.isEmpty()) m_view.size_list->setCurrentItem(child.at(0));
988 }
989
990 void RenderWidget::parseFile(QString exportFile, bool editable)
991 {
992     kDebug() << "// Parsing file: " << exportFile;
993     kDebug() << "------------------------------";
994     QDomDocument doc;
995     QFile file(exportFile);
996     doc.setContent(&file, false);
997     file.close();
998     QDomElement documentElement;
999     QDomElement profileElement;
1000     QString extension;
1001     QListWidgetItem *item;
1002     QDomNodeList groups = doc.elementsByTagName("group");
1003
1004     if (editable || groups.count() == 0) {
1005         QDomElement profiles = doc.documentElement();
1006         if (editable && profiles.attribute("version", 0).toInt() < 1) {
1007             kDebug() << "// OLD profile version";
1008             // this is an old profile version, update it
1009             QDomDocument newdoc;
1010             QDomElement newprofiles = newdoc.createElement("profiles");
1011             newprofiles.setAttribute("version", 1);
1012             newdoc.appendChild(newprofiles);
1013             QDomNodeList profilelist = doc.elementsByTagName("profile");
1014             for (int i = 0; i < profilelist.count(); i++) {
1015                 QString category = i18n("Custom");
1016                 QString extension;
1017                 QDomNode parent = profilelist.at(i).parentNode();
1018                 if (!parent.isNull()) {
1019                     QDomElement parentNode = parent.toElement();
1020                     if (parentNode.hasAttribute("name")) category = parentNode.attribute("name");
1021                     extension = parentNode.attribute("extension");
1022                 }
1023                 profilelist.at(i).toElement().setAttribute("category", category);
1024                 if (!extension.isEmpty()) profilelist.at(i).toElement().setAttribute("extension", extension);
1025                 QDomNode n = profilelist.at(i).cloneNode();
1026                 newprofiles.appendChild(newdoc.importNode(n, true));
1027             }
1028             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1029                 KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
1030                 return;
1031             }
1032             QTextStream out(&file);
1033             out << newdoc.toString();
1034             file.close();
1035             parseFile(exportFile, editable);
1036             return;
1037         }
1038
1039         QDomNode node = doc.elementsByTagName("profile").at(0);
1040         if (node.isNull()) {
1041             kDebug() << "// Export file: " << exportFile << " IS BROKEN";
1042             return;
1043         }
1044         int count = 1;
1045         while (!node.isNull()) {
1046             QDomElement profile = node.toElement();
1047             QString profileName = profile.attribute("name");
1048             QString standard = profile.attribute("standard");
1049             QString params = profile.attribute("args");
1050             QString category = profile.attribute("category", i18n("Custom"));
1051             QString dest = profile.attribute("destinationid");
1052             QString prof_extension = profile.attribute("extension");
1053             if (!prof_extension.isEmpty()) extension = prof_extension;
1054
1055             QList <QListWidgetItem *> list = m_view.format_list->findItems(category, Qt::MatchExactly);
1056             bool exists = false;
1057             for (int j = 0; j < list.count(); j++) {
1058                 if (list.at(j)->data(MetaGroupRole) == dest) {
1059                     exists = true;
1060                     break;
1061                 }
1062             }
1063             if (!exists) {
1064                 item = new QListWidgetItem(category, m_view.format_list);
1065                 item->setData(MetaGroupRole, dest);
1066             }
1067
1068             // Check if item with same name already exists and replace it,
1069             // allowing to override default profiles
1070
1071             list = m_view.size_list->findItems(profileName, Qt::MatchExactly);
1072
1073             for (int j = 0; j < list.count(); j++) {
1074                 if (list.at(j)->data(MetaGroupRole) == dest) {
1075                     QListWidgetItem *duplicate = list.takeAt(j);
1076                     delete duplicate;
1077                     j--;
1078                 }
1079             }
1080
1081             item = new QListWidgetItem(profileName, m_view.size_list);
1082             //kDebug() << "// ADDINg item with name: " << profileName << ", GRP" << category << ", DEST:" << dest ;
1083             item->setData(GroupRole, category);
1084             item->setData(MetaGroupRole, dest);
1085             item->setData(ExtensionRole, extension);
1086             item->setData(RenderRole, "avformat");
1087             item->setData(StandardRole, standard);
1088             item->setData(ParamsRole, params);
1089             if (profile.hasAttribute("url")) item->setData(ExtraRole, profile.attribute("url"));
1090             if (editable) {
1091                 item->setData(EditableRole, exportFile);
1092                 if (exportFile.endsWith("customprofiles.xml")) item->setIcon(KIcon("emblem-favorite"));
1093                 else item->setIcon(KIcon("applications-internet"));
1094             }
1095             node = doc.elementsByTagName("profile").at(count);
1096             count++;
1097         }
1098         return;
1099     }
1100
1101     int i = 0;
1102     QString groupName;
1103     QString profileName;
1104
1105     QString prof_extension;
1106     QString renderer;
1107     QString params;
1108     QString standard;
1109     KIcon icon;
1110
1111     while (!groups.item(i).isNull()) {
1112         documentElement = groups.item(i).toElement();
1113         QDomNode gname = documentElement.elementsByTagName("groupname").at(0);
1114         QString metagroupName;
1115         QString metagroupId;
1116         if (!gname.isNull()) {
1117             metagroupName = gname.firstChild().nodeValue();
1118             metagroupId = gname.toElement().attribute("id");
1119             if (!metagroupName.isEmpty() && !m_view.destination_list->contains(metagroupName)) {
1120                 if (metagroupId == "dvd") icon = KIcon("media-optical");
1121                 else if (metagroupId == "audioonly") icon = KIcon("audio-x-generic");
1122                 else if (metagroupId == "websites") icon = KIcon("applications-internet");
1123                 else if (metagroupId == "mediaplayers") icon = KIcon("applications-multimedia");
1124                 else if (metagroupId == "lossless") icon = KIcon("drive-harddisk");
1125                 else if (metagroupId == "mobile") icon = KIcon("pda");
1126                 m_view.destination_list->addItem(icon, i18n(metagroupName.toUtf8().data()), metagroupId);
1127             }
1128         }
1129         groupName = documentElement.attribute("name", i18n("Custom"));
1130         extension = documentElement.attribute("extension", QString());
1131         renderer = documentElement.attribute("renderer", QString());
1132         QList <QListWidgetItem *> list = m_view.format_list->findItems(groupName, Qt::MatchExactly);
1133         bool exists = false;
1134         for (int j = 0; j < list.count(); j++) {
1135             if (list.at(j)->data(MetaGroupRole) == metagroupId) {
1136                 exists = true;
1137                 break;
1138             }
1139         }
1140         if (!exists) {
1141             item = new QListWidgetItem(groupName, m_view.format_list);
1142             item->setData(MetaGroupRole, metagroupId);
1143         }
1144
1145         QDomNode n = groups.item(i).firstChild();
1146         while (!n.isNull()) {
1147             if (n.toElement().tagName() != "profile") {
1148                 n = n.nextSibling();
1149                 continue;
1150             }
1151             profileElement = n.toElement();
1152             profileName = profileElement.attribute("name");
1153             standard = profileElement.attribute("standard");
1154             params = profileElement.attribute("args");
1155             prof_extension = profileElement.attribute("extension");
1156             if (!prof_extension.isEmpty()) extension = prof_extension;
1157             item = new QListWidgetItem(profileName, m_view.size_list);
1158             item->setData(GroupRole, groupName);
1159             item->setData(MetaGroupRole, metagroupId);
1160             item->setData(ExtensionRole, extension);
1161             item->setData(RenderRole, renderer);
1162             item->setData(StandardRole, standard);
1163             item->setData(ParamsRole, params);
1164             if (profileElement.hasAttribute("url")) item->setData(ExtraRole, profileElement.attribute("url"));
1165             if (editable) item->setData(EditableRole, exportFile);
1166             n = n.nextSibling();
1167         }
1168
1169         i++;
1170     }
1171 }
1172
1173 void RenderWidget::setRenderJob(const QString &dest, int progress)
1174 {
1175     QTreeWidgetItem *item;
1176     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1177     if (!existing.isEmpty()) item = existing.at(0);
1178     else {
1179         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1180         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1181         if (progress == 0) {
1182             item->setData(1, Qt::UserRole + 2, WAITINGJOB);
1183             item->setIcon(0, KIcon("media-playback-pause"));
1184             item->setData(1, Qt::UserRole, i18n("Waiting..."));
1185         }
1186     }
1187     item->setData(2, Qt::UserRole, progress);
1188     item->setData(1, Qt::UserRole + 2, RUNNINGJOB);
1189     if (progress == 0) {
1190         item->setIcon(0, KIcon("system-run"));
1191         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1192         item->setData(1, Qt::UserRole + 1, QTime::currentTime());
1193         slotCheckJob();
1194     } else {
1195         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1196         int seconds = startTime.secsTo(QTime::currentTime());;
1197         const QString t = i18n("Estimated time %1", QTime().addSecs(seconds * (100 - progress) / progress).toString("hh:mm:ss"));
1198         item->setData(1, Qt::UserRole, t);
1199     }
1200 }
1201
1202 void RenderWidget::setRenderStatus(const QString &dest, int status, const QString &error)
1203 {
1204     QTreeWidgetItem *item;
1205     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1206     if (!existing.isEmpty()) item = existing.at(0);
1207     else {
1208         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1209         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1210     }
1211     item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
1212     if (status == -1) {
1213         // Job finished successfully
1214         item->setIcon(0, KIcon("dialog-ok"));
1215         item->setData(2, Qt::UserRole, 100);
1216         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1217         int seconds = startTime.secsTo(QTime::currentTime());
1218         const QTime tm = QTime().addSecs(seconds);
1219         const QString t = i18n("Rendering finished in %1", tm.toString("hh:mm:ss"));
1220         item->setData(1, Qt::UserRole, t);
1221         QString itemGroup = item->data(0, Qt::UserRole).toString();
1222         if (itemGroup == "dvd") {
1223             emit openDvdWizard(item->text(1), item->data(0, Qt::UserRole + 1).toString());
1224         } else if (itemGroup == "websites") {
1225             QString url = item->data(0, Qt::UserRole + 1).toString();
1226             if (!url.isEmpty()) new KRun(url, this);
1227         }
1228     } else if (status == -2) {
1229         // Rendering crashed
1230         item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
1231         item->setIcon(0, KIcon("dialog-close"));
1232         item->setData(2, Qt::UserRole, 100);
1233         m_view.error_log->append(i18n("<strong>Rendering of %1 crashed</strong><br />", dest));
1234         m_view.error_log->append(error);
1235         m_view.error_log->append("<hr />");
1236         m_view.error_box->setVisible(true);
1237     } else if (status == -3) {
1238         // User aborted job
1239         item->setData(1, Qt::UserRole, i18n("Rendering aborted"));
1240         item->setIcon(0, KIcon("dialog-cancel"));
1241         item->setData(2, Qt::UserRole, 100);
1242     }
1243     slotCheckJob();
1244     checkRenderStatus();
1245 }
1246
1247 void RenderWidget::slotAbortCurrentJob()
1248 {
1249     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1250     if (current) {
1251         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1252             emit abortProcess(current->text(1));
1253         else {
1254             delete current;
1255             slotCheckJob();
1256         }
1257     }
1258 }
1259
1260 void RenderWidget::slotCheckJob()
1261 {
1262     bool activate = false;
1263     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1264     if (current) {
1265         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1266             m_view.abort_job->setText(i18n("Abort Job"));
1267         else m_view.abort_job->setText(i18n("Remove Job"));
1268         activate = true;
1269     }
1270     m_view.abort_job->setEnabled(activate);
1271 }
1272
1273 void RenderWidget::slotCLeanUpJobs()
1274 {
1275     int ix = 0;
1276     QTreeWidgetItem *current = m_view.running_jobs->topLevelItem(ix);
1277     while (current) {
1278         if (current->data(1, Qt::UserRole + 2).toInt() == FINISHEDJOB)
1279             delete current;
1280         else ix++;
1281         current = m_view.running_jobs->topLevelItem(ix);
1282     }
1283     slotCheckJob();
1284 }
1285
1286 void RenderWidget::parseScriptFiles()
1287 {
1288     QStringList scriptsFilter;
1289     scriptsFilter << "*.sh";
1290     m_view.scripts_list->clear();
1291
1292     QTreeWidgetItem *item;
1293     // List the project scripts
1294     QStringList scriptFiles = QDir(m_projectFolder + "/scripts").entryList(scriptsFilter, QDir::Files);
1295     for (int i = 0; i < scriptFiles.size(); ++i) {
1296         KUrl scriptpath(m_projectFolder + "/scripts/" + scriptFiles.at(i));
1297         item = new QTreeWidgetItem(m_view.scripts_list, QStringList() << scriptpath.fileName());
1298         QString target;
1299         QFile file(scriptpath.path());
1300         if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1301             while (!file.atEnd()) {
1302                 QByteArray line = file.readLine();
1303                 if (line.startsWith("TARGET=")) {
1304                     target = QString(line).section("TARGET=", 1);
1305                     target.remove(QChar('"'));
1306                     break;
1307                 }
1308             }
1309             file.close();
1310         }
1311         item->setSizeHint(0, QSize(m_view.scripts_list->columnWidth(0), fontMetrics().height() * 2));
1312         item->setData(0, Qt::UserRole, target.simplified());
1313         item->setData(0, Qt::UserRole + 1, scriptpath.path());
1314     }
1315     bool activate = false;
1316     QTreeWidgetItem *script = m_view.scripts_list->topLevelItem(0);
1317     if (script) {
1318         script->setSelected(true);
1319         m_view.scripts_list->setCurrentItem(script);
1320         activate = true;
1321     }
1322 //    m_view.start_script->setEnabled(activate);
1323 //    m_view.delete_script->setEnabled(activate);
1324 }
1325
1326 void RenderWidget::slotCheckScript()
1327 {
1328     bool activate = false;
1329     QTreeWidgetItemIterator it(m_view.scripts_list);
1330     if (*it) activate = true;
1331     m_view.start_script->setEnabled(activate);
1332     m_view.delete_script->setEnabled(activate);
1333 }
1334
1335 void RenderWidget::slotStartScript()
1336 {
1337     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1338     if (item) {
1339         QString destination = item->data(0, Qt::UserRole).toString();
1340         QString path = item->data(0, Qt::UserRole + 1).toString();
1341         // Insert new job in queue
1342         QTreeWidgetItem *renderItem;
1343         QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(destination, Qt::MatchExactly, 1);
1344         if (!existing.isEmpty()) {
1345             renderItem = existing.at(0);
1346             if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1347                 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"));
1348                 return;
1349             }
1350         } else renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << destination << QString());
1351         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
1352         renderItem->setIcon(0, KIcon("media-playback-pause"));
1353         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
1354         renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1355         renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
1356         renderItem->setData(1, Qt::UserRole + 3, path);
1357         renderItem->setData(1, Qt::UserRole + 4, '1');
1358         checkRenderStatus();
1359         m_view.tabWidget->setCurrentIndex(1);
1360     }
1361 }
1362
1363 void RenderWidget::slotDeleteScript()
1364 {
1365     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1366     if (item) {
1367         QString path = item->data(0, Qt::UserRole + 1).toString();
1368         KIO::NetAccess::del(path + ".mlt", this);
1369         KIO::NetAccess::del(path, this);
1370         parseScriptFiles();
1371     }
1372 }
1373
1374 void RenderWidget::slotGenerateScript()
1375 {
1376     slotExport(true);
1377 }
1378
1379 void RenderWidget::slotHideLog()
1380 {
1381     m_view.error_box->setVisible(false);
1382 }