summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/minecraft/mod/ResourceFolderModel.hpp
blob: e909f0d26b278d81914bd34174141f7817584a20 (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
// 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.
 */
#pragma once

#include <QAbstractListModel>
#include <QAction>
#include <QDir>
#include <QFileSystemWatcher>
#include <QHeaderView>
#include <QMutex>
#include <QSet>
#include <QSortFilterProxyModel>
#include <QTreeView>

#include "Resource.hpp"

#include "BaseInstance.h"

#include "tasks/ConcurrentTask.h"
#include "tasks/Task.h"

class QSortFilterProxyModel;

/* A macro to define useful functions to handle Resource* -> T* more easily on derived classes */
#define RESOURCE_HELPERS(T)                                                                                            \
	T& at(int index)                                                                                                   \
	{                                                                                                                  \
		return *static_cast<T*>(m_resources[index].get());                                                             \
	}                                                                                                                  \
	const T& at(int index) const                                                                                       \
	{                                                                                                                  \
		return *static_cast<const T*>(m_resources.at(index).get());                                                    \
	}                                                                                                                  \
	QList<T*> selected##T##s(const QModelIndexList& indexes)                                                           \
	{                                                                                                                  \
		QList<T*> result;                                                                                              \
		for (const QModelIndex& index : indexes)                                                                       \
		{                                                                                                              \
			if (index.column() != 0)                                                                                   \
				continue;                                                                                              \
                                                                                                                       \
			result.append(&at(index.row()));                                                                           \
		}                                                                                                              \
		return result;                                                                                                 \
	}                                                                                                                  \
	QList<T*> all##T##s()                                                                                              \
	{                                                                                                                  \
		QList<T*> result;                                                                                              \
		result.reserve(m_resources.size());                                                                            \
                                                                                                                       \
		for (const Resource::Ptr& resource : m_resources)                                                              \
			result.append(static_cast<T*>(resource.get()));                                                            \
                                                                                                                       \
		return result;                                                                                                 \
	}

/** A basic model for external resources.
 *
 *  This model manages a list of resources. As such, external users of such resources do not own them,
 *  and the resource's lifetime is contingent on the model's lifetime.
 *
 *  Weak pointer access is provided via weakAt(), findWeak(), and isResourceValid() methods.
 *  External code should use these to avoid extending resource lifetime.
 */
class ResourceFolderModel : public QAbstractListModel
{
	Q_OBJECT
  public:
	ResourceFolderModel(const QDir& dir,
						BaseInstance* instance,
						bool is_indexed,
						bool create_dir,
						QObject* parent = nullptr);
	~ResourceFolderModel() override;

	virtual QString id() const
	{
		return "resource";
	}

	/** Starts watching the paths for changes.
	 *
	 *  Returns whether starting to watch all the paths was successful.
	 *  If one or more fails, it returns false.
	 */
	bool startWatching(const QStringList& paths);

	/** Stops watching the paths for changes.
	 *
	 *  Returns whether stopping to watch all the paths was successful.
	 *  If one or more fails, it returns false.
	 */
	bool stopWatching(const QStringList& paths);

	/* Helper methods for subclasses, using a predetermined list of paths. */
	virtual bool startWatching()
	{
		return startWatching({ indexDir().absolutePath(), m_dir.absolutePath() });
	}
	virtual bool stopWatching()
	{
		return stopWatching({ indexDir().absolutePath(), m_dir.absolutePath() });
	}

	QDir indexDir()
	{
		return { QString("%1/.index").arg(dir().absolutePath()) };
	}

	/** Given a path in the system, install that resource, moving it to its place in the
	 *  instance file hierarchy.
	 *
	 *  Returns whether the installation was succcessful.
	 */
	virtual bool installResource(QString path);

	virtual void installResourceWithFlameMetadata(QString path, ModPlatform::IndexedVersion& vers);

	/** Uninstall (i.e. remove all data about it) a resource, given its file name.
	 *
	 *  Returns whether the removal was successful.
	 */
	virtual bool uninstallResource(QString file_name, bool preserve_metadata = false);
	virtual bool deleteResources(const QModelIndexList&);
	virtual void deleteMetadata(const QModelIndexList&);

	/** Applies the given 'action' to the resources in 'indexes'.
	 *
	 *  Returns whether the action was successfully applied to all resources.
	 */
	virtual bool setResourceEnabled(const QModelIndexList& indexes, EnableAction action);

	/** Creates a new update task and start it. Returns false if no update was done, like when an update is already underway. */
	virtual bool update();

	/** Creates a new parse task, if needed, for 'res' and start it.*/
	virtual void resolveResource(Resource::Ptr res);

	qsizetype size() const
	{
		return m_resources.size();
	}
	[[nodiscard]] bool empty() const
	{
		return size() == 0;
	}

	Resource& at(int index)
	{
		return *m_resources[index].get();
	}
	const Resource& at(int index) const
	{
		return *m_resources.at(index).get();
	}

	/** Get a weak pointer to a resource by index.
	 *  This is the preferred way to access resources from external code,
	 *  as it doesn't extend the resource's lifetime.
	 */
	Resource::WeakPtr weakAt(int index)
	{
		if (index < 0 || index >= m_resources.size())
			return Resource::WeakPtr();
		return Resource::WeakPtr(m_resources[index].get());
	}

	/** Get a weak pointer to a resource by internal ID.
	 *  Returns null WeakPtr if not found.
	 */
	Resource::WeakPtr findWeak(const QString& id);

	/** Check if a weak pointer is still valid (resource still exists).
	 *  This is useful for external code that holds weak references.
	 */
	bool isResourceValid(Resource::WeakPtr ptr) const
	{
		return !ptr.isNull() && m_resources_index.contains(ptr->internal_id());
	}

	QList<Resource*> selectedResources(const QModelIndexList& indexes);
	QList<Resource*> allResources();

	Resource::Ptr find(QString id);

	QDir const& dir() const
	{
		return m_dir;
	}

	/** Checks whether there's any parse tasks being done.
	 *
	 *  Since they can be quite expensive, and are usually done in a separate thread, if we were to destroy the model
	 * while having such tasks would introduce an undefined behavior, most likely resulting in a crash.
	 */
	bool hasPendingParseTasks() const;

	/* Qt behavior */

	/* Basic columns */
	enum Columns
	{
		ActiveColumn = 0,
		NameColumn,
		DateColumn,
		ProviderColumn,
		SizeColumn,
		NUM_COLUMNS
	};

	QStringList columnNames(bool translated = true) const
	{
		return translated ? m_column_names_translated : m_column_names;
	}

	int rowCount(const QModelIndex& parent = {}) const override
	{
		return parent.isValid() ? 0 : static_cast<int>(size());
	}
	int columnCount(const QModelIndex& parent = {}) const override
	{
		return parent.isValid() ? 0 : NUM_COLUMNS;
	}

	Qt::DropActions supportedDropActions() const override;

	/// flags, mostly to support drag&drop
	Qt::ItemFlags flags(const QModelIndex& index) const override;
	QStringList mimeTypes() const override;
	[[nodiscard]] bool dropMimeData(const QMimeData* data,
									Qt::DropAction action,
									int row,
									int column,
									const QModelIndex& parent) override;

	[[nodiscard]] bool validateIndex(const QModelIndex& index) const;

	QBrush rowBackground(int row) const;
	QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
	bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;

	QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;

	void setupHeaderAction(QAction* act, int column);
	void saveColumns(QTreeView* tree);
	void loadColumns(QTreeView* tree);
	QMenu* createHeaderContextMenu(QTreeView* tree);

	/** This creates a proxy model to filter / sort the model for a UI.
	 *
	 *  The actual comparisons and filtering are done directly by the Resource, so to modify behavior go there instead!
	 */
	QSortFilterProxyModel* createFilterProxyModel(QObject* parent = nullptr);

	SortType columnToSortKey(size_t column) const;
	QList<QHeaderView::ResizeMode> columnResizeModes() const
	{
		return m_column_resize_modes;
	}

	class ProxyModel : public QSortFilterProxyModel
	{
	  public:
		explicit ProxyModel(QObject* parent = nullptr) : QSortFilterProxyModel(parent)
		{}

	  protected:
		bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
		bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override;
	};

	QString instDirPath() const;

  signals:
	void updateFinished();
	void parseFinished();

  protected:
	/** This creates a new update task to be executed by update().
	 *
	 *  The task should load and parse all resources necessary, and provide a way of accessing such results.
	 *
	 *  This Task is normally executed when opening a page, so it shouldn't contain much heavy work.
	 *  If such work is needed, try using it in the Task create by createParseTask() instead!
	 */
	[[nodiscard]] Task* createUpdateTask();

	[[nodiscard]] virtual Resource* createResource(const QFileInfo& info)
	{
		return new Resource(info);
	}

	/** This creates a new parse task to be executed by onUpdateSucceeded().
	 *
	 *  This task should load and parse all heavy info needed by a resource, such as parsing a manifest. It gets
	 * executed in the background, so it slowly updates the UI as tasks get done.
	 */
	[[nodiscard]] virtual Task* createParseTask(Resource&)
	{
		return nullptr;
	}

	/** Standard implementation of the model update logic.
	 *
	 *  It uses set operations to find differences between the current state and the updated state,
	 *  to act only on those disparities.
	 *
	 */
	void applyUpdates(QSet<QString>& current_set, QSet<QString>& new_set, QMap<QString, Resource::Ptr>& new_resources);

  protected slots:
	void directoryChanged(QString);

	/** Called when the update task is successful.
	 *
	 *  Override in subclasses to handle specific task result types.
	 *  The implementation typically uses static_cast to convert the Task to
	 *  the specific type returned by createUpdateTask().
	 *
	 *  Note: Qt's Q_OBJECT macro doesn't support template classes, so we use
	 *  runtime polymorphism with virtual methods and static_cast instead.
	 *  The type relationship is documented in createUpdateTask() for each subclass.
	 */
	virtual void onUpdateSucceeded();
	virtual void onUpdateFailed()
	{}

	/** Called when the parse task with the given ticket is successful.
	 *
	 *  This is just a simple reference implementation. You probably want to override it with your own logic in a
	 * subclass if the resource is complex and has more stuff to parse.
	 */
	virtual void onParseSucceeded(int ticket, QString resource_id);
	virtual void onParseFailed(int ticket, QString resource_id);

  protected:
	// Represents the relationship between a column's index (represented by the list index), and it's sorting key.
	// As such, the order in with they appear is very important!
	QList<SortType> m_column_sort_keys					 = { SortType::ENABLED,
															 SortType::NAME,
															 SortType::DATE,
															 SortType::PROVIDER,
															 SortType::SIZE };
	QStringList m_column_names							 = { "Enable", "Name", "Last Modified", "Provider", "Size" };
	QStringList m_column_names_translated				 = { tr("Enable"),
															 tr("Name"),
															 tr("Last Modified"),
															 tr("Provider"),
															 tr("Size") };
	QList<QHeaderView::ResizeMode> m_column_resize_modes = { QHeaderView::Interactive,
															 QHeaderView::Stretch,
															 QHeaderView::Interactive,
															 QHeaderView::Interactive,
															 QHeaderView::Interactive };
	QList<bool> m_columnsHideable						 = { false, false, true, true, true };

	QDir m_dir;
	BaseInstance* m_instance;
	QFileSystemWatcher m_watcher;
	bool m_is_watching = false;

	bool m_is_indexed;
	bool m_first_folder_load = true;

	Task::Ptr m_current_update_task = nullptr;
	bool m_scheduled_update			= false;

	QList<Resource::Ptr> m_resources;

	// Represents the relationship between a resource's internal ID and it's row position on the model.
	QMap<QString, int> m_resources_index;

	ConcurrentTask m_helper_thread_task;
	QMap<int, Task::Ptr> m_active_parse_tasks;
	std::atomic<int> m_next_resolution_ticket = 0;
};