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