renderwidget.cpp 58 KB
Newer Older
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/***************************************************************************
 *   Copyright (C) 2008 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

20

21 22 23
#include "renderwidget.h"
#include "kdenlivesettings.h"
#include "ui_saveprofile_ui.h"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
24 25 26

#include <KStandardDirs>
#include <KDebug>
27
#include <KMessageBox>
28
#include <KComboBox>
29
#include <KRun>
30
#include <KIO/NetAccess>
31
// #include <knewstuff2/engine.h>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
32

33 34 35 36 37 38 39 40
#include <QDomDocument>
#include <QItemDelegate>
#include <QTreeWidgetItem>
#include <QListWidgetItem>
#include <QHeaderView>
#include <QMenu>
#include <QProcess>
#include <QInputDialog>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
41

42 43 44 45 46
const int GroupRole = Qt::UserRole;
const int ExtensionRole = GroupRole + 1;
const int StandardRole = GroupRole + 2;
const int RenderRole = GroupRole + 3;
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 52 53 54 55 56
// Running job status
const int WAITINGJOB = 0;
const int RUNNINGJOB = 1;
const int FINISHEDJOB = 2;


57 58 59
RenderWidget::RenderWidget(const QString &projectfolder, QWidget * parent) :
        QDialog(parent),
        m_projectFolder(projectfolder)
60
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
61
    m_view.setupUi(this);
62
    setWindowTitle(i18n("Rendering"));
63 64 65 66
    m_view.buttonDelete->setIcon(KIcon("trash-empty"));
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

67 68 69 70
    m_view.buttonEdit->setIcon(KIcon("document-properties"));
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

71 72 73
    m_view.buttonSave->setIcon(KIcon("document-new"));
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

74
    m_view.buttonInfo->setIcon(KIcon("help-about"));
75
    m_view.hide_log->setIcon(KIcon("go-down"));
76 77 78 79 80

    if (KdenliveSettings::showrenderparams()) {
        m_view.buttonInfo->setDown(true);
    } else m_view.advanced_params->hide();

81 82
    m_view.rescale_size->setInputMask("0099\\x0099");
    m_view.rescale_size->setText("320x240");
83

84 85

    QMenu *renderMenu = new QMenu(i18n("Start Rendering"), this);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
86
    QAction *renderAction = renderMenu->addAction(KIcon("video-x-generic"), i18n("Render to File"));
87
    connect(renderAction, SIGNAL(triggered()), this, SLOT(slotExport()));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
88
    QAction *scriptAction = renderMenu->addAction(KIcon("application-x-shellscript"), i18n("Generate Script"));
89 90 91 92 93 94 95 96 97 98
    connect(scriptAction, SIGNAL(triggered()), this, SLOT(slotGenerateScript()));

    m_view.buttonStart->setMenu(renderMenu);
    m_view.buttonStart->setPopupMode(QToolButton::MenuButtonPopup);
    m_view.buttonStart->setDefaultAction(renderAction);
    m_view.buttonStart->setToolButtonStyle(Qt::ToolButtonTextOnly);
    m_view.abort_job->setEnabled(false);
    m_view.start_script->setEnabled(false);
    m_view.delete_script->setEnabled(false);

99 100
    m_view.format_list->setAlternatingRowColors(true);
    m_view.size_list->setAlternatingRowColors(true);
101

102
    parseProfiles();
103 104 105 106
    parseScriptFiles();

    connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
    connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
107 108
    connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
    connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
109

110 111
    connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));

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 117 118
    connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
    connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));

119 120
    connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
    connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
121
    connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
122 123
    connect(m_view.rescale, SIGNAL(toggled(bool)), m_view.rescale_size, SLOT(setEnabled(bool)));
    connect(m_view.destination_list, SIGNAL(activated(int)), this, SLOT(refreshView()));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
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 127
    connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
    connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
128

129 130
    connect(m_view.size_list, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotEditItem(QListWidgetItem *)));

131 132 133 134 135 136 137
    connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
    connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
    connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));

    connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
    connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));

138
    connect(m_view.format_selection, SIGNAL(activated(int)), this, SLOT(refreshView()));
139

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
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 146 147
    m_view.open_browser->setVisible(false);
    m_view.error_box->setVisible(false);

148 149
    m_view.splitter->setStretchFactor(1, 5);
    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 157 158
    QHeaderView *header = m_view.running_jobs->header();
    QFontMetrics fm = fontMetrics();
    //header->resizeSection(0, fm.width("typical-name-for-a-torrent.torrent"));
159 160
    header->setResizeMode(0, QHeaderView::Fixed);
    header->resizeSection(0, 30);
161
    header->setResizeMode(1, QHeaderView::Interactive);
162 163 164 165
    header->resizeSection(1, fm.width("typical-name-for-a-file.torrent"));
    header->setResizeMode(2, QHeaderView::Fixed);
    header->resizeSection(1, width() * 2 / 3);
    header->setResizeMode(2, QHeaderView::Interactive);
166 167
    //header->setResizeMode(1, QHeaderView::Fixed);

168 169 170 171
    m_view.scripts_list->setHeaderLabels(QStringList() << i18n("Script Files"));
    m_view.scripts_list->setItemDelegate(new RenderScriptDelegate(this));


172
    focusFirstVisibleItem();
173 174
}

175 176
void RenderWidget::slotEditItem(QListWidgetItem *item)
{
177 178
    QString edit = item->data(EditableRole).toString();
    if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) slotSaveProfile();
179 180 181
    else slotEditProfile();
}

182 183
void RenderWidget::showInfoPanel()
{
184 185 186 187 188 189 190 191 192
    if (m_view.advanced_params->isVisible()) {
        m_view.advanced_params->setVisible(false);
        m_view.buttonInfo->setDown(false);
        KdenliveSettings::setShowrenderparams(false);
    } else {
        m_view.advanced_params->setVisible(true);
        m_view.buttonInfo->setDown(true);
        KdenliveSettings::setShowrenderparams(true);
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
193 194
}

195 196
void RenderWidget::setDocumentPath(const QString path)
{
197 198 199
    m_projectFolder = path;
    const QString fileName = m_view.out_file->url().fileName();
    m_view.out_file->setUrl(KUrl(m_projectFolder + '/' + fileName));
200
    parseScriptFiles();
201 202
}

203 204
void RenderWidget::slotUpdateGuideBox()
{
205 206 207
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

208 209
void RenderWidget::slotCheckStartGuidePosition()
{
210 211 212 213
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
}

214 215
void RenderWidget::slotCheckEndGuidePosition()
{
216 217 218 219
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
}

220 221
void RenderWidget::setGuides(QDomElement guidesxml, double duration)
{
222 223 224 225
    m_view.guide_start->clear();
    m_view.guide_end->clear();
    QDomNodeList nodes = guidesxml.elementsByTagName("guide");
    if (nodes.count() > 0) {
226
        m_view.guide_start->addItem(i18n("Render"), "0");
227
        m_view.render_guide->setEnabled(true);
228 229 230 231 232
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
233 234 235 236 237 238 239 240 241 242 243
    for (int i = 0; i < nodes.count(); i++) {
        QDomElement e = nodes.item(i).toElement();
        if (!e.isNull()) {
            m_view.guide_start->addItem(e.attribute("comment"), e.attribute("time").toDouble());
            m_view.guide_end->addItem(e.attribute("comment"), e.attribute("time").toDouble());
        }
    }
    if (nodes.count() > 0)
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
}

244 245
// Will be called when the user selects an output file via the file dialog.
// File extension will be added automatically.
246 247
void RenderWidget::slotUpdateButtons(KUrl url)
{
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 252 253 254
        QListWidgetItem *item = m_view.size_list->currentItem();
        QString extension = item->data(ExtensionRole).toString();
        url = filenameWithExtension(url, extension);
        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 261
void RenderWidget::slotUpdateButtons()
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
262
    if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
263
    else m_view.buttonStart->setEnabled(true);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
264 265
}

266 267
void RenderWidget::slotSaveProfile()
{
268
    //TODO: update to correctly use metagroups
269 270 271
    Ui::SaveProfile_UI ui;
    QDialog *d = new QDialog(this);
    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 280 281
    QString customGroup = m_view.format_list->currentItem()->text();
    if (customGroup.isEmpty()) customGroup = i18n("Custom");
    ui.group_name->setText(customGroup);
282

283
    ui.parameters->setText(m_view.advanced_params->toPlainText());
284 285
    ui.extension->setText(m_view.size_list->currentItem()->data(ExtensionRole).toString());
    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 289 290 291 292
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
        QDomElement profiles = doc.documentElement();
        if (profiles.isNull() || profiles.tagName() != "profiles") {
            doc.clear();
            profiles = doc.createElement("profiles");
            profiles.setAttribute("version", 1);
            doc.appendChild(profiles);
        }
        int version = profiles.attribute("version", 0).toInt();
        if (version < 1) {
            kDebug() << "// OLD profile version";
            doc.clear();
            profiles = doc.createElement("profiles");
            profiles.setAttribute("version", 1);
            doc.appendChild(profiles);
        }

309
        QString newProfileName = ui.profile_name->text().simplified();
310 311 312 313
        QString newGroupName = ui.group_name->text().simplified();
        if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
        QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
        QDomNodeList profilelist = doc.elementsByTagName("profile");
314
        int i = 0;
315 316 317 318 319 320 321 322 323 324 325
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
            QString profileName = documentElement.attribute("name");
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
                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);
                if (!ok) return;
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
326 327 328
                    break;
                }
            }
329
            i++;
330
        }
331

332 333
        QDomElement profileElement = doc.createElement("profile");
        profileElement.setAttribute("name", newProfileName);
334 335
        profileElement.setAttribute("category", newGroupName);
        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 341 342 343 344 345 346 347 348

        //QCString save = doc.toString().utf8();

        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
            delete d;
            return;
        }
        QTextStream out(&file);
        out << doc.toString();
349 350 351
        if (file.error() != QFile::NoError) {
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
            file.close();
Ray Lehtiniemi's avatar
Ray Lehtiniemi committed
352
            delete d;
353 354
            return;
        }
355
        file.close();
356
        parseProfiles(newMetaGroupId, newGroupName, newProfileName);
357 358 359 360
    }
    delete d;
}

361 362
void RenderWidget::slotEditProfile()
{
363 364 365 366 367 368 369 370 371 372 373
    QListWidgetItem *item = m_view.size_list->currentItem();
    if (!item) return;
    QString currentGroup = m_view.format_list->currentItem()->text();

    QString params = item->data(ParamsRole).toString();
    QString extension = item->data(ExtensionRole).toString();
    QString currentProfile = item->text();

    Ui::SaveProfile_UI ui;
    QDialog *d = new QDialog(this);
    ui.setupUi(d);
374 375 376 377 378 379 380 381 382 383 384

    for (int i = 0; i < m_view.destination_list->count(); i++)
        ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));

    ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
    QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();

    QString customGroup = m_view.format_list->currentItem()->text();
    if (customGroup.isEmpty()) customGroup = i18n("Custom");
    ui.group_name->setText(customGroup);

385 386 387 388
    ui.profile_name->setText(currentProfile);
    ui.extension->setText(extension);
    ui.parameters->setText(params);
    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 394 395 396 397
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
        QDomElement profiles = doc.documentElement();

        if (profiles.isNull() || profiles.tagName() != "profiles") {
            doc.clear();
            profiles = doc.createElement("profiles");
            profiles.setAttribute("version", 1);
            doc.appendChild(profiles);
        }

        int version = profiles.attribute("version", 0).toInt();
        if (version < 1) {
            kDebug() << "// OLD profile version";
            doc.clear();
            profiles = doc.createElement("profiles");
            profiles.setAttribute("version", 1);
413
            doc.appendChild(profiles);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
        if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
        QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
        QDomNodeList profilelist = doc.elementsByTagName("profile");
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
            QString profileName = documentElement.attribute("name");
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
                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);
                if (!ok) return;
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
433 434 435
                    break;
                }
            }
436
            i++;
437
        }
438

439 440
        QDomElement profileElement = doc.createElement("profile");
        profileElement.setAttribute("name", newProfileName);
441 442
        profileElement.setAttribute("category", newGroupName);
        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 452 453 454
            return;
        }
        QTextStream out(&file);
        out << doc.toString();
455 456 457 458 459
        if (file.error() != QFile::NoError) {
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
            file.close();
            return;
        }
460
        file.close();
461
        parseProfiles(newMetaGroupId, newGroupName, newProfileName);
462
    } else delete d;
463 464
}

465 466
void RenderWidget::slotDeleteProfile(bool refresh)
{
467 468 469 470 471 472 473 474 475 476 477
    //TODO: delete a profile installed by KNewStuff the easy way
    /*
    QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
    if (!edit.endsWith("customprofiles.xml")) {
        // This is a KNewStuff installed file, process through KNS
        KNS::Engine engine(0);
        if (engine.init("kdenlive_render.knsrc")) {
            KNS::Entry::List entries;
        }
        return;
    }*/
