filelist.cpp 32.4 KB
Newer Older
Urs Fleisch's avatar
Urs Fleisch committed
1
2
3
4
5
6
7
/**
 * \file filelist.cpp
 * List of files to operate on.
 *
 * \b Project: Kid3
 * \author Urs Fleisch
 * \date 9 Jan 2003
8
 *
Urs Fleisch's avatar
Urs Fleisch committed
9
 * Copyright (C) 2003-2008  Urs Fleisch
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 *
 * This file is part of Kid3.
 *
 * Kid3 is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Kid3 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Urs Fleisch's avatar
Urs Fleisch committed
25
26
 */

27
#include "config.h"
Urs Fleisch's avatar
Urs Fleisch committed
28
29
30
#include <qfileinfo.h>
#include <qdir.h>
#include <qstringlist.h>
31
#include <qmessagebox.h>
32
33
34
#include <qinputdialog.h>
#include <qurl.h>
#include <qregexp.h>
Urs Fleisch's avatar
Urs Fleisch committed
35
#if QT_VERSION >= 0x040000
36
37
#include <QMenu>
#include <QHeaderView>
38
39
40
#if QT_VERSION >= 0x040300
#include <QDirIterator>
#endif
Urs Fleisch's avatar
Urs Fleisch committed
41
42
#else
#include <qpopupmenu.h>
43
#include <qheader.h>
Urs Fleisch's avatar
Urs Fleisch committed
44
#endif
45
#ifdef CONFIG_USE_KDE
46
#include <kdeversion.h>
47
48
#include <kmessagebox.h>
#endif
Urs Fleisch's avatar
Urs Fleisch committed
49

50
#include "taggedfile.h"
Urs Fleisch's avatar
Urs Fleisch committed
51
#include "filelist.h"
52
#include "filelistitem.h"
53
#include "kid3.h"
54
#include "externalprocess.h"
55
#include "qtcompatmac.h"
56
57
58
#ifdef HAVE_ID3LIB
#include "mp3file.h"
#endif
59
#ifdef HAVE_VORBIS
60
#include "oggfile.hpp"
61
62
#endif
#ifdef HAVE_FLAC
63
#include "flacfile.hpp"
64
#endif
65
66
67
68
#ifdef HAVE_TAGLIB
#include "taglibfile.h"
#endif

Urs Fleisch's avatar
Urs Fleisch committed
69
/** Only defined for generation of KDE3 translation files */
Urs Fleisch's avatar
Urs Fleisch committed
70
#define FOR_KDE3_PO_1 I18N_NOOP("Do you really want to delete these %1 items?")
Urs Fleisch's avatar
Urs Fleisch committed
71
/** Only defined for generation of KDE3 translation files */
Urs Fleisch's avatar
Urs Fleisch committed
72
73
#define FOR_KDE3_PO_2 I18N_NOOP("Error while deleting these %1 items:")

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/**
 * Replaces context command format codes in a string.
 */
class CommandFormatReplacer : public FrameFormatReplacer {
public:
	/**
	 * Constructor.
	 *
	 * @param frames frame collection
	 * @param str    string with format codes
	 * @param files  file list
	 * @param isDir  true if directory
	 */
	explicit CommandFormatReplacer(
		const FrameCollection& frames, const QString& str,
		const QStringList& files, bool isDir);

	/**
	 * Destructor.
	 */
	virtual ~CommandFormatReplacer();

	/**
	 * Get help text for supported format codes.
	 *
	 * @param onlyRows if true only the tr elements are returned,
	 *                 not the surrounding table
	 *
	 * @return help text.
	 */
	static QString getToolTip(bool onlyRows = false);

protected:
	/**
	 * Replace a format code (one character %c or multiple characters %{chars}).
	 * Supported format fields:
	 * Those supported by FrameFormatReplacer::getReplacement()
	 * %f %{file} filename
	 * %d %{directory} directory name
	 * %b %{browser} the web browser set in the configuration
	 *
	 * @param code format code
	 *
	 * @return replacement string,
	 *         QString::null if code not found.
	 */
	virtual QString getReplacement(const QString& code) const;

private:
	const QStringList& m_files;
	const bool m_isDir;
};


/**
 * Constructor.
 *
 * @param frames frame collection
 * @param str    string with format codes
 * @param files  file list
 * @param isDir  true if directory
 */
CommandFormatReplacer::CommandFormatReplacer(
	const FrameCollection& frames, const QString& str,
	const QStringList& files, bool isDir) :
	FrameFormatReplacer(frames, str), m_files(files), m_isDir(isDir) {}

/**
 * Destructor.
 */
CommandFormatReplacer::~CommandFormatReplacer() {}

/**
 * Replace a format code (one character %c or multiple characters %{chars}).
 * Supported format fields:
 * Those supported by FrameFormatReplacer::getReplacement()
 * %f %{file} filename
 * %d %{directory} directory name
 * %b %{browser} the web browser set in the configuration
 *
 * @param code format code
 *
 * @return replacement string,
 *         QString::null if code not found.
 */
