]> git.sesse.net Git - kdenlive/blob - src/renderwidget.cpp
Fix rendering bugs (874) when using the Rescale option due to not inserting the consu...
[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
580     QStringList overlayargs;
581     if (m_view.tc_overlay->isChecked()) {
582         QString filterFile = KStandardDirs::locate("appdata", "metadata.properties");
583         overlayargs << "meta.attr.timecode=1" << "meta.attr.timecode.markup=#timecode";
584         overlayargs << "-attach" << "data_feed:attr_check" << "-attach";
585         overlayargs << "data_show:" + filterFile << "_loader=1" << "dynamic=1";
586     }
587     double startPos = -1;
588     double endPos = -1;
589     if (m_view.render_guide->isChecked()) {
590         startPos = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
591         endPos = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
592     }
593     QString renderArgs = m_view.advanced_params->toPlainText().simplified();
594
595     // Adjust frame scale
596     int width;
597     int height;
598     if (m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
599         width = m_view.rescale_size->text().section('x', 0, 0).toInt();
600         height = m_view.rescale_size->text().section('x', 1, 1).toInt();
601     } else {
602         width = m_profile.width;
603         height = m_profile.height;
604     }
605     renderArgs.replace("%dar", '@' + QString::number(m_profile.display_aspect_num) + '/' + QString::number(m_profile.display_aspect_den));
606
607     // Adjust scanning
608     if (m_view.scanning_list->currentIndex() == 1) renderArgs.append(" progressive=1");
609     else if (m_view.scanning_list->currentIndex() == 2) renderArgs.append(" progressive=0");
610
611     // disable audio if requested
612     if (!m_view.export_audio->isChecked())
613         renderArgs.append(" an=1 ");
614
615     // Check if the rendering profile is different from project profile,
616     // in which case we need to use the producer_comsumer from MLT
617     QString std = renderArgs;
618     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
619     const QString currentSize = QString::number(width) + 'x' + QString::number(height);
620     QString subsize = currentSize;
621     if (std.startsWith("s=")) {
622         subsize = std.section(' ', 0, 0).toLower();
623         subsize = subsize.section("=", 1, 1);
624     } else if (std.contains(" s=")) {
625         subsize = std.section(" s=", 1, 1);
626         subsize = subsize.section(' ', 0, 0).toLower();
627     } else if (destination != "audioonly" && m_view.rescale->isChecked() && m_view.rescale->isEnabled()) 
628     {
629         subsize = QString(" s=%1x%2").arg(width).arg(height);
630         // Add current size parameter
631         renderArgs.append(subsize);
632     }
633     bool resizeProfile = (subsize != currentSize);
634
635     QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
636
637     QStringList renderParameters;
638     renderParameters << dest << item->data(RenderRole).toString() << renderArgs.simplified();
639     renderParameters << QString::number(m_view.render_zone->isChecked()) << QString::number(m_view.play_after->isChecked());
640     renderParameters << QString::number(startPos) << QString::number(endPos) << QString::number(resizeProfile);
641
642     QString scriptName;
643     if (scriptExport) {
644         bool ok;
645         int ix = 0;
646         QString scriptsFolder = m_projectFolder + "/scripts/";
647         KStandardDirs::makeDir(scriptsFolder);
648         QString path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
649         while (QFile::exists(path)) {
650             ix++;
651             path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
652         }
653         scriptName = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
654         if (!ok || scriptName.isEmpty()) return;
655         scriptName.prepend(scriptsFolder);
656         QFile f(scriptName);
657         if (f.exists()) {
658             if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
659                 return;
660         }
661         renderParameters << scriptName;
662         if (group == "dvd") renderParameters << QString::number(m_view.create_chapter->isChecked());
663         else renderParameters << QString::number(false);
664         emit doRender(renderParameters, overlayargs);
665         QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
666         m_view.tabWidget->setCurrentIndex(2);
667         return;
668     }
669     renderParameters << scriptName;
670     m_view.tabWidget->setCurrentIndex(1);
671
672     // insert item in running jobs list
673     QTreeWidgetItem *renderItem;
674     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
675     if (!existing.isEmpty()) {
676         renderItem = existing.at(0);
677         if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
678             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"));
679             return;
680         }
681         renderItem->setData(1, Qt::UserRole + 4, QString());
682     } else {
683         renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
684         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
685         renderItem->setIcon(0, KIcon("media-playback-pause"));
686         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
687     }
688     renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
689     renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
690     renderItem->setData(1, Qt::UserRole + 2, overlayargs);
691
692     // Set rendering type
693     if (group == "dvd") {
694         renderParameters << QString::number(m_view.create_chapter->isChecked());
695         if (m_view.open_dvd->isChecked()) {
696             renderItem->setData(0, Qt::UserRole, group);
697             if (renderArgs.contains("profile=")) {
698                 // rendering profile contains an MLT profile, so pass it to the running jog item, useful for dvd
699                 QString prof = renderArgs.section("profile=", 1, 1);
700                 prof = prof.section(' ', 0, 0);
701                 kDebug() << "// render profile: " << prof;
702                 renderItem->setData(0, Qt::UserRole + 1, prof);
703             }
704         }
705     } else {
706         renderParameters << QString::number(false);
707         if (group == "websites" && m_view.open_browser->isChecked()) {
708             renderItem->setData(0, Qt::UserRole, group);
709             // pass the url
710             QString url = m_view.size_list->currentItem()->data(ExtraRole).toString();
711             renderItem->setData(0, Qt::UserRole + 1, url);
712         }
713     }
714
715
716     renderItem->setData(1, Qt::UserRole + 3, renderParameters);
717     checkRenderStatus();
718 }
719
720 void RenderWidget::checkRenderStatus()
721 {
722     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
723     while (item) {
724         if (item->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) break;
725         else if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
726             item->setData(1, Qt::UserRole + 1, QTime::currentTime());
727             if (item->data(1, Qt::UserRole + 4).isNull()) {
728                 emit doRender(item->data(1, Qt::UserRole + 3).toStringList(), item->data(1, Qt::UserRole + 2).toStringList());
729             } else {
730                 // Script item
731                 QProcess::startDetached(item->data(1, Qt::UserRole + 3).toString());
732             }
733             break;
734         }
735         item = m_view.running_jobs->itemBelow(item);
736     }
737 }
738
739 void RenderWidget::setProfile(MltVideoProfile profile)
740 {
741     m_profile = profile;
742     //WARNING: this way to tell the video standard is a bit hackish...
743     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);
744     else m_view.format_selection->setCurrentIndex(1);
745     m_view.scanning_list->setCurrentIndex(0);
746     refreshView();
747 }
748
749 void RenderWidget::refreshView()
750 {
751     m_view.size_list->blockSignals(true);
752     QListWidgetItem *sizeItem;
753
754     QString destination;
755     KIcon brokenIcon("dialog-close");
756     if (m_view.destination_list->currentIndex() > 0)
757         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
758
759
760     if (destination == "dvd") {
761         m_view.open_dvd->setVisible(true);
762         m_view.create_chapter->setVisible(true);
763     } else {
764         m_view.open_dvd->setVisible(false);
765         m_view.create_chapter->setVisible(false);
766     }
767     if (destination == "websites") m_view.open_browser->setVisible(true);
768     else m_view.open_browser->setVisible(false);
769     if (!destination.isEmpty() && QString("dvd websites audioonly").contains(destination))
770         m_view.rescale->setEnabled(false);
771     else m_view.rescale->setEnabled(true);
772     // hide groups that are not in the correct destination
773     for (int i = 0; i < m_view.format_list->count(); i++) {
774         sizeItem = m_view.format_list->item(i);
775         if (sizeItem->data(MetaGroupRole).toString() == destination) {
776             sizeItem->setHidden(false);
777             //kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
778         } else sizeItem->setHidden(true);
779     }
780
781     // activate first visible item
782     QListWidgetItem * item = m_view.format_list->currentItem();
783     if (!item || item->isHidden()) {
784         for (int i = 0; i < m_view.format_list->count(); i++) {
785             if (!m_view.format_list->item(i)->isHidden()) {
786                 m_view.format_list->setCurrentRow(i);
787                 break;
788             }
789         }
790         item = m_view.format_list->currentItem();
791     }
792     if (!item || item->isHidden()) {
793         m_view.format_list->setEnabled(false);
794         m_view.size_list->setEnabled(false);
795         return;
796     } else {
797         m_view.format_list->setEnabled(true);
798         m_view.size_list->setEnabled(true);
799     }
800     int count = 0;
801     for (int i = 0; i < m_view.format_list->count() && count < 2; i++) {
802         if (!m_view.format_list->isRowHidden(i)) count++;
803     }
804     if (count > 1) m_view.format_list->setVisible(true);
805     else m_view.format_list->setVisible(false);
806     QString std;
807     QString group = item->text();
808     bool firstSelected = false;
809     const QStringList formatsList = KdenliveSettings::supportedformats();
810     const QStringList vcodecsList = KdenliveSettings::videocodecs();
811     const QStringList acodecsList = KdenliveSettings::audiocodecs();
812
813     for (int i = 0; i < m_view.size_list->count(); i++) {
814         sizeItem = m_view.size_list->item(i);
815         if ((sizeItem->data(GroupRole) == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole) == destination) {
816             std = sizeItem->data(StandardRole).toString();
817             if (!std.isEmpty()) {
818                 if (std.contains("PAL", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 0);
819                 else if (std.contains("NTSC", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 1);
820             } else {
821                 sizeItem->setHidden(false);
822                 if (!firstSelected) m_view.size_list->setCurrentItem(sizeItem);
823                 firstSelected = true;
824             }
825
826             if (!sizeItem->isHidden()) {
827                 // Make sure the selected profile uses an installed avformat codec / format
828                 std = sizeItem->data(ParamsRole).toString();
829
830                 if (!formatsList.isEmpty()) {
831                     QString format;
832                     if (std.startsWith("f=")) format = std.section("f=", 1, 1);
833                     else if (std.contains(" f=")) format = std.section(" f=", 1, 1);
834                     if (!format.isEmpty()) {
835                         format = format.section(' ', 0, 0).toLower();
836                         if (!formatsList.contains(format)) {
837                             kDebug() << "***** UNSUPPORTED F: " << format;
838                             //sizeItem->setHidden(true);
839                             sizeItem->setFlags(Qt::ItemIsSelectable);
840                             sizeItem->setToolTip(i18n("Unsupported video format: %1", format));
841                             sizeItem->setIcon(brokenIcon);
842                         }
843                     }
844                 }
845                 if (!acodecsList.isEmpty() && !sizeItem->isHidden()) {
846                     QString format;
847                     if (std.startsWith("acodec=")) format = std.section("acodec=", 1, 1);
848                     else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
849                     if (!format.isEmpty()) {
850                         format = format.section(' ', 0, 0).toLower();
851                         if (!acodecsList.contains(format)) {
852                             kDebug() << "*****  UNSUPPORTED ACODEC: " << format;
853                             //sizeItem->setHidden(true);
854                             sizeItem->setFlags(Qt::ItemIsSelectable);
855                             sizeItem->setToolTip(i18n("Unsupported audio codec: %1", format));
856                             sizeItem->setIcon(brokenIcon);
857                         }
858                     }
859                 }
860                 if (!vcodecsList.isEmpty() && !sizeItem->isHidden()) {
861                     QString format;
862                     if (std.startsWith("vcodec=")) format = std.section("vcodec=", 1, 1);
863                     else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
864                     if (!format.isEmpty()) {
865                         format = format.section(' ', 0, 0).toLower();
866                         if (!vcodecsList.contains(format)) {
867                             kDebug() << "*****  UNSUPPORTED VCODEC: " << format;
868                             //sizeItem->setHidden(true);
869                             sizeItem->setFlags(Qt::ItemIsSelectable);
870                             sizeItem->setToolTip(i18n("Unsupported video codec: %1", format));
871                             sizeItem->setIcon(brokenIcon);
872                         }
873                     }
874                 }
875             }
876         } else sizeItem->setHidden(true);
877     }
878     focusFirstVisibleItem();
879     m_view.size_list->blockSignals(false);
880     refreshParams();
881 }
882
883 KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension)
884 {
885     QString path;
886     if (!url.isEmpty()) {
887         path = url.path();
888         int pos = path.lastIndexOf('.') + 1;
889         if (pos == 0) path.append('.' + extension);
890         else path = path.left(pos) + extension;
891
892     } else {
893         path = m_projectFolder + "/untitled." + extension;
894     }
895     return KUrl(path);
896 }
897
898
899 void RenderWidget::refreshParams()
900 {
901     QListWidgetItem *item = m_view.size_list->currentItem();
902     if (!item || item->isHidden()) {
903         m_view.advanced_params->clear();
904         m_view.buttonStart->setEnabled(false);
905         return;
906     }
907     QString params = item->data(ParamsRole).toString();
908     QString extension = item->data(ExtensionRole).toString();
909     m_view.advanced_params->setPlainText(params);
910     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
911     if (params.contains(" s=") || destination == "audioonly") {
912         // profile has a fixed size, do not allow resize
913         m_view.rescale->setEnabled(false);
914         m_view.rescale_size->setEnabled(false);
915     } else {
916         m_view.rescale->setEnabled(true);
917         m_view.rescale_size->setEnabled(true);
918     }
919     KUrl url = filenameWithExtension(m_view.out_file->url(), extension);
920     m_view.out_file->setUrl(url);
921 //     if (!url.isEmpty()) {
922 //         QString path = url.path();
923 //         int pos = path.lastIndexOf('.') + 1;
924 //  if (pos == 0) path.append('.' + extension);
925 //         else path = path.left(pos) + extension;
926 //         m_view.out_file->setUrl(KUrl(path));
927 //     } else {
928 //         m_view.out_file->setUrl(KUrl(QDir::homePath() + "/untitled." + extension));
929 //     }
930     m_view.out_file->setFilter("*." + extension);
931     QString edit = item->data(EditableRole).toString();
932     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
933         m_view.buttonDelete->setEnabled(false);
934         m_view.buttonEdit->setEnabled(false);
935     } else {
936         m_view.buttonDelete->setEnabled(true);
937         m_view.buttonEdit->setEnabled(true);
938     }
939
940     m_view.buttonStart->setEnabled(m_view.size_list->currentItem()->flags() & Qt::ItemIsEnabled);
941 }
942
943 void RenderWidget::reloadProfiles()
944 {
945     parseProfiles();
946 }
947
948 void RenderWidget::parseProfiles(QString meta, QString group, QString profile)
949 {
950     m_view.size_list->clear();
951     m_view.format_list->clear();
952     m_view.destination_list->clear();
953     m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
954     m_view.destination_list->addItem(KIcon("media-optical"), i18n("DVD"), "dvd");
955     m_view.destination_list->addItem(KIcon("audio-x-generic"), i18n("Audio only"), "audioonly");
956     m_view.destination_list->addItem(KIcon("applications-internet"), i18n("Web sites"), "websites");
957     m_view.destination_list->addItem(KIcon("applications-multimedia"), i18n("Media players"), "mediaplayers");
958     m_view.destination_list->addItem(KIcon("drive-harddisk"), i18n("Lossless / HQ"), "lossless");
959     m_view.destination_list->addItem(KIcon("pda"), i18n("Mobile devices"), "mobile");
960
961     QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
962     parseFile(exportFile, false);
963
964
965     QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
966     QDir directory = QDir(exportFolder);
967     QStringList filter;
968     filter << "*.xml";
969     QStringList fileList = directory.entryList(filter, QDir::Files);
970     // We should parse customprofiles.xml in last position, so that user profiles
971     // can also override profiles installed by KNewStuff
972     fileList.removeAll("customprofiles.xml");
973     foreach(const QString &filename, fileList)
974     parseFile(exportFolder + '/' + filename, true);
975     if (QFile::exists(exportFolder + "/customprofiles.xml")) parseFile(exportFolder + "/customprofiles.xml", true);
976
977     if (!meta.isEmpty()) {
978         m_view.destination_list->blockSignals(true);
979         m_view.destination_list->setCurrentIndex(m_view.destination_list->findData(meta));
980         m_view.destination_list->blockSignals(false);
981     }
982     refreshView();
983     QList<QListWidgetItem *> child;
984     if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
985     if (!child.isEmpty()) {
986         for (int i = 0; i < child.count(); i++) {
987             if (child.at(i)->data(MetaGroupRole).toString() == meta) {
988                 m_view.format_list->setCurrentItem(child.at(i));
989                 break;
990             }
991         }
992     }
993     child.clear();
994     if (!profile.isEmpty()) child = m_view.size_list->findItems(profile, Qt::MatchExactly);
995     if (!child.isEmpty()) m_view.size_list->setCurrentItem(child.at(0));
996 }
997
998 void RenderWidget::parseFile(QString exportFile, bool editable)
999 {
1000     kDebug() << "// Parsing file: " << exportFile;
1001     kDebug() << "------------------------------";
1002     QDomDocument doc;
1003     QFile file(exportFile);
1004     doc.setContent(&file, false);
1005     file.close();
1006     QDomElement documentElement;
1007     QDomElement profileElement;
1008     QString extension;
1009     QListWidgetItem *item;
1010     QDomNodeList groups = doc.elementsByTagName("group");
1011
1012     if (editable || groups.count() == 0) {
1013         QDomElement profiles = doc.documentElement();
1014         if (editable && profiles.attribute("version", 0).toInt() < 1) {
1015             kDebug() << "// OLD profile version";
1016             // this is an old profile version, update it
1017             QDomDocument newdoc;
1018             QDomElement newprofiles = newdoc.createElement("profiles");
1019             newprofiles.setAttribute("version", 1);
1020             newdoc.appendChild(newprofiles);
1021             QDomNodeList profilelist = doc.elementsByTagName("profile");
1022             for (int i = 0; i < profilelist.count(); i++) {
1023                 QString category = i18n("Custom");
1024                 QString extension;
1025                 QDomNode parent = profilelist.at(i).parentNode();
1026                 if (!parent.isNull()) {
1027                     QDomElement parentNode = parent.toElement();
1028                     if (parentNode.hasAttribute("name")) category = parentNode.attribute("name");
1029                     extension = parentNode.attribute("extension");
1030                 }
1031                 profilelist.at(i).toElement().setAttribute("category", category);
1032                 if (!extension.isEmpty()) profilelist.at(i).toElement().setAttribute("extension", extension);
1033                 QDomNode n = profilelist.at(i).cloneNode();
1034                 newprofiles.appendChild(newdoc.importNode(n, true));
1035             }
1036             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1037                 KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
1038                 return;
1039             }
1040             QTextStream out(&file);
1041             out << newdoc.toString();
1042             file.close();
1043             parseFile(exportFile, editable);
1044             return;
1045         }
1046
1047         QDomNode node = doc.elementsByTagName("profile").at(0);
1048         if (node.isNull()) {
1049             kDebug() << "// Export file: " << exportFile << " IS BROKEN";
1050             return;
1051         }
1052         int count = 1;
1053         while (!node.isNull()) {
1054             QDomElement profile = node.toElement();
1055             QString profileName = profile.attribute("name");
1056             QString standard = profile.attribute("standard");
1057             QString params = profile.attribute("args");
1058             QString category = profile.attribute("category", i18n("Custom"));
1059             QString dest = profile.attribute("destinationid");
1060             QString prof_extension = profile.attribute("extension");
1061             if (!prof_extension.isEmpty()) extension = prof_extension;
1062
1063             QList <QListWidgetItem *> list = m_view.format_list->findItems(category, Qt::MatchExactly);
1064             bool exists = false;
1065             for (int j = 0; j < list.count(); j++) {
1066                 if (list.at(j)->data(MetaGroupRole) == dest) {
1067                     exists = true;
1068                     break;
1069                 }
1070             }
1071             if (!exists) {
1072                 item = new QListWidgetItem(category, m_view.format_list);
1073                 item->setData(MetaGroupRole, dest);
1074             }
1075
1076             // Check if item with same name already exists and replace it,
1077             // allowing to override default profiles
1078
1079             list = m_view.size_list->findItems(profileName, Qt::MatchExactly);
1080
1081             for (int j = 0; j < list.count(); j++) {
1082                 if (list.at(j)->data(MetaGroupRole) == dest) {
1083                     QListWidgetItem *duplicate = list.takeAt(j);
1084                     delete duplicate;
1085                     j--;
1086                 }
1087             }
1088
1089             item = new QListWidgetItem(profileName, m_view.size_list);
1090             //kDebug() << "// ADDINg item with name: " << profileName << ", GRP" << category << ", DEST:" << dest ;
1091             item->setData(GroupRole, category);
1092             item->setData(MetaGroupRole, dest);
1093             item->setData(ExtensionRole, extension);
1094             item->setData(RenderRole, "avformat");
1095             item->setData(StandardRole, standard);
1096             item->setData(ParamsRole, params);
1097             if (profile.hasAttribute("url")) item->setData(ExtraRole, profile.attribute("url"));
1098             if (editable) {
1099                 item->setData(EditableRole, exportFile);
1100                 if (exportFile.endsWith("customprofiles.xml")) item->setIcon(KIcon("emblem-favorite"));
1101                 else item->setIcon(KIcon("applications-internet"));
1102             }
1103             node = doc.elementsByTagName("profile").at(count);
1104             count++;
1105         }
1106         return;
1107     }
1108
1109     int i = 0;
1110     QString groupName;
1111     QString profileName;
1112
1113     QString prof_extension;
1114     QString renderer;
1115     QString params;
1116     QString standard;
1117     KIcon icon;
1118
1119     while (!groups.item(i).isNull()) {
1120         documentElement = groups.item(i).toElement();
1121         QDomNode gname = documentElement.elementsByTagName("groupname").at(0);
1122         QString metagroupName;
1123         QString metagroupId;
1124         if (!gname.isNull()) {
1125             metagroupName = gname.firstChild().nodeValue();
1126             metagroupId = gname.toElement().attribute("id");
1127             if (!metagroupName.isEmpty() && !m_view.destination_list->contains(metagroupName)) {
1128                 if (metagroupId == "dvd") icon = KIcon("media-optical");
1129                 else if (metagroupId == "audioonly") icon = KIcon("audio-x-generic");
1130                 else if (metagroupId == "websites") icon = KIcon("applications-internet");
1131                 else if (metagroupId == "mediaplayers") icon = KIcon("applications-multimedia");
1132                 else if (metagroupId == "lossless") icon = KIcon("drive-harddisk");
1133                 else if (metagroupId == "mobile") icon = KIcon("pda");
1134                 m_view.destination_list->addItem(icon, i18n(metagroupName.toUtf8().data()), metagroupId);
1135             }
1136         }
1137         groupName = documentElement.attribute("name", i18n("Custom"));
1138         extension = documentElement.attribute("extension", QString());
1139         renderer = documentElement.attribute("renderer", QString());
1140         QList <QListWidgetItem *> list = m_view.format_list->findItems(groupName, Qt::MatchExactly);
1141         bool exists = false;
1142         for (int j = 0; j < list.count(); j++) {
1143             if (list.at(j)->data(MetaGroupRole) == metagroupId) {
1144                 exists = true;
1145                 break;
1146             }
1147         }
1148         if (!exists) {
1149             item = new QListWidgetItem(groupName, m_view.format_list);
1150             item->setData(MetaGroupRole, metagroupId);
1151         }
1152
1153         QDomNode n = groups.item(i).firstChild();
1154         while (!n.isNull()) {
1155             if (n.toElement().tagName() != "profile") {
1156                 n = n.nextSibling();
1157                 continue;
1158             }
1159             profileElement = n.toElement();
1160             profileName = profileElement.attribute("name");
1161             standard = profileElement.attribute("standard");
1162             params = profileElement.attribute("args");
1163             prof_extension = profileElement.attribute("extension");
1164             if (!prof_extension.isEmpty()) extension = prof_extension;
1165             item = new QListWidgetItem(profileName, m_view.size_list);
1166             item->setData(GroupRole, groupName);
1167             item->setData(MetaGroupRole, metagroupId);
1168             item->setData(ExtensionRole, extension);
1169             item->setData(RenderRole, renderer);
1170             item->setData(StandardRole, standard);
1171             item->setData(ParamsRole, params);
1172             if (profileElement.hasAttribute("url")) item->setData(ExtraRole, profileElement.attribute("url"));
1173             if (editable) item->setData(EditableRole, exportFile);
1174             n = n.nextSibling();
1175         }
1176
1177         i++;
1178     }
1179 }
1180
1181 void RenderWidget::setRenderJob(const QString &dest, int progress)
1182 {
1183     QTreeWidgetItem *item;
1184     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1185     if (!existing.isEmpty()) item = existing.at(0);
1186     else {
1187         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1188         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1189         if (progress == 0) {
1190             item->setData(1, Qt::UserRole + 2, WAITINGJOB);
1191             item->setIcon(0, KIcon("media-playback-pause"));
1192             item->setData(1, Qt::UserRole, i18n("Waiting..."));
1193         }
1194     }
1195     item->setData(2, Qt::UserRole, progress);
1196     item->setData(1, Qt::UserRole + 2, RUNNINGJOB);
1197     if (progress == 0) {
1198         item->setIcon(0, KIcon("system-run"));
1199         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1200         item->setData(1, Qt::UserRole + 1, QTime::currentTime());
1201         slotCheckJob();
1202     } else {
1203         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1204         int seconds = startTime.secsTo(QTime::currentTime());;
1205         const QString t = i18n("Estimated time %1", QTime().addSecs(seconds * (100 - progress) / progress).toString("hh:mm:ss"));
1206         item->setData(1, Qt::UserRole, t);
1207     }
1208 }
1209
1210 void RenderWidget::setRenderStatus(const QString &dest, int status, const QString &error)
1211 {
1212     QTreeWidgetItem *item;
1213     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1214     if (!existing.isEmpty()) item = existing.at(0);
1215     else {
1216         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1217         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1218     }
1219     item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
1220     if (status == -1) {
1221         // Job finished successfully
1222         item->setIcon(0, KIcon("dialog-ok"));
1223         item->setData(2, Qt::UserRole, 100);
1224         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1225         int seconds = startTime.secsTo(QTime::currentTime());
1226         const QTime tm = QTime().addSecs(seconds);
1227         const QString t = i18n("Rendering finished in %1", tm.toString("hh:mm:ss"));
1228         item->setData(1, Qt::UserRole, t);
1229         QString itemGroup = item->data(0, Qt::UserRole).toString();
1230         if (itemGroup == "dvd") {
1231             emit openDvdWizard(item->text(1), item->data(0, Qt::UserRole + 1).toString());
1232         } else if (itemGroup == "websites") {
1233             QString url = item->data(0, Qt::UserRole + 1).toString();
1234             if (!url.isEmpty()) new KRun(url, this);
1235         }
1236     } else if (status == -2) {
1237         // Rendering crashed
1238         item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
1239         item->setIcon(0, KIcon("dialog-close"));
1240         item->setData(2, Qt::UserRole, 100);
1241         m_view.error_log->append(i18n("<strong>Rendering of %1 crashed</strong><br />", dest));
1242         m_view.error_log->append(error);
1243         m_view.error_log->append("<hr />");
1244         m_view.error_box->setVisible(true);
1245     } else if (status == -3) {
1246         // User aborted job
1247         item->setData(1, Qt::UserRole, i18n("Rendering aborted"));
1248         item->setIcon(0, KIcon("dialog-cancel"));
1249         item->setData(2, Qt::UserRole, 100);
1250     }
1251     slotCheckJob();
1252     checkRenderStatus();
1253 }
1254
1255 void RenderWidget::slotAbortCurrentJob()
1256 {
1257     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1258     if (current) {
1259         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1260             emit abortProcess(current->text(1));
1261         else {
1262             delete current;
1263             slotCheckJob();
1264         }
1265     }
1266 }
1267
1268 void RenderWidget::slotCheckJob()
1269 {
1270     bool activate = false;
1271     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1272     if (current) {
1273         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1274             m_view.abort_job->setText(i18n("Abort Job"));
1275         else m_view.abort_job->setText(i18n("Remove Job"));
1276         activate = true;
1277     }
1278     m_view.abort_job->setEnabled(activate);
1279 }
1280
1281 void RenderWidget::slotCLeanUpJobs()
1282 {
1283     int ix = 0;
1284     QTreeWidgetItem *current = m_view.running_jobs->topLevelItem(ix);
1285     while (current) {
1286         if (current->data(1, Qt::UserRole + 2).toInt() == FINISHEDJOB)
1287             delete current;
1288         else ix++;
1289         current = m_view.running_jobs->topLevelItem(ix);
1290     }
1291     slotCheckJob();
1292 }
1293
1294 void RenderWidget::parseScriptFiles()
1295 {
1296     QStringList scriptsFilter;
1297     scriptsFilter << "*.sh";
1298     m_view.scripts_list->clear();
1299
1300     QTreeWidgetItem *item;
1301     // List the project scripts
1302     QStringList scriptFiles = QDir(m_projectFolder + "/scripts").entryList(scriptsFilter, QDir::Files);
1303     for (int i = 0; i < scriptFiles.size(); ++i) {
1304         KUrl scriptpath(m_projectFolder + "/scripts/" + scriptFiles.at(i));
1305         item = new QTreeWidgetItem(m_view.scripts_list, QStringList() << scriptpath.fileName());
1306         QString target;
1307         QFile file(scriptpath.path());
1308         if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1309             while (!file.atEnd()) {
1310                 QByteArray line = file.readLine();
1311                 if (line.startsWith("TARGET=")) {
1312                     target = QString(line).section("TARGET=", 1);
1313                     target.remove(QChar('"'));
1314                     break;
1315                 }
1316             }
1317             file.close();
1318         }
1319         item->setSizeHint(0, QSize(m_view.scripts_list->columnWidth(0), fontMetrics().height() * 2));
1320         item->setData(0, Qt::UserRole, target.simplified());
1321         item->setData(0, Qt::UserRole + 1, scriptpath.path());
1322     }
1323     bool activate = false;
1324     QTreeWidgetItem *script = m_view.scripts_list->topLevelItem(0);
1325     if (script) {
1326         script->setSelected(true);
1327         m_view.scripts_list->setCurrentItem(script);
1328         activate = true;
1329     }
1330 //    m_view.start_script->setEnabled(activate);
1331 //    m_view.delete_script->setEnabled(activate);
1332 }
1333
1334 void RenderWidget::slotCheckScript()
1335 {
1336     bool activate = false;
1337     QTreeWidgetItemIterator it(m_view.scripts_list);
1338     if (*it) activate = true;
1339     m_view.start_script->setEnabled(activate);
1340     m_view.delete_script->setEnabled(activate);
1341 }
1342
1343 void RenderWidget::slotStartScript()
1344 {
1345     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1346     if (item) {
1347         QString destination = item->data(0, Qt::UserRole).toString();
1348         QString path = item->data(0, Qt::UserRole + 1).toString();
1349         // Insert new job in queue
1350         QTreeWidgetItem *renderItem;
1351         QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(destination, Qt::MatchExactly, 1);
1352         kDebug() << "------  START SCRIPT";
1353         if (!existing.isEmpty()) {
1354             renderItem = existing.at(0);
1355             if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1356                 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"));
1357                 return;
1358             }
1359         } else renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << destination << QString());
1360         kDebug() << "------  START SCRIPT 2";
1361         renderItem->setData(2, Qt::UserRole, 0);
1362         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
1363         renderItem->setIcon(0, KIcon("media-playback-pause"));
1364         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
1365         renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1366         renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
1367         renderItem->setData(1, Qt::UserRole + 3, path);
1368         renderItem->setData(1, Qt::UserRole + 4, '1');
1369         checkRenderStatus();
1370         m_view.tabWidget->setCurrentIndex(1);
1371     }
1372 }
1373
1374 void RenderWidget::slotDeleteScript()
1375 {
1376     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1377     if (item) {
1378         QString path = item->data(0, Qt::UserRole + 1).toString();
1379         KIO::NetAccess::del(path + ".mlt", this);
1380         KIO::NetAccess::del(path, this);
1381         parseScriptFiles();
1382     }
1383 }
1384
1385 void RenderWidget::slotGenerateScript()
1386 {
1387     slotExport(true);
1388 }
1389
1390 void RenderWidget::slotHideLog()
1391 {
1392     m_view.error_box->setVisible(false);
1393 }