478 479
    QString currentGroup = m_view.format_list->currentItem()->text();
    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 484 485 486 487 488
    QDomDocument doc;
    QFile file(exportFile);
    doc.setContent(&file, false);
    file.close();

    QDomElement documentElement;
489
    QDomNodeList profiles = doc.elementsByTagName("profile");
490
    int i = 0;
491 492 493
    QString groupName;
    QString profileName;
    QString destination;
494

495 496 497 498 499 500 501 502 503
    while (!profiles.item(i).isNull()) {
        documentElement = profiles.item(i).toElement();
        profileName = documentElement.attribute("name");
        groupName = documentElement.attribute("category");
        destination = documentElement.attribute("destinationid");

        if (profileName == currentProfile && groupName == currentGroup && destination == metaGroupId) {
            kDebug() << "// GOT it: " << profileName;
            doc.documentElement().removeChild(profiles.item(i));
504 505 506 507 508 509 510 511 512 513 514
            break;
        }
        i++;
    }

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
        return;
    }
    QTextStream out(&file);
    out << doc.toString();
515 516 517 518 519
    if (file.error() != QFile::NoError) {
        KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
        file.close();
        return;
    }
520
    file.close();
521 522 523 524
    if (refresh) {
        parseProfiles(metaGroupId, currentGroup);
        focusFirstVisibleItem();
    }
