File: file_utilities.cpp

package info (click to toggle)
telegram-desktop 4.6.5%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 53,300 kB
  • sloc: cpp: 605,857; python: 3,978; ansic: 1,636; sh: 965; makefile: 841; objc: 652; javascript: 187; xml: 165
file content (408 lines) | stat: -rw-r--r-- 10,535 bytes parent folder | download
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
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.

For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "core/file_utilities.h"

#include "boxes/abstract_box.h"
#include "storage/localstorage.h"
#include "storage/storage_account.h"
#include "base/platform/base_platform_info.h"
#include "base/platform/base_platform_file_utilities.h"
#include "platform/platform_file_utilities.h"
#include "core/application.h"
#include "base/unixtime.h"
#include "ui/delayed_activation.h"
#include "ui/chat/attach/attach_extensions.h"
#include "main/main_session.h"
#include "mainwindow.h"

#include <QtWidgets/QFileDialog>
#include <QtCore/QCoreApplication>
#include <QtCore/QStandardPaths>
#include <QtGui/QDesktopServices>

bool filedialogGetSaveFile(
		QPointer<QWidget> parent,
		QString &file,
		const QString &caption,
		const QString &filter,
		const QString &initialPath) {
	QStringList files;
	QByteArray remoteContent;
	Ui::PreventDelayedActivation();
	bool result = Platform::FileDialog::Get(
		parent,
		files,
		remoteContent,
		caption,
		filter,
		FileDialog::internal::Type::WriteFile,
		initialPath);
	file = files.isEmpty() ? QString() : files.at(0);
	return result;
}

bool filedialogGetSaveFile(
		QString &file,
		const QString &caption,
		const QString &filter,
		const QString &initialPath) {
	return filedialogGetSaveFile(
		Core::App().getFileDialogParent(),
		file,
		caption,
		filter,
		initialPath);
}

QString filedialogDefaultName(
		const QString &prefix,
		const QString &extension,
		const QString &path,
		bool skipExistance,
		TimeId fileTime) {
	auto directoryPath = path;
	if (directoryPath.isEmpty()) {
		if (cDialogLastPath().isEmpty()) {
			Platform::FileDialog::InitLastPath();
		}
		directoryPath = cDialogLastPath();
	}

	QString base;
	if (fileTime) {
		const auto date = base::unixtime::parse(fileTime);
		base = prefix + date.toString("_yyyy-MM-dd_HH-mm-ss");
	} else {
		struct tm tm;
		time_t t = time(NULL);
		mylocaltime(&tm, &t);

		const auto zero = QChar('0');
		base = prefix + u"_%1-%2-%3_%4-%5-%6"_q.arg(tm.tm_year + 1900).arg(tm.tm_mon + 1, 2, 10, zero).arg(tm.tm_mday, 2, 10, zero).arg(tm.tm_hour, 2, 10, zero).arg(tm.tm_min, 2, 10, zero).arg(tm.tm_sec, 2, 10, zero);
	}

	QString name;
	if (skipExistance) {
		name = base + extension;
	} else {
		QDir directory(directoryPath);
		const auto dir = directory.absolutePath();
		const auto nameBase = (dir.endsWith('/') ? dir : (dir + '/'))
			+ base;
		name = nameBase + extension;
		for (int i = 0; QFileInfo::exists(name); ++i) {
			name = nameBase + u" (%1)"_q.arg(i + 2) + extension;
		}
	}
	return name;
}

QString filedialogNextFilename(
		const QString &name,
		const QString &cur,
		const QString &path) {
	QDir directory(path.isEmpty() ? cDialogLastPath() : path);
	int32 extIndex = name.lastIndexOf('.');
	QString prefix = name, extension;
	if (extIndex >= 0) {
		extension = name.mid(extIndex);
		prefix = name.mid(0, extIndex);
	}
	const auto dir = directory.absolutePath();
	const auto nameBase = (dir.endsWith('/') ? dir : (dir + '/')) + prefix;
	auto result = nameBase + extension;
	for (int i = 0; result.toLower() != cur.toLower() && QFileInfo::exists(result); ++i) {
		result = nameBase + u" (%1)"_q.arg(i + 2) + extension;
	}
	return result;
}

