summaryrefslogtreecommitdiff
path: root/view/sharedcache/ui/dscwidget.cpp
blob: 2483a26e8ebeca3d50e75cc2d40431e7a992792a (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
//
// by kat // 9/15/22.
//

// CURRENTLY UNUSED CODE

#include "dscwidget.h"

#include "ui/viewframe.h"
#include "ui/progresstask.h"

#include <QtCore/QMimeData>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QVBoxLayout>
#include <filesystem>
#include <QtWidgets>

namespace fs = std::filesystem;


/// Format an address as hexadecimal. Does not include leading '0x' prefix.
QString formatAddress(uint64_t address)
{
	return QString::number(address, 16).rightJustified(8, '0');
};

//===-- DSCContentsModelItem ------------------------------------------------===//

DSCContentsModelItem::DSCContentsModelItem(DSCContentsModelItem* parent) : DSCContentsModelItem(nullptr, {}, {}, parent)
{}

DSCContentsModelItem::DSCContentsModelItem(
	BinaryViewRef view, std::string name, std::string installName, DSCContentsModelItem* parent) :
	m_bv(view),
	m_name(name), m_installName(installName), m_parent(parent)
{
	if (!installName.empty())
		m_type = ImageModelItem;
	else
		m_type = FolderModelItem;
}

QString DSCContentsModelItem::displayName() const
{
	return QString::fromStdString(m_name);
}

size_t DSCContentsModelItem::childCount() const
{
	return m_children.size();
}

DSCContentsModelItem* DSCContentsModelItem::child(size_t index)
{
	if (index < 0 || index >= m_children.size())
		return nullptr;

	return m_children[index];
}

void DSCContentsModelItem::addChild(DSCContentsModelItem* item)
{
	item->m_parent = this;
	m_children.push_back(item);
}

DSCContentsModelItem* DSCContentsModelItem::parent() const
{
	return m_parent;
}

size_t DSCContentsModelItem::row() const
{
	if (!m_parent)
		return 0;
	auto it = std::find(m_parent->m_children.begin(), m_parent->m_children.end(), this);
	return it - m_parent->m_children.begin();
}

QVariant DSCContentsModelItem::data(int column) const
{
	switch (column)
	{
	case DSCContentsModel::NameColumn:
		return displayName();

	default:
		return QVariant();
	}
}

QImage DSCContentsModelItem::icon() const
{
	auto kind = data(DSCContentsModel::KindColumn).toString();
	auto icon = QImage(":/icons/images/ComponentTree_" + kind + ".png");

	return icon.scaled(16, 16, Qt::KeepAspectRatio);
}

//===-- DSCContentsModel ----------------------------------------------------===//

DSCContentsModel::DSCContentsModel(BinaryViewRef bv, QObject* parent) : QAbstractItemModel(parent), m_bv(bv)
{
	m_cache = new SharedCacheAPI::SharedCache(bv);
	refresh();
}

struct ItemNode
{
	ItemNode* parent = nullptr;
	std::string fullPath;
	std::string path;
	DSCContentsModelItem* assignedModelItem = nullptr;
	std::unordered_map<std::string, ItemNode*> edges {};
};

std::vector<std::string> split(std::string str, std::string token)
{
	std::vector<std::string> result;
	while (str.size())
	{
		int index = str.find(token);
		if (index != std::string::npos)
		{
			result.push_back(str.substr(0, index));
			str = str.substr(index + token.size());
			if (str.size() == 0)
				result.push_back(str);
		}
		else
		{
			result.push_back(str);
			str = "";
		}
	}
	return result;
}

void DSCContentsModel::refresh()
{
	std::scoped_lock<std::mutex> lock(m_updateMutex);

	// Using `{begin,end}ResetModel` here is not ideal and is a temporary
	// hack at best. Actual model indices should be updated. That requires
	// more work and will be implemented after more important things have
	// been taken care of.
	beginResetModel();

	auto inames = m_cache->GetAvailableImages();

	m_root = new DSCContentsModelItem();

	std::unordered_map<std::string, DSCContentsModelItem*> folders {};
	folders["/"] = m_root;
	for (const auto& iname : inames)
	{
		auto pathItems = split(iname, "/");
		pathItems.pop_back();  // skip filenames
		std::string fullPath = "/";

		for (const auto& item : pathItems)
		{
			if (item.empty())
				continue;
			auto parentPath = fullPath;
			fullPath += item + "/";
			if (folders.count(fullPath) == 0)
			{
				auto pnode = folders.at(parentPath);
				auto* nnode = new DSCContentsModelItem(m_bv, item, "", pnode);
				pnode->addChild(nnode);
				folders[fullPath] = nnode;
			}
		}
	}

	// Ok, all our folders are in place. Put files in them.

	for (const auto& iname : inames)
	{
		auto file = fs::path(iname).filename().string();
		auto folderName = fs::path(iname).parent_path().string() + "/";
		if (auto folder = folders.find(folderName); folder != folders.end())
		{
			auto* nnode = new DSCContentsModelItem(m_bv, file, iname, folder->second);
			folder->second->addChild(nnode);
		}
		else
			BNLogError("DSCView Sidebar Logic Error: Couldn't find folder for %s %s %s", iname.c_str(), file.c_str(),
				folderName.c_str());
	}

	endResetModel();
}

QModelIndex DSCContentsModel::index(int row, int column, const QModelIndex& parentIndex) const
{
	if (!hasIndex(row, column, parentIndex))
		return QModelIndex();

	// Use the parent index's item if it is valid, otherwise use the root.
	DSCContentsModelItem* parent = nullptr;
	if (parentIndex.isValid())
		parent = static_cast<DSCContentsModelItem*>(parentIndex.internalPointer());
	else
		parent = m_root;

	// If the child is found, create an index for it; use an invalid index otherwise.
	auto item = parent->child(row);
	if (item)
		return createIndex(row, column, item);

	return QModelIndex();
}

QModelIndex DSCContentsModel::parent(const QModelIndex& index) const
{
	if (!index.isValid())
		return QModelIndex();

	auto child = static_cast<DSCContentsModelItem*>(index.internalPointer());
	auto parent = child->parent();
	if (parent == m_root || parent == nullptr)
		return QModelIndex();

	return createIndex(parent->row(), 0, parent);
}

QVariant DSCContentsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
	{
		switch (section)
		{
		case DSCContentsModel::NameColumn:
			return "Name";
		default:
			return "";
		}
	}

	return QAbstractItemModel::headerData(section, orientation, role);
}