525 526
}

527 528
void RenderWidget::updateButtons()
{
529 530 531 532
    if (!m_view.size_list->currentItem() || m_view.size_list->currentItem()->isHidden()) {
        m_view.buttonSave->setEnabled(false);
        m_view.buttonDelete->setEnabled(false);
        m_view.buttonEdit->setEnabled(false);
533
        m_view.buttonStart->setEnabled(false);
534 535
    } else {
        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();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
538
        if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
539 540 541
            m_view.buttonDelete->setEnabled(false);
            m_view.buttonEdit->setEnabled(false);
        } else {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
542 543
            m_view.buttonDelete->setEnabled(true);
            m_view.buttonEdit->setEnabled(true);
544 545 546 547 548
        }
    }
}


549 550
void RenderWidget::focusFirstVisibleItem()
{
551 552 553 554
    if (m_view.size_list->currentItem() && !m_view.size_list->currentItem()->isHidden()) {
        updateButtons();
        return;
    }
555
    for (int ix = 0; ix < m_view.size_list->count(); ix++) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
556 557 558 559 560
        QListWidgetItem *item = m_view.size_list->item(ix);
        if (item && !item->isHidden()) {
            m_view.size_list->setCurrentRow(ix);
            break;
        }
561 562
    }
    if (!m_view.size_list->currentItem()) m_view.size_list->setCurrentRow(0);