QString CommandFormatReplacer::getReplacement(const QString& code) const
{
	QString result = FrameFormatReplacer::getReplacement(code);
	if (result.isNull()) {
		QString name;

		if (code.length() == 1) {
			static const struct {
				char shortCode;
				const char* longCode;
			} shortToLong[] = {
				{ 'f', "file" },
				{ 'd', "directory" },
				{ 'b', "browser" }
			};
#if QT_VERSION >= 0x040000
			const char c = code[0].toLatin1();
#else
			const char c = code[0].latin1();
#endif
			for (unsigned i = 0; i < sizeof(shortToLong) / sizeof(shortToLong[0]); ++i) {
				if (shortToLong[i].shortCode == c) {
					name = shortToLong[i].longCode;
					break;
				}
			}
		} else if (code.length() > 1) {
			name = code;
		}

		if (!name.isNull()) {
			if (name == "file") {
				result = m_files.front();
			} else if (name == "directory") {
				result = m_files.front();
				if (!m_isDir) {
					int sepPos = result.QCM_lastIndexOf('/');
					if (sepPos < 0) {
						sepPos = result.QCM_lastIndexOf(QDir::separator());
					}
					if (sepPos >= 0) {
						result.truncate(sepPos);
					}
				}
			} else if (name == "browser") {
				result = Kid3App::s_miscCfg.m_browser;
			} else if (name == "url") {
				if (!m_files.empty()) {
					QUrl url;
					url.QCM_setScheme("file");
					url.QCM_setPath(m_files.front());
					result = url.toString(
#if QT_VERSION < 0x040000
						true
#endif
						);
				}
			}
		}
	}

	return result;
}

/**
 * Get help text for supported format codes.
 *
 * @param onlyRows if true only the tr elements are returned,
 *                 not the surrounding table
 *
 * @return help text.
 */
QString CommandFormatReplacer::getToolTip(bool onlyRows)
{
	QString str;
	if (!onlyRows) str += "<table>\n";
	str += FrameFormatReplacer::getToolTip(true);

	str += "<tr><td>%f</td><td>%{file}</td><td>";
	str += QCM_translate("Filename");
	str += "</td></tr>\n";

	str += "<tr><td>%F</td><td>%{files}</td><td>";
	str += QCM_translate(I18N_NOOP("Filenames"));
	str += "</td></tr>\n";

	str += "<tr><td>%uf</td><td>%{url}</td><td>";
	str += QCM_translate("URL");
	str += "</td></tr>\n";

	str += "<tr><td>%uF</td><td>%{urls}</td><td>";
	str += QCM_translate(I18N_NOOP("URLs"));
	str += "</td></tr>\n";

	str += "<tr><td>%d</td><td>%{directory}</td><td>";
	str += QCM_translate(I18N_NOOP("Directory name"));
	str += "</td></tr>\n";

	str += "<tr><td>%b</td><td>%{browser}</td><td>";
	str += QCM_translate("Browser");
	str += "</td></tr>\n";

	str += "<tr><td>%ua...</td><td>%u{artist}...</td><td>";
	str += QCM_translate(I18N_NOOP("Encode as URL"));
	str += "</td></tr>\n";

	if (!onlyRows) str += "</table>\n";
	return str;
}


270
271
/**
 * Constructor.
272
 * @param parent parent widget
273
 */
274
275
276
277
278
279
280
FileList::FileList(QWidget* parent) :
#if QT_VERSION >= 0x040000
	QTreeWidget(parent), m_iterator(0),
#else
	QListView(parent),
#endif
	m_currentItemInDir(0), m_process(0)
281
{
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#if QT_VERSION >= 0x040000
	setSelectionMode(ExtendedSelection);
	setSortingEnabled(false);
	setColumnCount(1);
	setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
			this, SLOT(customContextMenu(const QPoint&)));
	connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)),
					this, SLOT(expandItem(QTreeWidgetItem*)));
	connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)),
					this, SLOT(collapseItem(QTreeWidgetItem*)));
	connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
					this, SLOT(expandOrCollapseEmptyItem(QTreeWidgetItem*)));
#else
296
297
298
299
300
	setSelectionMode(Extended);
	setSorting(-1);
	addColumn("");
	connect(this, SIGNAL(contextMenuRequested(QListViewItem*, const QPoint&, int)),
			this, SLOT(contextMenu(QListViewItem*, const QPoint&)));
Urs Fleisch's avatar
Urs Fleisch committed
301
#endif
302
	header()->hide();
303
304
305
306
307
}

/**
 * Destructor.
 */
308
309
FileList::~FileList()
{
310
	delete m_process;
311
312
313
#if QT_VERSION >= 0x040000
	delete m_iterator;
#endif
314
}
Urs Fleisch's avatar
Urs Fleisch committed
315

316
317
318
319
320
321
/**
 * Returns the recommended size for the widget.
 * @return recommended size.
 */
QSize FileList::sizeHint() const
{
322
323
324
325
326
327
328
	return QSize(fontMetrics().maxWidth() * 25,
#if QT_VERSION >= 0x040000
							 QTreeWidget::sizeHint().height()
#else
							 QListView::sizeHint().height()
#endif
		);
329
330
331
332
333
334
335
336
337
}

/**
 * Get the next item in the filelist which contains a file.
 *
 * @param it list view iterator
 *
 * @return next item with file.
 */
338
339
340
341
342
343
344
static FileListItem* getNextItemWithFile(
#if QT_VERSION >= 0x040000
	QTreeWidgetItemIterator& it
#else
	QListViewItemIterator& it
#endif
	)
345
{
346
347
348
349
350
351
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* lvItem;
#else
	QListViewItem* lvItem;
#endif
	while ((lvItem = *it) != 0) {
352
353
354
355
356
357
358
		FileListItem* flItem = dynamic_cast<FileListItem*>(lvItem);
		if (flItem && flItem->getFile()) {
			return flItem;
		}
		++it;
	}
	return 0;
359
360
}

Urs Fleisch's avatar
Urs Fleisch committed
361
362
363
364
365
/**
 * Get the first item in the filelist.
 *
 * @return first file.
 */