constexpr int ComponentGuidDataRole = 64;

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

	auto item = static_cast<DSCContentsModelItem*>(index.internalPointer());
	if (!item)
		return {};

	switch (role)
	{
	case Qt::DisplayRole:
		return item->data(index.column());
	default:
		return {};
	}
}

bool DSCContentsModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
	return false;
}

Qt::ItemFlags DSCContentsModel::flags(const QModelIndex& index) const
{
	if (!index.isValid())
		return Qt::ItemIsDropEnabled;  // Root node

	Qt::ItemFlags flags = QAbstractItemModel::flags(index);

	return flags;
}


int DSCContentsModel::rowCount(const QModelIndex& parent) const
{
	DSCContentsModelItem* item;
	if (!parent.isValid())
		item = m_root;
	else
		item = static_cast<DSCContentsModelItem*>(parent.internalPointer());

	return item->childCount();
}

int DSCContentsModel::columnCount(const QModelIndex& parent) const
{
	return 1;
}

Qt::DropActions DSCContentsModel::supportedDropActions() const
{
	return Qt::IgnoreAction;
}


//===-- ComponentFilterModel ----------------------------------------------===//

DSCFilterModel::DSCFilterModel(BinaryViewRef data, QObject* parent) :
	QSortFilterProxyModel(parent), m_model(new DSCContentsModel(data))
{
	setSourceModel(m_model);
}

bool DSCFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
	auto index = sourceModel()->index(sourceRow, 0, sourceParent);
	if (!index.isValid())
		return false;

	return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}