563
    updateButtons();
564 565
}

566 567
void RenderWidget::slotExport(bool scriptExport)
{
568 569
    QListWidgetItem *item = m_view.size_list->currentItem();
    if (!item) return;
570

571 572 573
    const QString dest = m_view.out_file->url().path();
    if (dest.isEmpty()) return;
    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 577
            return;
    }
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

    QString scriptName;
    if (scriptExport) {
        bool ok;
        int ix = 0;
        QString scriptsFolder = m_projectFolder + "/scripts/";
        KStandardDirs::makeDir(scriptsFolder);
        QString path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
        while (QFile::exists(path)) {
            ix++;
            path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
        }
        scriptName = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
        if (!ok || scriptName.isEmpty()) return;
        scriptName.prepend(scriptsFolder);
        QFile f(scriptName);
        if (f.exists()) {
595
            if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
596 597 598 599
                return;
        }
    }

600 601 602 603 604 605 606
    QStringList overlayargs;
    if (m_view.tc_overlay->isChecked()) {
        QString filterFile = KStandardDirs::locate("appdata", "metadata.properties");
        overlayargs << "meta.attr.timecode=1" << "meta.attr.timecode.markup=#timecode";
        overlayargs << "-attach" << "data_feed:attr_check" << "-attach";
        overlayargs << "data_show:" + filterFile << "_fezzik=1" << "dynamic=1";
    }
