summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/icons/IconList.cpp
blob: 13181117fa05fdf3cee2ff559d4a1c50fb969d31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program 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, version 3.
 *
 *  This program 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, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "IconList.hpp"
#include <FileSystem.h>
#include <QDebug>
#include <QFileSystemWatcher>
#include <QMap>
#include <QMimeData>
#include <QSet>
#include <QUrl>
#include "icons/IconUtils.hpp"
#include <algorithm>

#define MAX_SIZE 1024

namespace projt::icons
{
	IconList::IconList(const QStringList& builtinPaths, const QString& path, QObject* parent)
		: QAbstractListModel(parent)
	{
		QSet<QString> builtinNames;

		// add builtin icons
		for (const auto& builtinPath : builtinPaths)
		{
			QDir instanceIcons(builtinPath);
			auto fileInfoList = instanceIcons.entryInfoList(QDir::Files, QDir::Name);
			for (const auto& fileInfo : fileInfoList)
			{
				builtinNames.insert(fileInfo.completeBaseName());
			}
		}
		for (const auto& builtinName : builtinNames)
		{
			addThemeIcon(builtinName);
		}

		m_watcher.reset(new QFileSystemWatcher());
		connect(m_watcher.get(), &QFileSystemWatcher::directoryChanged, this, &IconList::directoryChanged);
		connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this, &IconList::fileChanged);

		directoryChanged(path);

