renderwidget.cpp 46 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

#include <QDomDocument>
22 23
#include <QItemDelegate>
#include <QTreeWidgetItem>
24
#include <QListWidgetItem>
25
#include <QHeaderView>
26 27 28
#include <QMenu>
#include <QProcess>
#include <QInputDialog>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
29 30 31

#include <KStandardDirs>
#include <KDebug>
32
#include <KMessageBox>
33
#include <KComboBox>
34
#include <KRun>
35
#include <KIO/NetAccess>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
36 37 38

#include "kdenlivesettings.h"
#include "renderwidget.h"
39
#include "ui_saveprofile_ui.h"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
40

41 42 43 44 45
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;
46
const int EditableRole = GroupRole + 5;
47
const int MetaGroupRole = GroupRole + 6;
48
const int ExtraRole = GroupRole + 7;
49

50
RenderWidget::RenderWidget(const QString &projectfolder, QWidget * parent): QDialog(parent), m_projectFolder(projectfolder) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
51
    m_view.setupUi(this);
52
    setWindowTitle(i18n("Rendering"));
53 54 55 56
    m_view.buttonDelete->setIcon(KIcon("trash-empty"));
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

57 58 59 60
    m_view.buttonEdit->setIcon(KIcon("document-properties"));
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

61 62 63
    m_view.buttonSave->setIcon(KIcon("document-new"));
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

64 65 66 67 68 69
    m_view.buttonInfo->setIcon(KIcon("help-about"));

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

70 71
    m_view.rescale_size->setInputMask("0099\\x0099");
    m_view.rescale_size->setText("320x240");
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    QMenu *renderMenu = new QMenu(i18n("Start Rendering"), this);
    QAction *renderAction = renderMenu->addAction(KIcon("file-new"), i18n("Render to File"));
    connect(renderAction, SIGNAL(triggered()), this, SLOT(slotExport()));
    QAction *scriptAction = renderMenu->addAction(KIcon("file-new"), i18n("Generate Script"));
    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);


89
    parseProfiles();
90 91 92 93 94 95
    parseScriptFiles();

    connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
    connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
    connect(m_view.scripts_list, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(slotCheckScript()));
    connect(m_view.running_jobs, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(slotCheckJob()));
96

97 98
    connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));

99
    connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
100
    connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
101
    connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
102
    connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
103 104
    connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
    connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
105
    connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
106 107
    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
108
    connect(m_view.out_file, SIGNAL(textChanged(const QString &)), this, SLOT(slotUpdateButtons()));
109
    connect(m_view.out_file, SIGNAL(urlSelected(const KUrl &)), this, SLOT(slotUpdateButtons(const KUrl &)));
110 111
    connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
    connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
112

113 114 115 116 117 118 119
    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()));

120
    connect(m_view.format_selection, SIGNAL(activated(int)), this, SLOT(refreshView()));
121

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
122
    m_view.buttonStart->setEnabled(false);
123
    m_view.rescale_size->setEnabled(false);
124
    m_view.guides_box->setVisible(false);
125 126 127 128
    m_view.open_dvd->setVisible(false);
    m_view.open_browser->setVisible(false);
    m_view.error_box->setVisible(false);

129 130
    m_view.splitter->setStretchFactor(1, 5);
    m_view.splitter->setStretchFactor(0, 2);
131

132
    m_view.out_file->setMode(KFile::File);
133

134
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File") << i18n("Progress"));
135
    m_view.running_jobs->setItemDelegate(new RenderViewDelegate(this));
136

137 138 139
    QHeaderView *header = m_view.running_jobs->header();
    QFontMetrics fm = fontMetrics();
    //header->resizeSection(0, fm.width("typical-name-for-a-torrent.torrent"));
140 141
    header->setResizeMode(0, QHeaderView::Fixed);
    header->resizeSection(0, 30);
142
    header->setResizeMode(1, QHeaderView::Interactive);
143 144 145 146
    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);
147 148
    //header->setResizeMode(1, QHeaderView::Fixed);

