renderwidget.cpp 112 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"
24
#include "timecode.h"
Vincent Pinon's avatar
Vincent Pinon committed
25
#include "dialogs/profilesdialog.h"
26
#include "utils/KoIconUtils.h"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
27

28
#include "klocalizedstring.h"
29
#include <KMessageBox>
30
#include <KRun>
31
#include <KColorScheme>
32
#include <KNotification>
33

34 35
#include <qglobal.h>
#include <qstring.h>
36
#include <QDebug>
37 38
#include <QDomDocument>
#include <QTreeWidgetItem>
39
#include <QTreeWidgetItem>
40 41
#include <QHeaderView>
#include <QInputDialog>
42
#include <QProcess>
43
#include <QDBusConnectionInterface>
44
#include <QThread>
45
#include <QScriptEngine>
46
#include <QKeyEvent>
47
#include <QTimer>
48
#include <QStandardPaths>
49
#include <QDir>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
50

Vincent Pinon's avatar
Vincent Pinon committed
51
#include <locale>
52 53 54
#ifdef Q_OS_MAC
#include <xlocale.h>
#endif
55

56 57

// Render profiles roles
58 59 60 61 62 63 64 65 66 67
enum {GroupRole = Qt::UserRole,
      ExtensionRole,
      StandardRole,
      RenderRole,
      ParamsRole,
      EditableRole,
      ExtraRole,
      BitratesRole,
      DefaultBitrateRole,
      AudioBitratesRole,
68
      DefaultAudioBitrateRole,
69
      SpeedsRole,
70
      ErrorRole
71
     };
72

73 74 75
// Render job roles
const int ParametersRole = Qt::UserRole + 1;
const int TimeRole = Qt::UserRole + 2;
76 77
const int ProgressRole = Qt::UserRole + 3;
const int ExtraInfoRole = Qt::UserRole + 5;
78

79 80
const int DirectRenderType = QTreeWidgetItem::Type;
const int ScriptRenderType = QTreeWidgetItem::UserType;
81 82


83
// Running job status
84 85 86 87 88 89 90 91
enum JOBSTATUS {
    WAITINGJOB = 0,
    STARTINGJOB,
    RUNNINGJOB,
    FINISHEDJOB,
    FAILEDJOB,
    ABORTEDJOB
};
92 93


Laurent Montel's avatar
Laurent Montel committed
94 95
RenderJobItem::RenderJobItem(QTreeWidget * parent, const QStringList & strings, int type)
    : QTreeWidgetItem(parent, strings, type),
96 97
    m_status(-1)
{
98
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
99 100 101 102 103
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
Laurent Montel's avatar
Laurent Montel committed
104 105
    if (m_status == status)
        return;
106 107 108
    m_status = status;
    switch (status) {
        case WAITINGJOB:
109
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("media-playback-pause")));
110 111 112 113
            setData(1, Qt::UserRole, i18n("Waiting..."));
            break;
        case FINISHEDJOB:
            setData(1, Qt::UserRole, i18n("Rendering finished"));
114
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-ok")));
115
            setData(1, ProgressRole, 100);
116 117 118
            break;
        case FAILEDJOB:
            setData(1, Qt::UserRole, i18n("Rendering crashed"));
119
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-close")));
120
            setData(1, ProgressRole, 100);
121 122 123
            break;
        case ABORTEDJOB:
            setData(1, Qt::UserRole, i18n("Rendering aborted"));
124
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-cancel")));
125
            setData(1, ProgressRole, 100);
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        default:
            break;
    }
}

int RenderJobItem::status() const
{
    return m_status;
}

void RenderJobItem::setMetadata(const QString &data)
{
    m_data = data;
}

const QString RenderJobItem::metadata() const
{
    return m_data;
}
145 146


Laurent Montel's avatar
Laurent Montel committed
147
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, const MltVideoProfile &profile, QWidget * parent) :
148
        QDialog(parent),
149
        m_projectFolder(projectfolder),
150
        m_profile(profile),
151
        m_blockProcessing(false)
152
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
153
    m_view.setupUi(this);
154 155
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
156

157
    setWindowTitle(i18n("Rendering"));
158 159 160 161
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
162

163
    m_view.buttonDelete->setIcon(KoIconUtils::themedIcon(QStringLiteral("trash-empty")));
164 165 166
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

167
    m_view.buttonEdit->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-properties")));
168 169 170
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

171
    m_view.buttonSave->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-new")));
172 173
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

