OSDN Git Service

Updated changelog.
[lamexp/LameXP.git] / src / Model_FileList.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Model_FileList.h"
24
25 //Internal
26 #include "Global.h"
27
28 //MUtils
29 #include <MUtils/Global.h>
30
31 //Qt
32 #include <QFileInfo>
33 #include <QDir>
34 #include <QFile>
35 #include <QTextCodec>
36 #include <QTextStream>
37 #include <QInputDialog>
38
39 #define EXPAND(STR) QString(STR).leftJustified(96, ' ')
40 #define CHECK_HDR(STR,NAM) (!(STR).compare((NAM), Qt::CaseInsensitive))
41 #define MAKE_KEY(PATH) (QDir::fromNativeSeparators(PATH).toLower())
42
43 static inline int LOG10(int x)
44 {
45         int ret = 1;
46         while(x >= 10)
47         {
48                 ret++; x /= 10;
49         }
50         return ret;
51 }
52
53 ////////////////////////////////////////////////////////////
54 // Constructor & Destructor
55 ////////////////////////////////////////////////////////////
56
57 FileListModel::FileListModel(void)
58 :
59         m_blockUpdates(false),
60         m_fileIcon(":/icons/page_white_cd.png")
61 {
62 }
63
64 FileListModel::~FileListModel(void)
65 {
66 }
67
68 ////////////////////////////////////////////////////////////
69 // Public Functions
70 ////////////////////////////////////////////////////////////
71
72 int FileListModel::columnCount(const QModelIndex &parent) const
73 {
74         return 2;
75 }
76
77 int FileListModel::rowCount(const QModelIndex &parent) const
78 {
79         return m_fileList.count();
80 }
81
82 QVariant FileListModel::data(const QModelIndex &index, int role) const
83 {
84         if(((role == Qt::DisplayRole) || (role == Qt::ToolTipRole)) && (index.row() < m_fileList.count()) && (index.row() >= 0))
85         {
86                 switch(index.column())
87                 {
88                 case 0:
89                         return m_fileStore.value(m_fileList.at(index.row())).metaInfo().title();
90                         break;
91                 case 1:
92                         return QDir::toNativeSeparators(m_fileStore.value(m_fileList.at(index.row())).filePath());
93                         break;
94                 default:
95                         return QVariant();
96                         break;
97                 }               
98         }
99         else if((role == Qt::DecorationRole) && (index.column() == 0))
100         {
101                 return m_fileIcon;
102         }
103         else
104         {
105                 return QVariant();
106         }
107 }
108
109 QVariant FileListModel::headerData(int section, Qt::Orientation orientation, int role) const
110 {
111         if(role == Qt::DisplayRole)
112         {
113                 if(orientation == Qt::Horizontal)
114                 {
115                         switch(section)
116                         {
117                         case 0:
118                                 return QVariant(tr("Title"));
119                                 break;
120                         case 1:
121                                 return QVariant(tr("Full Path"));
122                                 break;
123                         default:
124                                 return QVariant();
125                                 break;
126                         }
127                 }
128                 else
129                 {
130                         return int2str(section + 1);
131                 }
132         }
133         else
134         {
135                 return QVariant();
136         }
137 }
138
139 void FileListModel::addFile(const QString &filePath)
140 {
141         QFileInfo fileInfo(filePath);
142         const QString key = MAKE_KEY(fileInfo.canonicalFilePath()); 
143         const bool flag = (!m_blockUpdates);
144
145         if(!m_fileStore.contains(key))
146         {
147                 AudioFileModel audioFile(fileInfo.canonicalFilePath());
148                 audioFile.metaInfo().setTitle(fileInfo.baseName());
149                 if(flag) beginInsertRows(QModelIndex(), m_fileList.count(), m_fileList.count());
150                 m_fileStore.insert(key, audioFile);
151                 m_fileList.append(key);
152                 if(flag) endInsertRows();
153                 emit rowAppended();
154         }
155 }
156
157 void FileListModel::addFile(const AudioFileModel &file)
158 {
159         const QString key = MAKE_KEY(file.filePath()); 
160         const bool flag = (!m_blockUpdates);
161
162         if(!m_fileStore.contains(key))
163         {
164                 if(flag) beginInsertRows(QModelIndex(), m_fileList.count(), m_fileList.count());
165                 m_fileStore.insert(key, file);
166                 m_fileList.append(key);
167                 if(flag) endInsertRows();
168                 emit rowAppended();
169         }
170 }
171
172 bool FileListModel::removeFile(const QModelIndex &index)
173 {
174         if(index.row() >= 0 && index.row() < m_fileList.count())
175         {
176                 beginResetModel();
177                 m_fileStore.remove(m_fileList.at(index.row()));
178                 m_fileList.removeAt(index.row());
179                 endResetModel();
180                 return true;
181         }
182         else
183         {
184                 return false;
185         }
186 }
187
188 void FileListModel::clearFiles(void)
189 {
190         beginResetModel();
191         m_fileList.clear();
192         m_fileStore.clear();
193         endResetModel();
194 }
195
196 bool FileListModel::moveFile(const QModelIndex &index, int delta)
197 {
198         if(delta != 0 && index.row() >= 0 && index.row() < m_fileList.count() && index.row() + delta >= 0 && index.row() + delta < m_fileList.count())
199         {
200                 beginResetModel();
201                 m_fileList.move(index.row(), index.row() + delta);
202                 endResetModel();
203                 return true;
204         }
205         else
206         {
207                 return false;
208         }
209 }
210
211 const AudioFileModel &FileListModel::getFile(const QModelIndex &index)
212 {
213         if(index.row() >= 0 && index.row() < m_fileList.count())
214         {
215                 return m_fileStore[m_fileList.at(index.row())];         //return m_fileStore.value(m_fileList.at(index.row()));
216         }
217         else
218         {
219                 return m_nullAudioFile;
220         }
221 }
222
223 AudioFileModel &FileListModel::operator[] (const QModelIndex &index)
224 {
225         const QString key = m_fileList.at(index.row());
226         return m_fileStore[key];
227 }
228
229 bool FileListModel::setFile(const QModelIndex &index, const AudioFileModel &audioFile)
230 {
231         if(index.row() >= 0 && index.row() < m_fileList.count())
232         {
233                 const QString oldKey = m_fileList.at(index.row());
234                 const QString newKey = MAKE_KEY(audioFile.filePath());
235                 
236                 beginResetModel();
237                 m_fileList.replace(index.row(), newKey);
238                 m_fileStore.remove(oldKey);
239                 m_fileStore.insert(newKey, audioFile);
240                 endResetModel();
241                 return true;
242         }
243         else
244         {
245                 return false;
246         }
247 }
248
249 int FileListModel::exportToCsv(const QString &outFile)
250 {
251         const int nFiles = m_fileList.count();
252         
253         bool havePosition = false, haveTitle = false, haveArtist = false, haveAlbum = false, haveGenre = false, haveYear = false, haveComment = false;
254         
255         for(int i = 0; i < nFiles; i++)
256         {
257                 const AudioFileModel &current = m_fileStore.value(m_fileList.at(i));
258                 const AudioFileModel_MetaInfo &metaInfo = current.metaInfo();
259                 
260                 if(metaInfo.position() > 0) havePosition = true;
261                 if(!metaInfo.title().isEmpty()) haveTitle = true;
262                 if(!metaInfo.artist().isEmpty()) haveArtist = true;
263                 if(!metaInfo.album().isEmpty()) haveAlbum = true;
264                 if(!metaInfo.genre().isEmpty()) haveGenre = true;
265                 if(metaInfo.year() > 0) haveYear = true;
266                 if(!metaInfo.comment().isEmpty()) haveComment = true;
267         }
268
269         if(!(haveTitle || haveArtist || haveAlbum || haveGenre || haveYear || haveComment))
270         {
271                 return CsvError_NoTags;
272         }
273
274         QFile file(outFile);
275
276         if(!file.open(QIODevice::WriteOnly))
277         {
278                 return CsvError_FileOpen;
279         }
280         else
281         {
282                 QStringList line;
283                 
284                 if(havePosition) line << "POSITION";
285                 if(haveTitle) line << "TITLE";
286                 if(haveArtist) line << "ARTIST";
287                 if(haveAlbum) line << "ALBUM";
288                 if(haveGenre) line << "GENRE";
289                 if(haveYear) line << "YEAR";
290                 if(haveComment) line << "COMMENT";
291
292                 if(file.write(line.join(";").append("\r\n").toUtf8().prepend("\xef\xbb\xbf")) < 1)
293                 {
294                         file.close();
295                         return CsvError_FileWrite;
296                 }
297         }
298
299         for(int i = 0; i < nFiles; i++)
300         {
301                 QStringList line;
302                 const AudioFileModel &current = m_fileStore.value(m_fileList.at(i));
303                 const AudioFileModel_MetaInfo &metaInfo = current.metaInfo();
304                 
305                 if(havePosition) line << QString::number(metaInfo.position());
306                 if(haveTitle) line << metaInfo.title().trimmed();
307                 if(haveArtist) line << metaInfo.artist().trimmed();
308                 if(haveAlbum) line << metaInfo.album().trimmed();
309                 if(haveGenre) line << metaInfo.genre().trimmed();
310                 if(haveYear) line << QString::number(metaInfo.year());
311                 if(haveComment) line << metaInfo.comment().trimmed();
312
313                 if(file.write(line.replaceInStrings(";", ",").join(";").append("\r\n").toUtf8()) < 1)
314                 {
315                         file.close();
316                         return CsvError_FileWrite;
317                 }
318         }
319
320         file.close();
321         return CsvError_OK;
322 }
323
324 int FileListModel::importFromCsv(QWidget *parent, const QString &inFile)
325 {
326         QFile file(inFile);
327         if(!file.open(QIODevice::ReadOnly))
328         {
329                 return CsvError_FileOpen;
330         }
331
332         QTextCodec *codec = NULL;
333         QByteArray bomCheck = file.peek(16);
334
335         if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xef\xbb\xbf"))
336         {
337                 codec = QTextCodec::codecForName("UTF-8");
338         }
339         else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xff\xfe"))
340         {
341                 codec = QTextCodec::codecForName("UTF-16LE");
342         }
343         else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xfe\xff"))
344         {
345                 codec = QTextCodec::codecForName("UTF-16BE");
346         }
347         else
348         {
349                 const QString systemDefault = tr("(System Default)");
350
351                 QStringList codecList;
352                 codecList.append(systemDefault);
353                 codecList.append(MUtils::available_codepages());
354
355                 QInputDialog *input = new QInputDialog(parent);
356                 input->setLabelText(EXPAND(tr("Select ANSI Codepage for CSV file:")));
357                 input->setOkButtonText(tr("OK"));
358                 input->setCancelButtonText(tr("Cancel"));
359                 input->setTextEchoMode(QLineEdit::Normal);
360                 input->setComboBoxItems(codecList);
361         
362                 if(input->exec() < 1)
363                 {
364                         MUTILS_DELETE(input);
365                         return CsvError_Aborted;
366                 }
367         
368                 if(input->textValue().compare(systemDefault, Qt::CaseInsensitive))
369                 {
370                         qDebug("User-selected codec is: %s", input->textValue().toLatin1().constData());
371                         codec = QTextCodec::codecForName(input->textValue().toLatin1().constData());
372                 }
373                 else
374                 {
375                         qDebug("Going to use the system's default codec!");
376                         codec = QTextCodec::codecForName("System");
377                 }
378
379                 MUTILS_DELETE(input);
380         }
381
382         bomCheck.clear();
383
384         //----------------------//
385
386         QTextStream stream(&file);
387         stream.setAutoDetectUnicode(false);
388         stream.setCodec(codec);
389
390         QString headerLine = stream.readLine().simplified();
391
392         while(headerLine.isEmpty())
393         {
394                 if(stream.atEnd())
395                 {
396                         qWarning("The file appears to be empty!");
397                         return CsvError_FileRead;
398                 }
399                 qWarning("Skipping a blank line at beginning of CSV file!");
400                 headerLine = stream.readLine().simplified();
401         }
402
403         QStringList header = headerLine.split(";", QString::KeepEmptyParts);
404
405         const int nCols = header.count();
406         const int nFiles = m_fileList.count();
407
408         if(nCols < 1)
409         {
410                 qWarning("Header appears to be empty!");
411                 return CsvError_FileRead;
412         }
413
414         bool *ignore = new bool[nCols];
415         memset(ignore, 0, sizeof(bool) * nCols);
416
417         for(int i = 0; i < nCols; i++)
418         {
419                 if((header[i] = header[i].trimmed()).isEmpty())
420                 {
421                         ignore[i] = true;
422                 }
423         }
424
425         //----------------------//
426
427         for(int i = 0; i < nFiles; i++)
428         {
429                 if(stream.atEnd())
430                 {
431                         MUTILS_DELETE_ARRAY(ignore);
432                         return CsvError_Incomplete;
433                 }
434                 
435                 QString line = stream.readLine().simplified();
436                 
437                 if(line.isEmpty())
438                 {
439                         qWarning("Skipping a blank line in CSV file!");
440                         continue;
441                 }
442                 
443                 QStringList data = line.split(";", QString::KeepEmptyParts);
444
445                 if(data.count() < header.count())
446                 {
447                         qWarning("Skipping an incomplete line in CSV file!");
448                         continue;
449                 }
450
451                 const QString key = m_fileList[i];
452
453                 for(int j = 0; j < nCols; j++)
454                 {
455                         if(ignore[j])
456                         {
457                                 continue;
458                         }
459                         else if(CHECK_HDR(header.at(j), "POSITION"))
460                         {
461                                 bool ok = false;
462                                 unsigned int temp = data.at(j).trimmed().toUInt(&ok);
463                                 if(ok) m_fileStore[key].metaInfo().setPosition(temp);
464                         }
465                         else if(CHECK_HDR(header.at(j), "TITLE"))
466                         {
467                                 QString temp = data.at(j).trimmed();
468                                 if(!temp.isEmpty()) m_fileStore[key].metaInfo().setTitle(temp);
469                         }
470                         else if(CHECK_HDR(header.at(j), "ARTIST"))
471                         {
472                                 QString temp = data.at(j).trimmed();
473                                 if(!temp.isEmpty()) m_fileStore[key].metaInfo().setArtist(temp);
474                         }
475                         else if(CHECK_HDR(header.at(j), "ALBUM"))
476                         {
477                                 QString temp = data.at(j).trimmed();
478                                 if(!temp.isEmpty()) m_fileStore[key].metaInfo().setAlbum(temp);
479                         }
480                         else if(CHECK_HDR(header.at(j), "GENRE"))
481                         {
482                                 QString temp = data.at(j).trimmed();
483                                 if(!temp.isEmpty()) m_fileStore[key].metaInfo().setGenre(temp);
484                         }
485                         else if(CHECK_HDR(header.at(j), "YEAR"))
486                         {
487                                 bool ok = false;
488                                 unsigned int temp = data.at(j).trimmed().toUInt(&ok);
489                                 if(ok) m_fileStore[key].metaInfo().setYear(temp);
490                         }
491                         else if(CHECK_HDR(header.at(j), "COMMENT"))
492                         {
493                                 QString temp = data.at(j).trimmed();
494                                 if(!temp.isEmpty()) m_fileStore[key].metaInfo().setComment(temp);
495                         }
496                         else
497                         {
498                                 qWarning("Unkonw field '%s' will be ignored!", MUTILS_UTF8(header.at(j)));
499                                 ignore[j] = true;
500                                 
501                                 if(!checkArray(ignore, false, nCols))
502                                 {
503                                         qWarning("No known fields left, aborting!");
504                                         return CsvError_NoTags;
505                                 }
506                         }
507                 }
508         }
509
510         //----------------------//
511
512         MUTILS_DELETE_ARRAY(ignore);
513         return CsvError_OK;
514 }
515
516 bool FileListModel::checkArray(const bool *a, const bool val, size_t len)
517 {
518         for(size_t i = 0; i < len; i++)
519         {
520                 if(a[i] == val) return true;
521         }
522
523         return false;
524 }
525
526 QString FileListModel::int2str(const int &value) const
527 {
528         if(m_fileList.count() < 10)
529         {
530                 return QString().sprintf("%d", value);
531         }
532         else
533         {
534                 const QString format = QString().sprintf("%%0%dd", LOG10(m_fileList.count()));
535                 return QString().sprintf(format.toLatin1().constData(), value);
536         }
537 }