149 150 151 152
    m_view.scripts_list->setHeaderLabels(QStringList() << i18n("Script Files"));
    m_view.scripts_list->setItemDelegate(new RenderScriptDelegate(this));


153
    focusFirstVisibleItem();
154 155 156 157 158 159 160 161 162 163 164 165
}

void RenderWidget::showInfoPanel() {
    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
166 167
}

168 169 170 171
void RenderWidget::setDocumentPath(const QString path) {
    m_projectFolder = path;
    const QString fileName = m_view.out_file->url().fileName();
    m_view.out_file->setUrl(KUrl(m_projectFolder + '/' + fileName));
172
    parseScriptFiles();
173 174
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
void RenderWidget::slotUpdateGuideBox() {
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

void RenderWidget::slotCheckStartGuidePosition() {
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
}

void RenderWidget::slotCheckEndGuidePosition() {
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
}

void RenderWidget::setGuides(QDomElement guidesxml, double duration) {
    m_view.guide_start->clear();
    m_view.guide_end->clear();
    QDomNodeList nodes = guidesxml.elementsByTagName("guide");
    if (nodes.count() > 0) {
194
        m_view.guide_start->addItem(i18n("Render"), "0");
195 196 197 198 199 200 201 202 203 204 205 206 207
        m_view.render_guide->setEnabled(true);
    } else m_view.render_guide->setEnabled(false);
    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));
}

208 209 210 211
// Will be called when the user selects an output file via the file dialog.
// File extension will be added automatically.
void RenderWidget::slotUpdateButtons(KUrl url) {
    if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
212
    else m_view.buttonStart->setEnabled(true);
213
    if (url != 0) {
214 215 216 217
        QListWidgetItem *item = m_view.size_list->currentItem();
        QString extension = item->data(ExtensionRole).toString();
        url = filenameWithExtension(url, extension);
        m_view.out_file->setUrl(url);
218 219 220
    }
}

221
// Will be called when the user changes the output file path in the text line.
222
// File extension must NOT be added, would make editing impossible!
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
223 224
void RenderWidget::slotUpdateButtons() {
    if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
225
    else m_view.buttonStart->setEnabled(true);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
226 227
}

228
void RenderWidget::slotSaveProfile() {
229
    //TODO: update to correctly use metagroups
230 231 232
    Ui::SaveProfile_UI ui;
    QDialog *d = new QDialog(this);
    ui.setupUi(d);
233 234 235 236 237 238

    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, MetaGroupRole));

    ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());

239 240 241 242 243 244 245 246 247
    QString customGroup = i18n("Custom");
    QStringList groupNames;
    for (int i = 0; i < m_view.format_list->count(); i++)
        groupNames.append(m_view.format_list->item(i)->text());
    if (!groupNames.contains(customGroup)) groupNames.prepend(customGroup);
    ui.group_name->addItems(groupNames);
    int pos = ui.group_name->findText(customGroup);
    ui.group_name->setCurrentIndex(pos);

248
    ui.parameters->setText(m_view.advanced_params->toPlainText());
249 250
    ui.extension->setText(m_view.size_list->currentItem()->data(ExtensionRole).toString());
    ui.profile_name->setFocus();
251
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
252
        QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
253 254 255 256 257 258 259 260
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();

        QDomElement documentElement;
        bool groupExists = false;
        QString groupName;
261
        QString newProfileName = ui.profile_name->text().simplified();
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        QString newGroupName = ui.group_name->currentText();
        QDomNodeList groups = doc.elementsByTagName("group");
        int i = 0;
        if (groups.count() == 0) {
            QDomElement profiles = doc.createElement("profiles");
            doc.appendChild(profiles);
        } else while (!groups.item(i).isNull()) {
                documentElement = groups.item(i).toElement();
                groupName = documentElement.attribute("name");
                kDebug() << "// SAVE, PARSING FROUP: " << i << ", name: " << groupName << ", LOOK FR: " << newGroupName;
                if (groupName == newGroupName) {
                    groupExists = true;
                    break;
                }
                i++;
            }
        if (!groupExists) {
            documentElement = doc.createElement("group");
            documentElement.setAttribute("name", ui.group_name->currentText());
            documentElement.setAttribute("renderer", "avformat");
            doc.documentElement().appendChild(documentElement);
        }
        QDomElement profileElement = doc.createElement("profile");
        profileElement.setAttribute("name", newProfileName);
        profileElement.setAttribute("extension", ui.extension->text().simplified());
