OSDN Git Service

Bump x265 version.
[x264-launcher/x264-launcher.git] / src / win_addJob.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "win_addJob.h"
23 #include "UIC_win_addJob.h"
24
25 //Internal
26 #include "global.h"
27 #include "model_options.h"
28 #include "model_preferences.h"
29 #include "model_sysinfo.h"
30 #include "model_recently.h"
31 #include "encoder_factory.h"
32 #include "mediainfo.h"
33 #include "win_help.h"
34 #include "win_editor.h"
35
36 //MUtils
37 #include <MUtils/Global.h>
38 #include <MUtils/OSSupport.h>
39 #include <MUtils/Exception.h>
40
41 //Qt
42 #include <QDate>
43 #include <QTimer>
44 #include <QCloseEvent>
45 #include <QMessageBox>
46 #include <QFileDialog>
47 #include <QDesktopServices>
48 #include <QValidator>
49 #include <QDir>
50 #include <QInputDialog>
51 #include <QSettings>
52 #include <QUrl>
53 #include <QAction>
54 #include <QClipboard>
55 #include <QToolTip>
56
57 #include <memory>
58
59 #define ARRAY_SIZE(ARRAY) (sizeof((ARRAY))/sizeof((ARRAY[0])))
60 #define VALID_DIR(PATH) ((!(PATH).isEmpty()) && QFileInfo(PATH).exists() && QFileInfo(PATH).isDir())
61 #define SHFL(X) ((*reinterpret_cast<int*>(&(X))) <<= 1)
62
63 #define REMOVE_USAFED_ITEM \
64 { \
65         for(int i = 0; i < ui->cbxTemplate->count(); i++) \
66         { \
67                 const OptionsModel* temp = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>()); \
68                 if(temp == NULL) \
69                 { \
70                         ui->cbxTemplate->blockSignals(true); \
71                         ui->cbxTemplate->removeItem(i); \
72                         ui->cbxTemplate->blockSignals(false); \
73                         break; \
74                 } \
75         } \
76 }
77
78 #define ADD_CONTEXTMENU_ACTION(WIDGET, ICON, TEXT, SLOTNAME) \
79 { \
80         QAction *_action = new QAction((ICON), (TEXT), this); \
81         _action->setData(QVariant::fromValue<void*>(WIDGET)); \
82         WIDGET->addAction(_action); \
83         connect(_action, SIGNAL(triggered(bool)), this, SLOT(SLOTNAME())); \
84 }
85
86 #define ADD_CONTEXTMENU_SEPARATOR(WIDGET) \
87 { \
88         QAction *_action = new QAction(this); \
89         _action->setSeparator(true); \
90         WIDGET->addAction(_action); \
91
92
93 Q_DECLARE_METATYPE(const void*)
94
95 ///////////////////////////////////////////////////////////////////////////////
96 // Disable Monitoring RAII
97 ///////////////////////////////////////////////////////////////////////////////
98
99 class DisableHelperRAII
100 {
101 public:
102         DisableHelperRAII(bool *const flag) : m_flag(flag)
103         {
104                 *m_flag = false;
105         }
106
107         ~DisableHelperRAII(void)
108         {
109                 *m_flag = true;
110         }
111
112 private:
113         bool *const m_flag;
114 };
115
116 ///////////////////////////////////////////////////////////////////////////////
117 // Validator
118 ///////////////////////////////////////////////////////////////////////////////
119
120 class StringValidator : public QValidator
121 {
122 public:
123         StringValidator(QLabel *notifier, QLabel *icon)
124         :
125                 m_notifier(notifier), m_icon(icon)
126         {
127                 m_notifier->hide();
128                 m_icon->hide();
129         }
130         
131         virtual State validate(QString &input, int &pos) const = 0;
132
133         virtual void fixup(QString &input) const
134         {
135                 input = input.simplified();
136         }
137
138 protected:
139         QLabel *const m_notifier, *const m_icon;
140
141         bool checkParam(const QStringList &input, const char *const params[], const bool &doubleMinus) const
142         {
143                 for(QStringList::ConstIterator iter = input.constBegin(); iter != input.constEnd(); iter++)
144                 {
145                         for(size_t k = 0; params[k]; k++)
146                         {
147                                 const QString param = QLatin1String(params[k]);
148                                 const QString prefix = ((param.length() > 1) && doubleMinus) ? QLatin1String("--") : QLatin1String("-");
149                                 if(iter->compare(QString("%1%2").arg(prefix, param), Qt::CaseInsensitive) == 0)
150                                 {
151                                         if(m_notifier)
152                                         {
153                                                 m_notifier->setText(tr("Forbidden parameter: %1").arg(*iter));
154                                         }
155                                         return true;
156                                 }
157                         }
158                         if(iter->startsWith("--", Qt::CaseInsensitive))
159                         {
160                                 for(int i = 2; i < iter->length(); i++)
161                                 {
162                                         if((iter->at(i) == QLatin1Char('=')) && (i > 2) && (i + 1 < iter->length()))
163                                         {
164                                                 break; /*to allow "--param=value" format*/
165                                         }
166                                         if((!iter->at(i).isLetter()) && ((iter->at(i) != QLatin1Char('-')) || (i < 3)))
167                                         {
168                                                 if(m_notifier)
169                                                 {
170                                                         m_notifier->setText(tr("Invalid string: %1").arg(*iter));
171                                                 }
172                                                 return true;
173                                         }
174                                 }
175                         }
176                 }
177
178                 return false;
179         }
180
181         bool checkPrefix(const QStringList &input, const bool &doubleMinus) const
182         {
183                 for(QStringList::ConstIterator iter = input.constBegin(); iter != input.constEnd(); iter++)
184                 {
185                         static const char *const c[3] = { "--", "-", NULL };
186                         for(size_t i = 0; c[i]; i++)
187                         {
188                                 const QString prefix = QString::fromLatin1(c[i]);
189                                 if(iter->compare(prefix, Qt::CaseInsensitive) == 0)
190                                 {
191                                         if(m_notifier)
192                                         {
193                                                 m_notifier->setText(tr("Invalid parameter: %1").arg(prefix));
194                                         }
195                                         return true;
196                                 }
197                         }
198                         if
199                         (
200                                 ((!doubleMinus) && iter->startsWith("--", Qt::CaseInsensitive)) ||
201                                 (doubleMinus && iter->startsWith("-", Qt::CaseInsensitive) && (!iter->startsWith("--", Qt::CaseInsensitive)) && (iter->length() > 2) && (!iter->at(1).isDigit())) ||
202                                 (doubleMinus && iter->startsWith("--", Qt::CaseInsensitive) && (iter->length() < 4))
203                         )
204                         {
205                                 if(m_notifier)
206                                 {
207                                         m_notifier->setText(tr("Invalid syntax: %1").arg(*iter));
208                                 }
209                                 return true;
210                         }
211                 }
212                 return false;
213         }
214
215         bool checkCharacters(const QStringList &input) const
216         {
217                 static const char c[] = {'*', '?', '<', '>', '|', NULL};
218
219                 for(QStringList::ConstIterator iter = input.constBegin(); iter != input.constEnd(); iter++)
220                 {
221                         for(size_t i = 0; c[i]; i++)
222                         {
223                                 if(iter->indexOf(QLatin1Char(c[i])) >= 0)
224                                 {
225                                         if(m_notifier)
226                                         {
227                                                 m_notifier->setText(tr("Invalid character: '%1'").arg(QLatin1Char(c[i])));
228                                         }
229                                         return true;
230                                 }
231                         }
232                 }
233                 return false;
234         }
235
236         const bool &setStatus(const bool &flag, const QString &toolName) const
237         {
238                 if(flag)
239                 {
240                         if(m_notifier)
241                         {
242                                 if(m_notifier->isHidden()) m_notifier->show();
243                                 if(m_icon) { if(m_icon->isHidden()) m_icon->show(); }
244                                 if(QWidget *w = m_notifier->topLevelWidget()->focusWidget())
245                                 {
246                                         QToolTip::showText(static_cast<QWidget*>(w->parent())->mapToGlobal(w->pos()), tr("<b>Warning:</b> You entered a parameter that is forbidden. Please note that the GUI will automatically set <i>this</i> parameter for you (if required)."), m_notifier, QRect());
247                                 }
248                         }
249                 }
250                 else
251                 {
252                         if(m_notifier)
253                         {
254                                 if(m_notifier->isVisible()) m_notifier->hide();
255                                 if(m_icon) { if(m_icon->isVisible()) m_icon->hide(); }
256                                 QToolTip::hideText();
257                         }
258                 }
259                 return flag;
260         }
261 };
262
263 class StringValidatorEncoder : public StringValidator
264 {
265 public:
266         StringValidatorEncoder(QLabel *notifier, QLabel *icon) : StringValidator(notifier, icon) {}
267
268         virtual State validate(QString &input, int &pos) const
269         {
270                 static const char *const params[] = {"B", "o", "h", "p", "q", /*"fps", "frames",*/ "preset", "tune", "profile",
271                         "stdin", "crf", "bitrate", "qp", "pass", "stats", "output", "help", "quiet", "codec", "y4m", NULL};
272
273                 const QString commandLine = input.trimmed();
274                 const QStringList tokens =  commandLine.isEmpty() ? QStringList() : MUtils::OS::crack_command_line(commandLine);
275
276                 const bool invalid = checkCharacters(tokens) || checkPrefix(tokens, true) || checkParam(tokens, params, true);
277                 return setStatus(invalid, "encoder") ? QValidator::Intermediate : QValidator::Acceptable;
278         }
279 };
280
281 class StringValidatorAvs2YUV : public StringValidator
282 {
283 public:
284         StringValidatorAvs2YUV(QLabel *notifier, QLabel *icon) : StringValidator(notifier, icon) {}
285
286         virtual State validate(QString &input, int &pos) const
287         {
288                 static const char *const params[] = {"o", "frames", "seek", "raw", "hfyu", "slave", NULL};
289
290                 const QString commandLine = input.trimmed();
291                 const QStringList tokens =  commandLine.isEmpty() ? QStringList() : MUtils::OS::crack_command_line(commandLine);
292
293                 const bool invalid = checkCharacters(tokens) || checkPrefix(tokens, false) || checkParam(tokens, params, false);
294                 return setStatus(invalid, "Avs2YUV") ? QValidator::Intermediate : QValidator::Acceptable;
295         }
296 };
297
298 ///////////////////////////////////////////////////////////////////////////////
299 // Constructor & Destructor
300 ///////////////////////////////////////////////////////////////////////////////
301
302 AddJobDialog::AddJobDialog(QWidget *parent, OptionsModel *const options, RecentlyUsed *const recentlyUsed, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
303 :
304         QDialog(parent),
305         m_options(options),
306         m_recentlyUsed(recentlyUsed),
307         m_sysinfo(sysinfo),
308         m_preferences(preferences),
309         m_defaults(new OptionsModel(sysinfo)),
310         ui(new Ui::AddJobDialog()),
311         m_monitorConfigChanges(false)
312 {
313         //Init the dialog, from the .ui file
314         ui->setupUi(this);
315         setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
316
317         //Fix dialog size
318         ui->buttonSaveTemplate->setMaximumHeight(20);
319         ui->buttonDeleteTemplate->setMaximumHeight(20);
320         resize(width(), minimumHeight());
321         setMinimumSize(size());
322         setMaximumHeight(height());
323
324         //Init encoder combobox
325         ui->cbxEncoderType->addItem(tr("x264 (AVC)"),  OptionsModel::EncType_X264);
326         ui->cbxEncoderType->addItem(tr("x265 (HEVC)"), OptionsModel::EncType_X265);
327         ui->cbxEncoderType->addItem(tr("NVEncC"),      OptionsModel::EncType_NVEnc);
328
329         //Init combobox items
330         ui->cbxTuning ->addItem(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED));
331         ui->cbxProfile->addItem(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED));
332
333         //Hide optional controls
334         ui->checkBoxApplyToAll->setVisible(false);
335
336         //Monitor combobox changes
337         connect(ui->cbxEncoderType,     SIGNAL(currentIndexChanged(int)), this, SLOT(encoderIndexChanged(int)));
338         connect(ui->cbxEncoderVariant,  SIGNAL(currentIndexChanged(int)), this, SLOT(variantIndexChanged(int)));
339         connect(ui->cbxRateControlMode, SIGNAL(currentIndexChanged(int)), this, SLOT(modeIndexChanged(int)));
340
341         //Activate buttons
342         connect(ui->buttonBrowseSource,   SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
343         connect(ui->buttonBrowseOutput,   SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
344         connect(ui->buttonSaveTemplate,   SIGNAL(clicked()), this, SLOT(saveTemplateButtonClicked()));
345         connect(ui->buttonDeleteTemplate, SIGNAL(clicked()), this, SLOT(deleteTemplateButtonClicked()));
346
347         //Setup validator
348         ui->editCustomX264Params->installEventFilter(this);
349         ui->editCustomX264Params->setValidator(new StringValidatorEncoder(ui->labelNotificationX264, ui->iconNotificationX264));
350         ui->editCustomX264Params->clear();
351         ui->editCustomAvs2YUVParams->installEventFilter(this);
352         ui->editCustomAvs2YUVParams->setValidator(new StringValidatorAvs2YUV(ui->labelNotificationAvs2YUV, ui->iconNotificationAvs2YUV));
353         ui->editCustomAvs2YUVParams->clear();
354
355         //Install event filter
356         ui->labelHelpScreenX264->installEventFilter(this);
357         ui->labelHelpScreenAvs2YUV->installEventFilter(this);
358
359         //Monitor for options changes
360         connect(ui->cbxEncoderType, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
361         connect(ui->cbxEncoderArch, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
362         connect(ui->cbxEncoderVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
363         connect(ui->cbxRateControlMode, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
364         connect(ui->spinQuantizer, SIGNAL(valueChanged(double)), this, SLOT(configurationChanged()));
365         connect(ui->spinBitrate, SIGNAL(valueChanged(int)), this, SLOT(configurationChanged()));
366         connect(ui->cbxPreset, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
367         connect(ui->cbxTuning, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
368         connect(ui->cbxProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
369         connect(ui->editCustomX264Params, SIGNAL(textChanged(QString)), this, SLOT(configurationChanged()));
370         connect(ui->editCustomAvs2YUVParams, SIGNAL(textChanged(QString)), this, SLOT(configurationChanged()));
371
372         //Create context menus
373         ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_edit.png"), tr("Open the Text-Editor"), editorActionTriggered);
374         ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_edit.png"), tr("Open the Text-Editor"), editorActionTriggered);
375         ADD_CONTEXTMENU_SEPARATOR(ui->editCustomX264Params);
376         ADD_CONTEXTMENU_SEPARATOR(ui->editCustomAvs2YUVParams);
377         ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_copy.png"), tr("Copy to Clipboard"), copyActionTriggered);
378         ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_copy.png"), tr("Copy to Clipboard"), copyActionTriggered);
379         ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_paste.png"), tr("Paste from Clipboard"), pasteActionTriggered);
380         ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_paste.png"), tr("Paste from Clipboard"), pasteActionTriggered);
381
382         //Setup template selector
383         loadTemplateList();
384         connect(ui->cbxTemplate, SIGNAL(currentIndexChanged(int)), this, SLOT(templateSelected()));
385
386         //Force initial UI update
387         encoderIndexChanged(ui->cbxEncoderType->currentIndex());
388         m_monitorConfigChanges = true;
389 }
390
391 AddJobDialog::~AddJobDialog(void)
392 {
393         //Free templates
394         for(int i = 0; i < ui->cbxTemplate->model()->rowCount(); i++)
395         {
396                 if(ui->cbxTemplate->itemText(i).startsWith("<") || ui->cbxTemplate->itemText(i).endsWith(">"))
397                 {
398                         continue;
399                 }
400                 const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
401                 ui->cbxTemplate->setItemData(i, QVariant::fromValue<const void*>(NULL));
402                 MUTILS_DELETE(item);
403         }
404
405         //Free validators
406         if(const QValidator *tmp = ui->editCustomX264Params->validator())
407         {
408                 ui->editCustomX264Params->setValidator(NULL);
409                 MUTILS_DELETE(tmp);
410         }
411         if(const QValidator *tmp = ui->editCustomAvs2YUVParams->validator())
412         {
413                 ui->editCustomAvs2YUVParams->setValidator(NULL);
414                 MUTILS_DELETE(tmp);
415         }
416
417         MUTILS_DELETE(m_defaults);
418         delete ui;
419 }
420
421 ///////////////////////////////////////////////////////////////////////////////
422 // Events
423 ///////////////////////////////////////////////////////////////////////////////
424
425 void AddJobDialog::showEvent(QShowEvent *event)
426 {
427         QDialog::showEvent(event);
428         templateSelected();
429
430         if((!ui->editSource->text().isEmpty()) && ui->editOutput->text().isEmpty())
431         {
432                 QString outPath = generateOutputFileName(QDir::fromNativeSeparators(ui->editSource->text()), m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
433                 ui->editOutput->setText(QDir::toNativeSeparators(outPath));
434                 ui->buttonAccept->setFocus();
435         }
436
437         ui->labelNotificationX264->hide();
438         ui->iconNotificationX264->hide();
439         ui->labelNotificationAvs2YUV->hide();
440         ui->iconNotificationAvs2YUV->hide();
441
442         //Enable drag&drop support for this window, required for Qt v4.8.4+
443         setAcceptDrops(true);
444 }
445
446 bool AddJobDialog::eventFilter(QObject *o, QEvent *e)
447 {
448         if((o == ui->labelHelpScreenX264) && (e->type() == QEvent::MouseButtonPress))
449         {
450                 OptionsModel options(m_sysinfo); saveOptions(&options);
451                 QScopedPointer<HelpDialog> helpScreen(new HelpDialog(this, false, m_sysinfo, &options, m_preferences));
452                 helpScreen->exec();
453         }
454         else if((o == ui->labelHelpScreenAvs2YUV) && (e->type() == QEvent::MouseButtonPress))
455         {
456                 OptionsModel options(m_sysinfo); saveOptions(&options);
457                 QScopedPointer<HelpDialog> helpScreen(new HelpDialog(this, true, m_sysinfo, &options, m_preferences));
458                 helpScreen->exec();
459         }
460         else if((o == ui->editCustomX264Params) && (e->type() == QEvent::FocusOut))
461         {
462                 ui->editCustomX264Params->setText(ui->editCustomX264Params->text().simplified());
463         }
464         else if((o == ui->editCustomAvs2YUVParams) && (e->type() == QEvent::FocusOut))
465         {
466                 ui->editCustomAvs2YUVParams->setText(ui->editCustomAvs2YUVParams->text().simplified());
467         }
468         return false;
469 }
470
471 void AddJobDialog::dragEnterEvent(QDragEnterEvent *event)
472 {
473         bool accept[2] = {false, false};
474
475         foreach(const QString &fmt, event->mimeData()->formats())
476         {
477                 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
478                 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
479         }
480
481         if(accept[0] && accept[1])
482         {
483                 event->acceptProposedAction();
484         }
485 }
486
487 void AddJobDialog::dropEvent(QDropEvent *event)
488 {
489         QString droppedFile;
490         QList<QUrl> urls = event->mimeData()->urls();
491
492         if(urls.count() > 1)
493         {
494                 QDragEnterEvent dragEvent(event->pos(), event->proposedAction(), event->mimeData(), Qt::NoButton, Qt::NoModifier);
495                 if(qApp->notify(parent(), &dragEvent))
496                 {
497                         qApp->notify(parent(), event);
498                         reject(); return;
499                 }
500         }
501
502         while((!urls.isEmpty()) && droppedFile.isEmpty())
503         {
504                 QUrl currentUrl = urls.takeFirst();
505                 QFileInfo file(currentUrl.toLocalFile());
506                 if(file.exists() && file.isFile())
507                 {
508                         qDebug("AddJobDialog::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
509                         droppedFile = file.canonicalFilePath();
510                 }
511         }
512         
513         if(!droppedFile.isEmpty())
514         {
515                 const QString outFileName = generateOutputFileName(droppedFile, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
516                 ui->editSource->setText(QDir::toNativeSeparators(droppedFile));
517                 ui->editOutput->setText(QDir::toNativeSeparators(outFileName));
518         }
519 }
520
521 ///////////////////////////////////////////////////////////////////////////////
522 // Slots
523 ///////////////////////////////////////////////////////////////////////////////
524
525 void AddJobDialog::encoderIndexChanged(int index)
526 {
527         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
528         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
529
530         //Update encoder architectures
531         const QList<AbstractEncoderInfo::ArchId> archs = encoderInfo.getArchitectures();
532         ui->cbxEncoderArch->clear();
533         for (quint32 archIdx = 0; archIdx < quint32(archs.count()); ++archIdx)
534         {
535                 ui->cbxEncoderArch->addItem(archs[archIdx].first, archIdx);
536         }
537
538         //Update encoder variants
539         const QStringList variants = encoderInfo.getVariants();
540         ui->cbxEncoderVariant->clear();
541         for(quint32 varntIdx = 0; varntIdx < quint32(variants.count()); ++varntIdx)
542         {
543                 ui->cbxEncoderVariant->addItem(variants[varntIdx], varntIdx);
544         }
545
546         //Update encoder RC modes
547         const QList<AbstractEncoderInfo::RCMode> rcModes = encoderInfo.getRCModes();
548         ui->cbxRateControlMode->clear();
549         for (quint32 rcIndex = 0; rcIndex < quint32(rcModes.count()); ++rcIndex)
550         {
551                 ui->cbxRateControlMode->addItem(rcModes[rcIndex].first, rcIndex);
552         }
553
554         //Update presets
555         const QStringList presets = encoderInfo.getPresets();
556         if(presets.empty())
557         {
558                 ui->cbxPreset->setEnabled(false);
559                 ui->cbxPreset->setCurrentIndex(0);
560         }
561         else
562         {
563                 ui->cbxPreset->setEnabled(true);
564                 ui->cbxPreset->clear();
565                 ui->cbxPreset->addItem(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED));
566                 ui->cbxPreset->addItems(presets);
567         }
568
569         //Update tunings
570         const QStringList tunings = encoderInfo.getTunings();
571         if(tunings.empty())
572         {
573                 ui->cbxTuning->setEnabled(false);
574                 ui->cbxTuning->setCurrentIndex(0);
575         }
576         else
577         {
578                 ui->cbxTuning->setEnabled(true);
579                 ui->cbxTuning->clear();
580                 ui->cbxTuning->addItem(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED));
581                 ui->cbxTuning->addItems(tunings);
582         }
583
584         variantIndexChanged(ui->cbxEncoderVariant->currentIndex());
585 }
586
587 void AddJobDialog::variantIndexChanged(int index)
588 {
589         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
590         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
591
592         //Update encoder profiles
593         const QStringList profiles = encoderInfo.getProfiles(ui->cbxEncoderVariant->itemData(index).toUInt());
594         if(profiles.empty())
595         {
596                 ui->cbxProfile->setEnabled(false);
597                 ui->cbxProfile->setCurrentIndex(0);
598         }
599         else
600         {
601                 ui->cbxProfile->setEnabled(true);
602                 ui->cbxProfile->clear();
603                 ui->cbxProfile->addItem(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED));
604                 ui->cbxProfile->addItems(profiles);
605         }
606         
607         modeIndexChanged(ui->cbxRateControlMode->currentIndex());
608 }
609
610 void AddJobDialog::modeIndexChanged(int index)
611 {
612         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
613         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
614
615         //Update bitrate/quantizer boxes
616         const AbstractEncoderInfo::RCType rcType = encoderInfo.rcModeToType(ui->cbxRateControlMode->itemData(index).toUInt());
617         ui->spinQuantizer->setEnabled(rcType == AbstractEncoderInfo::RC_TYPE_QUANTIZER);
618         ui->spinBitrate  ->setEnabled(rcType != AbstractEncoderInfo::RC_TYPE_QUANTIZER);
619 }
620
621 void AddJobDialog::accept(void)
622 {
623         //Get encoder info
624         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
625         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
626
627         //Check 64-Bit support
628         if (encoderInfo.archToType(ui->cbxEncoderArch->itemData(ui->cbxEncoderArch->currentIndex()).toUInt()) == AbstractEncoderInfo::ARCH_TYPE_X64)
629         {
630                 if (!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64))
631                 {
632                         QMessageBox::warning(this, tr("64-Bit unsupported!"), tr("<nobr>Sorry, this computer does <b>not</b> support 64-Bit encoders!</nobr>"));
633                         ui->cbxEncoderArch->setCurrentIndex(AbstractEncoderInfo::ARCH_TYPE_X86);
634                         return;
635                 }
636         }
637         
638         //Selection complete?
639         if(ui->editSource->text().trimmed().isEmpty())
640         {
641                 QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>Please select a valid source file first!<(nobr>"));
642                 return;
643         }
644         if(ui->editOutput->text().trimmed().isEmpty())
645         {
646                 QMessageBox::warning(this, tr("Not Selected!"), tr("<nobr>Please select a valid output file first!</nobr>"));
647                 return;
648         }
649
650         //Does source exist?
651         QFileInfo sourceFile = QFileInfo(this->sourceFile());
652         if(!(sourceFile.exists() && sourceFile.isFile()))
653         {
654                 QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>The selected source file could not be found!</nobr>"));
655                 return;
656         }
657
658         //Is the type of the source file supported?
659         const int sourceType = MediaInfo::analyze(sourceFile.canonicalFilePath());
660         if(sourceType == MediaInfo::FILETYPE_AVISYNTH)
661         {
662                 if(!m_sysinfo->hasAvisynth())
663                 {
664                         if(QMessageBox::warning(this, tr("Avisynth unsupported!"), tr("<nobr>An Avisynth script was selected as input, although Avisynth is <b>not</b> available!</nobr>"), tr("Abort"), tr("Ignore (at your own risk!)")) != 1)
665                         {
666                                 return;
667                         }
668                 }
669         }
670         else if(sourceType == MediaInfo::FILETYPE_VAPOURSYNTH)
671         {
672                 if(!m_sysinfo->hasVapourSynth())
673                 {
674                         if(QMessageBox::warning(this, tr("VapurSynth unsupported!"), tr("<nobr>A VapourSynth script was selected as input, although VapourSynth is <b>not/<b> available!</nobr>"), tr("Abort"), tr("Ignore (at your own risk!)")) != 1)
675                         {
676                                 return;
677                         }
678                 }
679         }
680         else if(!encoderInfo.isInputTypeSupported(sourceType))
681         {
682                 if(QMessageBox::warning(this, tr("Unsupported input format"), tr("<nobr>The selected encoder does <b>not</b> support the selected input format!</nobr>"), tr("Abort"), tr("Ignore (at your own risk!)")) != 1)
683                 {
684                         return;
685                 }
686         }
687         
688         //Is output file extension supported by encoder?
689         const QStringList outputFormats = encoderInfo.supportedOutputFormats();
690         QFileInfo outputFile = QFileInfo(this->outputFile());
691         if(!outputFormats.contains(outputFile.suffix(), Qt::CaseInsensitive))
692         {
693                 QMessageBox::warning(this, tr("Unsupported output format"), tr("<nobr>Sorry, the selected encoder does not support the selected output format!</nobr>"));
694                 ui->editOutput->setText(QDir::toNativeSeparators(QString("%1/%2.%3").arg(outputFile.absolutePath(), outputFile.completeBaseName(), outputFormats.first())));
695                 return;
696         }
697
698         //Does output file already exist?
699         if(outputFile.exists() && outputFile.isFile())
700         {
701                 int ret = QMessageBox::question(this, tr("Already Exists!"), tr("<nobr>Output file already exists! Overwrite?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
702                 if(ret != QMessageBox::Yes) return;
703         }
704         if(outputFile.exists() && (!outputFile.isFile()))
705         {
706                 QMessageBox::warning(this, tr("Not a File!"), tr("<nobr>Selected output file does not appear to be a valid file!</nobr>"));
707                 return;
708         }
709
710         //Is destination dir writable?
711         QFileInfo outputDir = QFileInfo(outputFile.absolutePath());
712         if(!(outputDir.exists() && outputDir.isDir() && outputDir.isWritable()))
713         {
714                 QMessageBox::warning(this, tr("Not Writable!"), tr("<nobr>Output directory does not exist or is not writable!</nobr>"));
715                 return;
716         }
717
718         //Custom parameters okay?
719         if(!ui->editCustomX264Params->hasAcceptableInput())
720         {
721                 int ret = QMessageBox::warning(this, tr("Invalid Params"), tr("<nobr>Your custom parameters are invalid and will be discarded!</nobr>"), QMessageBox::Ignore | QMessageBox::Cancel, QMessageBox::Cancel);
722                 if(ret != QMessageBox::Ignore) return;
723         }
724
725         //Update recently used
726         m_recentlyUsed->setFilterIndex(currentOutputIndx());
727         m_recentlyUsed->setSourceDirectory(currentSourcePath());
728         m_recentlyUsed->setOutputDirectory(currentOutputPath());
729         RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
730
731         //Save options
732         saveOptions(m_options);
733         QDialog::accept();
734 }
735
736 void AddJobDialog::browseButtonClicked(void)
737 {
738         if(QObject::sender() == ui->buttonBrowseSource)
739         {
740                 QString filePath = QFileDialog::getOpenFileName(this, tr("Open Source File"), currentSourcePath(true), getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
741                 if(!(filePath.isNull() || filePath.isEmpty()))
742                 {
743                         QString destFile = generateOutputFileName(filePath, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
744                         ui->editSource->setText(QDir::toNativeSeparators(filePath));
745                         ui->editOutput->setText(QDir::toNativeSeparators(destFile));
746                 }
747         }
748         else if(QObject::sender() == ui->buttonBrowseOutput)
749         {
750                 QString selectedType = getFilterStr(currentOutputIndx());
751                 QString filePath = QFileDialog::getSaveFileName(this, tr("Choose Output File"), currentOutputPath(true), getFilterLst(), &selectedType, QFileDialog::DontUseNativeDialog | QFileDialog::DontConfirmOverwrite);
752
753                 if(!(filePath.isNull() || filePath.isEmpty()))
754                 {
755                         if(getFilterIdx(QFileInfo(filePath).suffix()) < 0)
756                         {
757                                 int tempIndex = -1;
758                                 QRegExp regExp("\\(\\*\\.(\\w+)\\)");
759                                 if(regExp.lastIndexIn(selectedType) >= 0)
760                                 {
761                                         tempIndex = getFilterIdx(regExp.cap(1));
762                                 }
763                                 if(tempIndex < 0)
764                                 {
765                                         tempIndex = m_recentlyUsed->filterIndex();
766                                 }
767                                 filePath = QString("%1.%2").arg(filePath, getFilterExt(tempIndex));
768                         }
769                         ui->editOutput->setText(QDir::toNativeSeparators(filePath));
770                 }
771         }
772 }
773
774 void AddJobDialog::configurationChanged(void)
775 {
776         if(!m_monitorConfigChanges)
777         {
778                 return;
779         }
780
781         const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
782         if(options)
783         {
784                 ui->cbxTemplate->blockSignals(true);
785                 ui->cbxTemplate->insertItem(0, tr("<Modified Configuration>"), QVariant::fromValue<const void*>(NULL));
786                 ui->cbxTemplate->setCurrentIndex(0);
787                 ui->cbxTemplate->blockSignals(false);
788         }
789 }
790
791 void AddJobDialog::templateSelected(void)
792 {
793         const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
794         if(options)
795         {
796                 qDebug("Loading options!");
797                 m_lastTemplateName = ui->cbxTemplate->itemText(ui->cbxTemplate->currentIndex());
798                 REMOVE_USAFED_ITEM;
799                 restoreOptions(options);
800         }
801 }
802
803 void AddJobDialog::saveTemplateButtonClicked(void)
804 {
805         qDebug("Saving template");
806
807         QString name = m_lastTemplateName;
808         if(name.isEmpty() || name.contains('<') || name.contains('>'))
809         {
810                 name = tr("New Template");
811                 int n = 1;
812                 while(OptionsModel::templateExists(name))
813                 {
814                         name = tr("New Template (%1)").arg(QString::number(++n));
815                 }
816         }
817
818         QScopedPointer<OptionsModel> options(new OptionsModel(m_sysinfo));
819         saveOptions(options.data());
820
821         if(options->equals(m_defaults))
822         {
823                 QMessageBox::warning (this, tr("Oups"), tr("<nobr>It makes no sense to save the default settings!</nobr>"));
824                 ui->cbxTemplate->blockSignals(true);
825                 ui->cbxTemplate->setCurrentIndex(0);
826                 ui->cbxTemplate->blockSignals(false);
827                 REMOVE_USAFED_ITEM;
828                 return;
829         }
830
831         for(int i = 0; i < ui->cbxTemplate->count(); i++)
832         {
833                 const QString tempName = ui->cbxTemplate->itemText(i);
834                 if(tempName.contains('<') || tempName.contains('>'))
835                 {
836                         continue;
837                 }
838                 const OptionsModel* test = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
839                 if(test != NULL)
840                 {
841                         if(options->equals(test))
842                         {
843                                 QMessageBox::information (this, tr("Oups"), tr("<nobr>The current settings are already saved as template:<br><b>%1</b></nobr>").arg(ui->cbxTemplate->itemText(i)));
844                                 ui->cbxTemplate->blockSignals(true);
845                                 ui->cbxTemplate->setCurrentIndex(i);
846                                 ui->cbxTemplate->blockSignals(false);
847                                 REMOVE_USAFED_ITEM;
848                                 return;
849                         }
850                 }
851         }
852
853         forever
854         {
855                 bool ok = false;
856                 
857                 QStringList items;
858                 items << name;
859                 for(int i = 0; i < ui->cbxTemplate->count(); i++)
860                 {
861                         const QString tempName = ui->cbxTemplate->itemText(i);
862                         if(!(tempName.contains('<') || tempName.contains('>')))
863                         {
864                                 items << tempName;
865                         }
866                 }
867                 
868                 name = QInputDialog::getItem(this, tr("Save Template"), tr("Please enter the name of the template:").leftJustified(144, ' '), items, 0, true, &ok).simplified();
869                 if(!ok)
870                 {
871                         return;
872                 }
873                 if(name.isEmpty())
874                 {
875                         continue;
876                 }
877                 if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/') || name.contains('"'))
878                 {
879                         QMessageBox::warning (this, tr("Invalid Name"), tr("<nobr>Sorry, the name you have entered is invalid!</nobr>"));
880                         while(name.contains('<')) name.remove('<');
881                         while(name.contains('>')) name.remove('>');
882                         while(name.contains('\\')) name.remove('\\');
883                         while(name.contains('/')) name.remove('/');
884                         while(name.contains('"')) name.remove('"');
885                         name = name.simplified();
886                         continue;
887                 }
888                 if(OptionsModel::templateExists(name))
889                 {
890                         int ret = QMessageBox::warning (this, tr("Already Exists"), tr("<nobr>A template of that name already exists! Overwrite?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
891                         if(ret != QMessageBox::Yes)
892                         {
893                                 continue;
894                         }
895                 }
896                 break;
897         }
898         
899         if(!OptionsModel::saveTemplate(options.data(), name))
900         {
901                 QMessageBox::critical(this, tr("Save Failed"), tr("Sorry, the template could not be saved!"));
902                 return;
903         }
904         
905         ui->cbxTemplate->blockSignals(true);
906         for(int i = 0; i < ui->cbxTemplate->count(); i++)
907         {
908                 if(ui->cbxTemplate->itemText(i).compare(name, Qt::CaseInsensitive) == 0)
909                 {
910                         QScopedPointer<const OptionsModel> oldItem(reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>()));
911                         ui->cbxTemplate->setItemData(i, QVariant::fromValue<const void*>(options.take()));
912                         ui->cbxTemplate->setCurrentIndex(i);
913                 }
914         }
915         if(!options.isNull())
916         {
917                 const int index = ui->cbxTemplate->model()->rowCount();
918                 ui->cbxTemplate->insertItem(index, name, QVariant::fromValue<const void*>(options.take()));
919                 ui->cbxTemplate->setCurrentIndex(index);
920         }
921         ui->cbxTemplate->blockSignals(false);
922
923         m_lastTemplateName = name;
924         REMOVE_USAFED_ITEM;
925 }
926
927 void AddJobDialog::deleteTemplateButtonClicked(void)
928 {
929         const int index = ui->cbxTemplate->currentIndex();
930         QString name = ui->cbxTemplate->itemText(index);
931
932         if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/'))
933         {
934                 QMessageBox::warning (this, tr("Invalid Item"), tr("Sorry, the selected item cannot be deleted!"));
935                 return;
936         }
937
938         int ret = QMessageBox::question (this, tr("Delete Template"), tr("<nobr>Do you really want to delete the selected template?<br><b>%1</b></nobr>").arg(name), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
939         if(ret != QMessageBox::Yes)
940         {
941                 return;
942         }
943         
944         OptionsModel::deleteTemplate(name);
945         const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(index).value<const void*>());
946         ui->cbxTemplate->removeItem(index);
947         MUTILS_DELETE(item);
948 }
949
950 void AddJobDialog::editorActionTriggered(void)
951 {
952
953         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
954         {
955                 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
956                 
957                 EditorDialog *editor = new EditorDialog(this);
958                 editor->setEditText(lineEdit->text());
959
960                 if(editor->exec() == QDialog::Accepted)
961                 {
962                         lineEdit->setText(editor->getEditText());
963                 }
964
965                 MUTILS_DELETE(editor);
966         }
967 }
968
969 void AddJobDialog::copyActionTriggered(void)
970 {
971         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
972         {
973                 QClipboard *clipboard = QApplication::clipboard();
974                 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
975                 QString text = lineEdit->hasSelectedText() ? lineEdit->selectedText() : lineEdit->text();
976                 clipboard->setText(text);
977         }
978 }
979
980 void AddJobDialog::pasteActionTriggered(void)
981 {
982         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
983         {
984                 QClipboard *clipboard = QApplication::clipboard();
985                 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
986                 QString text = clipboard->text();
987                 if(!text.isEmpty()) lineEdit->setText(text);
988         }
989 }
990
991 ///////////////////////////////////////////////////////////////////////////////
992 // Public functions
993 ///////////////////////////////////////////////////////////////////////////////
994
995 QString AddJobDialog::sourceFile(void)
996 {
997         return QDir::fromNativeSeparators(ui->editSource->text());
998 }
999
1000 QString AddJobDialog::outputFile(void)
1001 {
1002         return QDir::fromNativeSeparators(ui->editOutput->text());
1003 }
1004
1005 bool AddJobDialog::runImmediately(void)
1006 {
1007         return ui->checkBoxRun->isChecked();
1008 }
1009
1010 bool AddJobDialog::applyToAll(void)
1011 {
1012         return ui->checkBoxApplyToAll->isChecked();
1013 }
1014
1015 void AddJobDialog::setRunImmediately(bool run)
1016 {
1017         ui->checkBoxRun->setChecked(run);
1018 }
1019
1020 void AddJobDialog::setSourceFile(const QString &path)
1021 {
1022         ui->editSource->setText(QDir::toNativeSeparators(path));
1023 }
1024
1025 void AddJobDialog::setOutputFile(const QString &path)
1026 {
1027         ui->editOutput->setText(QDir::toNativeSeparators(path));}
1028
1029 void AddJobDialog::setSourceEditable(const bool editable)
1030 {
1031         ui->buttonBrowseSource->setEnabled(editable);
1032 }
1033
1034 void AddJobDialog::setApplyToAllVisible(const bool visible)
1035 {
1036         ui->checkBoxApplyToAll->setVisible(visible);
1037 }
1038
1039 ///////////////////////////////////////////////////////////////////////////////
1040 // Private functions
1041 ///////////////////////////////////////////////////////////////////////////////
1042
1043 void AddJobDialog::loadTemplateList(void)
1044 {
1045         ui->cbxTemplate->addItem(tr("<Default>"), QVariant::fromValue<const void*>(m_defaults));
1046         ui->cbxTemplate->setCurrentIndex(0);
1047
1048         QMap<QString, OptionsModel*> templates = OptionsModel::loadAllTemplates(m_sysinfo);
1049         QStringList templateNames = templates.keys();
1050         templateNames.sort();
1051
1052         for(QStringList::ConstIterator current = templateNames.constBegin(); current != templateNames.constEnd(); current++)
1053         {
1054                 OptionsModel *currentTemplate = templates.take(*current);
1055                 ui->cbxTemplate->addItem(*current, QVariant::fromValue<const void*>(currentTemplate));
1056                 if(currentTemplate->equals(m_options))
1057                 {
1058                         ui->cbxTemplate->setCurrentIndex(ui->cbxTemplate->count() - 1);
1059                 }
1060         }
1061
1062         if((ui->cbxTemplate->currentIndex() == 0) && (!m_options->equals(m_defaults)))
1063         {
1064                 qWarning("Not the default -> recently used!");
1065                 ui->cbxTemplate->insertItem(1, tr("<Recently Used>"), QVariant::fromValue<const void*>(m_options));
1066                 ui->cbxTemplate->setCurrentIndex(1);
1067         }
1068 }
1069
1070 void AddJobDialog::updateComboBox(QComboBox *const cbox, const QString &text)
1071 {
1072         int index = 0;
1073         if(QAbstractItemModel *model = cbox->model())
1074         {
1075                 for(int i = 0; i < cbox->model()->rowCount(); i++)
1076                 {
1077                         if(model->data(model->index(i, 0, QModelIndex())).toString().compare(text, Qt::CaseInsensitive) == 0)
1078                         {
1079                                 index = i;
1080                                 break;
1081                         }
1082                 }
1083         }
1084         cbox->setCurrentIndex(index);
1085 }
1086
1087 void AddJobDialog::updateComboBox(QComboBox *const cbox, const int &data)
1088 {
1089         int index = 0;
1090         if (QAbstractItemModel *model = cbox->model())
1091         {
1092                 for (int i = 0; i < cbox->model()->rowCount(); i++)
1093                 {
1094                         if (cbox->itemData(i).toInt() == data)
1095                         {
1096                                 index = i;
1097                                 break;
1098                         }
1099                 }
1100         }
1101         cbox->setCurrentIndex(index);
1102 }
1103
1104 void AddJobDialog::updateComboBox(QComboBox *const cbox, const quint32 &data)
1105 {
1106         int index = 0;
1107         if(QAbstractItemModel *model = cbox->model())
1108         {
1109                 for(int i = 0; i < cbox->model()->rowCount(); i++)
1110                 {
1111                         if(cbox->itemData(i).toUInt() == data)
1112                         {
1113                                 index = i;
1114                                 break;
1115                         }
1116                 }
1117         }
1118         cbox->setCurrentIndex(index);
1119 }
1120
1121 void AddJobDialog::restoreOptions(const OptionsModel *options)
1122 {
1123         DisableHelperRAII disable(&m_monitorConfigChanges);
1124
1125         updateComboBox(ui->cbxEncoderType,     options->encType());
1126         updateComboBox(ui->cbxEncoderArch,     options->encArch());
1127         updateComboBox(ui->cbxEncoderVariant,  options->encVariant());
1128         updateComboBox(ui->cbxRateControlMode, options->rcMode());
1129
1130         ui->spinQuantizer->setValue(options->quantizer());
1131         ui->spinBitrate  ->setValue(options->bitrate());
1132
1133         updateComboBox(ui->cbxPreset,  options->preset());
1134         updateComboBox(ui->cbxTuning,  options->tune());
1135         updateComboBox(ui->cbxProfile, options->profile());
1136
1137         ui->editCustomX264Params   ->setText(options->customEncParams());
1138         ui->editCustomAvs2YUVParams->setText(options->customAvs2YUV());
1139 }
1140
1141 void AddJobDialog::saveOptions(OptionsModel *options)
1142 {
1143         options->setEncType(static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt()));
1144
1145         options->setEncArch   (ui->cbxEncoderArch    ->itemData(ui->cbxEncoderArch    ->currentIndex()).toUInt());
1146         options->setEncVariant(ui->cbxEncoderVariant ->itemData(ui->cbxEncoderVariant ->currentIndex()).toUInt());
1147         options->setRCMode    (ui->cbxRateControlMode->itemData(ui->cbxRateControlMode->currentIndex()).toUInt());
1148         
1149         options->setQuantizer(ui->spinQuantizer->value());
1150         options->setBitrate  (ui->spinBitrate  ->value());
1151         
1152         options->setPreset (ui->cbxPreset ->model()->data(ui->cbxPreset ->model()->index(ui->cbxPreset ->currentIndex(), 0)).toString());
1153         options->setTune   (ui->cbxTuning ->model()->data(ui->cbxTuning ->model()->index(ui->cbxTuning ->currentIndex(), 0)).toString());
1154         options->setProfile(ui->cbxProfile->model()->data(ui->cbxProfile->model()->index(ui->cbxProfile->currentIndex(), 0)).toString());
1155
1156         options->setCustomEncParams(ui->editCustomX264Params->hasAcceptableInput() ? ui->editCustomX264Params->text().simplified()     : QString());
1157         options->setCustomAvs2YUV(ui->editCustomAvs2YUVParams->hasAcceptableInput() ? ui->editCustomAvs2YUVParams->text().simplified() : QString());
1158 }
1159
1160 QString AddJobDialog::currentSourcePath(const bool bWithName)
1161 {
1162         QString path = m_recentlyUsed->sourceDirectory();
1163         QString currentSourceFile = this->sourceFile();
1164         
1165         if(!currentSourceFile.isEmpty())
1166         {
1167                 QString currentSourceDir = QFileInfo(currentSourceFile).absolutePath();
1168                 if(VALID_DIR(currentSourceDir))
1169                 {
1170                         path = currentSourceDir;
1171                 }
1172                 if(bWithName)
1173                 {
1174                         path.append("/").append(QFileInfo(currentSourceFile).fileName());
1175                 }
1176         }
1177
1178         return path;
1179 }
1180
1181 QString AddJobDialog::currentOutputPath(const bool bWithName)
1182 {
1183         QString path = m_recentlyUsed->outputDirectory();
1184         QString currentOutputFile = this->outputFile();
1185         
1186         if(!currentOutputFile.isEmpty())
1187         {
1188                 QString currentOutputDir = QFileInfo(currentOutputFile).absolutePath();
1189                 if(VALID_DIR(currentOutputDir))
1190                 {
1191                         path = currentOutputDir;
1192                 }
1193                 if(bWithName)
1194                 {
1195                         path.append("/").append(QFileInfo(currentOutputFile).fileName());
1196                 }
1197         }
1198
1199         return path;
1200 }
1201
1202 int AddJobDialog::currentOutputIndx(void)
1203 {
1204         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
1205         if(encType == OptionsModel::EncType_X265)
1206         {
1207                 return ARRAY_SIZE(X264_FILE_TYPE_FILTERS) - 1;
1208         }
1209         
1210         int index = m_recentlyUsed->filterIndex();
1211         const QString currentOutputFile = this->outputFile();
1212
1213         if(!currentOutputFile.isEmpty())
1214         {
1215                 const QString currentOutputExtn = QFileInfo(currentOutputFile).suffix();
1216                 const int tempIndex = getFilterIdx(currentOutputExtn);
1217                 if(tempIndex >= 0)
1218                 {
1219                         index = tempIndex;
1220                 }
1221         }
1222
1223         return index;
1224 }
1225
1226 ///////////////////////////////////////////////////////////////////////////////
1227 // Static functions
1228 ///////////////////////////////////////////////////////////////////////////////
1229
1230 QString AddJobDialog::generateOutputFileName(const QString &sourceFilePath, const QString &destinationDirectory, const int filterIndex, const bool saveToSourceDir)
1231 {
1232         QString name = QFileInfo(sourceFilePath).completeBaseName();
1233         QString path = saveToSourceDir ? QFileInfo(sourceFilePath).canonicalPath() : destinationDirectory;
1234         QString fext = getFilterExt(filterIndex);
1235         
1236         if(!VALID_DIR(path))
1237         {
1238                 RecentlyUsed defaults;
1239                 path = defaults.outputDirectory();
1240         }
1241
1242         QString outPath = QString("%1/%2.%3").arg(path, name, fext);
1243
1244         int n = 2;
1245         while(QFileInfo(outPath).exists())
1246         {
1247                 outPath = QString("%1/%2 (%3).%4").arg(path, name, QString::number(n++), fext);
1248         }
1249
1250         return outPath;
1251 }
1252
1253 /* ------------------------------------------------------------------------- */
1254
1255 QString AddJobDialog::getFilterExt(const int filterIndex)
1256 {
1257         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1258
1259         if((filterIndex >= 0) && (filterIndex < count))
1260         {
1261                 return QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt);
1262         }
1263
1264         return QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt);
1265 }
1266
1267 int AddJobDialog::getFilterIdx(const QString &fileExt)
1268 {
1269         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1270
1271         for(int i = 0; i < count; i++)
1272         {
1273                 if(fileExt.compare(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt), Qt::CaseInsensitive) == 0)
1274                 {
1275                         return i;
1276                 }
1277         }
1278
1279         return -1;
1280 }
1281
1282 QString AddJobDialog::getFilterStr(const int filterIndex)
1283 {
1284         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1285
1286         if((filterIndex >= 0) && (filterIndex < count))
1287         {
1288                 return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt));
1289         }
1290
1291         return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt));
1292 }
1293
1294 QString AddJobDialog::getFilterLst(void)
1295 {
1296         QStringList filters;
1297         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1298         
1299         for(int i = 0; i < count; i++)
1300         {
1301                 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt));
1302         }
1303
1304         return filters.join(";;");
1305 }
1306
1307 QString AddJobDialog::getInputFilterLst(void)
1308 {
1309         static const struct
1310         {
1311                 const char *name;
1312                 const char *fext;
1313         }
1314         s_filters[] =
1315         {
1316                 {"Avisynth Scripts", "avs"},
1317                 {"VapourSynth Scripts", "vpy"},
1318                 {"Matroska Files", "mkv"},
1319                 {"MPEG-4 Part 14 Container", "mp4"},
1320                 {"Audio Video Interleaved", "avi"},
1321                 {"Flash Video", "flv"},
1322                 {"YUV4MPEG2 Stream", "y4m"},
1323                 {"Uncompresses YUV Data", "yuv"},
1324         };
1325
1326         const int count = ARRAY_SIZE(s_filters);
1327
1328         QString allTypes;
1329         for(size_t index = 0; index < count; index++)
1330         {
1331
1332                 allTypes += QString((index > 0) ? " *.%1" : "*.%1").arg(QString::fromLatin1(s_filters[index].fext));
1333         }
1334         
1335         QStringList filters;
1336         filters << QString("All supported files (%1)").arg(allTypes);
1337
1338         for(size_t index = 0; index < count; index++)
1339         {
1340                 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(s_filters[index].name), QString::fromLatin1(s_filters[index].fext));
1341         }
1342                 
1343         filters << QString("All files (*.*)");
1344         return filters.join(";;");
1345 }
1346
1347