From 886847f457044a32ee3c56263bbcb15319364e7d Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Sat, 9 Mar 2024 11:15:37 +0400 Subject: [PATCH 001/240] Port notifications_manager_linux to cppgir --- Telegram/CMakeLists.txt | 1 + .../linux/notifications_manager_linux.cpp | 970 +++++++----------- .../linux/notifications_manager_linux.h | 1 + .../linux/org.freedesktop.Notifications.xml | 59 ++ 4 files changed, 436 insertions(+), 595 deletions(-) create mode 100644 Telegram/SourceFiles/platform/linux/org.freedesktop.Notifications.xml diff --git a/Telegram/CMakeLists.txt b/Telegram/CMakeLists.txt index 723c837a2..32acbe57e 100644 --- a/Telegram/CMakeLists.txt +++ b/Telegram/CMakeLists.txt @@ -1681,6 +1681,7 @@ else() include(${cmake_helpers_loc}/external/glib/generate_dbus.cmake) generate_dbus(Telegram org.freedesktop.portal. XdpBackground ${third_party_loc}/xdg-desktop-portal/data/org.freedesktop.portal.Background.xml) + generate_dbus(Telegram org.freedesktop. XdgNotifications ${src_loc}/platform/linux/org.freedesktop.Notifications.xml) if (NOT DESKTOP_APP_DISABLE_X11_INTEGRATION) target_link_libraries(Telegram diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp index 0473edf72..6367e76c2 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp @@ -29,7 +29,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include #include -#include +#include #include @@ -37,262 +37,87 @@ namespace Platform { namespace Notifications { namespace { +using namespace gi::repository; + constexpr auto kService = "org.freedesktop.Notifications"; constexpr auto kObjectPath = "/org/freedesktop/Notifications"; -constexpr auto kInterface = kService; -constexpr auto kPropertiesInterface = "org.freedesktop.DBus.Properties"; - -using PropertyMap = std::map; struct ServerInformation { - Glib::ustring name; - Glib::ustring vendor; + std::string name; + std::string vendor; QVersionNumber version; QVersionNumber specVersion; }; bool ServiceRegistered = false; ServerInformation CurrentServerInformation; -std::vector CurrentCapabilities; +std::vector CurrentCapabilities; [[nodiscard]] bool HasCapability(const char *value) { - return ranges::contains(CurrentCapabilities, value, &Glib::ustring::raw); -} - -void Noexcept(Fn callback, Fn failed = nullptr) noexcept { - try { - callback(); - return; - } catch (const std::exception &e) { - LOG(("Native Notification Error: %1").arg(e.what())); - } - - if (failed) { - failed(); - } + return ranges::contains(CurrentCapabilities, value); } std::unique_ptr CreateServiceWatcher() { - try { - const auto connection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); + auto connection = Gio::bus_get_sync(Gio::BusType::SESSION_, nullptr); + if (!connection) { + return nullptr; + } - const auto activatable = [&] { - const auto names = base::Platform::DBus::ListActivatableNames( - connection->gobj()); + const auto activatable = [&] { + const auto names = base::Platform::DBus::ListActivatableNames( + connection.gobj_()); - if (!names) { - // avoid service restart loop in sandboxed environments - return true; - } + if (!names) { + // avoid service restart loop in sandboxed environments + return true; + } - return ranges::contains(*names, kService); - }(); + return ranges::contains(*names, kService); + }(); - return std::make_unique( - connection->gobj(), - kService, - [=]( - const std::string &service, - const std::string &oldOwner, - const std::string &newOwner) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - if (activatable && newOwner.empty()) { - Core::App().notifications().clearAll(); - } else { - Core::App().notifications().createManager(); + return std::make_unique( + connection.gobj_(), + kService, + [=]( + const std::string &service, + const std::string &oldOwner, + const std::string &newOwner) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + if (activatable && newOwner.empty()) { + Core::App().notifications().clearAll(); + } else { + Core::App().notifications().createManager(); + } + }); + }); +} + +void StartServiceAsync(Gio::DBusConnection connection, Fn callback) { + namespace DBus = base::Platform::DBus; + DBus::StartServiceByNameAsync( + connection.gobj_(), + kService, + [=](Fn()> result) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + // get the error if any + if (const auto ret = result(); !ret) { + const auto error = static_cast( + ret.error().get()); + + if (error->gobj_()->domain != G_DBUS_ERROR + || error->code_() + != G_DBUS_ERROR_SERVICE_UNKNOWN) { + LOG(("Native Notification Error: %1").arg( + error->what())); } - }); + } + + callback(); }); - } catch (...) { - } - - return nullptr; + }); } -void StartServiceAsync(Fn callback) { - try { - const auto connection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - - namespace DBus = base::Platform::DBus; - DBus::StartServiceByNameAsync( - connection->gobj(), - kService, - [=](Fn()> result) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - // get the error if any - if (const auto ret = result(); !ret) { - static const auto NotSupportedErrors = { - "org.freedesktop.DBus.Error.ServiceUnknown", - }; - - if (ranges::none_of( - NotSupportedErrors, - [&](const auto &error) { - return strstr( - ret.error()->what(), - error); - })) { - throw std::runtime_error( - ret.error()->what()); - } - } - }); - - callback(); - }); - }); - - return; - } catch (...) { - } - - callback(); -} - -bool GetServiceRegistered() { - try { - const auto connection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - - const auto hasOwner = base::Platform::DBus::NameHasOwner( - connection->gobj(), - kService - ).value_or(false); - - static const auto activatable = [&] { - const auto names = base::Platform::DBus::ListActivatableNames( - connection->gobj()); - - if (!names) { - return false; - } - - return ranges::contains(*names, kService); - }(); - - return hasOwner || activatable; - } catch (...) { - } - - return false; -} - -void GetServerInformation(Fn callback) { - Noexcept([&] { - const auto connection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - - connection->call( - kObjectPath, - kInterface, - "GetServerInformation", - {}, - [=](const Glib::RefPtr &result) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - const auto reply = connection->call_finish(result); - - const auto name = reply - .get_child(0) - .get_dynamic(); - - const auto vendor = reply - .get_child(1) - .get_dynamic(); - - const auto version = reply - .get_child(2) - .get_dynamic(); - - const auto specVersion = reply - .get_child(3) - .get_dynamic(); - - callback(ServerInformation{ - name, - vendor, - QVersionNumber::fromString( - QString::fromStdString(version)), - QVersionNumber::fromString( - QString::fromStdString(specVersion)), - }); - }, [&] { - callback({}); - }); - }); - }, - kService); - }, [&] { - callback({}); - }); -} - -void GetCapabilities(Fn &)> callback) { - Noexcept([&] { - const auto connection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - - connection->call( - kObjectPath, - kInterface, - "GetCapabilities", - {}, - [=](const Glib::RefPtr &result) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - callback( - connection->call_finish(result) - .get_child(0) - .get_dynamic>() - ); - }, [&] { - callback({}); - }); - }); - }, - kService); - }, [&] { - callback({}); - }); -} - -void GetInhibited(Fn callback) { - Noexcept([&] { - const auto connection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - - connection->call( - kObjectPath, - kPropertiesInterface, - "Get", - Glib::create_variant(std::tuple{ - Glib::ustring(kInterface), - Glib::ustring("Inhibited"), - }), - [=](const Glib::RefPtr &result) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - callback( - connection->call_finish(result) - .get_child(0) - .get_dynamic>() - .get() - ); - }, [&] { - callback(false); - }); - }); - }, - kService); - }, [&] { - callback(false); - }); -} - -Glib::ustring GetImageKey(const QVersionNumber &specificationVersion) { +std::string GetImageKey(const QVersionNumber &specificationVersion) { const auto normalizedVersion = specificationVersion.normalized(); if (normalizedVersion.isNull()) { @@ -327,6 +152,7 @@ public: NotificationData( not_null manager, + XdgNotifications::NotificationsProxy proxy, NotificationId id); [[nodiscard]] bool init( @@ -350,27 +176,23 @@ private: const not_null _manager; NotificationId _id; - Glib::RefPtr _application; - Glib::RefPtr _notification; + Gio::Application _application; + Gio::Notification _notification; const std::string _guid; - Glib::RefPtr _dbusConnection; - Glib::ustring _title; - Glib::ustring _body; - std::vector _actions; - std::map _hints; - Glib::ustring _imageKey; + XdgNotifications::NotificationsProxy _proxy; + XdgNotifications::Notifications _interface; + std::string _title; + std::string _body; + std::vector _actions; + GLib::VariantDict _hints; + std::string _imageKey; uint _notificationId = 0; - uint _actionInvokedSignalId = 0; - uint _activationTokenSignalId = 0; - uint _notificationRepliedSignalId = 0; - uint _notificationClosedSignalId = 0; - - void notificationClosed(uint id, uint reason); - void actionInvoked(uint id, const Glib::ustring &actionName); - void activationToken(uint id, const Glib::ustring &token); - void notificationReplied(uint id, const Glib::ustring &text); + ulong _actionInvokedSignalId = 0; + ulong _activationTokenSignalId = 0; + ulong _notificationRepliedSignalId = 0; + ulong _notificationClosedSignalId = 0; }; @@ -378,13 +200,17 @@ using Notification = std::unique_ptr; NotificationData::NotificationData( not_null manager, + XdgNotifications::NotificationsProxy proxy, NotificationId id) : _manager(manager) , _id(id) , _application(UseGNotification() ? Gio::Application::get_default() : nullptr) -, _guid(_application ? Gio::DBus::generate_guid() : std::string()) { +, _guid(_application ? std::string(Gio::dbus_generate_guid()) : std::string()) +, _proxy(proxy) +, _interface(proxy) +, _hints(GLib::VariantDict::new_()) { } bool NotificationData::init( @@ -393,19 +219,19 @@ bool NotificationData::init( const QString &msg, Window::Notifications::Manager::DisplayOptions options) { if (_application) { - _notification = Gio::Notification::create( + _notification = Gio::Notification::new_( subtitle.isEmpty() ? title.toStdString() : subtitle.toStdString() + " (" + title.toStdString() + ')'); - _notification->set_body(msg.toStdString()); + _notification.set_body(msg.toStdString()); - _notification->set_icon( - Gio::ThemedIcon::create(base::IconName().toStdString())); + _notification.set_icon( + Gio::ThemedIcon::new_(base::IconName().toStdString())); // for chat messages, according to // https://docs.gtk.org/gio/enum.NotificationPriority.html - _notification->set_priority(Gio::Notification::Priority::HIGH); + _notification.set_priority(Gio::NotificationPriority::HIGH_); // glib 2.70+, we keep glib 2.56+ compatibility static const auto set_category = [] { @@ -416,90 +242,31 @@ bool NotificationData::init( }(); if (set_category) { - set_category(_notification->gobj(), "im.received"); + set_category(_notification.gobj_(), "im.received"); } - const auto idTuple = _id.toTuple(); + const auto idVariant = gi::wrap( + Glib::create_variant(_id.toTuple()).gobj_copy(), + gi::transfer_full); - _notification->set_default_action( + _notification.set_default_action_and_target( "app.notification-activate", - idTuple); + idVariant); if (!options.hideMarkAsRead) { - _notification->add_button( + _notification.add_button_with_target( tr::lng_context_mark_read(tr::now).toStdString(), "app.notification-mark-as-read", - idTuple); + idVariant); } return true; } - Noexcept([&] { - _dbusConnection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - }); - - if (!_dbusConnection) { + if (!_interface) { return false; } - const auto weak = base::make_weak(this); - - const auto signalEmitted = crl::guard(weak, [=]( - const Glib::RefPtr &connection, - const Glib::ustring &sender_name, - const Glib::ustring &object_path, - const Glib::ustring &interface_name, - const Glib::ustring &signal_name, - const Glib::VariantContainerBase ¶meters) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - if (signal_name == "ActionInvoked") { - const auto id = parameters - .get_child(0) - .get_dynamic(); - - const auto actionName = parameters - .get_child(1) - .get_dynamic(); - - actionInvoked(id, actionName); - } else if (signal_name == "ActivationToken") { - const auto id = parameters - .get_child(0) - .get_dynamic(); - - const auto token = parameters - .get_child(1) - .get_dynamic(); - - activationToken(id, token); - } else if (signal_name == "NotificationReplied") { - const auto id = parameters - .get_child(0) - .get_dynamic(); - - const auto text = parameters - .get_child(1) - .get_dynamic(); - - notificationReplied(id, text); - } else if (signal_name == "NotificationClosed") { - const auto id = parameters - .get_child(0) - .get_dynamic(); - - const auto reason = parameters - .get_child(1) - .get_dynamic(); - - notificationClosed(id, reason); - } - }); - }); - }); - _imageKey = GetImageKey(CurrentServerInformation.specVersion); if (HasCapability("body-markup")) { @@ -536,165 +303,215 @@ bool NotificationData::init( tr::lng_notification_reply(tr::now).toStdString()); _notificationRepliedSignalId = - _dbusConnection->signal_subscribe( - signalEmitted, - kService, - kInterface, - "NotificationReplied", - kObjectPath); + _interface.signal_notification_replied().connect([=]( + XdgNotifications::Notifications, + uint id, + std::string text) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + if (id == _notificationId) { + _manager->notificationReplied( + _id, + { QString::fromStdString(text), {} }); + } + }); + }); } - _actionInvokedSignalId = _dbusConnection->signal_subscribe( - signalEmitted, - kService, - kInterface, - "ActionInvoked", - kObjectPath); + _actionInvokedSignalId = _interface.signal_action_invoked().connect( + [=]( + XdgNotifications::Notifications, + uint id, + std::string actionName) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + if (id == _notificationId) { + if (actionName == "default") { + _manager->notificationActivated(_id); + } else if (actionName == "mail-mark-read") { + _manager->notificationReplied(_id, {}); + } + } + }); + }); - _activationTokenSignalId = _dbusConnection->signal_subscribe( - signalEmitted, - kService, - kInterface, - "ActivationToken", - kObjectPath); + _activationTokenSignalId = + _interface.signal_activation_token().connect([=]( + XdgNotifications::Notifications, + uint id, + std::string token) { + if (id == _notificationId) { + GLib::setenv("XDG_ACTIVATION_TOKEN", token, true); + } + }); } if (HasCapability("action-icons")) { - _hints["action-icons"] = Glib::create_variant(true); + _hints.insert_value("action-icons", GLib::Variant::new_boolean(true)); } // suppress system sound if telegram sound activated, // otherwise use system sound if (HasCapability("sound")) { if (Core::App().settings().soundNotify()) { - _hints["suppress-sound"] = Glib::create_variant(true); + _hints.insert_value( + "suppress-sound", + GLib::Variant::new_boolean(true)); } else { // sound name according to http://0pointer.de/public/sound-naming-spec.html - _hints["sound-name"] = Glib::create_variant( - Glib::ustring("message-new-instant")); + _hints.insert_value( + "sound-name", + GLib::Variant::new_string("message-new-instant")); } } if (HasCapability("x-canonical-append")) { - _hints["x-canonical-append"] = Glib::create_variant( - Glib::ustring("true")); + _hints.insert_value( + "x-canonical-append", + GLib::Variant::new_string("true")); } - _hints["category"] = Glib::create_variant(Glib::ustring("im.received")); + _hints.insert_value("category", GLib::Variant::new_string("im.received")); - _hints["desktop-entry"] = Glib::create_variant( - Glib::ustring(QGuiApplication::desktopFileName().toStdString())); + _hints.insert_value("desktop-entry", GLib::Variant::new_string( + QGuiApplication::desktopFileName().toStdString())); + + _notificationClosedSignalId = + _interface.signal_notification_closed().connect([=]( + XdgNotifications::Notifications, + uint id, + uint reason) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + /* + * From: https://specifications.freedesktop.org/notification-spec/latest/ar01s09.html + * The reason the notification was closed + * 1 - The notification expired. + * 2 - The notification was dismissed by the user. + * 3 - The notification was closed by a call to CloseNotification. + * 4 - Undefined/reserved reasons. + * + * If the notification was dismissed by the user (reason == 2), the notification is not kept in notification history. + * We do not need to send a "CloseNotification" call later to clear it from history. + * Therefore we can drop the notification reference now. + * In all other cases we keep the notification reference so that we may clear the notification later from history, + * if the message for that notification is read (e.g. chat is opened or read from another device). + */ + if (id == _notificationId && reason == 2) { + _manager->clearNotification(_id); + } + }); + }); - _notificationClosedSignalId = _dbusConnection->signal_subscribe( - signalEmitted, - kService, - kInterface, - "NotificationClosed", - kObjectPath); return true; } NotificationData::~NotificationData() { - if (_dbusConnection) { + if (_interface) { if (_actionInvokedSignalId != 0) { - _dbusConnection->signal_unsubscribe(_actionInvokedSignalId); + _interface.disconnect(_actionInvokedSignalId); } if (_activationTokenSignalId != 0) { - _dbusConnection->signal_unsubscribe(_activationTokenSignalId); + _interface.disconnect(_activationTokenSignalId); } if (_notificationRepliedSignalId != 0) { - _dbusConnection->signal_unsubscribe(_notificationRepliedSignalId); + _interface.disconnect(_notificationRepliedSignalId); } if (_notificationClosedSignalId != 0) { - _dbusConnection->signal_unsubscribe(_notificationClosedSignalId); + _interface.disconnect(_notificationClosedSignalId); } } } void NotificationData::show() { if (_application && _notification) { - _application->send_notification(_guid, _notification); + _application.send_notification(_guid, _notification); return; } // a hack for snap's activation restriction const auto weak = base::make_weak(this); - StartServiceAsync(crl::guard(weak, [=] { + StartServiceAsync(_proxy.get_connection(), crl::guard(weak, [=] { const auto iconName = _imageKey.empty() - || _hints.find(_imageKey) == end(_hints) - ? Glib::ustring(base::IconName().toStdString()) - : Glib::ustring(); - const auto connection = _dbusConnection; + || _hints.lookup_value(_imageKey) + ? std::string() + : base::IconName().toStdString(); - connection->call( - kObjectPath, - kInterface, - "Notify", - Glib::create_variant(std::tuple{ - Glib::ustring(std::string(AppName)), - uint(0), - iconName, - _title, - _body, - _actions, - _hints, - -1, - }), - crl::guard(weak, [=]( - const Glib::RefPtr &result) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - _notificationId = connection->call_finish(result) - .get_child(0) - .get_dynamic(); - }, [&] { - _manager->clearNotification(_id); + auto actions = _actions + | ranges::views::transform(&std::string::c_str) + | ranges::to_vector; + actions.push_back(nullptr); + + const auto callbackWrap = gi::unwrap( + Gio::AsyncReadyCallback( + crl::guard(weak, [=](GObject::Object, Gio::AsyncResult res) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + const auto result = _interface.call_notify_finish( + res); + + if (!result) { + Gio::DBusErrorNS_::strip_remote_error( + result.error()); + LOG(("Native Notification Error: %1").arg( + result.error().message_().c_str())); + _manager->clearNotification(_id); + return; + } + + _notificationId = std::get<1>(*result); }); - }); - }), - kService); + })), + gi::scope_async); + + xdg_notifications_notifications_call_notify( + _interface.gobj_(), + AppName.data(), + 0, + iconName.c_str(), + _title.c_str(), + _body.c_str(), + actions.data(), + _hints.end().gobj_(), + -1, + nullptr, + &callbackWrap->wrapper, + callbackWrap); })); } void NotificationData::close() { if (_application) { - _application->withdraw_notification(_guid); - _manager->clearNotification(_id); - return; + _application.withdraw_notification(_guid); + } else { + _interface.call_close_notification(_notificationId, nullptr); } - - _dbusConnection->call( - kObjectPath, - kInterface, - "CloseNotification", - Glib::create_variant(std::tuple{ - _notificationId, - }), - {}, - kService, - -1, - Gio::DBus::CallFlags::NO_AUTO_START); _manager->clearNotification(_id); } void NotificationData::setImage(QImage image) { - if (_notification) { - const auto imageData = [&] { - QByteArray ba; - QBuffer buffer(&ba); - buffer.open(QIODevice::WriteOnly); - image.save(&buffer, "PNG"); - return ba; - }(); + using DestroyNotify = gi::detail::callback< + void(), + gi::transfer_full_t, + std::tuple<> + >; - _notification->set_icon( - Gio::BytesIcon::create( - Glib::Bytes::create( - imageData.constData(), - imageData.size()))); + if (_notification) { + const auto imageData = std::make_shared(); + QBuffer buffer(imageData.get()); + buffer.open(QIODevice::WriteOnly); + image.save(&buffer, "PNG"); + + const auto callbackWrap = gi::unwrap( + DestroyNotify([imageData] {}), + gi::scope_notified); + + _notification.set_icon( + Gio::BytesIcon::new_( + gi::wrap(g_bytes_new_with_free_func( + imageData->constData(), + imageData->size(), + &callbackWrap->destroy, + callbackWrap), gi::transfer_full))); return; } @@ -709,71 +526,66 @@ void NotificationData::setImage(QImage image) { image.convertTo(QImage::Format_RGB888); } - _hints[_imageKey] = Glib::create_variant(std::tuple{ - image.width(), - image.height(), - int(image.bytesPerLine()), - image.hasAlphaChannel(), - 8, - image.hasAlphaChannel() ? 4 : 3, - std::vector( + const auto callbackWrap = gi::unwrap( + DestroyNotify([image] {}), + gi::scope_notified); + + _hints.insert_value(_imageKey, GLib::Variant::new_tuple({ + GLib::Variant::new_int32(image.width()), + GLib::Variant::new_int32(image.height()), + GLib::Variant::new_int32(image.bytesPerLine()), + GLib::Variant::new_boolean(image.hasAlphaChannel()), + GLib::Variant::new_int32(8), + GLib::Variant::new_int32(image.hasAlphaChannel() ? 4 : 3), + gi::wrap(g_variant_new_from_data( + G_VARIANT_TYPE_BYTESTRING, image.constBits(), - image.constBits() + image.sizeInBytes()), - }); -} - -void NotificationData::notificationClosed(uint id, uint reason) { - /* - * From: https://specifications.freedesktop.org/notification-spec/latest/ar01s09.html - * The reason the notification was closed - * 1 - The notification expired. - * 2 - The notification was dismissed by the user. - * 3 - The notification was closed by a call to CloseNotification. - * 4 - Undefined/reserved reasons. - * - * If the notification was dismissed by the user (reason == 2), the notification is not kept in notification history. - * We do not need to send a "CloseNotification" call later to clear it from history. - * Therefore we can drop the notification reference now. - * In all other cases we keep the notification reference so that we may clear the notification later from history, - * if the message for that notification is read (e.g. chat is opened or read from another device). - */ - if (id == _notificationId && reason == 2) { - _manager->clearNotification(_id); - } -} - -void NotificationData::actionInvoked( - uint id, - const Glib::ustring &actionName) { - if (id != _notificationId) { - return; - } - - if (actionName == "default") { - _manager->notificationActivated(_id); - } else if (actionName == "mail-mark-read") { - _manager->notificationReplied(_id, {}); - } -} - -void NotificationData::activationToken(uint id, const Glib::ustring &token) { - if (id == _notificationId) { - qputenv("XDG_ACTIVATION_TOKEN", QByteArray::fromStdString(token)); - } -} - -void NotificationData::notificationReplied( - uint id, - const Glib::ustring &text) { - if (id == _notificationId) { - _manager->notificationReplied( - _id, - { QString::fromStdString(text), {} }); - } + image.sizeInBytes(), + true, + &callbackWrap->destroy, + callbackWrap), gi::transfer_none), + })); } } // namespace +class Manager::Private : public base::has_weak_ptr { +public: + explicit Private(not_null manager); + + void init(XdgNotifications::NotificationsProxy proxy); + + void showNotification( + not_null peer, + MsgId topicRootId, + Ui::PeerUserpicView &userpicView, + MsgId msgId, + const QString &title, + const QString &subtitle, + const QString &msg, + DisplayOptions options); + void clearAll(); + void clearFromItem(not_null item); + void clearFromTopic(not_null topic); + void clearFromHistory(not_null history); + void clearFromSession(not_null session); + void clearNotification(NotificationId id); + void invokeIfNotInhibited(Fn callback); + + ~Private(); + +private: + const not_null _manager; + + base::flat_map< + ContextId, + base::flat_map> _notifications; + + XdgNotifications::NotificationsProxy _proxy; + XdgNotifications::Notifications _interface; + +}; + bool SkipToastForCustom() { return false; } @@ -828,12 +640,15 @@ bool ByDefault() { void Create(Window::Notifications::System *system) { static const auto ServiceWatcher = CreateServiceWatcher(); - const auto managerSetter = [=] { + const auto managerSetter = [=]( + XdgNotifications::NotificationsProxy proxy) { using ManagerType = Window::Notifications::ManagerType; if ((Core::App().settings().nativeNotifications() || Enforced()) && Supported()) { if (system->manager().type() != ManagerType::Native) { - system->setManager(std::make_unique(system)); + auto manager = std::make_unique(system); + manager->_private->init(proxy); + system->setManager(std::move(manager)); } } else if (Enforced()) { if (system->manager().type() != ManagerType::Dummy) { @@ -846,71 +661,83 @@ void Create(Window::Notifications::System *system) { }; const auto counter = std::make_shared(2); - const auto oneReady = [=] { + const auto oneReady = [=](XdgNotifications::NotificationsProxy proxy) { if (!--*counter) { - managerSetter(); + managerSetter(proxy); } }; - // snap doesn't allow access when the daemon is not running :( - StartServiceAsync([=] { - ServiceRegistered = GetServiceRegistered(); + XdgNotifications::NotificationsProxy::new_for_bus( + Gio::BusType::SESSION_, + Gio::DBusProxyFlags::NONE_, + kService, + kObjectPath, + [=](GObject::Object, Gio::AsyncResult res) { + auto proxy = + XdgNotifications::NotificationsProxy::new_for_bus_finish( + res, + nullptr); - if (!ServiceRegistered) { - CurrentServerInformation = {}; - CurrentCapabilities = {}; - managerSetter(); - return; - } + if (!proxy) { + ServiceRegistered = false; + CurrentServerInformation = {}; + CurrentCapabilities = {}; + managerSetter(nullptr); + return; + } - GetServerInformation([=](const ServerInformation &result) { - CurrentServerInformation = result; - oneReady(); + ServiceRegistered = bool(proxy.get_name_owner()); + if (!ServiceRegistered) { + CurrentServerInformation = {}; + CurrentCapabilities = {}; + managerSetter(proxy); + return; + } + + auto interface = XdgNotifications::Notifications(proxy); + + interface.call_get_server_information([=]( + GObject::Object, + Gio::AsyncResult res) mutable { + const auto result = + interface.call_get_server_information_finish(res); + if (result) { + CurrentServerInformation = { + std::get<1>(*result), + std::get<2>(*result), + QVersionNumber::fromString( + QString::fromStdString(std::get<3>(*result))), + QVersionNumber::fromString( + QString::fromStdString(std::get<4>(*result))), + }; + } else { + Gio::DBusErrorNS_::strip_remote_error(result.error()); + LOG(("Native Notification Error: %1").arg( + result.error().message_().c_str())); + CurrentServerInformation = {}; + } + oneReady(proxy); + }); + + interface.call_get_capabilities([=]( + GObject::Object, + Gio::AsyncResult res) mutable { + const auto result = interface.call_get_capabilities_finish( + res); + if (result) { + CurrentCapabilities = std::get<1>(*result) + | ranges::to>; + } else { + Gio::DBusErrorNS_::strip_remote_error(result.error()); + LOG(("Native Notification Error: %1").arg( + result.error().message_().c_str())); + CurrentCapabilities = {}; + } + oneReady(proxy); + }); }); - - GetCapabilities([=](const std::vector &result) { - CurrentCapabilities = result; - oneReady(); - }); - }); } -class Manager::Private : public base::has_weak_ptr { -public: - explicit Private(not_null manager); - - void showNotification( - not_null peer, - MsgId topicRootId, - Ui::PeerUserpicView &userpicView, - MsgId msgId, - const QString &title, - const QString &subtitle, - const QString &msg, - DisplayOptions options); - void clearAll(); - void clearFromItem(not_null item); - void clearFromTopic(not_null topic); - void clearFromHistory(not_null history); - void clearFromSession(not_null session); - void clearNotification(NotificationId id); - void invokeIfNotInhibited(Fn callback); - - ~Private(); - -private: - const not_null _manager; - - base::flat_map< - ContextId, - base::flat_map> _notifications; - - Glib::RefPtr _dbusConnection; - bool _inhibited = false; - uint _inhibitedSignalId = 0; - -}; - Manager::Private::Private(not_null manager) : _manager(manager) { const auto &serverInformation = CurrentServerInformation; @@ -940,57 +767,15 @@ Manager::Private::Private(not_null manager) ranges::fold_left( CurrentCapabilities, "", - [](const Glib::ustring &a, const Glib::ustring &b) { + [](const std::string &a, const std::string &b) { return a + (a.empty() ? "" : ", ") + b; }).c_str())); } +} - if (HasCapability("inhibitions")) { - Noexcept([&] { - _dbusConnection = Gio::DBus::Connection::get_sync( - Gio::DBus::BusType::SESSION); - }); - - if (!_dbusConnection) { - return; - } - - const auto weak = base::make_weak(this); - GetInhibited(crl::guard(weak, [=](bool result) { - _inhibited = result; - })); - - _inhibitedSignalId = _dbusConnection->signal_subscribe( - crl::guard(weak, [=]( - const Glib::RefPtr &connection, - const Glib::ustring &sender_name, - const Glib::ustring &object_path, - const Glib::ustring &interface_name, - const Glib::ustring &signal_name, - const Glib::VariantContainerBase ¶meters) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - Noexcept([&] { - const auto interface = parameters - .get_child(0) - .get_dynamic(); - - if (interface != kInterface) { - return; - } - - _inhibited = parameters - .get_child(1) - .get_dynamic() - .at("Inhibited") - .get_dynamic(); - }); - }); - }), - kService, - kPropertiesInterface, - "PropertiesChanged", - kObjectPath); - } +void Manager::Private::init(XdgNotifications::NotificationsProxy proxy) { + _proxy = proxy; + _interface = proxy; } void Manager::Private::showNotification( @@ -1013,6 +798,7 @@ void Manager::Private::showNotification( }; auto notification = std::make_unique( _manager, + _proxy, notificationId); const auto inited = notification->init( title, @@ -1139,19 +925,13 @@ void Manager::Private::clearNotification(NotificationId id) { } void Manager::Private::invokeIfNotInhibited(Fn callback) { - if (!_inhibited) { + if (!_interface.get_inhibited()) { callback(); } } Manager::Private::~Private() { clearAll(); - - if (_dbusConnection) { - if (_inhibitedSignalId != 0) { - _dbusConnection->signal_unsubscribe(_inhibitedSignalId); - } - } } Manager::Manager(not_null system) diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.h b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.h index adefaff6c..95c77626b 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.h +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.h @@ -38,6 +38,7 @@ protected: void doMaybeFlashBounce(Fn flashBounce) override; private: + friend void Create(Window::Notifications::System *system); class Private; const std::unique_ptr _private; diff --git a/Telegram/SourceFiles/platform/linux/org.freedesktop.Notifications.xml b/Telegram/SourceFiles/platform/linux/org.freedesktop.Notifications.xml new file mode 100644 index 000000000..c969a61f9 --- /dev/null +++ b/Telegram/SourceFiles/platform/linux/org.freedesktop.Notifications.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0ec518156604f6005e274a970bbde0390bb9fcab Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Sun, 10 Mar 2024 01:55:08 +0400 Subject: [PATCH 002/240] Pre-normalize notification daemon versions --- .../linux/notifications_manager_linux.cpp | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp index 6367e76c2..0fa06d3a1 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp @@ -117,17 +117,16 @@ void StartServiceAsync(Gio::DBusConnection connection, Fn callback) { }); } -std::string GetImageKey(const QVersionNumber &specificationVersion) { - const auto normalizedVersion = specificationVersion.normalized(); - - if (normalizedVersion.isNull()) { +std::string GetImageKey() { + const auto &specVersion = CurrentServerInformation.specVersion; + if (specVersion.isNull()) { LOG(("Native Notification Error: specification version is null")); return {}; } - if (normalizedVersion >= QVersionNumber(1, 2)) { + if (specVersion >= QVersionNumber(1, 2)) { return "image-data"; - } else if (normalizedVersion == QVersionNumber(1, 1)) { + } else if (specVersion == QVersionNumber(1, 1)) { return "image_data"; } @@ -210,7 +209,8 @@ NotificationData::NotificationData( , _guid(_application ? std::string(Gio::dbus_generate_guid()) : std::string()) , _proxy(proxy) , _interface(proxy) -, _hints(GLib::VariantDict::new_()) { +, _hints(GLib::VariantDict::new_()) +, _imageKey(GetImageKey()) { } bool NotificationData::init( @@ -267,8 +267,6 @@ bool NotificationData::init( return false; } - _imageKey = GetImageKey(CurrentServerInformation.specVersion); - if (HasCapability("body-markup")) { _title = title.toStdString(); @@ -706,9 +704,11 @@ void Create(Window::Notifications::System *system) { std::get<1>(*result), std::get<2>(*result), QVersionNumber::fromString( - QString::fromStdString(std::get<3>(*result))), + QString::fromStdString(std::get<3>(*result)) + ).normalized(), QVersionNumber::fromString( - QString::fromStdString(std::get<4>(*result))), + QString::fromStdString(std::get<4>(*result)) + ).normalized(), }; } else { Gio::DBusErrorNS_::strip_remote_error(result.error()); From dba9cada83131276fcde7941e6c4cc458808b533 Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Sun, 10 Mar 2024 02:00:52 +0400 Subject: [PATCH 003/240] Don't check whether specification version is null We log specification version anyway --- .../platform/linux/notifications_manager_linux.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp index 0fa06d3a1..b1478358d 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp @@ -119,17 +119,11 @@ void StartServiceAsync(Gio::DBusConnection connection, Fn callback) { std::string GetImageKey() { const auto &specVersion = CurrentServerInformation.specVersion; - if (specVersion.isNull()) { - LOG(("Native Notification Error: specification version is null")); - return {}; - } - if (specVersion >= QVersionNumber(1, 2)) { return "image-data"; } else if (specVersion == QVersionNumber(1, 1)) { return "image_data"; } - return "icon_data"; } From c9d58d42590a298483584b9b9aab50891ea0b903 Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Sun, 10 Mar 2024 02:47:21 +0400 Subject: [PATCH 004/240] Use HasCapability directly as an argument to ranges::all_of --- .../platform/linux/notifications_manager_linux.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp index b1478358d..bf9920729 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp @@ -624,9 +624,7 @@ bool ByDefault() { // To not to play sound with Don't Disturb activated // (no, using sound capability is not a way) "inhibitions", - }, [](const auto *capability) { - return HasCapability(capability); - }); + }, HasCapability); } void Create(Window::Notifications::System *system) { From 5394717ddc0afe7268c71fd11046ef35093bc3c0 Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Sun, 10 Mar 2024 04:58:45 +0400 Subject: [PATCH 005/240] Log only GError message --- .../platform/linux/specific_linux.cpp | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/Telegram/SourceFiles/platform/linux/specific_linux.cpp b/Telegram/SourceFiles/platform/linux/specific_linux.cpp index 4122097bc..7bbeb30c2 100644 --- a/Telegram/SourceFiles/platform/linux/specific_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/specific_linux.cpp @@ -79,8 +79,9 @@ void PortalAutostart(bool enabled, Fn done) { if (!proxy) { if (done) { + Gio::DBusErrorNS_::strip_remote_error(proxy.error()); LOG(("Portal Autostart Error: %1").arg( - proxy.error().what())); + proxy.error().message_().c_str())); done(false); } return; @@ -117,8 +118,10 @@ void PortalAutostart(bool enabled, Fn done) { if (!requestProxy) { if (done) { + Gio::DBusErrorNS_::strip_remote_error( + requestProxy.error()); LOG(("Portal Autostart Error: %1").arg( - requestProxy.error().what())); + requestProxy.error().message_().c_str())); done(false); } return; @@ -192,8 +195,11 @@ void PortalAutostart(bool enabled, Fn done) { if (!result) { if (done) { - LOG(("Portal Autostart Error: %1") - .arg(result.error().what())); + const auto &error = result.error(); + Gio::DBusErrorNS_::strip_remote_error( + error); + LOG(("Portal Autostart Error: %1").arg( + error.message_().c_str())); done(false); } @@ -247,7 +253,7 @@ bool GenerateDesktopFile( if (!loaded) { if (!silent) { - LOG(("App Error: %1").arg(loaded.error().what())); + LOG(("App Error: %1").arg(loaded.error().message_().c_str())); } return false; } @@ -257,7 +263,8 @@ bool GenerateDesktopFile( const auto removed = target.remove_group(group); if (!removed) { if (!silent) { - LOG(("App Error: %1").arg(removed.error().what())); + LOG(("App Error: %1").arg( + removed.error().message_().c_str())); } return false; } @@ -320,7 +327,7 @@ bool GenerateDesktopFile( const auto saved = target.save_to_file(targetFile.toStdString()); if (!saved) { if (!silent) { - LOG(("App Error: %1").arg(saved.error().what())); + LOG(("App Error: %1").arg(saved.error().message_().c_str())); } return false; } @@ -411,7 +418,7 @@ bool GenerateServiceFile(bool silent = false) { const auto saved = target.save_to_file(targetFile.toStdString()); if (!saved) { if (!silent) { - LOG(("App Error: %1").arg(saved.error().what())); + LOG(("App Error: %1").arg(saved.error().message_().c_str())); } return false; } From abdfa4f785ca0094a1db3959deb3d922ffd3d1d5 Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Mon, 11 Mar 2024 02:26:16 +0400 Subject: [PATCH 006/240] Remove not really needed notification capability checks If the notification daemon doesn't support any of the hints, it will just ignore them --- .../linux/notifications_manager_linux.cpp | 118 ++++++++---------- 1 file changed, 53 insertions(+), 65 deletions(-) diff --git a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp index bf9920729..85d0fc037 100644 --- a/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/notifications_manager_linux.cpp @@ -277,89 +277,77 @@ bool NotificationData::init( _body = msg.toStdString(); } - if (HasCapability("actions")) { - _actions.push_back("default"); - _actions.push_back(tr::lng_open_link(tr::now).toStdString()); + _actions.push_back("default"); + _actions.push_back(tr::lng_open_link(tr::now).toStdString()); - if (!options.hideMarkAsRead) { - // icon name according to https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html - _actions.push_back("mail-mark-read"); - _actions.push_back( - tr::lng_context_mark_read(tr::now).toStdString()); - } + if (!options.hideMarkAsRead) { + // icon name according to https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html + _actions.push_back("mail-mark-read"); + _actions.push_back(tr::lng_context_mark_read(tr::now).toStdString()); + } - if (HasCapability("inline-reply") - && !options.hideReplyButton) { - _actions.push_back("inline-reply"); - _actions.push_back( - tr::lng_notification_reply(tr::now).toStdString()); + if (HasCapability("inline-reply") && !options.hideReplyButton) { + _actions.push_back("inline-reply"); + _actions.push_back(tr::lng_notification_reply(tr::now).toStdString()); - _notificationRepliedSignalId = - _interface.signal_notification_replied().connect([=]( - XdgNotifications::Notifications, - uint id, - std::string text) { - Core::Sandbox::Instance().customEnterFromEventLoop([&] { - if (id == _notificationId) { - _manager->notificationReplied( - _id, - { QString::fromStdString(text), {} }); - } - }); - }); - } - - _actionInvokedSignalId = _interface.signal_action_invoked().connect( - [=]( + _notificationRepliedSignalId = + _interface.signal_notification_replied().connect([=]( XdgNotifications::Notifications, uint id, - std::string actionName) { + std::string text) { Core::Sandbox::Instance().customEnterFromEventLoop([&] { if (id == _notificationId) { - if (actionName == "default") { - _manager->notificationActivated(_id); - } else if (actionName == "mail-mark-read") { - _manager->notificationReplied(_id, {}); - } + _manager->notificationReplied( + _id, + { QString::fromStdString(text), {} }); } }); }); + } - _activationTokenSignalId = - _interface.signal_activation_token().connect([=]( - XdgNotifications::Notifications, - uint id, - std::string token) { - if (id == _notificationId) { - GLib::setenv("XDG_ACTIVATION_TOKEN", token, true); + _actionInvokedSignalId = _interface.signal_action_invoked().connect([=]( + XdgNotifications::Notifications, + uint id, + std::string actionName) { + Core::Sandbox::Instance().customEnterFromEventLoop([&] { + if (id == _notificationId) { + if (actionName == "default") { + _manager->notificationActivated(_id); + } else if (actionName == "mail-mark-read") { + _manager->notificationReplied(_id, {}); } - }); - } + } + }); + }); - if (HasCapability("action-icons")) { - _hints.insert_value("action-icons", GLib::Variant::new_boolean(true)); - } + _activationTokenSignalId = _interface.signal_activation_token().connect( + [=]( + XdgNotifications::Notifications, + uint id, + std::string token) { + if (id == _notificationId) { + GLib::setenv("XDG_ACTIVATION_TOKEN", token, true); + } + }); + + _hints.insert_value("action-icons", GLib::Variant::new_boolean(true)); // suppress system sound if telegram sound activated, // otherwise use system sound - if (HasCapability("sound")) { - if (Core::App().settings().soundNotify()) { - _hints.insert_value( - "suppress-sound", - GLib::Variant::new_boolean(true)); - } else { - // sound name according to http://0pointer.de/public/sound-naming-spec.html - _hints.insert_value( - "sound-name", - GLib::Variant::new_string("message-new-instant")); - } + if (Core::App().settings().soundNotify()) { + _hints.insert_value( + "suppress-sound", + GLib::Variant::new_boolean(true)); + } else { + // sound name according to http://0pointer.de/public/sound-naming-spec.html + _hints.insert_value( + "sound-name", + GLib::Variant::new_string("message-new-instant")); } - if (HasCapability("x-canonical-append")) { - _hints.insert_value( - "x-canonical-append", - GLib::Variant::new_string("true")); - } + _hints.insert_value( + "x-canonical-append", + GLib::Variant::new_string("true")); _hints.insert_value("category", GLib::Variant::new_string("im.received")); From d881019c3b069ff7d06a03bcb38242d43a0366aa Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Sun, 10 Mar 2024 02:11:58 +0400 Subject: [PATCH 007/240] Update submodules --- .../platform/linux/linux_xdp_open_with_dialog.cpp | 2 +- Telegram/SourceFiles/platform/linux/specific_linux.cpp | 5 +---- Telegram/lib_base | 2 +- cmake | 2 +- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/Telegram/SourceFiles/platform/linux/linux_xdp_open_with_dialog.cpp b/Telegram/SourceFiles/platform/linux/linux_xdp_open_with_dialog.cpp index bd82cb17f..9e409b900 100644 --- a/Telegram/SourceFiles/platform/linux/linux_xdp_open_with_dialog.cpp +++ b/Telegram/SourceFiles/platform/linux/linux_xdp_open_with_dialog.cpp @@ -91,7 +91,7 @@ bool ShowXDPOpenWithDialog(const QString &filepath) { }); auto result = interface.call_open_file_sync( - std::string(base::Platform::XDP::ParentWindowID()), + base::Platform::XDP::ParentWindowID(), GLib::Variant::new_handle(0), GLib::Variant::new_array({ GLib::Variant::new_dict_entry( diff --git a/Telegram/SourceFiles/platform/linux/specific_linux.cpp b/Telegram/SourceFiles/platform/linux/specific_linux.cpp index 7bbeb30c2..750c4dc5f 100644 --- a/Telegram/SourceFiles/platform/linux/specific_linux.cpp +++ b/Telegram/SourceFiles/platform/linux/specific_linux.cpp @@ -36,7 +36,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include #include -#include #include #include @@ -55,7 +54,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL namespace { using namespace gi::repository; -namespace Gio = gi::repository::Gio; using namespace Platform; using Platform::internal::WaylandIntegration; @@ -161,7 +159,7 @@ void PortalAutostart(bool enabled, Fn done) { commandline.push_back("-autostart"); interface.call_request_background( - std::string(base::Platform::XDP::ParentWindowID()), + base::Platform::XDP::ParentWindowID(), GLib::Variant::new_array({ GLib::Variant::new_dict_entry( GLib::Variant::new_string("handle_token"), @@ -695,7 +693,6 @@ void start() { GLib::set_application_name(AppName.data()); Glib::init(); - ::Gio::init(); Webview::WebKitGTK::SetSocketPath(u"%1/%2-%3-webview-%4"_q.arg( QDir::tempPath(), diff --git a/Telegram/lib_base b/Telegram/lib_base index 5b9556fdd..2a5567763 160000 --- a/Telegram/lib_base +++ b/Telegram/lib_base @@ -1 +1 @@ -Subproject commit 5b9556fddb9a67e514d0bed2c123e18cbe1663b7 +Subproject commit 2a55677634fef9f0c762c6305185fe773e3eae7b diff --git a/cmake b/cmake index 5a61112d6..5b703df9b 160000 --- a/cmake +++ b/cmake @@ -1 +1 @@ -Subproject commit 5a61112d6d025b56573ad48bcc1331ac65c4a927 +Subproject commit 5b703df9b8fc5417969fa40ddf12952368ae227b From d67f25d726470a049194f3fe8175d7599808969d Mon Sep 17 00:00:00 2001 From: Ilya Fedin Date: Wed, 13 Mar 2024 12:50:37 +0400 Subject: [PATCH 008/240] Update Qt to 6.7.0 on Linux --- Telegram/build/docker/centos_env/Dockerfile | 6 +++--- snap/snapcraft.yaml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Telegram/build/docker/centos_env/Dockerfile b/Telegram/build/docker/centos_env/Dockerfile index bf2ef2fbe..7a06f2ee6 100644 --- a/Telegram/build/docker/centos_env/Dockerfile +++ b/Telegram/build/docker/centos_env/Dockerfile @@ -1,7 +1,7 @@ {%- set GIT = "https://github.com" -%} {%- set GIT_FREEDESKTOP = GIT ~ "/gitlab-freedesktop-mirrors" -%} -{%- set QT = "6.6.2" -%} -{%- set QT_TAG = "v" ~ QT -%} +{%- set QT = "6.7.0" -%} +{%- set QT_TAG = "v" ~ QT ~ "-rc1" -%} {%- set QT_PREFIX = "/usr/local/desktop-app/Qt-" ~ QT -%} {%- set OPENSSL_VER = "1_1_1" -%} {%- set OPENSSL_PREFIX = "/usr/local/desktop-app/openssl-1.1.1" -%} @@ -785,7 +785,7 @@ RUN git clone -b {{ QT_TAG }} --depth=1 {{ GIT }}/qt/qt5.git qt_{{ QT }} \ && rm -rf qt_{{ QT }} FROM builder AS breakpad -RUN git clone -b v2023.01.27 --depth=1 https://chromium.googlesource.com/breakpad/breakpad.git \ +RUN git clone -b v2023.06.01 --depth=1 https://chromium.googlesource.com/breakpad/breakpad.git \ && cd breakpad \ && git clone -b v2022.10.12 --depth=1 https://chromium.googlesource.com/linux-syscall-support.git src/third_party/lss \ && env -u CFLAGS -u CXXFLAGS ./configure \ diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 0996a2797..3d9e75301 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -494,9 +494,9 @@ parts: - zlib1g - mesa-vulkan-drivers override-pull: | - QT=6.6.2 + QT=6.7.0 - git clone -b v${QT} --depth=1 https://github.com/qt/qt5.git . + git clone -b v${QT}-rc1 --depth=1 https://github.com/qt/qt5.git . git submodule update --init --recursive --depth=1 qtbase qtdeclarative qtwayland qtimageformats qtsvg qtshadertools cd qtbase From b20b3142a2efe6a04ab25ee4650dfea88136735d Mon Sep 17 00:00:00 2001 From: John Preston Date: Wed, 13 Mar 2024 20:49:24 +0400 Subject: [PATCH 009/240] Update submodules and patches commit. --- Telegram/build/docker/centos_env/Dockerfile | 2 +- Telegram/lib_base | 2 +- Telegram/lib_ui | 2 +- cmake | 2 +- snap/snapcraft.yaml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Telegram/build/docker/centos_env/Dockerfile b/Telegram/build/docker/centos_env/Dockerfile index 7a06f2ee6..274b4919a 100644 --- a/Telegram/build/docker/centos_env/Dockerfile +++ b/Telegram/build/docker/centos_env/Dockerfile @@ -54,7 +54,7 @@ FROM builder AS patches RUN git init patches \ && cd patches \ && git remote add origin {{ GIT }}/desktop-app/patches.git \ - && git fetch --depth=1 origin 0edd8a93409ca24e215fc8ba1e98814893ad05cf \ + && git fetch --depth=1 origin cc0c2f83650bbd52064bb7bc7257c950822cce5b \ && git reset --hard FETCH_HEAD \ && rm -rf .git diff --git a/Telegram/lib_base b/Telegram/lib_base index 2a5567763..928fe24bb 160000 --- a/Telegram/lib_base +++ b/Telegram/lib_base @@ -1 +1 @@ -Subproject commit 2a55677634fef9f0c762c6305185fe773e3eae7b +Subproject commit 928fe24bb723bbebd4bcc87792da54b796d0b5a9 diff --git a/Telegram/lib_ui b/Telegram/lib_ui index 6bce49302..2687a19b1 160000 --- a/Telegram/lib_ui +++ b/Telegram/lib_ui @@ -1 +1 @@ -Subproject commit 6bce493029a08b460db88cbaf528e49450751d1f +Subproject commit 2687a19b1435276e5a998d04b7d47df92e0c8391 diff --git a/cmake b/cmake index 5b703df9b..89c843ff6 160000 --- a/cmake +++ b/cmake @@ -1 +1 @@ -Subproject commit 5b703df9b8fc5417969fa40ddf12952368ae227b +Subproject commit 89c843ff6a007e08550c3d603d314a4edaae1732 diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 3d9e75301..f869d7697 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -167,7 +167,7 @@ parts: patches: source: https://github.com/desktop-app/patches.git source-depth: 1 - source-commit: 0edd8a93409ca24e215fc8ba1e98814893ad05cf + source-commit: cc0c2f83650bbd52064bb7bc7257c950822cce5b plugin: dump override-pull: | craftctl default From c4fc43ccc0cb309893b127da24f3cd489bfd56c5 Mon Sep 17 00:00:00 2001 From: John Preston Date: Wed, 13 Mar 2024 20:50:19 +0400 Subject: [PATCH 010/240] Fix rounding in boost features box. --- Telegram/SourceFiles/ui/boxes/boost_box.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Telegram/SourceFiles/ui/boxes/boost_box.cpp b/Telegram/SourceFiles/ui/boxes/boost_box.cpp index ff4c92c4e..0486d0cc3 100644 --- a/Telegram/SourceFiles/ui/boxes/boost_box.cpp +++ b/Telegram/SourceFiles/ui/boxes/boost_box.cpp @@ -127,6 +127,7 @@ namespace { st::boostLevelBadge.style.font->height ).marginsAdded(st::boostLevelBadge.margin); auto p = QPainter(label); + auto hq = PainterHighQualityEnabler(p); auto gradient = QLinearGradient( rect.topLeft(), rect.topRight()); From cd59f1d5762824ea6ecad918c1448de8ef53d8e9 Mon Sep 17 00:00:00 2001 From: 23rd <23rd@vivaldi.net> Date: Tue, 12 Mar 2024 15:57:00 +0300 Subject: [PATCH 011/240] Removed redundant constructor from HistoryView::ComposeControls. --- .../controls/history_view_compose_controls.cpp | 16 ---------------- .../controls/history_view_compose_controls.h | 6 ------ .../view/history_view_replies_section.cpp | 14 ++++++++++---- .../view/history_view_scheduled_section.cpp | 14 ++++++++++---- 4 files changed, 20 insertions(+), 30 deletions(-) diff --git a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp index bd8d6cb12..8eddbd40d 100644 --- a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp +++ b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp @@ -770,22 +770,6 @@ MessageToEdit FieldHeader::queryToEdit() { }; } -ComposeControls::ComposeControls( - not_null parent, - not_null controller, - Fn)> unavailableEmojiPasted, - Mode mode, - SendMenu::Type sendMenuType) -: ComposeControls(parent, ComposeControlsDescriptor{ - .show = controller->uiShow(), - .unavailableEmojiPasted = std::move(unavailableEmojiPasted), - .mode = mode, - .sendMenuType = sendMenuType, - .regularWindow = controller, - .stickerOrEmojiChosen = controller->stickerOrEmojiChosen(), -}) { -} - ComposeControls::ComposeControls( not_null parent, ComposeControlsDescriptor descriptor) diff --git a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h index d21ea9884..82d1a24de 100644 --- a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h +++ b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h @@ -128,12 +128,6 @@ public: using FieldHistoryAction = Ui::InputField::HistoryAction; using Mode = ComposeControlsMode; - ComposeControls( - not_null parent, - not_null controller, - Fn)> unavailableEmojiPasted, - Mode mode, - SendMenu::Type sendMenuType); ComposeControls( not_null parent, ComposeControlsDescriptor descriptor); diff --git a/Telegram/SourceFiles/history/view/history_view_replies_section.cpp b/Telegram/SourceFiles/history/view/history_view_replies_section.cpp index fc556245b..8813a2c05 100644 --- a/Telegram/SourceFiles/history/view/history_view_replies_section.cpp +++ b/Telegram/SourceFiles/history/view/history_view_replies_section.cpp @@ -215,10 +215,16 @@ RepliesWidget::RepliesWidget( , _topBarShadow(this) , _composeControls(std::make_unique( this, - controller, - [=](not_null emoji) { listShowPremiumToast(emoji); }, - ComposeControls::Mode::Normal, - SendMenu::Type::SilentOnly)) + ComposeControlsDescriptor{ + .show = controller->uiShow(), + .unavailableEmojiPasted = [=](not_null emoji) { + listShowPremiumToast(emoji); + }, + .mode = ComposeControls::Mode::Normal, + .sendMenuType = SendMenu::Type::SilentOnly, + .regularWindow = controller, + .stickerOrEmojiChosen = controller->stickerOrEmojiChosen(), + })) , _translateBar(std::make_unique(this, controller, history)) , _scroll(std::make_unique( this, diff --git a/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp b/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp index ca1fff7c9..2b00066bb 100644 --- a/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp +++ b/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp @@ -80,10 +80,16 @@ ScheduledWidget::ScheduledWidget( , _topBarShadow(this) , _composeControls(std::make_unique( this, - controller, - [=](not_null emoji) { listShowPremiumToast(emoji); }, - ComposeControls::Mode::Scheduled, - SendMenu::Type::Disabled)) + ComposeControlsDescriptor{ + .show = controller->uiShow(), + .unavailableEmojiPasted = [=](not_null emoji) { + listShowPremiumToast(emoji); + }, + .mode = ComposeControls::Mode::Scheduled, + .sendMenuType = SendMenu::Type::Disabled, + .regularWindow = controller, + .stickerOrEmojiChosen = controller->stickerOrEmojiChosen(), + })) , _cornerButtons( _scroll.data(), controller->chatStyle(), From 672ad64e530781d59454865ad20c3e0082703f7c Mon Sep 17 00:00:00 2001 From: 23rd <23rd@vivaldi.net> Date: Tue, 12 Mar 2024 15:36:36 +0300 Subject: [PATCH 012/240] Added initial ability to send and receive scheduled messages in forums. --- .../data/data_scheduled_messages.cpp | 39 ++++- .../data/data_scheduled_messages.h | 5 +- .../SourceFiles/history/history_widget.cpp | 3 + .../history_view_compose_controls.cpp | 37 ++++- .../controls/history_view_compose_controls.h | 4 + .../history/view/history_view_message.cpp | 4 +- .../view/history_view_replies_section.cpp | 36 ++++- .../view/history_view_scheduled_section.cpp | 145 ++++++++++++++---- .../view/history_view_scheduled_section.h | 10 +- 9 files changed, 246 insertions(+), 37 deletions(-) diff --git a/Telegram/SourceFiles/data/data_scheduled_messages.cpp b/Telegram/SourceFiles/data/data_scheduled_messages.cpp index 3fe58f530..3277cb44a 100644 --- a/Telegram/SourceFiles/data/data_scheduled_messages.cpp +++ b/Telegram/SourceFiles/data/data_scheduled_messages.cpp @@ -8,6 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_scheduled_messages.h" #include "base/unixtime.h" +#include "data/data_forum_topic.h" #include "data/data_peer.h" #include "data/data_session.h" #include "api/api_hash.h" @@ -173,6 +174,16 @@ int ScheduledMessages::count(not_null history) const { return (i != end(_data)) ? i->second.items.size() : 0; } +bool ScheduledMessages::hasFor(not_null topic) const { + const auto i = _data.find(topic->owningHistory()); + if (i == end(_data)) { + return false; + } + return ranges::any_of(i->second.items, [&](const OwnedItem &item) { + return item->topic() == topic; + }); +} + void ScheduledMessages::sendNowSimpleMessage( const MTPDupdateShortSentMessage &update, not_null local) { @@ -374,7 +385,8 @@ rpl::producer<> ScheduledMessages::updates(not_null history) { }) | rpl::to_empty; } -Data::MessagesSlice ScheduledMessages::list(not_null history) { +Data::MessagesSlice ScheduledMessages::list( + not_null history) const { auto result = Data::MessagesSlice(); const auto i = _data.find(history); if (i == end(_data)) { @@ -396,6 +408,31 @@ Data::MessagesSlice ScheduledMessages::list(not_null history) { return result; } +Data::MessagesSlice ScheduledMessages::list( + not_null topic) const { + auto result = Data::MessagesSlice(); + const auto i = _data.find(topic->Data::Thread::owningHistory()); + if (i == end(_data)) { + const auto i = _requests.find(topic->Data::Thread::owningHistory()); + if (i == end(_requests)) { + return result; + } + result.fullCount = result.skippedAfter = result.skippedBefore = 0; + return result; + } + const auto &list = i->second.items; + result.skippedAfter = result.skippedBefore = 0; + result.fullCount = int(list.size()); + result.ids = ranges::views::all( + list + ) | ranges::views::filter([&](const OwnedItem &item) { + return item->topic() == topic; + }) | ranges::views::transform( + &HistoryItem::fullId + ) | ranges::to_vector; + return result; +} + void ScheduledMessages::request(not_null history) { const auto peer = history->peer; if (peer->isBroadcast() && !Data::CanSendAnything(peer)) { diff --git a/Telegram/SourceFiles/data/data_scheduled_messages.h b/Telegram/SourceFiles/data/data_scheduled_messages.h index e4abea70a..5daacd099 100644 --- a/Telegram/SourceFiles/data/data_scheduled_messages.h +++ b/Telegram/SourceFiles/data/data_scheduled_messages.h @@ -34,6 +34,7 @@ public: [[nodiscard]] HistoryItem *lookupItem(PeerId peer, MsgId msg) const; [[nodiscard]] HistoryItem *lookupItem(FullMsgId itemId) const; [[nodiscard]] int count(not_null history) const; + [[nodiscard]] bool hasFor(not_null topic) const; [[nodiscard]] MsgId localMessageId(MsgId remoteId) const; void checkEntitiesAndUpdate(const MTPDmessage &data); @@ -51,7 +52,9 @@ public: not_null local); [[nodiscard]] rpl::producer<> updates(not_null history); - [[nodiscard]] Data::MessagesSlice list(not_null history); + [[nodiscard]] Data::MessagesSlice list(not_null history) const; + [[nodiscard]] Data::MessagesSlice list( + not_null topic) const; private: using OwnedItem = std::unique_ptr; diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp index 8a5fd3dfa..b480d1dea 100644 --- a/Telegram/SourceFiles/history/history_widget.cpp +++ b/Telegram/SourceFiles/history/history_widget.cpp @@ -2723,6 +2723,9 @@ void HistoryWidget::setupScheduledToggle() { ) | rpl::map([=](Dialogs::Key key) -> rpl::producer<> { if (const auto history = key.history()) { return session().data().scheduledMessages().updates(history); + } else if (const auto topic = key.topic()) { + return session().data().scheduledMessages().updates( + topic->owningHistory()); } return rpl::never(); }) | rpl::flatten_latest( diff --git a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp index 8eddbd40d..8fe8752c5 100644 --- a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp +++ b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.cpp @@ -850,9 +850,36 @@ ComposeControls::ComposeControls( descriptor.stickerOrEmojiChosen ) | rpl::start_to_stream(_stickerOrEmojiChosen, _wrap->lifetime()); } + if (descriptor.scheduledToggleValue) { + std::move( + descriptor.scheduledToggleValue + ) | rpl::start_with_next([=](bool hasScheduled) { + if (!_scheduled && hasScheduled) { + _scheduled = base::make_unique_q( + _wrap.get(), + st::historyScheduledToggle); + _scheduled->show(); + _scheduled->clicks( + ) | rpl::filter( + rpl::mappers::_1 == Qt::LeftButton + ) | rpl::to_empty | rpl::start_to_stream( + _showScheduledRequests, + _scheduled->lifetime()); + orderControls(); // Raise drag areas to the top. + updateControlsVisibility(); + updateControlsGeometry(_wrap->size()); + } else if (_scheduled && !hasScheduled) { + _scheduled = nullptr; + } + }, _wrap->lifetime()); + } init(); } +rpl::producer<> ComposeControls::showScheduledRequests() const { + return _showScheduledRequests.events(); +} + ComposeControls::~ComposeControls() { saveFieldToHistoryLocalDraft(); unregisterDraftSources(); @@ -2497,7 +2524,7 @@ void ComposeControls::finishAnimating() { void ComposeControls::updateControlsGeometry(QSize size) { // (_attachToggle|_replaceMedia) (_sendAs) -- _inlineResults ------ _tabbedPanel -- _fieldBarCancel - // (_attachDocument|_attachPhoto) _field (_ttlInfo) (_silent|_botCommandStart) _tabbedSelectorToggle _send + // (_attachDocument|_attachPhoto) _field (_ttlInfo) (_scheduled) (_silent|_botCommandStart) _tabbedSelectorToggle _send const auto fieldWidth = size.width() - _attachToggle->width() @@ -2508,6 +2535,7 @@ void ComposeControls::updateControlsGeometry(QSize size) { - (_likeShown ? _like->width() : 0) - (_botCommandShown ? _botCommandStart->width() : 0) - (_silent ? _silent->width() : 0) + - (_scheduled ? _scheduled->width() : 0) - (_ttlInfo ? _ttlInfo->width() : 0); { const auto oldFieldHeight = _field->height(); @@ -2566,6 +2594,10 @@ void ComposeControls::updateControlsGeometry(QSize size) { _silent->moveToRight(right, buttonsTop); right += _silent->width(); } + if (_scheduled) { + _scheduled->moveToRight(right, buttonsTop); + right += _scheduled->width(); + } if (_ttlInfo) { _ttlInfo->move(size.width() - right - _ttlInfo->width(), buttonsTop); } @@ -2595,6 +2627,9 @@ void ComposeControls::updateControlsVisibility() { } else { _attachToggle->show(); } + if (_scheduled) { + _scheduled->setVisible(!isEditingMessage()); + } } bool ComposeControls::updateLikeShown() { diff --git a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h index 82d1a24de..779c8c2d8 100644 --- a/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h +++ b/Telegram/SourceFiles/history/view/controls/history_view_compose_controls.h @@ -112,6 +112,7 @@ struct ComposeControlsDescriptor { QString voiceCustomCancelText; bool voiceLockFromBottom = false; ChatHelpers::ComposeFeatures features; + rpl::producer scheduledToggleValue; }; class ComposeControls final { @@ -172,6 +173,7 @@ public: [[nodiscard]] auto replyNextRequests() const -> rpl::producer; [[nodiscard]] rpl::producer<> focusRequests() const; + [[nodiscard]] rpl::producer<> showScheduledRequests() const; using MimeDataHook = Fn data, @@ -382,6 +384,7 @@ private: std::unique_ptr _silent; std::unique_ptr _ttlInfo; base::unique_qptr _charsLimitation; + base::unique_qptr _scheduled; std::unique_ptr _inlineResults; std::unique_ptr _tabbedPanel; @@ -408,6 +411,7 @@ private: rpl::event_stream<> _likeToggled; rpl::event_stream _replyNextRequests; rpl::event_stream<> _focusRequests; + rpl::event_stream<> _showScheduledRequests; rpl::variable _recording; rpl::variable _hasSendText; diff --git a/Telegram/SourceFiles/history/view/history_view_message.cpp b/Telegram/SourceFiles/history/view/history_view_message.cpp index 0c88e71e6..18c3dc57a 100644 --- a/Telegram/SourceFiles/history/view/history_view_message.cpp +++ b/Telegram/SourceFiles/history/view/history_view_message.cpp @@ -861,7 +861,9 @@ QSize Message::performCountOptimalSize() { void Message::refreshTopicButton() { const auto item = data(); - if (isAttachedToPrevious() || context() != Context::History) { + if (isAttachedToPrevious() + || (context() != Context::History) + || item->isScheduled()) { _topicButton = nullptr; } else if (const auto topic = item->topic()) { if (!_topicButton) { diff --git a/Telegram/SourceFiles/history/view/history_view_replies_section.cpp b/Telegram/SourceFiles/history/view/history_view_replies_section.cpp index 8813a2c05..7e4f218b2 100644 --- a/Telegram/SourceFiles/history/view/history_view_replies_section.cpp +++ b/Telegram/SourceFiles/history/view/history_view_replies_section.cpp @@ -14,6 +14,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/view/history_view_sticker_toast.h" #include "history/view/history_view_cursor_state.h" #include "history/view/history_view_contact_status.h" +#include "history/view/history_view_scheduled_section.h" #include "history/view/history_view_service_message.h" #include "history/view/history_view_pinned_tracker.h" #include "history/view/history_view_pinned_section.h" @@ -62,6 +63,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_changes.h" #include "data/data_shared_media.h" #include "data/data_send_action.h" +#include "data/data_scheduled_messages.h" #include "data/data_premium_limits.h" #include "storage/storage_media_prepare.h" #include "storage/storage_account.h" @@ -221,9 +223,19 @@ RepliesWidget::RepliesWidget( listShowPremiumToast(emoji); }, .mode = ComposeControls::Mode::Normal, - .sendMenuType = SendMenu::Type::SilentOnly, + .sendMenuType = _topic + ? SendMenu::Type::Scheduled + : SendMenu::Type::SilentOnly, .regularWindow = controller, .stickerOrEmojiChosen = controller->stickerOrEmojiChosen(), + .scheduledToggleValue = _topic + ? rpl::single(rpl::empty_value()) | rpl::then( + session().data().scheduledMessages().updates( + _topic->owningHistory()) + ) | rpl::map([=] { + return session().data().scheduledMessages().hasFor(_topic); + }) + : rpl::single(false), })) , _translateBar(std::make_unique(this, controller, history)) , _scroll(std::make_unique( @@ -364,6 +376,20 @@ RepliesWidget::RepliesWidget( ) | rpl::start_with_next([=] { _inner->update(); }, lifetime()); + } else { + session().api().sendActions( + ) | rpl::filter([=](const Api::SendAction &action) { + return (action.history == _history) + && (action.replyTo.topicRootId == _topic->topicRootId()); + }) | rpl::start_with_next([=](const Api::SendAction &action) { + if (action.options.scheduled) { + _composeControls->cancelReplyMessage(); + crl::on_main(this, [=, t = _topic] { + controller->showSection( + std::make_shared(t)); + }); + } + }, lifetime()); } setupTopicViewer(); @@ -778,6 +804,14 @@ void RepliesWidget::setupComposeControls() { data.direction == Direction::Next); }, lifetime()); + _composeControls->showScheduledRequests( + ) | rpl::start_with_next([=] { + controller()->showSection( + _topic + ? std::make_shared(_topic) + : std::make_shared(_history)); + }, lifetime()); + _composeControls->setMimeDataHook([=]( not_null data, Ui::InputField::MimeAction action) { diff --git a/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp b/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp index 2b00066bb..56f106e26 100644 --- a/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp +++ b/Telegram/SourceFiles/history/view/history_view_scheduled_section.cpp @@ -33,6 +33,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/mime_type.h" #include "chat_helpers/tabbed_selector.h" #include "main/main_session.h" +#include "data/data_forum.h" +#include "data/data_forum_topic.h" #include "data/data_session.h" #include "data/data_changes.h" #include "data/data_scheduled_messages.h" @@ -53,6 +55,16 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL namespace HistoryView { +ScheduledMemento::ScheduledMemento(not_null history) +: _history(history) +, _forumTopic(nullptr) { +} + +ScheduledMemento::ScheduledMemento(not_null forumTopic) +: _history(forumTopic->owningHistory()) +, _forumTopic(forumTopic) { +} + object_ptr ScheduledMemento::createWidget( QWidget *parent, not_null controller, @@ -61,7 +73,11 @@ object_ptr ScheduledMemento::createWidget( if (column == Window::Column::Third) { return nullptr; } - auto result = object_ptr(parent, controller, _history); + auto result = object_ptr( + parent, + controller, + _history, + _forumTopic); result->setInternalState(geometry, this); return result; } @@ -69,9 +85,11 @@ object_ptr ScheduledMemento::createWidget( ScheduledWidget::ScheduledWidget( QWidget *parent, not_null controller, - not_null history) + not_null history, + const Data::ForumTopic *forumTopic) : Window::SectionWidget(parent, controller, history->peer) , _history(history) +, _forumTopic(forumTopic) , _scroll( this, controller->chatStyle()->value(lifetime(), st::historyScroll), @@ -175,30 +193,80 @@ ScheduledWidget::ScheduledWidget( ScheduledWidget::~ScheduledWidget() = default; void ScheduledWidget::setupComposeControls() { - auto writeRestriction = rpl::combine( - session().changes().peerFlagsValue( - _history->peer, - Data::PeerUpdate::Flag::Rights), - Data::CanSendAnythingValue(_history->peer) - ) | rpl::map([=] { - const auto allWithoutPolls = Data::AllSendRestrictions() - & ~ChatRestriction::SendPolls; - const auto canSendAnything = Data::CanSendAnyOf( - _history->peer, - allWithoutPolls); - const auto restriction = Data::RestrictionError( - _history->peer, - ChatRestriction::SendOther); - auto text = !canSendAnything - ? (restriction - ? restriction - : tr::lng_group_not_accessible(tr::now)) - : std::optional(); - return text ? Controls::WriteRestriction{ - .text = std::move(*text), - .type = Controls::WriteRestrictionType::Rights, - } : Controls::WriteRestriction(); - }); + auto writeRestriction = _forumTopic + ? [&] { + auto topicWriteRestrictions = rpl::single( + ) | rpl::then(session().changes().topicUpdates( + Data::TopicUpdate::Flag::Closed + ) | rpl::filter([=](const Data::TopicUpdate &update) { + return (update.topic->history() == _history) + && (update.topic->rootId() == _forumTopic->rootId()); + }) | rpl::to_empty) | rpl::map([=] { + return (!_forumTopic + || _forumTopic->canToggleClosed() + || !_forumTopic->closed()) + ? std::optional() + : tr::lng_forum_topic_closed(tr::now); + }); + return rpl::combine( + session().changes().peerFlagsValue( + _history->peer, + Data::PeerUpdate::Flag::Rights), + Data::CanSendAnythingValue(_history->peer), + std::move(topicWriteRestrictions) + ) | rpl::map([=]( + auto, + auto, + std::optional topicRestriction) { + const auto allWithoutPolls = Data::AllSendRestrictions() + & ~ChatRestriction::SendPolls; + const auto canSendAnything = Data::CanSendAnyOf( + _forumTopic, + allWithoutPolls); + const auto restriction = Data::RestrictionError( + _history->peer, + ChatRestriction::SendOther); + auto text = !canSendAnything + ? (restriction + ? restriction + : topicRestriction + ? std::move(topicRestriction) + : tr::lng_group_not_accessible(tr::now)) + : topicRestriction + ? std::move(topicRestriction) + : std::optional(); + return text ? Controls::WriteRestriction{ + .text = std::move(*text), + .type = Controls::WriteRestrictionType::Rights, + } : Controls::WriteRestriction(); + }); + }() + : [&] { + return rpl::combine( + session().changes().peerFlagsValue( + _history->peer, + Data::PeerUpdate::Flag::Rights), + Data::CanSendAnythingValue(_history->peer) + ) | rpl::map([=] { + const auto allWithoutPolls = Data::AllSendRestrictions() + & ~ChatRestriction::SendPolls; + const auto canSendAnything = Data::CanSendAnyOf( + _history->peer, + allWithoutPolls); + const auto restriction = Data::RestrictionError( + _history->peer, + ChatRestriction::SendOther); + auto text = !canSendAnything + ? (restriction + ? restriction + : tr::lng_group_not_accessible(tr::now)) + : std::optional(); + return text ? Controls::WriteRestriction{ + .text = std::move(*text), + .type = Controls::WriteRestrictionType::Rights, + } : Controls::WriteRestriction(); + }); + }(); _composeControls->setHistory({ .history = _history.get(), .writeRestriction = std::move(writeRestriction), @@ -564,6 +632,12 @@ Api::SendAction ScheduledWidget::prepareSendAction( Api::SendOptions options) const { auto result = Api::SendAction(_history, options); result.options.sendAs = _composeControls->sendAsPeer(); + if (_forumTopic) { + result.replyTo.topicRootId = _forumTopic->topicRootId(); + result.replyTo.messageId = FullMsgId( + history()->peer->id, + _forumTopic->topicRootId()); + } return result; } @@ -576,7 +650,7 @@ void ScheduledWidget::send() { const auto error = GetErrorTextForSending( _history->peer, { - .topicRootId = MsgId(), + .topicRootId = _forumTopic ? _forumTopic->topicRootId() : MsgId(), .forward = nullptr, .text = &textWithTags, .ignoreSlowmodeCountdown = true, @@ -943,6 +1017,16 @@ bool ScheduledWidget::returnTabbedSelector() { } std::shared_ptr ScheduledWidget::createMemento() { + if (_forumTopic) { + if (const auto forum = history()->asForum()) { + const auto rootId = _forumTopic->topicRootId(); + if (const auto topic = forum->topicFor(rootId)) { + auto result = std::make_shared(topic); + saveState(result.get()); + return result; + } + } + } auto result = std::make_shared(history()); saveState(result.get()); return result; @@ -1098,7 +1182,9 @@ rpl::producer ScheduledWidget::listSource( return rpl::single(rpl::empty) | rpl::then( data->scheduledMessages().updates(_history) ) | rpl::map([=] { - return data->scheduledMessages().list(_history); + return _forumTopic + ? data->scheduledMessages().list(_forumTopic) + : data->scheduledMessages().list(_history); }) | rpl::after_next([=](const Data::MessagesSlice &slice) { highlightSingleNewMessage(slice); }); @@ -1187,6 +1273,9 @@ void ScheduledWidget::listUpdateDateLink( } bool ScheduledWidget::listElementHideReply(not_null view) { + if (const auto root = view->data()->topicRootId()) { + return root == view->data()->replyTo().messageId.msg; + } return false; } diff --git a/Telegram/SourceFiles/history/view/history_view_scheduled_section.h b/Telegram/SourceFiles/history/view/history_view_scheduled_section.h index 857410b4f..850e56bb7 100644 --- a/Telegram/SourceFiles/history/view/history_view_scheduled_section.h +++ b/Telegram/SourceFiles/history/view/history_view_scheduled_section.h @@ -58,7 +58,8 @@ public: ScheduledWidget( QWidget *parent, not_null controller, - not_null history); + not_null history, + const Data::ForumTopic *forumTopic); ~ScheduledWidget(); not_null history() const; @@ -261,6 +262,7 @@ private: Api::SendOptions options); const not_null _history; + const Data::ForumTopic *_forumTopic; std::shared_ptr _theme; object_ptr _scroll; QPointer _inner; @@ -280,9 +282,8 @@ private: class ScheduledMemento : public Window::SectionMemento { public: - ScheduledMemento(not_null history) - : _history(history) { - } + ScheduledMemento(not_null history); + ScheduledMemento(not_null forumTopic); object_ptr createWidget( QWidget *parent, @@ -300,6 +301,7 @@ public: private: const not_null _history; + const Data::ForumTopic *_forumTopic; ListMemento _list; }; From 125f856e67b38c075084359f6c58e68415526359 Mon Sep 17 00:00:00 2001 From: John Preston Date: Thu, 24 Aug 2023 18:04:32 +0200 Subject: [PATCH 013/240] Proof-of-concept (WebView2 / Local) iv. --- Telegram/CMakeLists.txt | 9 +- .../Resources/iv_html/highlight.9.12.0.css | 1 + .../Resources/iv_html/highlight.9.12.0.js | 3 + Telegram/Resources/iv_html/page.css | 871 ++++++++++++++ Telegram/Resources/iv_html/page.js | 86 ++ Telegram/Resources/qrc/telegram/iv.qrc | 8 + .../boxes/peers/edit_peer_color_box.cpp | 2 + Telegram/SourceFiles/core/application.cpp | 5 + Telegram/SourceFiles/core/application.h | 10 + Telegram/SourceFiles/data/data_session.cpp | 18 + Telegram/SourceFiles/data/data_session.h | 6 + Telegram/SourceFiles/data/data_web_page.cpp | 6 + Telegram/SourceFiles/data/data_web_page.h | 7 + .../history/view/history_view_view_button.cpp | 5 + .../view/media/history_view_web_page.cpp | 31 +- Telegram/SourceFiles/iv/iv_controller.cpp | 115 ++ Telegram/SourceFiles/iv/iv_controller.h | 42 + Telegram/SourceFiles/iv/iv_data.cpp | 63 + Telegram/SourceFiles/iv/iv_data.h | 47 + Telegram/SourceFiles/iv/iv_instance.cpp | 663 +++++++++++ Telegram/SourceFiles/iv/iv_instance.h | 45 + Telegram/SourceFiles/iv/iv_pch.h | 27 + Telegram/SourceFiles/iv/iv_prepare.cpp | 1038 +++++++++++++++++ Telegram/SourceFiles/iv/iv_prepare.h | 25 + Telegram/cmake/td_iv.cmake | 35 + 25 files changed, 3164 insertions(+), 4 deletions(-) create mode 100644 Telegram/Resources/iv_html/highlight.9.12.0.css create mode 100644 Telegram/Resources/iv_html/highlight.9.12.0.js create mode 100644 Telegram/Resources/iv_html/page.css create mode 100644 Telegram/Resources/iv_html/page.js create mode 100644 Telegram/Resources/qrc/telegram/iv.qrc create mode 100644 Telegram/SourceFiles/iv/iv_controller.cpp create mode 100644 Telegram/SourceFiles/iv/iv_controller.h create mode 100644 Telegram/SourceFiles/iv/iv_data.cpp create mode 100644 Telegram/SourceFiles/iv/iv_data.h create mode 100644 Telegram/SourceFiles/iv/iv_instance.cpp create mode 100644 Telegram/SourceFiles/iv/iv_instance.h create mode 100644 Telegram/SourceFiles/iv/iv_pch.h create mode 100644 Telegram/SourceFiles/iv/iv_prepare.cpp create mode 100644 Telegram/SourceFiles/iv/iv_prepare.h create mode 100644 Telegram/cmake/td_iv.cmake diff --git a/Telegram/CMakeLists.txt b/Telegram/CMakeLists.txt index 32acbe57e..5d30acc96 100644 --- a/Telegram/CMakeLists.txt +++ b/Telegram/CMakeLists.txt @@ -30,8 +30,9 @@ include(cmake/lib_tgvoip.cmake) include(cmake/lib_tgcalls.cmake) include(cmake/lib_prisma.cmake) include(cmake/td_export.cmake) -include(cmake/td_mtproto.cmake) +include(cmake/td_iv.cmake) include(cmake/td_lang.cmake) +include(cmake/td_mtproto.cmake) include(cmake/td_scheme.cmake) include(cmake/td_ui.cmake) include(cmake/generate_appdata_changelog.cmake) @@ -62,8 +63,9 @@ PRIVATE desktop-app::external_minizip tdesktop::td_export - tdesktop::td_mtproto + tdesktop::td_iv tdesktop::td_lang + tdesktop::td_mtproto tdesktop::td_scheme tdesktop::td_ui desktop-app::lib_webrtc @@ -995,6 +997,8 @@ PRIVATE intro/intro_step.h intro/intro_widget.cpp intro/intro_widget.h + iv/iv_instance.cpp + iv/iv_instance.h lang/lang_cloud_manager.cpp lang/lang_cloud_manager.h lang/lang_instance.cpp @@ -1567,6 +1571,7 @@ PRIVATE qrc/emoji_preview.qrc qrc/telegram/animations.qrc qrc/telegram/export.qrc + qrc/telegram/iv.qrc qrc/telegram/telegram.qrc qrc/telegram/sounds.qrc winrc/Telegram.rc diff --git a/Telegram/Resources/iv_html/highlight.9.12.0.css b/Telegram/Resources/iv_html/highlight.9.12.0.css new file mode 100644 index 000000000..7d8be18d0 --- /dev/null +++ b/Telegram/Resources/iv_html/highlight.9.12.0.css @@ -0,0 +1 @@ +.hljs{display:block;overflow-x:auto;padding:0.5em;background:#F0F0F0}.hljs,.hljs-subst{color:#444}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-built_in,.hljs-bullet,.hljs-code,.hljs-addition{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold} \ No newline at end of file diff --git a/Telegram/Resources/iv_html/highlight.9.12.0.js b/Telegram/Resources/iv_html/highlight.9.12.0.js new file mode 100644 index 000000000..f30a334c9 --- /dev/null +++ b/Telegram/Resources/iv_html/highlight.9.12.0.js @@ -0,0 +1,3 @@ +/*! highlight.js v9.12.0 | BSD3 License | git.io/hljslicense */ +!function(e){var t="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):t&&(t.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return t.hljs}))}(function(e){function t(e){return e.replace(/&/g,"&").replace(//g,">")}function r(e){return e.nodeName.toLowerCase()}function a(e,t){var r=e&&e.exec(t);return r&&0===r.index}function n(e){return E.test(e)}function i(e){var t,r,a,i,s=e.className+" ";if(s+=e.parentNode?e.parentNode.className:"",r=M.exec(s))return w(r[1])?r[1]:"no-highlight";for(s=s.split(/\s+/),t=0,a=s.length;a>t;t++)if(i=s[t],n(i)||w(i))return i}function s(e){var t,r={},a=Array.prototype.slice.call(arguments,1);for(t in e)r[t]=e[t];return a.forEach(function(e){for(t in e)r[t]=e[t]}),r}function c(e){var t=[];return function a(e,n){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?n+=i.nodeValue.length:1===i.nodeType&&(t.push({event:"start",offset:n,node:i}),n=a(i,n),r(i).match(/br|hr|img|input/)||t.push({event:"stop",offset:n,node:i}));return n}(e,0),t}function o(e,a,n){function i(){return e.length&&a.length?e[0].offset!==a[0].offset?e[0].offset"}function c(e){u+=""}function o(e){("start"===e.event?s:c)(e.node)}for(var l=0,u="",d=[];e.length||a.length;){var b=i();if(u+=t(n.substring(l,b[0].offset)),l=b[0].offset,b===e){d.reverse().forEach(c);do o(b.splice(0,1)[0]),b=i();while(b===e&&b.length&&b[0].offset===l);d.reverse().forEach(s)}else"start"===b[0].event?d.push(b[0].node):d.pop(),o(b.splice(0,1)[0])}return u+t(n.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(t){return s(e,{v:null},t)})),e.cached_variants||e.eW&&[s(e)]||[e]}function u(e){function t(e){return e&&e.source||e}function r(r,a){return new RegExp(t(r),"m"+(e.cI?"i":"")+(a?"g":""))}function a(n,i){if(!n.compiled){if(n.compiled=!0,n.k=n.k||n.bK,n.k){var s={},c=function(t,r){e.cI&&(r=r.toLowerCase()),r.split(" ").forEach(function(e){var r=e.split("|");s[r[0]]=[t,r[1]?Number(r[1]):1]})};"string"==typeof n.k?c("keyword",n.k):k(n.k).forEach(function(e){c(e,n.k[e])}),n.k=s}n.lR=r(n.l||/\w+/,!0),i&&(n.bK&&(n.b="\\b("+n.bK.split(" ").join("|")+")\\b"),n.b||(n.b=/\B|\b/),n.bR=r(n.b),n.e||n.eW||(n.e=/\B|\b/),n.e&&(n.eR=r(n.e)),n.tE=t(n.e)||"",n.eW&&i.tE&&(n.tE+=(n.e?"|":"")+i.tE)),n.i&&(n.iR=r(n.i)),null==n.r&&(n.r=1),n.c||(n.c=[]),n.c=Array.prototype.concat.apply([],n.c.map(function(e){return l("self"===e?n:e)})),n.c.forEach(function(e){a(e,n)}),n.starts&&a(n.starts,i);var o=n.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([n.tE,n.i]).map(t).filter(Boolean);n.t=o.length?r(o.join("|"),!0):{exec:function(){return null}}}}a(e)}function d(e,r,n,i){function s(e,t){var r,n;for(r=0,n=t.c.length;n>r;r++)if(a(t.c[r].bR,e))return t.c[r]}function c(e,t){if(a(e.eR,t)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?c(e.parent,t):void 0}function o(e,t){return!n&&a(t.iR,e)}function l(e,t){var r=v.cI?t[0].toLowerCase():t[0];return e.k.hasOwnProperty(r)&&e.k[r]}function p(e,t,r,a){var n=a?"":L.classPrefix,i='',i+t+s}function m(){var e,r,a,n;if(!N.k)return t(E);for(n="",r=0,N.lR.lastIndex=0,a=N.lR.exec(E);a;)n+=t(E.substring(r,a.index)),e=l(N,a),e?(M+=e[1],n+=p(e[0],t(a[0]))):n+=t(a[0]),r=N.lR.lastIndex,a=N.lR.exec(E);return n+t(E.substr(r))}function f(){var e="string"==typeof N.sL;if(e&&!x[N.sL])return t(E);var r=e?d(N.sL,E,!0,k[N.sL]):b(E,N.sL.length?N.sL:void 0);return N.r>0&&(M+=r.r),e&&(k[N.sL]=r.top),p(r.language,r.value,!1,!0)}function g(){C+=null!=N.sL?f():m(),E=""}function _(e){C+=e.cN?p(e.cN,"",!0):"",N=Object.create(e,{parent:{value:N}})}function h(e,t){if(E+=e,null==t)return g(),0;var r=s(t,N);if(r)return r.skip?E+=t:(r.eB&&(E+=t),g(),r.rB||r.eB||(E=t)),_(r,t),r.rB?0:t.length;var a=c(N,t);if(a){var n=N;n.skip?E+=t:(n.rE||n.eE||(E+=t),g(),n.eE&&(E=t));do N.cN&&(C+=R),N.skip||(M+=N.r),N=N.parent;while(N!==a.parent);return a.starts&&_(a.starts,""),n.rE?0:t.length}if(o(t,N))throw new Error('Illegal lexeme "'+t+'" for mode "'+(N.cN||"")+'"');return E+=t,t.length||1}var v=w(e);if(!v)throw new Error('Unknown language: "'+e+'"');u(v);var y,N=i||v,k={},C="";for(y=N;y!==v;y=y.parent)y.cN&&(C=p(y.cN,"",!0)+C);var E="",M=0;try{for(var B,S,$=0;;){if(N.t.lastIndex=$,B=N.t.exec(r),!B)break;S=h(r.substring($,B.index),B[0]),$=B.index+S}for(h(r.substr($)),y=N;y.parent;y=y.parent)y.cN&&(C+=R);return{r:M,value:C,language:e,top:N}}catch(A){if(A.message&&-1!==A.message.indexOf("Illegal"))return{r:0,value:t(r)};throw A}}function b(e,r){r=r||L.languages||k(x);var a={r:0,value:t(e)},n=a;return r.filter(w).forEach(function(t){var r=d(t,e,!1);r.language=t,r.r>n.r&&(n=r),r.r>a.r&&(n=a,a=r)}),n.language&&(a.second_best=n),a}function p(e){return L.tabReplace||L.useBR?e.replace(B,function(e,t){return L.useBR&&"\n"===e?"
":L.tabReplace?t.replace(/\t/g,L.tabReplace):""}):e}function m(e,t,r){var a=t?C[t]:r,n=[e.trim()];return e.match(/\bhljs\b/)||n.push("hljs"),-1===e.indexOf(a)&&n.push(a),n.join(" ").trim()}function f(e){var t,r,a,s,l,u=i(e);n(u)||(L.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e,l=t.textContent,a=u?d(u,l,!0):b(l),r=c(t),r.length&&(s=document.createElementNS("http://www.w3.org/1999/xhtml","div"),s.innerHTML=a.value,a.value=o(r,c(s),l)),a.value=p(a.value),e.innerHTML=a.value,e.className=m(e.className,u,a.language),e.result={language:a.language,re:a.r},a.second_best&&(e.second_best={language:a.second_best.language,re:a.second_best.r}))}function g(e){L=s(L,e)}function _(){if(!_.called){_.called=!0;var e=document.querySelectorAll("pre code");N.forEach.call(e,f)}}function h(){addEventListener("DOMContentLoaded",_,!1),addEventListener("load",_,!1)}function v(t,r){var a=x[t]=r(e);a.aliases&&a.aliases.forEach(function(e){C[e]=t})}function y(){return k(x)}function w(e){return e=(e||"").toLowerCase(),x[e]||x[C[e]]}var N=[],k=Object.keys,x={},C={},E=/^(no-?highlight|plain|text)$/i,M=/\blang(?:uage)?-([\w-]+)\b/i,B=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,R="
",L={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=d,e.highlightAuto=b,e.fixMarkup=p,e.highlightBlock=f,e.configure=g,e.initHighlighting=_,e.initHighlightingOnLoad=h,e.registerLanguage=v,e.listLanguages=y,e.getLanguage=w,e.inherit=s,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(t,r,a){var n=e.inherit({cN:"comment",b:t,e:r,c:[]},a||{});return n.c.push(e.PWM),n.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),n},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e.registerLanguage("apache",function(e){var t={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:""},{cN:"attribute",b:/\w+/,r:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",t]},t,e.QSM]}}],i:/\S/}}),e.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},r={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,r,a,t]}}),e.registerLanguage("coffeescript",function(e){var t={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},r="[A-Za-z$_][0-9A-Za-z$_]*",a={cN:"subst",b:/#\{/,e:/}/,k:t},n=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,a]},{b:/"/,e:/"/,c:[e.BE,a]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[a,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+r},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];a.c=n;var i=e.inherit(e.TM,{b:r}),s="(\\(.*\\))?\\s*\\B[-=]>",c={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:t,c:["self"].concat(n)}]};return{aliases:["coffee","cson","iced"],k:t,i:/\/\*/,c:n.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+r+"\\s*=\\s*"+s,e:"[-=]>",rB:!0,c:[i,c]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:s,e:"[-=]>",rB:!0,c:[c]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[i]},i]},{b:r+":",e:":",rB:!0,rE:!0,r:0}])}}),e.registerLanguage("cpp",function(e){var t={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[e.BE]},{b:'(u8?|U)?R"',e:'"',c:[e.BE]},{b:"'\\\\?.",e:"'",i:"."}]},a={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},n={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},e.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},e.CLCM,e.CBCM]},i=e.IR+"\\s*\\(",s={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},c=[t,e.CLCM,e.CBCM,a,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:s,i:"",k:s,c:["self",t]},{b:e.IR+"::",k:s},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:s,c:c.concat([{b:/\(/,e:/\)/,k:s,c:c.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+e.IR+"[\\*&\\s]+)+"+i,rB:!0,e:/[{;=]/,eE:!0,k:s,i:/[^\w\s\*&]/,c:[{b:i,rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:s,r:0,c:[e.CLCM,e.CBCM,r,a,t]},e.CLCM,e.CBCM,n]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},e.TM]}]),exports:{preprocessor:n,strings:r,k:s}}}),e.registerLanguage("cs",function(e){var t={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},r={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},a=e.inherit(r,{i:/\n/}),n={cN:"subst",b:"{",e:"}",k:t},i=e.inherit(n,{i:/\n/}),s={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,i]},c={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},n]},o=e.inherit(c,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},i]});n.c=[c,s,r,e.ASM,e.QSM,e.CNM,e.CBCM],i.c=[o,s,a,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[c,s,r,e.ASM,e.QSM]},u=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:t,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:""},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+u+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:t,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}}),e.registerLanguage("css",function(e){var t="[a-zA-Z-][a-zA-Z0-9_-]*",r={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:t,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,r]}]}}),e.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}}),e.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}}),e.registerLanguage("ini",function(e){var t={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},t,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}}),e.registerLanguage("java",function(e){var t="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=t+"(<"+t+"(\\s*,\\s*"+t+")*>)?",a="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",n="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",i={cN:"number",b:n,r:0};return{aliases:["jsp"],k:a,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+r+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:a,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:a,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},i,{cN:"meta",b:"@[A-Za-z]+"}]}}),e.registerLanguage("javascript",function(e){var t="[A-Za-z$_][0-9A-Za-z$_]*",r={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:r,c:[]},i={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,i,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:r,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,i,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:t+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:t,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+t+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:t},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:r,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:t}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}}),e.registerLanguage("json",function(e){var t={literal:"true false null"},r=[e.QSM,e.CNM],a={e:",",eW:!0,eE:!0,c:r,k:t},n={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(a,{b:/:/})],i:"\\S"},i={b:"\\[",e:"\\]",c:[e.inherit(a)],i:"\\S"};return r.splice(r.length,0,n,i),{c:r,k:t,i:"\\S"}}),e.registerLanguage("makefile",function(e){var t={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},e.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[r],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[r],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},r]}]}}),e.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}}),e.registerLanguage("nginx",function(e){var t={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},r={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,t],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[t]},{cN:"regexp",c:[e.BE,t],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},t]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:r}],r:0}],i:"[^\\s\\}]"}}),e.registerLanguage("objectivec",function(e){var t={cN:"built_in",b:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},r={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},a=/[a-zA-Z@][a-zA-Z0-9_]*/,n="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:r,l:a,i:""}]}]},{cN:"class",b:"("+n.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:n,l:a,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}}),e.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},a={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],s=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),a,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=s,a.c=s,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:s}}),e.registerLanguage("php",function(e){var t={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},r={cN:"meta",b:/<\?(php)?|\?>/},a={cN:"string",c:[e.BE,r],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},n={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[r]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},r,{cN:"keyword",b:/\$this\b/},t,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",t,e.CBCM,a,n]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},a,n]}}),e.registerLanguage("python",function(e){var t={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},r={cN:"meta",b:/^(>>>|\.\.\.) /},a={cN:"subst",b:/\{/,e:/\}/,k:t,i:/#/},n={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[r],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[r],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[r,a]},{b:/(fr|rf|f)"""/,e:/"""/,c:[r,a]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[a]},{b:/(fr|rf|f)"/,e:/"/,c:[a]},e.ASM,e.QSM]},i={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},s={cN:"params",b:/\(/,e:/\)/,c:["self",r,i,n]};return a.c=[n,i,r],{aliases:["py","gyp"],k:t,i:/(<\/|->|\?)|=>/,c:[r,i,n,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,s,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}}),e.registerLanguage("ruby",function(e){ +var t="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},a={cN:"doctag",b:"@[A-Za-z]+"},n={b:"#<",e:">"},i=[e.C("#","$",{c:[a]}),e.C("^\\=begin","^\\=end",{c:[a],r:10}),e.C("^__END__","\\n$")],s={cN:"subst",b:"#\\{",e:"}",k:r},c={cN:"string",c:[e.BE,s],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},o={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},l=[c,n,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(i)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:t}),o].concat(i)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[c,{b:t}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[n,{cN:"regexp",c:[e.BE,s],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(i),r:0}].concat(i);s.c=l,o.c=l;var u="[>?]>",d="[\\w#]+\\(\\w+\\):\\d+:\\d+>",b="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",p=[{b:/^\s*=>/,starts:{e:"$",c:l}},{cN:"meta",b:"^("+u+"|"+d+"|"+b+")",starts:{e:"$",c:l}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:i.concat(p).concat(l)}}),e.registerLanguage("shell",function(e){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}}),e.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}}),e}); \ No newline at end of file diff --git a/Telegram/Resources/iv_html/page.css b/Telegram/Resources/iv_html/page.css new file mode 100644 index 000000000..b5feac073 --- /dev/null +++ b/Telegram/Resources/iv_html/page.css @@ -0,0 +1,871 @@ +body { + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 25px; + padding: 0; + margin: 0; +} +article { + padding-bottom: 12px; + overflow: hidden; + white-space: pre-wrap; + max-width: 732px; + margin: 0 auto; +} +article h1, +article h2 { + font-family: 'Georgia'; + font-size: 28px; + line-height: 31px; + margin: 21px 18px 12px; + font-weight: normal; + min-height: 31px; +} +article h2 { + font-size: 24px; + line-height: 30px; + margin: -6px 18px 12px; + color: #777; +} +article h6.kicker { + font-family: 'Helvetica Neue'; + font-size: 14px; + line-height: 17px; + margin: 21px 18px 12px; + font-weight: 500; + color: #79828B; +} +article h6.kicker + h1 { + margin-top: 12px; +} +article address { + font-size: 15px; + color: #79828B; + margin: 12px 18px 21px; + font-style: normal; +} +article.rtl address { + direction: ltr; + text-align: right; +} +article address figure { + width: 25px; + height: 25px; + float: right; + margin: 0 0 0 12px; + background: no-repeat center; + background-size: cover; + border-radius: 50%; +} +article address a, +article address a[href] { + color: #79828B; +} +article address a[href] { + text-decoration: underline; +} +article a[href] { + color: #007EE5; + text-decoration: none; +} +article span.reference { + border: dotted #ddd; + border-width: 1px 1px 1px 2px; + background: rgba(255, 255, 255, 0.7); + margin: 0 1px; + padding: 2px; + position: relative; +} +article.rtl span.reference { + border-width: 1px 0 1px 1px; +} +article code { + font-size: 0.94em; + background: #eee; + border-radius: 2px; + padding: 0 3px 1px; +} +article mark { + background: #fcf8e3; + border-radius: 2px; + padding: 0 3px 1px; +} +article sup, +article sub { + font-size: 0.75em; + line-height: 1; +} +article p { + margin: 0 18px 12px; + word-wrap: break-word; +} +article ul p, +article ol p { + margin: 0 0 6px; +} +article pre, +article pre.hljs { + font-family: Menlo; + margin: 14px 0; + padding: 7px 18px; + background: #F5F8FC; + font-size: 16px; + white-space: pre-wrap; + word-wrap: break-word; + overflow-x: visible; + position: relative; +} +article ul pre, +article ol pre, +article ul pre.hljs, +article ol pre.hljs { + margin: 6px 0 6px -18px; +} +article.rtl ul pre, +article.rtl ol pre, +article.rtl ul pre.hljs, +article.rtl ol pre.hljs { + margin-right: -18px; + margin-left: 0; +} +article pre + pre { + margin-top: -14px; +} +article h3, +article h4 { + font-family: 'Georgia'; + font-size: 24px; + line-height: 30px; + margin: 18px 18px 9px; + font-weight: normal; +} +article h4 { + font-size: 19px; + margin: 18px 18px 7px; +} +article ul h3, +article ol h3 { + margin: 12px 0 7px; +} +article ul h4, +article ol h4 { + margin: 10px 0 5px; +} +article blockquote { + font-family: 'Georgia'; + margin: 18px 18px 16px; + padding-left: 22px; + position: relative; + font-style: italic; + word-wrap: break-word; +} +article blockquote:before { + content: ''; + position: absolute; + left: 1px; + top: 3px; + bottom: 3px; + width: 3px; + background-color: #000; + border-radius: 3px; +} +article.rtl blockquote { + padding-right: 22px; + padding-left: 0; +} +article.rtl blockquote:before { + right: 1px; + left: auto; +} +article aside { + font-family: 'Georgia'; + margin: 18px 18px 16px; + padding: 0 18px; + text-align: center; + font-style: italic; +} +article ul blockquote, +article ol blockquote, +article ul aside, +article ol aside { + margin: 12px 0 10px; +} +article blockquote cite, +article aside cite, +article footer cite, +article .iv-pullquote cite { + font-family: 'Helvetica Neue'; + font-size: 15px; + display: block; + color: #79828B; + line-height: 19px; + padding: 5px 0 2px; + font-style: normal; +} +article hr { + width: 50%; + margin: 36px auto 26px; + padding: 2px 0 10px; + border: none; +} +article ul hr, +article ol hr { + margin: 18px auto; +} +article hr:before { + content: ''; + display: block; + border-top: 1px solid #c9cdd1; + padding: 0 0 2px; +} +article footer hr { + margin: 18px auto 6px; +} +article ul, +article ol { + margin: 0 18px 12px; + padding-left: 18px; +} +article.rtl ul, +article.rtl ol { + padding-right: 18px; + padding-left: 0; +} +/*article ul { + list-style: none; +}*/ +article ul > li, +article ol > li { + padding-left: 4px; +} +article.rtl ul > li, +article.rtl ol > li { + padding-right: 4px; + padding-left: 0; +} +/*article ul > li { + position: relative; +} +article ul > li:before { + content: '\2022'; + position: absolute; + display: block; + font-size: 163%; + left: -19px; + top: 1px; +} +article.rtl ul > li:before { + left: auto; + right: -19px; +}*/ +article ul ul, +article ul ol, +article ol ul, +article ol ol { + margin: 0 0 12px; +} + +article table { + width: 100%; + border-collapse: collapse; +} +article table.bordered, +article table.bordered td, +article table.bordered th { + border: 1px solid #ddd; +} +article table.striped tr:nth-child(odd) td { + background-color: #f7f7f7; +} +article table caption { + font-size: 15px; + line-height: 18px; + margin: 4px 0 7px; + text-align: left; + color: #79828B; +} +article.rtl table caption { + text-align: right; +} +article td, +article th { + font-size: 15px; + line-height: 21px; + padding: 6px 5px 5px; + background-color: #fff; + vertical-align: middle; + font-weight: normal; + text-align: left; +} +article th { + background-color: #efefef; +} +article.rtl table td, +article.rtl table th { + text-align: right; +} +article details { + position: relative; + margin: 0 0 12px; + padding: 0 0 1px; +} +article details:before { + content: ''; + display: block; + border-bottom: 1px solid #c8c7cb; + position: absolute; + left: 18px; + right: 0; + bottom: 0; +} +article.rtl details:before { + right: 18px; + left: 0; +} +article details + details { + margin-top: -12px; +} +article details > details:last-child { + margin-bottom: -1px; +} +article summary { + padding: 10px 18px 10px 42px; + line-height: 25px; + min-height: 25px; +} +article.rtl summary { + padding-left: 18px; + padding-right: 42px; +} +article summary:hover { + cursor: pointer; +} +article summary:focus { + outline: none; +} +article summary::-webkit-details-marker { + display: none; +} +article summary::marker { + content: ''; +} +article summary:before { + content: ''; + background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAICAYAAADN5B7xAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAH1JREFUeNqEjUEKgCAQRSfrNi1bdZFadJjsMC46SSAIHqjB5mcFqdFfhD3eUyKZtb6ln92O2janmXdvrRu+ZTfAgasu1jAHU4qiHAwc/Ff4oCQKsxxZ0NT33XrxUTjkWvgiXFf3TWkU6Vt+XihH515yFiQRpfLnEMUw3yHAABZNTT9emBrvAAAAAElFTkSuQmCC'); + transition: all .2s ease; + display: inline-block; + position: absolute; + width: 12px; + height: 8px; + left: 18px; + top: 18px; +} +article.rtl summary:before { + right: 18px; + left: auto; +} +@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { + article summary:before { + background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAQCAYAAAAMJL+VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPxJREFUeNq8lEESgiAUhgFbZ0epSW28gB2pZbrrSukBHDWto1TrwHih45AiaDOxesLP9w1PBlzXNfrLSNPqkGWV8ysHGMBqv4mAlyFC7MRPk+T51Z0Lh73AAJZgIoRFUR/bEMb4TggJPG9TTIUzxmIuWHWzOCLfQQgwRiedRMBpIsObFvn+NgSTLEE2bCiKm6eDQ0bAkS2v4AjYuPvJcqtEu9DDshaB665zFZzSV6yCfyr5JplLTOA9wZiEg/a+72Qic9nxubMOPijQSZraCK4UjEiezSVYmsBHBSrJAEIJ1wr0knG4kUAt0cONBX2JGXzGi1uG7SNmOt4CDADc4r+K4txg+wAAAABJRU5ErkJggg=='); + background-size: 12px 8px; + } +} +article details[open] > summary:before { + /*transform: rotateZ(-180deg);*/ + transform: scaleY(-1); +} +article li summary { + padding-left: 24px; +} +article li details:before, +article li summary:before { + left: 0; +} + +img, +video, +iframe { + max-width: 100%; + max-height: 400px; + vertical-align: top; +} +video { + width: 100%; +} +audio { + width: 100%; + width: calc(100% - 36px); + margin: 0 18px; + vertical-align: top; +} +img { + font-size: 12px; + line-height: 14px; + color: #999; +} +img.pic { + max-height: none; + font-size: inherit; + vertical-align: middle; + position: relative; + top: -0.1em; +} +img.pic.optional { + opacity: 0.4; +} +body:hover img.pic.optional { + opacity: 1; +} +iframe.autosize { + max-height: none; +} +.iframe-wrap { + max-width: 100%; + vertical-align: top; + display: inline-block; + position: relative; +} +.iframe-wrap iframe { + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; +} +figure { + margin: 0 0 16px; + padding: 0; + text-align: center; + position: relative; +} +figure.nowide { + margin-left: 18px; + margin-right: 18px; +} +figure.nowide figcaption { + padding-left: 0; + padding-right: 0; +} +ul figure.nowide, +ol figure.nowide { + margin: 0 0 12px; +} +figure > figure { + margin: 0; +} +figcaption { + font-size: 15px; + color: #79828B; + padding: 6px 18px 0; + line-height: 19px; + text-align: left; +} +article.rtl figcaption { + text-align: right; +} +ul figcaption, +ol figcaption { + padding-left: 0; + padding-right: 0; +} +figcaption > cite { + font-family: 'Helvetica Neue'; + font-size: 12px; + display: block; + line-height: 15px; + padding: 2px 0 0; + font-style: normal; +} +footer { + margin: 12px 18px; + color: #79828B; +} + +figure.slideshow-wrap { + position: relative; +} +figure.slideshow { + position: relative; + white-space: nowrap; + width: 100%; + background: #000; + overflow: hidden; +} +figure.slideshow > figure { + position: static !important; + display: inline-block; + width: 100%; + vertical-align: middle; + transition: margin .3s; +} +figure.slideshow > figure figcaption { + box-sizing: border-box; + position: absolute; + bottom: 0; + width: 100%; + padding-bottom: 36px; +} +figure.slideshow > figure figcaption:after { + content: ''; + display: block; + position: absolute; + left: 0; + right: 0; + bottom: 0; + top: -75px; + background: -moz-linear-gradient(top,rgba(64,64,64,0),rgba(64,64,64,.55)); + background: -webkit-gradient(linear,0 0,0 100%,from(rgba(64,64,64,0)),to(rgba(64,64,64,.55))); + background: -o-linear-gradient(rgba(64,64,64,0),rgba(64,64,64,.55)); + pointer-events: none; +} +figure.slideshow > figure figcaption > span, +figure.slideshow > figure figcaption > cite { + position: relative; + color: #fff; + text-shadow: 0 1px rgba(0, 0, 0, .4); + z-index: 1; + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +figure.slideshow > figure figcaption > span { + display: -webkit-box; + max-height: 3.8em; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + white-space: pre-wrap; +} +figure.slideshow > figure figcaption code { + text-shadow: none; + background: rgba(204, 204, 204, .7); + color: #fff; +} +figure.slideshow > figure figcaption mark { + text-shadow: none; + background: rgba(33, 123, 134, .7); + color: #fff; +} +figure.slideshow > figure figcaption a, +figure.slideshow > figure figcaption a:hover { + color: #66baff; +} +.slideshow-buttons { + position: absolute; + width: 100%; + bottom: 10px; + white-space: nowrap; + overflow: hidden; + z-index: 3; +} +.slideshow-buttons > fieldset { + padding: 0 10px 20px; + margin: 0 0 -20px; + border: none; + line-height: 0; + overflow: hidden; + overflow-x: auto; + min-width: auto; +} +.slideshow-buttons label { + display: inline-block; + padding: 7px; + cursor: pointer; +} +.slideshow-buttons input { + position: absolute; + left: -10000px; +} +.slideshow-buttons label i { + display: inline-block; + background: #fff; + box-shadow: 0 0 3px rgba(0, 0, 0, .4); + border-radius: 3.5px; + width: 7px; + height: 7px; + opacity: .6; + transition: opacity .3s; +} +.slideshow-buttons input:checked ~ i { + opacity: 1; +} + +figure.collage { + margin: -2px 16px; + text-align: left; +} +figure.collage > figure { + display: inline-block; + vertical-align: top; + width: calc(25% - 4px); + margin: 2px; + box-sizing: border-box; +} +figure.collage > figure > i { + background: no-repeat center; + background-size: cover; + display: inline-block; + vertical-align: top; + width: 100%; + padding-top: 100%; +} + +figure.table-wrap { + overflow: auto; + -webkit-overflow-scrolling: touch; +} +figure.table { + display: table-cell; + padding: 0 18px; +} +article ol figure.table-wrap, +article ul figure.table-wrap { + margin-top: 7px; +} +article ol figure.table, +article ul figure.table { + padding: 0; +} + +figure blockquote.embed-post { + text-align: left; + margin-bottom: 0; +} +article.rtl figure blockquote.embed-post { + text-align: right; +} +blockquote.embed-post address { + margin: 0; + padding: 5px 0 9px; + overflow: hidden; +} +blockquote.embed-post address figure { + width: 50px; + height: 50px; + float: left; + margin: 0 12px 0 0; + background: no-repeat center; + background-size: cover; + border-radius: 50%; +} +article.rtl blockquote.embed-post address figure { + float: right; + margin-left: 12px; + margin-right: 0; +} +blockquote.embed-post address a { + display: inline-block; + padding-top: 2px; + font-size: 17px; + font-weight: 600; + color: #000; +} +blockquote.embed-post address time { + display: block; + line-height: 19px; +} +blockquote.embed-post p, +blockquote.embed-post blockquote { + margin: 0 0 7px; + clear: left; +} +blockquote.embed-post figcaption { + padding-left: 0; + padding-right: 0; +} +blockquote.embed-post figure.collage { + margin-left: -2px; + margin-right: -2px; +} +blockquote.embed-post footer { + margin: 12px 0 0; + font-style: normal; +} +blockquote.embed-post footer hr { + display: none; +} + +section.embed-post { + display: block; + width: auto; + height: auto; + background: #f7f7f7; + margin: 0 18px 12px; + padding: 24px 18px; + text-align: center; +} +section.embed-post strong { + font-size: 21px; + font-weight: normal; + display: block; + color: #777; +} +section.embed-post small { + display: block; + color: #777; +} + +section.related { + margin: 7px 0 12px; +} +section.related h4 { + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 26px; + font-weight: 500; + display: block; + padding: 7px 18px; + background: #f7f7f7; + margin: 0; + color: #000; +} +section.related a.related-link { + display: block; + padding: 15px 18px 16px; + background: #fff; + position: relative; + overflow: hidden; +} +section.related a.related-link:after { + content: ''; + display: block; + border-bottom: 1px solid #c8c7cb; + position: absolute; + left: 18px; + right: 0; + bottom: 0; +} +section.related .related-link-url { + display: block; + font-size: 15px; + line-height: 18px; + padding: 7px 0; + color: #999; + word-break: break-word; +} +section.related .related-link-thumb { + display: inline-block; + float: right; + width: 87px; + height: 87px; + border-radius: 4px; + background: no-repeat center; + background-size: cover; + margin-left: 15px; +} +section.related .related-link-content { + display: block; + margin: -3px 0; +} +section.related .related-link-title { + font-size: 15px; + font-weight: 500; + line-height: 18px; + display: block; + display: -webkit-box; + margin-bottom: 4px; + max-height: 36px; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + white-space: pre-wrap; + color: #000; +} +section.related .related-link-desc { + font-size: 14px; + line-height: 17px; + display: block; + display: -webkit-box; + max-height: 51px; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + white-space: pre-wrap; + color: #000; +} +section.related .related-link-source { + font-size: 13px; + line-height: 17px; + display: block; + overflow: hidden; + margin-top: 4px; + text-overflow: ellipsis; + white-space: nowrap; + color: #818181; +} + +section.message { + position: absolute; + display: table; + width: 100%; + height: 100%; +} +section.message.static { + position: static; + min-height: 200px; + height: 100vh; +} +section.message > aside { + display: table-cell; + vertical-align: middle; + text-align: center; + color: #999; + font-size: 24px; + pointer-events: none; +} +section.message > aside > cite { + display: block; + font-size: 14px; + padding: 10px 0 0; + font-style: normal; + color: #ccc; +} + +section.channel { + margin-top: -16px; + margin-bottom: -9px; +} +section.channel:first-child { + margin-top: 0; +} +section.channel > a { + display: block; + padding: 7px 18px; + background: #f7f7f7; +} +section.channel > a:before { + content: 'Join'; + color: #3196e8; + font-weight: 500; + margin-left: 7px; + float: right; +} +section.channel > a > h4 { + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 26px; + font-weight: 500; + margin: 0; + color: #000; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.iv-pullquote { + text-align: center; + max-width: 420px; + font-size: 19px; + display: block; + margin: 0 auto; +} +.iv-photo-wrap { + width: 100%; + background-size: 100%; + margin: 0 auto; +} +.iv-photo { + background-size: 100%; +} diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js new file mode 100644 index 000000000..d821a1e43 --- /dev/null +++ b/Telegram/Resources/iv_html/page.js @@ -0,0 +1,86 @@ +var IV = { + sendPostMessage: function(data) { + try { + window.parent.postMessage(JSON.stringify(data), window.parentOrigin); + } catch(e) {} + }, + frameClickHandler: function(e) { + var target = e.target, href; + do { + if (target.tagName == 'SUMMARY') return; + if (target.tagName == 'DETAILS') return; + if (target.tagName == 'LABEL') return; + if (target.tagName == 'AUDIO') return; + if (target.tagName == 'A') break; + } while (target = target.parentNode); + if (target && target.hasAttribute('href')) { + var base_loc = document.createElement('A'); + base_loc.href = window.currentUrl; + if (base_loc.origin != target.origin || + base_loc.pathname != target.pathname || + base_loc.search != target.search) { + IV.sendPostMessage({event: 'link_click', url: target.href}); + } + } + e.preventDefault(); + }, + postMessageHandler: function(event) { + if (event.source !== window.parent || + event.origin != window.parentOrigin) { + return; + } + try { + var data = JSON.parse(event.data); + } catch(e) { + var data = {}; + } + }, + slideshowSlide: function(el, next) { + var dir = window.getComputedStyle(el, null).direction || 'ltr'; + var marginProp = dir == 'rtl' ? 'marginRight' : 'marginLeft'; + if (next) { + var s = el.previousSibling.s; + s.value = (+s.value + 1 == s.length) ? 0 : +s.value + 1; + s.forEach(function(el){ el.checked && el.parentNode.scrollIntoView && el.parentNode.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'center'}); }); + el.firstChild.style[marginProp] = (-100 * s.value) + '%'; + } else { + el.form.nextSibling.firstChild.style[marginProp] = (-100 * el.value) + '%'; + } + return false; + }, + initPreBlocks: function() { + if (!hljs) return; + var pres = document.getElementsByTagName('pre'); + for (var i = 0; i < pres.length; i++) { + if (pres[i].hasAttribute('data-language')) { + hljs.highlightBlock(pres[i]); + } + } + }, + initEmbedBlocks: function() { + var iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; i++) { + (function(iframe) { + window.addEventListener('message', function(event) { + if (event.source !== iframe.contentWindow || + event.origin != window.origin) { + return; + } + try { + var data = JSON.parse(event.data); + } catch(e) { + var data = {}; + } + if (data.eventType == 'resize_frame') { + if (data.eventData.height) { + iframe.style.height = data.eventData.height + 'px'; + } + } + }, false); + })(iframes[i]); + } + } +}; + +document.onclick = IV.frameClickHandler; +window.onmessage = IV.postMessageHandler; diff --git a/Telegram/Resources/qrc/telegram/iv.qrc b/Telegram/Resources/qrc/telegram/iv.qrc new file mode 100644 index 000000000..4d67c89c7 --- /dev/null +++ b/Telegram/Resources/qrc/telegram/iv.qrc @@ -0,0 +1,8 @@ + + + ../../iv_html/page.css + ../../iv_html/page.js + ../../iv_html/highlight.9.12.0.css + ../../iv_html/highlight.9.12.0.js + + diff --git a/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp index 2e24d2804..a65864063 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_peer_color_box.cpp @@ -33,6 +33,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "info/boosts/info_boosts_widget.h" #include "info/profile/info_profile_emoji_status_panel.h" #include "info/info_memento.h" +#include "iv/iv_data.h" #include "lang/lang_keys.h" #include "lottie/lottie_icon.h" #include "lottie/lottie_single_player.h" @@ -310,6 +311,7 @@ PreviewWrap::PreviewWrap( nullptr, // photo nullptr, // document WebPageCollage(), + nullptr, // iv 0, // duration QString(), // author false, // hasLargeMedia diff --git a/Telegram/SourceFiles/core/application.cpp b/Telegram/SourceFiles/core/application.cpp index 7e7dadbd4..8fe1e75c7 100644 --- a/Telegram/SourceFiles/core/application.cpp +++ b/Telegram/SourceFiles/core/application.cpp @@ -44,6 +44,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "api/api_updates.h" #include "calls/calls_instance.h" #include "countries/countries_manager.h" +#include "iv/iv_instance.h" #include "lang/lang_file_parser.h" #include "lang/lang_translator.h" #include "lang/lang_cloud_manager.h" @@ -162,6 +163,7 @@ Application::Application() , _domain(std::make_unique(cDataFile())) , _exportManager(std::make_unique()) , _calls(std::make_unique()) +, _iv(std::make_unique()) , _langpack(std::make_unique()) , _langCloudManager(std::make_unique(langpack())) , _emojiKeywords(std::make_unique()) @@ -218,6 +220,7 @@ Application::~Application() { // Domain::finish() and there is a violation on Ensures(started()). Payments::CheckoutProcess::ClearAll(); InlineBots::AttachWebView::ClearAll(); + _iv->closeAll(); _domain->finish(); @@ -1272,6 +1275,8 @@ bool Application::hasActiveWindow(not_null session) const { return false; } else if (_calls->hasActivePanel(session)) { return true; + } else if (_iv->hasActiveWindow(session)) { + return true; } else if (const auto window = _lastActiveWindow) { return (window->account().maybeSession() == session) && window->widget()->isActive(); diff --git a/Telegram/SourceFiles/core/application.h b/Telegram/SourceFiles/core/application.h index b06e02074..123d1010a 100644 --- a/Telegram/SourceFiles/core/application.h +++ b/Telegram/SourceFiles/core/application.h @@ -45,6 +45,10 @@ class Account; class Session; } // namespace Main +namespace Iv { +class Instance; +} // namespace Iv + namespace Ui { namespace Animations { class Manager; @@ -280,6 +284,11 @@ public: return *_calls; } + // Iv. + Iv::Instance &iv() const { + return *_iv; + } + void logout(Main::Account *account = nullptr); void logoutWithChecks(Main::Account *account); void forceLogOut( @@ -409,6 +418,7 @@ private: const std::unique_ptr _domain; const std::unique_ptr _exportManager; const std::unique_ptr _calls; + const std::unique_ptr _iv; base::flat_map< Main::Account*, std::unique_ptr> _primaryWindows; diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index 24ea2cd46..36f35642d 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -36,6 +36,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "media/audio/media_audio.h" #include "boxes/abstract_box.h" #include "passport/passport_form_controller.h" +#include "iv/iv_data.h" #include "lang/lang_keys.h" // tr::lng_deleted(tr::now) in user name #include "data/business/data_business_chatbots.h" #include "data/business/data_business_info.h" @@ -3365,6 +3366,7 @@ not_null Session::processWebpage( nullptr, nullptr, WebPageCollage(), + nullptr, 0, QString(), false, @@ -3389,6 +3391,7 @@ not_null Session::webpage( nullptr, nullptr, WebPageCollage(), + nullptr, 0, QString(), false, @@ -3406,6 +3409,7 @@ not_null Session::webpage( PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, @@ -3423,6 +3427,7 @@ not_null Session::webpage( photo, document, std::move(collage), + std::move(iv), duration, author, hasLargeMedia, @@ -3503,6 +3508,14 @@ void Session::webpageApplyFields( }, [](const auto &) {}); } } + if (const auto page = data.vcached_page()) { + for (const auto photo : page->data().vphotos().v) { + processPhoto(photo); + } + for (const auto document : page->data().vdocuments().v) { + processDocument(document); + } + } webpageApplyFields( page, (story ? WebPageType::Story : ParseWebPageType(data)), @@ -3523,6 +3536,9 @@ void Session::webpageApplyFields( ? processDocument(*document).get() : lookupThemeDocument()), WebPageCollage(this, data), + (data.vcached_page() + ? std::make_unique(data, *data.vcached_page()) + : nullptr), data.vduration().value_or_empty(), qs(data.vauthor().value_or_empty()), data.is_has_large_media(), @@ -3541,6 +3557,7 @@ void Session::webpageApplyFields( PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, @@ -3557,6 +3574,7 @@ void Session::webpageApplyFields( photo, document, std::move(collage), + std::move(iv), duration, author, hasLargeMedia, diff --git a/Telegram/SourceFiles/data/data_session.h b/Telegram/SourceFiles/data/data_session.h index 74204af26..b233aead1 100644 --- a/Telegram/SourceFiles/data/data_session.h +++ b/Telegram/SourceFiles/data/data_session.h @@ -38,6 +38,10 @@ namespace Passport { struct SavedCredentials; } // namespace Passport +namespace Iv { +class Data; +} // namespace Iv + namespace Data { class Folder; @@ -581,6 +585,7 @@ public: PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, @@ -858,6 +863,7 @@ private: PhotoData *photo, DocumentData *document, WebPageCollage &&collage, + std::unique_ptr iv, int duration, const QString &author, bool hasLargeMedia, diff --git a/Telegram/SourceFiles/data/data_web_page.cpp b/Telegram/SourceFiles/data/data_web_page.cpp index 6174c138b..9b3f7fd66 100644 --- a/Telegram/SourceFiles/data/data_web_page.cpp +++ b/Telegram/SourceFiles/data/data_web_page.cpp @@ -15,6 +15,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "data/data_document.h" #include "lang/lang_keys.h" +#include "iv/iv_data.h" #include "ui/image/image.h" #include "ui/text/text_entity.h" @@ -206,6 +207,8 @@ WebPageData::WebPageData(not_null owner, const WebPageId &id) , _owner(owner) { } +WebPageData::~WebPageData() = default; + Data::Session &WebPageData::owner() const { return *_owner; } @@ -225,6 +228,7 @@ bool WebPageData::applyChanges( PhotoData *newPhoto, DocumentData *newDocument, WebPageCollage &&newCollage, + std::unique_ptr newIv, int newDuration, const QString &newAuthor, bool newHasLargeMedia, @@ -276,6 +280,7 @@ bool WebPageData::applyChanges( && photo == newPhoto && document == newDocument && collage.items == newCollage.items + && (!iv == !newIv) && duration == newDuration && author == resultAuthor && hasLargeMedia == (newHasLargeMedia ? 1 : 0) @@ -296,6 +301,7 @@ bool WebPageData::applyChanges( photo = newPhoto; document = newDocument; collage = std::move(newCollage); + iv = std::move(newIv); duration = newDuration; author = resultAuthor; pendingTill = newPendingTill; diff --git a/Telegram/SourceFiles/data/data_web_page.h b/Telegram/SourceFiles/data/data_web_page.h index 629ba2bc9..7b4f7db70 100644 --- a/Telegram/SourceFiles/data/data_web_page.h +++ b/Telegram/SourceFiles/data/data_web_page.h @@ -17,6 +17,10 @@ namespace Data { class Session; } // namespace Data +namespace Iv { +class Data; +} // namespace Iv + enum class WebPageType : uint8 { None, @@ -64,6 +68,7 @@ struct WebPageCollage { struct WebPageData { WebPageData(not_null owner, const WebPageId &id); + ~WebPageData(); [[nodiscard]] Data::Session &owner() const; [[nodiscard]] Main::Session &session() const; @@ -79,6 +84,7 @@ struct WebPageData { PhotoData *newPhoto, DocumentData *newDocument, WebPageCollage &&newCollage, + std::unique_ptr newIv, int newDuration, const QString &newAuthor, bool newHasLargeMedia, @@ -105,6 +111,7 @@ struct WebPageData { PhotoData *photo = nullptr; DocumentData *document = nullptr; WebPageCollage collage; + std::unique_ptr iv; int duration = 0; TimeId pendingTill = 0; uint32 version : 30 = 0; diff --git a/Telegram/SourceFiles/history/view/history_view_view_button.cpp b/Telegram/SourceFiles/history/view/history_view_view_button.cpp index 52e9847ae..aa12fe1c2 100644 --- a/Telegram/SourceFiles/history/view/history_view_view_button.cpp +++ b/Telegram/SourceFiles/history/view/history_view_view_button.cpp @@ -11,6 +11,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history.h" #include "history/history_item_components.h" #include "history/view/history_view_cursor_state.h" +#include "iv/iv_data.h" +#include "iv/iv_controller.h" #include "lang/lang_keys.h" #include "ui/effects/ripple_animation.h" #include "ui/painter.h" @@ -18,6 +20,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/window_session_controller.h" #include "styles/style_chat.h" +#include "core/application.h" +#include "iv/iv_instance.h" + namespace HistoryView { namespace { diff --git a/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp b/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp index 43b3d8370..5b46381fb 100644 --- a/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp +++ b/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp @@ -7,6 +7,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "history/view/media/history_view_web_page.h" +#include "core/application.h" +#include "base/qt/qt_key_modifiers.h" +#include "window/window_session_controller.h" +#include "iv/iv_instance.h" #include "core/click_handler_types.h" #include "core/ui_integration.h" #include "data/data_file_click_handler.h" @@ -82,7 +86,29 @@ constexpr auto kMaxOriginalEntryLines = 8192; return result; } +[[nodiscard]] ClickHandlerPtr IvClickHandler(not_null webpage) { + return std::make_shared([=](ClickContext context) { + const auto my = context.other.value(); + if (const auto controller = my.sessionWindow.get()) { + if (const auto iv = webpage->iv.get()) { +#ifdef _DEBUG + const auto local = base::IsCtrlPressed(); +#else // _DEBUG + const auto local = false; +#endif // _DEBUG + Core::App().iv().show(controller->uiShow(), iv, local); + return; + } else { + HiddenUrlClickHandler::Open(webpage->url, context.other); + } + } + }); +} + [[nodiscard]] QString PageToPhrase(not_null webpage) { + if (webpage->iv) { + return u"Instant View"_q; + } const auto type = webpage->type; return Ui::Text::Upper((type == WebPageType::Theme) ? tr::lng_view_button_theme(tr::now) @@ -118,7 +144,8 @@ constexpr auto kMaxOriginalEntryLines = 8192; [[nodiscard]] bool HasButton(not_null webpage) { const auto type = webpage->type; - return (type == WebPageType::Message) + return webpage->iv + || (type == WebPageType::Message) || (type == WebPageType::Group) || (type == WebPageType::Channel) || (type == WebPageType::ChannelBoost) @@ -245,7 +272,7 @@ QSize WebPage::countOptimalSize() { } return true; }(); - _openl = (previewOfHiddenUrl + _openl = _data->iv ? IvClickHandler(_data) : (previewOfHiddenUrl || UrlClickHandler::IsSuspicious(_data->url)) ? std::make_shared(_data->url) : std::make_shared(_data->url, true); diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp new file mode 100644 index 000000000..bac53f983 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -0,0 +1,115 @@ +/* +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 "iv/iv_controller.h" + +#include "iv/iv_data.h" +#include "ui/widgets/rp_window.h" +#include "webview/webview_data_stream_memory.h" +#include "webview/webview_embed.h" +#include "webview/webview_interface.h" + +#include +#include + +namespace Iv { + +Controller::Controller() = default; + +Controller::~Controller() { + _webview = nullptr; + _window = nullptr; +} + +void Controller::show(const QString &dataPath, Prepared page) { + _window = std::make_unique(); + const auto window = _window.get(); + + window->setGeometry({ 200, 200, 800, 600 }); + + const auto container = Ui::CreateChild( + window->body().get()); + window->sizeValue() | rpl::start_with_next([=](QSize size) { + container->setGeometry(QRect(QPoint(), size)); + }, container->lifetime()); + container->show(); + + _webview = std::make_unique( + container, + Webview::WindowConfig{ .userDataPath = dataPath }); + const auto raw = _webview.get(); + + window->lifetime().add([=] { + _webview = nullptr; + }); + if (!raw->widget()) { + _webview = nullptr; + _window = nullptr; + return; + } + raw->widget()->show(); + + container->geometryValue( + ) | rpl::start_with_next([=](QRect geometry) { + raw->widget()->setGeometry(geometry); + }, _lifetime); + + raw->setNavigationStartHandler([=](const QString &uri, bool newWindow) { + return true; + }); + raw->setNavigationDoneHandler([=](bool success) { + }); + raw->setDataRequestHandler([=](Webview::DataRequest request) { + if (!request.id.starts_with("iv/")) { + _dataRequests.fire(std::move(request)); + return Webview::DataResult::Pending; + } + const auto finishWith = [&](QByteArray data, std::string mime) { + request.done({ + .stream = std::make_unique( + std::move(data), + std::move(mime)), + }); + return Webview::DataResult::Done; + }; + const auto id = std::string_view(request.id).substr(3); + if (id == "page.html") { + return finishWith(page.html, "text/html"); + } + const auto css = id.ends_with(".css"); + const auto js = !css && id.ends_with(".js"); + if (!css && !js) { + return Webview::DataResult::Failed; + } + const auto qstring = QString::fromUtf8(id.data(), id.size()); + const auto pattern = u"^[a-zA-Z\\.\\-_0-9]+$"_q; + if (QRegularExpression(pattern).match(qstring).hasMatch()) { + auto file = QFile(u":/iv/"_q + qstring); + if (file.open(QIODevice::ReadOnly)) { + const auto mime = css ? "text/css" : "text/javascript"; + return finishWith(file.readAll(), mime); + } + } + return Webview::DataResult::Failed; + }); + + raw->init(R"( +)"); + raw->navigateToData("iv/page.html"); + + window->show(); +} + +rpl::producer Controller::dataRequests() const { + return _dataRequests.events(); +} + +rpl::lifetime &Controller::lifetime() { + return _lifetime; +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h new file mode 100644 index 000000000..b35dfc00a --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -0,0 +1,42 @@ +/* +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 +*/ +#pragma once + +namespace Webview { +struct DataRequest; +class Window; +} // namespace Webview + +namespace Ui { +class RpWindow; +} // namespace Ui + +namespace Iv { + +struct Prepared; + +class Controller final { +public: + Controller(); + ~Controller(); + + void show(const QString &dataPath, Prepared page); + + [[nodiscard]] rpl::producer dataRequests() const; + + [[nodiscard]] rpl::lifetime &lifetime(); + +private: + std::unique_ptr _window; + std::unique_ptr _webview; + rpl::event_stream _dataRequests; + rpl::lifetime _lifetime; + +}; + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_data.cpp b/Telegram/SourceFiles/iv/iv_data.cpp new file mode 100644 index 000000000..c34424e27 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_data.cpp @@ -0,0 +1,63 @@ +/* +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 "iv/iv_data.h" + +#include "iv/iv_prepare.h" + +namespace Iv { + +QByteArray GeoPointId(Geo point) { + const auto lat = int(point.lat * 1000000); + const auto lon = int(point.lon * 1000000); + const auto combined = (std::uint64_t(std::uint32_t(lat)) << 32) + | std::uint64_t(std::uint32_t(lon)); + return QByteArray::number(combined) + + ',' + + QByteArray::number(point.access); +} + +Geo GeoPointFromId(QByteArray data) { + const auto parts = data.split(','); + if (parts.size() != 2) { + return {}; + } + const auto combined = parts[0].toULongLong(); + const auto lat = int(std::uint32_t(combined >> 32)); + const auto lon = int(std::uint32_t(combined & 0xFFFFFFFFULL)); + return { + .lat = lat / 1000000., + .lon = lon / 1000000., + .access = parts[1].toULongLong(), + }; +} + +Data::Data(const MTPDwebPage &webpage, const MTPPage &page) +: _source(std::make_unique(Source{ + .page = page, + .webpagePhoto = (webpage.vphoto() + ? *webpage.vphoto() + : std::optional()), + .webpageDocument = (webpage.vdocument() + ? *webpage.vdocument() + : std::optional()), +})) { +} + +QString Data::id() const { + return qs(_source->page.data().vurl()); +} + +Data::~Data() = default; + +void Data::prepare(const Options &options, Fn done) const { + crl::async([source = *_source, options, done = std::move(done)] { + done(Prepare(source, options)); + }); +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_data.h b/Telegram/SourceFiles/iv/iv_data.h new file mode 100644 index 000000000..1eec747ef --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_data.h @@ -0,0 +1,47 @@ +/* +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 +*/ +#pragma once + +namespace Iv { + +struct Source; + +struct Options { + QString saveToFolder; +}; + +struct Prepared { + QByteArray html; + std::vector resources; + base::flat_map embeds; +}; + +struct Geo { + float64 lat = 0.; + float64 lon = 0.; + uint64 access = 0; +}; + +[[nodiscard]] QByteArray GeoPointId(Geo point); +[[nodiscard]] Geo GeoPointFromId(QByteArray data); + +class Data final { +public: + Data(const MTPDwebPage &webpage, const MTPPage &page); + ~Data(); + + [[nodiscard]] QString id() const; + + void prepare(const Options &options, Fn done) const; + +private: + const std::unique_ptr _source; + +}; + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_instance.cpp b/Telegram/SourceFiles/iv/iv_instance.cpp new file mode 100644 index 000000000..27f3dcfb2 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_instance.cpp @@ -0,0 +1,663 @@ +/* +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 "iv/iv_instance.h" + +#include "core/file_utilities.h" +#include "data/data_cloud_file.h" +#include "data/data_document.h" +#include "data/data_file_origin.h" +#include "data/data_photo_media.h" +#include "data/data_session.h" +#include "iv/iv_controller.h" +#include "iv/iv_data.h" +#include "main/main_account.h" +#include "main/main_domain.h" +#include "main/main_session.h" +#include "main/session/session_show.h" +#include "media/streaming/media_streaming_loader.h" +#include "storage/file_download.h" +#include "storage/storage_domain.h" +#include "ui/boxes/confirm_box.h" +#include "webview/webview_data_stream_memory.h" +#include "webview/webview_interface.h" + +namespace Iv { +namespace { + +constexpr auto kGeoPointScale = 1; +constexpr auto kGeoPointZoomMin = 13; +constexpr auto kMaxLoadParts = 3; +constexpr auto kKeepLoadingParts = 8; + +[[nodiscard]] QString LookupLocalPath( + const std::shared_ptr show) { + const auto &domain = show->session().account().domain(); + const auto &base = domain.local().webviewDataPath(); + static auto counter = 0; + return base + u"/iv/"_q + QString::number(++counter); +} + +[[nodiscard]] Storage::Cache::Key IvBaseCacheKey( + not_null document) { + auto big = document->bigFileBaseCacheKey(); + big.low += 0x7FF; + return big; +} + +} // namespace + +class Shown final : public base::has_weak_ptr { +public: + Shown( + std::shared_ptr show, + not_null data, + bool local); + + [[nodiscard]] bool showing( + not_null session, + not_null data) const; + [[nodiscard]] bool showingFrom(not_null session) const; + [[nodiscard]] bool activeFor(not_null session) const; + +private: + struct MapPreview { + std::unique_ptr<::Data::CloudFile> file; + QByteArray bytes; + }; + struct PartRequest { + Webview::DataRequest request; + QByteArray data; + std::vector loaded; + int64 offset = 0; + }; + struct FileLoad { + not_null document; + std::unique_ptr loader; + std::vector requests; + std::string mime; + rpl::lifetime lifetime; + }; + + void showLocal(Prepared result); + void showWindowed(Prepared result); + + // Local. + void showProgress(int index); + void loadResource(int index); + void finishLocal(const QString &path); + [[nodiscard]] QString localRoot() const; + void writeLocal(const QString &relative, const QByteArray &data); + void loadPhoto(QString id, PhotoId photoId); + void loadDocument(QString id, DocumentId documentId); + void loadPage(QString id, QString tag); + void loadMap(QString id, QString params); + void writeEmbed(QString id, QString hash); + + // Windowed. + void streamPhoto(PhotoId photoId, Webview::DataRequest request); + void streamFile(DocumentId documentId, Webview::DataRequest request); + void streamFile(FileLoad &file, Webview::DataRequest request); + void processPartInFile( + FileLoad &file, + Media::Streaming::LoadedPart &&part); + bool finishRequestWithPart( + PartRequest &request, + const Media::Streaming::LoadedPart &part); + void streamMap(QString params, Webview::DataRequest request); + void sendEmbed(QByteArray hash, Webview::DataRequest request); + + void requestDone( + Webview::DataRequest request, + QByteArray bytes, + std::string mime, + int64 offset = 0, + int64 total = 0); + void requestFail(Webview::DataRequest request); + + const not_null _session; + std::shared_ptr _show; + QString _id; + std::unique_ptr _controller; + base::flat_map _files; + + QString _localBase; + base::flat_map _embeds; + base::flat_map _maps; + std::vector _resources; + int _resource = -1; + + rpl::lifetime _lifetime; + +}; + +Shown::Shown( + std::shared_ptr show, + not_null data, + bool local) +: _session(&show->session()) +, _show(show) +, _id(data->id()) { + const auto weak = base::make_weak(this); + + const auto base = local ? LookupLocalPath(show) : QString(); + data->prepare({ .saveToFolder = base }, [=](Prepared result) { + crl::on_main(weak, [=, result = std::move(result)]() mutable { + _embeds = std::move(result.embeds); + if (!base.isEmpty()) { + _localBase = base; + showLocal(std::move(result)); + } else { + showWindowed(std::move(result)); + } + }); + }); +} + +void Shown::showLocal(Prepared result) { + showProgress(0); + + QDir(_localBase).removeRecursively(); + QDir().mkpath(_localBase); + + _resources = std::move(result.resources); + writeLocal(localRoot(), result.html); +} + +void Shown::showProgress(int index) { + const auto count = int(_resources.size() + 1); + _show->showToast(u"Saving %1 / %2..."_q.arg(index + 1).arg(count)); +} + +void Shown::finishLocal(const QString &path) { + if (path.isEmpty()) { + _show->showToast(u"Failed!"_q); + } else { + _show->showToast(u"Done!"_q); + File::Launch(path); + } + _id = QString(); +} + +QString Shown::localRoot() const { + return u"page.html"_q; +} + +void Shown::writeLocal(const QString &relative, const QByteArray &data) { + const auto path = _localBase + '/' + relative; + QFileInfo(path).absoluteDir().mkpath("."); + + auto f = QFile(path); + if (!f.open(QIODevice::WriteOnly) || f.write(data) != data.size()) { + finishLocal({}); + } else { + crl::on_main(this, [=] { + loadResource(_resource + 1); + }); + } +} + +void Shown::loadResource(int index) { + _resource = index; + if (_resource == _resources.size()) { + finishLocal(_localBase + '/' + localRoot()); + return; + } + showProgress(_resource + 1); + const auto id = QString::fromUtf8(_resources[_resource]); + if (id.startsWith(u"photo/"_q)) { + loadPhoto(id, id.mid(6).toULongLong()); + } else if (id.startsWith(u"document/"_q)) { + loadDocument(id, id.mid(9).toULongLong()); + } else if (id.startsWith(u"iv/"_q)) { + loadPage(id, id.mid(3)); + } else if (id.startsWith(u"map/"_q)) { + loadMap(id, id.mid(4)); + } else if (id.startsWith(u"html/"_q)) { + writeEmbed(id, id.mid(5)); + } else { + _show->show( + Ui::MakeInformBox(u"Skipping resource %1..."_q.arg(id))); + crl::on_main(this, [=] { + loadResource(index + 1); + }); + } +} + +void Shown::loadPhoto(QString id, PhotoId photoId) { + const auto photo = _session->data().photo(photoId); + const auto media = photo->createMediaView(); + media->wanted(::Data::PhotoSize::Large, ::Data::FileOrigin()); + const auto finish = [=](QByteArray bytes) { + writeLocal(id, bytes); + }; + if (media->loaded()) { + finish(media->imageBytes(::Data::PhotoSize::Large)); + } else { + photo->session().downloaderTaskFinished( + ) | rpl::filter([=] { + return media->loaded(); + }) | rpl::take(1) | rpl::start_with_next([=] { + finish(media->imageBytes(::Data::PhotoSize::Large)); + }, _lifetime); + } +} + +void Shown::loadDocument(QString id, DocumentId documentId) { + const auto path = _localBase + '/' + id; + QFileInfo(path).absoluteDir().mkpath("."); + + const auto document = _session->data().document(documentId); + document->save(::Data::FileOrigin(), path); + if (!document->loading()) { + crl::on_main(this, [=] { + loadResource(_resource + 1); + }); + } + document->session().downloaderTaskFinished( + ) | rpl::filter([=] { + return !document->loading(); + }) | rpl::take(1) | rpl::start_with_next([=] { + crl::on_main(this, [=] { + loadResource(_resource + 1); + }); + }, _lifetime); +} + +void Shown::loadPage(QString id, QString tag) { + if (!id.endsWith(u".css"_q) && !id.endsWith(u".js"_q)) { + finishLocal({}); + return; + } + const auto pattern = u"^[a-zA-Z\\.\\-_0-9]+$"_q; + if (QRegularExpression(pattern).match(tag).hasMatch()) { + auto file = QFile(u":/iv/"_q + tag); + if (file.open(QIODevice::ReadOnly)) { + writeLocal(id, file.readAll()); + return; + } + } + finishLocal({}); +} + +void Shown::loadMap(QString id, QString params) { + using namespace ::Data; + const auto i = _maps.find(params); + if (i != end(_maps)) { + writeLocal(id, i->second.bytes); + return; + } + const auto parts = params.split(u'&'); + if (parts.size() != 3) { + finishLocal({}); + return; + } + const auto point = GeoPointFromId(parts[0].toUtf8()); + const auto size = parts[1].split(','); + const auto zoom = parts[2].toInt(); + if (size.size() != 2) { + finishLocal({}); + return; + } + const auto location = GeoPointLocation{ + .lat = point.lat, + .lon = point.lon, + .access = point.access, + .width = size[0].toInt(), + .height = size[1].toInt(), + .zoom = std::max(zoom, kGeoPointZoomMin), + .scale = kGeoPointScale, + }; + const auto prepared = ImageWithLocation{ + .location = ImageLocation( + { location }, + location.width, + location.height) + }; + auto &preview = _maps.emplace(params, MapPreview()).first->second; + preview.file = std::make_unique(); + + UpdateCloudFile( + *preview.file, + prepared, + _session->data().cache(), + kImageCacheTag, + [=](FileOrigin origin) { /* restartLoader not used here */ }); + const auto autoLoading = false; + const auto finalCheck = [=] { return true; }; + const auto done = [=](QByteArray bytes) { + const auto i = _maps.find(params); + Assert(i != end(_maps)); + i->second.bytes = std::move(bytes); + writeLocal(id, i->second.bytes); + }; + LoadCloudFile( + _session, + *preview.file, + FileOrigin(), + LoadFromCloudOrLocal, + autoLoading, + kImageCacheTag, + finalCheck, + done, + [=](bool) { done("failed..."); }); +} + +void Shown::writeEmbed(QString id, QString hash) { + const auto i = _embeds.find(hash.toUtf8()); + if (i != end(_embeds)) { + writeLocal(id, i->second); + } else { + finishLocal({}); + } +} + +void Shown::showWindowed(Prepared result) { + _controller = std::make_unique(); + _controller->dataRequests( + ) | rpl::start_with_next([=](Webview::DataRequest request) { + const auto requested = QString::fromStdString(request.id); + const auto id = QStringView(requested); + if (id.startsWith(u"photo/")) { + streamPhoto(id.mid(6).toULongLong(), std::move(request)); + } else if (id.startsWith(u"document/"_q)) { + streamFile(id.mid(9).toULongLong(), std::move(request)); + } else if (id.startsWith(u"map/"_q)) { + streamMap(id.mid(4).toUtf8(), std::move(request)); + } else if (id.startsWith(u"html/"_q)) { + sendEmbed(id.mid(5).toUtf8(), std::move(request)); + } + }, _controller->lifetime()); + const auto domain = &_session->domain(); + _controller->show(domain->local().webviewDataPath(), std::move(result)); +} + +void Shown::streamPhoto(PhotoId photoId, Webview::DataRequest request) { + using namespace Data; + + const auto photo = _session->data().photo(photoId); + if (photo->isNull()) { + requestFail(std::move(request)); + return; + } + const auto media = photo->createMediaView(); + media->wanted(PhotoSize::Large, FileOrigin()); + const auto check = [=] { + if (!media->loaded() && !media->owner()->failed(PhotoSize::Large)) { + return false; + } + requestDone( + request, + media->imageBytes(PhotoSize::Large), + "image/jpeg"); + return true; + }; + if (!check()) { + photo->session().downloaderTaskFinished( + ) | rpl::filter( + check + ) | rpl::take(1) | rpl::start(_controller->lifetime()); + } +} + +void Shown::streamFile( + DocumentId documentId, + Webview::DataRequest request) { + using namespace Data; + + const auto i = _files.find(documentId); + if (i != end(_files)) { + streamFile(i->second, std::move(request)); + return; + } + const auto document = _session->data().document(documentId); + auto loader = document->createStreamingLoader(FileOrigin(), false); + if (!loader) { + requestFail(std::move(request)); + return; + } + auto &file = _files.emplace( + documentId, + FileLoad{ + .document = document, + .loader = std::move(loader), + .mime = document->mimeString().toStdString(), + }).first->second; + + file.loader->parts( + ) | rpl::start_with_next([=](Media::Streaming::LoadedPart &&part) { + const auto i = _files.find(documentId); + Assert(i != end(_files)); + processPartInFile(i->second, std::move(part)); + }, file.lifetime); + + streamFile(file, std::move(request)); +} + +void Shown::streamFile(FileLoad &file, Webview::DataRequest request) { + constexpr auto kPart = Media::Streaming::Loader::kPartSize; + const auto size = file.document->size; + const auto last = int((size + kPart - 1) / kPart); + const auto from = int(std::min(request.offset, size) / kPart); + const auto till = (request.limit > 0) + ? std::min(request.offset + request.limit, size) + : size; + const auto parts = std::min( + int((till + kPart - 1) / kPart) - from, + kMaxLoadParts); + //auto base = IvBaseCacheKey(document); + + const auto length = std::min((from + parts) * kPart, size) + - from * kPart; + file.requests.push_back(PartRequest{ + .request = std::move(request), + .data = QByteArray(length, 0), + .loaded = std::vector(parts, false), + .offset = from * kPart, + }); + + file.loader->resetPriorities(); + const auto load = std::min(from + kKeepLoadingParts, last) - from; + for (auto i = 0; i != load; ++i) { + file.loader->load((from + i) * kPart); + } +} + +void Shown::processPartInFile( + FileLoad &file, + Media::Streaming::LoadedPart &&part) { + for (auto i = begin(file.requests); i != end(file.requests);) { + if (finishRequestWithPart(*i, part)) { + auto done = base::take(*i); + i = file.requests.erase(i); + requestDone( + std::move(done.request), + done.data, + file.mime, + done.offset, + file.document->size); + } else { + ++i; + } + } +} + +bool Shown::finishRequestWithPart( + PartRequest &request, + const Media::Streaming::LoadedPart &part) { + const auto offset = part.offset; + if (offset == Media::Streaming::LoadedPart::kFailedOffset) { + request.data = QByteArray(); + return true; + } else if (offset < request.offset + || offset >= request.offset + request.data.size()) { + return false; + } + constexpr auto kPart = Media::Streaming::Loader::kPartSize; + const auto copy = std::min( + int(part.bytes.size()), + int(request.data.size() - (offset - request.offset))); + const auto index = (offset - request.offset) / kPart; + Assert(index < request.loaded.size()); + if (request.loaded[index]) { + return false; + } + request.loaded[index] = true; + memcpy( + request.data.data() + index * kPart, + part.bytes.constData(), + copy); + return !ranges::contains(request.loaded, false); +} + +void Shown::streamMap(QString params, Webview::DataRequest request) { + using namespace ::Data; + + const auto parts = params.split(u'&'); + if (parts.size() != 3) { + finishLocal({}); + return; + } + const auto point = GeoPointFromId(parts[0].toUtf8()); + const auto size = parts[1].split(','); + const auto zoom = parts[2].toInt(); + if (size.size() != 2) { + finishLocal({}); + return; + } + const auto location = GeoPointLocation{ + .lat = point.lat, + .lon = point.lon, + .access = point.access, + .width = size[0].toInt(), + .height = size[1].toInt(), + .zoom = std::max(zoom, kGeoPointZoomMin), + .scale = kGeoPointScale, + }; + const auto prepared = ImageWithLocation{ + .location = ImageLocation( + { location }, + location.width, + location.height) + }; + auto &preview = _maps.emplace(params, MapPreview()).first->second; + preview.file = std::make_unique(); + + UpdateCloudFile( + *preview.file, + prepared, + _session->data().cache(), + kImageCacheTag, + [=](FileOrigin origin) { /* restartLoader not used here */ }); + const auto autoLoading = false; + const auto finalCheck = [=] { return true; }; + const auto done = [=](QByteArray bytes) { + const auto i = _maps.find(params); + Assert(i != end(_maps)); + i->second.bytes = std::move(bytes); + requestDone(request, i->second.bytes, "image/png"); + }; + LoadCloudFile( + _session, + *preview.file, + FileOrigin(), + LoadFromCloudOrLocal, + autoLoading, + kImageCacheTag, + finalCheck, + done, + [=](bool) { done("failed..."); }); +} + +void Shown::sendEmbed(QByteArray hash, Webview::DataRequest request) { + const auto i = _embeds.find(hash); + if (i != end(_embeds)) { + requestDone(std::move(request), i->second, "text/html"); + } else { + requestFail(std::move(request)); + } +} + +void Shown::requestDone( + Webview::DataRequest request, + QByteArray bytes, + std::string mime, + int64 offset, + int64 total) { + if (bytes.isEmpty() && mime.empty()) { + requestFail(std::move(request)); + return; + } + crl::on_main([ + done = std::move(request.done), + data = std::move(bytes), + mime = std::move(mime), + offset, + total + ] { + using namespace Webview; + done({ + .stream = std::make_unique(data, mime), + .streamOffset = offset, + .totalSize = total, + }); + }); +} + +void Shown::requestFail(Webview::DataRequest request) { + crl::on_main([done = std::move(request.done)] { + done({}); + }); +} + +bool Shown::showing( + not_null session, + not_null data) const { + return showingFrom(session) && (_id == data->id()); +} + +bool Shown::showingFrom(not_null session) const { + return (_session == session); +} + +bool Shown::activeFor(not_null session) const { + return showingFrom(session) && _controller; +} + +Instance::Instance() = default; + +Instance::~Instance() = default; + +void Instance::show( + std::shared_ptr show, + not_null data, + bool local) { + const auto session = &show->session(); + if (_shown && _shown->showing(session, data)) { + return; + } + _shown = std::make_unique(show, data, local); + if (!_tracking.contains(session)) { + _tracking.emplace(session); + session->lifetime().add([=] { + _tracking.remove(session); + if (_shown && _shown->showingFrom(session)) { + _shown = nullptr; + } + }); + } +} + +bool Instance::hasActiveWindow(not_null session) const { + return _shown && _shown->activeFor(session); +} + +void Instance::closeAll() { + _shown = nullptr; +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_instance.h b/Telegram/SourceFiles/iv/iv_instance.h new file mode 100644 index 000000000..7a1b21f62 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_instance.h @@ -0,0 +1,45 @@ +/* +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 +*/ +#pragma once + +namespace Main { +class Session; +class SessionShow; +} // namespace Main + +namespace Iv { + +class Data; +class Shown; + +class Instance final { +public: + Instance(); + ~Instance(); + + void show( + std::shared_ptr show, + not_null data, + bool local); + + [[nodiscard]] bool hasActiveWindow( + not_null session) const; + + void closeAll(); + + [[nodiscard]] rpl::lifetime &lifetime(); + +private: + std::unique_ptr _shown; + base::flat_set> _tracking; + + rpl::lifetime _lifetime; + +}; + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_pch.h b/Telegram/SourceFiles/iv/iv_pch.h new file mode 100644 index 000000000..839432f44 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_pch.h @@ -0,0 +1,27 @@ +/* +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 +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "base/flat_map.h" +#include "base/flat_set.h" + +#include "scheme.h" +#include "logs.h" diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp new file mode 100644 index 000000000..a4709502d --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -0,0 +1,1038 @@ +/* +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 "iv/iv_prepare.h" + +#include "base/openssl_help.h" +#include "base/unixtime.h" +#include "iv/iv_data.h" +#include "lang/lang_keys.h" +#include "ui/image/image_prepare.h" + +#include + +namespace Iv { +namespace { + +struct Attribute { + QByteArray name; + std::optional value; +}; +using Attributes = std::vector; + +struct Photo { + uint64 id = 0; + int width = 0; + int height = 0; + QByteArray minithumbnail; +}; + +struct Document { + uint64 id = 0; +}; + +class Parser final { +public: + Parser(const Source &source, const Options &options); + + [[nodiscard]] Prepared result(); + +private: + void process(const Source &source); + void process(const MTPPhoto &photo); + void process(const MTPDocument &document); + + [[nodiscard]] QByteArray prepare(QByteArray body); + + [[nodiscard]] QByteArray html( + const QByteArray &head, + const QByteArray &body); + + [[nodiscard]] QByteArray page(const MTPDpage &data); + + template + [[nodiscard]] QByteArray list(const MTPVector &data); + + [[nodiscard]] QByteArray block(const MTPDpageBlockUnsupported &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockTitle &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockSubtitle &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockAuthorDate &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockHeader &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockSubheader &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockParagraph &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockPreformatted &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockFooter &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockDivider &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockAnchor &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockList &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockBlockquote &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockPullquote &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockPhoto &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockVideo &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockCover &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockEmbed &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockEmbedPost &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockCollage &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockSlideshow &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockChannel &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockAudio &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockKicker &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockTable &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockOrderedList &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockDetails &data); + [[nodiscard]] QByteArray block( + const MTPDpageBlockRelatedArticles &data); + [[nodiscard]] QByteArray block(const MTPDpageBlockMap &data); + + [[nodiscard]] QByteArray block(const MTPDpageRelatedArticle &data); + + [[nodiscard]] QByteArray block(const MTPDpageTableRow &data); + [[nodiscard]] QByteArray block(const MTPDpageTableCell &data); + + [[nodiscard]] QByteArray block(const MTPDpageListItemText &data); + [[nodiscard]] QByteArray block(const MTPDpageListItemBlocks &data); + + [[nodiscard]] QByteArray block(const MTPDpageListOrderedItemText &data); + [[nodiscard]] QByteArray block( + const MTPDpageListOrderedItemBlocks &data); + + [[nodiscard]] QByteArray tag( + const QByteArray &name, + const QByteArray &body = {}); + [[nodiscard]] QByteArray tag( + const QByteArray &name, + const Attributes &attributes, + const QByteArray &body = {}); + [[nodiscard]] QByteArray utf(const MTPstring &text); + [[nodiscard]] QByteArray utf(const tl::conditional &text); + [[nodiscard]] QByteArray rich(const MTPRichText &text); + [[nodiscard]] QByteArray plain(const MTPRichText &text); + [[nodiscard]] QByteArray caption(const MTPPageCaption &caption); + + [[nodiscard]] Photo parse(const MTPPhoto &photo); + [[nodiscard]] Document parse(const MTPDocument &document); + [[nodiscard]] Geo parse(const MTPGeoPoint &geo); + + [[nodiscard]] Photo photoById(uint64 id); + [[nodiscard]] Document documentById(uint64 id); + + [[nodiscard]] QByteArray photoFullUrl(const Photo &photo); + [[nodiscard]] QByteArray documentFullUrl(const Document &document); + [[nodiscard]] QByteArray embedUrl(const QByteArray &html); + [[nodiscard]] QByteArray mapUrl( + const Geo &geo, + int width, + int height, + int zoom); + [[nodiscard]] QByteArray resource(QByteArray id); + + const Options _options; + + const QByteArray _resourcePrefix; + base::flat_set _resources; + + Prepared _result; + + bool _rtl = false; + bool _imageAsBackground = false; + bool _captionAsTitle = false; + bool _captionWrapped = false; + base::flat_map _photosById; + base::flat_map _documentsById; + + bool _hasCode = false; + bool _hasEmbeds = false; + +}; + +[[nodiscard]] bool IsVoidElement(const QByteArray &name) { + // Thanks https://developer.mozilla.org/en-US/docs/Glossary/Void_element + static const auto voids = base::flat_set{ + "area"_q, + "base"_q, + "br"_q, + "col"_q, + "embed"_q, + "hr"_q, + "img"_q, + "input"_q, + "link"_q, + "meta"_q, + "source"_q, + "track"_q, + "wbr"_q, + }; + return voids.contains(name); +} + +Parser::Parser(const Source &source, const Options &options) +: _options(options) +, _resourcePrefix(options.saveToFolder.isEmpty() + ? "http://desktop-app-resource/" + : QByteArray()) +, _rtl(source.page.data().is_rtl()) { + process(source); + _result.html = prepare(page(source.page.data())); +} + +Prepared Parser::result() { + return _result; +} + +void Parser::process(const Source &source) { + const auto &data = source.page.data(); + for (const auto &photo : data.vphotos().v) { + process(photo); + } + for (const auto &document : data.vdocuments().v) { + process(document); + } + if (source.webpagePhoto) { + process(*source.webpagePhoto); + } + if (source.webpageDocument) { + process(*source.webpageDocument); + } +} + +void Parser::process(const MTPPhoto &photo) { + _photosById.emplace( + photo.match([](const auto &data) { return data.vid().v; }), + parse(photo)); +} + +void Parser::process(const MTPDocument &document) { + _documentsById.emplace( + document.match([](const auto &data) { return data.vid().v; }), + parse(document)); +} + +template +QByteArray Parser::list(const MTPVector &data) { + auto result = QByteArrayList(); + result.reserve(data.v.size()); + for (const auto &item : data.v) { + result.append(item.match([&](const auto &data) { + return block(data); + })); + } + return result.join(QByteArray()); +} + +QByteArray Parser::block(const MTPDpageBlockUnsupported &data) { + return "Unsupported."_q; +} + +QByteArray Parser::block(const MTPDpageBlockTitle &data) { + return tag("h1", { { "class", "iv-title" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockSubtitle &data) { + return tag("h2", { { "class", "iv-subtitle" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockAuthorDate &data) { + auto inner = rich(data.vauthor()); + if (const auto date = data.vpublished_date().v) { + const auto parsed = base::unixtime::parse(date); + inner += " \xE2\x80\xA2 " + + tag("time", langDateTimeFull(parsed).toUtf8()); + } + return tag("address", inner); +} + +QByteArray Parser::block(const MTPDpageBlockHeader &data) { + return tag("h3", { { "class", "iv-header" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockSubheader &data) { + return tag("h4", { { "class", "iv-subheader" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockParagraph &data) { + return tag("p", rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockPreformatted &data) { + auto list = Attributes(); + const auto language = utf(data.vlanguage()); + if (!language.isEmpty()) { + list.push_back({ "data-language", language }); + list.push_back({ "class", "lang-" + language }); + _hasCode = true; + } + return tag("pre", list, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockFooter &data) { + return tag("footer", { { "class", "iv-footer" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockDivider &data) { + return tag("hr", { {"class", "iv-divider" } }); +} + +QByteArray Parser::block(const MTPDpageBlockAnchor &data) { + return tag("a", { { "name", utf(data.vname())} }); +} + +QByteArray Parser::block(const MTPDpageBlockList &data) { + return tag("ul", list(data.vitems())); +} + +QByteArray Parser::block(const MTPDpageBlockBlockquote &data) { + const auto caption = rich(data.vcaption()); + const auto cite = caption.isEmpty() + ? QByteArray() + : tag("cite", caption); + return tag("blockquote", rich(data.vtext()) + cite); +} + +QByteArray Parser::block(const MTPDpageBlockPullquote &data) { + const auto caption = rich(data.vcaption()); + const auto cite = caption.isEmpty() + ? QByteArray() + : tag("cite", caption); + return tag( + "div", + { { "class", "iv-pullquote" } }, + rich(data.vtext()) + cite); +} + +QByteArray Parser::block(const MTPDpageBlockPhoto &data) { + const auto photo = photoById(data.vphoto_id().v); + if (!photo.id) { + return "Photo not found."; + } + const auto src = photoFullUrl(photo); + auto wrapStyle = QByteArray(); + if (photo.width) { + wrapStyle += "max-width:" + QByteArray::number(photo.width) + "px"; + } + const auto minithumb = Images::ExpandInlineBytes(photo.minithumbnail); + if (!minithumb.isEmpty()) { + const auto image = Images::Read({ .content = minithumb }); + wrapStyle += ";background-image:url('data:image/jpeg;base64," + + minithumb.toBase64() + + "');"; + } + const auto dimension = (photo.width && photo.height) + ? (photo.height / float64(photo.width)) + : (3 / 4.); + const auto paddingTopPercent = int(base::SafeRound(dimension * 100)); + const auto style = "background-image:url('" + src + "');" + "padding-top:" + QByteArray::number(paddingTopPercent) + "%"; + const auto inner = tag("div", { + { "class", "iv-photo" }, + { "style", style } }); + auto result = tag( + "div", + { { "class", "iv-photo-wrap" }, { "style", wrapStyle } }, + inner); + if (const auto url = data.vurl()) { + result = tag("a", { { "href", utf(*url) } }, result); + } + auto attributes = Attributes(); + if (_captionAsTitle) { + const auto caption = plain(data.vcaption().data().vtext()); + const auto credit = plain(data.vcaption().data().vtext()); + if (!caption.isEmpty() || !credit.isEmpty()) { + const auto title = (!caption.isEmpty() && !credit.isEmpty()) + ? (caption + " / " + credit) + : (caption + credit); + attributes.push_back({ "title", title }); + } + } else { + result += caption(data.vcaption()); + } + return tag("figure", attributes, result); +} + +QByteArray Parser::block(const MTPDpageBlockVideo &data) { + const auto video = documentById(data.vvideo_id().v); + if (!video.id) { + return "Video not found."; + } + const auto src = documentFullUrl(video); + auto vattributes = Attributes{}; + if (data.is_autoplay()) { + vattributes.push_back({ "preload", "auto" }); + vattributes.push_back({ "autoplay", std::nullopt }); + } else { + vattributes.push_back({ "controls", std::nullopt }); + } + if (data.is_loop()) { + vattributes.push_back({ "loop", std::nullopt }); + } + vattributes.push_back({ "muted", std::nullopt }); + auto result = tag( + "video", + vattributes, + tag("source", { { "src", src }, { "type", "video/mp4" } })); + auto attributes = Attributes(); + if (_captionAsTitle) { + const auto caption = plain(data.vcaption().data().vtext()); + const auto credit = plain(data.vcaption().data().vtext()); + if (!caption.isEmpty() || !credit.isEmpty()) { + const auto title = (!caption.isEmpty() && !credit.isEmpty()) + ? (caption + " / " + credit) + : (caption + credit); + attributes.push_back({ "title", title }); + } + } else { + result += caption(data.vcaption()); + } + return tag("figure", attributes, result); +} + +QByteArray Parser::block(const MTPDpageBlockCover &data) { + return tag("figure", data.vcover().match([&](const auto &data) { + return block(data); + })); +} + +QByteArray Parser::block(const MTPDpageBlockEmbed &data) { + _hasEmbeds = true; + auto eclass = data.is_full_width() ? QByteArray() : "nowide"; + auto width = QByteArray(); + auto height = QByteArray(); + auto iframeWidth = QByteArray(); + auto iframeHeight = QByteArray(); + const auto autosize = !data.vw(); + if (autosize) { + iframeWidth = "100%"; + eclass = "nowide"; + } else if (data.is_full_width() || !data.vw()->v) { + width = "100%"; + height = QByteArray::number(data.vh()->v) + "px"; + iframeWidth = "100%"; + iframeHeight = height; + } else { + const auto percent = data.vh()->v * 100 / data.vw()->v; + width = QByteArray::number(data.vw()->v) + "px"; + height = QByteArray::number(percent) + "%"; + } + auto attributes = Attributes(); + if (autosize) { + attributes.push_back({ "class", "autosize" }); + } + attributes.push_back({ "width", iframeWidth }); + attributes.push_back({ "height", iframeHeight }); + if (const auto url = data.vurl()) { + if (!autosize) { + attributes.push_back({ "src", utf(url) }); + } else { + attributes.push_back({ "srcdoc", utf(url) }); + } + } else if (const auto html = data.vhtml()) { + attributes.push_back({ "src", embedUrl(html->v) }); + } + if (!data.is_allow_scrolling()) { + attributes.push_back({ "scrolling", "no" }); + } + attributes.push_back({ "frameborder", "0" }); + attributes.push_back({ "allowtransparency", "true" }); + attributes.push_back({ "allowfullscreen", "true" }); + auto result = tag("iframe", attributes); + if (!autosize) { + result = tag("div", { + { "class", "iframe-wrap" }, + { "style", "width:" + width }, + }, tag("div", { + { "style", "padding-bottom: " + height }, + }, result)); + } + result += caption(data.vcaption()); + return tag("figure", { { "class", eclass } }, result); +} + +QByteArray Parser::block(const MTPDpageBlockEmbedPost &data) { + auto result = QByteArray(); + if (!data.vblocks().v.isEmpty()) { + auto address = QByteArray(); + const auto photo = photoById(data.vauthor_photo_id().v); + if (photo.id) { + const auto src = photoFullUrl(photo); + address += tag( + "figure", + { { "style", "background-image:url('" + src + "')" } }); + } + address += tag( + "a", + { { "rel", "author" }, { "onclick", "return false;" } }, + utf(data.vauthor())); + if (const auto date = data.vdate().v) { + const auto parsed = base::unixtime::parse(date); + address += tag("time", langDateTimeFull(parsed).toUtf8()); + } + const auto inner = tag("address", address) + list(data.vblocks()); + result = tag("blockquote", { { "class", "embed-post" } }, inner); + } else { + const auto url = utf(data.vurl()); + const auto inner = tag("strong", utf(data.vauthor())) + + tag("small", tag("a", { { "href", url } }, url)); + result = tag("section", { { "class", "embed-post" } }, inner); + } + result += caption(data.vcaption()); + return tag("figure", result); +} + +QByteArray Parser::block(const MTPDpageBlockCollage &data) { + auto result = tag( + "figure", + { { "class", "collage" } }, + list(data.vitems())); + return tag("figure", result + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageBlockSlideshow &data) { + auto inputs = QByteArrayList(); + auto i = 0; + for (auto i = 0; i != int(data.vitems().v.size()); ++i) { + auto attributes = Attributes{ + { "type", "radio" }, + { "name", "s" }, + { "value", QByteArray::number(i) }, + { "onchange", "return IV.slideshowSlide(this);" }, + }; + if (!i) { + attributes.push_back({ "checked", std::nullopt }); + } + inputs.append(tag("label", tag("input", attributes, tag("i")))); + } + const auto form = tag( + "form", + { { "class", "slideshow-buttons" } }, + tag("fieldset", inputs.join(QByteArray()))); + auto inner = form + tag("figure", { + { "class", "slideshow" }, + { "onclick", "return IV.slideshowSlide(this, 1);" }, + }, list(data.vitems())); + auto result = tag( + "figure", + { { "class", "slideshow-wrap" } }, + inner); + return tag("figure", result + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageBlockChannel &data) { + auto name = QByteArray(); + auto username = QByteArray(); + data.vchannel().match([&](const MTPDchannel &data) { + if (const auto has = data.vusername()) { + username = utf(*has); + } + name = utf(data.vtitle()); + }, [&](const MTPDchat &data) { + name = utf(data.vtitle()); + }, [](const auto &) { + }); + auto result = tag("h4", name); + if (!username.isEmpty()) { + const auto link = "https://t.me/" + username; + result = tag( + "a", + { { "href", link }, { "target", "_blank" } }, + result); + } + return tag("section", { { "class", "channel" } }, result); +} + +QByteArray Parser::block(const MTPDpageBlockAudio &data) { + const auto audio = documentById(data.vaudio_id().v); + if (!audio.id) { + return "Audio not found."; + } + const auto src = documentFullUrl(audio); + return tag("figure", tag("audio", { + { "src", src }, + { "controls", std::nullopt }, + }) + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageBlockKicker &data) { + return tag("h6", { { "class", "iv-kicker" } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageBlockTable &data) { + auto classes = QByteArrayList(); + if (data.is_bordered()) { + classes.push_back("bordered"); + } + if (data.is_striped()) { + classes.push_back("striped"); + } + auto attibutes = Attributes(); + if (!classes.isEmpty()) { + attibutes.push_back({ "class", classes.join(" ") }); + } + auto title = rich(data.vtitle()); + if (!title.isEmpty()) { + title = tag("caption", title); + } + auto result = tag("table", attibutes, title + list(data.vrows())); + result = tag("figure", { { "class", "table" } }, result); + result = tag("figure", { { "class", "table-wrap" } }, result); + return tag("figure", result); +} + +QByteArray Parser::block(const MTPDpageBlockOrderedList &data) { + return tag("ol", list(data.vitems())); +} + +QByteArray Parser::block(const MTPDpageBlockDetails &data) { + auto attributes = Attributes(); + if (data.is_open()) { + attributes.push_back({ "open", std::nullopt }); + } + return tag( + "details", + attributes, + tag("summary", rich(data.vtitle())) + list(data.vblocks())); +} + +QByteArray Parser::block(const MTPDpageBlockRelatedArticles &data) { + const auto result = list(data.varticles()); + if (result.isEmpty()) { + return QByteArray(); + } + auto title = rich(data.vtitle()); + if (!title.isEmpty()) { + title = tag("h4", { { "class", "iv-related-title" } }, title); + } + return tag("section", { { "class", "iv-related" } }, title + result); +} + +QByteArray Parser::block(const MTPDpageBlockMap &data) { + const auto geo = parse(data.vgeo()); + if (!geo.access) { + return "Map not found."; + } + const auto width = 650; + const auto height = std::min(450, (data.vh().v * width / data.vw().v)); + return tag("figure", tag("img", { + { "src", mapUrl(geo, width, height, data.vzoom().v) }, + }) + caption(data.vcaption())); +} + +QByteArray Parser::block(const MTPDpageRelatedArticle &data) { + auto result = QByteArray(); + const auto photo = photoById(data.vphoto_id().value_or_empty()); + if (photo.id) { + const auto src = photoFullUrl(photo); + result += tag("i", { + { "class", "related-link-thumb" }, + { "style", "background-image:url('" + src + "')" }, + }); + } + const auto title = data.vtitle(); + const auto description = data.vdescription(); + const auto author = data.vauthor(); + const auto published = data.vpublished_date(); + if (title || description || author || published) { + auto inner = QByteArray(); + if (title) { + inner += tag( + "span", + { { "class", "related-link-title" } }, + utf(*title)); + } + if (description) { + inner += tag( + "span", + { { "class", "related-link-desc" } }, + utf(*description)); + } + if (author || published) { + const auto separator = (author && published) ? ", " : ""; + const auto parsed = base::unixtime::parse(published->v); + inner += tag( + "span", + { { "class", "related-link-source" } }, + utf(*author) + separator + langDateTimeFull(parsed).toUtf8()); + } + result += tag("span", { + { "class", "related-link-content" }, + }, inner); + } + return tag("a", { + { "class", "related-link" }, + { "href", utf(data.vurl()) }, + }, result); +} + +QByteArray Parser::block(const MTPDpageTableRow &data) { + return tag("tr", list(data.vcells())); +} + +QByteArray Parser::block(const MTPDpageTableCell &data) { + const auto text = data.vtext() ? rich(*data.vtext()) : QByteArray(); + auto style = QByteArray(); + if (data.is_align_right()) { + style += "text-align:right;"; + } else if (data.is_align_center()) { + style += "text-align:center;"; + } else { + style += "text-align:left;"; + } + if (data.is_valign_bottom()) { + style += "vertical-align:bottom;"; + } else if (data.is_valign_middle()) { + style += "vertical-align:middle;"; + } else { + style += "vertical-align:top;"; + } + auto attributes = Attributes{ { "style", style } }; + if (const auto cs = data.vcolspan()) { + attributes.push_back({ "colspan", QByteArray::number(cs->v) }); + } + if (const auto rs = data.vrowspan()) { + attributes.push_back({ "rowspan", QByteArray::number(rs->v) }); + } + return tag(data.is_header() ? "th" : "td", attributes, text); +} + +QByteArray Parser::block(const MTPDpageListItemText &data) { + return tag("li", rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageListItemBlocks &data) { + return tag("li", list(data.vblocks())); +} + +QByteArray Parser::block(const MTPDpageListOrderedItemText &data) { + return tag("li", { { "value", utf(data.vnum()) } }, rich(data.vtext())); +} + +QByteArray Parser::block(const MTPDpageListOrderedItemBlocks &data) { + return tag( + "li", + { { "value", utf(data.vnum()) } }, + list(data.vblocks())); +} + +QByteArray Parser::utf(const MTPstring &text) { + return text.v; +} + +QByteArray Parser::utf(const tl::conditional &text) { + return text ? text->v : QByteArray(); +} + +QByteArray Parser::tag( + const QByteArray &name, + const QByteArray &body) { + return tag(name, {}, body); +} + +QByteArray Parser::tag( + const QByteArray &name, + const Attributes &attributes, + const QByteArray &body) { + auto list = QByteArrayList(); + list.reserve(attributes.size()); + for (auto &[name, value] : attributes) { + list.push_back(' ' + name + (value ? "=\"" + *value + "\"" : "")); + } + const auto serialized = list.join(QByteArray()); + return IsVoidElement(name) + ? ('<' + name + serialized + " />") + : ('<' + name + serialized + '>' + body + "'); +} + +QByteArray Parser::rich(const MTPRichText &text) { + return text.match([&](const MTPDtextEmpty &data) { + return QByteArray(); + }, [&](const MTPDtextPlain &data) { + struct Replacement { + QByteArray from; + QByteArray to; + }; + const auto replacements = std::vector{ + { "\xE2\x81\xA6", "" }, + { "\xE2\x81\xA7", "" }, + { "\xE2\x81\xA8", "" }, + { "\xE2\x81\xA9", "" }, + }; + auto text = utf(data.vtext()); + for (const auto &[from, to] : replacements) { + text.replace(from, to); + } + return text; + }, [&](const MTPDtextConcat &data) { + const auto &list = data.vtexts().v; + auto result = QByteArrayList(); + result.reserve(list.size()); + for (const auto &item : list) { + result.append(rich(item)); + } + return result.join(QByteArray()); + }, [&](const MTPDtextImage &data) { + const auto image = documentById(data.vdocument_id().v); + if (!image.id) { + return "Image not found."_q; + } + auto attributes = Attributes{ + { "class", "pic" }, + { "src", documentFullUrl(image) }, + }; + if (const auto width = data.vw().v) { + attributes.push_back({ "width", QByteArray::number(width) }); + } + if (const auto height = data.vh().v) { + attributes.push_back({ "height", QByteArray::number(height) }); + } + return tag("img", attributes); + }, [&](const MTPDtextBold &data) { + return tag("b", rich(data.vtext())); + }, [&](const MTPDtextItalic &data) { + return tag("i", rich(data.vtext())); + }, [&](const MTPDtextUnderline &data) { + return tag("u", rich(data.vtext())); + }, [&](const MTPDtextStrike &data) { + return tag("s", rich(data.vtext())); + }, [&](const MTPDtextFixed &data) { + return tag("code", rich(data.vtext())); + }, [&](const MTPDtextUrl &data) { + return tag("a", { + { "href", utf(data.vurl()) }, + }, rich(data.vtext())); + }, [&](const MTPDtextEmail &data) { + return tag("a", { + { "href", "mailto:" + utf(data.vemail()) }, + }, rich(data.vtext())); + }, [&](const MTPDtextSubscript &data) { + return tag("sub", rich(data.vtext())); + }, [&](const MTPDtextSuperscript &data) { + return tag("sup", rich(data.vtext())); + }, [&](const MTPDtextMarked &data) { + return tag("mark", rich(data.vtext())); + }, [&](const MTPDtextPhone &data) { + return tag("a", { + { "href", "tel:" + utf(data.vphone()) }, + }, rich(data.vtext())); + }, [&](const MTPDtextAnchor &data) { + const auto inner = rich(data.vtext()); + return inner.isEmpty() + ? tag("a", { { "name", utf(data.vname()) } }) + : tag( + "span", + { { "class", "reference" } }, + tag("a", { { "name", utf(data.vname()) } }) + inner); + }); +} + +QByteArray Parser::plain(const MTPRichText &text) { + return text.match([&](const MTPDtextEmpty &data) { + return QByteArray(); + }, [&](const MTPDtextPlain &data) { + return utf(data.vtext()); + }, [&](const MTPDtextConcat &data) { + const auto &list = data.vtexts().v; + auto result = QByteArrayList(); + result.reserve(list.size()); + for (const auto &item : list) { + result.append(plain(item)); + } + return result.join(QByteArray()); + }, [&](const MTPDtextImage &data) { + return QByteArray(); + }, [&](const auto &data) { + return plain(data.vtext()); + }); +} + +QByteArray Parser::caption(const MTPPageCaption &caption) { + auto text = rich(caption.data().vtext()); + const auto credit = rich(caption.data().vcredit()); + if (_captionWrapped && !text.isEmpty()) { + text = tag("span", text); + } + if (!credit.isEmpty()) { + text += tag("cite", credit); + } else if (text.isEmpty()) { + return QByteArray(); + } + return tag("figcaption", text); +} + +Photo Parser::parse(const MTPPhoto &photo) { + auto result = Photo{ + .id = photo.match([&](const auto &d) { return d.vid().v; }), + }; + auto sizes = base::flat_map(); + photo.match([](const MTPDphotoEmpty &) { + }, [&](const MTPDphoto &data) { + for (const auto &size : data.vsizes().v) { + size.match([&](const MTPDphotoSizeEmpty &data) { + }, [&](const MTPDphotoSize &data) { + sizes.emplace( + data.vtype().v, + QSize(data.vw().v, data.vh().v)); + }, [&](const MTPDphotoCachedSize &data) { + sizes.emplace( + data.vtype().v, + QSize(data.vw().v, data.vh().v)); + }, [&](const MTPDphotoStrippedSize &data) { + result.minithumbnail = data.vbytes().v; + }, [&](const MTPDphotoSizeProgressive &data) { + sizes.emplace( + data.vtype().v, + QSize(data.vw().v, data.vh().v)); + }, [&](const MTPDphotoPathSize &data) { + }); + } + }); + for (const auto attempt : { "y", "x", "w" }) { + const auto i = sizes.find(QByteArray(attempt)); + if (i != end(sizes)) { + result.width = i->second.width(); + result.height = i->second.height(); + break; + } + } + return result; +} + +Document Parser::parse(const MTPDocument &document) { + auto result = Document{ + .id = document.match([&](const auto &d) { return d.vid().v; }), + }; + document.match([](const MTPDdocumentEmpty &) { + }, [&](const MTPDdocument &data) { + }); + return result; +} + +Geo Parser::parse(const MTPGeoPoint &geo) { + return geo.match([](const MTPDgeoPointEmpty &) { + return Geo(); + }, [&](const MTPDgeoPoint &data) { + return Geo{ + .lat = data.vlat().v, + .lon = data.vlong().v, + .access = data.vaccess_hash().v, + }; + }); +} + +Photo Parser::photoById(uint64 id) { + const auto i = _photosById.find(id); + return (i != end(_photosById)) ? i->second : Photo(); +} + +Document Parser::documentById(uint64 id) { + const auto i = _documentsById.find(id); + return (i != end(_documentsById)) ? i->second : Document(); +} + +QByteArray Parser::photoFullUrl(const Photo &photo) { + return resource("photo/" + QByteArray::number(photo.id)); +} + +QByteArray Parser::documentFullUrl(const Document &document) { + return resource("document/" + QByteArray::number(document.id)); +} + +QByteArray Parser::embedUrl(const QByteArray &html) { + auto binary = std::array{}; + SHA256( + reinterpret_cast(html.data()), + html.size(), + binary.data()); + const auto hex = [](uchar value) -> char { + return (value >= 10) ? ('a' + (value - 10)) : ('0' + value); + }; + auto result = QByteArray(); + result.reserve(binary.size() * 2); + auto index = 0; + for (const auto byte : binary) { + result.push_back(hex(byte / 16)); + result.push_back(hex(byte % 16)); + } + result += ".html"; + _result.embeds.emplace(result, html); + return resource("html/" + result); +} + +QByteArray Parser::mapUrl(const Geo &geo, int width, int height, int zoom) { + return resource("map/" + + GeoPointId(geo) + "&" + + QByteArray::number(width) + "," + + QByteArray::number(height) + "&" + + QByteArray::number(zoom)); +} + +QByteArray Parser::resource(QByteArray id) { + if (!_options.saveToFolder.isEmpty() && _resources.emplace(id).second) { + _result.resources.push_back(id); + } + return _resourcePrefix + id; +} + +QByteArray Parser::page(const MTPDpage &data) { + const auto html = list(data.vblocks()); + if (html.isEmpty()) { + return html; + } + auto attributes = Attributes(); + if (_rtl) { + attributes.push_back({ "dir", "rtl" }); + attributes.push_back({ "class", "rtl" }); + } + return tag("article", attributes, html); +} + +QByteArray Parser::prepare(QByteArray body) { + auto head = QByteArray(); + auto js = QByteArray(); + if (body.isEmpty()) { + body = tag( + "section", + { { "class", "message" } }, + tag("aside", "Failed." + tag("cite", "Failed."))); + } + if (_hasCode) { + head += R"( + + +)"_q; + js += "IV.initPreBlocks();"; + } + if (_hasEmbeds) { + js += "IV.initEmbedBlocks();"; + } + if (!js.isEmpty()) { + body += tag("script", js); + } + return html(head, body); +} + +QByteArray Parser::html(const QByteArray &head, const QByteArray &body) { + return R"( + + + + + + + + )"_q + head + R"( + + )"_q + body + R"( + +)"_q; +} + +} // namespace + +Prepared Prepare(const Source &source, const Options &options) { + auto parser = Parser(source, options); + return parser.result(); +} + +} // namespace Iv diff --git a/Telegram/SourceFiles/iv/iv_prepare.h b/Telegram/SourceFiles/iv/iv_prepare.h new file mode 100644 index 000000000..f5971d607 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv_prepare.h @@ -0,0 +1,25 @@ +/* +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 +*/ +#pragma once + +namespace Iv { + +struct Options; +struct Prepared; + +struct Source { + MTPPage page; + std::optional webpagePhoto; + std::optional webpageDocument; +}; + +[[nodiscard]] Prepared Prepare( + const Source &source, + const Options &options); + +} // namespace Iv diff --git a/Telegram/cmake/td_iv.cmake b/Telegram/cmake/td_iv.cmake new file mode 100644 index 000000000..64fe487ce --- /dev/null +++ b/Telegram/cmake/td_iv.cmake @@ -0,0 +1,35 @@ +# 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 + +add_library(td_iv OBJECT) +init_non_host_target(td_iv) +add_library(tdesktop::td_iv ALIAS td_iv) + +target_precompile_headers(td_iv PRIVATE ${src_loc}/iv/iv_pch.h) +nice_target_sources(td_iv ${src_loc} +PRIVATE + iv/iv_controller.cpp + iv/iv_controller.h + iv/iv_data.cpp + iv/iv_data.h + iv/iv_pch.h + iv/iv_prepare.cpp + iv/iv_prepare.h +) + +target_include_directories(td_iv +PUBLIC + ${src_loc} +) + +target_link_libraries(td_iv +PUBLIC + desktop-app::lib_ui + tdesktop::td_scheme +PRIVATE + desktop-app::lib_webview + tdesktop::td_lang +) From 6d733bb5660a9a386260117aaeb64571d287d37f Mon Sep 17 00:00:00 2001 From: John Preston Date: Tue, 3 Oct 2023 21:21:52 +0400 Subject: [PATCH 014/240] Proof-of-concept custom scheme in WKWebView. --- Telegram/SourceFiles/data/data_session.cpp | 4 ++-- Telegram/SourceFiles/history/history_item.cpp | 2 ++ Telegram/SourceFiles/iv/iv_controller.cpp | 2 +- Telegram/SourceFiles/iv/iv_prepare.cpp | 10 +++------- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index 36f35642d..d0d3d8555 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -3509,10 +3509,10 @@ void Session::webpageApplyFields( } } if (const auto page = data.vcached_page()) { - for (const auto photo : page->data().vphotos().v) { + for (const auto &photo : page->data().vphotos().v) { processPhoto(photo); } - for (const auto document : page->data().vdocuments().v) { + for (const auto &document : page->data().vdocuments().v) { processDocument(document); } } diff --git a/Telegram/SourceFiles/history/history_item.cpp b/Telegram/SourceFiles/history/history_item.cpp index b55baa6d2..d990c56ef 100644 --- a/Telegram/SourceFiles/history/history_item.cpp +++ b/Telegram/SourceFiles/history/history_item.cpp @@ -18,6 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history_item_helpers.h" #include "history/history_unread_things.h" #include "history/history.h" +#include "iv/iv_data.h" #include "mtproto/mtproto_config.h" #include "ui/text/format_values.h" #include "ui/text/text_isolated_emoji.h" @@ -668,6 +669,7 @@ HistoryItem::HistoryItem( : nullptr), nullptr, WebPageCollage(), + nullptr, 0, QString(), false, diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index bac53f983..6f9069dfd 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -29,7 +29,7 @@ void Controller::show(const QString &dataPath, Prepared page) { _window = std::make_unique(); const auto window = _window.get(); - window->setGeometry({ 200, 200, 800, 600 }); + window->setGeometry({ 200, 200, 600, 800 }); const auto container = Ui::CreateChild( window->body().get()); diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp index a4709502d..69a86689c 100644 --- a/Telegram/SourceFiles/iv/iv_prepare.cpp +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -132,13 +132,11 @@ private: const Options _options; - const QByteArray _resourcePrefix; base::flat_set _resources; Prepared _result; bool _rtl = false; - bool _imageAsBackground = false; bool _captionAsTitle = false; bool _captionWrapped = false; base::flat_map _photosById; @@ -171,9 +169,6 @@ private: Parser::Parser(const Source &source, const Options &options) : _options(options) -, _resourcePrefix(options.saveToFolder.isEmpty() - ? "http://desktop-app-resource/" - : QByteArray()) , _rtl(source.page.data().is_rtl()) { process(source); _result.html = prepare(page(source.page.data())); @@ -968,10 +963,11 @@ QByteArray Parser::mapUrl(const Geo &geo, int width, int height, int zoom) { } QByteArray Parser::resource(QByteArray id) { - if (!_options.saveToFolder.isEmpty() && _resources.emplace(id).second) { + const auto toFolder = !_options.saveToFolder.isEmpty(); + if (toFolder && _resources.emplace(id).second) { _result.resources.push_back(id); } - return _resourcePrefix + id; + return toFolder ? id : ('/' + id); } QByteArray Parser::page(const MTPDpage &data) { From 212259aae34027525d3393ce6086968bd28e14a8 Mon Sep 17 00:00:00 2001 From: John Preston Date: Fri, 1 Dec 2023 18:47:24 +0400 Subject: [PATCH 015/240] Handle shortcuts in IV. --- Telegram/Resources/iv_html/page.js | 188 ++++++++++++---------- Telegram/SourceFiles/core/application.cpp | 15 +- Telegram/SourceFiles/iv/iv_controller.cpp | 69 +++++++- Telegram/SourceFiles/iv/iv_controller.h | 22 ++- Telegram/SourceFiles/iv/iv_instance.cpp | 53 ++++++ Telegram/SourceFiles/iv/iv_instance.h | 3 + Telegram/cmake/td_iv.cmake | 6 + 7 files changed, 261 insertions(+), 95 deletions(-) diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index d821a1e43..8486e2cc7 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -1,86 +1,112 @@ var IV = { - sendPostMessage: function(data) { - try { - window.parent.postMessage(JSON.stringify(data), window.parentOrigin); - } catch(e) {} - }, - frameClickHandler: function(e) { - var target = e.target, href; - do { - if (target.tagName == 'SUMMARY') return; - if (target.tagName == 'DETAILS') return; - if (target.tagName == 'LABEL') return; - if (target.tagName == 'AUDIO') return; - if (target.tagName == 'A') break; - } while (target = target.parentNode); - if (target && target.hasAttribute('href')) { - var base_loc = document.createElement('A'); - base_loc.href = window.currentUrl; - if (base_loc.origin != target.origin || - base_loc.pathname != target.pathname || - base_loc.search != target.search) { - IV.sendPostMessage({event: 'link_click', url: target.href}); - } - } - e.preventDefault(); - }, - postMessageHandler: function(event) { - if (event.source !== window.parent || - event.origin != window.parentOrigin) { - return; - } - try { - var data = JSON.parse(event.data); - } catch(e) { - var data = {}; - } - }, - slideshowSlide: function(el, next) { - var dir = window.getComputedStyle(el, null).direction || 'ltr'; - var marginProp = dir == 'rtl' ? 'marginRight' : 'marginLeft'; - if (next) { - var s = el.previousSibling.s; - s.value = (+s.value + 1 == s.length) ? 0 : +s.value + 1; - s.forEach(function(el){ el.checked && el.parentNode.scrollIntoView && el.parentNode.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'center'}); }); - el.firstChild.style[marginProp] = (-100 * s.value) + '%'; - } else { - el.form.nextSibling.firstChild.style[marginProp] = (-100 * el.value) + '%'; - } - return false; - }, - initPreBlocks: function() { - if (!hljs) return; - var pres = document.getElementsByTagName('pre'); - for (var i = 0; i < pres.length; i++) { - if (pres[i].hasAttribute('data-language')) { - hljs.highlightBlock(pres[i]); - } - } - }, - initEmbedBlocks: function() { - var iframes = document.getElementsByTagName('iframe'); - for (var i = 0; i < iframes.length; i++) { - (function(iframe) { - window.addEventListener('message', function(event) { - if (event.source !== iframe.contentWindow || - event.origin != window.origin) { - return; - } - try { - var data = JSON.parse(event.data); - } catch(e) { - var data = {}; - } - if (data.eventType == 'resize_frame') { - if (data.eventData.height) { - iframe.style.height = data.eventData.height + 'px'; - } - } - }, false); - })(iframes[i]); - } - } + notify: function(message) { + if (window.external && window.external.invoke) { + window.external.invoke(JSON.stringify(message)); + } + }, + frameClickHandler: function(e) { + var target = e.target, href; + do { + if (target.tagName == 'SUMMARY') return; + if (target.tagName == 'DETAILS') return; + if (target.tagName == 'LABEL') return; + if (target.tagName == 'AUDIO') return; + if (target.tagName == 'A') break; + } while (target = target.parentNode); + if (target && target.hasAttribute('href')) { + var base_loc = document.createElement('A'); + base_loc.href = window.currentUrl; + if (base_loc.origin != target.origin || + base_loc.pathname != target.pathname || + base_loc.search != target.search) { + IV.notify({ event: 'link_click', url: target.href }); + } + } + e.preventDefault(); + }, + frameKeyDown: function (e) { + let keyW = (e.key === 'w') + || (e.code === 'KeyW') + || (e.keyCode === 87); + let keyQ = (e.key === 'q') + || (e.code === 'KeyQ') + || (e.keyCode === 81); + let keyM = (e.key === 'm') + || (e.code === 'KeyM') + || (e.keyCode === 77); + if ((e.metaKey || e.ctrlKey) && (keyW || keyQ || keyM)) { + e.preventDefault(); + IV.notify({ + event: 'keydown', + modifier: e.ctrlKey ? 'ctrl' : 'cmd', + key: keyW ? 'w' : keyQ ? 'q' : 'm', + }); + } else if (e.key === 'Escape' || e.keyCode === 27) { + e.preventDefault(); + IV.notify({ + event: 'keydown', + key: 'escape', + }); + } + }, + postMessageHandler: function(event) { + if (event.source !== window.parent || + event.origin != window.parentOrigin) { + return; + } + try { + var data = JSON.parse(event.data); + } catch(e) { + var data = {}; + } + }, + slideshowSlide: function(el, next) { + var dir = window.getComputedStyle(el, null).direction || 'ltr'; + var marginProp = dir == 'rtl' ? 'marginRight' : 'marginLeft'; + if (next) { + var s = el.previousSibling.s; + s.value = (+s.value + 1 == s.length) ? 0 : +s.value + 1; + s.forEach(function(el){ el.checked && el.parentNode.scrollIntoView && el.parentNode.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'center'}); }); + el.firstChild.style[marginProp] = (-100 * s.value) + '%'; + } else { + el.form.nextSibling.firstChild.style[marginProp] = (-100 * el.value) + '%'; + } + return false; + }, + initPreBlocks: function() { + if (!hljs) return; + var pres = document.getElementsByTagName('pre'); + for (var i = 0; i < pres.length; i++) { + if (pres[i].hasAttribute('data-language')) { + hljs.highlightBlock(pres[i]); + } + } + }, + initEmbedBlocks: function() { + var iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; i++) { + (function(iframe) { + window.addEventListener('message', function(event) { + if (event.source !== iframe.contentWindow || + event.origin != window.origin) { + return; + } + try { + var data = JSON.parse(event.data); + } catch(e) { + var data = {}; + } + if (data.eventType == 'resize_frame') { + if (data.eventData.height) { + iframe.style.height = data.eventData.height + 'px'; + } + } + }, false); + })(iframes[i]); + } + } }; document.onclick = IV.frameClickHandler; +document.onkeydown = IV.frameKeyDown; window.onmessage = IV.postMessageHandler; diff --git a/Telegram/SourceFiles/core/application.cpp b/Telegram/SourceFiles/core/application.cpp index 8fe1e75c7..06691b5c9 100644 --- a/Telegram/SourceFiles/core/application.cpp +++ b/Telegram/SourceFiles/core/application.cpp @@ -1547,12 +1547,12 @@ bool Application::closeActiveWindow() { if (_mediaView && _mediaView->isActive()) { _mediaView->close(); return true; - } else if (!calls().closeCurrentActiveCall()) { - if (const auto window = activeWindow()) { - if (window->widget()->isActive()) { - window->close(); - return true; - } + } else if (_iv->closeActive() || calls().closeCurrentActiveCall()) { + return true; + } else if (const auto window = activeWindow()) { + if (window->widget()->isActive()) { + window->close(); + return true; } } return false; @@ -1562,7 +1562,8 @@ bool Application::minimizeActiveWindow() { if (_mediaView && _mediaView->isActive()) { _mediaView->minimize(); return true; - } else if (calls().minimizeCurrentActiveCall()) { + } else if (_iv->minimizeActive() + || calls().minimizeCurrentActiveCall()) { return true; } else { if (const auto window = activeWindow()) { diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index 6f9069dfd..709461eaa 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -7,14 +7,20 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "iv/iv_controller.h" +#include "base/platform/base_platform_info.h" #include "iv/iv_data.h" #include "ui/widgets/rp_window.h" #include "webview/webview_data_stream_memory.h" #include "webview/webview_embed.h" #include "webview/webview_interface.h" +#include "styles/palette.h" #include +#include +#include +#include #include +#include namespace Iv { @@ -47,22 +53,56 @@ void Controller::show(const QString &dataPath, Prepared page) { _webview = nullptr; }); if (!raw->widget()) { - _webview = nullptr; - _window = nullptr; + _events.fire(Event::Close); return; } + window->events( + ) | rpl::start_with_next([=](not_null e) { + if (e->type() == QEvent::Close) { + close(); + } else if (e->type() == QEvent::KeyPress) { + const auto event = static_cast(e.get()); + if (event->key() == Qt::Key_Escape) { + escape(); + } + } + }, window->lifetime()); raw->widget()->show(); container->geometryValue( ) | rpl::start_with_next([=](QRect geometry) { raw->widget()->setGeometry(geometry); - }, _lifetime); + }, container->lifetime()); + + container->paintRequest() | rpl::start_with_next([=](QRect clip) { + QPainter(container).fillRect(clip, st::windowBg); + }, container->lifetime()); raw->setNavigationStartHandler([=](const QString &uri, bool newWindow) { return true; }); raw->setNavigationDoneHandler([=](bool success) { }); + raw->setMessageHandler([=](const QJsonDocument &message) { + crl::on_main(_window.get(), [=] { + const auto object = message.object(); + const auto event = object.value("event").toString(); + if (event == u"keydown"_q) { + const auto key = object.value("key").toString(); + const auto modifier = object.value("modifier").toString(); + const auto ctrl = Platform::IsMac() ? u"cmd"_q : u"ctrl"_q; + if (key == u"escape"_q) { + escape(); + } else if (key == u"w"_q && modifier == ctrl) { + close(); + } else if (key == u"m"_q && modifier == ctrl) { + minimize(); + } else if (key == u"q"_q && modifier == ctrl) { + quit(); + } + } + }); + }); raw->setDataRequestHandler([=](Webview::DataRequest request) { if (!request.id.starts_with("iv/")) { _dataRequests.fire(std::move(request)); @@ -104,8 +144,27 @@ void Controller::show(const QString &dataPath, Prepared page) { window->show(); } -rpl::producer Controller::dataRequests() const { - return _dataRequests.events(); +bool Controller::active() const { + return _window && _window->isActiveWindow(); +} + +void Controller::minimize() { + if (_window) { + _window->setWindowState(_window->windowState() + | Qt::WindowMinimized); + } +} + +void Controller::escape() { + close(); +} + +void Controller::close() { + _events.fire(Event::Close); +} + +void Controller::quit() { + _events.fire(Event::Quit); } rpl::lifetime &Controller::lifetime() { diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h index b35dfc00a..7e623f7ce 100644 --- a/Telegram/SourceFiles/iv/iv_controller.h +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -25,16 +25,34 @@ public: Controller(); ~Controller(); - void show(const QString &dataPath, Prepared page); + enum class Event { + Close, + Quit, + }; - [[nodiscard]] rpl::producer dataRequests() const; + void show(const QString &dataPath, Prepared page); + [[nodiscard]] bool active() const; + void minimize(); + + [[nodiscard]] rpl::producer dataRequests() const { + return _dataRequests.events(); + } + + [[nodiscard]] rpl::producer events() const { + return _events.events(); + } [[nodiscard]] rpl::lifetime &lifetime(); private: + void escape(); + void close(); + void quit(); + std::unique_ptr _window; std::unique_ptr _webview; rpl::event_stream _dataRequests; + rpl::event_stream _events; rpl::lifetime _lifetime; }; diff --git a/Telegram/SourceFiles/iv/iv_instance.cpp b/Telegram/SourceFiles/iv/iv_instance.cpp index 27f3dcfb2..4a1accd7e 100644 --- a/Telegram/SourceFiles/iv/iv_instance.cpp +++ b/Telegram/SourceFiles/iv/iv_instance.cpp @@ -8,6 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "iv/iv_instance.h" #include "core/file_utilities.h" +#include "core/shortcuts.h" #include "data/data_cloud_file.h" #include "data/data_document.h" #include "data/data_file_origin.h" @@ -63,6 +64,17 @@ public: not_null data) const; [[nodiscard]] bool showingFrom(not_null session) const; [[nodiscard]] bool activeFor(not_null session) const; + [[nodiscard]] bool active() const; + + void minimize(); + + [[nodiscard]] rpl::producer events() const { + return _events.events(); + } + + [[nodiscard]] rpl::lifetime &lifetime() { + return _lifetime; + } private: struct MapPreview { @@ -131,6 +143,8 @@ private: std::vector _resources; int _resource = -1; + rpl::event_stream _events; + rpl::lifetime _lifetime; }; @@ -358,6 +372,10 @@ void Shown::writeEmbed(QString id, QString hash) { void Shown::showWindowed(Prepared result) { _controller = std::make_unique(); + + _controller->events( + ) | rpl::start_to_stream(_events, _controller->lifetime()); + _controller->dataRequests( ) | rpl::start_with_next([=](Webview::DataRequest request) { const auto requested = QString::fromStdString(request.id); @@ -372,6 +390,7 @@ void Shown::showWindowed(Prepared result) { sendEmbed(id.mid(5).toUtf8(), std::move(request)); } }, _controller->lifetime()); + const auto domain = &_session->domain(); _controller->show(domain->local().webviewDataPath(), std::move(result)); } @@ -628,6 +647,16 @@ bool Shown::activeFor(not_null session) const { return showingFrom(session) && _controller; } +bool Shown::active() const { + return _controller && _controller->active(); +} + +void Shown::minimize() { + if (_controller) { + _controller->minimize(); + } +} + Instance::Instance() = default; Instance::~Instance() = default; @@ -641,6 +670,14 @@ void Instance::show( return; } _shown = std::make_unique(show, data, local); + _shown->events() | rpl::start_with_next([=](Controller::Event event) { + if (event == Controller::Event::Close) { + _shown = nullptr; + } else if (event == Controller::Event::Quit) { + Shortcuts::Launch(Shortcuts::Command::Quit); + } + }, _shown->lifetime()); + if (!_tracking.contains(session)) { _tracking.emplace(session); session->lifetime().add([=] { @@ -656,6 +693,22 @@ bool Instance::hasActiveWindow(not_null session) const { return _shown && _shown->activeFor(session); } +bool Instance::closeActive() { + if (!_shown || !_shown->active()) { + return false; + } + _shown = nullptr; + return true; +} + +bool Instance::minimizeActive() { + if (!_shown || !_shown->active()) { + return false; + } + _shown->minimize(); + return true; +} + void Instance::closeAll() { _shown = nullptr; } diff --git a/Telegram/SourceFiles/iv/iv_instance.h b/Telegram/SourceFiles/iv/iv_instance.h index 7a1b21f62..566876303 100644 --- a/Telegram/SourceFiles/iv/iv_instance.h +++ b/Telegram/SourceFiles/iv/iv_instance.h @@ -30,6 +30,9 @@ public: [[nodiscard]] bool hasActiveWindow( not_null session) const; + bool closeActive(); + bool minimizeActive(); + void closeAll(); [[nodiscard]] rpl::lifetime &lifetime(); diff --git a/Telegram/cmake/td_iv.cmake b/Telegram/cmake/td_iv.cmake index 64fe487ce..c15db5afc 100644 --- a/Telegram/cmake/td_iv.cmake +++ b/Telegram/cmake/td_iv.cmake @@ -20,6 +20,12 @@ PRIVATE iv/iv_prepare.h ) +nice_target_sources(td_iv ${res_loc} +PRIVATE + iv_html/page.css + iv_html/page.js +) + target_include_directories(td_iv PUBLIC ${src_loc} From f9299eee2aa4e527813f15b7e47533707f9d99e5 Mon Sep 17 00:00:00 2001 From: John Preston Date: Sat, 2 Dec 2023 22:43:16 +0400 Subject: [PATCH 016/240] Apply app color scheme, test dynamic header. --- Telegram/Resources/iv_html/page.css | 1049 +++++++++++---------- Telegram/Resources/iv_html/page.js | 16 +- Telegram/SourceFiles/iv/iv_controller.cpp | 192 +++- Telegram/SourceFiles/iv/iv_controller.h | 10 + Telegram/SourceFiles/iv/iv_prepare.cpp | 9 +- 5 files changed, 727 insertions(+), 549 deletions(-) diff --git a/Telegram/Resources/iv_html/page.css b/Telegram/Resources/iv_html/page.css index b5feac073..6f27a6e1c 100644 --- a/Telegram/Resources/iv_html/page.css +++ b/Telegram/Resources/iv_html/page.css @@ -1,871 +1,884 @@ body { - font-family: 'Helvetica Neue'; - font-size: 17px; - line-height: 25px; - padding: 0; - margin: 0; + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 25px; + padding: 0; + margin: 0; + background-color: var(--td-window-bg); + color: var(--td-window-fg); } + +html.custom_scroll ::-webkit-scrollbar { + border-radius: 5px !important; + border: 3px solid transparent !important; + background-color: var(--td-scroll-bg) !important; + background-clip: content-box !important; + width: 10px !important; +} +html.custom_scroll ::-webkit-scrollbar:hover { + background-color: var(--td-scroll-bg-over) !important; +} +html.custom_scroll ::-webkit-scrollbar-thumb { + border-radius: 5px !important; + border: 3px solid transparent !important; + background-color: var(--td-scroll-bar-bg) !important; + background-clip: content-box !important; +} +html.custom_scroll ::-webkit-scrollbar-thumb:hover { + background-color: var(--td-scroll-bar-bg-over) !important; +} + article { - padding-bottom: 12px; - overflow: hidden; - white-space: pre-wrap; - max-width: 732px; - margin: 0 auto; + padding-bottom: 12px; + overflow: hidden; + white-space: pre-wrap; + max-width: 732px; + margin: 0 auto; } article h1, article h2 { - font-family: 'Georgia'; - font-size: 28px; - line-height: 31px; - margin: 21px 18px 12px; - font-weight: normal; - min-height: 31px; + font-family: 'Georgia'; + font-size: 28px; + line-height: 31px; + margin: 21px 18px 12px; + font-weight: normal; + min-height: 31px; } article h2 { - font-size: 24px; - line-height: 30px; - margin: -6px 18px 12px; - color: #777; -} -article h6.kicker { - font-family: 'Helvetica Neue'; - font-size: 14px; - line-height: 17px; - margin: 21px 18px 12px; - font-weight: 500; - color: #79828B; -} -article h6.kicker + h1 { - margin-top: 12px; + font-size: 24px; + line-height: 30px; + margin: -6px 18px 12px; + color: var(--td-window-sub-text-fg); } article address { - font-size: 15px; - color: #79828B; - margin: 12px 18px 21px; - font-style: normal; + font-size: 15px; + color: var(--td-window-sub-text-fg); + margin: 12px 18px 21px; + font-style: normal; } article.rtl address { - direction: ltr; - text-align: right; + direction: ltr; + text-align: right; } article address figure { - width: 25px; - height: 25px; - float: right; - margin: 0 0 0 12px; - background: no-repeat center; - background-size: cover; - border-radius: 50%; + width: 25px; + height: 25px; + float: right; + margin: 0 0 0 12px; + background: no-repeat center; + background-size: cover; + border-radius: 50%; } article address a, article address a[href] { - color: #79828B; + color: var(--td-window-sub-text-fg); } article address a[href] { - text-decoration: underline; + text-decoration: underline; } article a[href] { - color: #007EE5; - text-decoration: none; + color: var(--td-window-active-text-fg); + text-decoration: none; } article span.reference { - border: dotted #ddd; - border-width: 1px 1px 1px 2px; - background: rgba(255, 255, 255, 0.7); - margin: 0 1px; - padding: 2px; - position: relative; + border: dotted var(--td-window-sub-text-fg); + border-width: 1px 1px 1px 2px; + background: rgba(255, 255, 255, 0.7); + margin: 0 1px; + padding: 2px; + position: relative; } article.rtl span.reference { - border-width: 1px 0 1px 1px; + border-width: 1px 0 1px 1px; } article code { - font-size: 0.94em; - background: #eee; - border-radius: 2px; - padding: 0 3px 1px; + font-size: 0.94em; + background: var(--td-box-divider-bg); + border-radius: 2px; + padding: 0 3px 1px; } article mark { - background: #fcf8e3; - border-radius: 2px; - padding: 0 3px 1px; + background: var(--td-window-bg-over); + color: var(--td-window-fg); + border-radius: 2px; + padding: 0 3px 1px; } article sup, article sub { - font-size: 0.75em; - line-height: 1; + font-size: 0.75em; + line-height: 1; } article p { - margin: 0 18px 12px; - word-wrap: break-word; + margin: 0 18px 12px; + word-wrap: break-word; } article ul p, article ol p { - margin: 0 0 6px; + margin: 0 0 6px; } article pre, article pre.hljs { - font-family: Menlo; - margin: 14px 0; - padding: 7px 18px; - background: #F5F8FC; - font-size: 16px; - white-space: pre-wrap; - word-wrap: break-word; - overflow-x: visible; - position: relative; + font-family: Menlo; + margin: 14px 0; + padding: 7px 18px; + background: #F5F8FC; + font-size: 16px; + white-space: pre-wrap; + word-wrap: break-word; + overflow-x: visible; + position: relative; } article ul pre, article ol pre, article ul pre.hljs, article ol pre.hljs { - margin: 6px 0 6px -18px; + margin: 6px 0 6px -18px; } article.rtl ul pre, article.rtl ol pre, article.rtl ul pre.hljs, article.rtl ol pre.hljs { - margin-right: -18px; - margin-left: 0; + margin-right: -18px; + margin-left: 0; } article pre + pre { - margin-top: -14px; + margin-top: -14px; } article h3, article h4 { - font-family: 'Georgia'; - font-size: 24px; - line-height: 30px; - margin: 18px 18px 9px; - font-weight: normal; + font-family: 'Georgia'; + font-size: 24px; + line-height: 30px; + margin: 18px 18px 9px; + font-weight: normal; } article h4 { - font-size: 19px; - margin: 18px 18px 7px; + font-size: 19px; + margin: 18px 18px 7px; } article ul h3, article ol h3 { - margin: 12px 0 7px; + margin: 12px 0 7px; } article ul h4, article ol h4 { - margin: 10px 0 5px; + margin: 10px 0 5px; } article blockquote { - font-family: 'Georgia'; - margin: 18px 18px 16px; - padding-left: 22px; - position: relative; - font-style: italic; - word-wrap: break-word; + font-family: 'Georgia'; + margin: 18px 18px 16px; + padding-left: 22px; + position: relative; + font-style: italic; + word-wrap: break-word; } article blockquote:before { - content: ''; - position: absolute; - left: 1px; - top: 3px; - bottom: 3px; - width: 3px; - background-color: #000; - border-radius: 3px; + content: ''; + position: absolute; + left: 1px; + top: 3px; + bottom: 3px; + width: 3px; + background-color: var(--td-window-bg-active); + border-radius: 3px; } article.rtl blockquote { - padding-right: 22px; - padding-left: 0; + padding-right: 22px; + padding-left: 0; } article.rtl blockquote:before { - right: 1px; - left: auto; + right: 1px; + left: auto; } article aside { - font-family: 'Georgia'; - margin: 18px 18px 16px; - padding: 0 18px; - text-align: center; - font-style: italic; + font-family: 'Georgia'; + margin: 18px 18px 16px; + padding: 0 18px; + text-align: center; + font-style: italic; } article ul blockquote, article ol blockquote, article ul aside, article ol aside { - margin: 12px 0 10px; + margin: 12px 0 10px; } article blockquote cite, article aside cite, article footer cite, article .iv-pullquote cite { - font-family: 'Helvetica Neue'; - font-size: 15px; - display: block; - color: #79828B; - line-height: 19px; - padding: 5px 0 2px; - font-style: normal; + font-family: 'Helvetica Neue'; + font-size: 15px; + display: block; + color: var(--td-window-sub-text-fg); + line-height: 19px; + padding: 5px 0 2px; + font-style: normal; } article hr { - width: 50%; - margin: 36px auto 26px; - padding: 2px 0 10px; - border: none; + width: 50%; + margin: 36px auto 26px; + padding: 2px 0 10px; + border: none; } article ul hr, article ol hr { - margin: 18px auto; + margin: 18px auto; } article hr:before { - content: ''; - display: block; - border-top: 1px solid #c9cdd1; - padding: 0 0 2px; + content: ''; + display: block; + border-top: 1px solid var(--td-window-sub-text-fg); + padding: 0 0 2px; } article footer hr { - margin: 18px auto 6px; + margin: 18px auto 6px; } article ul, article ol { - margin: 0 18px 12px; - padding-left: 18px; + margin: 0 18px 12px; + padding-left: 18px; } article.rtl ul, article.rtl ol { - padding-right: 18px; - padding-left: 0; + padding-right: 18px; + padding-left: 0; } /*article ul { - list-style: none; + list-style: none; }*/ article ul > li, article ol > li { - padding-left: 4px; + padding-left: 4px; } article.rtl ul > li, article.rtl ol > li { - padding-right: 4px; - padding-left: 0; + padding-right: 4px; + padding-left: 0; } /*article ul > li { - position: relative; + position: relative; } article ul > li:before { - content: '\2022'; - position: absolute; - display: block; - font-size: 163%; - left: -19px; - top: 1px; + content: '\2022'; + position: absolute; + display: block; + font-size: 163%; + left: -19px; + top: 1px; } article.rtl ul > li:before { - left: auto; - right: -19px; + left: auto; + right: -19px; }*/ article ul ul, article ul ol, article ol ul, article ol ol { - margin: 0 0 12px; + margin: 0 0 12px; } article table { - width: 100%; - border-collapse: collapse; + width: 100%; + border-collapse: collapse; } article table.bordered, article table.bordered td, article table.bordered th { - border: 1px solid #ddd; + border: 1px solid var(--td-box-divider-fg); } article table.striped tr:nth-child(odd) td { - background-color: #f7f7f7; + background-color: var(--td-box-divider-bg); } article table caption { - font-size: 15px; - line-height: 18px; - margin: 4px 0 7px; - text-align: left; - color: #79828B; + font-size: 15px; + line-height: 18px; + margin: 4px 0 7px; + text-align: left; + color: var(--td-window-sub-text-fg); } article.rtl table caption { - text-align: right; + text-align: right; } article td, article th { - font-size: 15px; - line-height: 21px; - padding: 6px 5px 5px; - background-color: #fff; - vertical-align: middle; - font-weight: normal; - text-align: left; + font-size: 15px; + line-height: 21px; + padding: 6px 5px 5px; + background-color: var(--td-window-bg); + vertical-align: middle; + font-weight: normal; + text-align: left; } article th { - background-color: #efefef; + background-color: var(--td-box-divider-bg); } article.rtl table td, article.rtl table th { - text-align: right; + text-align: right; } article details { - position: relative; - margin: 0 0 12px; - padding: 0 0 1px; + position: relative; + margin: 0 0 12px; + padding: 0 0 1px; } article details:before { - content: ''; - display: block; - border-bottom: 1px solid #c8c7cb; - position: absolute; - left: 18px; - right: 0; - bottom: 0; + content: ''; + display: block; + border-bottom: 1px solid var(--td-box-divider-fg); + position: absolute; + left: 18px; + right: 0; + bottom: 0; } article.rtl details:before { - right: 18px; - left: 0; + right: 18px; + left: 0; } article details + details { - margin-top: -12px; + margin-top: -12px; } article details > details:last-child { - margin-bottom: -1px; + margin-bottom: -1px; } article summary { - padding: 10px 18px 10px 42px; - line-height: 25px; - min-height: 25px; + padding: 10px 18px 10px 42px; + line-height: 25px; + min-height: 25px; } article.rtl summary { - padding-left: 18px; - padding-right: 42px; + padding-left: 18px; + padding-right: 42px; } article summary:hover { - cursor: pointer; + cursor: pointer; } article summary:focus { - outline: none; + outline: none; } article summary::-webkit-details-marker { - display: none; + display: none; } article summary::marker { - content: ''; + content: ''; } article summary:before { - content: ''; - background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAICAYAAADN5B7xAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAH1JREFUeNqEjUEKgCAQRSfrNi1bdZFadJjsMC46SSAIHqjB5mcFqdFfhD3eUyKZtb6ln92O2janmXdvrRu+ZTfAgasu1jAHU4qiHAwc/Ff4oCQKsxxZ0NT33XrxUTjkWvgiXFf3TWkU6Vt+XihH515yFiQRpfLnEMUw3yHAABZNTT9emBrvAAAAAElFTkSuQmCC'); - transition: all .2s ease; - display: inline-block; - position: absolute; - width: 12px; - height: 8px; - left: 18px; - top: 18px; + content: ''; + background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAICAYAAADN5B7xAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAH1JREFUeNqEjUEKgCAQRSfrNi1bdZFadJjsMC46SSAIHqjB5mcFqdFfhD3eUyKZtb6ln92O2janmXdvrRu+ZTfAgasu1jAHU4qiHAwc/Ff4oCQKsxxZ0NT33XrxUTjkWvgiXFf3TWkU6Vt+XihH515yFiQRpfLnEMUw3yHAABZNTT9emBrvAAAAAElFTkSuQmCC'); + transition: all .2s ease; + display: inline-block; + position: absolute; + width: 12px; + height: 8px; + left: 18px; + top: 18px; } article.rtl summary:before { - right: 18px; - left: auto; + right: 18px; + left: auto; } @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { - article summary:before { - background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAQCAYAAAAMJL+VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPxJREFUeNq8lEESgiAUhgFbZ0epSW28gB2pZbrrSukBHDWto1TrwHih45AiaDOxesLP9w1PBlzXNfrLSNPqkGWV8ysHGMBqv4mAlyFC7MRPk+T51Z0Lh73AAJZgIoRFUR/bEMb4TggJPG9TTIUzxmIuWHWzOCLfQQgwRiedRMBpIsObFvn+NgSTLEE2bCiKm6eDQ0bAkS2v4AjYuPvJcqtEu9DDshaB665zFZzSV6yCfyr5JplLTOA9wZiEg/a+72Qic9nxubMOPijQSZraCK4UjEiezSVYmsBHBSrJAEIJ1wr0knG4kUAt0cONBX2JGXzGi1uG7SNmOt4CDADc4r+K4txg+wAAAABJRU5ErkJggg=='); - background-size: 12px 8px; - } + article summary:before { + background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAQCAYAAAAMJL+VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPxJREFUeNq8lEESgiAUhgFbZ0epSW28gB2pZbrrSukBHDWto1TrwHih45AiaDOxesLP9w1PBlzXNfrLSNPqkGWV8ysHGMBqv4mAlyFC7MRPk+T51Z0Lh73AAJZgIoRFUR/bEMb4TggJPG9TTIUzxmIuWHWzOCLfQQgwRiedRMBpIsObFvn+NgSTLEE2bCiKm6eDQ0bAkS2v4AjYuPvJcqtEu9DDshaB665zFZzSV6yCfyr5JplLTOA9wZiEg/a+72Qic9nxubMOPijQSZraCK4UjEiezSVYmsBHBSrJAEIJ1wr0knG4kUAt0cONBX2JGXzGi1uG7SNmOt4CDADc4r+K4txg+wAAAABJRU5ErkJggg=='); + background-size: 12px 8px; + } } article details[open] > summary:before { - /*transform: rotateZ(-180deg);*/ - transform: scaleY(-1); + /*transform: rotateZ(-180deg);*/ + transform: scaleY(-1); } article li summary { - padding-left: 24px; + padding-left: 24px; } article li details:before, article li summary:before { - left: 0; + left: 0; } img, video, iframe { - max-width: 100%; - max-height: 400px; - vertical-align: top; + max-width: 100%; + max-height: 400px; + vertical-align: top; } video { - width: 100%; + width: 100%; } audio { - width: 100%; - width: calc(100% - 36px); - margin: 0 18px; - vertical-align: top; + width: 100%; + width: calc(100% - 36px); + margin: 0 18px; + vertical-align: top; } img { - font-size: 12px; - line-height: 14px; - color: #999; + font-size: 12px; + line-height: 14px; + color: var(--td-window-sub-text-fg); } img.pic { - max-height: none; - font-size: inherit; - vertical-align: middle; - position: relative; - top: -0.1em; + max-height: none; + font-size: inherit; + vertical-align: middle; + position: relative; + top: -0.1em; } img.pic.optional { - opacity: 0.4; + opacity: 0.4; } body:hover img.pic.optional { - opacity: 1; + opacity: 1; } iframe.autosize { - max-height: none; + max-height: none; } .iframe-wrap { - max-width: 100%; - vertical-align: top; - display: inline-block; - position: relative; + max-width: 100%; + vertical-align: top; + display: inline-block; + position: relative; } .iframe-wrap iframe { - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; } figure { - margin: 0 0 16px; - padding: 0; - text-align: center; - position: relative; + margin: 0 0 16px; + padding: 0; + text-align: center; + position: relative; } figure.nowide { - margin-left: 18px; - margin-right: 18px; + margin-left: 18px; + margin-right: 18px; } figure.nowide figcaption { - padding-left: 0; - padding-right: 0; + padding-left: 0; + padding-right: 0; } ul figure.nowide, ol figure.nowide { - margin: 0 0 12px; + margin: 0 0 12px; } figure > figure { - margin: 0; + margin: 0; } figcaption { - font-size: 15px; - color: #79828B; - padding: 6px 18px 0; - line-height: 19px; - text-align: left; + font-size: 15px; + color: var(--td-window-sub-text-fg); + padding: 6px 18px 0; + line-height: 19px; + text-align: left; } article.rtl figcaption { - text-align: right; + text-align: right; } ul figcaption, ol figcaption { - padding-left: 0; - padding-right: 0; + padding-left: 0; + padding-right: 0; } figcaption > cite { - font-family: 'Helvetica Neue'; - font-size: 12px; - display: block; - line-height: 15px; - padding: 2px 0 0; - font-style: normal; + font-family: 'Helvetica Neue'; + font-size: 12px; + display: block; + line-height: 15px; + padding: 2px 0 0; + font-style: normal; } footer { - margin: 12px 18px; - color: #79828B; + margin: 12px 18px; + color: var(--td-window-sub-text-fg); } figure.slideshow-wrap { - position: relative; + position: relative; } figure.slideshow { - position: relative; - white-space: nowrap; - width: 100%; - background: #000; - overflow: hidden; + position: relative; + white-space: nowrap; + width: 100%; + background: #000; + overflow: hidden; } figure.slideshow > figure { - position: static !important; - display: inline-block; - width: 100%; - vertical-align: middle; - transition: margin .3s; + position: static !important; + display: inline-block; + width: 100%; + vertical-align: middle; + transition: margin .3s; } figure.slideshow > figure figcaption { - box-sizing: border-box; - position: absolute; - bottom: 0; - width: 100%; - padding-bottom: 36px; + box-sizing: border-box; + position: absolute; + bottom: 0; + width: 100%; + padding-bottom: 36px; } figure.slideshow > figure figcaption:after { - content: ''; - display: block; - position: absolute; - left: 0; - right: 0; - bottom: 0; - top: -75px; - background: -moz-linear-gradient(top,rgba(64,64,64,0),rgba(64,64,64,.55)); - background: -webkit-gradient(linear,0 0,0 100%,from(rgba(64,64,64,0)),to(rgba(64,64,64,.55))); - background: -o-linear-gradient(rgba(64,64,64,0),rgba(64,64,64,.55)); - pointer-events: none; + content: ''; + display: block; + position: absolute; + left: 0; + right: 0; + bottom: 0; + top: -75px; + background: -moz-linear-gradient(top,rgba(64,64,64,0),rgba(64,64,64,.55)); + background: -webkit-gradient(linear,0 0,0 100%,from(rgba(64,64,64,0)),to(rgba(64,64,64,.55))); + background: -o-linear-gradient(rgba(64,64,64,0),rgba(64,64,64,.55)); + pointer-events: none; } figure.slideshow > figure figcaption > span, figure.slideshow > figure figcaption > cite { - position: relative; - color: #fff; - text-shadow: 0 1px rgba(0, 0, 0, .4); - z-index: 1; - display: block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + position: relative; + color: #fff; + text-shadow: 0 1px rgba(0, 0, 0, .4); + z-index: 1; + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } figure.slideshow > figure figcaption > span { - display: -webkit-box; - max-height: 3.8em; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - white-space: pre-wrap; + display: -webkit-box; + max-height: 3.8em; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + white-space: pre-wrap; } figure.slideshow > figure figcaption code { - text-shadow: none; - background: rgba(204, 204, 204, .7); - color: #fff; + text-shadow: none; + background: rgba(204, 204, 204, .7); + color: #fff; } figure.slideshow > figure figcaption mark { - text-shadow: none; - background: rgba(33, 123, 134, .7); - color: #fff; + text-shadow: none; + background: rgba(33, 123, 134, .7); + color: #fff; } figure.slideshow > figure figcaption a, figure.slideshow > figure figcaption a:hover { - color: #66baff; + color: #66baff; } .slideshow-buttons { - position: absolute; - width: 100%; - bottom: 10px; - white-space: nowrap; - overflow: hidden; - z-index: 3; + position: absolute; + width: 100%; + bottom: 10px; + white-space: nowrap; + overflow: hidden; + z-index: 3; } .slideshow-buttons > fieldset { - padding: 0 10px 20px; - margin: 0 0 -20px; - border: none; - line-height: 0; - overflow: hidden; - overflow-x: auto; - min-width: auto; + padding: 0 10px 20px; + margin: 0 0 -20px; + border: none; + line-height: 0; + overflow: hidden; + overflow-x: auto; + min-width: auto; } .slideshow-buttons label { - display: inline-block; - padding: 7px; - cursor: pointer; + display: inline-block; + padding: 7px; + cursor: pointer; } .slideshow-buttons input { - position: absolute; - left: -10000px; + position: absolute; + left: -10000px; } .slideshow-buttons label i { - display: inline-block; - background: #fff; - box-shadow: 0 0 3px rgba(0, 0, 0, .4); - border-radius: 3.5px; - width: 7px; - height: 7px; - opacity: .6; - transition: opacity .3s; + display: inline-block; + background: #fff; + box-shadow: 0 0 3px rgba(0, 0, 0, .4); + border-radius: 3.5px; + width: 7px; + height: 7px; + opacity: .6; + transition: opacity .3s; } .slideshow-buttons input:checked ~ i { - opacity: 1; + opacity: 1; } figure.collage { - margin: -2px 16px; - text-align: left; + margin: -2px 16px; + text-align: left; } figure.collage > figure { - display: inline-block; - vertical-align: top; - width: calc(25% - 4px); - margin: 2px; - box-sizing: border-box; + display: inline-block; + vertical-align: top; + width: calc(25% - 4px); + margin: 2px; + box-sizing: border-box; } figure.collage > figure > i { - background: no-repeat center; - background-size: cover; - display: inline-block; - vertical-align: top; - width: 100%; - padding-top: 100%; + background: no-repeat center; + background-size: cover; + display: inline-block; + vertical-align: top; + width: 100%; + padding-top: 100%; } figure.table-wrap { - overflow: auto; - -webkit-overflow-scrolling: touch; + overflow: auto; + -webkit-overflow-scrolling: touch; } figure.table { - display: table-cell; - padding: 0 18px; + display: table-cell; + padding: 0 18px; } article ol figure.table-wrap, article ul figure.table-wrap { - margin-top: 7px; + margin-top: 7px; } article ol figure.table, article ul figure.table { - padding: 0; + padding: 0; } figure blockquote.embed-post { - text-align: left; - margin-bottom: 0; + text-align: left; + margin-bottom: 0; } article.rtl figure blockquote.embed-post { - text-align: right; + text-align: right; } blockquote.embed-post address { - margin: 0; - padding: 5px 0 9px; - overflow: hidden; + margin: 0; + padding: 5px 0 9px; + overflow: hidden; } blockquote.embed-post address figure { - width: 50px; - height: 50px; - float: left; - margin: 0 12px 0 0; - background: no-repeat center; - background-size: cover; - border-radius: 50%; + width: 50px; + height: 50px; + float: left; + margin: 0 12px 0 0; + background: no-repeat center; + background-size: cover; + border-radius: 50%; } article.rtl blockquote.embed-post address figure { - float: right; - margin-left: 12px; - margin-right: 0; + float: right; + margin-left: 12px; + margin-right: 0; } blockquote.embed-post address a { - display: inline-block; - padding-top: 2px; - font-size: 17px; - font-weight: 600; - color: #000; + display: inline-block; + padding-top: 2px; + font-size: 17px; + font-weight: 600; + color: var(--td-window-fg); } blockquote.embed-post address time { - display: block; - line-height: 19px; + display: block; + line-height: 19px; } blockquote.embed-post p, blockquote.embed-post blockquote { - margin: 0 0 7px; - clear: left; + margin: 0 0 7px; + clear: left; } blockquote.embed-post figcaption { - padding-left: 0; - padding-right: 0; + padding-left: 0; + padding-right: 0; } blockquote.embed-post figure.collage { - margin-left: -2px; - margin-right: -2px; + margin-left: -2px; + margin-right: -2px; } blockquote.embed-post footer { - margin: 12px 0 0; - font-style: normal; + margin: 12px 0 0; + font-style: normal; } blockquote.embed-post footer hr { - display: none; + display: none; } section.embed-post { - display: block; - width: auto; - height: auto; - background: #f7f7f7; - margin: 0 18px 12px; - padding: 24px 18px; - text-align: center; + display: block; + width: auto; + height: auto; + background: var(--td-box-divider-bg); + margin: 0 18px 12px; + padding: 24px 18px; + text-align: center; } section.embed-post strong { - font-size: 21px; - font-weight: normal; - display: block; - color: #777; + font-size: 21px; + font-weight: normal; + display: block; + color: var(--td-window-sub-text-fg); } section.embed-post small { - display: block; - color: #777; + display: block; + color: var(--td-window-sub-text-fg); } section.related { - margin: 7px 0 12px; + margin: 7px 0 12px; } section.related h4 { - font-family: 'Helvetica Neue'; - font-size: 17px; - line-height: 26px; - font-weight: 500; - display: block; - padding: 7px 18px; - background: #f7f7f7; - margin: 0; - color: #000; + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 26px; + font-weight: 500; + display: block; + padding: 7px 18px; + background: var(--td-box-divider-bg); + margin: 0; + color: var(--td-window-fg); } section.related a.related-link { - display: block; - padding: 15px 18px 16px; - background: #fff; - position: relative; - overflow: hidden; + display: block; + padding: 15px 18px 16px; + background: var(--td-window-bg); + position: relative; + overflow: hidden; } section.related a.related-link:after { - content: ''; - display: block; - border-bottom: 1px solid #c8c7cb; - position: absolute; - left: 18px; - right: 0; - bottom: 0; + content: ''; + display: block; + border-bottom: 1px solid var(--td-box-divider-fg); + position: absolute; + left: 18px; + right: 0; + bottom: 0; } section.related .related-link-url { - display: block; - font-size: 15px; - line-height: 18px; - padding: 7px 0; - color: #999; - word-break: break-word; + display: block; + font-size: 15px; + line-height: 18px; + padding: 7px 0; + color: var(--td-window-sub-text-fg); + word-break: break-word; } section.related .related-link-thumb { - display: inline-block; - float: right; - width: 87px; - height: 87px; - border-radius: 4px; - background: no-repeat center; - background-size: cover; - margin-left: 15px; + display: inline-block; + float: right; + width: 87px; + height: 87px; + border-radius: 4px; + background: no-repeat center; + background-size: cover; + margin-left: 15px; } section.related .related-link-content { - display: block; - margin: -3px 0; + display: block; + margin: -3px 0; } section.related .related-link-title { - font-size: 15px; - font-weight: 500; - line-height: 18px; - display: block; - display: -webkit-box; - margin-bottom: 4px; - max-height: 36px; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; - overflow: hidden; - text-overflow: ellipsis; - white-space: pre-wrap; - color: #000; + font-size: 15px; + font-weight: 500; + line-height: 18px; + display: block; + display: -webkit-box; + margin-bottom: 4px; + max-height: 36px; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + white-space: pre-wrap; + color: var(--td-window-fg); } section.related .related-link-desc { - font-size: 14px; - line-height: 17px; - display: block; - display: -webkit-box; - max-height: 51px; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - overflow: hidden; - text-overflow: ellipsis; - white-space: pre-wrap; - color: #000; + font-size: 14px; + line-height: 17px; + display: block; + display: -webkit-box; + max-height: 51px; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + text-overflow: ellipsis; + white-space: pre-wrap; + color: var(--td-window-fg); } section.related .related-link-source { - font-size: 13px; - line-height: 17px; - display: block; - overflow: hidden; - margin-top: 4px; - text-overflow: ellipsis; - white-space: nowrap; - color: #818181; + font-size: 13px; + line-height: 17px; + display: block; + overflow: hidden; + margin-top: 4px; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--td-window-sub-text-fg); } section.message { - position: absolute; - display: table; - width: 100%; - height: 100%; + position: absolute; + display: table; + width: 100%; + height: 100%; } section.message.static { - position: static; - min-height: 200px; - height: 100vh; + position: static; + min-height: 200px; + height: 100vh; } section.message > aside { - display: table-cell; - vertical-align: middle; - text-align: center; - color: #999; - font-size: 24px; - pointer-events: none; + display: table-cell; + vertical-align: middle; + text-align: center; + color: var(--td-window-sub-text-fg); + font-size: 24px; + pointer-events: none; } section.message > aside > cite { - display: block; - font-size: 14px; - padding: 10px 0 0; - font-style: normal; - color: #ccc; + display: block; + font-size: 14px; + padding: 10px 0 0; + font-style: normal; + color: var(--td-window-sub-text-fg); } section.channel { - margin-top: -16px; - margin-bottom: -9px; + margin-top: -16px; + margin-bottom: -9px; } section.channel:first-child { - margin-top: 0; + margin-top: 0; } section.channel > a { - display: block; - padding: 7px 18px; - background: #f7f7f7; + display: block; + padding: 7px 18px; + background: var(--td-box-divider-bg); } section.channel > a:before { - content: 'Join'; - color: #3196e8; - font-weight: 500; - margin-left: 7px; - float: right; + content: var(--td-lng-group-call-join); + color: var(--td-window-active-text-fg); + font-weight: 500; + margin-left: 7px; + float: right; } section.channel > a > h4 { - font-family: 'Helvetica Neue'; - font-size: 17px; - line-height: 26px; - font-weight: 500; - margin: 0; - color: #000; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + font-family: 'Helvetica Neue'; + font-size: 17px; + line-height: 26px; + font-weight: 500; + margin: 0; + color: var(--td-window-fg); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; } .iv-pullquote { - text-align: center; - max-width: 420px; - font-size: 19px; - display: block; - margin: 0 auto; + text-align: center; + max-width: 420px; + font-size: 19px; + display: block; + margin: 0 auto; } .iv-photo-wrap { - width: 100%; - background-size: 100%; - margin: 0 auto; + width: 100%; + background-size: 100%; + margin: 0 auto; } .iv-photo { - background-size: 100%; + background-size: 100%; } diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index 8486e2cc7..b81a556b1 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -49,15 +49,13 @@ var IV = { }); } }, - postMessageHandler: function(event) { - if (event.source !== window.parent || - event.origin != window.parentOrigin) { - return; - } - try { - var data = JSON.parse(event.data); - } catch(e) { - var data = {}; + updateStyles: function (styles) { + if (IV.styles !== styles) { + console.log('Setting', styles); + IV.styles = styles; + document.getElementsByTagName('html')[0].style = styles; + } else { + console.log('Skipping', styles); } }, slideshowSlide: function(el, next) { diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index 709461eaa..b2e6e0582 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -8,13 +8,18 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "iv/iv_controller.h" #include "base/platform/base_platform_info.h" +#include "base/invoke_queued.h" #include "iv/iv_data.h" +#include "lang/lang_keys.h" #include "ui/widgets/rp_window.h" #include "webview/webview_data_stream_memory.h" #include "webview/webview_embed.h" #include "webview/webview_interface.h" #include "styles/palette.h" +#include "base/call_delayed.h" +#include "ui/effects/animations.h" + #include #include #include @@ -23,8 +28,99 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include namespace Iv { +namespace { -Controller::Controller() = default; +[[nodiscard]] QByteArray ComputeStyles() { + static const auto map = base::flat_map{ + { "scroll-bg", &st::scrollBg }, + { "scroll-bg-over", &st::scrollBgOver }, + { "scroll-bar-bg", &st::scrollBarBg }, + { "scroll-bar-bg-over", &st::scrollBarBgOver }, + { "window-bg", &st::windowBg }, + { "window-bg-over", &st::windowBgOver }, + { "window-bg-ripple", &st::windowBgRipple }, + { "window-fg", &st::windowFg }, + { "window-sub-text-fg", &st::windowSubTextFg }, + { "window-active-text-fg", &st::windowActiveTextFg }, + { "window-bg-active", &st::windowBgActive }, + { "box-divider-bg", &st::boxDividerBg }, + { "box-divider-fg", &st::boxDividerFg }, + }; + static const auto phrases = base::flat_map>{ + { "group-call-join", tr::lng_group_call_join }, + }; + static const auto serialize = [](const style::color *color) { + const auto qt = (*color)->c; + if (qt.alpha() == 255) { + return '#' + + QByteArray::number(qt.red(), 16).right(2) + + QByteArray::number(qt.green(), 16).right(2) + + QByteArray::number(qt.blue(), 16).right(2); + } + return "rgba(" + + QByteArray::number(qt.red()) + "," + + QByteArray::number(qt.green()) + "," + + QByteArray::number(qt.blue()) + "," + + QByteArray::number(qt.alpha() / 255.) + ")"; + }; + static const auto escape = [](tr::phrase<> phrase) { + const auto text = phrase(tr::now); + + auto result = QByteArray(); + for (auto i = 0; i != text.size(); ++i) { + uint ucs4 = text[i].unicode(); + if (QChar::isHighSurrogate(ucs4) && i + 1 != text.size()) { + ushort low = text[i + 1].unicode(); + if (QChar::isLowSurrogate(low)) { + ucs4 = QChar::surrogateToUcs4(ucs4, low); + ++i; + } + } + if (ucs4 == '\'' || ucs4 == '\"' || ucs4 == '\\') { + result.append('\\').append(char(ucs4)); + } else if (ucs4 < 32 || ucs4 > 127) { + result.append('\\' + QByteArray::number(ucs4, 16) + ' '); + } else { + result.append(char(ucs4)); + } + } + return result; + }; + auto result = QByteArray(); + for (const auto &[name, phrase] : phrases) { + result += "--td-lng-" + name + ":'" + escape(phrase) + "'; "; + } + for (const auto &[name, color] : map) { + result += "--td-" + name + ':' + serialize(color) + ';'; + } + return result; +} + +[[nodiscard]] QByteArray EscapeForAttribute(QByteArray value) { + return value + .replace('&', "&") + .replace('"', """) + .replace('\'', "'") + .replace('<', "<") + .replace('>', ">"); +} + +[[nodiscard]] QByteArray EscapeForScriptString(QByteArray value) { + return value + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\'', "\\\'"); +} + +} // namespace +Controller::Controller() +: _updateStyles([=] { + const auto str = EscapeForScriptString(ComputeStyles()); + if (_webview) { + _webview->eval("IV.updateStyles(\"" + str + "\");"); + } +}) { +} Controller::~Controller() { _webview = nullptr; @@ -32,21 +128,66 @@ Controller::~Controller() { } void Controller::show(const QString &dataPath, Prepared page) { + createWindow(); + InvokeQueued(_container, [=, page = std::move(page)]() mutable { + showInWindow(dataPath, std::move(page)); + }); +} + +void Controller::createWindow() { _window = std::make_unique(); const auto window = _window.get(); window->setGeometry({ 200, 200, 600, 800 }); - const auto container = Ui::CreateChild( - window->body().get()); - window->sizeValue() | rpl::start_with_next([=](QSize size) { - container->setGeometry(QRect(QPoint(), size)); - }, container->lifetime()); - container->show(); + const auto skip = window->lifetime().make_state>(0); + _container = Ui::CreateChild(window->body().get()); + rpl::combine( + window->body()->sizeValue(), + skip->value() + ) | rpl::start_with_next([=](QSize size, int skip) { + _container->setGeometry(QRect(QPoint(), size).marginsRemoved({ 0, skip, 0, 0 })); + }, _container->lifetime()); + + base::call_delayed(5000, window, [=] { + const auto animation = window->lifetime().make_state(); + animation->start([=] { + *skip = animation->value(64); + if (!animation->animating()) { + base::call_delayed(4000, window, [=] { + animation->start([=] { + *skip = animation->value(0); + }, 64, 0, 200, anim::easeOutCirc); + }); + } + }, 0, 64, 200, anim::easeOutCirc); + }); + + window->body()->paintRequest() | rpl::start_with_next([=](QRect clip) { + auto p = QPainter(window->body()); + p.fillRect(clip, st::windowBg); + p.fillRect(clip, QColor(0, 128, 0, 128)); + }, window->body()->lifetime()); + + _container->paintRequest() | rpl::start_with_next([=](QRect clip) { + QPainter(_container).fillRect(clip, st::windowBg); + }, _container->lifetime()); + + _container->show(); + window->show(); +} + +void Controller::showInWindow(const QString &dataPath, Prepared page) { + Expects(_container != nullptr); + + const auto window = _window.get(); _webview = std::make_unique( - container, - Webview::WindowConfig{ .userDataPath = dataPath }); + _container, + Webview::WindowConfig{ + .opaqueBg = st::windowBg->c, + .userDataPath = dataPath, + }); const auto raw = _webview.get(); window->lifetime().add([=] { @@ -69,14 +210,10 @@ void Controller::show(const QString &dataPath, Prepared page) { }, window->lifetime()); raw->widget()->show(); - container->geometryValue( - ) | rpl::start_with_next([=](QRect geometry) { - raw->widget()->setGeometry(geometry); - }, container->lifetime()); - - container->paintRequest() | rpl::start_with_next([=](QRect clip) { - QPainter(container).fillRect(clip, st::windowBg); - }, container->lifetime()); + _container->sizeValue( + ) | rpl::start_with_next([=](QSize size) { + raw->widget()->setGeometry(QRect(QPoint(), size)); + }, _container->lifetime()); raw->setNavigationStartHandler([=](const QString &uri, bool newWindow) { return true; @@ -113,12 +250,27 @@ void Controller::show(const QString &dataPath, Prepared page) { .stream = std::make_unique( std::move(data), std::move(mime)), - }); + }); return Webview::DataResult::Done; }; const auto id = std::string_view(request.id).substr(3); if (id == "page.html") { - return finishWith(page.html, "text/html"); + const auto i = page.html.indexOf("= 0); + const auto colored = page.html.mid(0, i + 5) + + " style=\"" + EscapeForAttribute(ComputeStyles()) + "\"" + + page.html.mid(i + 5); + if (!_subscribedToColors) { + _subscribedToColors = true; + + rpl::merge( + Lang::Updated(), + style::PaletteChanged() + ) | rpl::start_with_next([=] { + _updateStyles.call(); + }, _webview->lifetime()); + } + return finishWith(colored, "text/html"); } const auto css = id.ends_with(".css"); const auto js = !css && id.ends_with(".js"); @@ -140,8 +292,6 @@ void Controller::show(const QString &dataPath, Prepared page) { raw->init(R"( )"); raw->navigateToData("iv/page.html"); - - window->show(); } bool Controller::active() const { diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h index 7e623f7ce..5a081ca32 100644 --- a/Telegram/SourceFiles/iv/iv_controller.h +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -7,12 +7,15 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #pragma once +#include "base/invoke_queued.h" + namespace Webview { struct DataRequest; class Window; } // namespace Webview namespace Ui { +class RpWidget; class RpWindow; } // namespace Ui @@ -45,14 +48,21 @@ public: [[nodiscard]] rpl::lifetime &lifetime(); private: + void createWindow(); + void showInWindow(const QString &dataPath, Prepared page); + void escape(); void close(); void quit(); std::unique_ptr _window; + Ui::RpWidget *_container = nullptr; std::unique_ptr _webview; rpl::event_stream _dataRequests; rpl::event_stream _events; + SingleQueuedInvokation _updateStyles; + bool _subscribedToColors = false; + rpl::lifetime _lifetime; }; diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp index 69a86689c..dc93510c7 100644 --- a/Telegram/SourceFiles/iv/iv_prepare.cpp +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -12,6 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "iv/iv_data.h" #include "lang/lang_keys.h" #include "ui/image/image_prepare.h" +#include "styles/palette.h" #include @@ -1009,8 +1010,14 @@ QByteArray Parser::prepare(QByteArray body) { } QByteArray Parser::html(const QByteArray &head, const QByteArray &body) { +#ifdef Q_OS_MAC + const auto classAttribute = ""_q; +#else // Q_OS_MAC + const auto classAttribute = " class=\"custom_scroll\""_q; +#endif // Q_OS_MAC + return R"( - + From f508ad5e7583529dc3f941bbd52ec6563601f3d0 Mon Sep 17 00:00:00 2001 From: John Preston Date: Mon, 4 Dec 2023 15:48:17 +0400 Subject: [PATCH 017/240] Implement title and in-IV buttons. --- Telegram/Resources/iv_html/page.css | 94 ++++++++++++++++ Telegram/Resources/iv_html/page.js | 95 ++++++++++++++-- Telegram/SourceFiles/iv/iv.style | 100 +++++++++++++++++ Telegram/SourceFiles/iv/iv_controller.cpp | 126 +++++++++++++++++----- Telegram/SourceFiles/iv/iv_controller.h | 10 ++ Telegram/SourceFiles/iv/iv_data.cpp | 3 + Telegram/SourceFiles/iv/iv_data.h | 1 + Telegram/SourceFiles/iv/iv_prepare.cpp | 26 ++++- Telegram/SourceFiles/iv/iv_prepare.h | 1 + Telegram/cmake/td_iv.cmake | 1 + Telegram/cmake/td_ui.cmake | 1 + 11 files changed, 416 insertions(+), 42 deletions(-) create mode 100644 Telegram/SourceFiles/iv/iv.style diff --git a/Telegram/Resources/iv_html/page.css b/Telegram/Resources/iv_html/page.css index 6f27a6e1c..591fab69b 100644 --- a/Telegram/Resources/iv_html/page.css +++ b/Telegram/Resources/iv_html/page.css @@ -28,6 +28,100 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { background-color: var(--td-scroll-bar-bg-over) !important; } +.fixed_button { + position: fixed; + background-color: var(--td-history-to-down-bg); + border: none; + border-radius: 50%; + width: 32px; + height: 32px; + box-shadow: 0 0 4px -2px var(--td-history-to-down-shadow); + cursor: pointer; + outline: none; + z-index: 1000; + overflow: hidden; + user-select: none; + display: flex; + justify-content: center; + align-items: center; +} +.fixed_button:hover { + background-color: var(--td-history-to-down-bg-over); +} +.fixed_button svg { + fill: none; + position: relative; + z-index: 1; +} +.fixed_button .ripple .inner { + position: absolute; + border-radius: 50%; + transform: scale(0); + opacity: 1; + animation: ripple 650ms cubic-bezier(0.22, 1, 0.36, 1) forwards; + background-color: var(--td-history-to-down-bg-ripple); +} +.fixed_button .ripple.hiding { + animation: fadeOut 200ms linear forwards; +} +@keyframes ripple { + to { + transform: scale(2); + } +} +@keyframes fadeOut { + to { + opacity: 0; + } +} +#top_menu svg { + width: 16px; + height: 16px; +} +#top_menu circle { + fill: var(--td-history-to-down-fg); +} +#top_menu:hover circle { + fill: var(--td-history-to-down-fg-over); +} +#top_menu { + top: 10px; + right: 10px; +} +#top_back path, +#bottom_up path { + stroke: var(--td-history-to-down-fg); + stroke-width: 2; + stroke-linecap: round; + stroke-linejoin: round; +} +#top_back:hover path, +#bottom_up:hover path { + stroke: var(--td-history-to-down-fg-over); +} +#top_back { + top: 10px; + left: 10px; + transition: left 200ms linear; +} +#top_back svg { + transform: rotate(90deg); +} +#top_back.hidden { + left: -36px; +} +#bottom_up { + bottom: 10px; + right: 10px; + transition: bottom 200ms linear; +} +#bottom_up svg { + transform: rotate(180deg); +} +#bottom_up.hidden { + bottom: -36px; +} + article { padding-bottom: 12px; overflow: hidden; diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index b81a556b1..89aa8fc30 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -25,15 +25,15 @@ var IV = { e.preventDefault(); }, frameKeyDown: function (e) { - let keyW = (e.key === 'w') + const keyW = (e.key === 'w') || (e.code === 'KeyW') || (e.keyCode === 87); - let keyQ = (e.key === 'q') + const keyQ = (e.key === 'q') || (e.code === 'KeyQ') || (e.keyCode === 81); - let keyM = (e.key === 'm') - || (e.code === 'KeyM') - || (e.keyCode === 77); + const keyM = (e.key === 'm') + || (e.code === 'KeyM') + || (e.keyCode === 77); if ((e.metaKey || e.ctrlKey) && (keyW || keyQ || keyM)) { e.preventDefault(); IV.notify({ @@ -49,13 +49,26 @@ var IV = { }); } }, + frameMouseEnter: function (e) { + IV.notify({ event: 'mouseenter' }); + }, + frameMouseUp: function (e) { + IV.notify({ event: 'mouseup' }); + }, + lastScrollTop: 0, + frameScrolled: function (e) { + const now = document.documentElement.scrollTop; + if (now < 100) { + document.getElementById('bottom_up').classList.add('hidden'); + } else if (now > IV.lastScrollTop && now > 200) { + document.getElementById('bottom_up').classList.remove('hidden'); + } + IV.lastScrollTop = now; + }, updateStyles: function (styles) { if (IV.styles !== styles) { - console.log('Setting', styles); IV.styles = styles; document.getElementsByTagName('html')[0].style = styles; - } else { - console.log('Skipping', styles); } }, slideshowSlide: function(el, next) { @@ -72,7 +85,9 @@ var IV = { return false; }, initPreBlocks: function() { - if (!hljs) return; + if (!hljs) { + return; + } var pres = document.getElementsByTagName('pre'); for (var i = 0; i < pres.length; i++) { if (pres[i].hasAttribute('data-language')) { @@ -102,9 +117,71 @@ var IV = { }, false); })(iframes[i]); } + }, + addRipple: function (button, x, y) { + const ripple = document.createElement('span'); + ripple.classList.add('ripple'); + + const inner = document.createElement('span'); + inner.classList.add('inner'); + x -= button.offsetLeft; + y -= button.offsetTop; + + const mx = button.clientWidth - x; + const my = button.clientHeight - y; + const sq1 = x * x + y * y; + const sq2 = mx * mx + y * y; + const sq3 = x * x + my * my; + const sq4 = mx * mx + my * my; + const radius = Math.sqrt(Math.max(sq1, sq2, sq3, sq4)); + + inner.style.width = inner.style.height = `${2 * radius}px`; + inner.style.left = `${x - radius}px`; + inner.style.top = `${y - radius}px`; + inner.classList.add('inner'); + + ripple.addEventListener('animationend', function (e) { + if (e.animationName === 'fadeOut') { + ripple.remove(); + } + }); + + ripple.appendChild(inner); + button.appendChild(ripple); + }, + stopRipples: function (button) { + const ripples = button.getElementsByClassName('ripple'); + for (var i = 0; i < ripples.length; ++i) { + const ripple = ripples[i]; + if (!ripple.classList.contains('hiding')) { + ripple.classList.add('hiding'); + } + } + }, + init: function () { + const buttons = document.getElementsByClassName('fixed_button'); + for (let i = 0; i < buttons.length; ++i) { + const button = buttons[i]; + button.addEventListener('mousedown', function (e) { + IV.addRipple(e.currentTarget, e.clientX, e.clientY); + }); + button.addEventListener('mouseup', function (e) { + IV.stopRipples(e.currentTarget); + }); + button.addEventListener('mouseleave', function (e) { + IV.stopRipples(e.currentTarget); + }); + } + }, + toTop: function () { + document.getElementById('bottom_up').classList.add('hidden'); + window.scrollTo({ top: 0, behavior: 'smooth' }); } }; document.onclick = IV.frameClickHandler; document.onkeydown = IV.frameKeyDown; +document.onmouseenter = IV.frameMouseEnter; +document.onmouseup = IV.frameMouseUp; +document.onscroll = IV.frameScrolled; window.onmessage = IV.postMessageHandler; diff --git a/Telegram/SourceFiles/iv/iv.style b/Telegram/SourceFiles/iv/iv.style new file mode 100644 index 000000000..832916791 --- /dev/null +++ b/Telegram/SourceFiles/iv/iv.style @@ -0,0 +1,100 @@ +/* +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 +*/ +using "ui/basic.style"; +using "ui/widgets/widgets.style"; + +ivTitleHeight: 24px; +ivTitleIconShift: point(0px, 0px); +ivTitleButton: IconButton(windowTitleButton) { + height: ivTitleHeight; + iconPosition: ivTitleIconShift; +} +ivTitleButtonClose: IconButton(windowTitleButtonClose) { + height: ivTitleHeight; + iconPosition: ivTitleIconShift; +} + +ivTitleButtonSize: size(windowTitleButtonWidth, ivTitleHeight); +ivTitle: WindowTitle(defaultWindowTitle) { + height: ivTitleHeight; + style: TextStyle(defaultTextStyle) { + font: font(semibold 12px); + } + shadow: false; + minimize: IconButton(ivTitleButton) { + icon: icon { + { ivTitleButtonSize, titleButtonBg }, + { "title_button_minimize", titleButtonFg, ivTitleIconShift }, + }; + iconOver: icon { + { ivTitleButtonSize, titleButtonBgOver }, + { "title_button_minimize", titleButtonFgOver, ivTitleIconShift }, + }; + } + minimizeIconActive: icon { + { ivTitleButtonSize, titleButtonBgActive }, + { "title_button_minimize", titleButtonFgActive, ivTitleIconShift }, + }; + minimizeIconActiveOver: icon { + { ivTitleButtonSize, titleButtonBgActiveOver }, + { "title_button_minimize", titleButtonFgActiveOver, ivTitleIconShift }, + }; + maximize: IconButton(windowTitleButton) { + icon: icon { + { ivTitleButtonSize, titleButtonBg }, + { "title_button_maximize", titleButtonFg, ivTitleIconShift }, + }; + iconOver: icon { + { ivTitleButtonSize, titleButtonBgOver }, + { "title_button_maximize", titleButtonFgOver, ivTitleIconShift }, + }; + } + maximizeIconActive: icon { + { ivTitleButtonSize, titleButtonBgActive }, + { "title_button_maximize", titleButtonFgActive, ivTitleIconShift }, + }; + maximizeIconActiveOver: icon { + { ivTitleButtonSize, titleButtonBgActiveOver }, + { "title_button_maximize", titleButtonFgActiveOver, ivTitleIconShift }, + }; + restoreIcon: icon { + { ivTitleButtonSize, titleButtonBg }, + { "title_button_restore", titleButtonFg, ivTitleIconShift }, + }; + restoreIconOver: icon { + { ivTitleButtonSize, titleButtonBgOver }, + { "title_button_restore", titleButtonFgOver, ivTitleIconShift }, + }; + restoreIconActive: icon { + { ivTitleButtonSize, titleButtonBgActive }, + { "title_button_restore", titleButtonFgActive, ivTitleIconShift }, + }; + restoreIconActiveOver: icon { + { ivTitleButtonSize, titleButtonBgActiveOver }, + { "title_button_restore", titleButtonFgActiveOver, ivTitleIconShift }, + }; + close: IconButton(windowTitleButtonClose) { + icon: icon { + { ivTitleButtonSize, titleButtonCloseBg }, + { "title_button_close", titleButtonCloseFg, ivTitleIconShift }, + }; + iconOver: icon { + { ivTitleButtonSize, titleButtonCloseBgOver }, + { "title_button_close", titleButtonCloseFgOver, ivTitleIconShift }, + }; + } + closeIconActive: icon { + { ivTitleButtonSize, titleButtonCloseBgActive }, + { "title_button_close", titleButtonCloseFgActive, ivTitleIconShift }, + }; + closeIconActiveOver: icon { + { ivTitleButtonSize, titleButtonCloseBgActiveOver }, + { "title_button_close", titleButtonCloseFgActiveOver, ivTitleIconShift }, + }; +} +ivTitleExpandedHeight: 76px; diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index b2e6e0582..6a775466d 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -11,14 +11,16 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/invoke_queued.h" #include "iv/iv_data.h" #include "lang/lang_keys.h" +#include "ui/platform/ui_platform_window_title.h" #include "ui/widgets/rp_window.h" +#include "ui/painter.h" #include "webview/webview_data_stream_memory.h" #include "webview/webview_embed.h" #include "webview/webview_interface.h" #include "styles/palette.h" - -#include "base/call_delayed.h" -#include "ui/effects/animations.h" +#include "styles/style_iv.h" +#include "styles/style_widgets.h" +#include "styles/style_window.h" #include #include @@ -39,12 +41,23 @@ namespace { { "window-bg", &st::windowBg }, { "window-bg-over", &st::windowBgOver }, { "window-bg-ripple", &st::windowBgRipple }, + { "window-bg-active", &st::windowBgActive }, { "window-fg", &st::windowFg }, { "window-sub-text-fg", &st::windowSubTextFg }, { "window-active-text-fg", &st::windowActiveTextFg }, - { "window-bg-active", &st::windowBgActive }, + { "window-shadow-fg", &st::windowShadowFg }, { "box-divider-bg", &st::boxDividerBg }, { "box-divider-fg", &st::boxDividerFg }, + { "menu-icon-fg", &st::menuIconFg }, + { "menu-icon-fg-over", &st::menuIconFgOver }, + { "menu-bg", &st::menuBg }, + { "menu-bg-over", &st::menuBgOver }, + { "history-to-down-fg", &st::historyToDownFg }, + { "history-to-down-fg-over", &st::historyToDownFgOver }, + { "history-to-down-bg", &st::historyToDownBg }, + { "history-to-down-bg-over", &st::historyToDownBgOver }, + { "history-to-down-bg-ripple", &st::historyToDownBgRipple }, + { "history-to-down-shadow", &st::historyToDownShadow }, }; static const auto phrases = base::flat_map>{ { "group-call-join", tr::lng_group_call_join }, @@ -124,52 +137,103 @@ Controller::Controller() Controller::~Controller() { _webview = nullptr; + _title = nullptr; _window = nullptr; } void Controller::show(const QString &dataPath, Prepared page) { createWindow(); + _titleText.setText(st::ivTitle.style, page.title); InvokeQueued(_container, [=, page = std::move(page)]() mutable { showInWindow(dataPath, std::move(page)); }); } +void Controller::updateTitleGeometry() { + _title->setGeometry(0, 0, _window->width(), st::ivTitle.height); +} + +void Controller::paintTitle(Painter &p, QRect clip) { + const auto active = _window->isActiveWindow(); + const auto full = _title->width(); + p.setPen(active ? st::ivTitle.fgActive : st::ivTitle.fg); + const auto available = QRect( + _titleLeftSkip, + 0, + full - _titleLeftSkip - _titleRightSkip, + _title->height()); + const auto use = std::min(available.width(), _titleText.maxWidth()); + const auto center = full + - 2 * std::max(_titleLeftSkip, _titleRightSkip); + const auto left = (use <= center) + ? ((full - use) / 2) + : (use < available.width() && _titleLeftSkip < _titleRightSkip) + ? (available.x() + available.width() - use) + : available.x(); + const auto titleTextHeight = st::ivTitle.style.font->height; + const auto top = (st::ivTitle.height - titleTextHeight) / 2; + _titleText.drawLeftElided(p, left, top, available.width(), full); +} + void Controller::createWindow() { _window = std::make_unique(); + _window->setTitleStyle(st::ivTitle); const auto window = _window.get(); - window->setGeometry({ 200, 200, 600, 800 }); + _title = std::make_unique(window); + _title->setAttribute(Qt::WA_TransparentForMouseEvents); + _title->paintRequest() | rpl::start_with_next([=](QRect clip) { + auto p = Painter(_title.get()); + paintTitle(p, clip); + }, _title->lifetime()); + window->widthValue() | rpl::start_with_next([=] { + updateTitleGeometry(); + }, _title->lifetime()); - const auto skip = window->lifetime().make_state>(0); +#ifdef Q_OS_MAC + _titleLeftSkip = 8 + 12 + 8 + 12 + 8 + 12 + 8; + _titleRightSkip = st::ivTitle.style.font->spacew; +#else // Q_OS_MAC + using namespace Ui::Platform; + TitleControlsLayoutValue( + ) | rpl::start_with_next([=](TitleControls::Layout layout) { + const auto accumulate = [](const auto &list) { + auto result = 0; + for (const auto control : list) { + switch (control) { + case TitleControl::Close: + result += st::ivTitle.close.width; + break; + case TitleControl::Minimize: + result += st::ivTitle.minimize.width; + break; + case TitleControl::Maximize: + result += st::ivTitle.maximize.width; + break; + } + } + return result; + }; + const auto space = st::ivTitle.style.font->spacew; + _titleLeftSkip = accumulate(layout.left) + space; + _titleRightSkip = accumulate(layout.right) + space; + _title->update(); + }, _title->lifetime()); +#endif // Q_OS_MAC + + window->setGeometry({ 200, 200, 600, 800 }); + window->setMinimumSize({ st::windowMinWidth, st::windowMinHeight }); _container = Ui::CreateChild(window->body().get()); rpl::combine( window->body()->sizeValue(), - skip->value() - ) | rpl::start_with_next([=](QSize size, int skip) { - _container->setGeometry(QRect(QPoint(), size).marginsRemoved({ 0, skip, 0, 0 })); + _title->heightValue() + ) | rpl::start_with_next([=](QSize size, int title) { + title -= window->body()->y(); + _container->setGeometry(QRect(QPoint(), size).marginsRemoved( + { 0, title, 0, 0 })); }, _container->lifetime()); - base::call_delayed(5000, window, [=] { - const auto animation = window->lifetime().make_state(); - animation->start([=] { - *skip = animation->value(64); - if (!animation->animating()) { - base::call_delayed(4000, window, [=] { - animation->start([=] { - *skip = animation->value(0); - }, 64, 0, 200, anim::easeOutCirc); - }); - } - }, 0, 64, 200, anim::easeOutCirc); - }); - - window->body()->paintRequest() | rpl::start_with_next([=](QRect clip) { - auto p = QPainter(window->body()); - p.fillRect(clip, st::windowBg); - p.fillRect(clip, QColor(0, 128, 0, 128)); - }, window->body()->lifetime()); - _container->paintRequest() | rpl::start_with_next([=](QRect clip) { QPainter(_container).fillRect(clip, st::windowBg); }, _container->lifetime()); @@ -237,6 +301,10 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { } else if (key == u"q"_q && modifier == ctrl) { quit(); } + } else if (event == u"mouseenter"_q) { + window->overrideSystemButtonOver({}); + } else if (event == u"mouseup"_q) { + window->overrideSystemButtonDown({}); } }); }); diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h index 5a081ca32..1170974e1 100644 --- a/Telegram/SourceFiles/iv/iv_controller.h +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -8,6 +8,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #pragma once #include "base/invoke_queued.h" +#include "ui/effects/animations.h" +#include "ui/text/text.h" + +class Painter; namespace Webview { struct DataRequest; @@ -49,6 +53,8 @@ public: private: void createWindow(); + void updateTitleGeometry(); + void paintTitle(Painter &p, QRect clip); void showInWindow(const QString &dataPath, Prepared page); void escape(); @@ -56,6 +62,10 @@ private: void quit(); std::unique_ptr _window; + std::unique_ptr _title; + Ui::Text::String _titleText; + int _titleLeftSkip = 0; + int _titleRightSkip = 0; Ui::RpWidget *_container = nullptr; std::unique_ptr _webview; rpl::event_stream _dataRequests; diff --git a/Telegram/SourceFiles/iv/iv_data.cpp b/Telegram/SourceFiles/iv/iv_data.cpp index c34424e27..962d4fe23 100644 --- a/Telegram/SourceFiles/iv/iv_data.cpp +++ b/Telegram/SourceFiles/iv/iv_data.cpp @@ -45,6 +45,9 @@ Data::Data(const MTPDwebPage &webpage, const MTPPage &page) .webpageDocument = (webpage.vdocument() ? *webpage.vdocument() : std::optional()), + .title = (webpage.vtitle() + ? qs(*webpage.vtitle()) + : qs(webpage.vauthor().value_or_empty())) })) { } diff --git a/Telegram/SourceFiles/iv/iv_data.h b/Telegram/SourceFiles/iv/iv_data.h index 1eec747ef..3c2d04980 100644 --- a/Telegram/SourceFiles/iv/iv_data.h +++ b/Telegram/SourceFiles/iv/iv_data.h @@ -16,6 +16,7 @@ struct Options { }; struct Prepared { + QString title; QByteArray html; std::vector resources; base::flat_map embeds; diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp index dc93510c7..a1b8749ef 100644 --- a/Telegram/SourceFiles/iv/iv_prepare.cpp +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -172,6 +172,7 @@ Parser::Parser(const Source &source, const Options &options) : _options(options) , _rtl(source.page.data().is_rtl()) { process(source); + _result.title = source.title; _result.html = prepare(page(source.page.data())); } @@ -1003,9 +1004,7 @@ QByteArray Parser::prepare(QByteArray body) { if (_hasEmbeds) { js += "IV.initEmbedBlocks();"; } - if (!js.isEmpty()) { - body += tag("script", js); - } + body += tag("script", js + "IV.init();"); return html(head, body); } @@ -1026,7 +1025,26 @@ QByteArray Parser::html(const QByteArray &head, const QByteArray &body) { )"_q + head + R"( - )"_q + body + R"( + + + + +)"_q + body + R"( + )"_q; } diff --git a/Telegram/SourceFiles/iv/iv_prepare.h b/Telegram/SourceFiles/iv/iv_prepare.h index f5971d607..06cb0d87c 100644 --- a/Telegram/SourceFiles/iv/iv_prepare.h +++ b/Telegram/SourceFiles/iv/iv_prepare.h @@ -16,6 +16,7 @@ struct Source { MTPPage page; std::optional webpagePhoto; std::optional webpageDocument; + QString title; }; [[nodiscard]] Prepared Prepare( diff --git a/Telegram/cmake/td_iv.cmake b/Telegram/cmake/td_iv.cmake index c15db5afc..1ef5a9604 100644 --- a/Telegram/cmake/td_iv.cmake +++ b/Telegram/cmake/td_iv.cmake @@ -38,4 +38,5 @@ PUBLIC PRIVATE desktop-app::lib_webview tdesktop::td_lang + tdesktop::td_ui ) diff --git a/Telegram/cmake/td_ui.cmake b/Telegram/cmake/td_ui.cmake index 817f3c9ab..7aa713ec0 100644 --- a/Telegram/cmake/td_ui.cmake +++ b/Telegram/cmake/td_ui.cmake @@ -26,6 +26,7 @@ set(style_files info/boosts/giveaway/giveaway.style info/userpic/info_userpic_builder.style intro/intro.style + iv/iv.style media/player/media_player.style passport/passport.style payments/ui/payments.style From 51d5b7bab6a0978b2d45cad7bdb34f3e032e3b32 Mon Sep 17 00:00:00 2001 From: John Preston Date: Mon, 4 Dec 2023 23:06:44 +0400 Subject: [PATCH 018/240] Support channel link / channel join. --- Telegram/Resources/iv_html/page.css | 62 ++++-- Telegram/Resources/iv_html/page.js | 67 +++++-- Telegram/SourceFiles/data/data_session.cpp | 28 +++ .../view/media/history_view_web_page.cpp | 56 ++++-- Telegram/SourceFiles/iv/iv_controller.cpp | 187 +++++++++++++++--- Telegram/SourceFiles/iv/iv_controller.h | 33 +++- Telegram/SourceFiles/iv/iv_data.h | 6 +- Telegram/SourceFiles/iv/iv_instance.cpp | 124 +++++++++++- Telegram/SourceFiles/iv/iv_instance.h | 5 + Telegram/SourceFiles/iv/iv_prepare.cpp | 129 +++--------- .../window/window_session_controller.cpp | 2 + .../window_session_controller_link_info.h | 1 + 12 files changed, 520 insertions(+), 180 deletions(-) diff --git a/Telegram/Resources/iv_html/page.css b/Telegram/Resources/iv_html/page.css index 591fab69b..f9b086a4d 100644 --- a/Telegram/Resources/iv_html/page.css +++ b/Telegram/Resources/iv_html/page.css @@ -35,7 +35,7 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { border-radius: 50%; width: 32px; height: 32px; - box-shadow: 0 0 4px -2px var(--td-history-to-down-shadow); + box-shadow: 0 0 3px 0px var(--td-history-to-down-shadow); cursor: pointer; outline: none; z-index: 1000; @@ -44,6 +44,7 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { display: flex; justify-content: center; align-items: center; + padding: 0px; } .fixed_button:hover { background-color: var(--td-history-to-down-bg-over); @@ -52,6 +53,8 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { fill: none; position: relative; z-index: 1; + width: 24px; + height: 24px; } .fixed_button .ripple .inner { position: absolute; @@ -74,9 +77,10 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { opacity: 0; } } -#top_menu svg { - width: 16px; - height: 16px; +@keyframes fadeIn { + to { + opacity: 1; + } } #top_menu circle { fill: var(--td-history-to-down-fg); @@ -89,13 +93,21 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { right: 10px; } #top_back path, +#top_back line, #bottom_up path { stroke: var(--td-history-to-down-fg); - stroke-width: 2; +} +#top_back path, +#top_back line { + stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; } +#bottom_up path { + stroke-width: 1.4; +} #top_back:hover path, +#top_back:hover line, #bottom_up:hover path { stroke: var(--td-history-to-down-fg-over); } @@ -104,9 +116,6 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { left: 10px; transition: left 200ms linear; } -#top_back svg { - transform: rotate(90deg); -} #top_back.hidden { left: -36px; } @@ -115,9 +124,6 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { right: 10px; transition: bottom 200ms linear; } -#bottom_up svg { - transform: rotate(180deg); -} #bottom_up.hidden { bottom: -36px; } @@ -939,16 +945,23 @@ section.channel:first-child { } section.channel > a { display: block; - padding: 7px 18px; background: var(--td-box-divider-bg); } -section.channel > a:before { - content: var(--td-lng-group-call-join); +section.channel > a > div.join { color: var(--td-window-active-text-fg); font-weight: 500; - margin-left: 7px; + padding: 7px 18px; float: right; } +section.channel.joined > a > div.join { + display: none; +} +section.channel > a > div.join:hover { + text-decoration: underline; +} +section.channel > a > div.join span:before { + content: var(--td-lng-group-call-join); +} section.channel > a > h4 { font-family: 'Helvetica Neue'; font-size: 17px; @@ -959,6 +972,7 @@ section.channel > a > h4 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + padding: 7px 18px; } .iv-pullquote { @@ -976,3 +990,21 @@ section.channel > a > h4 { .iv-photo { background-size: 100%; } + +.toast { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background-color: var(--td-toast-bg); + color: var(--td-toast-fg); + padding: 10px 20px; + border-radius: 6px; + z-index: 9999; + opacity: 0; + animation: fadeIn 200ms linear forwards; +} +.toast.hiding { + opacity: 1; + animation: fadeOut 1000ms linear forwards; +} diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index 89aa8fc30..3f986998c 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -5,22 +5,36 @@ var IV = { } }, frameClickHandler: function(e) { - var target = e.target, href; - do { - if (target.tagName == 'SUMMARY') return; - if (target.tagName == 'DETAILS') return; - if (target.tagName == 'LABEL') return; - if (target.tagName == 'AUDIO') return; - if (target.tagName == 'A') break; - } while (target = target.parentNode); - if (target && target.hasAttribute('href')) { - var base_loc = document.createElement('A'); - base_loc.href = window.currentUrl; - if (base_loc.origin != target.origin || - base_loc.pathname != target.pathname || - base_loc.search != target.search) { - IV.notify({ event: 'link_click', url: target.href }); + var target = e.target; + var context = ''; + console.log('click', target); + while (target) { + if (target.tagName == 'AUDIO' || target.tagName == 'VIDEO') { + return; } + if (context === '' + && target.hasAttribute + && target.hasAttribute('data-context')) { + context = String(target.getAttribute('data-context')); + } + if (target.tagName == 'A') { + break; + } + target = target.parentNode; + } + if (!target || !target.hasAttribute('href')) { + return; + } + var base_loc = document.createElement('A'); + base_loc.href = window.currentUrl; + if (base_loc.origin != target.origin + || base_loc.pathname != target.pathname + || base_loc.search != target.search) { + IV.notify({ + event: 'link_click', + url: target.href, + context: context, + }); } e.preventDefault(); }, @@ -71,6 +85,16 @@ var IV = { document.getElementsByTagName('html')[0].style = styles; } }, + toggleChannelJoined: function (id, joined) { + const channels = document.getElementsByClassName('channel'); + const full = 'channel' + id; + for (var i = 0; i < channels.length; ++i) { + const channel = channels[i]; + if (String(channel.getAttribute('data-context')) === full) { + channel.classList.toggle('joined', joined); + } + } + }, slideshowSlide: function(el, next) { var dir = window.getComputedStyle(el, null).direction || 'ltr'; var marginProp = dir == 'rtl' ? 'marginRight' : 'marginLeft'; @@ -172,6 +196,19 @@ var IV = { IV.stopRipples(e.currentTarget); }); } + IV.notify({ event: 'ready' }); + }, + showTooltip: function (text) { + var toast = document.createElement('div'); + toast.classList.add('toast'); + toast.textContent = text; + document.body.appendChild(toast); + setTimeout(function () { + toast.classList.add('hiding'); + }, 2000); + setTimeout(function () { + document.body.removeChild(toast); + }, 3000); }, toTop: function () { document.getElementById('bottom_up').classList.add('hidden'); diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index d0d3d8555..b5376fab2 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -3515,6 +3515,34 @@ void Session::webpageApplyFields( for (const auto &document : page->data().vdocuments().v) { processDocument(document); } + const auto process = [&]( + const MTPPageBlock &block, + const auto &self) -> void { + block.match([&](const MTPDpageBlockChannel &data) { + processChat(data.vchannel()); + }, [&](const MTPDpageBlockCover &data) { + self(data.vcover(), self); + }, [&](const MTPDpageBlockEmbedPost &data) { + for (const auto &block : data.vblocks().v) { + self(block, self); + } + }, [&](const MTPDpageBlockCollage &data) { + for (const auto &block : data.vitems().v) { + self(block, self); + } + }, [&](const MTPDpageBlockSlideshow &data) { + for (const auto &block : data.vitems().v) { + self(block, self); + } + }, [&](const MTPDpageBlockDetails &data) { + for (const auto &block : data.vblocks().v) { + self(block, self); + } + }, [](const auto &) {}); + }; + for (const auto &block : page->data().vblocks().v) { + process(block, process); + } } webpageApplyFields( page, diff --git a/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp b/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp index 5b46381fb..bab288d4f 100644 --- a/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp +++ b/Telegram/SourceFiles/history/view/media/history_view_web_page.cpp @@ -86,17 +86,47 @@ constexpr auto kMaxOriginalEntryLines = 8192; return result; } -[[nodiscard]] ClickHandlerPtr IvClickHandler(not_null webpage) { +[[nodiscard]] QString ExtractHash( + not_null webpage, + const TextWithEntities &text) { + const auto simplify = [](const QString &url) { + auto result = url.split('#')[0].toLower(); + if (result.endsWith('/')) { + result.chop(1); + } + const auto prefixes = { u"http://"_q, u"https://"_q }; + for (const auto &prefix : prefixes) { + if (result.startsWith(prefix)) { + result = result.mid(prefix.size()); + break; + } + } + return result; + }; + const auto simplified = simplify(webpage->url); + for (const auto &entity : text.entities) { + const auto link = (entity.type() == EntityType::Url) + ? text.text.mid(entity.offset(), entity.length()) + : (entity.type() == EntityType::CustomUrl) + ? entity.data() + : QString(); + if (simplify(link) == simplified) { + const auto i = link.indexOf('#'); + return (i > 0) ? link.mid(i + 1) : QString(); + } + } + return QString(); +} + +[[nodiscard]] ClickHandlerPtr IvClickHandler( + not_null webpage, + const TextWithEntities &text) { return std::make_shared([=](ClickContext context) { const auto my = context.other.value(); if (const auto controller = my.sessionWindow.get()) { if (const auto iv = webpage->iv.get()) { -#ifdef _DEBUG - const auto local = base::IsCtrlPressed(); -#else // _DEBUG - const auto local = false; -#endif // _DEBUG - Core::App().iv().show(controller->uiShow(), iv, local); + const auto hash = ExtractHash(webpage, text); + Core::App().iv().show(controller->uiShow(), iv, hash); return; } else { HiddenUrlClickHandler::Open(webpage->url, context.other); @@ -235,6 +265,7 @@ QSize WebPage::countOptimalSize() { const auto lineHeight = UnitedLineHeight(); if (!_openl && (!_data->url.isEmpty() || _sponsoredData)) { + const auto original = _parent->data()->originalText(); const auto previewOfHiddenUrl = [&] { if (_data->type == WebPageType::BotApp) { // Bot Web Apps always show confirmation on hidden urls. @@ -258,12 +289,11 @@ QSize WebPage::countOptimalSize() { return result; }; const auto simplified = simplify(_data->url); - const auto full = _parent->data()->originalText(); - for (const auto &entity : full.entities) { + for (const auto &entity : original.entities) { if (entity.type() != EntityType::Url) { continue; } - const auto link = full.text.mid( + const auto link = original.text.mid( entity.offset(), entity.length()); if (simplify(link) == simplified) { @@ -272,8 +302,10 @@ QSize WebPage::countOptimalSize() { } return true; }(); - _openl = _data->iv ? IvClickHandler(_data) : (previewOfHiddenUrl - || UrlClickHandler::IsSuspicious(_data->url)) + _openl = _data->iv + ? IvClickHandler(_data, original) + : (previewOfHiddenUrl || UrlClickHandler::IsSuspicious( + _data->url)) ? std::make_shared(_data->url) : std::make_shared(_data->url, true); if (_data->document diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index 6a775466d..592cd3be9 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -58,6 +58,8 @@ namespace { { "history-to-down-bg-over", &st::historyToDownBgOver }, { "history-to-down-bg-ripple", &st::historyToDownBgRipple }, { "history-to-down-shadow", &st::historyToDownShadow }, + { "toast-bg", &st::toastBg }, + { "toast-fg", &st::toastFg }, }; static const auto phrases = base::flat_map>{ { "group-call-join", tr::lng_group_call_join }, @@ -125,30 +127,125 @@ namespace { .replace('\'', "\\\'"); } +[[nodiscard]] QByteArray WrapPage( + const Prepared &page, + const QByteArray &initScript) { +#ifdef Q_OS_MAC + const auto classAttribute = ""_q; +#else // Q_OS_MAC + const auto classAttribute = " class=\"custom_scroll\""_q; +#endif // Q_OS_MAC + + const auto js = QByteArray() + + (page.hasCode ? "IV.initPreBlocks();" : "") + + (page.hasEmbeds ? "IV.initEmbedBlocks();" : "") + + "IV.init();" + + initScript; + + const auto contentAttributes = page.rtl + ? " dir=\"rtl\" class=\"rtl\""_q + : QByteArray(); + + return R"( + + + + + + + + + + + + + + + "_q + page.content + R"( + + + +)"_q; +} + } // namespace + Controller::Controller() : _updateStyles([=] { const auto str = EscapeForScriptString(ComputeStyles()); if (_webview) { - _webview->eval("IV.updateStyles(\"" + str + "\");"); + _webview->eval("IV.updateStyles('" + str + "');"); } }) { } Controller::~Controller() { + _ready = false; _webview = nullptr; _title = nullptr; _window = nullptr; } -void Controller::show(const QString &dataPath, Prepared page) { +void Controller::show( + const QString &dataPath, + Prepared page, + base::flat_map> inChannelValues) { createWindow(); + const auto js = fillInChannelValuesScript(std::move(inChannelValues)); + _titleText.setText(st::ivTitle.style, page.title); InvokeQueued(_container, [=, page = std::move(page)]() mutable { - showInWindow(dataPath, std::move(page)); + showInWindow(dataPath, std::move(page), js); + if (!_webview) { + return; + } }); } +QByteArray Controller::fillInChannelValuesScript( + base::flat_map> inChannelValues) { + auto result = QByteArray(); + for (auto &[id, in] : inChannelValues) { + std::move(in) | rpl::start_with_next([=](bool in) { + if (_ready) { + _webview->eval(toggleInChannelScript(id, in)); + } else { + _inChannelChanged[id] = in; + } + }, _lifetime); + } + for (const auto &[id, in] : base::take(_inChannelChanged)) { + result += toggleInChannelScript(id, in); + } + return result; +} + +QByteArray Controller::toggleInChannelScript( + const QByteArray &id, + bool in) const { + const auto value = in ? "true" : "false"; + return "IV.toggleChannelJoined('" + id + "', " + value + ");"; +} + void Controller::updateTitleGeometry() { _title->setGeometry(0, 0, _window->width(), st::ivTitle.height); } @@ -242,7 +339,10 @@ void Controller::createWindow() { window->show(); } -void Controller::showInWindow(const QString &dataPath, Prepared page) { +void Controller::showInWindow( + const QString &dataPath, + Prepared page, + const QByteArray &initScript) { Expects(_container != nullptr); const auto window = _window.get(); @@ -255,10 +355,11 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { const auto raw = _webview.get(); window->lifetime().add([=] { + _ready = false; _webview = nullptr; }); if (!raw->widget()) { - _events.fire(Event::Close); + _events.fire({ Event::Type::Close }); return; } window->events( @@ -291,20 +392,24 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { if (event == u"keydown"_q) { const auto key = object.value("key").toString(); const auto modifier = object.value("modifier").toString(); - const auto ctrl = Platform::IsMac() ? u"cmd"_q : u"ctrl"_q; - if (key == u"escape"_q) { - escape(); - } else if (key == u"w"_q && modifier == ctrl) { - close(); - } else if (key == u"m"_q && modifier == ctrl) { - minimize(); - } else if (key == u"q"_q && modifier == ctrl) { - quit(); - } + processKey(key, modifier); } else if (event == u"mouseenter"_q) { window->overrideSystemButtonOver({}); } else if (event == u"mouseup"_q) { window->overrideSystemButtonDown({}); + } else if (event == u"link_click"_q) { + const auto url = object.value("url").toString(); + const auto context = object.value("context").toString(); + processLink(url, context); + } else if (event == u"ready"_q) { + _ready = true; + auto script = QByteArray(); + for (const auto &[id, in] : base::take(_inChannelChanged)) { + script += toggleInChannelScript(id, in); + } + if (!script.isEmpty()) { + _webview->eval(script); + } } }); }); @@ -323,11 +428,6 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { }; const auto id = std::string_view(request.id).substr(3); if (id == "page.html") { - const auto i = page.html.indexOf("= 0); - const auto colored = page.html.mid(0, i + 5) - + " style=\"" + EscapeForAttribute(ComputeStyles()) + "\"" - + page.html.mid(i + 5); if (!_subscribedToColors) { _subscribedToColors = true; @@ -338,7 +438,7 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { _updateStyles.call(); }, _webview->lifetime()); } - return finishWith(colored, "text/html"); + return finishWith(WrapPage(page, initScript), "text/html"); } const auto css = id.ends_with(".css"); const auto js = !css && id.ends_with(".js"); @@ -357,15 +457,52 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { return Webview::DataResult::Failed; }); - raw->init(R"( -)"); + raw->init(R"()"); raw->navigateToData("iv/page.html"); } +void Controller::processKey(const QString &key, const QString &modifier) { + const auto ctrl = Platform::IsMac() ? u"cmd"_q : u"ctrl"_q; + if (key == u"escape"_q) { + escape(); + } else if (key == u"w"_q && modifier == ctrl) { + close(); + } else if (key == u"m"_q && modifier == ctrl) { + minimize(); + } else if (key == u"q"_q && modifier == ctrl) { + quit(); + } +} + +void Controller::processLink(const QString &url, const QString &context) { + const auto channelPrefix = u"channel"_q; + const auto joinPrefix = u"join_link"_q; + if (context.startsWith(channelPrefix)) { + _events.fire({ + Event::Type::OpenChannel, + context.mid(channelPrefix.size()), + }); + } else if (context.startsWith(joinPrefix)) { + _events.fire({ + Event::Type::JoinChannel, + context.mid(joinPrefix.size()), + }); + } +} + bool Controller::active() const { return _window && _window->isActiveWindow(); } +void Controller::showJoinedTooltip() { + if (_webview) { + _webview->eval("IV.showTooltip('" + + EscapeForScriptString( + tr::lng_action_you_joined(tr::now).toUtf8()) + + "');"); + } +} + void Controller::minimize() { if (_window) { _window->setWindowState(_window->windowState() @@ -378,11 +515,11 @@ void Controller::escape() { } void Controller::close() { - _events.fire(Event::Close); + _events.fire({ Event::Type::Close }); } void Controller::quit() { - _events.fire(Event::Quit); + _events.fire({ Event::Type::Quit }); } rpl::lifetime &Controller::lifetime() { diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h index 1170974e1..5b565d285 100644 --- a/Telegram/SourceFiles/iv/iv_controller.h +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -32,13 +32,23 @@ public: Controller(); ~Controller(); - enum class Event { - Close, - Quit, + struct Event { + enum class Type { + Close, + Quit, + OpenChannel, + JoinChannel, + }; + Type type = Type::Close; + QString context; }; - void show(const QString &dataPath, Prepared page); + void show( + const QString &dataPath, + Prepared page, + base::flat_map> inChannelValues); [[nodiscard]] bool active() const; + void showJoinedTooltip(); void minimize(); [[nodiscard]] rpl::producer dataRequests() const { @@ -55,7 +65,18 @@ private: void createWindow(); void updateTitleGeometry(); void paintTitle(Painter &p, QRect clip); - void showInWindow(const QString &dataPath, Prepared page); + void showInWindow( + const QString &dataPath, + Prepared page, + const QByteArray &initScript); + [[nodiscard]] QByteArray fillInChannelValuesScript( + base::flat_map> inChannelValues); + [[nodiscard]] QByteArray toggleInChannelScript( + const QByteArray &id, + bool in) const; + + void processKey(const QString &key, const QString &modifier); + void processLink(const QString &url, const QString &context); void escape(); void close(); @@ -70,8 +91,10 @@ private: std::unique_ptr _webview; rpl::event_stream _dataRequests; rpl::event_stream _events; + base::flat_map _inChannelChanged; SingleQueuedInvokation _updateStyles; bool _subscribedToColors = false; + bool _ready = false; rpl::lifetime _lifetime; diff --git a/Telegram/SourceFiles/iv/iv_data.h b/Telegram/SourceFiles/iv/iv_data.h index 3c2d04980..97acdd753 100644 --- a/Telegram/SourceFiles/iv/iv_data.h +++ b/Telegram/SourceFiles/iv/iv_data.h @@ -17,9 +17,13 @@ struct Options { struct Prepared { QString title; - QByteArray html; + QByteArray content; std::vector resources; base::flat_map embeds; + base::flat_set channelIds; + bool rtl = false; + bool hasCode = false; + bool hasEmbeds = false; }; struct Geo { diff --git a/Telegram/SourceFiles/iv/iv_instance.cpp b/Telegram/SourceFiles/iv/iv_instance.cpp index 4a1accd7e..b597ddf95 100644 --- a/Telegram/SourceFiles/iv/iv_instance.cpp +++ b/Telegram/SourceFiles/iv/iv_instance.cpp @@ -7,13 +7,18 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "iv/iv_instance.h" +#include "apiwrap.h" +#include "core/application.h" #include "core/file_utilities.h" #include "core/shortcuts.h" +#include "data/data_changes.h" +#include "data/data_channel.h" #include "data/data_cloud_file.h" #include "data/data_document.h" #include "data/data_file_origin.h" #include "data/data_photo_media.h" #include "data/data_session.h" +#include "info/profile/info_profile_values.h" #include "iv/iv_controller.h" #include "iv/iv_data.h" #include "main/main_account.h" @@ -26,6 +31,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/boxes/confirm_box.h" #include "webview/webview_data_stream_memory.h" #include "webview/webview_interface.h" +#include "window/window_controller.h" +#include "window/window_session_controller.h" +#include "window/window_session_controller_link_info.h" namespace Iv { namespace { @@ -66,6 +74,7 @@ public: [[nodiscard]] bool activeFor(not_null session) const; [[nodiscard]] bool active() const; + void showJoinedTooltip(); void minimize(); [[nodiscard]] rpl::producer events() const { @@ -123,6 +132,7 @@ private: void streamMap(QString params, Webview::DataRequest request); void sendEmbed(QByteArray hash, Webview::DataRequest request); + void fillChannelJoinedValues(const Prepared &result); void requestDone( Webview::DataRequest request, QByteArray bytes, @@ -136,6 +146,7 @@ private: QString _id; std::unique_ptr _controller; base::flat_map _files; + base::flat_map> _inChannelValues; QString _localBase; base::flat_map _embeds; @@ -162,6 +173,7 @@ Shown::Shown( data->prepare({ .saveToFolder = base }, [=](Prepared result) { crl::on_main(weak, [=, result = std::move(result)]() mutable { _embeds = std::move(result.embeds); + fillChannelJoinedValues(result); if (!base.isEmpty()) { _localBase = base; showLocal(std::move(result)); @@ -172,6 +184,22 @@ Shown::Shown( }); } +void Shown::fillChannelJoinedValues(const Prepared &result) { + for (const auto &id : result.channelIds) { + const auto channelId = ChannelId(id.toLongLong()); + const auto channel = _session->data().channel(channelId); + if (!channel->isLoaded() && !channel->username().isEmpty()) { + channel->session().api().request(MTPcontacts_ResolveUsername( + MTP_string(channel->username()) + )).done([=](const MTPcontacts_ResolvedPeer &result) { + channel->owner().processUsers(result.data().vusers()); + channel->owner().processChats(result.data().vchats()); + }).send(); + } + _inChannelValues[id] = Info::Profile::AmInChannelValue(channel); + } +} + void Shown::showLocal(Prepared result) { showProgress(0); @@ -179,7 +207,7 @@ void Shown::showLocal(Prepared result) { QDir().mkpath(_localBase); _resources = std::move(result.resources); - writeLocal(localRoot(), result.html); + writeLocal(localRoot(), result.content); } void Shown::showProgress(int index) { @@ -392,7 +420,10 @@ void Shown::showWindowed(Prepared result) { }, _controller->lifetime()); const auto domain = &_session->domain(); - _controller->show(domain->local().webviewDataPath(), std::move(result)); + _controller->show( + domain->local().webviewDataPath(), + std::move(result), + base::duplicate(_inChannelValues)); } void Shown::streamPhoto(PhotoId photoId, Webview::DataRequest request) { @@ -651,6 +682,12 @@ bool Shown::active() const { return _controller && _controller->active(); } +void Shown::showJoinedTooltip() { + if (_controller) { + _controller->showJoinedTooltip(); + } +} + void Shown::minimize() { if (_controller) { _controller->minimize(); @@ -670,11 +707,34 @@ void Instance::show( return; } _shown = std::make_unique(show, data, local); + _shownSession = session; _shown->events() | rpl::start_with_next([=](Controller::Event event) { - if (event == Controller::Event::Close) { + using Type = Controller::Event::Type; + switch (event.type) { + case Type::Close: _shown = nullptr; - } else if (event == Controller::Event::Quit) { + break; + case Type::Quit: Shortcuts::Launch(Shortcuts::Command::Quit); + break; + case Type::OpenChannel: + processOpenChannel(event.context); + break; + case Type::JoinChannel: + processJoinChannel(event.context); + break; + } + }, _shown->lifetime()); + + session->changes().peerUpdates( + ::Data::PeerUpdate::Flag::ChannelAmIn + ) | rpl::start_with_next([=](const ::Data::PeerUpdate &update) { + if (const auto channel = update.peer->asChannel()) { + if (channel->amIn()) { + if (_joining.remove(not_null(channel))) { + _shown->showJoinedTooltip(); + } + } } }, _shown->lifetime()); @@ -682,6 +742,16 @@ void Instance::show( _tracking.emplace(session); session->lifetime().add([=] { _tracking.remove(session); + for (auto i = begin(_joining); i != end(_joining);) { + if (&(*i)->session() == session) { + i = _joining.erase(i); + } else { + ++i; + } + } + if (_shownSession == session) { + _shownSession = nullptr; + } if (_shown && _shown->showingFrom(session)) { _shown = nullptr; } @@ -689,6 +759,52 @@ void Instance::show( } } +void Instance::processOpenChannel(const QString &context) { + if (!_shownSession) { + return; + } else if (const auto channelId = ChannelId(context.toLongLong())) { + const auto channel = _shownSession->data().channel(channelId); + if (channel->isLoaded()) { + if (const auto window = Core::App().windowFor(channel)) { + if (const auto controller = window->sessionController()) { + controller->showPeerHistory(channel); + _shown = nullptr; + } + } + } else if (!channel->username().isEmpty()) { + if (const auto window = Core::App().windowFor(channel)) { + if (const auto controller = window->sessionController()) { + controller->showPeerByLink({ + .usernameOrId = channel->username(), + }); + _shown = nullptr; + } + } + } + } +} + +void Instance::processJoinChannel(const QString &context) { + if (!_shownSession) { + return; + } else if (const auto channelId = ChannelId(context.toLongLong())) { + const auto channel = _shownSession->data().channel(channelId); + _joining.emplace(channel); + if (channel->isLoaded()) { + _shownSession->api().joinChannel(channel); + } else if (!channel->username().isEmpty()) { + if (const auto window = Core::App().windowFor(channel)) { + if (const auto controller = window->sessionController()) { + controller->showPeerByLink({ + .usernameOrId = channel->username(), + .joinChannel = true, + }); + } + } + } + } +} + bool Instance::hasActiveWindow(not_null session) const { return _shown && _shown->activeFor(session); } diff --git a/Telegram/SourceFiles/iv/iv_instance.h b/Telegram/SourceFiles/iv/iv_instance.h index 566876303..87c061f21 100644 --- a/Telegram/SourceFiles/iv/iv_instance.h +++ b/Telegram/SourceFiles/iv/iv_instance.h @@ -38,8 +38,13 @@ public: [[nodiscard]] rpl::lifetime &lifetime(); private: + void processOpenChannel(const QString &context); + void processJoinChannel(const QString &context); + std::unique_ptr _shown; + Main::Session *_shownSession = nullptr; base::flat_set> _tracking; + base::flat_set> _joining; rpl::lifetime _lifetime; diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp index a1b8749ef..58bf05d4a 100644 --- a/Telegram/SourceFiles/iv/iv_prepare.cpp +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -47,14 +47,6 @@ private: void process(const MTPPhoto &photo); void process(const MTPDocument &document); - [[nodiscard]] QByteArray prepare(QByteArray body); - - [[nodiscard]] QByteArray html( - const QByteArray &head, - const QByteArray &body); - - [[nodiscard]] QByteArray page(const MTPDpage &data); - template [[nodiscard]] QByteArray list(const MTPVector &data); @@ -143,9 +135,6 @@ private: base::flat_map _photosById; base::flat_map _documentsById; - bool _hasCode = false; - bool _hasEmbeds = false; - }; [[nodiscard]] bool IsVoidElement(const QByteArray &name) { @@ -169,11 +158,11 @@ private: } Parser::Parser(const Source &source, const Options &options) -: _options(options) -, _rtl(source.page.data().is_rtl()) { +: _options(options) { process(source); _result.title = source.title; - _result.html = prepare(page(source.page.data())); + _result.rtl = source.page.data().is_rtl(); + _result.content = list(source.page.data().vblocks()); } Prepared Parser::result() { @@ -260,7 +249,7 @@ QByteArray Parser::block(const MTPDpageBlockPreformatted &data) { if (!language.isEmpty()) { list.push_back({ "data-language", language }); list.push_back({ "class", "lang-" + language }); - _hasCode = true; + _result.hasCode = true; } return tag("pre", list, rich(data.vtext())); } @@ -270,7 +259,7 @@ QByteArray Parser::block(const MTPDpageBlockFooter &data) { } QByteArray Parser::block(const MTPDpageBlockDivider &data) { - return tag("hr", { {"class", "iv-divider" } }); + return tag("hr", { { "class", "iv-divider" } }); } QByteArray Parser::block(const MTPDpageBlockAnchor &data) { @@ -393,7 +382,7 @@ QByteArray Parser::block(const MTPDpageBlockCover &data) { } QByteArray Parser::block(const MTPDpageBlockEmbed &data) { - _hasEmbeds = true; + _result.hasEmbeds = true; auto eclass = data.is_full_width() ? QByteArray() : "nowide"; auto width = QByteArray(); auto height = QByteArray(); @@ -519,6 +508,9 @@ QByteArray Parser::block(const MTPDpageBlockSlideshow &data) { QByteArray Parser::block(const MTPDpageBlockChannel &data) { auto name = QByteArray(); auto username = QByteArray(); + auto id = data.vchannel().match([](const auto &data) { + return QByteArray::number(data.vid().v); + }); data.vchannel().match([&](const MTPDchannel &data) { if (const auto has = data.vusername()) { username = utf(*has); @@ -528,15 +520,23 @@ QByteArray Parser::block(const MTPDpageBlockChannel &data) { name = utf(data.vtitle()); }, [](const auto &) { }); - auto result = tag("h4", name); - if (!username.isEmpty()) { - const auto link = "https://t.me/" + username; - result = tag( - "a", - { { "href", link }, { "target", "_blank" } }, - result); - } - return tag("section", { { "class", "channel" } }, result); + auto result = tag( + "div", + { { "class", "join" }, { "data-context", "join_link" + id } }, + tag("span") + ) + tag("h4", name); + const auto link = username.isEmpty() + ? "javascript:alert('Channel Link');" + : "https://t.me/" + username; + result = tag( + "a", + { { "href", link }, { "data-context", "channel" + id } }, + result); + _result.channelIds.emplace(id); + return tag("section", { + { "class", "channel joined" }, + { "data-context", "channel" + id }, + }, result); } QByteArray Parser::block(const MTPDpageBlockAudio &data) { @@ -972,83 +972,6 @@ QByteArray Parser::resource(QByteArray id) { return toFolder ? id : ('/' + id); } -QByteArray Parser::page(const MTPDpage &data) { - const auto html = list(data.vblocks()); - if (html.isEmpty()) { - return html; - } - auto attributes = Attributes(); - if (_rtl) { - attributes.push_back({ "dir", "rtl" }); - attributes.push_back({ "class", "rtl" }); - } - return tag("article", attributes, html); -} - -QByteArray Parser::prepare(QByteArray body) { - auto head = QByteArray(); - auto js = QByteArray(); - if (body.isEmpty()) { - body = tag( - "section", - { { "class", "message" } }, - tag("aside", "Failed." + tag("cite", "Failed."))); - } - if (_hasCode) { - head += R"( - - -)"_q; - js += "IV.initPreBlocks();"; - } - if (_hasEmbeds) { - js += "IV.initEmbedBlocks();"; - } - body += tag("script", js + "IV.init();"); - return html(head, body); -} - -QByteArray Parser::html(const QByteArray &head, const QByteArray &body) { -#ifdef Q_OS_MAC - const auto classAttribute = ""_q; -#else // Q_OS_MAC - const auto classAttribute = " class=\"custom_scroll\""_q; -#endif // Q_OS_MAC - - return R"( - - - - - - - - )"_q + head + R"( - - - - - -)"_q + body + R"( - - -)"_q; -} - } // namespace Prepared Prepare(const Source &source, const Options &options) { diff --git a/Telegram/SourceFiles/window/window_session_controller.cpp b/Telegram/SourceFiles/window/window_session_controller.cpp index 15ea551e8..031946f0a 100644 --- a/Telegram/SourceFiles/window/window_session_controller.cpp +++ b/Telegram/SourceFiles/window/window_session_controller.cpp @@ -314,6 +314,8 @@ void SessionNavigation::showPeerByLink(const PeerByLinkInfo &info) { peer, [=](bool) { showPeerByLinkResolved(peer, info); }, true); + } else if (info.joinChannel && peer->isChannel()) { + peer->session().api().joinChannel(peer->asChannel()); } else { showPeerByLinkResolved(peer, info); } diff --git a/Telegram/SourceFiles/window/window_session_controller_link_info.h b/Telegram/SourceFiles/window/window_session_controller_link_info.h index 927185e5a..5cf6dce7e 100644 --- a/Telegram/SourceFiles/window/window_session_controller_link_info.h +++ b/Telegram/SourceFiles/window/window_session_controller_link_info.h @@ -38,6 +38,7 @@ struct PeerByLinkInfo { QString startToken; ChatAdminRights startAdminRights; bool startAutoSubmit = false; + bool joinChannel = false; QString botAppName; bool botAppForceConfirmation = false; QString attachBotUsername; From 5c428ca502cb283d7970e1025b523d970fe40154 Mon Sep 17 00:00:00 2001 From: John Preston Date: Tue, 5 Dec 2023 11:54:46 +0400 Subject: [PATCH 019/240] Support anchor jumps. --- Telegram/Resources/iv_html/page.js | 29 ++++++++++++++++------- Telegram/SourceFiles/iv/iv_controller.cpp | 11 +++++++-- Telegram/SourceFiles/iv/iv_controller.h | 1 + Telegram/SourceFiles/iv/iv_data.h | 1 + Telegram/SourceFiles/iv/iv_instance.cpp | 15 ++++++++---- Telegram/SourceFiles/iv/iv_instance.h | 2 +- Telegram/SourceFiles/iv/iv_prepare.cpp | 10 ++++++++ 7 files changed, 53 insertions(+), 16 deletions(-) diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index 3f986998c..c0a9c7896 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -7,7 +7,6 @@ var IV = { frameClickHandler: function(e) { var target = e.target; var context = ''; - console.log('click', target); while (target) { if (target.tagName == 'AUDIO' || target.tagName == 'VIDEO') { return; @@ -25,16 +24,28 @@ var IV = { if (!target || !target.hasAttribute('href')) { return; } - var base_loc = document.createElement('A'); - base_loc.href = window.currentUrl; - if (base_loc.origin != target.origin - || base_loc.pathname != target.pathname - || base_loc.search != target.search) { + var base = document.createElement('A'); + base.href = window.location.href; + if (base.origin != target.origin + || base.pathname != target.pathname + || base.search != target.search) { IV.notify({ event: 'link_click', url: target.href, context: context, }); + } else if (target.hash.length < 2) { + IV.hash = ''; + IV.scrollTo(0); + } else { + const name = target.hash.substr(1); + IV.hash = name; + + const element = document.getElementsByName(name)[0]; + if (element) { + const y = element.getBoundingClientRect().y; + IV.scrollTo(y + document.documentElement.scrollTop); + } } e.preventDefault(); }, @@ -183,6 +194,8 @@ var IV = { } }, init: function () { + IV.hash = window.location.hash.substr(1); + const buttons = document.getElementsByClassName('fixed_button'); for (let i = 0; i < buttons.length; ++i) { const button = buttons[i]; @@ -210,9 +223,9 @@ var IV = { document.body.removeChild(toast); }, 3000); }, - toTop: function () { + scrollTo: function (y) { document.getElementById('bottom_up').classList.add('hidden'); - window.scrollTo({ top: 0, behavior: 'smooth' }); + window.scrollTo({ top: y || 0, behavior: 'smooth' }); } }; diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index 592cd3be9..6b1d6cc0f 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -175,7 +175,7 @@ namespace { - - - "_q + page.content + R"( +
+ "_q + page.content + R"( +
@@ -199,28 +200,29 @@ Controller::Controller() _webview->eval("IV.updateStyles('" + str + "');"); } }) { + createWindow(); } Controller::~Controller() { + _window->hide(); _ready = false; _webview = nullptr; _title = nullptr; _window = nullptr; } +bool Controller::showFast(const QString &url, const QString &hash) { + return false; +} + void Controller::show( const QString &dataPath, Prepared page, base::flat_map> inChannelValues) { - createWindow(); - const auto js = fillInChannelValuesScript(std::move(inChannelValues)); - + page.script = fillInChannelValuesScript(std::move(inChannelValues)); _titleText.setText(st::ivTitle.style, page.title); InvokeQueued(_container, [=, page = std::move(page)]() mutable { - showInWindow(dataPath, std::move(page), js); - if (!_webview) { - return; - } + showInWindow(dataPath, std::move(page)); }); } @@ -228,13 +230,15 @@ QByteArray Controller::fillInChannelValuesScript( base::flat_map> inChannelValues) { auto result = QByteArray(); for (auto &[id, in] : inChannelValues) { - std::move(in) | rpl::start_with_next([=](bool in) { - if (_ready) { - _webview->eval(toggleInChannelScript(id, in)); - } else { - _inChannelChanged[id] = in; - } - }, _lifetime); + if (_inChannelSubscribed.emplace(id).second) { + std::move(in) | rpl::start_with_next([=](bool in) { + if (_ready) { + _webview->eval(toggleInChannelScript(id, in)); + } else { + _inChannelChanged[id] = in; + } + }, _lifetime); + } } for (const auto &[id, in] : base::take(_inChannelChanged)) { result += toggleInChannelScript(id, in); @@ -342,14 +346,10 @@ void Controller::createWindow() { window->show(); } -void Controller::showInWindow( - const QString &dataPath, - Prepared page, - const QByteArray &initScript) { - Expects(_container != nullptr); +void Controller::createWebview(const QString &dataPath) { + Expects(!_webview); const auto window = _window.get(); - _url = page.url; _webview = std::make_unique( _container, Webview::WindowConfig{ @@ -362,10 +362,7 @@ void Controller::showInWindow( _ready = false; _webview = nullptr; }); - if (!raw->widget()) { - _events.fire({ Event::Type::Close }); - return; - } + window->events( ) | rpl::start_with_next([=](not_null e) { if (e->type() == QEvent::Close) { @@ -411,11 +408,18 @@ void Controller::showInWindow( for (const auto &[id, in] : base::take(_inChannelChanged)) { script += toggleInChannelScript(id, in); } + if (_navigateToIndexWhenReady >= 0) { + script += navigateScript( + std::exchange(_navigateToIndexWhenReady, -1), + base::take(_navigateToHashWhenReady)); + } if (!script.isEmpty()) { _webview->eval(script); } } else if (event == u"menu"_q) { - menu(object.value("hash").toString()); + menu( + object.value("index").toInt(), + object.value("hash").toString()); } }); }); @@ -433,7 +437,7 @@ void Controller::showInWindow( return Webview::DataResult::Done; }; const auto id = std::string_view(request.id).substr(3); - if (id == "page.html") { + if (id.starts_with("page") && id.ends_with(".html")) { if (!_subscribedToColors) { _subscribedToColors = true; @@ -444,7 +448,33 @@ void Controller::showInWindow( _updateStyles.call(); }, _webview->lifetime()); } - return finishWith(WrapPage(page, initScript), "text/html"); + auto index = 0; + const auto result = std::from_chars( + id.data() + 4, + id.data() + id.size() - 5, + index); + if (result.ec != std::errc() + || index < 0 + || index >= _pages.size()) { + return Webview::DataResult::Failed; + } + return finishWith(WrapPage(_pages[index]), "text/html"); + } else if (id.starts_with("page") && id.ends_with(".json")) { + auto index = 0; + const auto result = std::from_chars( + id.data() + 4, + id.data() + id.size() - 5, + index); + if (result.ec != std::errc() + || index < 0 + || index >= _pages.size()) { + return Webview::DataResult::Failed; + } + auto &page = _pages[index]; + return finishWith(QJsonDocument(QJsonObject{ + { "html", QJsonValue(QString::fromUtf8(page.content)) }, + { "js", QJsonValue(QString::fromUtf8(page.script)) }, + }).toJson(QJsonDocument::Compact), "application/json"); } const auto css = id.ends_with(".css"); const auto js = !css && id.ends_with(".js"); @@ -464,12 +494,48 @@ void Controller::showInWindow( }); raw->init(R"()"); +} - auto id = u"iv/page.html"_q; - if (!page.hash.isEmpty()) { - id += '#' + page.hash; +void Controller::showInWindow(const QString &dataPath, Prepared page) { + Expects(_container != nullptr); + + const auto url = page.url; + const auto hash = page.hash; + auto i = _indices.find(url); + if (i == end(_indices)) { + _pages.push_back(std::move(page)); + i = _indices.emplace(url, int(_pages.size() - 1)).first; } - raw->navigateToData(id); + const auto index = i->second; + if (!_webview) { + createWebview(dataPath); + if (_webview && _webview->widget()) { + auto id = u"iv/page%1.html"_q.arg(index); + if (!hash.isEmpty()) { + id += '#' + hash; + } + _webview->navigateToData(id); + } else { + _events.fire({ Event::Type::Close }); + } + } else if (_ready) { + _webview->eval(navigateScript(index, hash)); + _window->activateWindow(); + _window->setFocus(); + } else { + _navigateToIndexWhenReady = index; + _navigateToHashWhenReady = hash; + _window->activateWindow(); + _window->setFocus(); + } +} + +QByteArray Controller::navigateScript(int index, const QString &hash) { + return "IV.navigateTo(" + + QByteArray::number(index) + + ", '" + + EscapeForScriptString(hash.toUtf8()) + + "');"; } void Controller::processKey(const QString &key, const QString &modifier) { @@ -537,8 +603,8 @@ void Controller::minimize() { } } -void Controller::menu(const QString &hash) { - if (!_webview || _menu) { +void Controller::menu(int index, const QString &hash) { + if (!_webview || _menu || index < 0 || index > _pages.size()) { return; } _menu = base::make_unique_q( @@ -552,7 +618,8 @@ void Controller::menu(const QString &hash) { } })); - const auto url = _url + (hash.isEmpty() ? u""_q : ('#' + hash)); + const auto url = _pages[index].url + + (hash.isEmpty() ? u""_q : ('#' + hash)); const auto openInBrowser = crl::guard(_window.get(), [=] { _events.fire({ .type = Event::Type::OpenLinkExternal, .url = url }); }); diff --git a/Telegram/SourceFiles/iv/iv_controller.h b/Telegram/SourceFiles/iv/iv_controller.h index f0b77276e..36b2f14c4 100644 --- a/Telegram/SourceFiles/iv/iv_controller.h +++ b/Telegram/SourceFiles/iv/iv_controller.h @@ -50,6 +50,7 @@ public: QString context; }; + [[nodiscard]] bool showFast(const QString &url, const QString &hash); void show( const QString &dataPath, Prepared page, @@ -70,12 +71,12 @@ public: private: void createWindow(); + void createWebview(const QString &dataPath); + [[nodiscard]] QByteArray navigateScript(int index, const QString &hash); + void updateTitleGeometry(); void paintTitle(Painter &p, QRect clip); - void showInWindow( - const QString &dataPath, - Prepared page, - const QByteArray &initScript); + void showInWindow(const QString &dataPath, Prepared page); [[nodiscard]] QByteArray fillInChannelValuesScript( base::flat_map> inChannelValues); [[nodiscard]] QByteArray toggleInChannelScript( @@ -85,7 +86,7 @@ private: void processKey(const QString &key, const QString &modifier); void processLink(const QString &url, const QString &context); - void menu(const QString &hash); + void menu(int index, const QString &hash); void escape(); void close(); void quit(); @@ -101,11 +102,16 @@ private: rpl::event_stream _dataRequests; rpl::event_stream _events; base::flat_map _inChannelChanged; + base::flat_set _inChannelSubscribed; SingleQueuedInvokation _updateStyles; - QString _url; bool _subscribedToColors = false; bool _ready = false; + std::vector _pages; + base::flat_map _indices; + QString _navigateToHashWhenReady; + int _navigateToIndexWhenReady = -1; + rpl::lifetime _lifetime; }; diff --git a/Telegram/SourceFiles/iv/iv_data.h b/Telegram/SourceFiles/iv/iv_data.h index 9340c511f..f995c2c3f 100644 --- a/Telegram/SourceFiles/iv/iv_data.h +++ b/Telegram/SourceFiles/iv/iv_data.h @@ -18,6 +18,7 @@ struct Options { struct Prepared { QString title; QByteArray content; + QByteArray script; QString url; QString hash; std::vector resources; diff --git a/Telegram/SourceFiles/iv/iv_instance.cpp b/Telegram/SourceFiles/iv/iv_instance.cpp index b4539da6e..b62e0d5b3 100644 --- a/Telegram/SourceFiles/iv/iv_instance.cpp +++ b/Telegram/SourceFiles/iv/iv_instance.cpp @@ -81,6 +81,8 @@ public: [[nodiscard]] bool activeFor(not_null session) const; [[nodiscard]] bool active() const; + void moveTo(not_null data, QString hash); + void showJoinedTooltip(); void minimize(); @@ -115,6 +117,9 @@ private: std::vector requests; }; + void prepare(not_null data, const QString &hash); + void createController(); + void showLocal(Prepared result); void showWindowed(Prepared result); @@ -163,6 +168,8 @@ private: base::flat_map _files; base::flat_map> _inChannelValues; + bool _preparing = false; + QString _localBase; base::flat_map _embeds; base::flat_map _maps; @@ -181,15 +188,24 @@ Shown::Shown( not_null data, QString hash) : _session(&show->session()) -, _show(show) -, _id(data->id()) { +, _show(show) { + prepare(data, hash); +} + +void Shown::prepare(not_null data, const QString &hash) { const auto weak = base::make_weak(this); + _preparing = true; + const auto id = _id = data->id(); const auto base = /*local ? LookupLocalPath(show) : */QString(); data->prepare({ .saveToFolder = base }, [=](Prepared result) { result.hash = hash; crl::on_main(weak, [=, result = std::move(result)]() mutable { - result.url = _id; + result.url = id; + if (_id != id || !_preparing) { + return; + } + _preparing = false; _embeds = std::move(result.embeds); fillChannelJoinedValues(result); if (!base.isEmpty()) { @@ -416,7 +432,9 @@ void Shown::writeEmbed(QString id, QString hash) { } } -void Shown::showWindowed(Prepared result) { +void Shown::createController() { + Expects(!_controller); + _controller = std::make_unique(); _controller->events( @@ -436,6 +454,12 @@ void Shown::showWindowed(Prepared result) { sendEmbed(id.mid(5).toUtf8(), std::move(request)); } }, _controller->lifetime()); +} + +void Shown::showWindowed(Prepared result) { + if (!_controller) { + createController(); + } const auto domain = &_session->domain(); _controller->show( @@ -753,6 +777,12 @@ bool Shown::active() const { return _controller && _controller->active(); } +void Shown::moveTo(not_null data, QString hash) { + if (!_controller || !_controller->showFast(data->id(), hash)) { + prepare(data, hash); + } +} + void Shown::showJoinedTooltip() { if (_controller) { _controller->showJoinedTooltip(); @@ -774,7 +804,8 @@ void Instance::show( not_null data, QString hash) { const auto session = &show->session(); - if (_shown && _shown->showing(session, data)) { + if (_shown && _shownSession == session) { + _shown->moveTo(data, hash); return; } _shown = std::make_unique(show, data, hash); diff --git a/Telegram/SourceFiles/iv/iv_prepare.cpp b/Telegram/SourceFiles/iv/iv_prepare.cpp index a9186997f..3f1e63fff 100644 --- a/Telegram/SourceFiles/iv/iv_prepare.cpp +++ b/Telegram/SourceFiles/iv/iv_prepare.cpp @@ -744,7 +744,7 @@ QByteArray Parser::block(const MTPDpageBlockAudio &data) { } QByteArray Parser::block(const MTPDpageBlockKicker &data) { - return tag("h6", { { "class", "kicker" } }, rich(data.vtext())); + return tag("h5", { { "class", "kicker" } }, rich(data.vtext())); } QByteArray Parser::block(const MTPDpageBlockTable &data) { From 5f3c380d564803c335db1f593a9af29ff13da903 Mon Sep 17 00:00:00 2001 From: John Preston Date: Thu, 15 Feb 2024 13:48:49 +0400 Subject: [PATCH 025/240] Fix navigation on macOS. --- Telegram/Resources/iv_html/page.js | 34 +++++++++++++++++------ Telegram/SourceFiles/iv/iv_controller.cpp | 10 ++++++- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index 1e15dd90d..862859203 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -93,13 +93,16 @@ var IV = { }, lastScrollTop: 0, frameScrolled: function (e) { - const now = document.documentElement.scrollTop; - if (now < 100) { + const was = IV.lastScrollTop; + IV.lastScrollTop = IV.findPageScroll().scrollTop; + IV.updateJumpToTop(was < IV.lastScrollTop); + }, + updateJumpToTop: function (scrolledDown) { + if (IV.lastScrollTop < 100) { document.getElementById('bottom_up').classList.add('hidden'); - } else if (now > IV.lastScrollTop && now > 200) { + } else if (scrolledDown && IV.lastScrollTop > 200) { document.getElementById('bottom_up').classList.remove('hidden'); } - IV.lastScrollTop = now; }, updateStyles: function (styles) { if (IV.styles !== styles) { @@ -221,7 +224,13 @@ var IV = { } }, init: function () { + IV.platform = window.navigator.platform.toLowerCase(); + IV.mac = IV.platform.startsWith('mac'); + IV.win = IV.platform.startsWith('win'); + window.history.replaceState(IV.computeCurrentState(), ''); + IV.lastScrollTop = window.history.state.scroll; + IV.findPageScroll().onscroll = IV.frameScrolled; const buttons = document.getElementsByClassName('fixed_button'); for (let i = 0; i < buttons.length; ++i) { @@ -287,7 +296,9 @@ var IV = { }, 3000); }, scrollTo: function (y, instant) { - document.getElementById('bottom_up').classList.add('hidden'); + if (y < 200) { + document.getElementById('bottom_up').classList.add('hidden'); + } IV.findPageScroll().scrollTo({ top: y || 0, behavior: instant ? 'instant' : 'smooth' @@ -348,6 +359,7 @@ var IV = { el.innerHTML = '
' + data.html + '
'; + el.onscroll = IV.frameScrolled; IV.cache[index].dom = el; IV.navigateToDOM(index, hash); @@ -357,7 +369,7 @@ var IV = { navigateToDOM: function (index, hash) { IV.pending = null; if (IV.index == index) { - IV.jumpToHash(hash); + IV.jumpToHash(hash, IV.mac); return; } window.history.replaceState(IV.computeCurrentState(), ''); @@ -429,11 +441,16 @@ var IV = { IV.initMedia(); if (scroll === undefined) { IV.jumpToHash(hash, true); + } else { + IV.lastScrollTop = scroll; + IV.updateJumpToTop(true); } } else if (scroll !== undefined) { - IV.scrollTo(scroll); + IV.scrollTo(scroll, IV.mac); + IV.lastScrollTop = scroll; + IV.updateJumpToTop(true); } else { - IV.jumpToHash(hash); + IV.jumpToHash(hash, IV.mac); } }, back: function () { @@ -449,7 +466,6 @@ document.onclick = IV.frameClickHandler; document.onkeydown = IV.frameKeyDown; document.onmouseenter = IV.frameMouseEnter; document.onmouseup = IV.frameMouseUp; -document.onscroll = IV.frameScrolled; window.onmessage = IV.postMessageHandler; window.addEventListener('popstate', function (e) { diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index d2f299121..98de7e49d 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -204,7 +204,9 @@ Controller::Controller() } Controller::~Controller() { - _window->hide(); + if (_window) { + _window->hide(); + } _ready = false; _webview = nullptr; _title = nullptr; @@ -424,6 +426,10 @@ void Controller::createWebview(const QString &dataPath) { }); }); raw->setDataRequestHandler([=](Webview::DataRequest request) { + const auto pos = request.id.find('#'); + if (pos != request.id.npos) { + request.id = request.id.substr(0, pos); + } if (!request.id.starts_with("iv/")) { _dataRequests.fire(std::move(request)); return Webview::DataResult::Pending; @@ -520,11 +526,13 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { } } else if (_ready) { _webview->eval(navigateScript(index, hash)); + _window->raise(); _window->activateWindow(); _window->setFocus(); } else { _navigateToIndexWhenReady = index; _navigateToHashWhenReady = hash; + _window->raise(); _window->activateWindow(); _window->setFocus(); } From 0a87dbea6829f36927e9930fd101a3aa3e758714 Mon Sep 17 00:00:00 2001 From: John Preston Date: Fri, 16 Feb 2024 11:25:15 +0400 Subject: [PATCH 026/240] Fix focusing IV content. --- Telegram/Resources/iv_html/page.css | 3 +++ Telegram/Resources/iv_html/page.js | 27 ++++++++++++++++++----- Telegram/SourceFiles/iv/iv_controller.cpp | 16 +++++++++++++- 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/Telegram/Resources/iv_html/page.css b/Telegram/Resources/iv_html/page.css index 1da34f68a..e6bd5af80 100644 --- a/Telegram/Resources/iv_html/page.css +++ b/Telegram/Resources/iv_html/page.css @@ -135,6 +135,9 @@ html.custom_scroll ::-webkit-scrollbar-thumb:hover { overflow-x: hidden; overflow-y: auto; } +.page-scroll:focus { + outline: none; +} .page-slide { position: relative; width: 100%; diff --git a/Telegram/Resources/iv_html/page.js b/Telegram/Resources/iv_html/page.js index 862859203..333c127f1 100644 --- a/Telegram/Resources/iv_html/page.js +++ b/Telegram/Resources/iv_html/page.js @@ -79,10 +79,14 @@ var IV = { }); } else if (e.key === 'Escape' || e.keyCode === 27) { e.preventDefault(); - IV.notify({ - event: 'keydown', - key: 'escape', - }); + if (IV.position) { + window.history.back(); + } else { + IV.notify({ + event: 'keydown', + key: 'escape', + }); + } } }, frameMouseEnter: function (e) { @@ -250,6 +254,8 @@ var IV = { } IV.initMedia(); IV.notify({ event: 'ready' }); + + IV.forceScrollFocus(); }, initMedia: function () { const photos = document.getElementsByClassName('photo'); @@ -356,6 +362,7 @@ var IV = { var data = JSON.parse(IV.cache[index].content); var el = document.createElement('div'); el.className = 'page-scroll'; + el.tabIndex = '-1'; el.innerHTML = '
' + data.html + '
'; @@ -370,6 +377,7 @@ var IV = { IV.pending = null; if (IV.index == index) { IV.jumpToHash(hash, IV.mac); + IV.forceScrollFocus(); return; } window.history.replaceState(IV.computeCurrentState(), ''); @@ -452,6 +460,15 @@ var IV = { } else { IV.jumpToHash(hash, IV.mac); } + + IV.forceScrollFocus(); + }, + forceScrollFocus: function () { + IV.findPageScroll().focus(); + setTimeout(function () { + // Doesn't work on #hash-ed pages in Windows WebView2 otherwise. + IV.findPageScroll().focus(); + }, 100); }, back: function () { window.history.back(); @@ -467,9 +484,9 @@ document.onkeydown = IV.frameKeyDown; document.onmouseenter = IV.frameMouseEnter; document.onmouseup = IV.frameMouseUp; window.onmessage = IV.postMessageHandler; - window.addEventListener('popstate', function (e) { if (e.state) { IV.showDOM(e.state.index, e.state.hash, e.state.scroll); } }); +document.addEventListener("DOMContentLoaded", IV.forceScrollFocus); diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index 98de7e49d..b26ca8237 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -9,6 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/platform/base_platform_info.h" #include "base/invoke_queued.h" +#include "base/qt_signal_producer.h" #include "iv/iv_data.h" #include "lang/lang_keys.h" #include "ui/platform/ui_platform_window_title.h" @@ -31,6 +32,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include #include #include +#include #include namespace Iv { @@ -182,7 +184,7 @@ namespace { -
+
"_q + page.content + R"(
@@ -286,6 +288,15 @@ void Controller::createWindow() { _window->setTitleStyle(st::ivTitle); const auto window = _window.get(); + base::qt_signal_producer( + window->window()->windowHandle(), + &QWindow::activeChanged + ) | rpl::filter([=] { + return _webview && window->window()->windowHandle()->isActive(); + }) | rpl::start_with_next([=] { + _webview->focus(); + }, window->lifetime()); + _title = std::make_unique(window); _title->setAttribute(Qt::WA_TransparentForMouseEvents); _title->paintRequest() | rpl::start_with_next([=](QRect clip) { @@ -521,6 +532,7 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { id += '#' + hash; } _webview->navigateToData(id); + _webview->focus(); } else { _events.fire({ Event::Type::Close }); } @@ -529,12 +541,14 @@ void Controller::showInWindow(const QString &dataPath, Prepared page) { _window->raise(); _window->activateWindow(); _window->setFocus(); + _webview->focus(); } else { _navigateToIndexWhenReady = index; _navigateToHashWhenReady = hash; _window->raise(); _window->activateWindow(); _window->setFocus(); + _webview->focus(); } } From 315859bf7ba0b05ba91fcc00993a2c61620e394c Mon Sep 17 00:00:00 2001 From: John Preston Date: Mon, 11 Mar 2024 16:59:11 +0400 Subject: [PATCH 027/240] Load full webpage and update in IV. --- .../iv_html/morphdom-umd.min.2.7.2.js | 1 + Telegram/Resources/iv_html/page.js | 100 ++++++++++++++---- Telegram/Resources/qrc/telegram/iv.qrc | 1 + Telegram/SourceFiles/data/data_web_page.cpp | 1 + Telegram/SourceFiles/iv/iv_controller.cpp | 42 +++++++- Telegram/SourceFiles/iv/iv_controller.h | 4 + Telegram/SourceFiles/iv/iv_data.cpp | 4 + Telegram/SourceFiles/iv/iv_data.h | 1 + Telegram/SourceFiles/iv/iv_instance.cpp | 75 +++++++++++-- Telegram/SourceFiles/iv/iv_instance.h | 8 +- 10 files changed, 199 insertions(+), 38 deletions(-) create mode 100644 Telegram/Resources/iv_html/morphdom-umd.min.2.7.2.js diff --git a/Telegram/Resources/iv_html/morphdom-umd.min.2.7.2.js b/Telegram/Resources/iv_html/morphdom-umd.min.2.7.2.js new file mode 100644 index 000000000..1e40c7eae --- /dev/null +++ b/Telegram/Resources/iv_html/morphdom-umd.min.2.7.2.js @@ -0,0 +1 @@ +(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):(global=global||self,global.morphdom=factory())})(this,function(){"use strict";var DOCUMENT_FRAGMENT_NODE=11;function morphAttrs(fromNode,toNode){var toNodeAttrs=toNode.attributes;var attr;var attrName;var attrNamespaceURI;var attrValue;var fromValue;if(toNode.nodeType===DOCUMENT_FRAGMENT_NODE||fromNode.nodeType===DOCUMENT_FRAGMENT_NODE){return}for(var i=toNodeAttrs.length-1;i>=0;i--){attr=toNodeAttrs[i];attrName=attr.name;attrNamespaceURI=attr.namespaceURI;attrValue=attr.value;if(attrNamespaceURI){attrName=attr.localName||attrName;fromValue=fromNode.getAttributeNS(attrNamespaceURI,attrName);if(fromValue!==attrValue){if(attr.prefix==="xmlns"){attrName=attr.name}fromNode.setAttributeNS(attrNamespaceURI,attrName,attrValue)}}else{fromValue=fromNode.getAttribute(attrName);if(fromValue!==attrValue){fromNode.setAttribute(attrName,attrValue)}}}var fromNodeAttrs=fromNode.attributes;for(var d=fromNodeAttrs.length-1;d>=0;d--){attr=fromNodeAttrs[d];attrName=attr.name;attrNamespaceURI=attr.namespaceURI;if(attrNamespaceURI){attrName=attr.localName||attrName;if(!toNode.hasAttributeNS(attrNamespaceURI,attrName)){fromNode.removeAttributeNS(attrNamespaceURI,attrName)}}else{if(!toNode.hasAttribute(attrName)){fromNode.removeAttribute(attrName)}}}}var range;var NS_XHTML="http://www.w3.org/1999/xhtml";var doc=typeof document==="undefined"?undefined:document;var HAS_TEMPLATE_SUPPORT=!!doc&&"content"in doc.createElement("template");var HAS_RANGE_SUPPORT=!!doc&&doc.createRange&&"createContextualFragment"in doc.createRange();function createFragmentFromTemplate(str){var template=doc.createElement("template");template.innerHTML=str;return template.content.childNodes[0]}function createFragmentFromRange(str){if(!range){range=doc.createRange();range.selectNode(doc.body)}var fragment=range.createContextualFragment(str);return fragment.childNodes[0]}function createFragmentFromWrap(str){var fragment=doc.createElement("body");fragment.innerHTML=str;return fragment.childNodes[0]}function toElement(str){str=str.trim();if(HAS_TEMPLATE_SUPPORT){return createFragmentFromTemplate(str)}else if(HAS_RANGE_SUPPORT){return createFragmentFromRange(str)}return createFragmentFromWrap(str)}function compareNodeNames(fromEl,toEl){var fromNodeName=fromEl.nodeName;var toNodeName=toEl.nodeName;var fromCodeStart,toCodeStart;if(fromNodeName===toNodeName){return true}fromCodeStart=fromNodeName.charCodeAt(0);toCodeStart=toNodeName.charCodeAt(0);if(fromCodeStart<=90&&toCodeStart>=97){return fromNodeName===toNodeName.toUpperCase()}else if(toCodeStart<=90&&fromCodeStart>=97){return toNodeName===fromNodeName.toUpperCase()}else{return false}}function createElementNS(name,namespaceURI){return!namespaceURI||namespaceURI===NS_XHTML?doc.createElement(name):doc.createElementNS(namespaceURI,name)}function moveChildren(fromEl,toEl){var curChild=fromEl.firstChild;while(curChild){var nextChild=curChild.nextSibling;toEl.appendChild(curChild);curChild=nextChild}return toEl}function syncBooleanAttrProp(fromEl,toEl,name){if(fromEl[name]!==toEl[name]){fromEl[name]=toEl[name];if(fromEl[name]){fromEl.setAttribute(name,"")}else{fromEl.removeAttribute(name)}}}var specialElHandlers={OPTION:function(fromEl,toEl){var parentNode=fromEl.parentNode;if(parentNode){var parentName=parentNode.nodeName.toUpperCase();if(parentName==="OPTGROUP"){parentNode=parentNode.parentNode;parentName=parentNode&&parentNode.nodeName.toUpperCase()}if(parentName==="SELECT"&&!parentNode.hasAttribute("multiple")){if(fromEl.hasAttribute("selected")&&!toEl.selected){fromEl.setAttribute("selected","selected");fromEl.removeAttribute("selected")}parentNode.selectedIndex=-1}}syncBooleanAttrProp(fromEl,toEl,"selected")},INPUT:function(fromEl,toEl){syncBooleanAttrProp(fromEl,toEl,"checked");syncBooleanAttrProp(fromEl,toEl,"disabled");if(fromEl.value!==toEl.value){fromEl.value=toEl.value}if(!toEl.hasAttribute("value")){fromEl.removeAttribute("value")}},TEXTAREA:function(fromEl,toEl){var newValue=toEl.value;if(fromEl.value!==newValue){fromEl.value=newValue}var firstChild=fromEl.firstChild;if(firstChild){var oldValue=firstChild.nodeValue;if(oldValue==newValue||!newValue&&oldValue==fromEl.placeholder){return}firstChild.nodeValue=newValue}},SELECT:function(fromEl,toEl){if(!toEl.hasAttribute("multiple")){var selectedIndex=-1;var i=0;var curChild=fromEl.firstChild;var optgroup;var nodeName;while(curChild){nodeName=curChild.nodeName&&curChild.nodeName.toUpperCase();if(nodeName==="OPTGROUP"){optgroup=curChild;curChild=optgroup.firstChild}else{if(nodeName==="OPTION"){if(curChild.hasAttribute("selected")){selectedIndex=i;break}i++}curChild=curChild.nextSibling;if(!curChild&&optgroup){curChild=optgroup.nextSibling;optgroup=null}}}fromEl.selectedIndex=selectedIndex}}};var ELEMENT_NODE=1;var DOCUMENT_FRAGMENT_NODE$1=11;var TEXT_NODE=3;var COMMENT_NODE=8;function noop(){}function defaultGetNodeKey(node){if(node){return node.getAttribute&&node.getAttribute("id")||node.id}}function morphdomFactory(morphAttrs){return function morphdom(fromNode,toNode,options){if(!options){options={}}if(typeof toNode==="string"){if(fromNode.nodeName==="#document"||fromNode.nodeName==="HTML"||fromNode.nodeName==="BODY"){var toNodeHtml=toNode;toNode=doc.createElement("html");toNode.innerHTML=toNodeHtml}else{toNode=toElement(toNode)}}else if(toNode.nodeType===DOCUMENT_FRAGMENT_NODE$1){toNode=toNode.firstElementChild}var getNodeKey=options.getNodeKey||defaultGetNodeKey;var onBeforeNodeAdded=options.onBeforeNodeAdded||noop;var onNodeAdded=options.onNodeAdded||noop;var onBeforeElUpdated=options.onBeforeElUpdated||noop;var onElUpdated=options.onElUpdated||noop;var onBeforeNodeDiscarded=options.onBeforeNodeDiscarded||noop;var onNodeDiscarded=options.onNodeDiscarded||noop;var onBeforeElChildrenUpdated=options.onBeforeElChildrenUpdated||noop;var skipFromChildren=options.skipFromChildren||noop;var addChild=options.addChild||function(parent,child){return parent.appendChild(child)};var childrenOnly=options.childrenOnly===true;var fromNodesLookup=Object.create(null);var keyedRemovalList=[];function addKeyedRemoval(key){keyedRemovalList.push(key)}function walkDiscardedChildNodes(node,skipKeyedNodes){if(node.nodeType===ELEMENT_NODE){var curChild=node.firstChild;while(curChild){var key=undefined;if(skipKeyedNodes&&(key=getNodeKey(curChild))){addKeyedRemoval(key)}else{onNodeDiscarded(curChild);if(curChild.firstChild){walkDiscardedChildNodes(curChild,skipKeyedNodes)}}curChild=curChild.nextSibling}}}function removeNode(node,parentNode,skipKeyedNodes){if(onBeforeNodeDiscarded(node)===false){return}if(parentNode){parentNode.removeChild(node)}onNodeDiscarded(node);walkDiscardedChildNodes(node,skipKeyedNodes)}function indexTree(node){if(node.nodeType===ELEMENT_NODE||node.nodeType===DOCUMENT_FRAGMENT_NODE$1){var curChild=node.firstChild;while(curChild){var key=getNodeKey(curChild);if(key){fromNodesLookup[key]=curChild}indexTree(curChild);curChild=curChild.nextSibling}}}indexTree(fromNode);function handleNodeAdded(el){onNodeAdded(el);var curChild=el.firstChild;while(curChild){var nextSibling=curChild.nextSibling;var key=getNodeKey(curChild);if(key){var unmatchedFromEl=fromNodesLookup[key];if(unmatchedFromEl&&compareNodeNames(curChild,unmatchedFromEl)){curChild.parentNode.replaceChild(unmatchedFromEl,curChild);morphEl(unmatchedFromEl,curChild)}else{handleNodeAdded(curChild)}}else{handleNodeAdded(curChild)}curChild=nextSibling}}function cleanupFromEl(fromEl,curFromNodeChild,curFromNodeKey){while(curFromNodeChild){var fromNextSibling=curFromNodeChild.nextSibling;if(curFromNodeKey=getNodeKey(curFromNodeChild)){addKeyedRemoval(curFromNodeKey)}else{removeNode(curFromNodeChild,fromEl,true)}curFromNodeChild=fromNextSibling}}function morphEl(fromEl,toEl,childrenOnly){var toElKey=getNodeKey(toEl);if(toElKey){delete fromNodesLookup[toElKey]}if(!childrenOnly){if(onBeforeElUpdated(fromEl,toEl)===false){return}morphAttrs(fromEl,toEl);onElUpdated(fromEl);if(onBeforeElChildrenUpdated(fromEl,toEl)===false){return}}if(fromEl.nodeName!=="TEXTAREA"){morphChildren(fromEl,toEl)}else{specialElHandlers.TEXTAREA(fromEl,toEl)}}function morphChildren(fromEl,toEl){var skipFrom=skipFromChildren(fromEl,toEl);var curToNodeChild=toEl.firstChild;var curFromNodeChild=fromEl.firstChild;var curToNodeKey;var curFromNodeKey;var fromNextSibling;var toNextSibling;var matchingFromEl;outer:while(curToNodeChild){toNextSibling=curToNodeChild.nextSibling;curToNodeKey=getNodeKey(curToNodeChild);while(!skipFrom&&curFromNodeChild){fromNextSibling=curFromNodeChild.nextSibling;if(curToNodeChild.isSameNode&&curToNodeChild.isSameNode(curFromNodeChild)){curToNodeChild=toNextSibling;curFromNodeChild=fromNextSibling;continue outer}curFromNodeKey=getNodeKey(curFromNodeChild);var curFromNodeType=curFromNodeChild.nodeType;var isCompatible=undefined;if(curFromNodeType===curToNodeChild.nodeType){if(curFromNodeType===ELEMENT_NODE){if(curToNodeKey){if(curToNodeKey!==curFromNodeKey){if(matchingFromEl=fromNodesLookup[curToNodeKey]){if(fromNextSibling===matchingFromEl){isCompatible=false}else{fromEl.insertBefore(matchingFromEl,curFromNodeChild);if(curFromNodeKey){addKeyedRemoval(curFromNodeKey)}else{removeNode(curFromNodeChild,fromEl,true)}curFromNodeChild=matchingFromEl;curFromNodeKey=getNodeKey(curFromNodeChild)}}else{isCompatible=false}}}else if(curFromNodeKey){isCompatible=false}isCompatible=isCompatible!==false&&compareNodeNames(curFromNodeChild,curToNodeChild);if(isCompatible){morphEl(curFromNodeChild,curToNodeChild)}}else if(curFromNodeType===TEXT_NODE||curFromNodeType==COMMENT_NODE){isCompatible=true;if(curFromNodeChild.nodeValue!==curToNodeChild.nodeValue){curFromNodeChild.nodeValue=curToNodeChild.nodeValue}}}if(isCompatible){curToNodeChild=toNextSibling;curFromNodeChild=fromNextSibling;continue outer}if(curFromNodeKey){addKeyedRemoval(curFromNodeKey)}else{removeNode(curFromNodeChild,fromEl,true)}curFromNodeChild=fromNextSibling}if(curToNodeKey&&(matchingFromEl=fromNodesLookup[curToNodeKey])&&compareNodeNames(matchingFromEl,curToNodeChild)){if(!skipFrom){addChild(fromEl,matchingFromEl)}morphEl(matchingFromEl,curToNodeChild)}else{var onBeforeNodeAddedResult=onBeforeNodeAdded(curToNodeChild);if(onBeforeNodeAddedResult!==false){if(onBeforeNodeAddedResult){curToNodeChild=onBeforeNodeAddedResult}if(curToNodeChild.actualize){curToNodeChild=curToNodeChild.actualize(fromEl.ownerDocument||doc)}addChild(fromEl,curToNodeChild);handleNodeAdded(curToNodeChild)}}curToNodeChild=toNextSibling;curFromNodeChild=fromNextSibling}cleanupFromEl(fromEl,curFromNodeChild,curFromNodeKey);var specialElHandler=specialElHandlers[fromEl.nodeName];if(specialElHandler){specialElHandler(fromEl,toEl)}}var morphedNode=fromNode;var morphedNodeType=morphedNode.nodeType;var toNodeType=toNode.nodeType;if(!childrenOnly){if(morphedNodeType===ELEMENT_NODE){if(toNodeType===ELEMENT_NODE){if(!compareNodeNames(fromNode,toNode)){onNodeDiscarded(fromNode);morphedNode=moveChildren(fromNode,createElementNS(toNode.nodeName,toNode.namespaceURI))}}else{morphedNode=toNode}}else if(morphedNodeType===TEXT_NODE||morphedNodeType===COMMENT_NODE){if(toNodeType===morphedNodeType){if(morphedNode.nodeValue!==toNode.nodeValue){morphedNode.nodeValue=toNode.nodeValue}return morphedNode}else{morphedNode=toNode}}}if(morphedNode===toNode){onNodeDiscarded(fromNode)}else{if(toNode.isSameNode&&toNode.isSameNode(morphedNode)){return}morphEl(morphedNode,toNode,childrenOnly);if(keyedRemovalList){for(var i=0,len=keyedRemovalList.length;i
'; + result.onscroll = IV.frameScrolled; + return result; + }, navigateToLoaded: function (index, hash) { if (IV.cache[index].dom) { IV.navigateToDOM(index, hash); } else { var data = JSON.parse(IV.cache[index].content); - var el = document.createElement('div'); - el.className = 'page-scroll'; - el.tabIndex = '-1'; - el.innerHTML = '
' - + data.html - + '
'; - el.onscroll = IV.frameScrolled; - IV.cache[index].dom = el; + IV.cache[index].dom = IV.makeScrolledContent(data.html); IV.navigateToDOM(index, hash); eval(data.js); @@ -417,6 +460,14 @@ var IV = { was.parentNode.appendChild(now); if (scroll !== undefined) { now.scrollTop = scroll; + setTimeout(function () { + // When returning by history.back to an URL with a hash + // for the first time browser forces the scroll to the + // hash instead of the saved scroll position. + // + // This workaround prevents incorrect scroll position. + now.scrollTop = scroll; + }, 0); } now.classList.add(back ? 'hidden-left' : 'hidden-right'); @@ -446,7 +497,12 @@ var IV = { topBack.classList.remove('hidden'); } IV.index = index; - IV.initMedia(); + if (IV.cache[index].contentUpdated) { + IV.cache[index].contentUpdated = false; + IV.applyUpdatedContent(index); + } else { + IV.initMedia(); + } if (scroll === undefined) { IV.jumpToHash(hash, true); } else { diff --git a/Telegram/Resources/qrc/telegram/iv.qrc b/Telegram/Resources/qrc/telegram/iv.qrc index 4d67c89c7..1c9e9eb6a 100644 --- a/Telegram/Resources/qrc/telegram/iv.qrc +++ b/Telegram/Resources/qrc/telegram/iv.qrc @@ -4,5 +4,6 @@ ../../iv_html/page.js ../../iv_html/highlight.9.12.0.css ../../iv_html/highlight.9.12.0.js + ../../iv_html/morphdom-umd.min.2.7.2.js diff --git a/Telegram/SourceFiles/data/data_web_page.cpp b/Telegram/SourceFiles/data/data_web_page.cpp index 9b3f7fd66..bac9f6386 100644 --- a/Telegram/SourceFiles/data/data_web_page.cpp +++ b/Telegram/SourceFiles/data/data_web_page.cpp @@ -281,6 +281,7 @@ bool WebPageData::applyChanges( && document == newDocument && collage.items == newCollage.items && (!iv == !newIv) + && (!iv || iv->partial() == newIv->partial()) && duration == newDuration && author == resultAuthor && hasLargeMedia == (newHasLargeMedia ? 1 : 0) diff --git a/Telegram/SourceFiles/iv/iv_controller.cpp b/Telegram/SourceFiles/iv/iv_controller.cpp index b26ca8237..c4e391254 100644 --- a/Telegram/SourceFiles/iv/iv_controller.cpp +++ b/Telegram/SourceFiles/iv/iv_controller.cpp @@ -161,9 +161,7 @@ namespace { - - - +