174
    m_view.hide_log->setIcon(KoIconUtils::themedIcon(QStringLiteral("go-down")));
175

176
    m_view.buttonFavorite->setIcon(KoIconUtils::themedIcon(QStringLiteral("favorite")));
177
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
178

179
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
180

181 182 183 184 185 186 187 188 189 190 191 192
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.optionsGroup, SLOT(setVisible(bool)));
    m_view.videoLabel->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.videoLabel, SLOT(setVisible(bool)));
    m_view.video->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.video, SLOT(setVisible(bool)));
    m_view.audioLabel->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.audioLabel, SLOT(setVisible(bool)));
    m_view.audio->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.audio, SLOT(setVisible(bool)));
    connect(m_view.quality, SIGNAL(valueChanged(int)), this, SLOT(adjustAVQualities(int)));
    connect(m_view.video, SIGNAL(valueChanged(int)), this, SLOT(adjustQuality(int)));
193
    connect(m_view.speed, SIGNAL(valueChanged(int)), this, SLOT(adjustSpeed(int)));
194

195 196
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
197
    setRescaleEnabled(false);
198 199 200 201 202 203 204
    m_view.guides_box->setVisible(false);
    m_view.open_dvd->setVisible(false);
    m_view.create_chapter->setVisible(false);
    m_view.open_browser->setVisible(false);
    m_view.error_box->setVisible(false);
    m_view.tc_type->setEnabled(false);
    m_view.checkTwoPass->setEnabled(false);
205
    m_view.proxy_render->setHidden(!enableProxy);
206

207 208
    KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
    QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
209
    m_view.errorBox->setStyleSheet(QStringLiteral("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
210
    int height = QFontInfo(font()).pixelSize();
211
    m_view.errorIcon->setPixmap(KoIconUtils::themedIcon(QStringLiteral("dialog-warning")).pixmap(height, height));
212 213 214
    m_view.errorBox->setHidden(true);

    m_infoMessage = new KMessageWidget;
215
    m_view.info->addWidget(m_infoMessage);
216 217 218
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

219 220 221 222
    m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
    m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
    connect(m_view.encoder_threads, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateEncodeThreads(int)));

223 224 225
    m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
    connect(m_view.rescale_width, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleWidth(int)));
    connect(m_view.rescale_height, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleHeight(int)));
226
    m_view.rescale_keep->setIcon(KoIconUtils::themedIcon(QStringLiteral("edit-link")));
227 228
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
    connect(m_view.rescale_keep, SIGNAL(clicked()), this, SLOT(slotSwitchAspectRatio()));
229

230 231 232
    connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
    connect(m_view.buttonGenerateScript, SIGNAL(clicked()), this, SLOT(slotGenerateScript()));

233 234 235 236
    m_view.abort_job->setEnabled(false);
    m_view.start_script->setEnabled(false);
    m_view.delete_script->setEnabled(false);

237 238 239
    connect(m_view.export_audio, SIGNAL(stateChanged(int)), this, SLOT(slotUpdateAudioLabel(int)));
    m_view.export_audio->setCheckState(Qt::PartiallyChecked);

240
    parseProfiles();
241
    parseScriptFiles();
242 243
    m_view.running_jobs->setUniformRowHeights(false);
    m_view.scripts_list->setUniformRowHeights(false);
244 245
    connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
    connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
246 247
    connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
    connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
Laurent Montel's avatar
Laurent Montel committed
248
    connect(m_view.running_jobs, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotPlayRendering(QTreeWidgetItem*,int)));
249

250
    connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
251
    connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
252
    connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
253 254
    connect(m_view.buttonFavorite, SIGNAL(clicked()), this, SLOT(slotCopyToFavorites()));

255
    connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
256
    connect(m_view.start_job, SIGNAL(clicked()), this, SLOT(slotStartCurrentJob()));
257 258 259
    connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
    connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));

260 261
    connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
    connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
262
    connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
263
    connect(m_view.rescale, SIGNAL(toggled(bool)), this, SLOT(setRescaleEnabled(bool)));
Laurent Montel's avatar
Laurent Montel committed
264
    connect(m_view.out_file, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons()));
265
    connect(m_view.out_file, SIGNAL(urlSelected(QUrl)), this, SLOT(slotUpdateButtons(QUrl)));
266

267 268
    connect(m_view.formats, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(refreshParams()));
    connect(m_view.formats, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotEditItem(QTreeWidgetItem*)));
269

