OSDN Git Service

2f7caf9f147a0f468fc640f564f9bdd4abade97b
[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 StringValidatorX264 : public StringValidator
264 {
265 public:
266         StringValidatorX264(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", 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
328         //Init arch combobox
329         ui->cbxEncoderArch->addItem(tr("32-Bit"), OptionsModel::EncArch_x86_32);
330         ui->cbxEncoderArch->addItem(tr("64-Bit"), OptionsModel::EncArch_x86_64);
331
332         //Init rc-mode combobox
333         ui->cbxRateControlMode->addItem(tr("CRF"),    OptionsModel::RCMode_CRF);
334         ui->cbxRateControlMode->addItem(tr("CQ"),     OptionsModel::RCMode_CQ);
335         ui->cbxRateControlMode->addItem(tr("2-Pass"), OptionsModel::RCMode_2Pass);
336         ui->cbxRateControlMode->addItem(tr("ABR"),    OptionsModel::RCMode_ABR);
337
338         //Init combobox items
339         ui->cbxTuning ->addItem(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED));
340         ui->cbxProfile->addItem(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED));
341
342         //Hide optional controls
343         ui->checkBoxApplyToAll->setVisible(false);
344
345         //Monitor combobox changes
346         connect(ui->cbxEncoderType,     SIGNAL(currentIndexChanged(int)), this, SLOT(encoderIndexChanged(int)));
347         connect(ui->cbxEncoderVariant,  SIGNAL(currentIndexChanged(int)), this, SLOT(variantIndexChanged(int)));
348         connect(ui->cbxRateControlMode, SIGNAL(currentIndexChanged(int)), this, SLOT(modeIndexChanged(int)));
349
350         //Activate buttons
351         connect(ui->buttonBrowseSource,   SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
352         connect(ui->buttonBrowseOutput,   SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
353         connect(ui->buttonSaveTemplate,   SIGNAL(clicked()), this, SLOT(saveTemplateButtonClicked()));
354         connect(ui->buttonDeleteTemplate, SIGNAL(clicked()), this, SLOT(deleteTemplateButtonClicked()));
355
356         //Setup validator
357         ui->editCustomX264Params->installEventFilter(this);
358         ui->editCustomX264Params->setValidator(new StringValidatorX264(ui->labelNotificationX264, ui->iconNotificationX264));
359         ui->editCustomX264Params->clear();
360         ui->editCustomAvs2YUVParams->installEventFilter(this);
361         ui->editCustomAvs2YUVParams->setValidator(new StringValidatorAvs2YUV(ui->labelNotificationAvs2YUV, ui->iconNotificationAvs2YUV));
362         ui->editCustomAvs2YUVParams->clear();
363
364         //Install event filter
365         ui->labelHelpScreenX264->installEventFilter(this);
366         ui->labelHelpScreenAvs2YUV->installEventFilter(this);
367
368         //Monitor for options changes
369         connect(ui->cbxEncoderType, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
370         connect(ui->cbxEncoderArch, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
371         connect(ui->cbxEncoderVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
372         connect(ui->cbxRateControlMode, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
373         connect(ui->spinQuantizer, SIGNAL(valueChanged(double)), this, SLOT(configurationChanged()));
374         connect(ui->spinBitrate, SIGNAL(valueChanged(int)), this, SLOT(configurationChanged()));
375         connect(ui->cbxPreset, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
376         connect(ui->cbxTuning, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
377         connect(ui->cbxProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
378         connect(ui->editCustomX264Params, SIGNAL(textChanged(QString)), this, SLOT(configurationChanged()));
379         connect(ui->editCustomAvs2YUVParams, SIGNAL(textChanged(QString)), this, SLOT(configurationChanged()));
380
381         //Create context menus
382         ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_edit.png"), tr("Open the Text-Editor"), editorActionTriggered);
383         ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_edit.png"), tr("Open the Text-Editor"), editorActionTriggered);
384         ADD_CONTEXTMENU_SEPARATOR(ui->editCustomX264Params);
385         ADD_CONTEXTMENU_SEPARATOR(ui->editCustomAvs2YUVParams);
386         ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_copy.png"), tr("Copy to Clipboard"), copyActionTriggered);
387         ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_copy.png"), tr("Copy to Clipboard"), copyActionTriggered);
388         ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_paste.png"), tr("Paste from Clipboard"), pasteActionTriggered);
389         ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_paste.png"), tr("Paste from Clipboard"), pasteActionTriggered);
390
391         //Setup template selector
392         loadTemplateList();
393         connect(ui->cbxTemplate, SIGNAL(currentIndexChanged(int)), this, SLOT(templateSelected()));
394
395         //Force initial UI update
396         encoderIndexChanged(ui->cbxEncoderType->currentIndex());
397         m_monitorConfigChanges = true;
398 }
399
400 AddJobDialog::~AddJobDialog(void)
401 {
402         //Free templates
403         for(int i = 0; i < ui->cbxTemplate->model()->rowCount(); i++)
404         {
405                 if(ui->cbxTemplate->itemText(i).startsWith("<") || ui->cbxTemplate->itemText(i).endsWith(">"))
406                 {
407                         continue;
408                 }
409                 const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
410                 ui->cbxTemplate->setItemData(i, QVariant::fromValue<const void*>(NULL));
411                 MUTILS_DELETE(item);
412         }
413
414         //Free validators
415         if(const QValidator *tmp = ui->editCustomX264Params->validator())
416         {
417                 ui->editCustomX264Params->setValidator(NULL);
418                 MUTILS_DELETE(tmp);
419         }
420         if(const QValidator *tmp = ui->editCustomAvs2YUVParams->validator())
421         {
422                 ui->editCustomAvs2YUVParams->setValidator(NULL);
423                 MUTILS_DELETE(tmp);
424         }
425
426         MUTILS_DELETE(m_defaults);
427         delete ui;
428 }
429
430 ///////////////////////////////////////////////////////////////////////////////
431 // Events
432 ///////////////////////////////////////////////////////////////////////////////
433
434 void AddJobDialog::showEvent(QShowEvent *event)
435 {
436         QDialog::showEvent(event);
437         templateSelected();
438
439         if((!ui->editSource->text().isEmpty()) && ui->editOutput->text().isEmpty())
440         {
441                 QString outPath = generateOutputFileName(QDir::fromNativeSeparators(ui->editSource->text()), m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
442                 ui->editOutput->setText(QDir::toNativeSeparators(outPath));
443                 ui->buttonAccept->setFocus();
444         }
445
446         ui->labelNotificationX264->hide();
447         ui->iconNotificationX264->hide();
448         ui->labelNotificationAvs2YUV->hide();
449         ui->iconNotificationAvs2YUV->hide();
450
451         //Enable drag&drop support for this window, required for Qt v4.8.4+
452         setAcceptDrops(true);
453 }
454
455 bool AddJobDialog::eventFilter(QObject *o, QEvent *e)
456 {
457         if((o == ui->labelHelpScreenX264) && (e->type() == QEvent::MouseButtonPress))
458         {
459                 OptionsModel options(m_sysinfo); saveOptions(&options);
460                 QScopedPointer<HelpDialog> helpScreen(new HelpDialog(this, false, m_sysinfo, &options, m_preferences));
461                 helpScreen->exec();
462         }
463         else if((o == ui->labelHelpScreenAvs2YUV) && (e->type() == QEvent::MouseButtonPress))
464         {
465                 OptionsModel options(m_sysinfo); saveOptions(&options);
466                 QScopedPointer<HelpDialog> helpScreen(new HelpDialog(this, true, m_sysinfo, &options, m_preferences));
467                 helpScreen->exec();
468         }
469         else if((o == ui->editCustomX264Params) && (e->type() == QEvent::FocusOut))
470         {
471                 ui->editCustomX264Params->setText(ui->editCustomX264Params->text().simplified());
472         }
473         else if((o == ui->editCustomAvs2YUVParams) && (e->type() == QEvent::FocusOut))
474         {
475                 ui->editCustomAvs2YUVParams->setText(ui->editCustomAvs2YUVParams->text().simplified());
476         }
477         return false;
478 }
479
480 void AddJobDialog::dragEnterEvent(QDragEnterEvent *event)
481 {
482         bool accept[2] = {false, false};
483
484         foreach(const QString &fmt, event->mimeData()->formats())
485         {
486                 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
487                 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
488         }
489
490         if(accept[0] && accept[1])
491         {
492                 event->acceptProposedAction();
493         }
494 }
495
496 void AddJobDialog::dropEvent(QDropEvent *event)
497 {
498         QString droppedFile;
499         QList<QUrl> urls = event->mimeData()->urls();
500
501         if(urls.count() > 1)
502         {
503                 QDragEnterEvent dragEvent(event->pos(), event->proposedAction(), event->mimeData(), Qt::NoButton, Qt::NoModifier);
504                 if(qApp->notify(parent(), &dragEvent))
505                 {
506                         qApp->notify(parent(), event);
507                         reject(); return;
508                 }
509         }
510
511         while((!urls.isEmpty()) && droppedFile.isEmpty())
512         {
513                 QUrl currentUrl = urls.takeFirst();
514                 QFileInfo file(currentUrl.toLocalFile());
515                 if(file.exists() && file.isFile())
516                 {
517                         qDebug("AddJobDialog::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
518                         droppedFile = file.canonicalFilePath();
519                 }
520         }
521         
522         if(!droppedFile.isEmpty())
523         {
524                 const QString outFileName = generateOutputFileName(droppedFile, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
525                 ui->editSource->setText(QDir::toNativeSeparators(droppedFile));
526                 ui->editOutput->setText(QDir::toNativeSeparators(outFileName));
527         }
528 }
529
530 ///////////////////////////////////////////////////////////////////////////////
531 // Slots
532 ///////////////////////////////////////////////////////////////////////////////
533
534 void AddJobDialog::encoderIndexChanged(int index)
535 {
536         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
537         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
538
539         //Update encoder variants
540         const QFlags<OptionsModel::EncVariant> variants = encoderInfo.getVariants();
541         ui->cbxEncoderVariant->clear();
542         for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_MIN; varnt <= OptionsModel::EncVariant_MAX; SHFL(varnt))
543         {
544                 if(variants.testFlag(varnt))
545                 {
546                         QString varntText;
547                         switch(varnt)
548                         {
549                                 case OptionsModel::EncVariant_8Bit:  varntText = tr("8-Bit");  break;
550                                 case OptionsModel::EncVariant_10Bit: varntText = tr("10-Bit"); break;
551                                 case OptionsModel::EncVariant_12Bit: varntText = tr("12-Bit"); break;
552                                 default: MUTILS_THROW("Bad encoder variant!");
553                         }
554                         ui->cbxEncoderVariant->addItem(varntText, QVariant(varnt));
555                 }
556         }
557
558         //Update presets
559         const QStringList presets = encoderInfo.getPresets();
560         if(presets.empty())
561         {
562                 ui->cbxPreset->setEnabled(false);
563                 ui->cbxPreset->setCurrentIndex(0);
564         }
565         else
566         {
567                 ui->cbxPreset->setEnabled(true);
568                 ui->cbxPreset->clear();
569                 ui->cbxPreset->addItem(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED));
570                 ui->cbxPreset->addItems(presets);
571         }
572
573         //Update tunings
574         const QStringList tunings = encoderInfo.getTunings();
575         if(tunings.empty())
576         {
577                 ui->cbxTuning->setEnabled(false);
578                 ui->cbxTuning->setCurrentIndex(0);
579         }
580         else
581         {
582                 ui->cbxTuning->setEnabled(true);
583                 ui->cbxTuning->clear();
584                 ui->cbxTuning->addItem(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED));
585                 ui->cbxTuning->addItems(tunings);
586         }
587
588         variantIndexChanged(ui->cbxEncoderVariant->currentIndex());
589 }
590
591 void AddJobDialog::variantIndexChanged(int index)
592 {
593         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
594         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
595
596         //Update encoder profiles
597         const QStringList profiles = encoderInfo.getProfiles(static_cast<OptionsModel::EncVariant>(ui->cbxEncoderVariant->itemData(index).toInt()));
598         if(profiles.empty())
599         {
600                 ui->cbxProfile->setEnabled(false);
601                 ui->cbxProfile->setCurrentIndex(0);
602         }
603         else
604         {
605                 ui->cbxProfile->setEnabled(true);
606                 ui->cbxProfile->clear();
607                 ui->cbxProfile->addItem(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED));
608                 ui->cbxProfile->addItems(profiles);
609         }
610         
611         modeIndexChanged(ui->cbxRateControlMode->currentIndex());
612 }
613
614 void AddJobDialog::modeIndexChanged(int index)
615 {
616         ui->spinQuantizer->setEnabled(index == OptionsModel::RCMode_CRF || index == OptionsModel::RCMode_CQ);
617         ui->spinBitrate  ->setEnabled(index == OptionsModel::RCMode_ABR || index == OptionsModel::RCMode_2Pass);
618 }
619
620 void AddJobDialog::accept(void)
621 {
622         //Check 64-Bit support
623         if((ui->cbxEncoderArch->currentIndex() == OptionsModel::EncArch_x86_64) && (!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64)))
624         {
625                 QMessageBox::warning(this, tr("64-Bit unsupported!"), tr("<nobr>Sorry, this computer does <b>not</b> support 64-Bit encoders!</nobr>"));
626                 ui->cbxEncoderArch->setCurrentIndex(OptionsModel::EncArch_x86_32);
627                 return;
628         }
629         
630         //Selection complete?
631         if(ui->editSource->text().trimmed().isEmpty())
632         {
633                 QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>Please select a valid source file first!<(nobr>"));
634                 return;
635         }
636         if(ui->editOutput->text().trimmed().isEmpty())
637         {
638                 QMessageBox::warning(this, tr("Not Selected!"), tr("<nobr>Please select a valid output file first!</nobr>"));
639                 return;
640         }
641
642         //Does source exist?
643         QFileInfo sourceFile = QFileInfo(this->sourceFile());
644         if(!(sourceFile.exists() && sourceFile.isFile()))
645         {
646                 QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>The selected source file could not be found!</nobr>"));
647                 return;
648         }
649
650         //Get encoder info
651         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
652         const AbstractEncoderInfo &encoderInfo = EncoderFactory::getEncoderInfo(encType);
653
654         //Is selected RC mode supported?
655         if(!encoderInfo.isRCModeSupported(static_cast<OptionsModel::RCMode>(ui->cbxRateControlMode->currentIndex())))
656         {
657                 QMessageBox::warning(this, tr("Bad RC Mode!"), tr("<nobr>The selected RC mode is not supported by the selected encoder!</nobr>"));
658                 for(int i = 0; i < ui->cbxRateControlMode->count(); i++)
659                 {
660                         if(encoderInfo.isRCModeSupported(static_cast<OptionsModel::RCMode>(i)))
661                         {
662                                 ui->cbxRateControlMode->setCurrentIndex(i);
663                                 break;
664                         }
665                 }
666                 return;
667         }
668
669         //Is the type of the source file supported?
670         const int sourceType = MediaInfo::analyze(sourceFile.canonicalFilePath());
671         if(sourceType == MediaInfo::FILETYPE_AVISYNTH)
672         {
673                 if(!m_sysinfo->hasAvisynth())
674                 {
675                         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)
676                         {
677                                 return;
678                         }
679                 }
680         }
681         else if(sourceType == MediaInfo::FILETYPE_VAPOURSYNTH)
682         {
683                 if(!m_sysinfo->hasAvisynth())
684                 {
685                         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)
686                         {
687                                 return;
688                         }
689                 }
690         }
691         else if(!encoderInfo.isInputTypeSupported(sourceType))
692         {
693                 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)
694                 {
695                         return;
696                 }
697         }
698         
699         //Is output file extension supported by encoder?
700         const QStringList outputFormats = encoderInfo.supportedOutputFormats();
701         QFileInfo outputFile = QFileInfo(this->outputFile());
702         if(!outputFormats.contains(outputFile.suffix(), Qt::CaseInsensitive))
703         {
704                 QMessageBox::warning(this, tr("Unsupported output format"), tr("<nobr>Sorry, the selected encoder does not support the selected output format!</nobr>"));
705                 ui->editOutput->setText(QDir::toNativeSeparators(QString("%1/%2.%3").arg(outputFile.absolutePath(), outputFile.completeBaseName(), outputFormats.first())));
706                 return;
707         }
708
709         //Does output file already exist?
710         if(outputFile.exists() && outputFile.isFile())
711         {
712                 int ret = QMessageBox::question(this, tr("Already Exists!"), tr("<nobr>Output file already exists! Overwrite?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
713                 if(ret != QMessageBox::Yes) return;
714         }
715         if(outputFile.exists() && (!outputFile.isFile()))
716         {
717                 QMessageBox::warning(this, tr("Not a File!"), tr("<nobr>Selected output file does not appear to be a valid file!</nobr>"));
718                 return;
719         }
720
721         //Is destination dir writable?
722         QFileInfo outputDir = QFileInfo(outputFile.absolutePath());
723         if(!(outputDir.exists() && outputDir.isDir() && outputDir.isWritable()))
724         {
725                 QMessageBox::warning(this, tr("Not Writable!"), tr("<nobr>Output directory does not exist or is not writable!</nobr>"));
726                 return;
727         }
728
729         //Custom parameters okay?
730         if(!ui->editCustomX264Params->hasAcceptableInput())
731         {
732                 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);
733                 if(ret != QMessageBox::Ignore) return;
734         }
735
736         //Update recently used
737         m_recentlyUsed->setFilterIndex(currentOutputIndx());
738         m_recentlyUsed->setSourceDirectory(currentSourcePath());
739         m_recentlyUsed->setOutputDirectory(currentOutputPath());
740         RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
741
742         //Save options
743         saveOptions(m_options);
744         QDialog::accept();
745 }
746
747 void AddJobDialog::browseButtonClicked(void)
748 {
749         if(QObject::sender() == ui->buttonBrowseSource)
750         {
751                 QString filePath = QFileDialog::getOpenFileName(this, tr("Open Source File"), currentSourcePath(true), getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
752                 if(!(filePath.isNull() || filePath.isEmpty()))
753                 {
754                         QString destFile = generateOutputFileName(filePath, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
755                         ui->editSource->setText(QDir::toNativeSeparators(filePath));
756                         ui->editOutput->setText(QDir::toNativeSeparators(destFile));
757                 }
758         }
759         else if(QObject::sender() == ui->buttonBrowseOutput)
760         {
761                 QString selectedType = getFilterStr(currentOutputIndx());
762                 QString filePath = QFileDialog::getSaveFileName(this, tr("Choose Output File"), currentOutputPath(true), getFilterLst(), &selectedType, QFileDialog::DontUseNativeDialog | QFileDialog::DontConfirmOverwrite);
763
764                 if(!(filePath.isNull() || filePath.isEmpty()))
765                 {
766                         if(getFilterIdx(QFileInfo(filePath).suffix()) < 0)
767                         {
768                                 int tempIndex = -1;
769                                 QRegExp regExp("\\(\\*\\.(\\w+)\\)");
770                                 if(regExp.lastIndexIn(selectedType) >= 0)
771                                 {
772                                         tempIndex = getFilterIdx(regExp.cap(1));
773                                 }
774                                 if(tempIndex < 0)
775                                 {
776                                         tempIndex = m_recentlyUsed->filterIndex();
777                                 }
778                                 filePath = QString("%1.%2").arg(filePath, getFilterExt(tempIndex));
779                         }
780                         ui->editOutput->setText(QDir::toNativeSeparators(filePath));
781                 }
782         }
783 }
784
785 void AddJobDialog::configurationChanged(void)
786 {
787         if(!m_monitorConfigChanges)
788         {
789                 return;
790         }
791
792         const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
793         if(options)
794         {
795                 ui->cbxTemplate->blockSignals(true);
796                 ui->cbxTemplate->insertItem(0, tr("<Modified Configuration>"), QVariant::fromValue<const void*>(NULL));
797                 ui->cbxTemplate->setCurrentIndex(0);
798                 ui->cbxTemplate->blockSignals(false);
799         }
800 }
801
802 void AddJobDialog::templateSelected(void)
803 {
804         const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
805         if(options)
806         {
807                 qDebug("Loading options!");
808                 m_lastTemplateName = ui->cbxTemplate->itemText(ui->cbxTemplate->currentIndex());
809                 REMOVE_USAFED_ITEM;
810                 restoreOptions(options);
811         }
812 }
813
814 void AddJobDialog::saveTemplateButtonClicked(void)
815 {
816         qDebug("Saving template");
817
818         QString name = m_lastTemplateName;
819         if(name.isEmpty() || name.contains('<') || name.contains('>'))
820         {
821                 name = tr("New Template");
822                 int n = 1;
823                 while(OptionsModel::templateExists(name))
824                 {
825                         name = tr("New Template (%1)").arg(QString::number(++n));
826                 }
827         }
828
829         QScopedPointer<OptionsModel> options(new OptionsModel(m_sysinfo));
830         saveOptions(options.data());
831
832         if(options->equals(m_defaults))
833         {
834                 QMessageBox::warning (this, tr("Oups"), tr("<nobr>It makes no sense to save the default settings!</nobr>"));
835                 ui->cbxTemplate->blockSignals(true);
836                 ui->cbxTemplate->setCurrentIndex(0);
837                 ui->cbxTemplate->blockSignals(false);
838                 REMOVE_USAFED_ITEM;
839                 return;
840         }
841
842         for(int i = 0; i < ui->cbxTemplate->count(); i++)
843         {
844                 const QString tempName = ui->cbxTemplate->itemText(i);
845                 if(tempName.contains('<') || tempName.contains('>'))
846                 {
847                         continue;
848                 }
849                 const OptionsModel* test = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
850                 if(test != NULL)
851                 {
852                         if(options->equals(test))
853                         {
854                                 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)));
855                                 ui->cbxTemplate->blockSignals(true);
856                                 ui->cbxTemplate->setCurrentIndex(i);
857                                 ui->cbxTemplate->blockSignals(false);
858                                 REMOVE_USAFED_ITEM;
859                                 return;
860                         }
861                 }
862         }
863
864         forever
865         {
866                 bool ok = false;
867                 
868                 QStringList items;
869                 items << name;
870                 for(int i = 0; i < ui->cbxTemplate->count(); i++)
871                 {
872                         const QString tempName = ui->cbxTemplate->itemText(i);
873                         if(!(tempName.contains('<') || tempName.contains('>')))
874                         {
875                                 items << tempName;
876                         }
877                 }
878                 
879                 name = QInputDialog::getItem(this, tr("Save Template"), tr("Please enter the name of the template:").leftJustified(144, ' '), items, 0, true, &ok).simplified();
880                 if(!ok)
881                 {
882                         return;
883                 }
884                 if(name.isEmpty())
885                 {
886                         continue;
887                 }
888                 if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/') || name.contains('"'))
889                 {
890                         QMessageBox::warning (this, tr("Invalid Name"), tr("<nobr>Sorry, the name you have entered is invalid!</nobr>"));
891                         while(name.contains('<')) name.remove('<');
892                         while(name.contains('>')) name.remove('>');
893                         while(name.contains('\\')) name.remove('\\');
894                         while(name.contains('/')) name.remove('/');
895                         while(name.contains('"')) name.remove('"');
896                         name = name.simplified();
897                         continue;
898                 }
899                 if(OptionsModel::templateExists(name))
900                 {
901                         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);
902                         if(ret != QMessageBox::Yes)
903                         {
904                                 continue;
905                         }
906                 }
907                 break;
908         }
909         
910         if(!OptionsModel::saveTemplate(options.data(), name))
911         {
912                 QMessageBox::critical(this, tr("Save Failed"), tr("Sorry, the template could not be saved!"));
913                 return;
914         }
915         
916         ui->cbxTemplate->blockSignals(true);
917         for(int i = 0; i < ui->cbxTemplate->count(); i++)
918         {
919                 if(ui->cbxTemplate->itemText(i).compare(name, Qt::CaseInsensitive) == 0)
920                 {
921                         QScopedPointer<const OptionsModel> oldItem(reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>()));
922                         ui->cbxTemplate->setItemData(i, QVariant::fromValue<const void*>(options.take()));
923                         ui->cbxTemplate->setCurrentIndex(i);
924                 }
925         }
926         if(!options.isNull())
927         {
928                 const int index = ui->cbxTemplate->model()->rowCount();
929                 ui->cbxTemplate->insertItem(index, name, QVariant::fromValue<const void*>(options.take()));
930                 ui->cbxTemplate->setCurrentIndex(index);
931         }
932         ui->cbxTemplate->blockSignals(false);
933
934         m_lastTemplateName = name;
935         REMOVE_USAFED_ITEM;
936 }
937
938 void AddJobDialog::deleteTemplateButtonClicked(void)
939 {
940         const int index = ui->cbxTemplate->currentIndex();
941         QString name = ui->cbxTemplate->itemText(index);
942
943         if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/'))
944         {
945                 QMessageBox::warning (this, tr("Invalid Item"), tr("Sorry, the selected item cannot be deleted!"));
946                 return;
947         }
948
949         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);
950         if(ret != QMessageBox::Yes)
951         {
952                 return;
953         }
954         
955         OptionsModel::deleteTemplate(name);
956         const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(index).value<const void*>());
957         ui->cbxTemplate->removeItem(index);
958         MUTILS_DELETE(item);
959 }
960
961 void AddJobDialog::editorActionTriggered(void)
962 {
963
964         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
965         {
966                 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
967                 
968                 EditorDialog *editor = new EditorDialog(this);
969                 editor->setEditText(lineEdit->text());
970
971                 if(editor->exec() == QDialog::Accepted)
972                 {
973                         lineEdit->setText(editor->getEditText());
974                 }
975
976                 MUTILS_DELETE(editor);
977         }
978 }
979
980 void AddJobDialog::copyActionTriggered(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 = lineEdit->hasSelectedText() ? lineEdit->selectedText() : lineEdit->text();
987                 clipboard->setText(text);
988         }
989 }
990
991 void AddJobDialog::pasteActionTriggered(void)
992 {
993         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
994         {
995                 QClipboard *clipboard = QApplication::clipboard();
996                 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
997                 QString text = clipboard->text();
998                 if(!text.isEmpty()) lineEdit->setText(text);
999         }
1000 }
1001
1002 ///////////////////////////////////////////////////////////////////////////////
1003 // Public functions
1004 ///////////////////////////////////////////////////////////////////////////////
1005
1006 QString AddJobDialog::sourceFile(void)
1007 {
1008         return QDir::fromNativeSeparators(ui->editSource->text());
1009 }
1010
1011 QString AddJobDialog::outputFile(void)
1012 {
1013         return QDir::fromNativeSeparators(ui->editOutput->text());
1014 }
1015
1016 bool AddJobDialog::runImmediately(void)
1017 {
1018         return ui->checkBoxRun->isChecked();
1019 }
1020
1021 bool AddJobDialog::applyToAll(void)
1022 {
1023         return ui->checkBoxApplyToAll->isChecked();
1024 }
1025
1026 void AddJobDialog::setRunImmediately(bool run)
1027 {
1028         ui->checkBoxRun->setChecked(run);
1029 }
1030
1031 void AddJobDialog::setSourceFile(const QString &path)
1032 {
1033         ui->editSource->setText(QDir::toNativeSeparators(path));
1034 }
1035
1036 void AddJobDialog::setOutputFile(const QString &path)
1037 {
1038         ui->editOutput->setText(QDir::toNativeSeparators(path));}
1039
1040 void AddJobDialog::setSourceEditable(const bool editable)
1041 {
1042         ui->buttonBrowseSource->setEnabled(editable);
1043 }
1044
1045 void AddJobDialog::setApplyToAllVisible(const bool visible)
1046 {
1047         ui->checkBoxApplyToAll->setVisible(visible);
1048 }
1049
1050 ///////////////////////////////////////////////////////////////////////////////
1051 // Private functions
1052 ///////////////////////////////////////////////////////////////////////////////
1053
1054 void AddJobDialog::loadTemplateList(void)
1055 {
1056         ui->cbxTemplate->addItem(tr("<Default>"), QVariant::fromValue<const void*>(m_defaults));
1057         ui->cbxTemplate->setCurrentIndex(0);
1058
1059         QMap<QString, OptionsModel*> templates = OptionsModel::loadAllTemplates(m_sysinfo);
1060         QStringList templateNames = templates.keys();
1061         templateNames.sort();
1062
1063         for(QStringList::ConstIterator current = templateNames.constBegin(); current != templateNames.constEnd(); current++)
1064         {
1065                 OptionsModel *currentTemplate = templates.take(*current);
1066                 ui->cbxTemplate->addItem(*current, QVariant::fromValue<const void*>(currentTemplate));
1067                 if(currentTemplate->equals(m_options))
1068                 {
1069                         ui->cbxTemplate->setCurrentIndex(ui->cbxTemplate->count() - 1);
1070                 }
1071         }
1072
1073         if((ui->cbxTemplate->currentIndex() == 0) && (!m_options->equals(m_defaults)))
1074         {
1075                 qWarning("Not the default -> recently used!");
1076                 ui->cbxTemplate->insertItem(1, tr("<Recently Used>"), QVariant::fromValue<const void*>(m_options));
1077                 ui->cbxTemplate->setCurrentIndex(1);
1078         }
1079 }
1080
1081 void AddJobDialog::updateComboBox(QComboBox *const cbox, const QString &text)
1082 {
1083         int index = 0;
1084         if(QAbstractItemModel *model = cbox->model())
1085         {
1086                 for(int i = 0; i < cbox->model()->rowCount(); i++)
1087                 {
1088                         if(model->data(model->index(i, 0, QModelIndex())).toString().compare(text, Qt::CaseInsensitive) == 0)
1089                         {
1090                                 index = i;
1091                                 break;
1092                         }
1093                 }
1094         }
1095         cbox->setCurrentIndex(index);
1096 }
1097
1098 void AddJobDialog::updateComboBox(QComboBox *const cbox, const int &data)
1099 {
1100         int index = 0;
1101         if(QAbstractItemModel *model = cbox->model())
1102         {
1103                 for(int i = 0; i < cbox->model()->rowCount(); i++)
1104                 {
1105                         if(cbox->itemData(i).toInt() == data)
1106                         {
1107                                 index = i;
1108                                 break;
1109                         }
1110                 }
1111         }
1112         cbox->setCurrentIndex(index);
1113 }
1114
1115 void AddJobDialog::restoreOptions(const OptionsModel *options)
1116 {
1117         DisableHelperRAII disbale(&m_monitorConfigChanges);
1118
1119         updateComboBox(ui->cbxEncoderType,     options->encType());
1120         updateComboBox(ui->cbxEncoderArch,     options->encArch());
1121         updateComboBox(ui->cbxEncoderVariant,  options->encVariant());
1122         updateComboBox(ui->cbxRateControlMode, options->rcMode());
1123
1124         ui->spinQuantizer->setValue(options->quantizer());
1125         ui->spinBitrate  ->setValue(options->bitrate());
1126
1127         updateComboBox(ui->cbxPreset,  options->preset());
1128         updateComboBox(ui->cbxTuning,  options->tune());
1129         updateComboBox(ui->cbxProfile, options->profile());
1130
1131         ui->editCustomX264Params   ->setText(options->customEncParams());
1132         ui->editCustomAvs2YUVParams->setText(options->customAvs2YUV());
1133 }
1134
1135 void AddJobDialog::saveOptions(OptionsModel *options)
1136 {
1137         options->setEncType   (static_cast<OptionsModel::EncType>   (ui->cbxEncoderType    ->itemData(ui->cbxEncoderType    ->currentIndex()).toInt()));
1138         options->setEncArch   (static_cast<OptionsModel::EncArch>   (ui->cbxEncoderArch    ->itemData(ui->cbxEncoderArch    ->currentIndex()).toInt()));
1139         options->setEncVariant(static_cast<OptionsModel::EncVariant>(ui->cbxEncoderVariant ->itemData(ui->cbxEncoderVariant ->currentIndex()).toInt()));
1140         options->setRCMode    (static_cast<OptionsModel::RCMode>    (ui->cbxRateControlMode->itemData(ui->cbxRateControlMode->currentIndex()).toInt()));
1141         
1142         options->setQuantizer(ui->spinQuantizer->value());
1143         options->setBitrate(ui->spinBitrate->value());
1144         
1145         options->setPreset (ui->cbxPreset ->model()->data(ui->cbxPreset ->model()->index(ui->cbxPreset ->currentIndex(), 0)).toString());
1146         options->setTune   (ui->cbxTuning ->model()->data(ui->cbxTuning ->model()->index(ui->cbxTuning ->currentIndex(), 0)).toString());
1147         options->setProfile(ui->cbxProfile->model()->data(ui->cbxProfile->model()->index(ui->cbxProfile->currentIndex(), 0)).toString());
1148
1149         options->setCustomEncParams(ui->editCustomX264Params->hasAcceptableInput() ? ui->editCustomX264Params->text().simplified() : QString());
1150         options->setCustomAvs2YUV(ui->editCustomAvs2YUVParams->hasAcceptableInput() ? ui->editCustomAvs2YUVParams->text().simplified() : QString());
1151 }
1152
1153 QString AddJobDialog::currentSourcePath(const bool bWithName)
1154 {
1155         QString path = m_recentlyUsed->sourceDirectory();
1156         QString currentSourceFile = this->sourceFile();
1157         
1158         if(!currentSourceFile.isEmpty())
1159         {
1160                 QString currentSourceDir = QFileInfo(currentSourceFile).absolutePath();
1161                 if(VALID_DIR(currentSourceDir))
1162                 {
1163                         path = currentSourceDir;
1164                 }
1165                 if(bWithName)
1166                 {
1167                         path.append("/").append(QFileInfo(currentSourceFile).fileName());
1168                 }
1169         }
1170
1171         return path;
1172 }
1173
1174 QString AddJobDialog::currentOutputPath(const bool bWithName)
1175 {
1176         QString path = m_recentlyUsed->outputDirectory();
1177         QString currentOutputFile = this->outputFile();
1178         
1179         if(!currentOutputFile.isEmpty())
1180         {
1181                 QString currentOutputDir = QFileInfo(currentOutputFile).absolutePath();
1182                 if(VALID_DIR(currentOutputDir))
1183                 {
1184                         path = currentOutputDir;
1185                 }
1186                 if(bWithName)
1187                 {
1188                         path.append("/").append(QFileInfo(currentOutputFile).fileName());
1189                 }
1190         }
1191
1192         return path;
1193 }
1194
1195 int AddJobDialog::currentOutputIndx(void)
1196 {
1197         const OptionsModel::EncType encType = static_cast<OptionsModel::EncType>(ui->cbxEncoderType->itemData(ui->cbxEncoderType->currentIndex()).toInt());
1198         if(encType == OptionsModel::EncType_X265)
1199         {
1200                 return ARRAY_SIZE(X264_FILE_TYPE_FILTERS) - 1;
1201         }
1202         
1203         int index = m_recentlyUsed->filterIndex();
1204         const QString currentOutputFile = this->outputFile();
1205
1206         if(!currentOutputFile.isEmpty())
1207         {
1208                 const QString currentOutputExtn = QFileInfo(currentOutputFile).suffix();
1209                 const int tempIndex = getFilterIdx(currentOutputExtn);
1210                 if(tempIndex >= 0)
1211                 {
1212                         index = tempIndex;
1213                 }
1214         }
1215
1216         return index;
1217 }
1218
1219 ///////////////////////////////////////////////////////////////////////////////
1220 // Static functions
1221 ///////////////////////////////////////////////////////////////////////////////
1222
1223 QString AddJobDialog::generateOutputFileName(const QString &sourceFilePath, const QString &destinationDirectory, const int filterIndex, const bool saveToSourceDir)
1224 {
1225         QString name = QFileInfo(sourceFilePath).completeBaseName();
1226         QString path = saveToSourceDir ? QFileInfo(sourceFilePath).canonicalPath() : destinationDirectory;
1227         QString fext = getFilterExt(filterIndex);
1228         
1229         if(!VALID_DIR(path))
1230         {
1231                 RecentlyUsed defaults;
1232                 path = defaults.outputDirectory();
1233         }
1234
1235         QString outPath = QString("%1/%2.%3").arg(path, name, fext);
1236
1237         int n = 2;
1238         while(QFileInfo(outPath).exists())
1239         {
1240                 outPath = QString("%1/%2 (%3).%4").arg(path, name, QString::number(n++), fext);
1241         }
1242
1243         return outPath;
1244 }
1245
1246 /* ------------------------------------------------------------------------- */
1247
1248 QString AddJobDialog::getFilterExt(const int filterIndex)
1249 {
1250         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1251
1252         if((filterIndex >= 0) && (filterIndex < count))
1253         {
1254                 return QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt);
1255         }
1256
1257         return QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt);
1258 }
1259
1260 int AddJobDialog::getFilterIdx(const QString &fileExt)
1261 {
1262         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1263
1264         for(int i = 0; i < count; i++)
1265         {
1266                 if(fileExt.compare(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt), Qt::CaseInsensitive) == 0)
1267                 {
1268                         return i;
1269                 }
1270         }
1271
1272         return -1;
1273 }
1274
1275 QString AddJobDialog::getFilterStr(const int filterIndex)
1276 {
1277         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1278
1279         if((filterIndex >= 0) && (filterIndex < count))
1280         {
1281                 return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt));
1282         }
1283
1284         return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt));
1285 }
1286
1287 QString AddJobDialog::getFilterLst(void)
1288 {
1289         QStringList filters;
1290         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1291         
1292         for(int i = 0; i < count; i++)
1293         {
1294                 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt));
1295         }
1296
1297         return filters.join(";;");
1298 }
1299
1300 QString AddJobDialog::getInputFilterLst(void)
1301 {
1302         static const struct
1303         {
1304                 const char *name;
1305                 const char *fext;
1306         }
1307         s_filters[] =
1308         {
1309                 {"Avisynth Scripts", "avs"},
1310                 {"VapourSynth Scripts", "vpy"},
1311                 {"Matroska Files", "mkv"},
1312                 {"MPEG-4 Part 14 Container", "mp4"},
1313                 {"Audio Video Interleaved", "avi"},
1314                 {"Flash Video", "flv"},
1315                 {"YUV4MPEG2 Stream", "y4m"},
1316                 {"Uncompresses YUV Data", "yuv"},
1317         };
1318
1319         const int count = ARRAY_SIZE(s_filters);
1320
1321         QString allTypes;
1322         for(size_t index = 0; index < count; index++)
1323         {
1324
1325                 allTypes += QString((index > 0) ? " *.%1" : "*.%1").arg(QString::fromLatin1(s_filters[index].fext));
1326         }
1327         
1328         QStringList filters;
1329         filters << QString("All supported files (%1)").arg(allTypes);
1330
1331         for(size_t index = 0; index < count; index++)
1332         {
1333                 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(s_filters[index].name), QString::fromLatin1(s_filters[index].fext));
1334         }
1335                 
1336         filters << QString("All files (*.*)");
1337         return filters.join(";;");
1338 }
1339
1340