2
0
mirror of https://github.com/telegramdesktop/tdesktop synced 2025-08-31 06:26:18 +00:00

Renamed / moved a bunch of files.

Next commit fixes the build.
This commit is contained in:
John Preston
2017-03-04 12:56:07 +03:00
parent 08167a6a91
commit b0dbe9d353
22 changed files with 83 additions and 83 deletions

View File

@@ -0,0 +1,660 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "pspecific.h"
#include "platform/linux/linux_libs.h"
#include "lang.h"
#include "application.h"
#include "mainwidget.h"
#include "mainwindow.h"
#include "platform/linux/file_utilities_linux.h"
#include "localstorage.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <cstdlib>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <iostream>
#include <qpa/qplatformnativeinterface.h>
using namespace Platform;
using Platform::File::internal::EscapeShell;
namespace {
class _PsEventFilter : public QAbstractNativeEventFilter {
public:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) {
//auto wnd = App::wnd();
//if (!wnd) return false;
return false;
}
};
_PsEventFilter *_psEventFilter = nullptr;
QRect _monitorRect;
auto _monitorLastGot = 0LL;
} // namespace
QRect psDesktopRect() {
auto tnow = getms();
if (tnow > _monitorLastGot + 1000LL || tnow < _monitorLastGot) {
_monitorLastGot = tnow;
_monitorRect = QApplication::desktop()->availableGeometry(App::wnd());
}
return _monitorRect;
}
void psShowOverAll(QWidget *w, bool canFocus) {
w->show();
}
void psBringToBack(QWidget *w) {
w->hide();
}
QAbstractNativeEventFilter *psNativeEventFilter() {
delete _psEventFilter;
_psEventFilter = new _PsEventFilter();
return _psEventFilter;
}
void psWriteDump() {
}
QString demanglestr(const QString &mangled) {
if (mangled.isEmpty()) return mangled;
QByteArray cmd = ("c++filt -n " + mangled).toUtf8();
FILE *f = popen(cmd.constData(), "r");
if (!f) return "BAD_SYMBOL_" + mangled;
QString result;
char buffer[4096] = { 0 };
while (!feof(f)) {
if (fgets(buffer, 4096, f) != NULL) {
result += buffer;
}
}
pclose(f);
return result.trimmed();
}
QStringList addr2linestr(uint64 *addresses, int count) {
QStringList result;
if (!count) return result;
result.reserve(count);
QByteArray cmd = "addr2line -e " + EscapeShell(QFile::encodeName(cExeDir() + cExeName()));
for (int i = 0; i < count; ++i) {
if (addresses[i]) {
cmd += qsl(" 0x%1").arg(addresses[i], 0, 16).toUtf8();
}
}
FILE *f = popen(cmd.constData(), "r");
QStringList addr2lineResult;
if (f) {
char buffer[4096] = {0};
while (!feof(f)) {
if (fgets(buffer, 4096, f) != NULL) {
addr2lineResult.push_back(QString::fromUtf8(buffer));
}
}
pclose(f);
}
for (int i = 0, j = 0; i < count; ++i) {
if (addresses[i]) {
if (j < addr2lineResult.size() && !addr2lineResult.at(j).isEmpty() && !addr2lineResult.at(j).startsWith(qstr("0x"))) {
QString res = addr2lineResult.at(j).trimmed();
if (int index = res.indexOf(qstr("/Telegram/"))) {
if (index > 0) {
res = res.mid(index + qstr("/Telegram/").size());
}
}
result.push_back(res);
} else {
result.push_back(QString());
}
++j;
} else {
result.push_back(QString());
}
}
return result;
}
QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) {
QString initial = QString::fromUtf8(crashdump), result;
QStringList lines = initial.split('\n');
result.reserve(initial.size());
int32 i = 0, l = lines.size();
while (i < l) {
uint64 addresses[1024] = { 0 };
for (; i < l; ++i) {
result.append(lines.at(i)).append('\n');
QString line = lines.at(i).trimmed();
if (line == qstr("Backtrace:")) {
++i;
break;
}
}
int32 start = i;
for (; i < l; ++i) {
QString line = lines.at(i).trimmed();
if (line.isEmpty()) break;
QRegularExpressionMatch m1 = QRegularExpression(qsl("^(.+)\\(([^+]+)\\+([^\\)]+)\\)\\[(.+)\\]$")).match(line);
QRegularExpressionMatch m2 = QRegularExpression(qsl("^(.+)\\[(.+)\\]$")).match(line);
QString addrstr = m1.hasMatch() ? m1.captured(4) : (m2.hasMatch() ? m2.captured(2) : QString());
if (!addrstr.isEmpty()) {
uint64 addr = addrstr.startsWith(qstr("0x")) ? addrstr.mid(2).toULongLong(0, 16) : addrstr.toULongLong();
if (addr > 1) {
addresses[i - start] = addr;
}
}
}
QStringList addr2line = addr2linestr(addresses, i - start);
for (i = start; i < l; ++i) {
QString line = lines.at(i).trimmed();
if (line.isEmpty()) break;
result.append(qsl("\n%1. ").arg(i - start));
if (line.startsWith(qstr("ERROR: "))) {
result.append(line).append('\n');
continue;
}
if (line == qstr("[0x1]")) {
result.append(qsl("(0x1 separator)\n"));
continue;
}
QRegularExpressionMatch m1 = QRegularExpression(qsl("^(.+)\\(([^+]*)\\+([^\\)]+)\\)(.+)$")).match(line);
QRegularExpressionMatch m2 = QRegularExpression(qsl("^(.+)\\[(.+)\\]$")).match(line);
if (!m1.hasMatch() && !m2.hasMatch()) {
result.append(qstr("BAD LINE: ")).append(line).append('\n');
continue;
}
if (m1.hasMatch()) {
result.append(demanglestr(m1.captured(2))).append(qsl(" + ")).append(m1.captured(3)).append(qsl(" [")).append(m1.captured(1)).append(qsl("] "));
if (!addr2line.at(i - start).isEmpty() && addr2line.at(i - start) != qsl("??:0")) {
result.append(qsl(" (")).append(addr2line.at(i - start)).append(qsl(")\n"));
} else {
result.append(m1.captured(4)).append(qsl(" (demangled)")).append('\n');
}
} else {
result.append('[').append(m2.captured(1)).append(']');
if (!addr2line.at(i - start).isEmpty() && addr2line.at(i - start) != qsl("??:0")) {
result.append(qsl(" (")).append(addr2line.at(i - start)).append(qsl(")\n"));
} else {
result.append(' ').append(m2.captured(2)).append('\n');
}
}
}
}
return result;
}
bool _removeDirectory(const QString &path) { // from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c
QByteArray pathRaw = QFile::encodeName(path);
DIR *d = opendir(pathRaw.constData());
if (!d) return false;
while (struct dirent *p = readdir(d)) {
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
QString fname = path + '/' + p->d_name;
QByteArray fnameRaw = QFile::encodeName(fname);
struct stat statbuf;
if (!stat(fnameRaw.constData(), &statbuf)) {
if (S_ISDIR(statbuf.st_mode)) {
if (!_removeDirectory(fname)) {
closedir(d);
return false;
}
} else {
if (unlink(fnameRaw.constData())) {
closedir(d);
return false;
}
}
}
}
closedir(d);
return !rmdir(pathRaw.constData());
}
void psDeleteDir(const QString &dir) {
_removeDirectory(dir);
}
namespace {
auto _lastUserAction = 0LL;
} // namespace
void psUserActionDone() {
_lastUserAction = getms(true);
}
bool psIdleSupported() {
return false;
}
TimeMs psIdleTime() {
return getms(true) - _lastUserAction;
}
void psActivateProcess(uint64 pid) {
// objc_activateProgram();
}
QString psCurrentCountry() {
QString country;// = objc_currentCountry();
return country.isEmpty() ? QString::fromLatin1(DefaultCountry) : country;
}
QString psCurrentLanguage() {
QString lng;// = objc_currentLang();
return lng.isEmpty() ? QString::fromLatin1(DefaultLanguage) : lng;
}
namespace {
QString getHomeDir() {
struct passwd *pw = getpwuid(getuid());
return (pw && pw->pw_dir && strlen(pw->pw_dir)) ? (QFile::decodeName(pw->pw_dir) + '/') : QString();
}
} // namespace
QString psAppDataPath() {
// Previously we used ~/.TelegramDesktop, so look there first.
// If we find data there, we should still use it.
auto home = getHomeDir();
if (!home.isEmpty()) {
auto oldPath = home + qsl(".TelegramDesktop/");
auto oldSettingsBase = oldPath + qsl("tdata/settings");
if (QFile(oldSettingsBase + '0').exists() || QFile(oldSettingsBase + '1').exists()) {
return oldPath;
}
}
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + '/';
}
QString psDownloadPath() {
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + '/' + str_const_toString(AppName) + '/';
}
QString psCurrentExeDirectory(int argc, char *argv[]) {
QString first = argc ? QFile::decodeName(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.isSymLink()) {
info = info.symLinkTarget();
}
if (info.exists()) {
return QDir(info.absolutePath()).absolutePath() + '/';
}
}
return QString();
}
QString psCurrentExeName(int argc, char *argv[]) {
QString first = argc ? QFile::decodeName(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.isSymLink()) {
info = info.symLinkTarget();
}
if (info.exists()) {
return info.fileName();
}
}
return QString();
}
void psDoCleanup() {
try {
psAutoStart(false, true);
psSendToMenu(false, true);
} catch (...) {
}
}
int psCleanup() {
psDoCleanup();
return 0;
}
void psDoFixPrevious() {
}
int psFixPrevious() {
psDoFixPrevious();
return 0;
}
namespace Platform {
void start() {
}
void finish() {
delete _psEventFilter;
_psEventFilter = nullptr;
}
void SetWatchingMediaKeys(bool watching) {
}
bool TransparentWindowsSupported(QPoint globalPosition) {
if (auto app = static_cast<QGuiApplication*>(QCoreApplication::instance())) {
if (auto native = app->platformNativeInterface()) {
if (auto desktop = QApplication::desktop()) {
auto index = desktop->screenNumber(globalPosition);
auto screens = QGuiApplication::screens();
if (auto screen = (index >= 0 && index < screens.size()) ? screens[index] : QGuiApplication::primaryScreen()) {
if (native->nativeResourceForScreen(QByteArray("compositingEnabled"), screen)) {
return true;
}
static OrderedSet<int> WarnedAbout;
if (!WarnedAbout.contains(index)) {
WarnedAbout.insert(index);
LOG(("WARNING: Compositing is disabled for screen index %1 (for position %2,%3)").arg(index).arg(globalPosition.x()).arg(globalPosition.y()));
}
} else {
LOG(("WARNING: Could not get screen for index %1 (for position %2,%3)").arg(index).arg(globalPosition.x()).arg(globalPosition.y()));
}
}
}
}
return false;
}
namespace ThirdParty {
void start() {
Libs::start();
MainWindow::LibsLoaded();
}
void finish() {
}
} // namespace ThirdParty
} // namespace Platform
namespace {
bool _psRunCommand(const QByteArray &command) {
int result = system(command.constData());
if (result) {
DEBUG_LOG(("App Error: command failed, code: %1, command (in utf8): %2").arg(result).arg(command.constData()));
return false;
}
DEBUG_LOG(("App Info: command succeeded, command (in utf8): %1").arg(command.constData()));
return true;
}
} // namespace
void psRegisterCustomScheme() {
#ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME
auto home = getHomeDir();
if (home.isEmpty() || cBetaVersion()) return; // don't update desktop file for beta version
#ifndef TDESKTOP_DISABLE_DESKTOP_FILE_GENERATION
DEBUG_LOG(("App Info: placing .desktop file"));
if (QDir(home + qsl(".local/")).exists()) {
QString apps = home + qsl(".local/share/applications/");
QString icons = home + qsl(".local/share/icons/");
if (!QDir(apps).exists()) QDir().mkpath(apps);
if (!QDir(icons).exists()) QDir().mkpath(icons);
QString path = cWorkingDir() + qsl("tdata/"), file = path + qsl("telegramdesktop.desktop");
QDir().mkpath(path);
QFile f(file);
if (f.open(QIODevice::WriteOnly)) {
QString icon = icons + qsl("telegram.png");
auto iconExists = QFile(icon).exists();
if (Local::oldSettingsVersion() < 10021 && iconExists) {
// Icon was changed.
if (QFile(icon).remove()) {
iconExists = false;
}
}
if (!iconExists) {
if (QFile(qsl(":/gui/art/icon256.png")).copy(icon)) {
DEBUG_LOG(("App Info: Icon copied to 'tdata'"));
}
}
QTextStream s(&f);
s.setCodec("UTF-8");
s << "[Desktop Entry]\n";
s << "Encoding=UTF-8\n";
s << "Version=1.0\n";
s << "Name=Telegram Desktop\n";
s << "Comment=Official desktop version of Telegram messaging app\n";
s << "Exec=" << EscapeShell(QFile::encodeName(cExeDir() + cExeName())) << " -- %u\n";
s << "Icon=telegram\n";
s << "Terminal=false\n";
s << "StartupWMClass=Telegram\n";
s << "Type=Application\n";
s << "Categories=Network;\n";
s << "MimeType=x-scheme-handler/tg;\n";
f.close();
if (_psRunCommand("desktop-file-install --dir=" + EscapeShell(QFile::encodeName(home + qsl(".local/share/applications"))) + " --delete-original " + EscapeShell(QFile::encodeName(file)))) {
DEBUG_LOG(("App Info: removing old .desktop file"));
QFile(qsl("%1.local/share/applications/telegram.desktop").arg(home)).remove();
_psRunCommand("update-desktop-database " + EscapeShell(QFile::encodeName(home + qsl(".local/share/applications"))));
_psRunCommand("xdg-mime default telegramdesktop.desktop x-scheme-handler/tg");
}
} else {
LOG(("App Error: Could not open '%1' for write").arg(file));
}
}
#endif // !TDESKTOP_DISABLE_DESKTOP_FILE_GENERATION
DEBUG_LOG(("App Info: registerting for Gnome"));
if (_psRunCommand("gconftool-2 -t string -s /desktop/gnome/url-handlers/tg/command " + EscapeShell(EscapeShell(QFile::encodeName(cExeDir() + cExeName())) + " -- %s"))) {
_psRunCommand("gconftool-2 -t bool -s /desktop/gnome/url-handlers/tg/needs_terminal false");
_psRunCommand("gconftool-2 -t bool -s /desktop/gnome/url-handlers/tg/enabled true");
}
DEBUG_LOG(("App Info: placing .protocol file"));
QString services;
if (QDir(home + qsl(".kde4/")).exists()) {
services = home + qsl(".kde4/share/kde4/services/");
} else if (QDir(home + qsl(".kde/")).exists()) {
services = home + qsl(".kde/share/kde4/services/");
}
if (!services.isEmpty()) {
if (!QDir(services).exists()) QDir().mkpath(services);
QString path = services, file = path + qsl("tg.protocol");
QFile f(file);
if (f.open(QIODevice::WriteOnly)) {
QTextStream s(&f);
s.setCodec("UTF-8");
s << "[Protocol]\n";
s << "exec=" << QFile::decodeName(EscapeShell(QFile::encodeName(cExeDir() + cExeName()))) << " -- %u\n";
s << "protocol=tg\n";
s << "input=none\n";
s << "output=none\n";
s << "helper=true\n";
s << "listing=false\n";
s << "reading=false\n";
s << "writing=false\n";
s << "makedir=false\n";
s << "deleting=false\n";
f.close();
} else {
LOG(("App Error: Could not open '%1' for write").arg(file));
}
}
#endif // !TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME
}
void psNewVersion() {
psRegisterCustomScheme();
}
bool _execUpdater(bool update = true, const QString &crashreport = QString()) {
static const int MaxLen = 65536, MaxArgsCount = 128;
char path[MaxLen] = {0};
QByteArray data(QFile::encodeName(cExeDir() + "Updater"));
memcpy(path, data.constData(), data.size());
char *args[MaxArgsCount] = {0}, p_noupdate[] = "-noupdate", p_autostart[] = "-autostart", p_debug[] = "-debug", p_tosettings[] = "-tosettings", p_key[] = "-key", p_path[] = "-workpath", p_startintray[] = "-startintray", p_testmode[] = "-testmode", p_crashreport[] = "-crashreport";
char p_datafile[MaxLen] = {0}, p_pathbuf[MaxLen] = {0}, p_crashreportbuf[MaxLen] = {0};
int argIndex = 0;
args[argIndex++] = path;
if (!update) {
args[argIndex++] = p_noupdate;
args[argIndex++] = p_tosettings;
}
if (cLaunchMode() == LaunchModeAutoStart) args[argIndex++] = p_autostart;
if (cDebug()) args[argIndex++] = p_debug;
if (cStartInTray()) args[argIndex++] = p_startintray;
if (cTestMode()) args[argIndex++] = p_testmode;
if (cDataFile() != qsl("data")) {
QByteArray dataf = QFile::encodeName(cDataFile());
if (dataf.size() < MaxLen) {
memcpy(p_datafile, dataf.constData(), dataf.size());
args[argIndex++] = p_key;
args[argIndex++] = p_datafile;
}
}
QByteArray pathf = QFile::encodeName(cWorkingDir());
if (pathf.size() < MaxLen) {
memcpy(p_pathbuf, pathf.constData(), pathf.size());
args[argIndex++] = p_path;
args[argIndex++] = p_pathbuf;
}
if (!crashreport.isEmpty()) {
QByteArray crashreportf = QFile::encodeName(crashreport);
if (crashreportf.size() < MaxLen) {
memcpy(p_crashreportbuf, crashreportf.constData(), crashreportf.size());
args[argIndex++] = p_crashreport;
args[argIndex++] = p_crashreportbuf;
}
}
Logs::closeMain();
SignalHandlers::finish();
pid_t pid = fork();
switch (pid) {
case -1: return false;
case 0: execv(path, args); return false;
}
return true;
}
void psExecUpdater() {
if (!_execUpdater()) {
psDeleteDir(cWorkingDir() + qsl("tupdates/temp"));
}
}
void psExecTelegram(const QString &crashreport) {
_execUpdater(false, crashreport);
}
bool psShowOpenWithMenu(int x, int y, const QString &file) {
return false;
}
void psAutoStart(bool start, bool silent) {
}
void psSendToMenu(bool send, bool silent) {
}
void psUpdateOverlayed(QWidget *widget) {
}
bool linuxMoveFile(const char *from, const char *to) {
FILE *ffrom = fopen(from, "rb"), *fto = fopen(to, "wb");
if (!ffrom) {
if (fto) fclose(fto);
return false;
}
if (!fto) {
fclose(ffrom);
return false;
}
static const int BufSize = 65536;
char buf[BufSize];
while (size_t size = fread(buf, 1, BufSize, ffrom)) {
fwrite(buf, 1, size, fto);
}
struct stat fst; // from http://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c
//let's say this wont fail since you already worked OK on that fp
if (fstat(fileno(ffrom), &fst) != 0) {
fclose(ffrom);
fclose(fto);
return false;
}
//update to the same uid/gid
if (fchown(fileno(fto), fst.st_uid, fst.st_gid) != 0) {
fclose(ffrom);
fclose(fto);
return false;
}
//update the permissions
if (fchmod(fileno(fto), fst.st_mode) != 0) {
fclose(ffrom);
fclose(fto);
return false;
}
fclose(ffrom);
fclose(fto);
if (unlink(from)) {
return false;
}
return true;
}
bool psLaunchMaps(const LocationCoords &coords) {
return false;
}