607 608 609 610 611 612
    double startPos = -1;
    double endPos = -1;
    if (m_view.render_guide->isChecked()) {
        startPos = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
        endPos = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
    }
613
    QString renderArgs = m_view.advanced_params->toPlainText().simplified();
614 615 616 617 618 619 620 621 622 623 624

    // Adjust frame scale
    int width;
    int height;
    if (m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
        width = m_view.rescale_size->text().section('x', 0, 0).toInt();
        height = m_view.rescale_size->text().section('x', 1, 1).toInt();
    } else {
        width = m_profile.width;
        height = m_profile.height;
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
625
    renderArgs.replace("%dar", '@' + QString::number(m_profile.display_aspect_num) + '/' + QString::number(m_profile.display_aspect_den));
626 627 628 629 630 631 632 633

    // Adjust scanning
    if (m_view.scanning_list->currentIndex() == 1) renderArgs.append(" progressive=1");
    else if (m_view.scanning_list->currentIndex() == 2) renderArgs.append(" progressive=0");

    // disable audio if requested
    if (!m_view.export_audio->isChecked())
        renderArgs.append(" an=1 ");
634 635 636 637 638

    // Check if the rendering profile is different from project profile,
    // in which case we need to use the producer_comsumer from MLT
    bool resizeProfile = false;

639
    QString std = renderArgs;
640
    QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
641 642 643 644 645 646
    if (std.startsWith("s=")) {
        QString subsize = std.section(' ', 0, 0).toLower();
        subsize = subsize.section("=", 1, 1);
        const QString currentSize = QString::number(width) + 'x' + QString::number(height);
        if (subsize != currentSize) resizeProfile = true;
    } else if (std.contains(" s=")) {
647 648
        QString subsize = std.section(" s=", 1, 1);
        subsize = subsize.section(' ', 0, 0).toLower();
649
        const QString currentSize = QString::number(width) + 'x' + QString::number(height);
650
        if (subsize != currentSize) resizeProfile = true;
651
    } else if (destination != "audioonly") {
652
        // Add current size parametrer
653
        renderArgs.append(QString(" s=%1x%2").arg(width).arg(height));
654 655
    }

656 657
    // insert item in running jobs list
    QTreeWidgetItem *renderItem;
658
    QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
659 660 661 662 663 664 665 666 667 668 669 670
    if (!existing.isEmpty()) {
        renderItem = existing.at(0);
        if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
            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"));
            return;
        }
    } else {
        renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
        renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
        renderItem->setIcon(0, KIcon("media-playback-pause"));
        renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
    }
671
    renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
672
    renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
673 674 675 676 677 678
    renderItem->setData(1, Qt::UserRole + 2, overlayargs);
    QStringList renderParameters;
    renderParameters << dest << item->data(RenderRole).toString() << renderArgs.simplified();
    renderParameters << QString::number(m_view.render_zone->isChecked()) << QString::number(m_view.play_after->isChecked());
    renderParameters << QString::number(startPos) << QString::number(endPos) << QString::number(resizeProfile);
    renderParameters << scriptName;
679

680
    // Set rendering type
681
    QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    if (group == "dvd") {
        renderParameters << QString::number(m_view.create_chapter->isChecked());
        if (m_view.open_dvd->isChecked()) {
            renderItem->setData(0, Qt::UserRole, group);
            if (renderArgs.contains("profile=")) {
                // rendering profile contains an MLT profile, so pass it to the running jog item, useful for dvd
                QString prof = renderArgs.section("profile=", 1, 1);
                prof = prof.section(' ', 0, 0);
                kDebug() << "// render profile: " << prof;
                renderItem->setData(0, Qt::UserRole + 1, prof);
            }
        }
    } else {
        renderParameters << QString::number(false);
        if (group == "websites" && m_view.open_browser->isChecked()) {
            renderItem->setData(0, Qt::UserRole, group);
            // pass the url
            QString url = m_view.size_list->currentItem()->data(ExtraRole).toString();
            renderItem->setData(0, Qt::UserRole + 1, url);
701 702
        }
    }