366
FileListItem* FileList::first()
Urs Fleisch's avatar
Urs Fleisch committed
367
{
368
369
370
371
372
373
374
375
376
377
378
#if QT_VERSION >= 0x040000
	delete m_iterator;
	if (topLevelItemCount() > 0) {
		m_iterator = new QTreeWidgetItemIterator(this);
		return getNextItemWithFile(*m_iterator);
	} else {
		m_iterator = 0;
		return 0;
	}
#else
	m_iterator = QListViewItemIterator(this);
379
	return getNextItemWithFile(m_iterator);
380
#endif
Urs Fleisch's avatar
Urs Fleisch committed
381
382
383
384
385
386
387
}

/**
 * Get the next item in the filelist.
 *
 * @return next file.
 */
388
FileListItem* FileList::next()
Urs Fleisch's avatar
Urs Fleisch committed
389
{
390
391
392
393
394
395
396
#if QT_VERSION >= 0x040000
	if (m_iterator && **m_iterator) {
		++*m_iterator;
		return getNextItemWithFile(*m_iterator);
	}
#else
	if (*m_iterator) {
397
398
399
		++m_iterator;
		return getNextItemWithFile(m_iterator);
	}
400
#endif
401
	return 0;
Urs Fleisch's avatar
Urs Fleisch committed
402
403
}

404
405
406
407
408
409
410
411
412
413
/**
 * Get the current item in the filelist.
 *
 * @return current file.
 */
FileListItem* FileList::current()
{
	return dynamic_cast<FileListItem*>(currentItem());
}

Urs Fleisch's avatar
Urs Fleisch committed
414
/**
415
 * Get the next item in the current directory which contains a file.
Urs Fleisch's avatar
Urs Fleisch committed
416
 *
417
418
419
 * @param lvItem list view item
 *
 * @return next item with file.
Urs Fleisch's avatar
Urs Fleisch committed
420
 */
421
422
423
424
425
426
427
static FileListItem* getNextItemWithFileInDir(
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* lvItem
#else
	QListViewItem* lvItem
#endif
	)
428
429
430
431
432
433
{
	while (lvItem) {
		FileListItem* flItem = dynamic_cast<FileListItem*>(lvItem);
		if (flItem && flItem->getFile()) {
			return flItem;
		}
434
435
436
437
438
439
440
441
#if QT_VERSION >= 0x040000
		QTreeWidgetItem* parent = lvItem->parent();
		QTreeWidgetItemIterator it(lvItem);
		lvItem = *(++it);
		if (lvItem && lvItem->parent() != parent) {
			lvItem = 0;
		}
#else
442
		lvItem = lvItem->nextSibling();
443
#endif
444
445
446
	}
	return 0;
}
Urs Fleisch's avatar
Urs Fleisch committed
447

448
449
450
451
452
453
/**
 * Get the first item in the the current directory.
 *
 * @return first file.
 */
FileListItem* FileList::firstInDir()
Urs Fleisch's avatar
Urs Fleisch committed
454
{
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#if QT_VERSION >= 0x040000
	// try to get the currently selected directory
	if (topLevelItemCount() <= 0) {
		m_currentItemInDir = 0;
		return 0;
	}
	QTreeWidgetItemIterator it(this, QTreeWidgetItemIterator::Selected);
	FileListItem* item = dynamic_cast<FileListItem*>(*it);
	if (item &&
		 (item->getDirInfo() ||
			(item->getFile() &&
			 (item = dynamic_cast<FileListItem*>(item->parent())) != 0))) {
		m_currentItemInDir =
			getNextItemWithFileInDir(item->child(0));
	} else {
		// if not found, get the first child of the list view
		m_currentItemInDir =
			getNextItemWithFileInDir(topLevelItem(0));
	}

	// if still not found, get the first file in the list view
	if (!m_currentItemInDir) {
		it = QTreeWidgetItemIterator(this);
		m_currentItemInDir = getNextItemWithFile(it);
	}

	return m_currentItemInDir;
#else
483
	// try to get the currently selected directory
484
485
	QListViewItemIterator it(this, QListViewItemIterator::Selected);
	FileListItem* item = dynamic_cast<FileListItem*>(*it);
486
487
488
489
490
491
492
493
494
495
496
497
498
499
	if (item &&
		 (item->getDirInfo() ||
			(item->getFile() &&
			 (item = dynamic_cast<FileListItem*>(item->parent())) != 0))) {
		m_currentItemInDir =
			getNextItemWithFileInDir(item->firstChild());
	} else {
		// if not found, get the first child of the list view
		m_currentItemInDir =
			getNextItemWithFileInDir(firstChild());
	}

	// if still not found, get the first file in the list view
	if (!m_currentItemInDir) {
500
		it = QListViewItemIterator(this);
501
502
503
504
		m_currentItemInDir = getNextItemWithFile(it);
	}

	return m_currentItemInDir;
505
#endif
506
507
508
509
510
511
512
513
514
515
}

/**
 * Get the next item in the current directory.
 *
 * @return next file.
 */
FileListItem* FileList::nextInDir()
{
	if (m_currentItemInDir) {
516
517
518
519
520
521
522
523
524
#if QT_VERSION >= 0x040000
		QTreeWidgetItem* parent = m_currentItemInDir->parent();
		QTreeWidgetItemIterator it(m_currentItemInDir);
		QTreeWidgetItem* nextSibling = *(++it);
		if (nextSibling && nextSibling->parent() != parent) {
			nextSibling = 0;
		}
		m_currentItemInDir = getNextItemWithFileInDir(nextSibling);
#else
525
526
		m_currentItemInDir =
			getNextItemWithFileInDir(m_currentItemInDir->nextSibling());
527
#endif
528
529
530
531
	}
	return m_currentItemInDir;
}