View File

@@ -0,0 +1,103 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include <execinfo.h>
#include <signal.h>
inline QString psServerPrefix() {
return qsl("/tmp/");
}
inline void psCheckLocalSocket(const QString &serverName) {
QFile address(serverName);
if (address.exists()) {
address.remove();
}
}
void psWriteDump();
QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile);
void psDeleteDir(const QString &dir);
void psUserActionDone();
bool psIdleSupported();
TimeMs psIdleTime();
QStringList psInitLogs();
void psClearInitLogs();
void psActivateProcess(uint64 pid = 0);
QString psLocalServerPrefix();
QString psCurrentCountry();
QString psCurrentLanguage();
QString psAppDataPath();
QString psDownloadPath();
QString psCurrentExeDirectory(int argc, char *argv[]);
QString psCurrentExeName(int argc, char *argv[]);
void psAutoStart(bool start, bool silent = false);
void psSendToMenu(bool send, bool silent = false);
QRect psDesktopRect();
void psShowOverAll(QWidget *w, bool canFocus = true);
void psBringToBack(QWidget *w);
int psCleanup();
int psFixPrevious();
void psExecUpdater();
void psExecTelegram(const QString &arg = QString());
QAbstractNativeEventFilter *psNativeEventFilter();
void psNewVersion();
void psUpdateOverlayed(QWidget *widget);
inline QByteArray psDownloadPathBookmark(const QString &path) {
return QByteArray();
}
inline QByteArray psPathBookmark(const QString &path) {
return QByteArray();
}
inline void psDownloadPathEnableAccess() {
}
class PsFileBookmark {
public:
PsFileBookmark(const QByteArray &bookmark) {
}
bool check() const {
return true;
}
bool enable() const {
return true;
}
void disable() const {
}
const QString &name(const QString &original) const {
return original;
}
QByteArray bookmark() const {
return QByteArray();
}
};
bool linuxMoveFile(const char *from, const char *to);
bool psLaunchMaps(const LocationCoords &coords);