703

704 705 706

    renderItem->setData(1, Qt::UserRole + 3, renderParameters);

707
    checkRenderStatus();
708 709 710 711 712
    if (scriptName.isEmpty()) m_view.tabWidget->setCurrentIndex(1);
    else {
        QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
        m_view.tabWidget->setCurrentIndex(2);
    }
713 714
}

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
void RenderWidget::checkRenderStatus()
{
    QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
    while (item) {
        if (item->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) break;
        else if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
            item->setData(1, Qt::UserRole + 1, QTime::currentTime());
            if (item->data(1, Qt::UserRole + 4).isNull())
                emit doRender(item->data(1, Qt::UserRole + 3).toStringList(), item->data(1, Qt::UserRole + 2).toStringList());
            else QProcess::startDetached(item->data(1, Qt::UserRole + 3).toString());
            break;
        }
        item = m_view.running_jobs->itemBelow(item);
    }
}

731 732
void RenderWidget::setProfile(MltVideoProfile profile)
{
733 734 735
    m_profile = profile;
    //WARNING: this way to tell the video standard is a bit hackish...
    if (m_profile.description.contains("pal", Qt::CaseInsensitive) || m_profile.description.contains("25", Qt::CaseInsensitive) || m_profile.description.contains("50", Qt::CaseInsensitive)) m_view.format_selection->setCurrentIndex(0);
736
    else m_view.format_selection->setCurrentIndex(1);
737
    m_view.scanning_list->setCurrentIndex(0);
738 739 740
    refreshView();
}