namespace File {

void OpenUrl(const QString &url) {
	crl::on_main([=] {
		Ui::PreventDelayedActivation();
		Platform::File::UnsafeOpenUrl(url);
	});
}

void OpenEmailLink(const QString &email) {
	crl::on_main([=] {
		Ui::PreventDelayedActivation();
		Platform::File::UnsafeOpenEmailLink(email);
	});
}

void OpenWith(const QString &filepath) {
	InvokeQueued(QCoreApplication::instance(), [=] {
		if (!Platform::File::UnsafeShowOpenWithDropdown(filepath)) {
			Ui::PreventDelayedActivation();
			if (!Platform::File::UnsafeShowOpenWith(filepath)) {
				Platform::File::UnsafeLaunch(filepath);
			}
		}
	});
}

void Launch(const QString &filepath) {
	crl::on_main([=] {
		Ui::PreventDelayedActivation();
		Platform::File::UnsafeLaunch(filepath);
	});
}

void ShowInFolder(const QString &filepath) {
	crl::on_main([=] {
		Ui::PreventDelayedActivation();
		if (Platform::IsLinux()) {
			// Hide mediaview to make other apps visible.
			Core::App().hideMediaView();
		}
		base::Platform::ShowInFolder(filepath);
	});
}

QString DefaultDownloadPathFolder(not_null<Main::Session*> session) {
	return session->supportMode() ? u"Tsupport Desktop"_q : AppName.utf16();
}

QString DefaultDownloadPath(not_null<Main::Session*> session) {
	if (!Core::App().canReadDefaultDownloadPath()) {
		return session->local().tempDirectory();
	}
	return QStandardPaths::writableLocation(
		QStandardPaths::DownloadLocation)
		+ '/'
		+ DefaultDownloadPathFolder(session)
		+ '/';
}

namespace internal {

void UnsafeOpenUrlDefault(const QString &url) {
	QDesktopServices::openUrl(url);
}

void UnsafeOpenEmailLinkDefault(const QString &email) {
	auto url = QUrl(u"mailto:"_q + email);
	QDesktopServices::openUrl(url);
}

void UnsafeLaunchDefault(const QString &filepath) {
	QDesktopServices::openUrl(QUrl::fromLocalFile(filepath));
}

} // namespace internal
} // namespace File