Urs Fleisch's avatar
Urs Fleisch committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/**
 * Get the next item in the filelist which contains a file or a directory.
 *
 * @param it list view iterator
 *
 * @return next item with file or directory.
 */
static FileListItem* getNextItemWithFileOrDir(
#if QT_VERSION >= 0x040000
	QTreeWidgetItemIterator& it
#else
	QListViewItemIterator& it
#endif
	)
{
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* lvItem;
#else
	QListViewItem* lvItem;
#endif
	while ((lvItem = *it) != 0) {
		FileListItem* flItem = dynamic_cast<FileListItem*>(lvItem);
		if (flItem) {
			return flItem;
		}
		++it;
	}
	return 0;
}

/**
 * Get the first file or directory item in the filelist.
 *
 * @return first file.
 */
FileListItem* FileList::firstFileOrDir()
{
#if QT_VERSION >= 0x040000
	delete m_iterator;
	if (topLevelItemCount() > 0) {
		m_iterator = new QTreeWidgetItemIterator(this);
		return getNextItemWithFileOrDir(*m_iterator);
	} else {
		m_iterator = 0;
		return 0;
	}
#else
	m_iterator = QListViewItemIterator(this);
	return getNextItemWithFileOrDir(m_iterator);
#endif
}

/**
 * Get the next file or directory item in the filelist.
 *
 * @return next file.
 */
FileListItem* FileList::nextFileOrDir()
{
#if QT_VERSION >= 0x040000
	if (m_iterator && **m_iterator) {
		++*m_iterator;
		return getNextItemWithFileOrDir(*m_iterator);
	}
#else
	if (*m_iterator) {
		++m_iterator;
		return getNextItemWithFileOrDir(m_iterator);
	}
#endif
	return 0;
}

605
606
607
608
609
610
611
612
/**
 * Get the number of files selected in the filelist.
 *
 * @return number of files selected.
 */
int FileList::numFilesSelected()
{
	int numSelected = 0;
613
614
615
616
617
618
619
620
#if QT_VERSION >= 0x040000
	if (topLevelItemCount() <= 0) {
		return 0;
	}
	QTreeWidgetItemIterator it(this, QTreeWidgetItemIterator::Selected);
#else
	QListViewItemIterator it(this, QListViewItemIterator::Selected);
#endif
621
622
623
624
625
626
627
628
	FileListItem* item;
	while ((item = getNextItemWithFile(it)) != 0) {
		++numSelected;
		++it;
	}
	return numSelected;
}

629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/**
 * Select the first file.
 *
 * @return true if a file exists.
 */
bool FileList::selectFirstFile()
{
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* item = *QTreeWidgetItemIterator(this);
	if (item) {
		clearSelection();
		setCurrentItem(item);
		setItemSelected(item, true);
		return true;
	}
#else
	QListViewItem* item = firstChild();
	if (item) {
		clearSelection();
		setCurrentItem(item);
		setSelected(item, true);
		return true;
	}
#endif
	return false;
}

656
657
/**
 * Select the next file.
658
659
 *
 * @return true if a next file exists.
660
 */
661
bool FileList::selectNextFile()
662
{
663
664
665
666
667
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* item = currentItem();
	if (item && (item = *(++QTreeWidgetItemIterator(item))) != 0) {
		clearSelection();
		setCurrentItem(item);
Urs Fleisch's avatar
Urs Fleisch committed
668
		setItemSelected(item, true);
669
		return true;
670
671
672
	}
#else
	QListViewItem* item = currentItem();
673
674
675
	if (item && (item = item->itemBelow()) != 0) {
		clearSelection();
		setCurrentItem(item);
Urs Fleisch's avatar
Urs Fleisch committed
676
		setSelected(item, true);
677
		return true;
678
	}
679
#endif
680
	return false;
681
682
683
684
}

/**
 * Select the previous file.
685
686
 *
 * @return true if a previous file exists.
687
 */
688
bool FileList::selectPreviousFile()
689
{
690
691
692
693
694
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* item = currentItem();
	if (item && (item = *(--QTreeWidgetItemIterator(item))) != 0) {
		clearSelection();
		setCurrentItem(item);
Urs Fleisch's avatar
Urs Fleisch committed
695
		setItemSelected(item, true);
696
		return true;
697
698
699
	}
#else
	QListViewItem* item = currentItem();
700
701
702
	if (item && (item = item->itemAbove()) != 0) {
		clearSelection();
		setCurrentItem(item);
Urs Fleisch's avatar
Urs Fleisch committed
703
		setSelected(item, true);
704
		return true;
705
	}
706
#endif
707
	return false;
708
709
710
711
712
713
714
715
}

/**
 * Fill the filelist with the files found in the directory tree.
 *
 * @param dirInfo  information  about directory
 * @param item     parent directory item or 0 if top-level
 * @param listView parent list view if top-level, else 0
716
 * @param fileName name of file to select (optional, else empty)
717
718
 */
void FileList::readSubDirectory(DirInfo* dirInfo, FileListItem* item,
719
																FileList* listView, const QString& fileName)