287
        profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
288 289 290 291 292 293 294 295 296 297 298 299
        documentElement.appendChild(profileElement);

        //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();
        file.close();
300
        parseProfiles(newGroupName, newProfileName);
301 302 303 304
    }
    delete d;
}

305
void RenderWidget::slotEditProfile() {
306
    //TODO: update to correctly use metagroups
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    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);
    QStringList groupNames;
    for (int i = 0; i < m_view.format_list->count(); i++)
        groupNames.append(m_view.format_list->item(i)->text());
    if (!groupNames.contains(currentGroup)) groupNames.prepend(currentGroup);
    ui.group_name->addItems(groupNames);
    int pos = ui.group_name->findText(currentGroup);
    ui.group_name->setCurrentIndex(pos);
    ui.profile_name->setText(currentProfile);
    ui.extension->setText(extension);
    ui.parameters->setText(params);
    ui.profile_name->setFocus();

    if (d->exec() == QDialog::Accepted) {
331
        slotDeleteProfile();
332
        QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();

        QDomElement documentElement;
        bool groupExists = false;
        QString groupName;
        QString newProfileName = ui.profile_name->text();
        QString newGroupName = ui.group_name->currentText();
        QDomNodeList groups = doc.elementsByTagName("group");
        int i = 0;
        if (groups.count() == 0) {
            QDomElement profiles = doc.createElement("profiles");
            doc.appendChild(profiles);
        } else while (!groups.item(i).isNull()) {
                documentElement = groups.item(i).toElement();
                groupName = documentElement.attribute("name");
                kDebug() << "// SAVE, PARSING FROUP: " << i << ", name: " << groupName << ", LOOK FR: " << newGroupName;
                if (groupName == newGroupName) {
                    groupExists = true;
                    break;
                }
                i++;
            }
        if (!groupExists) {
            documentElement = doc.createElement("group");
            documentElement.setAttribute("name", ui.group_name->currentText());
            documentElement.setAttribute("renderer", "avformat");
            doc.documentElement().appendChild(documentElement);
        }
        QDomElement profileElement = doc.createElement("profile");
        profileElement.setAttribute("name", newProfileName);
        profileElement.setAttribute("extension", ui.extension->text().simplified());
367
        profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        documentElement.appendChild(profileElement);

        //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();
        file.close();
        parseProfiles(newGroupName, newProfileName);
    }
    delete d;
}

385 386 387 388
void RenderWidget::slotDeleteProfile() {
    QString currentGroup = m_view.format_list->currentItem()->text();
    QString currentProfile = m_view.size_list->currentItem()->text();

389
    QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    QDomDocument doc;
    QFile file(exportFile);
    doc.setContent(&file, false);
    file.close();

    QDomElement documentElement;
    bool groupExists = false;
    QString groupName;
    QDomNodeList groups = doc.elementsByTagName("group");
    int i = 0;

    while (!groups.item(i).isNull()) {
        documentElement = groups.item(i).toElement();
        groupName = documentElement.attribute("name");
        if (groupName == currentGroup) {
            QDomNodeList children = documentElement.childNodes();
            for (int j = 0; j < children.count(); j++) {
                QDomElement pro = children.at(j).toElement();
                if (pro.attribute("name") == currentProfile) {
                    groups.item(i).removeChild(children.at(j));
                    if (groups.item(i).childNodes().isEmpty())
                        doc.documentElement().removeChild(groups.item(i));
                    break;
                }
            }
            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();
    file.close();
427
    parseProfiles(currentGroup);
428 429 430
    focusFirstVisibleItem();
}

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
void RenderWidget::updateButtons() {
    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);
    } else {
        m_view.buttonSave->setEnabled(true);
        if (m_view.size_list->currentItem()->data(EditableRole).toString().isEmpty()) {
            m_view.buttonDelete->setEnabled(false);
            m_view.buttonEdit->setEnabled(false);
        } else {
            m_view.buttonDelete->setEnabled(true);
            m_view.buttonEdit->setEnabled(true);
        }
    }
}