View File

@@ -0,0 +1,471 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "pspecific.h"
#include "lang.h"
#include "application.h"
#include "mainwidget.h"
#include "historywidget.h"
#include "localstorage.h"
#include "passcodewidget.h"
#include "mainwindow.h"
#include "history/history_location_manager.h"
#include <execinfo.h>
namespace {
QStringList _initLogs;
class _PsEventFilter : public QAbstractNativeEventFilter {
public:
_PsEventFilter() {
}
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) {
auto wnd = App::wnd();
if (!wnd) return false;
return wnd->psFilterNativeEvent(message);
}
};
_PsEventFilter *_psEventFilter = nullptr;
};
namespace {
QRect _monitorRect;
TimeMs _monitorLastGot = 0;
} // namespace
QRect psDesktopRect() {
auto tnow = getms(true);
if (tnow > _monitorLastGot + 1000 || tnow < _monitorLastGot) {
_monitorLastGot = tnow;
_monitorRect = QApplication::desktop()->availableGeometry(App::wnd());
}
return _monitorRect;
}
void psShowOverAll(QWidget *w, bool canFocus) {
objc_showOverAll(w->winId(), canFocus);
}
void psBringToBack(QWidget *w) {
objc_bringToBack(w->winId());
}
QAbstractNativeEventFilter *psNativeEventFilter() {
delete _psEventFilter;
_psEventFilter = new _PsEventFilter();
return _psEventFilter;
}
void psWriteDump() {
double v = objc_appkitVersion();
SignalHandlers::dump() << "OS-Version: " << v;
}
QString demanglestr(const QString &mangled) {
QByteArray cmd = ("c++filt -n " + mangled).toUtf8();
FILE *f = popen(cmd.constData(), "r");
if (!f) return "BAD_SYMBOL_" + mangled;
QString result;
char buffer[4096] = {0};
while (!feof(f)) {
if (fgets(buffer, 4096, f) != NULL) {
result += buffer;
}
}
pclose(f);
return result.trimmed();
}
QString escapeShell(const QString &str) {
QString result;
const QChar *b = str.constData(), *e = str.constEnd();
for (const QChar *ch = b; ch != e; ++ch) {
if (*ch == ' ' || *ch == '"' || *ch == '\'' || *ch == '\\') {
if (result.isEmpty()) {
result.reserve(str.size() * 2);
}
if (ch > b) {
result.append(b, ch - b);
}
result.append('\\');
b = ch;
}
}
if (result.isEmpty()) return str;
if (e > b) {
result.append(b, e - b);
}
return result;
}
QStringList atosstr(uint64 *addresses, int count, uint64 base) {
QStringList result;
if (!count) return result;
result.reserve(count);
QString cmdstr = "atos -o " + escapeShell(cExeDir() + cExeName()) + qsl("/Contents/MacOS/Telegram -l 0x%1").arg(base, 0, 16);
for (int i = 0; i < count; ++i) {
if (addresses[i]) {
cmdstr += qsl(" 0x%1").arg(addresses[i], 0, 16);
}
}
QByteArray cmd = cmdstr.toUtf8();
FILE *f = popen(cmd.constData(), "r");
QStringList atosResult;
if (f) {
char buffer[4096] = {0};
while (!feof(f)) {
if (fgets(buffer, 4096, f) != NULL) {
atosResult.push_back(QString::fromUtf8(buffer));
}
}
pclose(f);
}
for (int i = 0, j = 0; i < count; ++i) {
if (addresses[i]) {
if (j < atosResult.size() && !atosResult.at(j).isEmpty() && !atosResult.at(j).startsWith(qstr("0x"))) {
result.push_back(atosResult.at(j).trimmed());
} else {
result.push_back(QString());
}
++j;
} else {
result.push_back(QString());
}
}
return result;
}
QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) {
QString initial = QString::fromUtf8(crashdump), result;
QStringList lines = initial.split('\n');
result.reserve(initial.size());
int32 i = 0, l = lines.size();
while (i < l) {
uint64 addresses[1024] = { 0 };
for (; i < l; ++i) {
result.append(lines.at(i)).append('\n');
QString line = lines.at(i).trimmed();
if (line == qstr("Base image addresses:")) {
++i;
break;
}
}
uint64 base = 0;
for (int32 start = i; i < l; ++i) {
QString line = lines.at(i).trimmed();
if (line.isEmpty()) break;
if (!base) {
QRegularExpressionMatch m = QRegularExpression(qsl("^\\d+ (\\d+) \\((.+)\\)")).match(line);
if (m.hasMatch()) {
if (uint64 address = m.captured(1).toULongLong()) {
if (m.captured(2).endsWith(qstr("Contents/MacOS/Telegram"))) {
base = address;
}
}
}
}
}
if (base) {
result.append(qsl("(base address read: 0x%1)\n").arg(base, 0, 16));
} else {
result.append(qsl("ERROR: base address not read!\n"));
}
for (; i < l; ++i) {
result.append(lines.at(i)).append('\n');
QString line = lines.at(i).trimmed();
if (line == qstr("Backtrace:")) {
++i;
break;
}
}
int32 start = i;
for (; i < l; ++i) {
QString line = lines.at(i).trimmed();
if (line.isEmpty()) break;
if (QRegularExpression(qsl("^\\d+")).match(line).hasMatch()) {
QStringList lst = line.split(' ', QString::SkipEmptyParts);
if (lst.size() > 2) {
uint64 addr = lst.at(2).startsWith(qstr("0x")) ? lst.at(2).mid(2).toULongLong(0, 16) : lst.at(2).toULongLong();
addresses[i - start] = addr;
}
}
}
QStringList atos = atosstr(addresses, i - start, base);
for (i = start; i < l; ++i) {
QString line = lines.at(i).trimmed();
if (line.isEmpty()) break;
if (!QRegularExpression(qsl("^\\d+")).match(line).hasMatch()) {
if (!lines.at(i).startsWith(qstr("ERROR: "))) {
result.append(qstr("BAD LINE: "));
}
result.append(line).append('\n');
continue;
}
QStringList lst = line.split(' ', QString::SkipEmptyParts);
result.append('\n').append(lst.at(0)).append(qsl(". "));
if (lst.size() < 3) {
result.append(qstr("BAD LINE: ")).append(line).append('\n');
continue;
}
if (lst.size() > 5 && lst.at(3) == qsl("0x0") && lst.at(4) == qsl("+") && lst.at(5) == qsl("1")) {
result.append(qsl("(0x1 separator)\n"));
continue;
}
if (i - start < atos.size()) {
if (!atos.at(i - start).isEmpty()) {
result.append(atos.at(i - start)).append('\n');
continue;
}
}
for (int j = 1, s = lst.size();;) {
if (lst.at(j).startsWith('_')) {
result.append(demanglestr(lst.at(j)));
if (++j < s) {
result.append(' ');
for (;;) {
result.append(lst.at(j));
if (++j < s) {
result.append(' ');
} else {
break;
}
}
}
break;
} else if (j > 2) {
result.append(lst.at(j));
}
if (++j < s) {
result.append(' ');
} else {
break;
}
}
result.append(qsl(" [demangled]")).append('\n');
}
}
return result;
}
void psDeleteDir(const QString &dir) {
objc_deleteDir(dir);
}
namespace {
auto _lastUserAction = 0LL;
} // namespace
void psUserActionDone() {
_lastUserAction = getms(true);
}
bool psIdleSupported() {
return objc_idleSupported();
}
TimeMs psIdleTime() {
auto idleTime = 0LL;
return objc_idleTime(idleTime) ? idleTime : (getms(true) - _lastUserAction);
}
QStringList psInitLogs() {
return _initLogs;
}
void psClearInitLogs() {
_initLogs = QStringList();
}
void psActivateProcess(uint64 pid) {
if (!pid) {
objc_activateProgram(App::wnd() ? App::wnd()->winId() : 0);
}
}
QString psCurrentCountry() {
QString country = objc_currentCountry();
return country.isEmpty() ? QString::fromLatin1(DefaultCountry) : country;
}
QString psCurrentLanguage() {
QString lng = objc_currentLang();
return lng.isEmpty() ? QString::fromLatin1(DefaultLanguage) : lng;
}
QString psAppDataPath() {
return objc_appDataPath();
}
QString psDownloadPath() {
return objc_downloadPath();
}
QString psCurrentExeDirectory(int argc, char *argv[]) {
QString first = argc ? fromUtf8Safe(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.exists()) {
return QDir(info.absolutePath() + qsl("/../../..")).absolutePath() + '/';
}
}
return QString();
}
QString psCurrentExeName(int argc, char *argv[]) {
QString first = argc ? fromUtf8Safe(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.exists()) {
return QDir(QDir(info.absolutePath() + qsl("/../..")).absolutePath()).dirName();
}
}
return QString();
}
void psDoCleanup() {
try {
psAutoStart(false, true);
psSendToMenu(false, true);
} catch (...) {
}
}
int psCleanup() {
psDoCleanup();
return 0;
}
void psDoFixPrevious() {
}
int psFixPrevious() {
psDoFixPrevious();
return 0;
}
namespace Platform {
void start() {
objc_start();
}
void finish() {
delete _psEventFilter;
_psEventFilter = nullptr;
objc_finish();
}
bool TransparentWindowsSupported(QPoint globalPosition) {
return true;
}
namespace ThirdParty {
void start() {
}
void finish() {
}
} // namespace ThirdParty
} // namespace Platform
void psNewVersion() {
objc_registerCustomScheme();
}
void psExecUpdater() {
if (!objc_execUpdater()) {
psDeleteDir(cWorkingDir() + qsl("tupdates/temp"));
}
}
void psExecTelegram(const QString &crashreport) {
objc_execTelegram(crashreport);
}
void psAutoStart(bool start, bool silent) {
}
void psSendToMenu(bool send, bool silent) {
}
void psUpdateOverlayed(QWidget *widget) {
}
void psDownloadPathEnableAccess() {
objc_downloadPathEnableAccess(Global::DownloadPathBookmark());
}
QByteArray psDownloadPathBookmark(const QString &path) {
return objc_downloadPathBookmark(path);
}
QByteArray psPathBookmark(const QString &path) {
return objc_pathBookmark(path);
}
bool psLaunchMaps(const LocationCoords &coords) {
return QDesktopServices::openUrl(qsl("https://maps.apple.com/?q=Point&z=16&ll=%1,%2").arg(coords.latAsString()).arg(coords.lonAsString()));
}
QString strNotificationAboutThemeChange() {
const uint32 letters[] = { 0xE9005541, 0x5600DC70, 0x88001570, 0xF500D86C, 0x8100E165, 0xEE005949, 0x2900526E, 0xAE00FB74, 0x96000865, 0x7000CD72, 0x3B001566, 0x5F007361, 0xAE00B663, 0x74009A65, 0x29003054, 0xC6002668, 0x98003865, 0xFA00336D, 0xA3007A65, 0x93001443, 0xBB007868, 0xE100E561, 0x3500366E, 0xC0007A67, 0x0200CA65, 0xBE00DF64, 0xE300BB4E, 0x2900D26F, 0xD500D374, 0xE900E269, 0x86008F66, 0xC4006669, 0x1C00A863, 0xE600A761, 0x8E00EE74, 0xB300B169, 0xCF00B36F, 0xE600D36E };
return strMakeFromLetters(letters);
}
QString strNotificationAboutScreenLocked() {
const uint32 letters[] = { 0x22008263, 0x0800DB6F, 0x45004F6D, 0xCC00972E, 0x0E00A861, 0x9700D970, 0xA100D570, 0x8900686C, 0xB300B365, 0xFE00DE2E, 0x76009B73, 0xFA00BF63, 0xE000A772, 0x9C009F65, 0x4E006065, 0xD900426E, 0xB7007849, 0x64006473, 0x6700824C, 0xE300706F, 0x7C00A063, 0x8F00D76B, 0x04001C65, 0x1C00A664 };
return strMakeFromLetters(letters);
}
QString strNotificationAboutScreenUnlocked() {
const uint32 letters[] = { 0x9200D763, 0xC8003C6F, 0xD2003F6D, 0x6000012E, 0x36004061, 0x4400E570, 0xA500BF70, 0x2E00796C, 0x4A009E65, 0x2E00612E, 0xC8001D73, 0x57002263, 0xF0005872, 0x49000765, 0xE5008D65, 0xE600D76E, 0xE8007049, 0x19005C73, 0x34009455, 0xB800B36E, 0xF300CA6C, 0x4C00806F, 0x5300A763, 0xD1003B6B, 0x63003565, 0xF800F264 };
return strMakeFromLetters(letters);
}
QString strStyleOfInterface() {
const uint32 letters[] = { 0xEF004041, 0x4C007F70, 0x1F007A70, 0x9E00A76C, 0x8500D165, 0x2E003749, 0x7B00526E, 0x3400E774, 0x3C00FA65, 0x6200B172, 0xF7001D66, 0x0B002961, 0x71008C63, 0x86005465, 0xA3006F53, 0x11006174, 0xCD001779, 0x8200556C, 0x6C009B65 };
return strMakeFromLetters(letters);
}