720
721
722
723
724
725
{
	if (!dirInfo) return;
	QString dirname = dirInfo->getDirname();
	int numFiles = 0;
	FileListItem* last = 0;
	QDir dir(dirname);
726
#if QT_VERSION >= 0x040000
727
728
729
730
731
	const QDir::Filters dirFilters =
		QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Files;
	QStringList nameFilters(Kid3App::s_miscCfg.m_nameFilter.split(' '));
	QStringList dirContents = dir.entryList(
		nameFilters, dirFilters, QDir::DirsFirst | QDir::IgnoreCase);
732
#else
733
	QStringList dirContents = dir.entryList(QDir::Dirs) +
Urs Fleisch's avatar
Urs Fleisch committed
734
		dir.entryList(Kid3App::s_miscCfg.m_nameFilter, QDir::Files);
735
#endif
736
	for (QStringList::Iterator it = dirContents.begin();
Urs Fleisch's avatar
Urs Fleisch committed
737
			 it != dirContents.end(); ++it) {
738
739
		QString filename = dirname + QDir::separator() + *it;
		if (!QFileInfo(filename).isDir()) {
740
			TaggedFile* taggedFile = TaggedFile::createFile(dirInfo, *it);
741
742
743
744
745
746
			if (taggedFile) {
				if (item) {
					last = new FileListItem(item, last, taggedFile);
				} else if (listView) {
					last = new FileListItem(listView, last, taggedFile);
				}
747
748
749
750
751
752
753
				if (!fileName.isEmpty() && fileName == *it && last && listView) {
					listView->clearSelection();
					listView->setCurrentItem(last);
#if QT_VERSION >= 0x040000
					listView->setItemSelected(last, true);
#else
					listView->setSelected(last, true);
754
					listView->ensureItemVisible(last);
755
756
#endif
				}
757
758
759
760
761
762
763
764
765
766
767
				++numFiles;
			}
		} else {
			if (*it != "." && *it != "..") {
				if (item) {
					last = new FileListItem(item, last, 0);
				} else if (listView) {
					last = new FileListItem(listView, last, 0);
				}
				if (last) {
					last->setDirInfo(new DirInfo(filename));
768
769
770
771
772
773
#if QT_VERSION >= 0x040300
					last->setChildIndicatorPolicy(
						QDirIterator(filename, nameFilters, dirFilters).hasNext() ?
						QTreeWidgetItem::ShowIndicator :
						QTreeWidgetItem::DontShowIndicatorWhenChildless);
#endif
Urs Fleisch's avatar
Urs Fleisch committed
774
775
776
777
				}
			}
		}
	}
778
	dirInfo->setNumFiles(numFiles);
Urs Fleisch's avatar
Urs Fleisch committed
779
780
781
}

/**
782
 * Fill the filelist with the files found in a directory.
Urs Fleisch's avatar
Urs Fleisch committed
783
 *
784
785
786
 * @param name     path of directory
 * @param fileName name of file to select (optional, else empty)
 *
787
 * @return false if name is not directory path, else true.
Urs Fleisch's avatar
Urs Fleisch committed
788
 */
789
bool FileList::readDir(const QString& name, const QString& fileName)
790
791
792
793
{
	QFileInfo file(name);
	if(file.isDir()) {
		clear();
794
		m_dirInfo.setDirname(file.QCM_absoluteFilePath());
795
		readSubDirectory(&m_dirInfo, 0, this, fileName);
796
797
798
799
		return true;
	}
	return false;
}
Urs Fleisch's avatar
Urs Fleisch committed
800

801
802
803
804
805
806
/**
 * Refresh text of all files in listview and check if any file is modified.
 *
 * @return true if a file is modified.
 */
bool FileList::updateModificationState()
Urs Fleisch's avatar
Urs Fleisch committed
807
{
808
809
810
811
812
	FileListItem* item = first();
	bool modified = false;
	while (item != 0) {
		if (item->getFile()->isChanged()) {
			modified = true;
Urs Fleisch's avatar
Urs Fleisch committed
813
		}
814
		item->updateIcons();
815
		item = next();
Urs Fleisch's avatar
Urs Fleisch committed
816
	}
817
818
819
#if QT_VERSION >= 0x040000
	update();
#else
820
	triggerUpdate();
821
#endif
Urs Fleisch's avatar
Urs Fleisch committed
822
823
824
	return modified;
}

825
826
827
828
829
830
/**
 * Display a context menu with operations for selected files.
 *
 * @param item list box item
 * @param pos  position where context menu is drawn on screen
 */
831
832
833
834
835
836
837
void FileList::contextMenu(
#if QT_VERSION >= 0x040000
	QTreeWidgetItem* item,
#else
	QListViewItem* item,
#endif
	const QPoint& pos)
838
{
839
	if (item && !Kid3App::s_miscCfg.m_contextMenuCommands.empty()) {
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
#if QT_VERSION >= 0x040000
		QMenu menu(this);
		menu.addAction(i18n("&Rename"), this, SLOT(renameFile()));
		menu.addAction(i18n("&Delete"), this, SLOT(deleteFile()));
		int id = 0;
		for (MiscConfig::MenuCommandList::const_iterator
					 it = Kid3App::s_miscCfg.m_contextMenuCommands.begin();
				 it != Kid3App::s_miscCfg.m_contextMenuCommands.end();
				 ++it) {
			menu.addAction((*it).getName());
			++id;
		}
		connect(&menu, SIGNAL(triggered(QAction*)), this, SLOT(executeAction(QAction*)));
#else
		QPopupMenu menu(this);
855
856
		menu.insertItem(i18n("&Rename"), this, SLOT(renameFile()));
		menu.insertItem(i18n("&Delete"), this, SLOT(deleteFile()));
857
		int id = 0;
858
		for (MiscConfig::MenuCommandList::const_iterator
859
860
					 it = Kid3App::s_miscCfg.m_contextMenuCommands.begin();
				 it != Kid3App::s_miscCfg.m_contextMenuCommands.end();
861
				 ++it) {
862
863
			menu.insertItem((*it).getName(), this, SLOT(executeContextCommand(int)), 0, id);
			++id;
864
		}
865
#endif
866
867
868
869
870
		menu.setMouseTracking(true);
		menu.exec(pos);
	}
}