449
void RenderWidget::focusFirstVisibleItem() {
450 451 452 453
    if (m_view.size_list->currentItem() && !m_view.size_list->currentItem()->isHidden()) {
        updateButtons();
        return;
    }
454
    for (uint ix = 0; ix < m_view.size_list->count(); ix++) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
455 456 457 458 459
        QListWidgetItem *item = m_view.size_list->item(ix);
        if (item && !item->isHidden()) {
            m_view.size_list->setCurrentRow(ix);
            break;
        }
460 461
    }
    if (!m_view.size_list->currentItem()) m_view.size_list->setCurrentRow(0);
462
    updateButtons();
463 464
}

465
void RenderWidget::slotExport(bool scriptExport) {
466 467
    QListWidgetItem *item = m_view.size_list->currentItem();
    if (!item) return;
468

469 470 471
    const QString dest = m_view.out_file->url().path();
    if (dest.isEmpty()) return;
    QFile f(dest);
472
    if (f.exists()) {
473
        if (KMessageBox::warningYesNo(this, i18n("Output file already exists. Do you want to overwrite it ?")) != KMessageBox::Yes)
474 475
            return;
    }
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

    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()) {
            if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it ?")) != KMessageBox::Yes)
                return;
        }
    }

498 499 500 501 502 503 504
    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";
    }
505 506 507 508 509 510
    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();
    }
511
    QString renderArgs = m_view.advanced_params->toPlainText();
512 513 514 515 516 517 518 519 520 521 522

    // 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;
    }
523
    renderArgs.replace("%dar", "@" + QString::number(m_profile.display_aspect_num) + "/" + QString::number(m_profile.display_aspect_den));
524 525 526 527 528 529 530 531

    // 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 ");
532 533 534 535 536

    // 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;

537
    QString std = renderArgs;
538 539
    QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
    if (std.contains(" s=")) {
540 541
        QString subsize = std.section(" s=", 1, 1);
        subsize = subsize.section(' ', 0, 0).toLower();
542
        const QString currentSize = QString::number(width) + 'x' + QString::number(height);
543
        if (subsize != currentSize) resizeProfile = true;
544
    } else if (destination != "audioonly") {
545
        // Add current size parametrer
546
        renderArgs.append(QString(" s=%1x%2").arg(width).arg(height));
547 548
    }

549 550
    // insert item in running jobs list
    QTreeWidgetItem *renderItem;
551
    QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
552
    if (!existing.isEmpty()) renderItem = existing.at(0);
553 554
    else renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
    renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
555
    renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
556

557
    // Set rendering type
558 559 560 561 562 563 564 565 566 567
    QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
    if (group == "dvd" && 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, usefull 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);
        }
568 569 570 571 572
    } else 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);
573
    }
574

575 576 577 578 579 580
    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);
    if (scriptName.isEmpty()) m_view.tabWidget->setCurrentIndex(1);
    else {
        QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
        m_view.tabWidget->setCurrentIndex(2);
    }
581 582
}

583 584 585 586
void RenderWidget::setProfile(MltVideoProfile profile) {
    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);
587
    else m_view.format_selection->setCurrentIndex(1);
588
    m_view.scanning_list->setCurrentIndex(0);
589 590 591 592
    refreshView();
}

void RenderWidget::refreshView() {
593
    m_view.size_list->blockSignals(true);
594 595 596
    QListWidgetItem *sizeItem;

    QString destination;
597
    KIcon brokenIcon("dialog-close");
598 599 600
    if (m_view.destination_list->currentIndex() > 0)
        destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();

601 602
    kDebug() << "// SELECTED DESTINATION: " << destination;

603 604 605 606 607 608 609 610 611 612
    if (destination == "dvd") m_view.open_dvd->setVisible(true);
    else m_view.open_dvd->setVisible(false);
    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);