View File

@@ -0,0 +1,111 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include "pspecific_mac_p.h"
inline QString psServerPrefix() {
#ifndef OS_MAC_STORE
return qsl("/tmp/");
#else // OS_MAC_STORE
return objc_documentsPath();
#endif // OS_MAC_STORE
}
inline void psCheckLocalSocket(const QString &serverName) {
QFile address(serverName);
if (address.exists()) {
address.remove();
}
}
void psWriteDump();
QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile);
void psDeleteDir(const QString &dir);
void psUserActionDone();
bool psIdleSupported();
TimeMs psIdleTime();
QStringList psInitLogs();
void psClearInitLogs();
void psActivateProcess(uint64 pid = 0);
QString psLocalServerPrefix();
QString psCurrentCountry();
QString psCurrentLanguage();
QString psAppDataPath();
QString psDownloadPath();
QString psCurrentExeDirectory(int argc, char *argv[]);
QString psCurrentExeName(int argc, char *argv[]);
void psAutoStart(bool start, bool silent = false);
void psSendToMenu(bool send, bool silent = false);
QRect psDesktopRect();
void psShowOverAll(QWidget *w, bool canFocus = true);
void psBringToBack(QWidget *w);
int psCleanup();
int psFixPrevious();
void psExecUpdater();
void psExecTelegram(const QString &crashreport = QString());
bool psShowOpenWithMenu(int x, int y, const QString &file);
QAbstractNativeEventFilter *psNativeEventFilter();
void psNewVersion();
void psUpdateOverlayed(QWidget *widget);
void psDownloadPathEnableAccess();
QByteArray psDownloadPathBookmark(const QString &path);
QByteArray psPathBookmark(const QString &path);
class PsFileBookmark {
public:
PsFileBookmark(const QByteArray &bookmark) : _inner(bookmark) {
}
bool check() const {
return _inner.valid();
}
bool enable() const {
return _inner.enable();
}
void disable() const {
return _inner.disable();
}
const QString &name(const QString &original) const {
return _inner.name(original);
}
QByteArray bookmark() const {
return _inner.bookmark();
}
private:
objc_FileBookmark _inner;
};
QString strNotificationAboutThemeChange();
QString strNotificationAboutScreenLocked();
QString strNotificationAboutScreenUnlocked();
QString strStyleOfInterface();
bool psLaunchMaps(const LocationCoords &coords);