871
872
873
/**
 * Format a string list from the selected files.
 * Supported format fields:
874
 * Those supported by FrameFormatReplacer::getReplacement(),
875
 * when prefixed with u, encoded as URL
876
877
 * %f filename
 * %F list of files
878
879
 * %uf URL of single file
 * %uF list of URLs
880
 * %d directory name
881
 * %b the web browser set in the configuration
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
 *
 * @todo %f and %F are full paths, which is inconsistent with the
 * export format strings but compatible with .desktop files.
 * %d is duration in export format.
 * The export codes should be changed.
 *
 * @param format format specification
 *
 * @return formatted string list.
 */
QStringList FileList::formatStringList(const QStringList& format)
{
	QStringList files;
	FileListItem* firstSelectedItem = 0;
	FileListItem* item = first();
	while (item != 0) {
		if (item->isInSelection()) {
			if (!firstSelectedItem) {
				firstSelectedItem = item;
			}
			files.push_back(item->getFile()->getAbsFilename());
		}
		item = next();
	}

	const DirInfo* dirInfo = 0;
	if (files.empty() &&
			(item = dynamic_cast<FileListItem*>(currentItem())) != 0 &&
			(dirInfo = item->getDirInfo()) != 0) {
		files.push_back(dirInfo->getDirname());
		firstSelectedItem = firstInDir();
	}

915
	FrameCollection frames;
916
917
918
919
	QStringList fmt;
	for (QStringList::const_iterator it = format.begin();
			 it != format.end();
			 ++it) {
920
		if ((*it).QCM_indexOf('%') == -1) {
921
922
			fmt.push_back(*it);
		} else {
923
			if (*it == "%F" || *it == "%{files}") {
924
925
				// list of files
				fmt += files;
926
			} else if (*it == "%uF" || *it == "%{urls}") {
927
				// list of URLs or URL
928
				QUrl url;
929
				url.QCM_setScheme("file");
930
931
932
				for (QStringList::const_iterator fit = files.begin();
						 fit != files.end();
						 ++fit) {
933
934
					url.QCM_setPath(*fit);
					fmt.push_back(url.toString());
935
936
937
938
				}
			} else {
				if (firstSelectedItem) {
					// use merged tags 1 and 2 to format string
939
940
941
942
					FrameCollection frames1;
					firstSelectedItem->getFile()->getAllFramesV1(frames1);
					firstSelectedItem->getFile()->getAllFramesV2(frames);
					frames.merge(frames1);
943
				}
944
945
946
947
948
				QString str(*it);
				str.replace("%uf", "%{url}");
				CommandFormatReplacer cfr(frames, str, files, dirInfo != 0);
				cfr.replacePercentCodes(FrameFormatReplacer::FSF_SupportUrlEncode);
				fmt.push_back(cfr.getString());
949
950
951
952
953
954
			}
		}
	}
	return fmt;
}

955
956
957
/**
 * Get help text for format codes supported by formatStringList().
 *
Urs Fleisch's avatar
Urs Fleisch committed
958
959
 * @param onlyRows if true only the tr elements are returned,
 *                 not the surrounding table
960
961
962
963
964
 *
 * @return help text.
 */
QString FileList::getFormatToolTip(bool onlyRows)
{
965
	return CommandFormatReplacer::getToolTip(onlyRows);
966
967
}

968
969
970
971
972
973
974
/**
 * Execute a context menu command.
 *
 * @param id command ID
 */
void FileList::executeContextCommand(int id)
{
975
	if (id < static_cast<int>(Kid3App::s_miscCfg.m_contextMenuCommands.size())) {
976
		QStringList args;
977
978
979
		const MiscConfig::MenuCommand& menuCmd = Kid3App::s_miscCfg.m_contextMenuCommands[id];
		QString cmd = menuCmd.getCommand();

980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
		int len = cmd.length();
		int begin;
		int end = 0;
		while (end < len) {
			begin = end;
			while (begin < len && cmd[begin] == ' ') ++begin;
			if (begin >= len) break;
			if (cmd[begin] == '"') {
				++begin;
				QString str;
				while (begin < len) {
					if (cmd[begin] == '\\' && begin + 1 < len &&
							(cmd[begin + 1] == '\\' ||
							 cmd[begin + 1] == '"')) {
						++begin;
					} else if (cmd[begin] == '"') {
						break;
					}
					str += cmd[begin];
					++begin;
				}
				args.push_back(str);
				end = begin;
			} else {
1004
				end = cmd.QCM_indexOf(' ', begin + 1);
1005
1006
				if (end == -1) end = len;
				args.push_back(cmd.mid(begin, end - begin));
1007
			}
1008
			++end;
1009
1010
1011
1012
1013
1014
		}

		args = formatStringList(args);

		if (!m_process) {
			m_process = new ExternalProcess(this);
1015
		}
1016
1017
1018
1019
1020
1021
		if (m_process) {
			m_process->launchCommand(menuCmd.getName(), args, menuCmd.mustBeConfirmed(), menuCmd.outputShown());
		}
	}
}

1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
/**
 * Execute a context menu action.
 *
 * @param action action of selected menu
 */