613
        if (sizeItem->data(MetaGroupRole).toString() == destination) {
614
            sizeItem->setHidden(false);
615 616
            kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
        } else sizeItem->setHidden(true);
617 618 619 620 621 622 623 624 625 626 627
    }

    // 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;
            }
        }
628 629
        item = m_view.format_list->currentItem();
    }
630
    if (!item || item->isHidden()) return;
631 632 633 634 635 636
    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);
637 638 639
    QString std;
    QString group = item->text();
    bool firstSelected = false;
640 641 642
    const QStringList formatsList = KdenliveSettings::supportedformats();
    const QStringList vcodecsList = KdenliveSettings::videocodecs();
    const QStringList acodecsList = KdenliveSettings::audiocodecs();
643

644 645
    for (int i = 0; i < m_view.size_list->count(); i++) {
        sizeItem = m_view.size_list->item(i);
646
        if ((sizeItem->data(GroupRole) == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole) == destination) {
647
            std = sizeItem->data(StandardRole).toString();
648 649 650 651 652 653 654 655
            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;
            }
656

657 658 659 660 661 662 663 664 665 666 667 668
            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)) {
                            kDebug() << "*****  UNSUPPORTED F: " << format;
669 670 671 672
                            //sizeItem->setHidden(true);
                            sizeItem->setFlags(Qt::NoItemFlags);
                            sizeItem->setToolTip(i18n("Unsupported video format: %1", format));
                            sizeItem->setIcon(brokenIcon);
673 674 675 676 677 678 679 680 681 682 683
                        }
                    }
                }
                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;
684 685 686 687
                            //sizeItem->setHidden(true);
                            sizeItem->setFlags(Qt::NoItemFlags);
                            sizeItem->setToolTip(i18n("Unsupported audio codec: %1", format));
                            sizeItem->setIcon(brokenIcon);
688 689 690 691 692 693 694 695 696 697 698
                        }
                    }
                }
                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;
699 700 701 702
                            //sizeItem->setHidden(true);
                            sizeItem->setFlags(Qt::NoItemFlags);
                            sizeItem->setToolTip(i18n("Unsupported video codec: %1", format));
                            sizeItem->setIcon(brokenIcon);
703 704 705 706
                        }
                    }
                }
            }
707 708
        } else sizeItem->setHidden(true);
    }
709
    focusFirstVisibleItem();
710 711
    m_view.size_list->blockSignals(false);
    refreshParams();
712 713
}

714 715 716 717 718 719 720 721 722
KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension) {
    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 {
723
        path = m_projectFolder + "/untitled." + extension;
724 725 726 727 728
    }
    return KUrl(path);
}


729 730
void RenderWidget::refreshParams() {
    QListWidgetItem *item = m_view.size_list->currentItem();
731 732 733 734 735
    if (!item || item->isHidden()) {
        m_view.advanced_params->clear();
        m_view.buttonStart->setEnabled(false);
        return;
    }
736 737
    QString params = item->data(ParamsRole).toString();
    QString extension = item->data(ExtensionRole).toString();
738
    m_view.advanced_params->setPlainText(params);
739 740 741 742 743 744 745 746 747
    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);
    }
748 749 750 751 752 753 754 755 756 757 758
    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));
//     }
759
    m_view.out_file->setFilter("*." + extension);
760

761
    if (item->data(EditableRole).toString().isEmpty()) {
762 763 764 765 766
        m_view.buttonDelete->setEnabled(false);
        m_view.buttonEdit->setEnabled(false);
    } else {
        m_view.buttonDelete->setEnabled(true);
        m_view.buttonEdit->setEnabled(true);
767
    }
768
    m_view.buttonStart->setEnabled(true);
769 770
}

771 772 773 774
void RenderWidget::reloadProfiles() {
    parseProfiles();
}