270 271 272 273 274 275 276
    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()));

277
    connect(m_view.tc_overlay, SIGNAL(toggled(bool)), m_view.tc_type, SLOT(setEnabled(bool)));
278

279 280
    //m_view.splitter->setStretchFactor(1, 5);
    //m_view.splitter->setStretchFactor(0, 2);
281

282
    m_view.out_file->setMode(KFile::File);
283
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
284

285
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
286 287
    m_jobsDelegate = new RenderViewDelegate(this);
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
288

289
    QHeaderView *header = m_view.running_jobs->header();
290
    header->setSectionResizeMode(0, QHeaderView::Fixed);
291
    header->resizeSection(0, 30);
292
    header->setSectionResizeMode(1, QHeaderView::Interactive);
293

294
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
295 296
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
297
    header = m_view.scripts_list->header();
298
    header->setSectionResizeMode(0, QHeaderView::Fixed);
299
    header->resizeSection(0, 30);
300

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
301
    // Find path for Kdenlive renderer
302
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
303
    if (!QFile::exists(m_renderer)) {
304
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
Laurent Montel's avatar
Laurent Montel committed
305
        if (m_renderer.isEmpty())
306
            m_renderer = QStringLiteral("kdenlive_render");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
307 308
    }

309
    QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
310
    if (!interface || (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager"))))
311 312
        m_view.shutdown->setEnabled(false);

313
    focusFirstVisibleItem();
314
    adjustSize();
315 316 317 318 319 320
}

QSize RenderWidget::sizeHint() const
{
    // Make sure the widget has minimum size on opening
    return QSize(200, 200);
321 322
}

323 324 325 326 327 328 329 330
RenderWidget::~RenderWidget()
{
    m_view.running_jobs->blockSignals(true);
    m_view.scripts_list->blockSignals(true);
    m_view.running_jobs->clear();
    m_view.scripts_list->clear();
    delete m_jobsDelegate;
    delete m_scriptsDelegate;
331
    delete m_infoMessage;
332 333
}

334
void RenderWidget::slotEditItem(QTreeWidgetItem *item)
335
{
336 337 338 339
    if (item->parent() == NULL) {
        // This is a top level item - group - don't edit
        return;
    }
340
    const QString edit = item->data(0, EditableRole).toString();
Laurent Montel's avatar
Laurent Montel committed
341 342
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml")))
        slotSaveProfile();
343 344 345
    else slotEditProfile();
}

346 347
void RenderWidget::showInfoPanel()
{
348 349 350 351 352 353 354
    if (m_view.advanced_params->isVisible()) {
        m_view.advanced_params->setVisible(false);
        KdenliveSettings::setShowrenderparams(false);
    } else {
        m_view.advanced_params->setVisible(true);
        KdenliveSettings::setShowrenderparams(true);
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
355 356
}

357
void RenderWidget::setDocumentPath(const QString &path)
358
{
359
    if (m_view.out_file->url().adjusted(QUrl::RemoveFilename).path() == QUrl::fromLocalFile(m_projectFolder).adjusted(QUrl::RemoveFilename).path()) {
360
        const QString fileName = m_view.out_file->url().fileName();
361
        m_view.out_file->setUrl(QUrl(path + fileName));
362
    }
363
    m_projectFolder = path;
364
    parseScriptFiles();
365

366 367
}

368 369
void RenderWidget::slotUpdateGuideBox()
{
370 371 372
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

373 374
void RenderWidget::slotCheckStartGuidePosition()
{
375 376 377 378
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
}

379 380
void RenderWidget::slotCheckEndGuidePosition()
{
381 382 383 384
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
}

385
void RenderWidget::setGuides(QMap <double, QString> guidesData, double duration)
386
{
387 388
    m_view.guide_start->clear();
    m_view.guide_end->clear();
389
    if (!guidesData.isEmpty()) {
390
        m_view.guide_start->addItem(i18n("Beginning"), "0");
391
        m_view.render_guide->setEnabled(true);
392 393 394 395 396
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
397
    double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
398 399 400 401 402 403 404
    QMapIterator<double, QString> i(guidesData);
    while (i.hasNext()) {
        i.next();
        GenTime pos = GenTime(i.key());
        const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
        m_view.guide_start->addItem(i.value() + '/' + guidePos, i.key());
        m_view.guide_end->addItem(i.value() + '/' + guidePos, i.key());
405
    }
406
    if (!guidesData.isEmpty())
407 408 409
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
}

410
/**
Simon Eugster's avatar
Simon Eugster committed
411 412 413
 * Will be called when the user selects an output file via the file dialog.
 * File extension will be added automatically.
 */
414
void RenderWidget::slotUpdateButtons(const QUrl &url)
415
{
416 417 418 419
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonGenerateScript->setEnabled(false);
        m_view.buttonRender->setEnabled(false);
    } else {
420 421
        updateButtons(); // This also checks whether the selected format is available
    }
422
    if (url.isValid()) {
423 424
        QTreeWidgetItem *item = m_view.formats->currentItem();
        if (!item || !item->parent()) { // categories have no parent
425 426
            m_view.buttonRender->setEnabled(false);
            m_view.buttonGenerateScript->setEnabled(false);
427 428
            return;
        }
429
        const QString extension = item->data(0, ExtensionRole).toString();
Laurent Montel's avatar
Laurent Montel committed
430
        m_view.out_file->setUrl(filenameWithExtension(url, extension));
431 432 433
    }
}

Simon Eugster's avatar
Simon Eugster committed
434 435 436 437
/**
 * Will be called when the user changes the output file path in the text line.
 * File extension must NOT be added, would make editing impossible!
 */
438 439
void RenderWidget::slotUpdateButtons()
{
440 441 442 443 444 445
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonRender->setEnabled(false);
        m_view.buttonGenerateScript->setEnabled(false);
    } else {
        updateButtons(); // This also checks whether the selected format is available
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
446 447
}

448 449
void RenderWidget::slotSaveProfile()
{
450
    Ui::SaveProfile_UI ui;
451
    QPointer<QDialog> d = new QDialog(this);
452
    ui.setupUi(d);
453

454
    QString customGroup;
455
    QStringList arguments = m_view.advanced_params->toPlainText().split(' ', QString::SkipEmptyParts);
456
    if (!arguments.isEmpty()) {
457
        ui.parameters->setText(arguments.join(QStringLiteral(" ")));
458
    }
459
    ui.profile_name->setFocus();
460 461
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (item && item->parent()) { //not a category
462
        // Duplicate current item settings
463 464
        customGroup = item->parent()->text(0);
        ui.extension->setText(item->data(0, ExtensionRole).toString());
465 466
        if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
467 468 469 470 471 472
                ui.vbitrates_label->setText(i18n("Qualities"));
                ui.default_vbitrate_label->setText(i18n("Default quality"));
            } else {
                ui.vbitrates_label->setText(i18n("Bitrates"));
                ui.default_vbitrate_label->setText(i18n("Default bitrate"));
            }
473 474
            if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && item->data(0, BitratesRole).toStringList().count()) {
                QStringList bitrates = item->data(0, BitratesRole).toStringList();
475
                ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
476 477
                if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String))
                    ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
478
            }
479
        }