741 742
void RenderWidget::refreshView()
{
743
    m_view.size_list->blockSignals(true);
744 745 746
    QListWidgetItem *sizeItem;

    QString destination;
747
    KIcon brokenIcon("dialog-close");
748 749 750
    if (m_view.destination_list->currentIndex() > 0)
        destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();

751

752 753 754 755 756 757 758
    if (destination == "dvd") {
        m_view.open_dvd->setVisible(true);
        m_view.create_chapter->setVisible(true);
    } else {
        m_view.open_dvd->setVisible(false);
        m_view.create_chapter->setVisible(false);
    }
759 760 761 762 763 764 765 766
    if (destination == "websites") m_view.open_browser->setVisible(true);
    else m_view.open_browser->setVisible(false);
    if (!destination.isEmpty() && QString("dvd websites audioonly").contains(destination))
        m_view.rescale->setEnabled(false);
    else m_view.rescale->setEnabled(true);
    // hide groups that are not in the correct destination
    for (int i = 0; i < m_view.format_list->count(); i++) {
        sizeItem = m_view.format_list->item(i);
767
        if (sizeItem->data(MetaGroupRole).toString() == destination) {
768
            sizeItem->setHidden(false);
769
            //kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
770
        } else sizeItem->setHidden(true);
771 772 773 774 775 776 777 778 779 780 781
    }

    // activate first visible item
    QListWidgetItem * item = m_view.format_list->currentItem();
    if (!item || item->isHidden()) {
        for (int i = 0; i < m_view.format_list->count(); i++) {
            if (!m_view.format_list->item(i)->isHidden()) {
                m_view.format_list->setCurrentRow(i);
                break;
            }
        }
782 783
        item = m_view.format_list->currentItem();
    }
784 785 786 787 788 789 790 791
    if (!item || item->isHidden()) {
        m_view.format_list->setEnabled(false);
        m_view.size_list->setEnabled(false);
        return;
    } else {
        m_view.format_list->setEnabled(true);
        m_view.size_list->setEnabled(true);
    }
792 793 794 795 796 797
    int count = 0;
    for (int i = 0; i < m_view.format_list->count() && count < 2; i++) {
        if (!m_view.format_list->isRowHidden(i)) count++;
    }
    if (count > 1) m_view.format_list->setVisible(true);
    else m_view.format_list->setVisible(false);
798 799 800
    QString std;
    QString group = item->text();
    bool firstSelected = false;
801 802 803
    const QStringList formatsList = KdenliveSettings::supportedformats();
    const QStringList vcodecsList = KdenliveSettings::videocodecs();
    const QStringList acodecsList = KdenliveSettings::audiocodecs();
804

805 806
    for (int i = 0; i < m_view.size_list->count(); i++) {
        sizeItem = m_view.size_list->item(i);
807
        if ((sizeItem->data(GroupRole) == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole) == destination) {
808
            std = sizeItem->data(StandardRole).toString();
809 810 811 812 813 814 815 816
            if (!std.isEmpty()) {
                if (std.contains("PAL", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 0);
                else if (std.contains("NTSC", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 1);
            } else {
                sizeItem->setHidden(false);
                if (!firstSelected) m_view.size_list->setCurrentItem(sizeItem);
                firstSelected = true;
            }
817

818 819 820 821 822 823 824 825 826 827 828
            if (!sizeItem->isHidden()) {
                // Make sure the selected profile uses an installed avformat codec / format
                std = sizeItem->data(ParamsRole).toString();

                if (!formatsList.isEmpty()) {
                    QString format;
                    if (std.startsWith("f=")) format = std.section("f=", 1, 1);
                    else if (std.contains(" f=")) format = std.section(" f=", 1, 1);
                    if (!format.isEmpty()) {
                        format = format.section(' ', 0, 0).toLower();
                        if (!formatsList.contains(format)) {
829
                            kDebug() << "***** UNSUPPORTED F: " << format;
830
                            //sizeItem->setHidden(true);
831
                            sizeItem->setFlags(Qt::ItemIsSelectable);
832 833
                            sizeItem->setToolTip(i18n("Unsupported video format: %1", format));
                            sizeItem->setIcon(brokenIcon);
834 835 836 837 838 839 840 841 842 843 844
                        }
                    }
                }
                if (!acodecsList.isEmpty() && !sizeItem->isHidden()) {
                    QString format;
                    if (std.startsWith("acodec=")) format = std.section("acodec=", 1, 1);
                    else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
                    if (!format.isEmpty()) {
                        format = format.section(' ', 0, 0).toLower();
                        if (!acodecsList.contains(format)) {
                            kDebug() << "*****  UNSUPPORTED ACODEC: " << format;
845
                            //sizeItem->setHidden(true);
846
                            sizeItem->setFlags(Qt::ItemIsSelectable);
847 848
                            sizeItem->setToolTip(i18n("Unsupported audio codec: %1", format));
                            sizeItem->setIcon(brokenIcon);
849 850 851 852 853 854 855 856 857 858 859
                        }
                    }
                }
                if (!vcodecsList.isEmpty() && !sizeItem->isHidden()) {
                    QString format;
                    if (std.startsWith("vcodec=")) format = std.section("vcodec=", 1, 1);
                    else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
                    if (!format.isEmpty()) {
                        format = format.section(' ', 0, 0).toLower();
                        if (!vcodecsList.contains(format)) {
                            kDebug() << "*****  UNSUPPORTED VCODEC: " << format;
860
                            //sizeItem->setHidden(true);
861
                            sizeItem->setFlags(Qt::ItemIsSelectable);
862 863
                            sizeItem->setToolTip(i18n("Unsupported video codec: %1", format));
                            sizeItem->setIcon(brokenIcon);
864 865 866 867
                        }
                    }
                }
            }
868 869
        } else sizeItem->setHidden(true);
    }
870
    focusFirstVisibleItem();
871 872
    m_view.size_list->blockSignals(false);
    refreshParams();
873 874
}

875 876
KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension)
{
877 878 879 880 881 882 883 884
    QString path;
    if (!url.isEmpty()) {
        path = url.path();
        int pos = path.lastIndexOf('.') + 1;
        if (pos == 0) path.append('.' + extension);
        else path = path.left(pos) + extension;

    } else {
885
        path = m_projectFolder + "/untitled." + extension;
886 887 888 889 890
    }
    return KUrl(path);
}


891 892
void RenderWidget::refreshParams()
{
893
    QListWidgetItem *item = m_view.size_list->currentItem();
894 895 896 897 898
    if (!item || item->isHidden()) {
        m_view.advanced_params->clear();
        m_view.buttonStart->setEnabled(false);
        return;
    }
899 900
    QString params = item->data(ParamsRole).toString();
    QString extension = item->data(ExtensionRole).toString();
901
    m_view.advanced_params->setPlainText(params);
902 903 904 905 906 907 908 909 910
    QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
    if (params.contains(" s=") || destination == "audioonly") {
        // profile has a fixed size, do not allow resize
        m_view.rescale->setEnabled(false);
        m_view.rescale_size->setEnabled(false);
    } else {
        m_view.rescale->setEnabled(true);
        m_view.rescale_size->setEnabled(true);
    }
911 912 913 914 915 916 917 918 919 920 921
    KUrl url = filenameWithExtension(m_view.out_file->url(), extension);
    m_view.out_file->setUrl(url);
//     if (!url.isEmpty()) {
//         QString path = url.path();
//         int pos = path.lastIndexOf('.') + 1;
//  if (pos == 0) path.append('.' + extension);
//         else path = path.left(pos) + extension;
//         m_view.out_file->setUrl(KUrl(path));
//     } else {
//         m_view.out_file->setUrl(KUrl(QDir::homePath() + "/untitled." + extension));
//     }
922
    m_view.out_file->setFilter("*." + extension);
923
    QString edit = item->data(EditableRole).toString();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
924
    if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
925 926 927
        m_view.buttonDelete->setEnabled(false);
        m_view.buttonEdit->setEnabled(false);
    } else {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
928 929
        m_view.buttonDelete->setEnabled(true);
        m_view.buttonEdit->setEnabled(true);
930
    }
931 932

    m_view.buttonStart->setEnabled(m_view.size_list->currentItem()->flags() & Qt::ItemIsEnabled);
933 934
}