namespace FileDialog {

void GetOpenPath(
		QPointer<QWidget> parent,
		const QString &caption,
		const QString &filter,
		Fn<void(OpenResult &&result)> callback,
		Fn<void()> failed) {
	InvokeQueued(QCoreApplication::instance(), [=] {
		auto files = QStringList();
		auto remoteContent = QByteArray();
		Ui::PreventDelayedActivation();
		const auto success = Platform::FileDialog::Get(
			parent,
			files,
			remoteContent,
			caption,
			filter,
			FileDialog::internal::Type::ReadFile);
		if (success
			&& ((!files.isEmpty() && !files[0].isEmpty())
				|| !remoteContent.isEmpty())) {
			if (callback) {
				auto result = OpenResult();
				if (!files.isEmpty() && !files[0].isEmpty()) {
					result.paths.push_back(files[0]);
				}
				result.remoteContent = remoteContent;
				callback(std::move(result));
			}
		} else if (failed) {
			failed();
		}
	});
}

void GetOpenPaths(
		QPointer<QWidget> parent,
		const QString &caption,
		const QString &filter,
		Fn<void(OpenResult &&result)> callback,
		Fn<void()> failed) {
	InvokeQueued(QCoreApplication::instance(), [=] {
		auto files = QStringList();
		auto remoteContent = QByteArray();
		Ui::PreventDelayedActivation();
		const auto success = Platform::FileDialog::Get(
			parent,
			files,
			remoteContent,
			caption,
			filter,
			FileDialog::internal::Type::ReadFiles);
		if (success && (!files.isEmpty() || !remoteContent.isEmpty())) {
			if (callback) {
				auto result = OpenResult();
				result.paths = files;
				result.remoteContent = remoteContent;
				callback(std::move(result));
			}
		} else if (failed) {
			failed();
		}
	});
}

void GetWritePath(
		QPointer<QWidget> parent,
		const QString &caption,
		const QString &filter,
		const QString &initialPath,
		Fn<void(QString &&result)> callback,
		Fn<void()> failed) {
	InvokeQueued(QCoreApplication::instance(), [=] {
		auto file = QString();
		if (filedialogGetSaveFile(parent, file, caption, filter, initialPath)) {
			if (callback) {
				callback(std::move(file));
			}
		} else if (failed) {
			failed();
		}
	});
}

void GetFolder(
		QPointer<QWidget> parent,
		const QString &caption,
		const QString &initialPath,
		Fn<void(QString &&result)> callback,
		Fn<void()> failed) {
	InvokeQueued(QCoreApplication::instance(), [=] {
		auto files = QStringList();
		auto remoteContent = QByteArray();
		Ui::PreventDelayedActivation();
		const auto success = Platform::FileDialog::Get(
			parent,
			files,
			remoteContent,
			caption,
			QString(),
			FileDialog::internal::Type::ReadFolder,
			initialPath);
		if (success && !files.isEmpty() && !files[0].isEmpty()) {
			if (callback) {
				callback(std::move(files[0]));
			}
		} else if (failed) {
			failed();
		}
	});
}

QString AllFilesFilter() {
#ifdef Q_OS_WIN
	return u"All files (*.*)"_q;
#else // Q_OS_WIN
	return u"All files (*)"_q;
#endif // Q_OS_WIN
}

QString ImagesFilter() {
	return u"Image files (*"_q + Ui::ImageExtensions().join(u" *"_q) + u")"_q;
}

QString AllOrImagesFilter() {
	return AllFilesFilter() + u";;"_q + ImagesFilter();
}

QString ImagesOrAllFilter() {
	return ImagesFilter() + u";;"_q + AllFilesFilter();
}

QString PhotoVideoFilesFilter() {
	return u"Image and Video Files (*.png *.jpg *.jpeg *.mp4 *.mov);;"_q
		+ AllFilesFilter();
}

const QString &Tmp() {
	static const auto tmp = u"tmp"_q;
	return tmp;
}

namespace internal {

void InitLastPathDefault() {
	cSetDialogLastPath(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
}

bool GetDefault(
		QPointer<QWidget> parent,
		QStringList &files,
		QByteArray &remoteContent,
		const QString &caption,
		const QString &filter,
		FileDialog::internal::Type type,
		QString startFile = QString()) {
	if (cDialogLastPath().isEmpty()) {
		Platform::FileDialog::InitLastPath();
	}

	remoteContent = QByteArray();
	if (startFile.isEmpty() || startFile.at(0) != '/') {
		startFile = cDialogLastPath() + '/' + startFile;
	}
	QString file;

	const auto resolvedParent = (parent && parent->window()->isVisible())
		? parent->window()
		: Core::App().getFileDialogParent();
	Core::App().notifyFileDialogShown(true);
	if (type == Type::ReadFiles) {
		files = QFileDialog::getOpenFileNames(resolvedParent, caption, startFile, filter);
		QString path = files.isEmpty() ? QString() : QFileInfo(files.back()).absoluteDir().absolutePath();
		if (!path.isEmpty() && path != cDialogLastPath()) {
			cSetDialogLastPath(path);
			Local::writeSettings();
		}
		return !files.isEmpty();
	} else if (type == Type::ReadFolder) {
		file = QFileDialog::getExistingDirectory(resolvedParent, caption, startFile);
	} else if (type == Type::WriteFile) {
		file = QFileDialog::getSaveFileName(resolvedParent, caption, startFile, filter);
	} else {
		file = QFileDialog::getOpenFileName(resolvedParent, caption, startFile, filter);
	}
	Core::App().notifyFileDialogShown(false);

	if (file.isEmpty()) {
		files = QStringList();
		return false;
	}
	if (type != Type::ReadFolder) {
		// Save last used directory for all queries except directory choosing.
		auto path = QFileInfo(file).absoluteDir().absolutePath();
		if (!path.isEmpty() && path != cDialogLastPath()) {
			cSetDialogLastPath(path);
			Local::writeSettings();
		}
	}
	files = QStringList(file);
	return true;
}

} // namespace internal
} // namespace FileDialog