480
        else ui.vbitrates->setHidden(true);
481 482
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
483 484 485 486 487 488
                ui.abitrates_label->setText(i18n("Qualities"));
                ui.default_abitrate_label->setText(i18n("Default quality"));
            } else {
                ui.abitrates_label->setText(i18n("Bitrates"));
                ui.default_abitrate_label->setText(i18n("Default bitrate"));
            }
489 490
            if ( item && item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && item->data(0, AudioBitratesRole).toStringList().count()) {
                QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
491
                ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
492 493
                if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String))
                    ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
494
            }
495
        }
496
        else ui.abitrates->setHidden(true);
497 498 499 500 501

        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
502
    }
503

504 505
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
    ui.group_name->setText(customGroup);
506

507
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
508 509
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
510
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
511 512

        QDomDocument doc;
513 514 515 516
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
517
        QString args = ui.parameters->toPlainText().simplified();
518 519
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
520
            // profile has a variable bitrate
521 522 523 524 525
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());
        } else if (args.contains(QStringLiteral("%quality"))) {
            profileElement.setAttribute(QStringLiteral("defaultquality"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("qualities"), ui.vbitrates_list->text());
526
        }
527

528
        if (args.contains(QStringLiteral("%audiobitrate"))) {
529
            // profile has a variable bitrate
530 531 532
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
533
            // profile has a variable bitrate
534 535
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
536
        }
537
        if (!ui.speeds_list->toPlainText().isEmpty()) {
538 539
            profileElement.setAttribute(QStringLiteral("speeds"), ui.speeds_list->toPlainText().replace('\n', ';').simplified());
        }
540

541 542 543
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

544
        parseProfiles();
545 546 547 548 549
    }
    delete d;
}