#if QT_VERSION >= 0x040000
void FileList::executeAction(QAction* action)
{
	if (action) {
		QString name = action->text();
		int id = 0;
		for (MiscConfig::MenuCommandList::const_iterator
					 it = Kid3App::s_miscCfg.m_contextMenuCommands.begin();
				 it != Kid3App::s_miscCfg.m_contextMenuCommands.end();
				 ++it) {
			if (name == (*it).getName()) {
				executeContextCommand(id);
				break;
			}
			++id;
		}
	}
}
#else
void FileList::executeAction(QAction*) {}
#endif

1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
/**
 * Rename the selected file(s).
 */
void FileList::renameFile()
{
	bool fileSelected = false;
	bool fileRenamed = false;
	FileListItem* item = first();
	TaggedFile* taggedFile;
	while (item != 0) {
		if (item->isInSelection() &&
				(taggedFile = item->getFile()) != 0) {
			bool ok;
1062
1063
			QString newFileName = QInputDialog::QCM_getText(
				this,
1064
1065
				i18n("Rename File"),
				i18n("Enter new file name:"),
1066
				QLineEdit::Normal, taggedFile->getFilename(), &ok);
1067
1068
1069
1070
1071
1072
			if (ok && !newFileName.isEmpty()) {
				if (taggedFile->isChanged()) {
					taggedFile->setFilename(newFileName);
					fileRenamed = true;
				} else {
					QString newPath = taggedFile->getDirname() + '/' + newFileName;
1073
1074
1075
1076
1077
1078
1079
					const DirInfo* dirInfo = taggedFile->getDirInfo();
					QString absFilename = taggedFile->getAbsFilename();
					QString filename = taggedFile->getFilename();
					// This will close the file.
					// The file must be closed before renaming on Windows.
					item->setFile(0);
					if (QDir().rename(absFilename, newPath)) {
1080
						TaggedFile* newTaggedFile =
1081
							TaggedFile::createFile(dirInfo, newFileName);
1082
1083
1084
1085
1086
						if (newTaggedFile) {
							item->setFile(newTaggedFile);
							fileRenamed = true;
						}
					} else {
1087
						item->setFile(TaggedFile::createFile(dirInfo, filename));
1088
1089
1090
						QMessageBox::warning(
							0, i18n("File Error"),
							i18n("Error while renaming:\n") +
1091
							KCM_i18n2("Rename %1 to %2 failed\n", filename, newFileName),
1092
1093
1094
							QMessageBox::Ok, QCM_NoButton);
					}
				}
1095
			}
1096
			fileSelected = true;
1097
		}
1098
1099
1100
1101
1102
		item = next();
	}
	if (fileRenamed) {
		emit selectedFilesRenamed();
	}
1103

1104
1105
1106
1107
1108
1109
	const DirInfo* dirInfo;
	if (!fileSelected &&
			(item = dynamic_cast<FileListItem*>(currentItem())) != 0 &&
			(dirInfo = item->getDirInfo()) != 0) {
		QFileInfo fi(dirInfo->getDirname());
		bool ok;
1110
1111
		QString newDirName = QInputDialog::QCM_getText(
			this,
1112
1113
			i18n("Rename Directory"),
			i18n("Enter new directory name:"),
1114
			QLineEdit::Normal, fi.fileName(), &ok);
1115
		if (ok && !newDirName.isEmpty()) {
1116
1117
1118
#if QT_VERSION >= 0x040000
			QString newPath = fi.dir().path() + '/' + newDirName;
#else
1119
			QString newPath = fi.dirPath() + '/' + newDirName;
1120
#endif
1121
1122
1123
1124
1125
1126
			if (QDir().rename(dirInfo->getDirname(), newPath)) {
				item->setDirName(newPath);
			} else {
				QMessageBox::warning(
					0, i18n("File Error"),
					i18n("Error while renaming:\n") +
1127
					KCM_i18n2("Rename %1 to %2 failed\n", fi.fileName(), newDirName),
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
					QMessageBox::Ok, QCM_NoButton);
			}
		}
	}
}

/**
 * Delete the selected file(s).
 */