View File

@@ -0,0 +1,74 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
// e is NSEvent*
bool objc_handleMediaKeyEvent(void *e);
void objc_holdOnTop(WId winId);
bool objc_darkMode();
void objc_showOverAll(WId winId, bool canFocus = true);
void objc_bringToBack(WId winId);
void objc_activateWnd(WId winId);
void objc_debugShowAlert(const QString &str);
void objc_outputDebugString(const QString &str);
bool objc_idleSupported();
bool objc_idleTime(TimeMs &idleTime);
void objc_start();
void objc_finish();
bool objc_execUpdater();
void objc_execTelegram(const QString &crashreport);
void objc_registerCustomScheme();
void objc_activateProgram(WId winId);
bool objc_moveFile(const QString &from, const QString &to);
void objc_deleteDir(const QString &dir);
double objc_appkitVersion();
QString objc_documentsPath();
QString objc_appDataPath();
QString objc_downloadPath();
QString objc_currentCountry();
QString objc_currentLang();
QByteArray objc_downloadPathBookmark(const QString &path);
QByteArray objc_pathBookmark(const QString &path);
void objc_downloadPathEnableAccess(const QByteArray &bookmark);
class objc_FileBookmark {
public:
objc_FileBookmark(const QByteArray &bookmark);
bool valid() const;
bool enable() const;
void disable() const;
const QString &name(const QString &original) const;
QByteArray bookmark() const;
~objc_FileBookmark();
private:
#ifdef OS_MAC_STORE
class objc_FileBookmarkData;
objc_FileBookmarkData *data = nullptr;
#endif // OS_MAC_STORE
};