775
void RenderWidget::parseProfiles(QString group, QString profile) {
776 777
    m_view.size_list->clear();
    m_view.format_list->clear();
778 779
    m_view.destination_list->clear();
    m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
780 781 782 783 784 785 786
    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");

787
    QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
788
    parseFile(exportFile, false);
789 790 791 792 793 794 795 796


    QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
    QDir directory = QDir(exportFolder);
    QStringList filter;
    filter << "*.xml";
    const QStringList fileList = directory.entryList(filter, QDir::Files);
    foreach(const QString filename, fileList)
797
    parseFile(exportFolder + '/' + filename, filename == "customprofiles.xml");
798

799
    refreshView();
800
    QList<QListWidgetItem *> child;
801
    if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
802
    if (!child.isEmpty()) m_view.format_list->setCurrentItem(child.at(0));
803 804
    child.clear();
    if (!profile.isEmpty()) child = m_view.size_list->findItems(profile, Qt::MatchExactly);
805
    if (!child.isEmpty()) m_view.size_list->setCurrentItem(child.at(0));
806 807 808
}

void RenderWidget::parseFile(QString exportFile, bool editable) {
809 810
    kDebug() << "// Parsing file: " << exportFile;
    kDebug() << "------------------------------";
811 812 813
    QDomDocument doc;
    QFile file(exportFile);
    doc.setContent(&file, false);
814
    file.close();
815 816
    QDomElement documentElement;
    QDomElement profileElement;
817 818
    QString extension;
    QListWidgetItem *item;
819 820 821
    QDomNodeList groups = doc.elementsByTagName("group");

    if (groups.count() == 0) {
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        QDomNode node = doc.elementsByTagName("profile").at(0);
        if (node.isNull()) {
            kDebug() << "// Export file: " << exportFile << " IS BROKEN";
            return;
        }
        QDomElement profile = node.toElement();
        QString profileName = profile.attribute("name");
        QString standard = profile.attribute("standard");
        QString params = profile.attribute("args");
        QString category = profile.attribute("category", i18n("Custom"));
        QString dest = profile.attribute("destinationid");
        QString prof_extension = profile.attribute("extension");
        if (!prof_extension.isEmpty()) extension = prof_extension;

        QList <QListWidgetItem *> list = m_view.format_list->findItems(category, Qt::MatchExactly);
        bool exists = false;
        for (int j = 0; j < list.count(); j++) {
            if (list.at(j)->data(MetaGroupRole) == dest) {
                exists = true;
                break;
            }
        }
        if (!exists) {
            item = new QListWidgetItem(category, m_view.format_list);
            item->setData(MetaGroupRole, dest);
        }

        item = new QListWidgetItem(profileName, m_view.size_list);
        kDebug() << "// ADDINg item with name: " << profileName << ", GRP" << category << ", DEST:" << dest ;
        item->setData(GroupRole, category);
        item->setData(MetaGroupRole, dest);
        item->setData(ExtensionRole, extension);
        item->setData(RenderRole, "avformat");
        item->setData(StandardRole, standard);
        item->setData(ParamsRole, params);
        if (profile.hasAttribute("url")) item->setData(ExtraRole, profile.attribute("url"));
        if (editable) item->setData(EditableRole, "true");
859 860
        return;
    }
861

862 863 864
    int i = 0;
    QString groupName;
    QString profileName;
865

866 867 868 869
    QString prof_extension;
    QString renderer;
    QString params;
    QString standard;
870
    KIcon icon;
871

872 873
    while (!groups.item(i).isNull()) {
        documentElement = groups.item(i).toElement();
874 875 876 877 878 879 880 881 882 883 884 885
        QDomNode gname = documentElement.elementsByTagName("groupname").at(0);
        QString metagroupName;
        QString metagroupId;
        if (!gname.isNull()) {
            metagroupName = gname.firstChild().nodeValue();
            metagroupId = gname.toElement().attribute("id");
            if (!metagroupName.isEmpty() && !m_view.destination_list->contains(metagroupName)) {
                if (metagroupId == "dvd") icon = KIcon("media-optical");
                else if (metagroupId == "audioonly") icon = KIcon("audio-x-generic");
                else if (metagroupId == "websites") icon = KIcon("applications-internet");
                else if (metagroupId == "mediaplayers") icon = KIcon("applications-multimedia");
                else if (metagroupId == "lossless") icon = KIcon("drive-harddisk");
886
                else if (metagroupId == "mobile") icon = KIcon("pda");
887 888 889
                m_view.destination_list->addItem(icon, i18n(metagroupName.toUtf8().data()), metagroupId);
            }
        }
890
        groupName = documentElement.attribute("name", i18n("Custom"));
891 892
        extension = documentElement.attribute("extension", QString::null);
        renderer = documentElement.attribute("renderer", QString::null);
893 894 895 896 897 898 899 900 901
        QList <QListWidgetItem *> list = m_view.format_list->findItems(groupName, Qt::MatchExactly);
        bool exists = false;
        for (int j = 0; j < list.count(); j++) {
            if (list.at(j)->data(MetaGroupRole) == metagroupId) {
                exists = true;
                break;
            }
        }
        if (!exists) {
902 903 904
            item = new QListWidgetItem(groupName, m_view.format_list);
            item->setData(MetaGroupRole, metagroupId);
        }
905 906 907

        QDomNode n = groups.item(i).firstChild();
        while (!n.isNull()) {
908 909 910 911
            if (n.toElement().tagName() != "profile") {
                n = n.nextSibling();
                continue;
            }
912 913 914 915 916 917 918 919
            profileElement = n.toElement();
            profileName = profileElement.attribute("name");
            standard = profileElement.attribute("standard");
            params = profileElement.attribute("args");
            prof_extension = profileElement.attribute("extension");
            if (!prof_extension.isEmpty()) extension = prof_extension;
            item = new QListWidgetItem(profileName, m_view.size_list);
            item->setData(GroupRole, groupName);
920
            item->setData(MetaGroupRole, metagroupId);
921 922 923 924
            item->setData(ExtensionRole, extension);
            item->setData(RenderRole, renderer);
            item->setData(StandardRole, standard);
            item->setData(ParamsRole, params);
925
            if (profileElement.hasAttribute("url")) item->setData(ExtraRole, profileElement.attribute("url"));
926
            if (editable) item->setData(EditableRole, "true");
927 928 929 930 931
            n = n.nextSibling();
        }

        i++;
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
932 933
}

934
void RenderWidget::setRenderJob(const QString &dest, int progress) {
935
    QTreeWidgetItem *item;
936
    QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
937
    if (!existing.isEmpty()) item = existing.at(0);
938 939 940 941 942
    else item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
    item->setData(2, Qt::UserRole, progress);
    if (progress == 0) {
        item->setIcon(0, KIcon("system-run"));
        item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
943
        item->setData(1, Qt::UserRole + 1, QTime::currentTime());
944
        slotCheckJob();
945
    } else {
946 947 948 949
        QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
        int seconds = startTime.secsTo(QTime::currentTime());;
        const QString t = i18n("Estimated time %1", QTime().addSecs(seconds * (100 - progress) / progress).toString("hh:mm:ss"));
        item->setData(1, Qt::UserRole, t);
950
    }
951 952 953 954
}

void RenderWidget::setRenderStatus(const QString &dest, int status, const QString &error) {
    QTreeWidgetItem *item;
955
    QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
956
    if (!existing.isEmpty()) item = existing.at(0);
957
    else item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
958
    if (status == -1) {
959 960
        // Job finished successfully
        item->setIcon(0, KIcon("dialog-ok"));
961
        item->setData(2, Qt::UserRole, 100);
962
        QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
963
        int seconds = startTime.secsTo(QTime::currentTime());
964 965 966
        const QTime tm = QTime().addSecs(seconds);
        const QString t = i18n("Rendering finished in %1", tm.toString("hh:mm:ss"));
        item->setData(1, Qt::UserRole, t);
967 968
        QString itemGroup = item->data(0, Qt::UserRole).toString();
        if (itemGroup == "dvd") {
969
            emit openDvdWizard(item->text(1), item->data(0, Qt::UserRole + 1).toString());
970 971 972
        } else if (itemGroup == "websites") {
            QString url = item->data(0, Qt::UserRole + 1).toString();
            if (!url.isEmpty()) KRun *openBrowser = new KRun(url, this);
973
        }
974
    } else if (status == -2) {
975
        // Rendering crashed
976
        item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
977
        item->setIcon(0, KIcon("dialog-close"));
978
        item->setData(2, Qt::UserRole, 100);
979 980 981 982 983
        m_view.error_log->append(i18n("<strong>Rendering of %1 crashed</strong><br />", dest));
        m_view.error_log->append(error);
        m_view.error_log->append("<hr />");
        m_view.error_box->setVisible(true);
    } else if (status == -3) {
984
        // User aborted job
985
        item->setData(1, Qt::UserRole, i18n("Rendering aborted"));
986
        item->setIcon(0, KIcon("dialog-cancel"));
987
        item->setData(2, Qt::UserRole, 100);
988
    }
989
    slotCheckJob();
990
}
991

992 993
void RenderWidget::slotAbortCurrentJob() {
    QTreeWidgetItem *current = m_view.running_jobs->currentItem();
994
    if (current) emit abortProcess(current->text(1));
995 996
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
void RenderWidget::slotCheckJob() {
    bool activate = false;
    QTreeWidgetItem *current = m_view.running_jobs->currentItem();
    if (current) {
        int percent = current->data(2, Qt::UserRole).toInt();
        if (percent < 100) activate = true;
    }
    m_view.abort_job->setEnabled(activate);
}

void RenderWidget::parseScriptFiles() {
    QStringList scriptsFilter;
    scriptsFilter << "*.sh";
    m_view.scripts_list->clear();

    QTreeWidgetItem *item;
    // List the project scripts
    QStringList scriptFiles = QDir(m_projectFolder + "/scripts").entryList(scriptsFilter, QDir::Files);
    for (int i = 0; i < scriptFiles.size(); ++i) {
        KUrl scriptpath(m_projectFolder + "/scripts/" + scriptFiles.at(i));
        item = new QTreeWidgetItem(m_view.scripts_list, QStringList() << scriptpath.fileName());
        QString target;
        QFile file(scriptpath.path());
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            while (!file.atEnd()) {
                QByteArray line = file.readLine();
                if (line.startsWith("TARGET=")) {
                    target = QString(line).section("TARGET=", 1);
                    target.remove(QChar('"'));
                    break;
                }
            }
            file.close();
        }
        item->setSizeHint(0, QSize(m_view.scripts_list->columnWidth(0), fontMetrics().height() * 2));
        item->setData(0, Qt::UserRole, target);
        item->setData(0, Qt::UserRole + 1, scriptpath.path());
    }
    bool activate = false;
    QTreeWidgetItemIterator it(m_view.scripts_list);
    if (*it) {
        kDebug() << "// FOUND SCRIPT ITEM:" << (*it)->text(0);
        // Selecting item does not work, why ???
        m_view.scripts_list->setCurrentItem(*it);
        (*it)->setSelected(true);
        activate = true;
    }
    kDebug() << "SELECTED SCRIPTS: " << m_view.scripts_list->selectedItems().count();
    m_view.start_script->setEnabled(activate);
    m_view.delete_script->setEnabled(activate);
}

void RenderWidget::slotCheckScript() {
    bool activate = false;
    QTreeWidgetItemIterator it(m_view.scripts_list);
    if (*it) activate = true;
    m_view.start_script->setEnabled(activate);
    m_view.delete_script->setEnabled(activate);
}

void RenderWidget::slotStartScript() {
    QTreeWidgetItem *item = m_view.scripts_list->currentItem();
    if (item) {
        QString path = item->data(0, Qt::UserRole + 1).toString();
        QProcess::startDetached(path);
        m_view.tabWidget->setCurrentIndex(1);
    }
}

void RenderWidget::slotDeleteScript() {
    QTreeWidgetItem *item = m_view.scripts_list->currentItem();
    if (item) {
        QString path = item->data(0, Qt::UserRole + 1).toString();
        KIO::NetAccess::del(path + ".westley", this);
        KIO::NetAccess::del(path, this);
        parseScriptFiles();
    }
}

void RenderWidget::slotGenerateScript() {
    slotExport(true);
}