1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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.
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.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_CueImport.h"
25 #include "../tmp/UIC_CueSheetImport.h"
29 #include "Model_CueSheet.h"
30 #include "Model_AudioFile.h"
31 #include "Model_FileList.h"
32 #include "Dialog_WorkingBanner.h"
33 #include "Thread_FileAnalyzer.h"
34 #include "Thread_CueSplitter.h"
35 #include "Registry_Decoder.h"
36 #include "LockedFile.h"
40 #include <QMessageBox>
42 #include <QFileDialog>
43 #include <QProgressDialog>
46 #include <QInputDialog>
48 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
49 #define EXPAND(STR) QString(STR).leftJustified(96, ' ')
51 ////////////////////////////////////////////////////////////
52 // Constructor & Destructor
53 ////////////////////////////////////////////////////////////
55 CueImportDialog::CueImportDialog(QWidget
*parent
, FileListModel
*fileList
, const QString
&cueFile
, const SettingsModel
*settings
)
58 ui(new Ui::CueSheetImport
),
60 m_cueFileName(cueFile
),
63 //Init the dialog, from the .ui file
67 setMinimumSize(this->size());
68 setMaximumHeight(this->height());
71 m_model
= new CueSheetModel();
72 connect(m_model
, SIGNAL(modelReset()), this, SLOT(modelChanged()));
75 ui
->treeView
->setModel(m_model
);
76 ui
->treeView
->header()->setStretchLastSection(false);
77 ui
->treeView
->header()->setResizeMode(QHeaderView::ResizeToContents
);
78 ui
->treeView
->header()->setResizeMode(1, QHeaderView::Stretch
);
79 ui
->treeView
->header()->setMovable(false);
80 ui
->treeView
->setItemsExpandable(false);
82 //Enable up/down button
83 connect(ui
->imprtButton
, SIGNAL(clicked()), this, SLOT(importButtonClicked()));
84 connect(ui
->browseButton
, SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
85 connect(ui
->loadOtherButton
, SIGNAL(clicked()), this, SLOT(loadOtherButtonClicked()));
88 ui
->labelHeaderText
->setText(QString("<b>%1</b><br>%2").arg(tr("Import Cue Sheet"), tr("The following Cue Sheet will be split and imported into LameXP.")));
91 CueImportDialog::~CueImportDialog(void)
93 LAMEXP_DELETE(m_model
);
97 ////////////////////////////////////////////////////////////
99 ////////////////////////////////////////////////////////////
101 void CueImportDialog::showEvent(QShowEvent
*event
)
103 QDialog::showEvent(event
);
107 ////////////////////////////////////////////////////////////
109 ////////////////////////////////////////////////////////////
111 int CueImportDialog::exec(void)
113 WorkingBanner
*progress
= new WorkingBanner(dynamic_cast<QWidget
*>(parent()));
114 progress
->show(tr("Loading Cue Sheet file, please be patient..."));
116 QFileInfo
cueFileInfo(m_cueFileName
);
117 if(!cueFileInfo
.exists() || !cueFileInfo
.isFile())
119 QString text
= QString("<nobr>%1</nobr><br><nobr>%2</nobr><br><br><nobr>%3</nobr>").arg(tr("Failed to load the Cue Sheet file:"), QDir::toNativeSeparators(m_cueFileName
), tr("The specified file could not be found!")).replace("-", "−");
120 QMessageBox::warning(progress
, tr("Cue Sheet Error"), text
);
122 LAMEXP_DELETE(progress
);
123 return CueSheetModel::ErrorIOFailure
;
126 //----------------------//
128 QTextCodec
*codec
= NULL
;
130 QFile
cueFile(cueFileInfo
.canonicalFilePath());
131 cueFile
.open(QIODevice::ReadOnly
);
132 QByteArray bomCheck
= cueFile
.isOpen() ? cueFile
.peek(16) : QByteArray();
134 if((!bomCheck
.isEmpty()) && bomCheck
.startsWith("\xef\xbb\xbf"))
136 codec
= QTextCodec::codecForName("UTF-8");
138 else if((!bomCheck
.isEmpty()) && bomCheck
.startsWith("\xff\xfe"))
140 codec
= QTextCodec::codecForName("UTF-16LE");
142 else if((!bomCheck
.isEmpty()) && bomCheck
.startsWith("\xfe\xff"))
144 codec
= QTextCodec::codecForName("UTF-16BE");
148 const QString systemDefault
= tr("(System Default)");
150 QStringList codecList
;
151 codecList
.append(systemDefault
);
152 codecList
.append(lamexp_available_codepages());
154 QInputDialog
*input
= new QInputDialog(progress
);
155 input
->setLabelText(EXPAND(tr("Select ANSI Codepage for Cue Sheet file:")));
156 input
->setOkButtonText(tr("OK"));
157 input
->setCancelButtonText(tr("Cancel"));
158 input
->setTextEchoMode(QLineEdit::Normal
);
159 input
->setComboBoxItems(codecList
);
161 if(input
->exec() < 1)
164 LAMEXP_DELETE(input
);
165 LAMEXP_DELETE(progress
);
169 if(input
->textValue().compare(systemDefault
, Qt::CaseInsensitive
))
171 qDebug("User-selected codec is: %s", input
->textValue().toLatin1().constData());
172 codec
= QTextCodec::codecForName(input
->textValue().toLatin1().constData());
176 qDebug("Going to use the system's default codec!");
177 codec
= QTextCodec::codecForName("System");
180 LAMEXP_DELETE(input
);
185 //----------------------//
187 QString baseName
= cueFileInfo
.completeBaseName().simplified();
188 while(baseName
.endsWith(".") || baseName
.endsWith(" ")) baseName
.chop(1);
189 if(baseName
.isEmpty()) baseName
= tr("New Folder");
191 m_outputDir
= QString("%1/%2").arg(cueFileInfo
.canonicalPath(), baseName
);
192 for(int n
= 2; QDir(m_outputDir
).exists() || QFileInfo(m_outputDir
).exists(); n
++)
194 m_outputDir
= QString("%1/%2 (%3)").arg(cueFileInfo
.canonicalPath(), baseName
, QString::number(n
));
197 setWindowTitle(QString("%1: %2").arg(windowTitle().split(":", QString::SkipEmptyParts
).first().trimmed(), cueFileInfo
.fileName()));
199 int iResult
= m_model
->loadCueSheet(m_cueFileName
, QApplication::instance(), codec
);
200 if(iResult
!= CueSheetModel::ErrorSuccess
)
202 QString errorMsg
= tr("An unknown error has occured!");
206 case CueSheetModel::ErrorIOFailure
:
207 errorMsg
= tr("The file could not be opened for reading. Make sure you have the required rights!");
209 case CueSheetModel::ErrorBadFile
:
210 errorMsg
= tr("The provided file does not look like a valid Cue Sheet disc image file!");
212 case CueSheetModel::ErrorUnsupported
:
213 errorMsg
= QString("%1<br>%2").arg(tr("Could not find any supported audio track in the Cue Sheet image!"), tr("Note that LameXP can not handle \"binary\" Cue Sheet images."));
215 case CueSheetModel::ErrorInconsistent
:
216 errorMsg
= tr("The selected Cue Sheet file contains inconsistent information. Take care!");
220 QString text
= QString("<nobr>%1</nobr><br><nobr>%2</nobr><br><br><nobr>%3</nobr>").arg(tr("Failed to load the Cue Sheet file:"), QDir::toNativeSeparators(m_cueFileName
), errorMsg
).replace("-", "−");
221 QMessageBox::warning(progress
, tr("Cue Sheet Error"), text
);
223 LAMEXP_DELETE(progress
);
228 LAMEXP_DELETE(progress
);
229 return QDialog::exec();
232 void CueImportDialog::modelChanged(void)
234 ui
->treeView
->expandAll();
235 ui
->editOutputDir
->setText(QDir::toNativeSeparators(m_outputDir
));
236 ui
->labelArtist
->setText(m_model
->getAlbumPerformer().isEmpty() ? tr("Unknown Artist") : m_model
->getAlbumPerformer());
237 ui
->labelAlbum
->setText(m_model
->getAlbumTitle().isEmpty() ? tr("Unknown Album") : m_model
->getAlbumTitle());
240 void CueImportDialog::browseButtonClicked(void)
242 QString newOutDir
, currentDir
= m_outputDir
;
244 while(QDir(currentDir
).exists())
246 int pos
= qMax(currentDir
.lastIndexOf(QChar('\\')), currentDir
.lastIndexOf(QChar('/')));
247 if(pos
> 0) currentDir
.left(pos
- 1); else break;
250 if(lamexp_themes_enabled())
252 newOutDir
= QFileDialog::getExistingDirectory(this, tr("Choose Output Directory"), currentDir
);
256 QFileDialog
dialog(this, tr("Choose Output Directory"));
257 dialog
.setFileMode(QFileDialog::DirectoryOnly
);
258 dialog
.setDirectory(currentDir
);
261 newOutDir
= dialog
.selectedFiles().first();
265 if(!newOutDir
.isEmpty())
267 m_outputDir
= newOutDir
;
272 void CueImportDialog::importButtonClicked(void)
274 static const unsigned __int64 oneGigabyte
= 1073741824ui
64;
275 static const unsigned __int64 minimumFreeDiskspaceMultiplier
= 2ui
64;
276 static const char *writeTestBuffer
= "LAMEXP_WRITE_TEST";
278 QDir
outputDir(m_outputDir
);
279 outputDir
.mkpath(".");
280 if(!(outputDir
.exists() && outputDir
.isReadable()))
282 QMessageBox::warning(this, tr("LameXP"), QString("<nobr>%2</nobr>").arg(tr("Error: The selected output directory could not be created!")));
286 QFile
writeTest(QString("%1/~%2.txt").arg(m_outputDir
, lamexp_rand_str()));
287 if(!(writeTest
.open(QIODevice::ReadWrite
) && (writeTest
.write(writeTestBuffer
) == strlen(writeTestBuffer
))))
289 QMessageBox::warning(this, tr("LameXP"), QString("<nobr>%2</nobr>").arg(tr("Error: The selected output directory is not writable!")));
299 unsigned __int64 currentFreeDiskspace
= lamexp_free_diskspace(m_outputDir
, &ok
);
301 if(ok
&& (currentFreeDiskspace
< (oneGigabyte
* minimumFreeDiskspaceMultiplier
)))
303 QMessageBox::warning(this, tr("Low Diskspace Warning"), QString("<nobr>%1</nobr><br><nobr>%2</nobr>").arg(tr("There are less than %1 GB of free diskspace available in the selected output directory.").arg(QString::number(minimumFreeDiskspaceMultiplier
)), tr("It is highly recommend to free up more diskspace before proceeding with the import!")));
311 void CueImportDialog::loadOtherButtonClicked(void)
316 void CueImportDialog::analyzedFile(const AudioFileModel
&file
)
318 qDebug("Received result: <%s> <%s/%s>", file
.filePath().toLatin1().constData(), file
.formatContainerType().toLatin1().constData(), file
.formatAudioType().toLatin1().constData());
322 ////////////////////////////////////////////////////////////
324 ////////////////////////////////////////////////////////////
326 void CueImportDialog::importCueSheet(void)
330 //Fetch all files that are referenced in the Cue Sheet and lock them
331 int nFiles
= m_model
->getFileCount();
332 for(int i
= 0; i
< nFiles
; i
++)
334 QString temp
= m_model
->getFileName(i
);
337 m_locks
<< new LockedFile(temp
);
341 qWarning("Failed to lock file: %s", err
);
347 //Analyze all source files first
348 if(analyzeFiles(files
))
350 //Now split files according to Cue Sheet
355 while(!m_locks
.isEmpty())
357 delete m_locks
.takeFirst();
361 bool CueImportDialog::analyzeFiles(QStringList
&files
)
364 bool bSuccess
= true;
366 WorkingBanner
*progress
= new WorkingBanner(this);
367 FileAnalyzer
*analyzer
= new FileAnalyzer(files
);
369 connect(analyzer
, SIGNAL(fileSelected(QString
)), progress
, SLOT(setText(QString
)), Qt::QueuedConnection
);
370 connect(analyzer
, SIGNAL(fileAnalyzed(AudioFileModel
)), this, SLOT(analyzedFile(AudioFileModel
)), Qt::QueuedConnection
);
371 connect(progress
, SIGNAL(userAbort()), analyzer
, SLOT(abortProcess()), Qt::DirectConnection
);
373 progress
->show(tr("Analyzing file(s), please wait..."), analyzer
);
376 if(analyzer
->filesAccepted() < static_cast<unsigned int>(files
.count()))
378 if(QMessageBox::warning(this, tr("Analysis Failed"), tr("Warning: The format of some of the input files could not be determined!"), tr("Continue Anyway"), tr("Abort")) == 1)
384 LAMEXP_DELETE(progress
);
385 LAMEXP_DELETE(analyzer
);
390 void CueImportDialog::splitFiles(void)
392 QString baseName
= QFileInfo(m_cueFileName
).completeBaseName().replace(".", " ").simplified();
394 WorkingBanner
*progress
= new WorkingBanner(this);
395 CueSplitter
*splitter
= new CueSplitter(m_outputDir
, baseName
, m_model
, m_fileInfo
);
397 connect(splitter
, SIGNAL(fileSelected(QString
)), progress
, SLOT(setText(QString
)), Qt::QueuedConnection
);
398 connect(splitter
, SIGNAL(fileSplit(AudioFileModel
)), m_fileList
, SLOT(addFile(AudioFileModel
)), Qt::QueuedConnection
);
399 connect(splitter
, SIGNAL(progressValChanged(unsigned int)), progress
, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection
);
400 connect(splitter
, SIGNAL(progressMaxChanged(unsigned int)), progress
, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection
);
401 connect(progress
, SIGNAL(userAbort()), splitter
, SLOT(abortProcess()), Qt::DirectConnection
);
403 DecoderRegistry::configureDecoders(m_settings
);
405 progress
->show(tr("Splitting file(s), please wait..."), splitter
);
408 if(splitter
->getAborted())
410 QMessageBox::warning(this, tr("Cue Sheet Error"), tr("Process was aborted by the user after %n track(s)!", "", splitter
->getTracksSuccess()));
412 else if(!splitter
->getSuccess())
414 QMessageBox::warning(this, tr("Cue Sheet Error"), tr("An unexpected error has occured while splitting the Cue Sheet!"));
418 QString text
= QString("<nobr>%1 %2</nobr>").arg(tr("Imported %n track(s) from the Cue Sheet.", "", splitter
->getTracksSuccess()), tr("Skipped %n track(s).", "", splitter
->getTracksSkipped()));
419 QMessageBox::information(this, tr("Cue Sheet Completed"), text
);
422 LAMEXP_DELETE(splitter
);
423 LAMEXP_DELETE(progress
);