550
void RenderWidget::saveProfile(const QDomElement &newprofile)
551
{
552 553
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/");
    if (!dir.exists()) {
554
        dir.mkpath(QStringLiteral("."));
555
    }
556
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
557
    QDomDocument doc;
558
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
559 560 561 562
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
563
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
564
        doc.clear();
565 566
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
567 568
        doc.appendChild(profiles);
    }
569
    int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
570 571
    if (version < 1) {
        doc.clear();
572 573
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
574 575
        doc.appendChild(profiles);
    }
576

577

578
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
579 580 581 582
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        // make sure a profile with same name doesn't exist
        documentElement = profilelist.item(i).toElement();
583 584
        QString profileName = documentElement.attribute(QStringLiteral("name"));
        if (profileName == newprofile.attribute(QStringLiteral("name"))) {
585 586
            // a profile with that same name already exists
            bool ok;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
587
            QString 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, profileName, &ok);
588 589 590 591
            if (!ok) return;
            if (profileName == newProfileName) {
                profiles.removeChild(profilelist.item(i));
                break;
592 593
            }
        }
594
        ++i;
595
    }
596

597
    profiles.appendChild(newprofile);
598

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

601
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
602
        KMessageBox::sorry(this, i18n("Unable to write to file %1", dir.absoluteFilePath("customprofiles.xml")));
603 604 605 606 607
        return;
    }
    QTextStream out(&file);
    out << doc.toString();
    if (file.error() != QFile::NoError) {
608
        KMessageBox::error(this, i18n("Cannot write to file %1", dir.absoluteFilePath("customprofiles.xml")));
609
        file.close();
610 611 612
        return;
    }
    file.close();
613 614 615 616
}

void RenderWidget::slotCopyToFavorites()
{
617 618
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent())
Laurent Montel's avatar
Laurent Montel committed
619
        return;
620
    QString currentGroup = item->parent()->text(0);
621

622 623 624
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
625
    QDomDocument doc;
626 627 628 629 630 631 632
    QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
    profileElement.setAttribute(QStringLiteral("name"), currentProfile);
    profileElement.setAttribute(QStringLiteral("category"), i18nc("Category Name", "Custom"));
    profileElement.setAttribute(QStringLiteral("destinationid"), QStringLiteral("favorites"));
    profileElement.setAttribute(QStringLiteral("extension"), extension);
    profileElement.setAttribute(QStringLiteral("args"), params);
    if (params.contains(QStringLiteral("%bitrate"))) {
633
        // profile has a variable bitrate
634 635
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QStringLiteral(",")));
636
    } else if (params.contains(QStringLiteral("%quality"))) {
637 638
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QStringLiteral(",")));
639
    }
640
    if (params.contains(QStringLiteral("%audiobitrate"))) {
641
        // profile has a variable bitrate
642 643
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QStringLiteral(",")));
644
    } else if (params.contains(QStringLiteral("%audioquality"))) {
645
        // profile has a variable bitrate
646 647 648
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QStringLiteral(",")));
    }
649
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
650 651
        // profile has a variable speed
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QStringLiteral(";")));
652
    }
653 654
    doc.appendChild(profileElement);
    saveProfile(doc.documentElement());
655
    parseProfiles();
656 657
}

658 659
void RenderWidget::slotEditProfile()
{
660 661 662
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent()) return;
    QString currentGroup = item->parent()->text(0);
663

664
    QString params = item->data(0, ParamsRole).toString();
665 666

    Ui::SaveProfile_UI ui;
667
    QPointer<QDialog> d = new QDialog(this);
668
    ui.setupUi(d);
669

670
    QString customGroup = item->parent()->text(0);
Yuri Chornoivan's avatar
Yuri Chornoivan committed
671
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
672 673
    ui.group_name->setText(customGroup);

674 675
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
676 677
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
678 679
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.contains(QStringLiteral("%quality"))) {
680 681 682 683 684 685
            ui.vbitrates_label->setText(i18n("Qualities"));
            ui.default_vbitrate_label->setText(i18n("Default quality"));
        } else {
            ui.vbitrates_label->setText(i18n("Bitrates"));
            ui.default_vbitrate_label->setText(i18n("Default bitrate"));
        }
686 687
        if ( item->data(0, BitratesRole).canConvert(QVariant::StringList) && item->data(0, BitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
688
            ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
689 690
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String))
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
691
        }
