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