		// Forces the UI to update, so that lengthy icon names are shown properly from the start
		emit iconUpdated({});
	}

	void IconList::sortIconList()
	{
		qDebug() << "Sorting icon list...";
		std::sort(m_icons.begin(),
				  m_icons.end(),
				  [](const IconEntry& a, const IconEntry& b)
				  {
					  bool aIsSubdir = a.m_key.contains(QDir::separator());
					  bool bIsSubdir = b.m_key.contains(QDir::separator());
					  if (aIsSubdir != bIsSubdir)
					  {
						  return !aIsSubdir; // root-level icons come first
					  }
					  return a.m_key.localeAwareCompare(b.m_key) < 0;
				  });
		reindex();
	}

	// Helper function to add directories recursively
	bool IconList::addPathRecursively(const QString& path)
	{
		QDir dir(path);
		if (!dir.exists())
		{
			return false;
		}

		// Add the directory itself
		bool watching = m_watcher->addPath(path);

		// Add all subdirectories
		QFileInfoList entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
		for (const QFileInfo& entry : entries)
		{
			if (addPathRecursively(entry.absoluteFilePath()))
			{
				watching = true;
			}
		}
		return watching;
	}

	QStringList IconList::getIconFilePaths() const
	{
		QStringList iconFiles{};
		QStringList directories{ m_dir.absolutePath() };
		while (!directories.isEmpty())
		{
			QString first = directories.takeFirst();
			QDir dir(first);
			for (QFileInfo& fileInfo :
				 dir.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot, QDir::Name))
			{
				if (fileInfo.isDir())
				{
					directories.push_back(fileInfo.absoluteFilePath());
				}
				else
				{
					iconFiles.push_back(fileInfo.absoluteFilePath());
				}
			}
		}
		return iconFiles;
	}

	namespace
	{
		QString formatName(const QDir& iconsDir, const QFileInfo& iconFile)
		{
			if (iconFile.dir() == iconsDir)
			{
				return iconFile.completeBaseName();
			}

			constexpr auto delimiter = " » ";
			QString relativePathWithoutExtension =
				iconsDir.relativeFilePath(iconFile.dir().path()) + QDir::separator() + iconFile.completeBaseName();
			return relativePathWithoutExtension.replace(QDir::separator(), delimiter);
		}

		/// Split into a separate function because the preprocessing impedes readability
		QSet<QString> toStringSet(const QList<QString>& list)
		{
			QSet<QString> set(list.begin(), list.end());
			return set;
		}
	} // namespace

	void IconList::directoryChanged(const QString& path)
	{
		QDir newDir(path);
		if (m_dir.absolutePath() != newDir.absolutePath())
		{
			if (!path.startsWith(m_dir.absolutePath()))
			{
				m_dir.setPath(path);
			}
			m_dir.refresh();
			if (m_isWatching)
			{
				stopWatching();
			}
			startWatching();
		}
		m_dir.refresh();
		if (!m_dir.exists() && !FS::ensureFolderPathExists(m_dir.absolutePath()))
		{
			return;
		}
		m_dir.refresh();
		const QStringList newFileNamesList = getIconFilePaths();
		const QSet<QString> newSet		   = toStringSet(newFileNamesList);
		QSet<QString> currentSet;
		for (const IconEntry& it : m_icons)
		{
			if (!it.has(IconType::FileBased))
			{
				continue;
			}
			QFileInfo icon(it.getFilePath());
			currentSet.insert(icon.absoluteFilePath());
		}
		QSet<QString> toRemove = currentSet - newSet;
		QSet<QString> toAdd	   = newSet - currentSet;

		for (const QString& removedPath : toRemove)
		{
			qDebug() << "Removing icon " << removedPath;
			QFileInfo removedFile(removedPath);
			QString relativePath = m_dir.relativeFilePath(removedFile.absoluteFilePath());
			QString key			 = QFileInfo(relativePath).completeBaseName();

			int idx = getIconIndex(key);
			if (idx == -1)
			{
				continue;
			}
			m_icons[idx].remove(FileBased);
			if (m_icons[idx].type() == ToBeDeleted)
			{
				beginRemoveRows(QModelIndex(), idx, idx);
				m_icons.remove(idx);
				reindex();
				endRemoveRows();
			}
			else
			{
				dataChanged(index(idx), index(idx));
			}
			m_watcher->removePath(removedPath);
			emit iconUpdated(key);
		}

		for (const QString& addedPath : toAdd)
		{
			qDebug() << "Adding icon " << addedPath;

			QFileInfo addfile(addedPath);
			QString relativePath = m_dir.relativeFilePath(addfile.absoluteFilePath());
			QString key			 = QFileInfo(relativePath).completeBaseName();
			QString name		 = formatName(m_dir, addfile);

			if (addIcon(key, name, addfile.filePath(), IconType::FileBased))
			{
				m_watcher->addPath(addedPath);
				emit iconUpdated(key);
			}
		}

		sortIconList();
	}

	void IconList::fileChanged(const QString& path)
	{
		qDebug() << "Checking icon " << path;
		QFileInfo checkfile(path);
		if (!checkfile.exists())
		{
			return;
		}
		QString key = m_dir.relativeFilePath(checkfile.absoluteFilePath());
		int idx		= getIconIndex(key);
		if (idx == -1)
		{
			return;
		}
		QIcon icon(path);
		if (icon.availableSizes().empty())
		{
			return;
		}

		m_icons[idx].m_images[IconType::FileBased].icon = icon;
		dataChanged(index(idx), index(idx));
		emit iconUpdated(key);
	}

	void IconList::SettingChanged(const Setting& setting, const QVariant& value)
	{
		if (setting.id() != "IconsDir")
		{
			return;
		}

		directoryChanged(value.toString());
	}

	void IconList::startWatching()
	{
		auto abs_path = m_dir.absolutePath();
		FS::ensureFolderPathExists(abs_path);
		m_isWatching = addPathRecursively(abs_path);
		if (m_isWatching)
		{
			qDebug() << "Started watching " << abs_path;
		}
		else
		{
			qDebug() << "Failed to start watching " << abs_path;
		}
	}

	void IconList::stopWatching()
	{
		m_watcher->removePaths(m_watcher->files());
		m_watcher->removePaths(m_watcher->directories());
		m_isWatching = false;
	}

	QStringList IconList::mimeTypes() const
	{
		QStringList types;
		types << "text/uri-list";
		return types;
	}

	Qt::DropActions IconList::supportedDropActions() const
	{
		return Qt::CopyAction;
	}

	bool IconList::dropMimeData(const QMimeData* data,
								Qt::DropAction action,
								[[maybe_unused]] int row,
								[[maybe_unused]] int column,
								[[maybe_unused]] const QModelIndex& parent)
	{
		if (action == Qt::IgnoreAction)
		{
			return true;
		}
		// check if the action is supported
		if (!data || !(action & supportedDropActions()))
		{
			return false;
		}

		// files dropped from outside?
		if (data->hasUrls())
		{
			auto urls = data->urls();
			QStringList iconFiles;
			for (const auto& url : urls)
			{
				// only local files may be dropped...
				if (!url.isLocalFile())
				{
					continue;
				}
				iconFiles += url.toLocalFile();
			}
			installIcons(iconFiles);
			return true;
		}
		return false;
	}

	Qt::ItemFlags IconList::flags(const QModelIndex& index) const
	{
		Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);
		return Qt::ItemIsDropEnabled | defaultFlags;
	}

	QVariant IconList::data(const QModelIndex& index, int role) const
	{
		if (!index.isValid())
		{
			return {};
		}

		int row = index.row();

		if (row < 0 || row >= m_icons.size())
		{
			return {};
		}

		switch (role)
		{
			case Qt::DecorationRole: return m_icons[row].icon();
			case Qt::DisplayRole: return m_icons[row].name();
			case Qt::UserRole: return m_icons[row].m_key;
			default: return {};
		}
	}

	int IconList::rowCount(const QModelIndex& parent) const
	{
		return parent.isValid() ? 0 : m_icons.size();
	}

	void IconList::installIcons(const QStringList& iconFiles)
	{
		for (const QString& file : iconFiles)
		{
			installIcon(file, {});
		}
	}

	void IconList::installIcon(const QString& file, const QString& name)
	{
		QFileInfo fileinfo(file);
		if (!fileinfo.isReadable() || !fileinfo.isFile())
		{
			return;
		}

		if (!isIconSuffix(fileinfo.suffix()))
		{
			return;
		}

		QString target = FS::PathCombine(getDirectory(), name.isEmpty() ? fileinfo.fileName() : name);
		QFile::copy(file, target);
	}

	bool IconList::iconFileExists(const QString& key) const
	{
		auto iconEntry = icon(key);
		return iconEntry && iconEntry->has(IconType::FileBased);
	}

	/// Returns the icon with the given key or nullptr if it doesn't exist.
	const IconEntry* IconList::icon(const QString& key) const
	{
		int iconIdx = getIconIndex(key);
		if (iconIdx == -1)
		{
			return nullptr;
		}
		return &m_icons[iconIdx];
	}

	bool IconList::deleteIcon(const QString& key)
	{
		auto* iconEntry = icon(key);
		return iconEntry && iconFileExists(key) && FS::deletePath(iconEntry->getFilePath());
	}

	bool IconList::trashIcon(const QString& key)
	{
		auto* iconEntry = icon(key);
		return iconEntry && iconFileExists(key) && FS::trash(iconEntry->getFilePath(), nullptr);
	}

	bool IconList::addThemeIcon(const QString& key)
	{
		auto iter = m_nameIndex.find(key);
		if (iter != m_nameIndex.end())
		{
			auto& oldOne = m_icons[*iter];
			oldOne.replace(Builtin, key);
			dataChanged(index(*iter), index(*iter));
			return true;
		}
		// add a new icon
		beginInsertRows(QModelIndex(), m_icons.size(), m_icons.size());
		{
			IconEntry iconEntry;
			iconEntry.m_name = key;
			iconEntry.m_key	 = key;
			iconEntry.replace(Builtin, key);
			m_icons.push_back(iconEntry);
			m_nameIndex[key] = m_icons.size() - 1;
		}
		endInsertRows();
		return true;
	}

	bool IconList::addIcon(const QString& key, const QString& name, const QString& path, const IconType type)
	{
		// replace the icon even? is the input valid?
		QIcon icon(path);
		if (icon.isNull())
		{
			return false;
		}
		auto iter = m_nameIndex.find(key);
		if (iter != m_nameIndex.end())
		{
			auto& oldOne = m_icons[*iter];
			oldOne.replace(type, icon, path);
			dataChanged(index(*iter), index(*iter));
			return true;
		}
		// add a new icon
		beginInsertRows(QModelIndex(), m_icons.size(), m_icons.size());
		{
			IconEntry iconEntry;
			iconEntry.m_name = name;
			iconEntry.m_key	 = key;
			iconEntry.replace(type, icon, path);
			m_icons.push_back(iconEntry);
			m_nameIndex[key] = m_icons.size() - 1;
		}
		endInsertRows();
		return true;
	}

	void IconList::saveIcon(const QString& key, const QString& path, const char* format) const
	{
		auto icon	= getIcon(key);
		auto pixmap = icon.pixmap(128, 128);
		pixmap.save(path, format);
	}

	void IconList::reindex()
	{
		m_nameIndex.clear();
		for (int i = 0; i < m_icons.size(); i++)
		{
			m_nameIndex[m_icons[i].m_key] = i;
			emit iconUpdated(m_icons[i].m_key); // prevents incorrect indices with proxy model
		}
	}

	QIcon IconList::getIcon(const QString& key) const
	{
		int iconIndex = getIconIndex(key);

		if (iconIndex != -1)
		{
			return m_icons[iconIndex].icon();
		}

		// Fallback for icons that don't exist.
		iconIndex = getIconIndex("grass");

		if (iconIndex != -1)
		{
			return m_icons[iconIndex].icon();
		}
		return {};
	}

	int IconList::getIconIndex(const QString& key) const
	{
		auto iter = m_nameIndex.find(key == "default" ? "grass" : key);
		if (iter != m_nameIndex.end())
		{
			return *iter;
		}

		return -1;
	}

	QString IconList::getDirectory() const
	{
		return m_dir.absolutePath();
	}

	/// Returns the directory of the icon with the given key or the default directory if it's a builtin icon.
	QString IconList::iconDirectory(const QString& key) const
	{
		for (const auto& iconEntry : m_icons)
		{
			if (iconEntry.m_key == key && iconEntry.has(IconType::FileBased))
			{
				QFileInfo iconFile(iconEntry.getFilePath());
				return iconFile.dir().path();
			}
		}
		return getDirectory();
	}
} // namespace projt::icons