Laurent Montel's avatar
Laurent Montel committed
692 693
    } else {
        ui.vbitrates->setHidden(true);
694
    }
Laurent Montel's avatar
Laurent Montel committed
695

696 697
    if (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
698 699 700 701 702 703
            ui.abitrates_label->setText(i18n("Qualities"));
            ui.default_abitrate_label->setText(i18n("Default quality"));
        } else {
            ui.abitrates_label->setText(i18n("Bitrates"));
            ui.default_abitrate_label->setText(i18n("Default bitrate"));
        }
704 705
        if ( item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && item->data(0, AudioBitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
706
            ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
707 708
            if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String))
                ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
709 710 711
        }
    }
    else ui.abitrates->setHidden(true);
712 713 714 715 716 717

    if ( item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
        QStringList speeds = item->data(0, SpeedsRole).toStringList();
        ui.speeds_list->setText(speeds.join('\n'));
    }

718
    d->setWindowTitle(i18n("Edit Profile"));
719

720
    if (d->exec() == QDialog::Accepted) {
721
        slotDeleteProfile(false);
722
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
723 724 725 726 727
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
728 729
        QDomElement profiles = doc.documentElement();

730
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
731
            doc.clear();
732 733
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
734 735 736
            doc.appendChild(profiles);
        }

737
        int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
738 739
        if (version < 1) {
            doc.clear();
740 741
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
742
            doc.appendChild(profiles);
743 744 745 746
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
747
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
748
        QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
749 750 751 752
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
753
            QString profileName = documentElement.attribute(QStringLiteral("name"));
754 755 756
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
757
                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);
758 759 760
                if (!ok) return;
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
761 762 763
                    break;
                }
            }
764
            ++i;
765
        }
766

767 768 769 770
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
771
        QString args = ui.parameters->toPlainText().simplified();
772 773
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
774
            // profile has a variable bitrate
775 776 777 778 779
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());
        } else if(args.contains(QStringLiteral("%quality"))) {
            profileElement.setAttribute(QStringLiteral("defaultquality"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("qualities"), ui.vbitrates_list->text());
780
        }
781
        if (args.contains(QStringLiteral("%audiobitrate"))) {
782
            // profile has a variable bitrate
783 784 785 786 787
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
788 789
        }

790
        if (!ui.speeds_list->toPlainText().isEmpty()) {
791 792 793
            // profile has a variable speed
            profileElement.setAttribute(QStringLiteral("speeds"), ui.speeds_list->toPlainText().replace('\n', ';').simplified());
        }
794

795
        profiles.appendChild(profileElement);
796 797

        //QCString save = doc.toString().utf8();
798
        delete d;
799
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
800
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
801 802 803 804
            return;
        }
        QTextStream out(&file);
        out << doc.toString();
805 806 807 808 809
        if (file.error() != QFile::NoError) {
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
            file.close();
            return;
        }
810
        file.close();
811
        parseProfiles();
812
    } else delete d;
813 814
}

815 816
void RenderWidget::slotDeleteProfile(bool refresh)
{
817 818
    //TODO: delete a profile installed by KNewStuff the easy way
    /*
819
    QString edit = m_view.formats->currentItem()->data(EditableRole).toString();
820
    if (!edit.endsWith(QLatin1String("customprofiles.xml"))) {
821
        // This is a KNewStuff installed file, process through KNS
822 823 824 825 826 827
        KNS::Engine engine(0);
        if (engine.init("kdenlive_render.knsrc")) {
            KNS::Entry::List entries;
        }
        return;
    }*/
828 829 830 831
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent()) return;
    QString currentProfile = item->text(0);
    QString currentGroup = item->parent()->text(0);
832

833
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
834 835 836 837 838 839
    QDomDocument doc;
    QFile file(exportFile);
    doc.setContent(&file, false);
    file.close();

    QDomElement documentElement;
840
    QDomNodeList profiles = doc.elementsByTagName(QStringLiteral("profile"));
841
    int i = 0;
842 843 844
    QString profileName;
    while (!profiles.item(i).isNull()) {
        documentElement = profiles.item(i).toElement();
845
        profileName = documentElement.attribute(QStringLiteral("name"));
846
        if (profileName == currentProfile) {
847
            doc.documentElement().removeChild(profiles.item(i));
848 849
            break;
        }
850
        ++i;
851 852 853 854 855 856 857 858
    }

    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();
859 860 861 862 863
    if (file.error() != QFile::NoError) {
        KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
        file.close();
        return;