DSCSidebarView::DSCSidebarView(ViewFrame* frame, BinaryViewRef data, QWidget* parent) :
	QTreeView(parent), m_data(data), m_frame(frame), m_parent(parent)
{
	connect(this, &DSCSidebarView::doubleClicked, this, &DSCSidebarView::navigateToIndex);

	setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this, &DSCSidebarView::customContextMenuRequested, [this](const QPoint& p) {
		auto menu = createContextMenu();
		menu->popup(viewport()->mapToGlobal(p));
	});
}


void DSCSidebarView::navigateToIndex(const QModelIndex& index)
{
	auto filterParent = static_cast<DSCSidebarWidget*>(m_parent);
	if (!filterParent)
		return;
	auto modelItem = static_cast<DSCContentsModelItem*>(filterParent->m_model->mapToSource(index).internalPointer());

	if (modelItem->m_installName.empty())
		return;

	QMessageBox::StandardButton reply;
	reply = QMessageBox::question(this, "Load Image", "Load " + QString::fromStdString(modelItem->m_name) + "?",
		QMessageBox::Yes | QMessageBox::No);

	if (reply == QMessageBox::Yes)
	{
		SharedCacheAPI::SharedCache* cache = new SharedCacheAPI::SharedCache(m_data);
		cache->LoadImageWithInstallName(modelItem->m_installName);
		m_data->UpdateAnalysis();
	}
}

QMenu* DSCSidebarView::createContextMenu()
{
	auto menu = new QMenu();

	return menu;
}

//===-- ComponentTree -----------------------------------------------------===//

DSCSidebarWidget::DSCSidebarWidget(ViewFrame* frame, BinaryViewRef data) :
	SidebarWidget("dyld_shared_cache"), m_data(data), m_frame(frame), m_header(new QWidget)
{
	auto view = data;
	m_tree = new DSCSidebarView(frame, view, this);
	m_model = new DSCFilterModel(view);
	m_tree->setDragDropMode(QAbstractItemView::DragDrop);
	m_tree->setSelectionMode(QAbstractItemView::ExtendedSelection);
	m_tree->setDragEnabled(true);
	m_tree->setAcceptDrops(true);
	m_tree->setDropIndicatorShown(true);
	m_tree->header()->setSectionsMovable(false);

	m_tree->setModel(m_model);
	m_model->setRecursiveFilteringEnabled(true);

	m_filterEdit = new FilterEdit(this);
	m_filterView = new FilteredView(this, m_tree, this, m_filterEdit);
	m_filterView->setFilterPlaceholderText("Search Shared Cache Files");

	auto headerLayout = new QHBoxLayout(m_header);
	headerLayout->setContentsMargins(0, 0, 0, 0);
	headerLayout->addWidget(m_filterEdit);

	auto layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(m_filterView);
}

//===-- ComponentTree - FilterTarget --------------------------------------===//

void DSCSidebarWidget::setFilter(const std::string& filter)
{
	m_model->setFilterFixedString(QString::fromStdString(filter));
}

void DSCSidebarWidget::scrollToFirstItem() {}

void DSCSidebarWidget::scrollToCurrentItem() {}

void DSCSidebarWidget::selectFirstItem() {}

void DSCSidebarWidget::activateFirstItem() {}

//===-- DSCSidebarWidget - SidebarWidget -------------------------------------===//

QWidget* DSCSidebarWidget::headerWidget()
{
	return m_header;
}

void DSCSidebarWidget::focus() {}

QImage temporaryIcon()
{
	QImage icon(56, 56, QImage::Format_RGB32);
	icon.fill(0);

	QPainter p;
	p.begin(&icon);
	p.setFont({"Inter", 16});
	p.setPen({255, 255, 255, 255});
	p.drawText(QRectF {0, 0, 56, 56}, Qt::AlignCenter, "DSC");
	p.end();

	return icon;
}

DSCSidebarWidgetType::DSCSidebarWidgetType() : SidebarWidgetType(temporaryIcon(), "Shared Cache") {}

SidebarWidget* DSCSidebarWidgetType::createWidget(ViewFrame* frame, BinaryViewRef data)
{
	return new DSCSidebarWidget(frame, data);
}