View File

@@ -0,0 +1,647 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#include "pspecific_mac_p.h"
#include "mainwindow.h"
#include "mainwidget.h"
#include "messenger.h"
#include "localstorage.h"
#include "media/player/media_player_instance.h"
#include "media/media_audio.h"
#include "platform/mac/mac_utilities.h"
#include "styles/style_window.h"
#include "lang.h"
#include <Cocoa/Cocoa.h>
#include <CoreFoundation/CFURL.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hidsystem/ev_keymap.h>
#include <SPMediaKeyTap.h>
using Platform::Q2NSString;
using Platform::NSlang;
using Platform::NS2QString;
@interface qVisualize : NSObject {
}
+ (id)str:(const QString &)str;
- (id)initWithString:(const QString &)str;
+ (id)bytearr:(const QByteArray &)arr;
- (id)initWithByteArray:(const QByteArray &)arr;
- (id)debugQuickLookObject;
@end
@implementation qVisualize {
NSString *value;
}
+ (id)bytearr:(const QByteArray &)arr {
return [[qVisualize alloc] initWithByteArray:arr];
}
- (id)initWithByteArray:(const QByteArray &)arr {
if (self = [super init]) {
value = [NSString stringWithUTF8String:arr.constData()];
}
return self;
}
+ (id)str:(const QString &)str {
return [[qVisualize alloc] initWithString:str];
}
- (id)initWithString:(const QString &)str {
if (self = [super init]) {
value = [NSString stringWithUTF8String:str.toUtf8().constData()];
}
return self;
}
- (id)debugQuickLookObject {
return value;
}
@end
@interface ApplicationDelegate : NSObject<NSApplicationDelegate> {
SPMediaKeyTap *keyTap;
BOOL watchingMediaKeys;
}
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
- (void)applicationDidBecomeActive:(NSNotification *)aNotification;
- (void)receiveWakeNote:(NSNotification*)note;
- (void)setWatchingMediaKeys:(BOOL)watching;
- (BOOL)isWatchingMediaKeys;
- (void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event;
@end
ApplicationDelegate *_sharedDelegate = nil;
@implementation ApplicationDelegate {
}
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag {
if (App::wnd() && App::wnd()->isHidden()) App::wnd()->showFromTray();
return YES;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
keyTap = nullptr;
watchingMediaKeys = false;
#ifndef OS_MAC_STORE
if ([SPMediaKeyTap usesGlobalMediaKeyTap]) {
keyTap = [[SPMediaKeyTap alloc] initWithDelegate:self];
} else {
LOG(("Media key monitoring disabled"));
}
#endif // else for !OS_MAC_STORE
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification {
if (auto messenger = Messenger::InstancePointer()) {
messenger->handleAppActivated();
if (auto window = App::wnd()) {
if (window->isHidden()) {
window->showFromTray();
}
}
}
}
- (void)receiveWakeNote:(NSNotification*)aNotification {
if (auto messenger = Messenger::InstancePointer()) {
messenger->checkLocalTime();
}
LOG(("Audio Info: -receiveWakeNote: received, scheduling detach from audio device"));
Media::Player::DetachFromDeviceByTimer();
}
- (void)setWatchingMediaKeys:(BOOL)watching {
if (watchingMediaKeys != watching) {
watchingMediaKeys = watching;
if (keyTap) {
#ifndef OS_MAC_STORE
if (watchingMediaKeys) {
[keyTap startWatchingMediaKeys];
} else {
[keyTap stopWatchingMediaKeys];
}
#endif // else for !OS_MAC_STORE
}
}
}
- (BOOL)isWatchingMediaKeys {
return watchingMediaKeys;
}
- (void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)e {
if (e && [e type] == NSSystemDefined && [e subtype] == SPSystemDefinedEventMediaKeys) {
objc_handleMediaKeyEvent(e);
}
}
@end
namespace Platform {
void SetWatchingMediaKeys(bool watching) {
if (_sharedDelegate) {
[_sharedDelegate setWatchingMediaKeys:(watching ? YES : NO)];
}
}
} // namespace Platform
void objc_holdOnTop(WId winId) {
NSWindow *wnd = [reinterpret_cast<NSView *>(winId) window];
[wnd setHidesOnDeactivate:NO];
}
bool objc_darkMode() {
bool result = false;
@autoreleasepool {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] persistentDomainForName:NSGlobalDomain];
id style = [dict objectForKey:Q2NSString(strStyleOfInterface())];
BOOL darkModeOn = (style && [style isKindOfClass:[NSString class]] && NSOrderedSame == [style caseInsensitiveCompare:@"dark"]);
result = darkModeOn ? true : false;
}
return result;
}
void objc_showOverAll(WId winId, bool canFocus) {
NSWindow *wnd = [reinterpret_cast<NSView *>(winId) window];
[wnd setLevel:NSPopUpMenuWindowLevel];
if (!canFocus) {
[wnd setStyleMask:NSUtilityWindowMask | NSNonactivatingPanelMask];
[wnd setCollectionBehavior:NSWindowCollectionBehaviorMoveToActiveSpace|NSWindowCollectionBehaviorStationary|NSWindowCollectionBehaviorFullScreenAuxiliary|NSWindowCollectionBehaviorIgnoresCycle];
}
}
void objc_bringToBack(WId winId) {
NSWindow *wnd = [reinterpret_cast<NSView *>(winId) window];
[wnd setLevel:NSModalPanelWindowLevel];
}
void objc_activateWnd(WId winId) {
NSWindow *wnd = [reinterpret_cast<NSView *>(winId) window];
[wnd orderFront:wnd];
}
bool objc_handleMediaKeyEvent(void *ev) {
auto e = reinterpret_cast<NSEvent*>(ev);
int keyCode = (([e data1] & 0xFFFF0000) >> 16);
int keyFlags = ([e data1] & 0x0000FFFF);
int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
int keyRepeat = (keyFlags & 0x1);
if (!_sharedDelegate || ![_sharedDelegate isWatchingMediaKeys]) {
return false;
}
switch (keyCode) {
case NX_KEYTYPE_PLAY:
if (keyState == 0) { // Play pressed and released
Media::Player::instance()->playPause();
return true;
}
break;
case NX_KEYTYPE_FAST:
if (keyState == 0) { // Next pressed and released
Media::Player::instance()->next();
return true;
}
break;
case NX_KEYTYPE_REWIND:
if (keyState == 0) { // Previous pressed and released
Media::Player::instance()->previous();
return true;
}
break;
}
return false;
}
void objc_debugShowAlert(const QString &str) {
@autoreleasepool {
[[NSAlert alertWithMessageText:@"Debug Message" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@", Q2NSString(str)] runModal];
}
}
void objc_outputDebugString(const QString &str) {
@autoreleasepool {
NSLog(@"%@", Q2NSString(str));
}
}
bool objc_idleSupported() {
auto idleTime = 0LL;
return objc_idleTime(idleTime);
}
bool objc_idleTime(TimeMs &idleTime) { // taken from https://github.com/trueinteractions/tint/issues/53
CFMutableDictionaryRef properties = 0;
CFTypeRef obj;
mach_port_t masterPort;
io_iterator_t iter;
io_registry_entry_t curObj;
IOMasterPort(MACH_PORT_NULL, &masterPort);
/* Get IOHIDSystem */
IOServiceGetMatchingServices(masterPort, IOServiceMatching("IOHIDSystem"), &iter);
if (iter == 0) {
return false;
} else {
curObj = IOIteratorNext(iter);
}
if (IORegistryEntryCreateCFProperties(curObj, &properties, kCFAllocatorDefault, 0) == KERN_SUCCESS && properties != NULL) {
obj = CFDictionaryGetValue(properties, CFSTR("HIDIdleTime"));
CFRetain(obj);
} else {
return false;
}
uint64 err = ~0L, result = err;
if (obj) {
CFTypeID type = CFGetTypeID(obj);
if (type == CFDataGetTypeID()) {
CFDataGetBytes((CFDataRef) obj, CFRangeMake(0, sizeof(result)), (UInt8*)&result);
} else if (type == CFNumberGetTypeID()) {
CFNumberGetValue((CFNumberRef)obj, kCFNumberSInt64Type, &result);
} else {
// error
}
CFRelease(obj);
if (result != err) {
result /= 1000000; // return as ms
}
} else {
// error
}
CFRelease((CFTypeRef)properties);
IOObjectRelease(curObj);
IOObjectRelease(iter);
if (result == err) return false;
idleTime = static_cast<TimeMs>(result);
return true;
}
void objc_start() {
_sharedDelegate = [[ApplicationDelegate alloc] init];
[[NSApplication sharedApplication] setDelegate:_sharedDelegate];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: _sharedDelegate
selector: @selector(receiveWakeNote:)
name: NSWorkspaceDidWakeNotification object: NULL];
}
namespace {
NSURL *_downloadPathUrl = nil;
}
void objc_finish() {
[_sharedDelegate release];
if (_downloadPathUrl) {
[_downloadPathUrl stopAccessingSecurityScopedResource];
_downloadPathUrl = nil;
}
}
void objc_registerCustomScheme() {
#ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME
OSStatus result = LSSetDefaultHandlerForURLScheme(CFSTR("tg"), (CFStringRef)[[NSBundle mainBundle] bundleIdentifier]);
DEBUG_LOG(("App Info: set default handler for 'tg' scheme result: %1").arg(result));
#endif // !TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME
}
BOOL _execUpdater(BOOL update = YES, const QString &crashreport = QString()) {
@autoreleasepool {
NSString *path = @"", *args = @"";
@try {
path = [[NSBundle mainBundle] bundlePath];
if (!path) {
LOG(("Could not get bundle path!!"));
return NO;
}
path = [path stringByAppendingString:@"/Contents/Frameworks/Updater"];
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:@"-workpath", Q2NSString(cWorkingDir()), @"-procid", nil];
[args addObject:[NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]]];
if (cRestartingToSettings()) [args addObject:@"-tosettings"];
if (!update) [args addObject:@"-noupdate"];
if (cLaunchMode() == LaunchModeAutoStart) [args addObject:@"-autostart"];
if (cDebug()) [args addObject:@"-debug"];
if (cStartInTray()) [args addObject:@"-startintray"];
if (cTestMode()) [args addObject:@"-testmode"];
if (cDataFile() != qsl("data")) {
[args addObject:@"-key"];
[args addObject:Q2NSString(cDataFile())];
}
if (!crashreport.isEmpty()) {
[args addObject:@"-crashreport"];
[args addObject:Q2NSString(crashreport)];
}
DEBUG_LOG(("Application Info: executing %1 %2").arg(NS2QString(path)).arg(NS2QString([args componentsJoinedByString:@" "])));
Logs::closeMain();
SignalHandlers::finish();
if (![NSTask launchedTaskWithLaunchPath:path arguments:args]) {
DEBUG_LOG(("Task not launched while executing %1 %2").arg(NS2QString(path)).arg(NS2QString([args componentsJoinedByString:@" "])));
return NO;
}
}
@catch (NSException *exception) {
LOG(("Exception caught while executing %1 %2").arg(NS2QString(path)).arg(NS2QString(args)));
return NO;
}
@finally {
}
}
return YES;
}
bool objc_execUpdater() {
return !!_execUpdater();
}
void objc_execTelegram(const QString &crashreport) {
#ifndef OS_MAC_STORE
_execUpdater(NO, crashreport);
#else // OS_MAC_STORE
@autoreleasepool {
NSDictionary *conf = [NSDictionary dictionaryWithObject:[NSArray array] forKey:NSWorkspaceLaunchConfigurationArguments];
[[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:Q2NSString(cExeDir() + cExeName())] options:NSWorkspaceLaunchAsync | NSWorkspaceLaunchNewInstance configuration:conf error:0];
}
#endif // OS_MAC_STORE
}
void objc_activateProgram(WId winId) {
[NSApp activateIgnoringOtherApps:YES];
if (winId) {
NSWindow *w = [reinterpret_cast<NSView*>(winId) window];
[w makeKeyAndOrderFront:NSApp];
}
}
bool objc_moveFile(const QString &from, const QString &to) {
@autoreleasepool {
NSString *f = Q2NSString(from), *t = Q2NSString(to);
if ([[NSFileManager defaultManager] fileExistsAtPath:t]) {
NSData *data = [NSData dataWithContentsOfFile:f];
if (data) {
if ([data writeToFile:t atomically:YES]) {
if ([[NSFileManager defaultManager] removeItemAtPath:f error:nil]) {
return true;
}
}
}
} else {
if ([[NSFileManager defaultManager] moveItemAtPath:f toPath:t error:nil]) {
return true;
}
}
}
return false;
}
void objc_deleteDir(const QString &dir) {
@autoreleasepool {
[[NSFileManager defaultManager] removeItemAtPath:Q2NSString(dir) error:nil];
}
}
double objc_appkitVersion() {
return NSAppKitVersionNumber;
}
QString objc_documentsPath() {
NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
if (url) {
return QString::fromUtf8([[url path] fileSystemRepresentation]) + '/';
}
return QString();
}
QString objc_appDataPath() {
NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
if (url) {
return QString::fromUtf8([[url path] fileSystemRepresentation]) + '/' + str_const_toString(AppName) + '/';
}
return QString();
}
QString objc_downloadPath() {
NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSDownloadsDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
if (url) {
return QString::fromUtf8([[url path] fileSystemRepresentation]) + '/' + str_const_toString(AppName) + '/';
}
return QString();
}
QString objc_currentCountry() {
NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale.
NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
return countryCode ? NS2QString(countryCode) : QString();
}
QString objc_currentLang() {
NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale.
NSString *currentLang = [currentLocale objectForKey:NSLocaleLanguageCode];
return currentLang ? NS2QString(currentLang) : QString();
}
QByteArray objc_downloadPathBookmark(const QString &path) {
#ifndef OS_MAC_STORE
return QByteArray();
#else // OS_MAC_STORE
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path.toUtf8().constData()] isDirectory:YES];
if (!url) return QByteArray();
NSError *error = nil;
NSData *data = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
return data ? QByteArray::fromNSData(data) : QByteArray();
#endif // OS_MAC_STORE
}
QByteArray objc_pathBookmark(const QString &path) {
#ifndef OS_MAC_STORE
return QByteArray();
#else // OS_MAC_STORE
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path.toUtf8().constData()]];
if (!url) return QByteArray();
NSError *error = nil;
NSData *data = [url bookmarkDataWithOptions:(NSURLBookmarkCreationWithSecurityScope | NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess) includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
return data ? QByteArray::fromNSData(data) : QByteArray();
#endif // OS_MAC_STORE
}
void objc_downloadPathEnableAccess(const QByteArray &bookmark) {
#ifdef OS_MAC_STORE
if (bookmark.isEmpty()) return;
BOOL isStale = NO;
NSError *error = nil;
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark.toNSData() options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
if (!url) return;
if ([url startAccessingSecurityScopedResource]) {
if (_downloadPathUrl) {
[_downloadPathUrl stopAccessingSecurityScopedResource];
}
_downloadPathUrl = url;
Global::SetDownloadPath(NS2QString([_downloadPathUrl path]) + '/');
if (isStale) {
NSData *data = [_downloadPathUrl bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
if (data) {
Global::SetDownloadPathBookmark(QByteArray::fromNSData(data));
Local::writeUserSettings();
}
}
}
#endif // OS_MAC_STORE
}
#ifdef OS_MAC_STORE
namespace {
QMutex _bookmarksMutex;
}
class objc_FileBookmark::objc_FileBookmarkData {
public:
~objc_FileBookmarkData() {
if (url) [url release];
}
NSURL *url = nil;
QString name;
QByteArray bookmark;
int counter = 0;
};
#endif // OS_MAC_STORE
objc_FileBookmark::objc_FileBookmark(const QByteArray &bookmark) {
#ifdef OS_MAC_STORE
if (bookmark.isEmpty()) return;
BOOL isStale = NO;
NSError *error = nil;
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark.toNSData() options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
if (!url) return;
if ([url startAccessingSecurityScopedResource]) {
data = new objc_FileBookmarkData();
data->url = [url retain];
data->name = NS2QString([url path]);
data->bookmark = bookmark;
[url stopAccessingSecurityScopedResource];
}
#endif // OS_MAC_STORE
}
bool objc_FileBookmark::valid() const {
if (enable()) {
disable();
return true;
}
return false;
}
bool objc_FileBookmark::enable() const {
#ifndef OS_MAC_STORE
return true;
#else // OS_MAC_STORE
if (!data) return false;
QMutexLocker lock(&_bookmarksMutex);
if (data->counter > 0 || [data->url startAccessingSecurityScopedResource] == YES) {
++data->counter;
return true;
}
return false;
#endif // OS_MAC_STORE
}
void objc_FileBookmark::disable() const {
#ifdef OS_MAC_STORE
if (!data) return;
QMutexLocker lock(&_bookmarksMutex);
if (data->counter > 0) {
--data->counter;
if (!data->counter) {
[data->url stopAccessingSecurityScopedResource];
}
}
#endif // OS_MAC_STORE
}
const QString &objc_FileBookmark::name(const QString &original) const {
#ifndef OS_MAC_STORE
return original;
#else // OS_MAC_STORE
return (data && !data->name.isEmpty()) ? data->name : original;
#endif // OS_MAC_STORE
}
QByteArray objc_FileBookmark::bookmark() const {
#ifndef OS_MAC_STORE
return QByteArray();
#else // OS_MAC_STORE
return data ? data->bookmark : QByteArray();
#endif // OS_MAC_STORE
}
objc_FileBookmark::~objc_FileBookmark() {
#ifdef OS_MAC_STORE
if (data && data->counter > 0) {
LOG(("Did not disable() bookmark, counter: %1").arg(data->counter));
[data->url stopAccessingSecurityScopedResource];
}
#endif // OS_MAC_STORE
}

View File

@@ -0,0 +1,45 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#ifdef Q_OS_MAC
#include "pspecific_mac.h"
#elif defined Q_OS_LINUX // Q_OS_MAC
#include "pspecific_linux.h"
#elif defined Q_OS_WIN // Q_OS_MAC || Q_OS_LINUX
#include "pspecific_win.h"
#endif // Q_OS_MAC || Q_OS_LINUX || Q_OS_WIN
namespace Platform {
void start();
void finish();
void SetWatchingMediaKeys(bool watching);
bool TransparentWindowsSupported(QPoint globalPosition);
namespace ThirdParty {
void start();
void finish();
} // namespace ThirdParty
} // namespace Platform

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,101 @@
/*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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, either version 3 of the License, or
(at your option) any later version.
It 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.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
*/
#pragma once
#include <windows.h>
inline QString psServerPrefix() {
return qsl("Global\\");
}
inline void psCheckLocalSocket(const QString &) {
}
void psWriteDump();
void psWriteStackTrace();
QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile);
void psDeleteDir(const QString &dir);
void psUserActionDone();
bool psIdleSupported();
TimeMs psIdleTime();
QStringList psInitLogs();
void psClearInitLogs();
void psActivateProcess(uint64 pid = 0);
QString psLocalServerPrefix();
QString psCurrentCountry();
QString psCurrentLanguage();
QString psAppDataPath();
QString psAppDataPathOld();
QString psDownloadPath();
QString psCurrentExeDirectory(int argc, char *argv[]);
QString psCurrentExeName(int argc, char *argv[]);
void psAutoStart(bool start, bool silent = false);
void psSendToMenu(bool send, bool silent = false);
QRect psDesktopRect();
void psShowOverAll(QWidget *w, bool canFocus = true);
void psBringToBack(QWidget *w);
int psCleanup();
int psFixPrevious();
void psExecUpdater();
void psExecTelegram(const QString &arg = QString());
QAbstractNativeEventFilter *psNativeEventFilter();
void psNewVersion();
void psUpdateOverlayed(TWidget *widget);
inline QByteArray psDownloadPathBookmark(const QString &path) {
return QByteArray();
}
inline QByteArray psPathBookmark(const QString &path) {
return QByteArray();
}
inline void psDownloadPathEnableAccess() {
}
class PsFileBookmark {
public:
PsFileBookmark(const QByteArray &bookmark) {
}
bool check() const {
return true;
}
bool enable() const {
return true;
}
void disable() const {
}
const QString &name(const QString &original) const {
return original;
}
QByteArray bookmark() const {
return QByteArray();
}
};
bool psLaunchMaps(const LocationCoords &coords);