summaryrefslogtreecommitdiffstats
path: root/application/dialogs/ExportInstanceDialog.cpp
blob: 8d320a3c957afc9effb7450893a1d9e0a6740927 (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
/* Copyright 2013-2015 MultiMC Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ExportInstanceDialog.h"
#include "ui_ExportInstanceDialog.h"
#include <BaseInstance.h>
#include <MMCZip.h>
#include <QFileDialog>
#include <QMessageBox>
#include <qfilesystemmodel.h>

#include <QSortFilterProxyModel>
#include <QDebug>
#include <qstack.h>
#include <QSaveFile>
#include "MMCStrings.h"
#include "SeparatorPrefixTree.h"
#include "Env.h"
#include <icons/IconList.h>
#include <FileSystem.h>

class PackIgnoreProxy : public QSortFilterProxyModel
{
	Q_OBJECT

public:
	PackIgnoreProxy(InstancePtr instance, QObject *parent) : QSortFilterProxyModel(parent)
	{
		m_instance = instance;
	}
	// NOTE: Sadly, we have to do sorting ourselves.
	bool lessThan(const QModelIndex &left, const QModelIndex &right) const
	{
		QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
		if (!fsm)
		{
			return QSortFilterProxyModel::lessThan(left, right);
		}
		bool asc = sortOrder() == Qt::AscendingOrder ? true : false;

		QFileInfo leftFileInfo = fsm->fileInfo(left);
		QFileInfo rightFileInfo = fsm->fileInfo(right);

		if (!leftFileInfo.isDir() && rightFileInfo.isDir())
		{
			return !asc;
		}
		if (leftFileInfo.isDir() && !rightFileInfo.isDir())
		{
			return asc;
		}

		// sort and proxy model breaks the original model...
		if (sortColumn() == 0)
		{
			return Strings::naturalCompare(leftFileInfo.fileName(), rightFileInfo.fileName(),
										   Qt::CaseInsensitive) < 0;
		}
		if (sortColumn() == 1)
		{
			auto leftSize = leftFileInfo.size();
			auto rightSize = rightFileInfo.size();
			if ((leftSize == rightSize) || (leftFileInfo.isDir() && rightFileInfo.isDir()))
			{
				return Strings::naturalCompare(leftFileInfo.fileName(),
											   rightFileInfo.fileName(),
											   Qt::CaseInsensitive) < 0
						   ? asc
						   : !asc;
			}
			return leftSize < rightSize;
		}
		return QSortFilterProxyModel::lessThan(left, right);
	}

	virtual Qt::ItemFlags flags(const QModelIndex &index) const
	{
		if (!index.isValid())
			return Qt::NoItemFlags;

		auto sourceIndex = mapToSource(index);
		Qt::ItemFlags flags = sourceIndex.flags();
		if (index.column() == 0)
		{
			flags |= Qt::ItemIsUserCheckable;
			if (sourceIndex.model()->hasChildren(sourceIndex))
			{
				flags |= Qt::ItemIsTristate;
			}
		}

		return flags;
	}

	virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
	{
		QModelIndex sourceIndex = mapToSource(index);

		if (index.column() == 0 && role == Qt::CheckStateRole)
		{
			QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
			auto blockedPath = relPath(fsm->filePath(sourceIndex));
			auto cover = blocked.cover(blockedPath);
			if (!cover.isNull())
			{
				return QVariant(Qt::Unchecked);
			}
			else if (blocked.exists(blockedPath))
			{
				return QVariant(Qt::PartiallyChecked);
			}
			else
			{
				return QVariant(Qt::Checked);
			}
		}

		return sourceIndex.data(role);
	}

	virtual bool setData(const QModelIndex &index, const QVariant &value,
						 int role = Qt::EditRole)
	{
		if (index.column() == 0 && role == Qt::CheckStateRole)
		{
			Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
			return setFilterState(index, state);
		}

		QModelIndex sourceIndex = mapToSource(index);
		return QSortFilterProxyModel::sourceModel()->setData(sourceIndex, value, role);
	}

	QString relPath(const QString &path) const
	{
		QString prefix = QDir().absoluteFilePath(m_instance->instanceRoot());
		prefix += '/';
		if (!path.startsWith(prefix))
		{
			return QString();
		}
		return path.mid(prefix.size());
	}

	bool setFilterState(QModelIndex index, Qt::CheckState state)
	{
		QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());

		if (!fsm)
		{
			return false;
		}

		QModelIndex sourceIndex = mapToSource(index);
		auto blockedPath = relPath(fsm->filePath(sourceIndex));
		bool changed = false;
		if (state == Qt::Unchecked)
		{
			// blocking a path
			auto &node = blocked.insert(blockedPath);
			// get rid of all blocked nodes below
			node.clear();
			changed = true;
		}
		else if (state == Qt::Checked || state == Qt::PartiallyChecked)
		{
			if (!blocked.remove(blockedPath))
			{
				auto cover = blocked.cover(blockedPath);
				qDebug() << "Blocked by cover" << cover;
				// uncover
				blocked.remove(cover);
				// block all contents, except for any cover
				QModelIndex rootIndex =
					fsm->index(FS::PathCombine(m_instance->instanceRoot(), cover));
				QModelIndex doing = rootIndex;
				int row = 0;
				QStack<QModelIndex> todo;
				while (1)
				{
					auto node = doing.child(row, 0);
					if (!node.isValid())
					{
						if (!todo.size())
						{
							break;
						}
						else
						{
							doing = todo.pop();
							row = 0;
							continue;
						}
					}
					auto relpath = relPath(fsm->filePath(node));
					if (blockedPath.startsWith(relpath)) // cover found?
					{
						// continue processing cover later
						todo.push(node);
					}
					else
					{
						// or just block this one.
						blocked.insert(relpath);
					}
					row++;
				}
			}
			changed = true;
		}
		if (changed)
		{
			// update the thing
			emit dataChanged(index, index, {Qt::CheckStateRole});
			// update everything above index
			QModelIndex up = index.parent();
			while (1)
			{
				if (!up.isValid())
					break;
				emit dataChanged(up, up, {Qt::CheckStateRole});
				up = up.parent();
			}
			// and everything below the index
			QModelIndex doing = index;
			int row = 0;
			QStack<QModelIndex> todo;
			while (1)
			{
				auto node = doing.child(row, 0);
				if (!node.isValid())
				{
					if (!todo.size())
					{
						break;
					}
					else
					{
						doing = todo.pop();
						row = 0;
						continue;
					}
				}
				emit dataChanged(node, node, {Qt::CheckStateRole});
				todo.push(node);
				row++;
			}
			// siblings and unrelated nodes are ignored
		}
		return true;
	}

	bool shouldExpand(QModelIndex index)
	{
		QModelIndex sourceIndex = mapToSource(index);
		QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
		if (!fsm)
		{
			return false;
		}
		auto blockedPath = relPath(fsm->filePath(sourceIndex));
		auto found = blocked.find(blockedPath);
		if(found)
		{
			return !found->leaf();
		}
		return false;
	}

	void setBlockedPaths(QStringList paths)
	{
		beginResetModel();
		blocked.clear();
		blocked.insert(paths);
		endResetModel();
	}

	const SeparatorPrefixTree<'/'> & blockedPaths() const
	{
		return blocked;
	}

protected:
	bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const
	{
		Q_UNUSED(source_parent)

		// adjust the columns you want to filter out here
		// return false for those that will be hidden
		if (source_column == 2 || source_column == 3)
			return false;

		return true;
	}

private:
	InstancePtr m_instance;
	SeparatorPrefixTree<'/'> blocked;
};

ExportInstanceDialog::ExportInstanceDialog(InstancePtr instance, QWidget *parent)
	: QDialog(parent), ui(new Ui::ExportInstanceDialog), m_instance(instance)
{
	ui->setupUi(this);
	auto model = new QFileSystemModel(this);
	proxyModel = new PackIgnoreProxy(m_instance, this);
	loadPackIgnore();
	proxyModel->setSourceModel(model);
	auto root = instance->instanceRoot();
	ui->treeView->setModel(proxyModel);
	ui->treeView->setRootIndex(proxyModel->mapFromSource(model->index(root)));

	connect(proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(rowsInserted(QModelIndex,int,int)));

	model->setRootPath(root);
	auto headerView = ui->treeView->header();
	headerView->setSectionResizeMode(QHeaderView::ResizeToContents);
	headerView->setSectionResizeMode(0, QHeaderView::Stretch);
}

ExportInstanceDialog::~ExportInstanceDialog()
{
	delete ui;
}

/// Save icon to instance's folder is needed
void SaveIcon(InstancePtr m_instance)
{
	auto iconKey = m_instance->iconKey();
	auto iconList = ENV.icons();
	auto mmcIcon = iconList->icon(iconKey);
	if(mmcIcon)
	{
		bool saveIcon = false;
		switch(mmcIcon->type())
		{
			case MMCIcon::FileBased:
			case MMCIcon::Transient:
				saveIcon = true;
			default:
				break;
		}
		if(saveIcon)
		{
			auto & image = mmcIcon->m_images[mmcIcon->type()];
			auto & icon = image.icon;
			auto sizes = icon.availableSizes();
			if(sizes.size() == 0)
			{
				return;
			}
			auto areaOf = [](QSize size)
			{
				return size.width() * size.height();
			};
			QSize largest = sizes[0];
			// find variant with largest area
			for(auto size: sizes)
			{
				if(areaOf(largest) < areaOf(size))
				{
					largest = size;
				}
			}
			auto pixmap = icon.pixmap(largest);
			pixmap.save(FS::PathCombine(m_instance->instanceRoot(), iconKey + ".png"));
		}
	}
}

bool ExportInstanceDialog::doExport()
{
	auto name = FS::RemoveInvalidFilenameChars(m_instance->name());

	const QString output = QFileDialog::getSaveFileName(
		this, tr("Export %1").arg(m_instance->name()),
		FS::PathCombine(QDir::homePath(), name + ".zip"), "Zip (*.zip)");
	if (output.isNull())
	{
		return false;
	}
	if (QFile::exists(output))
	{
		int ret =
			QMessageBox::question(this, tr("Overwrite?"),
								  tr("This file already exists. Do you want to overwrite it?"),
								  QMessageBox::No, QMessageBox::Yes);
		if (ret == QMessageBox::No)
		{
			return false;
		}
	}

	SaveIcon(m_instance);

	if (!MMCZip::compressDir(output, m_instance->instanceRoot(), name, &proxyModel->blockedPaths()))
	{
		QMessageBox::warning(this, tr("Error"), tr("Unable to export instance"));
		return false;
	}
	return true;
}

void ExportInstanceDialog::done(int result)
{
	savePackIgnore();
	if (result == QDialog::Accepted)
	{
		if (doExport())
		{
			QDialog::done(QDialog::Accepted);
			return;
		}
		else
		{
			return;
		}
	}
	QDialog::done(result);
}

void ExportInstanceDialog::rowsInserted(QModelIndex parent, int top, int bottom)
{
	//WARNING: possible off-by-one?
	for(int i = top; i < bottom; i++)
	{
		auto node = parent.child(i, 0);
		if(proxyModel->shouldExpand(node))
		{
			auto expNode = node.parent();
			if(!expNode.isValid())
			{
				continue;
			}
			ui->treeView->expand(node);
		}
	}
}

QString ExportInstanceDialog::ignoreFileName()
{
	return FS::PathCombine(m_instance->instanceRoot(), ".packignore");
}

void ExportInstanceDialog::loadPackIgnore()
{
	auto filename = ignoreFileName();
	QFile ignoreFile(filename);
	if(!ignoreFile.open(QIODevice::ReadOnly))
	{
		return;
	}
	auto data = ignoreFile.readAll();
	auto string = QString::fromUtf8(data);
	proxyModel->setBlockedPaths(string.split('\n', QString::SkipEmptyParts));
}

void ExportInstanceDialog::savePackIgnore()
{
	auto data = proxyModel->blockedPaths().toStringList().join('\n').toUtf8();
	auto filename = ignoreFileName();
	try
	{
		FS::write(filename, data);
	}
	catch (Exception & e)
	{
		qWarning() << e.cause();
	}
}

#include "ExportInstanceDialog.moc"