935 936
void RenderWidget::reloadProfiles()
{
937 938 939
    parseProfiles();
}

940 941
void RenderWidget::parseProfiles(QString meta, QString group, QString profile)
{
942 943
    m_view.size_list->clear();
    m_view.format_list->clear();
944 945
    m_view.destination_list->clear();
    m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
946 947 948 949 950 951 952
    m_view.destination_list->addItem(KIcon("media-optical"), i18n("DVD"), "dvd");
    m_view.destination_list->addItem(KIcon("audio-x-generic"), i18n("Audio only"), "audioonly");
    m_view.destination_list->addItem(KIcon("applications-internet"), i18n("Web sites"), "websites");
    m_view.destination_list->addItem(KIcon("applications-multimedia"), i18n("Media players"), "mediaplayers");
    m_view.destination_list->addItem(KIcon("drive-harddisk"), i18n("Lossless / HQ"), "lossless");
    m_view.destination_list->addItem(KIcon("pda"), i18n("Mobile devices"), "mobile");

953
    QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
954
    parseFile(exportFile, false);
955 956 957 958 959 960


    QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
    QDir directory = QDir(exportFolder);
    QStringList filter;
    filter << "*.xml";
961 962 963 964
    QStringList fileList = directory.entryList(filter, QDir::Files);
    // We should parse customprofiles.xml in last position, so that user profiles
    // can also override profiles installed by KNewStuff
    fileList.removeAll("customprofiles.xml");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
965
    foreach(const QString &filename, fileList)
966
    parseFile(exportFolder + '/' + filename, true);
967
    if (QFile::exists(exportFolder + "/customprofiles.xml")) parseFile(exportFolder + "/customprofiles.xml", true);
968

969 970 971 972 973
    if (!meta.isEmpty()) {
        m_view.destination_list->blockSignals(true);
        m_view.destination_list->setCurrentIndex(m_view.destination_list->findData(meta));
        m_view.destination_list->blockSignals(false);
    }
974
    refreshView();
975
    QList<QListWidgetItem *> child;
976
    if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
977 978 979 980 981 982 983 984
    if (!child.isEmpty()) {
        for (int i = 0; i < child.count(); i++) {
            if (child.at(i)->data(MetaGroupRole).toString() == meta) {
                m_view.format_list->setCurrentItem(child.at(i));
                break;
            }