void FileList::deleteFile()
{
	QStringList files;
	FileListItem* item = first();
	while (item != 0) {
		if (item->isInSelection()) {
			files.push_back(item->getFile()->getAbsFilename());
		}
		item = next();
	}

	unsigned numFiles = files.size();
	if (numFiles > 0) {
#ifdef CONFIG_USE_KDE
		if (KMessageBox::warningContinueCancelList(
					this,
1153
1154
#if KDE_VERSION >= 0x035c00
					i18np("Do you really want to delete this item?",
Urs Fleisch's avatar
Urs Fleisch committed
1155
								"Do you really want to delete these %1 items?", numFiles),
1156
1157
1158
1159
					files,
					i18n("Delete Files"),
					KStandardGuiItem::del(), KStandardGuiItem::cancel(), QString(),
#else
1160
1161
1162
					i18n("Do you really want to delete this item?",
							 "Do you really want to delete these %n items?", numFiles),
					files,
1163
1164
1165
					i18n("Delete Files"),
					KStdGuiItem::del(), QString::null,
#endif
1166
1167
1168
					KMessageBox::Dangerous) == KMessageBox::Continue)
#else
		QString txt = numFiles > 1 ?
1169
			KCM_i18n1("Do you really want to delete these %1 items?", numFiles) :
1170
1171
1172
1173
			i18n("Do you really want to delete this item?");
		txt += '\n';
		txt += files.join("\n");
		if (
1174
#if QT_VERSION >= 0x030100
1175
			QMessageBox::question
1176
#else
1177
1178
1179
1180
1181
			QMessageBox::warning
#endif
			(
				this, i18n("Delete Files"), txt,
				QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok)
1182
#endif
1183
		{
1184
1185
1186
#if QT_VERSION >= 0x040000
			QList<QTreeWidgetItem*> itemsToDelete;
#endif
1187
1188
1189
1190
1191
			files.clear();
			FileListItem* item = first();
			while (item != 0) {
				FileListItem* nextItem = next();
				if (item->isInSelection()) {
1192
1193
1194
1195
1196
1197
1198
1199
1200
					TaggedFile* taggedFile = item->getFile();
					if (taggedFile) {
						const DirInfo* dirInfo = taggedFile->getDirInfo();
						QString absFilename = taggedFile->getAbsFilename();
						QString filename = taggedFile->getFilename();
						// This will close the file.
						// The file must be closed before deleting on Windows.
						item->setFile(0);
						if (QDir().remove(absFilename)) {
1201
1202
1203
#if QT_VERSION >= 0x040000
							itemsToDelete.append(item);
#else
1204
							delete item;
1205
#endif
1206
						} else {
1207
							item->setFile(TaggedFile::createFile(dirInfo, filename));
1208
1209
							files.push_back(absFilename);
						}
1210
1211
1212
					}
				}
				item = nextItem;
1213
			}
1214
1215
1216
1217
#if QT_VERSION >= 0x040000
			qDeleteAll(itemsToDelete);
			itemsToDelete.clear();
#endif
1218
1219
1220
			if (!files.empty()) {
#ifdef CONFIG_USE_KDE
				KMessageBox::errorList(
1221
1222
1223
					0,
#if KDE_VERSION >= 0x035c00
					i18np("Error while deleting this item:",
Urs Fleisch's avatar
Urs Fleisch committed
1224
								"Error while deleting these %1 items:", files.size()),
1225
1226
1227
1228
#else
					i18n("Error while deleting this item:",
							 "Error while deleting these %n items:", files.size()),
#endif
1229
1230
1231
1232
					files,
					i18n("File Error"));
#else
				QString txt = files.size() > 1 ?
1233
					KCM_i18n1("Error while deleting these %1 items:", files.size()) :
1234
1235
1236
1237
1238
1239
1240
					i18n("Error while deleting this item:");
				txt += '\n';
				txt += files.join("\n");
				QMessageBox::warning(
					0, i18n("File Error"), txt,
					QMessageBox::Ok, QCM_NoButton);
#endif
1241
			}
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
		}
	}

	const DirInfo* dirInfo;
	if (numFiles == 0 &&
			(item = dynamic_cast<FileListItem*>(currentItem())) != 0 &&
			(dirInfo = item->getDirInfo()) != 0) {
		if (
#ifdef CONFIG_USE_KDE
			KMessageBox::warningContinueCancelList(
				this,
				i18n("Do you really want to delete this item?"),
				QStringList(dirInfo->getDirname()),
1255
1256
1257
1258
1259
1260
				i18n("Delete Files"),
#if KDE_VERSION >= 0x035c00
				KStandardGuiItem::del(), KStandardGuiItem::cancel(), QString(),
#else
				KStdGuiItem::del(), QString::null,
#endif
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
				KMessageBox::Dangerous) == KMessageBox::Continue
#else
#if QT_VERSION >= 0x030100
			QMessageBox::question
#else
			QMessageBox::warning
#endif
			(
				this, i18n("Delete Files"),
				i18n("Do you really want to delete this item?") + '\n' + dirInfo->getDirname(),
				QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok
#endif
			) {
			if (QDir().rmdir(dirInfo->getDirname())) {
				delete item;
			} else {
#ifdef CONFIG_USE_KDE
				KMessageBox::errorList(
					0, i18n("Directory must be empty.\n") +
					i18n("Error while deleting this item:"),
					QStringList(dirInfo->getDirname()),
					i18n("File Error"));
#else
				QMessageBox::warning(
					0, i18n("File Error"),
					i18n("Directory must be empty.\n") +
					i18n("Error while deleting this item:") + '\n' + dirInfo->getDirname(),
					QMessageBox::Ok, QCM_NoButton);
#endif
1290
1291
1292
1293
			}
		}
	}
}
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349

#if QT_VERSION >= 0x040000
/**
 * Expand an item.
 *
 * @param item item
 */
void FileList::expandItem(QTreeWidgetItem* item)
{
	FileListItem* fli = dynamic_cast<FileListItem*>(item);
	if (fli) {
		fli->setOpen(true);
	}
}

/**
 * Collapse an item.
 *
 * @param item item
 */
void FileList::collapseItem(QTreeWidgetItem* item)
{
	FileListItem* fli = dynamic_cast<FileListItem*>(item);
	if (fli) {
		fli->setOpen(false);
	}
}

/**
 * Display a custom context menu with operations for selected files.
 *
 * @param pos  position where context menu is drawn on screen
 */
void FileList::customContextMenu(const QPoint& pos)
{
	contextMenu(currentItem(), mapToGlobal(pos));
}

/**
 * Expand or collapse an item which has no children.
 *
 * @param item item
 */
void FileList::expandOrCollapseEmptyItem(QTreeWidgetItem* item)
{
	FileListItem* fli = dynamic_cast<FileListItem*>(item);
	if (fli && fli->getDirInfo() && !item->childCount()) {
		fli->setOpen(!fli->isOpen());
	}
}
#else
void FileList::expandItem(QTreeWidgetItem*) {}
void FileList::collapseItem(QTreeWidgetItem*) {}
void FileList::customContextMenu(const QPoint&) {}
void FileList::expandOrCollapseEmptyItem(QTreeWidgetItem*) {}
#endif